Modern Apps git

← Modern-Apps.git

ml: upload only the weights window a plan reads

Commit
ea0ec7a9866012b3e849c47e965cf8941706f148
Author
vayun-mathur <[email protected]>
When
2026-10-25 22:14 UTC (1 month ago)
Parents
f8b3982

Diff

library/ml/src/main/rust/src/nets/mod_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part1.rs b/library/ml/src/main/rust/src/nets/mod_part1.rsindex 35f46c2cfb..cfb760bb0d 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -14,6 +14,12 @@ pub struct Push {     /// Element offset of the first input in the activation arena.     pub in0: u32,     /// Element offset of the second input, for the binary ops.+    ///+    /// [`Kind::Conv`] reuses this as the tiled-path selector: 1 routes to the+    /// register-blocked spatial implementation in `shaders/conv_tiled.glsl`, 0 to+    /// the one-invocation-per-element one. The binary ops are the only other+    /// readers and no convolution is one, so the two uses cannot meet. Set by+    /// [`Builder::spatial_tiling`]; zero everywhere that never opts in.     pub in1: u32,     /// Element offset of the output in the arena.     pub out: u32,@@ -325,15 +331,18 @@ impl Kind {             | Kind::Quantize             | Kind::Argmax             | Kind::GatedActivate => {}+            // A scalar (`mul_scalar`) or a low/high pair (`clamp`) at `act_weight`.+            Kind::MulScalar | Kind::Clamp => {+                reads.push(WeightRead { at: elems(push.act_weight), field: "act_weight" });+            }             Kind::Activate-            | Kind::MulScalar-            | Kind::Clamp             | Kind::AttnApply             | Kind::AttnApplyCached             | Kind::AttnApplyBanded             | Kind::Rotary => {}         }-        if !reads.is_empty() && push.act == Act::PRelu(0).code() {+        let applies_act = !reads.is_empty() || matches!(self, Kind::Activate | Kind::GatedActivate);+        if applies_act && push.act == Act::PRelu(0).code() {             let slope = WeightRead { at: elems(push.act_weight), field: "act_weight" };             if !reads.contains(&slope) {                 reads.push(slope);
library/ml/src/main/rust/src/vulkan/parity_part8.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part8.rs b/library/ml/src/main/rust/src/vulkan/parity_part8.rsindex f3d55e20a0..6101c11606 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part8.rs@@ -1 +1,89 @@ // Device parity fixtures (runtime work). See `parity.rs` for the helpers.++/// A file whose plan reads only tensors deep inside it, behind big unused ones.+///+/// Tensors: 0 big, 1-2 an early gamma/beta, 3 big, 4-6 an int8 1x1 conv, 7-8 a late gamma/beta.+/// The big ones have odd lengths so the window's start is not a tensor boundary rounded by luck.+fn deep_window_fixture() -> (Weights, Plan, Plan) {+    const C: u32 = 64;+    const W: u32 = 9;+    let kernel: Vec<i8> = (0..C * C).map(|i| (i % 7) as i8 - 3).collect();+    let tensors = vec![+        Fixture::F16(vec![3_000_001], spread(3_000_001, 0.3)),+        Fixture::F16(vec![C], spread(C as usize, 1.7)),+        Fixture::F16(vec![C], spread(C as usize, 2.9)),+        Fixture::F16(vec![2_500_003], spread(2_500_003, 0.9)),+        Fixture::I8(vec![C, C, 1, 1], kernel),+        Fixture::F16(vec![C], vec![1.0 / 16.0; C as usize]),+        Fixture::F16(vec![C], spread(C as usize, 0.4)),+        Fixture::F16(vec![C], spread(C as usize, 1.1)),+        Fixture::F16(vec![C], spread(C as usize, 2.3)),+    ];+    let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);+    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+    let dims = |index: usize| -> Vec<u32> {+        match index {+            0 => vec![3_000_001],+            3 => vec![2_500_003],+            4 => vec![C, C, 1, 1],+            _ => vec![C],+        }+    };++    let mut b = Builder::new(&weights);+    let x = b.input(Shape::new(C, 1, W));+    let y = b.conv_int8(x, 4, C, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Relu);+    let y = b.layer_norm(y, 7, 1e-5);+    for index in 0..4 {+        b.host_tensor(index, &dims(index));+    }+    let deep = b.finish(&[y]).expect("the deep plan builds");++    let mut b = Builder::new(&weights);+    let x = b.input(Shape::new(C, 1, W));+    let y = b.layer_norm(x, 1, 1e-5);+    for index in (0..9).filter(|&i| i != 1 && i != 2) {+        b.host_tensor(index, &dims(index));+    }+    let early = b.finish(&[y]).expect("the early plan builds");+    (weights, deep, early)+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_net_uploads_only_the_window_its_plan_reads() {+    let (weights, deep, early) = deep_window_fixture();+    let input = spread(64 * 9, 0.6);+    let host_deep = run_multi(&deep, weights.data(), &[&input]).expect("the interpreter runs");+    let host_early = run_multi(&early, weights.data(), &[&input]).expect("the interpreter runs");+    let total = weights.data().len() as u64;+    let offset_of = |index: usize| u64::from(weights.tensor(index).expect("it exists").offset);+    let kernel_at = offset_of(4);++    let mut net = Net::new(device(), deep.clone(), &weights, RESCALE_ONLY).expect("it records");+    let (lo, hi) = net.weights_window();+    assert!(lo > 0 && lo <= kernel_at && kernel_at - lo < 256, "window starts at {lo}");+    assert_eq!(hi, total, "the last tensor is read, so the window runs to the end");+    assert!(hi - lo < total / 100, "{} of {total} bytes uploaded", hi - lo);+    let windowed = net.infer_raw(&input).expect("the windowed net runs");+    matches("a windowed net", &host_deep, &windowed);++    let mut whole = Net::whole(device(), deep.clone(), &weights, RESCALE_ONLY).expect("it records");+    assert_eq!(whole.weights_window(), (0, total));+    let all = whole.infer_raw(&input).expect("the whole-file net runs");+    assert_eq!(windowed, all, "the window changes where bytes live, not what is computed");++    // Outside the window: refused, and the net keeps working at the plan it had.+    let refused = net.rebuild(early.clone());+    assert!(refused.is_err(), "a plan reading below the window was installed");+    let again = net.infer_raw(&input).expect("the net survives the refused rebuild");+    assert_eq!(again, windowed);++    let mut both = Net::covering(device(), deep, &[&early], &weights, RESCALE_ONLY)+        .expect("the covering net records");+    let (lo, _) = both.weights_window();+    assert!(lo <= offset_of(1) && lo > 0, "covering window at {lo}");+    matches("a covering net", &host_deep, &both.infer_raw(&input).expect("it runs"));+    both.rebuild(early).expect("the covered plan installs");+    matches("a covering net rebuilt", &host_early, &both.infer_raw(&input).expect("it runs"));+}
library/ml/src/main/rust/src/vulkan/reshape.rs
diff --git a/library/ml/src/main/rust/src/vulkan/reshape.rs b/library/ml/src/main/rust/src/vulkan/reshape.rsindex 5d1310bd9a..95efa97af9 100644--- a/library/ml/src/main/rust/src/vulkan/reshape.rs+++ b/library/ml/src/main/rust/src/vulkan/reshape.rs@@ -78,7 +78,34 @@ impl<S: Copy + PartialEq> Reshaped<S> {     ) -> Result<Reshaped<S>, String> {         let first = plan(&offsets, shape)?;         let built = vec![(shape, first.clone())];-        let net = Net::new(context, first, data, RESCALE_ONLY)?;+        let net = Net::whole(context, first, data, RESCALE_ONLY)?;+        Ok(Reshaped { net, offsets, at: shape, plan, built })+    }++    /// [`Reshaped::streamed`], uploading only the tensors the plans at `shapes` read.+    ///+    /// Recorded at `shapes[0]`. [`Reshaped::at`] any shape whose plan reads outside that window+    /// is an error the net survives. For a file much larger than what its plans touch, such as+    /// Gemma's 3.6 GB EMBED read by a 14 MB gather plan.+    pub fn windowed(+        context: Arc<Context>,+        offsets: Offsets,+        data: &dyn Blob,+        shapes: &[S],+        plan: fn(&Offsets, S) -> Result<Plan, String>,+    ) -> Result<Reshaped<S>, String> {+        let Some(&shape) = shapes.first() else {+            return Err("Reshaped::windowed needs at least one shape".into());+        };+        let mut built = Vec::with_capacity(shapes.len());+        for &each in shapes {+            built.push((each, plan(&offsets, each)?));+        }+        let first = built.first().map(|(_, plan)| plan.clone()).ok_or("no plan was built")?;+        let also: Vec<&Plan> = built.iter().skip(1).map(|(_, plan)| plan).collect();+        let net = Net::covering(context, first, &also, data, RESCALE_ONLY)?;+        let keep = built.len().saturating_sub(BUILT_PLANS);+        built.drain(..keep);         Ok(Reshaped { net, offsets, at: shape, plan, built })     } 
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex 1a5ae33206..03ea0f7f38 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -273,8 +273,12 @@ pub struct Net {     ///     /// Almost always one window over the whole file. See [`super::segment`].     segments: Segments,-    /// The `.maml` tensor table, for [`Segments::for_op`].+    /// The `.maml` tensors inside the uploaded window, offsets relative to its start, for+    /// [`Segments::for_op`].     tensors: Vec<crate::weights::Tensor>,+    /// The `[lo, hi)` data-section bytes in the weights buffer. Byte 0 of the buffer is file+    /// byte `lo`; a plan reading outside the window is refused at record time.+    window: (u64, u64),     /// This net's own command pool, not the context's.     ///     /// A `VkCommandPool` is externally synchronised across *recording* as well as across
library/ml/src/main/rust/src/vulkan/run_part1.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part1.rs b/library/ml/src/main/rust/src/vulkan/run_part1.rsindex bf4b1454ed..3cff930b9d 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -6,20 +6,65 @@ impl Net {     /// of heap.     ///     /// A [`Blob`] rather than a [`crate::weights::Weights`] so that a bundled net can stream-    /// straight out of the APK. Nothing here reads the tensor table — the [`Plan`] already carries-    /// every resolved offset — which is what makes the two interchangeable.+    /// straight out of the APK.+    ///+    /// Only the bytes `plan`'s ops read are uploaded: the smallest window of whole tensors+    /// covering them. A later [`Net::rebuild`] must read inside that window, so a net that+    /// switches between plans reading different tensors is built with [`Net::covering`] or+    /// [`Net::whole`].     pub fn new(         context: Arc<Context>,         plan: Plan,         weights: &dyn Blob,         normalise: Normalise,     ) -> Result<Net, String> {+        Self::covering(context, plan, &[], weights, normalise)+    }++    /// [`Net::new`], uploading the window that covers `plan` and every plan in `also`.+    pub fn covering(+        context: Arc<Context>,+        plan: Plan,+        also: &[&Plan],+        weights: &dyn Blob,+        normalise: Normalise,+    ) -> Result<Net, String> {+        let align = context.limits.min_storage_buffer_offset_alignment.max(super::segment::ALIGNMENT);+        let mut plans = vec![&plan];+        plans.extend_from_slice(also);+        let window = super::segment::read_window(&plans, weights.tensors(), align)?;+        Self::with_window(context, plan, weights, normalise, window)+    }++    /// [`Net::new`], uploading the whole data section so any plan over this file can be+    /// installed by [`Net::rebuild`].+    pub fn whole(+        context: Arc<Context>,+        plan: Plan,+        weights: &dyn Blob,+        normalise: Normalise,+    ) -> Result<Net, String> {+        let window = (0, weights.data_len());+        Self::with_window(context, plan, weights, normalise, window)+    }++    fn with_window(+        context: Arc<Context>,+        plan: Plan,+        weights: &dyn Blob,+        normalise: Normalise,+        window: (u64, u64),+    ) -> Result<Net, String> {+        let (lo, hi) = window;+        if lo > hi || hi > weights.data_len() {+            return Err(format!("weights window {lo}..{hi} of a {}-byte file", weights.data_len()));+        }         let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2;         // Vulkan forbids a zero-sized buffer, and the descriptor set needs a real one bound to         // the weights binding whether or not any shader reads it. A plan can legitimately read         // no weights at all — a purely elementwise one does — so this floors the allocation         // rather than refusing the plan.-        let weights_bytes = (weights.data_len() as vk::DeviceSize).max(2);+        let weights_bytes = ((hi - lo) as vk::DeviceSize).max(2);         let input_elems = binding_elems(&plan.inputs);         let output_elems = binding_elems(&plan.outputs);         // One staging buffer for both directions: the inputs and the outputs are never in@@ -33,7 +78,7 @@ impl Net {         let segments = Segments::plan(weights_bytes, &context.limits)?;         // A few kilobytes, kept because `record` needs each tensor's extent to know which window         // an op fits in, and `rebuild` installs plans this net was not constructed with.-        let tensors = weights.tensors().to_vec();+        let tensors = super::segment::window_tensors(weights.tensors(), lo, hi);          let weights_buffer = Buffer::device_local(&context, weights_bytes)?;         let arena = Buffer::device_local(&context, arena_bytes)?;@@ -71,6 +116,7 @@ impl Net {             pipelines,             segments,             tensors,+            window,             command_pool,             command_buffer: vk::CommandBuffer::null(),             fence: vk::Fence::null(),@@ -84,8 +130,9 @@ impl Net {         let staged = std::time::Instant::now();         net.upload_weights(weights)?;         timing!(-            "upload {} MB in {:.0} ms",+            "upload {} MB of {} MB (bytes {lo}..{hi}) in {:.0} ms",             weights_bytes / (1024 * 1024),+            weights.data_len() / (1024 * 1024),             staged.elapsed().as_secs_f64() * 1000.0         );         net.command_buffer = net.allocate_command_buffer()?;@@ -132,6 +179,13 @@ impl Net {         if self.poisoned {             return Err("this network is unusable after an earlier failure".into());         }+        // Before anything changes, so a plan reading past the uploaded window is an error the+        // net survives rather than one that retires it at record time.+        for (step, op) in plan.ops.iter().enumerate() {+            if let Op::Dispatch { kind, push, .. } = op {+                self.windowed(step, *kind, push)?;+            }+        }         let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2;         let input_elems = binding_elems(&plan.inputs);         let output_elems = binding_elems(&plan.outputs);@@ -247,7 +301,8 @@ impl Net {     /// trip per chunk — 16 for that sampler — against a transfer that is bandwidth-bound anyway,     /// and it happens once per net rather than once per inference.     fn upload_weights(&self, weights: &dyn Blob) -> Result<(), String> {-        let total = weights.data_len();+        let (lo, hi) = self.window;+        let total = hi - lo;         if total == 0 {             return Ok(());         }@@ -270,7 +325,7 @@ impl Net {                     Some(piece) => piece,                     None => break Err("a chunk is larger than its buffer".to_string()),                 };-                if let Err(e) = weights.read_at(written, piece) {+                if let Err(e) = weights.read_at(lo + written, piece) {                     break Err(e);                 }                 if let Err(e) = staging.write(piece) {@@ -312,6 +367,38 @@ impl Net {         }     } +    /// `push` rebased into the uploaded window, or an error if it reads outside it.+    fn windowed(+        &self,+        step: usize,+        kind: crate::nets::Kind,+        push: &crate::nets::Push,+    ) -> Result<crate::nets::Push, String> {+        let (lo, hi) = self.window;+        let reads = kind.weight_reads(push);+        for read in &reads {+            let inside = read.at >= lo+                && self.tensors.iter().any(|tensor| {+                    let start = lo + u64::from(tensor.offset);+                    let end = start + tensor.dtype.bytes(u64::from(tensor.len));+                    read.at >= start && read.at < end.max(start + 1)+                });+            if !inside {+                return Err(format!(+                    "step {step} ({kind:?}) reads {} at byte {}, outside the weights window \+                     {lo}..{hi} this net uploaded. Build it with Net::covering or Net::whole.",+                    read.field, read.at+                ));+            }+        }+        Ok(super::segment::rebase_push(lo, kind, push))+    }++    /// The `[lo, hi)` data-section bytes this net uploaded.+    pub fn weights_window(&self) -> (u64, u64) {+        self.window+    }+     fn allocate_command_buffer(&self) -> Result<vk::CommandBuffer, String> {         let info = vk::CommandBufferAllocateInfo::default()             .command_pool(self.command_pool)
library/ml/src/main/rust/src/vulkan/run_part2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part2.rs b/library/ml/src/main/rust/src/vulkan/run_part2.rsindex d8d07f85d5..cce1436800 100644--- a/library/ml/src/main/rust/src/vulkan/run_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part2.rs@@ -89,9 +89,10 @@ impl Net {                             vk::PipelineBindPoint::COMPUTE,                             self.pipelines.for_kind(kind),                         );-                        // The window an op's weights are visible through, and the push rebased-                        // into it. Both are the identity unless the file was larger than one-                        // descriptor's range, so the common case records what it always did.+                        // File offsets made relative to the uploaded window, then to the+                        // descriptor window inside it. Both are the identity for a plan that+                        // reads from byte 0 of a file one descriptor can hold.+                        let push = self.windowed(step, kind, &push)?;                         let segment =                             self.segments.for_op(step, kind, &push, &self.tensors)?.unwrap_or(0);                         let set = match self.pipelines.descriptor_sets.get(segment) {
library/ml/src/main/rust/src/vulkan/segment.rs
diff --git a/library/ml/src/main/rust/src/vulkan/segment.rs b/library/ml/src/main/rust/src/vulkan/segment.rsindex 4b74964239..4456e6f61e 100644--- a/library/ml/src/main/rust/src/vulkan/segment.rs+++ b/library/ml/src/main/rust/src/vulkan/segment.rs@@ -140,37 +140,7 @@ impl Segments {     /// The kinds named below must stay in step with the word-unit arm of [`Kind::weight_reads`],     /// which is the only place that decides what a `weight` offset counts in.     pub fn rebase(&self, index: usize, kind: Kind, push: &Push) -> Push {-        let base = self.segments.get(index).map_or(0, |segment| segment.base);-        if base == 0 {-            return *push;-        }-        let elems = (base / 2) as u32;-        let words = (base / 4) as u32;-        let mut out = *push;-        for read in kind.weight_reads(push) {-            match read.field {-                "weight"-                    if matches!(-                        kind,-                        Kind::ConvInt8-                            | Kind::ConvPointInt8-                            | Kind::ConvVecInt8-                            | Kind::ConvVecInt4-                            | Kind::ConvPointInt4-                            | Kind::ConvQ2K-                            | Kind::ConvVecQ2K-                            | Kind::ConvPointQ2K-                    ) =>-                {-                    out.weight = push.weight.saturating_sub(words);-                }-                "weight" => out.weight = push.weight.saturating_sub(elems),-                "bias" => out.bias = push.bias.saturating_sub(elems),-                "act_weight" => out.act_weight = push.act_weight.saturating_sub(elems),-                _ => {}-            }-        }-        out+        rebase_push(self.segments.get(index).map_or(0, |segment| segment.base), kind, push)     }      /// The `[from, to)` byte span of the weights one op reads, or `None` if it reads none.@@ -209,13 +179,98 @@ impl Segments {     } } -/// The end of the tensor containing byte `at`.+/// `push` with every weights offset it reads moved down by `base` bytes, a multiple of+/// [`ALIGNMENT`]. Callers must have checked that no read lies below `base`.+pub(crate) fn rebase_push(base: u64, kind: Kind, push: &Push) -> Push {+    if base == 0 {+        return *push;+    }+    let elems = (base / 2) as u32;+    let words = (base / 4) as u32;+    let mut out = *push;+    for read in kind.weight_reads(push) {+        match read.field {+            "weight"+                if matches!(+                    kind,+                    Kind::ConvInt8+                        | Kind::ConvPointInt8+                        | Kind::ConvVecInt8+                        | Kind::ConvVecInt4+                        | Kind::ConvPointInt4+                        | Kind::ConvQ2K+                        | Kind::ConvVecQ2K+                        | Kind::ConvPointQ2K+                ) =>+            {+                out.weight = push.weight.saturating_sub(words);+            }+            "weight" => out.weight = push.weight.saturating_sub(elems),+            "bias" => out.bias = push.bias.saturating_sub(elems),+            "act_weight" => out.act_weight = push.act_weight.saturating_sub(elems),+            _ => {}+        }+    }+    out+}++/// The `[start, end)` byte extent of the tensor containing byte `at`. /// /// A linear scan, run once per op per recording over a table of at most a few hundred entries.-fn tensor_end(at: u64, tensors: &[Tensor]) -> Option<u64> {+fn tensor_extent(at: u64, tensors: &[Tensor]) -> Option<(u64, u64)> {     tensors.iter().find_map(|tensor| {         let start = u64::from(tensor.offset);         let bytes = tensor.dtype.bytes(u64::from(tensor.len));-        (at >= start && at < start + bytes.max(1)).then_some(start + bytes)+        (at >= start && at < start + bytes.max(1)).then_some((start, start + bytes))     }) }++fn tensor_end(at: u64, tensors: &[Tensor]) -> Option<u64> {+    tensor_extent(at, tensors).map(|(_, end)| end)+}++/// The `[lo, hi)` bytes of the data section that `plans`' ops read, whole tensors, with `lo`+/// rounded down to `align`. `(0, 0)` when nothing is read.+pub(crate) fn read_window(+    plans: &[&crate::nets::Plan],+    tensors: &[Tensor],+    align: u64,+) -> Result<(u64, u64), String> {+    let mut lo = u64::MAX;+    let mut hi = 0u64;+    for plan in plans {+        for (step, op) in plan.ops.iter().enumerate() {+            let crate::nets::Op::Dispatch { kind, push, .. } = op else { continue };+            for read in kind.weight_reads(push) {+                let (start, end) = tensor_extent(read.at, tensors).ok_or_else(|| {+                    format!(+                        "step {step} ({kind:?}) reads {} at byte {}, which is inside none of the \+                         {} tensors the file describes",+                        read.field,+                        read.at,+                        tensors.len()+                    )+                })?;+                lo = lo.min(start);+                hi = hi.max(end);+            }+        }+    }+    if hi == 0 {+        return Ok((0, 0));+    }+    Ok((lo - lo % align.max(1), hi))+}++/// The tensors lying wholly inside `[lo, hi)`, with offsets made relative to `lo`.+pub(crate) fn window_tensors(tensors: &[Tensor], lo: u64, hi: u64) -> Vec<Tensor> {+    tensors+        .iter()+        .filter_map(|tensor| {+            let start = u64::from(tensor.offset);+            let end = start + tensor.dtype.bytes(u64::from(tensor.len));+            (start >= lo && end <= hi)+                .then(|| Tensor { offset: (start - lo) as u32, ..*tensor })+        })+        .collect()+}