Modern Apps git

← Modern-Apps.git

library:ml: re-record a net at a new shape, keeping its weights uploaded

Commit
d473145b0a8e0044f4e53e7bebdf2ae558788d67
Author
vayun-mathur <[email protected]>
When
2026-08-28 18:37 UTC (3 months ago)
Parents
16be9e2

Diff

library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 7a9916b416..4d0972c7a0 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -111,8 +111,13 @@ fn build( fn compare(what: &str, plan: Plan, data: Vec<u8>, inputs: &[&[f32]]) {     let host = run_multi(&plan, &data, inputs).expect("the interpreter runs the plan");     let got = on_device(plan, data, inputs);+    matches(what, &host, &got);+}++/// Require the interpreter's outputs and the device's to agree, one binding at a time.+fn matches(what: &str, host: &[Vec<f32>], got: &[Vec<f32>]) {     assert_eq!(got.len(), host.len(), "{what}: output count");-    for (index, (host, got)) in host.iter().zip(&got).enumerate() {+    for (index, (host, got)) in host.iter().zip(got).enumerate() {         assert_eq!(got.len(), host.len(), "{what}: output {index} length");         // Scale from the interpreter's output, not from the pair, so a device result that came         // back as zeros cannot shrink the threshold until it passes.@@ -284,3 +289,40 @@ fn a_two_lane_embedding_agrees_with_the_reference() {         |b, ids| b.embed(ids[0], 0, rows, channels),     ); }++#[test]+#[ignore = "needs a Vulkan device"]+fn a_rebuilt_net_agrees_with_the_reference_at_each_shape() {+    // Supertonic runs one set of weights at whatever length the utterance turns out to be, so+    // `Net::rebuild` re-records a net instead of building a second one and uploading 198 MB+    // again. The widths go up and then back down on purpose: growing reallocates the arena and+    // rewrites the descriptor, while shrinking keeps the buffer it already has, and it is the+    // second visit to a narrow shape that would catch a descriptor left pointing at the arena+    // that was freed under it.+    let gamma = spread(8, 1.1);+    let beta = spread(8, 2.3);+    let given = Given::new(&[(vec![8], gamma), (vec![8], beta)])+        .expect("the fixture tensors are consistent");+    let data = given.data().to_vec();+    // Two ops, so the second reads out of the arena what the first wrote into it. A one-op plan+    // would pass on a rebind that had gone to the wrong buffer, since its only read is the input+    // copy the command buffer performs by handle rather than through the descriptor set.+    let at = |width: u32| {+        build(&given, &[Shape::new(8, 1, width)], |b, ids| {+            let normed = b.layer_norm(ids[0], 0, 1e-5);+            b.add(normed, ids[0])+        })+    };++    let weights = Weights::from_data(data.clone());+    let mut net = Net::new(device(), at(3), &weights, RESCALE_ONLY)+        .expect("the plan records into a command buffer");+    for width in [9u32, 4] {+        let plan = at(width);+        let input = spread(8 * width as usize, width as f32);+        let host = run_multi(&plan, &data, &[&input]).expect("the interpreter runs the plan");+        net.rebuild(plan).expect("the net re-records at the new shape");+        let got = net.infer_raw(&input).expect("the rebuilt buffer submits and reads back");+        matches(&format!("a net rebuilt at {width}"), &host, &got);+    }+}
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex d28903f4f6..703ec324a3 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -136,6 +136,30 @@ pub struct Pipelines { }  impl Pipelines {+    /// Point binding 0 at a different arena buffer, for [`super::run::Net::rebuild`].+    ///+    /// Only the arena moves: the weights are uploaded once and outlive any reshape, which is the+    /// whole reason rebuilding beats constructing a second net. The caller must have waited for+    /// the device to go idle first — a descriptor set may not be written while a command buffer+    /// that uses it is pending.+    pub fn rebind_arena(+        &self,+        device: &ash::Device,+        arena: vk::Buffer,+        arena_size: vk::DeviceSize,+    ) {+        let arena_info =+            vk::DescriptorBufferInfo::default().buffer(arena).offset(0).range(arena_size);+        let write = vk::WriteDescriptorSet::default()+            .dst_set(self.descriptor_set)+            .dst_binding(0)+            .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+            .buffer_info(std::slice::from_ref(&arena_info));+        // SAFETY: a descriptor write to a set this struct owns, against a buffer the caller+        // keeps alive. Nothing using the set is pending, per the contract above.+        unsafe { device.update_descriptor_sets(std::slice::from_ref(&write), &[]) };+    }+     /// Build all of them and point the descriptor set at `arena` and `weights`.     pub fn new(         context: &Context,
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 3968f946d9..db36a95cea 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -59,7 +59,8 @@ pub struct Net {     command_pool: vk::CommandPool,     command_buffer: vk::CommandBuffer,     fence: vk::Fence,-    /// Set when a submission was left pending, after which this net is unusable.+    /// Set when a submission was left pending, or a recording left part-written, after which+    /// this net is unusable.     ///     /// A `wait_for_fences` timeout returns an error while the submission is **still in     /// flight**. Nothing can cancel it, so resetting the fence, resubmitting the command@@ -67,7 +68,8 @@ pub struct Net {     /// five-second timeout exists precisely so a hung GPU does not block forever, this is     /// an anticipated path rather than a theoretical one. Once poisoned, every later     /// `infer` fails immediately without touching Vulkan, and only `Drop` — which waits-    /// for the device to go idle first — cleans up.+    /// for the device to go idle first — cleans up. [`Net::rebuild`] sets it for the other+    /// reason: a command buffer it failed to finish recording must never be submitted.     poisoned: bool,     /// Scratch for the fp16 input and the fp16 output, so an inference allocates nothing.     input_scratch: Vec<u16>,@@ -143,6 +145,80 @@ impl Net {         Ok(net)     } +    /// Re-record this net at `plan`'s shapes, keeping the weights already uploaded.+    ///+    /// Supertonic's nets are shaped by the utterance — the text encoder runs at the character+    /// count, the sampler and the vocoder at the latent length — and a [`Plan`] is one command+    /// buffer recorded at fixed shapes, so a new length needs a new recording. It does not need a+    /// new upload: the weights are the expensive part (198 MB for Supertonic, 605 MB for+    /// SMaLL-100) and they do not depend on the length. So this keeps the weights buffer and+    /// re-uses the arena and the staging buffer too, growing them only when the new shapes need+    /// more than the old ones did — which for a sequence of utterances means the allocation+    /// happens a handful of times rather than once per sentence.+    ///+    /// `plan` must have been built against the same weights as this net's. Nothing here checks+    /// that, because [`crate::nets::Builder::finish`] already refuses a plan that does not read+    /// every tensor in its file, so a plan for a different `.maml` cannot reach here.+    pub fn rebuild(&mut self, plan: Plan) -> Result<(), String> {+        if self.poisoned {+            return Err("this network is unusable after an earlier failure".into());+        }+        let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2;+        let input_elems = binding_elems(&plan.inputs);+        let output_elems = binding_elems(&plan.outputs);+        let staging_bytes = (input_elems.max(output_elems) as vk::DeviceSize) * 2;++        // Allocate before touching any state. A failure part-way through must leave the net+        // running at its old plan: a descriptor pointing at a new arena while the recorded+        // command buffer still copies the inputs into the old one would be a wrong answer at the+        // right shape, which is far worse than an error.+        let grown_arena = if arena_bytes > self.arena.size {+            Some(Buffer::device_local(&self.context, arena_bytes)?)+        } else {+            None+        };+        let grown_staging = if staging_bytes > self.staging.size {+            Some(Buffer::staging(&self.context, staging_bytes)?)+        } else {+            None+        };++        // SAFETY: a descriptor set may not be rewritten, and a bound buffer may not be freed,+        // while a command buffer using either is pending. `submit` waits on its fence before+        // returning and the check above rejects the one case where it did not, so nothing is in+        // fact pending — but this costs one round trip per length change, not per inference, and+        // it makes that reasoning unnecessary rather than load-bearing.+        unsafe {+            let guard = self.context.lock_queue();+            let idle = self.context.device.device_wait_idle();+            drop(guard);+            idle.map_err(|e| format!("device_wait_idle {e:?}"))?;+        }++        // Past here nothing fails until `record`, so the net cannot be left describing one shape+        // and recording another. Each old `Buffer` frees itself as it is replaced, after the wait+        // above.+        if let Some(arena) = grown_arena {+            self.pipelines.rebind_arena(&self.context.device, arena.buffer, arena.size);+            self.arena = arena;+        }+        if let Some(staging) = grown_staging {+            self.staging = staging;+        }+        self.input_scratch.resize(input_elems, 0);+        self.output_scratch.resize(output_elems, 0);+        self.plan = plan;++        // A `record` that fails leaves the command buffer part-written, and submitting that is+        // not something a later caller may be allowed to do. There is no way back — both of its+        // failure modes are device loss or host OOM — so the net is retired instead.+        if let Err(e) = self.record() {+            self.poisoned = true;+            return Err(e);+        }+        Ok(())+    }+     /// Copy the weights blob to device-local memory through the staging buffer.     ///     /// Its own one-shot command buffer and its own staging allocation, because the@@ -584,7 +660,7 @@ impl Net {     /// here once rather than twice.     fn submit(&mut self) -> Result<(), String> {         if self.poisoned {-            return Err("a previous submission timed out; this network is unusable".into());+            return Err("this network is unusable after an earlier failure".into());         }         // SAFETY: the scratch buffer is exactly the fp16 elements the recorded copy         // regions move, and `u16` has no padding or invalid bit patterns.