Modern Apps git

← Modern-Apps.git

ml: warm row-norm dispatches once, Supertonic new-sentence reshape 160 -> 100 ms

Commit
6a15f611bf8994a3b6cabbc27850f655bad24025
Author
vayun-mathur <[email protected]>
When
2026-10-26 05:28 UTC (1 month ago)
Parents
40def16

Diff

library/ml/src/main/rust/examples/profile_supertonic.rs
diff --git a/library/ml/src/main/rust/examples/profile_supertonic.rs b/library/ml/src/main/rust/examples/profile_supertonic.rsindex 0508ba56f0..7c259580de 100644--- a/library/ml/src/main/rust/examples/profile_supertonic.rs+++ b/library/ml/src/main/rust/examples/profile_supertonic.rs@@ -398,6 +398,34 @@ fn run() -> Result<(), String> {     print_kinds("vocoder", &stages.vocoder_times);      assert_eq!(stages.sampler_ms.len(), STEPS as usize, "one dual submit per step");++    // Further, differently sized sentences in the same process (`MODELRUNNER_SECOND`, split on+    // `|`): what each new sentence length costs once everything is warm.+    let more = std::env::var("MODELRUNNER_SECOND").unwrap_or_default();+    for second in more.split('|').filter(|s| !s.is_empty()) {+        let reshaped = stages.reshape_ms;+        let (text, sampler, vocoder) =+            (stages.reshape_text_ms, stages.reshape_sampler_ms, stages.reshape_vocoder_ms);+        let whole = Instant::now();+        let samples = supertonic::synthesise(+            &mut stages,+            &conditioning,+            &indexer,+            &voice,+            second,+            LANGUAGE,+            &|count| noise.borrow_mut().normal(count),+        )?;+        println!(+            "second    {:>8.1} ms, {} samples, reshape {:.1} ms (ttl {:.1}, ve {:.1}, voc {:.1})",+            ms(whole),+            samples.len(),+            stages.reshape_ms - reshaped,+            stages.reshape_text_ms - text,+            stages.reshape_sampler_ms - sampler,+            stages.reshape_vocoder_ms - vocoder+        );+    }     Ok(()) } 
library/ml/src/main/rust/shaders/reduce.glsl
diff --git a/library/ml/src/main/rust/shaders/reduce.glsl b/library/ml/src/main/rust/shaders/reduce.glslindex 8b3036609d..8fc9cdf3e5 100644--- a/library/ml/src/main/rust/shaders/reduce.glsl+++ b/library/ml/src/main/rust/shaders/reduce.glsl@@ -23,8 +23,13 @@ // Every call is reached by the whole workgroup: the row index is per workgroup, so an early // `return` on it is uniform, and `p.kw` is a push constant. -// One slot per subgroup. 64 covers a subgroup size of 1, which no device has but costs nothing.-shared float reduce_partial[64];+// Sixteen slots: a 64-lane workgroup has at most 16 subgroups whenever subgroups have at least+// 4 lanes (every real device), and the loops below take more in batches of 16, summing in the+// same order, so the result never depends on it. Not 64: on Mali the driver's per-dispatch+// recording cost grows with shared bytes x workgroups, and 64 slots made Supertonic's row-mode+// layer norms cost up to ~1 ms each to record at a new sentence length.+#define REDUCE_SLOTS 16u+shared float reduce_partial[REDUCE_SLOTS];  // The row this workgroup owns in row mode, across the same 2-D grid `global_index` flattens. uint reduce_row() {@@ -39,30 +44,38 @@ bool reduce_row_mode() { // The sum of `value` over every lane of the workgroup, returned to every lane. float workgroup_sum(float value) {     float summed = subgroupAdd(value);-    if (subgroupElect()) {-        reduce_partial[gl_SubgroupID] = summed;-    }-    barrier();     float total = 0.0;-    for (uint i = 0u; i < gl_NumSubgroups; i++) {-        total += reduce_partial[i];+    for (uint first = 0u; first < gl_NumSubgroups; first += REDUCE_SLOTS) {+        if (subgroupElect() && gl_SubgroupID >= first && gl_SubgroupID < first + REDUCE_SLOTS) {+            reduce_partial[gl_SubgroupID - first] = summed;+        }+        barrier();+        uint count = min(REDUCE_SLOTS, gl_NumSubgroups - first);+        for (uint i = 0u; i < count; i++) {+            total += reduce_partial[i];+        }+        // The next batch or reduction reuses the slots, so nobody may write them until everyone+        // has read.+        barrier();     }-    // The next reduction reuses the slots, so nobody may write them until everyone has read.-    barrier();     return total; }  // The maximum of `value` over every lane of the workgroup, returned to every lane. float workgroup_max(float value) {     float top = subgroupMax(value);-    if (subgroupElect()) {-        reduce_partial[gl_SubgroupID] = top;-    }-    barrier();-    float peak = reduce_partial[0];-    for (uint i = 1u; i < gl_NumSubgroups; i++) {-        peak = max(peak, reduce_partial[i]);+    float peak = 0.0;+    for (uint first = 0u; first < gl_NumSubgroups; first += REDUCE_SLOTS) {+        if (subgroupElect() && gl_SubgroupID >= first && gl_SubgroupID < first + REDUCE_SLOTS) {+            reduce_partial[gl_SubgroupID - first] = top;+        }+        barrier();+        peak = first == 0u ? reduce_partial[0] : max(peak, reduce_partial[0]);+        uint count = min(REDUCE_SLOTS, gl_NumSubgroups - first);+        for (uint i = 1u; i < count; i++) {+            peak = max(peak, reduce_partial[i]);+        }+        barrier();     }-    barrier();     return peak; }
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 749b69bb9d..f1c8887c67 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part8.rs@@ -211,3 +211,41 @@ fn a_widened_int8_gemm_matches_the_int8_paths_bit_for_bit() {         }     } }++/// Record cost of row-mode reductions by kind and width (24 dispatches each, 512-long rows):+/// prints how long `Net::rebuild` takes to re-record at `width` rows. Measures, asserts nothing.+#[test]+#[ignore = "needs a Vulkan device"]+fn report_row_reduce_record_cost() {+    type Make = fn(&mut Builder, Id) -> Id;+    let kinds: [(&str, Make, usize, bool); 4] = [+        ("rms_norm", |b, x| b.rms_norm(x, 0, 1e-5), 1, false),+        ("layer_norm", |b, x| b.layer_norm(x, 0, 1e-5), 2, false),+        ("softmax", |b, x| b.softmax(x), 0, true),+        ("rms_norm", |b, x| b.rms_norm(x, 0, 1e-5), 1, false),+    ];+    for (name, make, count, rows_in_channels) in kinds {+        for width in [1u32, 16, 68, 200] {+            let source = Invented::new(count);+            let plan_at = |rows: u32| {+                let shape =+                    if rows_in_channels { Shape::new(rows, 1, 512) } else { Shape::new(512, 1, rows) };+                let mut b = Builder::new(&source);+                let mut x = b.input(shape);+                for _ in 0..24 {+                    x = make(&mut b, x);+                }+                b.finish(&[x]).expect("the probe plan builds")+            };+            let (small, big) = (plan_at(1), plan_at(width));+            let weights = Weights::from_data(source.into_data());+            let mut net = Net::new(device(), small, &weights, RESCALE_ONLY).expect("the net records");+            let started = std::time::Instant::now();+            net.rebuild(big).expect("the net re-records");+            println!(+                "record-probe {name} rows {width}: rebuild {:.2} ms for 24 dispatches",+                started.elapsed().as_secs_f64() * 1e3+            );+        }+    }+}
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 5191e3ce4c..0acb532cb8 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -290,6 +290,9 @@ pub struct Net {     /// time, and nothing else can reach this pool.     command_pool: vk::CommandPool,     command_buffer: vk::CommandBuffer,+    /// One-shot transfers (arena copies, persistent-tensor writes and reads), kept apart from+    /// `command_buffer` so they never disturb the plan's recording. See [`Net::run_once`].+    transfer: vk::CommandBuffer,     /// Other plans' recordings, oldest first, each still valid against the current arena,     /// staging buffer and descriptor sets. A rebuild into one of these plans swaps buffers     /// instead of re-recording.
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 cd9c1c3184..17d6cfdce9 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -133,6 +133,7 @@ impl Net {             window,             command_pool,             command_buffer: vk::CommandBuffer::null(),+            transfer: vk::CommandBuffer::null(),             recorded: Vec::new(),             spare: Vec::new(),             pinned_seen,@@ -157,6 +158,8 @@ impl Net {             staged.elapsed().as_secs_f64() * 1000.0         );         net.command_buffer = net.allocate_command_buffer()?;+        net.transfer = net.allocate_command_buffer()?;+        net.warm_row_dispatches()?;         net.fence = net.create_fence()?;         // Written before the first record so a shader reading it never sees uninitialised         // memory, even on a plan that never calls `set_params`.
library/ml/src/main/rust/src/vulkan/run_part3.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part3.rs b/library/ml/src/main/rust/src/vulkan/run_part3.rsindex 47a6387cb7..ec98c59003 100644--- a/library/ml/src/main/rust/src/vulkan/run_part3.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part3.rs@@ -64,16 +64,16 @@ impl Net {         // is recorded and waited on entirely within this call.         unsafe {             device-                .begin_command_buffer(self.command_buffer, &vk::CommandBufferBeginInfo::default())+                .begin_command_buffer(self.transfer, &vk::CommandBufferBeginInfo::default())                 .map_err(|e| format!("begin: {e:?}"))?;             let region = vk::BufferCopy::default().src_offset(0).dst_offset(0).size(self.arena.size);             device.cmd_copy_buffer(-                self.command_buffer,+                self.transfer,                 self.arena.buffer,                 into.buffer,                 std::slice::from_ref(&region),             );-            device.end_command_buffer(self.command_buffer).map_err(|e| format!("end: {e:?}"))?;+            device.end_command_buffer(self.transfer).map_err(|e| format!("end: {e:?}"))?;             self.run_once()         }     }@@ -105,7 +105,7 @@ impl Net {         // so nothing else observes it and the fence outlives the work.         unsafe {             device-                .begin_command_buffer(self.command_buffer, &vk::CommandBufferBeginInfo::default())+                .begin_command_buffer(self.transfer, &vk::CommandBufferBeginInfo::default())                 .map_err(|e| format!("begin: {e:?}"))?;             let mut at = 0u64;             for &(from, elems) in ranges {@@ -114,14 +114,14 @@ impl Net {                     .dst_offset(at)                     .size(u64::from(elems) * 2);                 device.cmd_copy_buffer(-                    self.command_buffer,+                    self.transfer,                     self.arena.buffer,                     self.staging.buffer,                     std::slice::from_ref(&region),                 );                 at += u64::from(elems) * 2;             }-            device.end_command_buffer(self.command_buffer).map_err(|e| format!("end: {e:?}"))?;+            device.end_command_buffer(self.transfer).map_err(|e| format!("end: {e:?}"))?;             self.run_once()?;         }         let mut halves = vec![0u16; (total / 2) as usize];@@ -154,7 +154,7 @@ impl Net {         // SAFETY: as `read_arena`.         unsafe {             device-                .begin_command_buffer(self.command_buffer, &vk::CommandBufferBeginInfo::default())+                .begin_command_buffer(self.transfer, &vk::CommandBufferBeginInfo::default())                 .map_err(|e| format!("begin: {e:?}"))?;             let mut at = 0u64;             for &(to, elems) in ranges {@@ -163,39 +163,33 @@ impl Net {                     .dst_offset(u64::from(to) * 2)                     .size(u64::from(elems) * 2);                 device.cmd_copy_buffer(-                    self.command_buffer,+                    self.transfer,                     self.staging.buffer,                     self.arena.buffer,                     std::slice::from_ref(&region),                 );                 at += u64::from(elems) * 2;             }-            device.end_command_buffer(self.command_buffer).map_err(|e| format!("end: {e:?}"))?;+            device.end_command_buffer(self.transfer).map_err(|e| format!("end: {e:?}"))?;             self.run_once()         }     } -    /// Submit the recorded command buffer and wait for it, then restore the plan's recording.+    /// Submit the one-shot transfer buffer and wait for it.     ///-    /// # The restore is not optional-    ///-    /// `Net` records its plan into `command_buffer` **once** and re-submits it for every-    /// inference. The transfer helpers above record into that same buffer, which resets it - so-    /// without putting the plan back, the next `infer` submits a buffer holding nothing but a-    /// `vkCmdCopyBuffer`. No shader runs, the outputs are whatever the arena already held, and-    /// the model answers with fluent nonsense.-    ///-    /// That is exactly what shipping the precomputed cache did: the bake prefilled correctly,-    /// exported, and every generation *after* the export was reading a net that no longer had a-    /// plan recorded.+    /// The transfer helpers above record into `transfer`, never into `command_buffer`, so the+    /// plan's recording survives and nothing is re-recorded: writing persistent tensors (or+    /// copying the arena on a growth) costs a submit, not a ~400-dispatch record. The plan's+    /// first barrier, after its input copies, names TRANSFER_WRITE as a source, so it orders+    /// these writes before the plan's reads.     ///     /// # Safety     ///-    /// The command buffer must be recorded and ended, and not already in flight.+    /// `transfer` must be recorded and ended, and nothing may be in flight on this net.     unsafe fn run_once(&mut self) -> Result<(), String> {         let device = &self.context.device;         let submit =-            vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&self.command_buffer));+            vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&self.transfer));         unsafe {             device.reset_fences(&[self.fence]).map_err(|e| format!("reset: {e:?}"))?;             // The queue is shared with every other net in the process, so the lock is not@@ -210,9 +204,7 @@ impl Net {                 .wait_for_fences(&[self.fence], true, FENCE_TIMEOUT_NS)                 .map_err(|e| format!("wait_for_fences {e:?}"))?;         }-        // SAFETY: the transfer above is complete - the fence was waited on - so the buffer is-        // free to re-record.-        unsafe { self.record() }+        Ok(())     }      /// Bytes a second, measured by copying the arena to a scratch buffer of the same size.
library/ml/src/main/rust/src/vulkan/run_part8.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part8.rs b/library/ml/src/main/rust/src/vulkan/run_part8.rsindex 84800e4e84..d1fdb66bbf 100644--- a/library/ml/src/main/rust/src/vulkan/run_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part8.rs@@ -139,3 +139,70 @@ impl Net {         self.widened.iter().map(|w| 2 * w.bytes).sum()     } }++impl Net {+    /// Row-mode reductions (one 64-lane workgroup per row, shared memory) recorded per command+    /// buffer, and the rows each covers: the row-mode cap, `ROW_REDUCE_MAX_ROWS` in `nets`.+    const WARM_DISPATCHES: u32 = 96;+    const WARM_ROWS: u32 = 256;++    /// Once per process, record (never submit) row-mode reductions at the largest size into the+    /// transfer buffer.+    ///+    /// On Mali the driver's `vkCmdDispatch` for a shared-memory shader costs ~0.5-1 ms whenever+    /// the dispatch needs more of its internal memory than any recorded before, and that memory+    /// is kept process-wide. Without this, every Supertonic sentence longer than all earlier+    /// ones paid 50-90 ms re-recording the sampler's 72 row-mode layer norms. Only a net with a+    /// row-mode layer norm triggers it, so nets that never record one skip the ~47 ms.+    fn warm_row_dispatches(&self) -> Result<(), String> {+        static WARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+        let row_layer_norm = self.plan.ops.iter().any(|op| {+            matches!(op, Op::Dispatch { kind: crate::nets::Kind::LayerNorm, push, .. } if push.kw == 1)+        });+        if !row_layer_norm || WARMED.swap(true, std::sync::atomic::Ordering::SeqCst) {+            return Ok(());+        }+        let started = std::time::Instant::now();+        let device = &self.context.device;+        let set = self.pipelines.descriptor_sets.first().copied().ok_or("no descriptor set")?;+        // Zero rows: were this ever submitted, every workgroup would return at once.+        let push = crate::nets::Push { kw: 1, ..crate::nets::Push::default() };+        // SAFETY: `transfer` is this net's own idle buffer; it is recorded and ended here and+        // never submitted, and the next transfer re-begins (resets) it.+        unsafe {+            device+                .begin_command_buffer(self.transfer, &vk::CommandBufferBeginInfo::default())+                .map_err(|e| format!("begin: {e:?}"))?;+            device.cmd_bind_pipeline(+                self.transfer,+                vk::PipelineBindPoint::COMPUTE,+                self.pipelines.for_kind(crate::nets::Kind::LayerNorm),+            );+            device.cmd_bind_descriptor_sets(+                self.transfer,+                vk::PipelineBindPoint::COMPUTE,+                self.pipelines.layout(),+                0,+                &[set],+                &[],+            );+            device.cmd_push_constants(+                self.transfer,+                self.pipelines.layout(),+                vk::ShaderStageFlags::COMPUTE,+                0,+                push_bytes(&push),+            );+            for _ in 0..Self::WARM_DISPATCHES {+                device.cmd_dispatch(self.transfer, Self::WARM_ROWS, 1, 1);+            }+            device.end_command_buffer(self.transfer).map_err(|e| format!("end: {e:?}"))?;+            // Hand the grown memory back so other command buffers can take it.+            device+                .reset_command_buffer(self.transfer, vk::CommandBufferResetFlags::RELEASE_RESOURCES)+                .map_err(|e| format!("reset: {e:?}"))?;+        }+        timing!("row-dispatch warm-up {:.1} ms", started.elapsed().as_secs_f64() * 1e3);+        Ok(())+    }+}