Modern Apps git

← Modern-Apps.git

ml: two-stage device argmax (63 workgroups + fold), 1.6 -> 0.12 ms on Pixel

Commit
312a308cf513b9beda5446a7bc9881eb798251f1
Author
vayun-mathur <[email protected]>
When
2026-10-25 23:20 UTC (1 month ago)
Parents
f4ce1c6

Diff

library/ml/src/main/rust/shaders/argmax.comp
diff --git a/library/ml/src/main/rust/shaders/argmax.comp b/library/ml/src/main/rust/shaders/argmax.compindex d7d39cfc0f..2d6d5b60f1 100644--- a/library/ml/src/main/rust/shaders/argmax.comp+++ b/library/ml/src/main/rust/shaders/argmax.comp@@ -1,39 +1,39 @@ #version 450-//! Greedy argmax over a logits row: the winning index as two fp16 values.+//! Greedy argmax over a logits row, first stage: one `(value, lo, hi)` partial per workgroup. //!-//! # Why on the device+//! # Why two stages //!-//! The 262,144-logit host scan costs ~14 ms a token (plus the 512 KB-//! readback it implies when logits otherwise stay on the device). This-//! reduces on the device and reads back 2 values instead of 262144 — no-//! 512 KB readback, no host scan. The full-logits path (Kotlin sampling)-//! is untouched — this serves greedy decoding only, which is what-//! `bridge_part6::argmax` does on the host.+//! One 64-lane workgroup grid-striding over 262,144 logits leaves the GPU idle: 64 lanes+//! each scan 4,096 values (~1.6 ms of a 24 ms NLLB decode step on a Pixel 8). Here up to+//! 64 workgroups (see `argmax_groups` in `nets`) each reduce a slice to the slice maximum,+//! and `argmax_fold.comp` folds the partials to the winning index. Same `[lo, hi]` fp16+//! output contract, same lowest-index tie-break. //! //! # How //!-//! 64 lanes grid-stride over `p.count` logits (the concatenated head splits,-//! vocab-wide). Each lane keeps its local (value, index) maximum; a shared-//! 64-entry reduction folds them; lane 0 stores the winner as TWO fp16-//! values: `lo = id % 2048`, `hi = id / 2048`. Both are exactly-//! representable (fp16 integers are exact to 2048; ids < 262144 give-//! hi < 128); the host reconstructs `hi * 2048 + lo`. A single fp16 slot-//! cannot hold the id either way: as a value it rounds past 2048, and as-//! bits `uintBitsToFloat` produces a denormal that `float16_t()` converts-//! (not bitcasts) to zero.-//!-//! Ties keep the FIRST index (strict `>`), matching the host loop's-//! `value > best.0`.+//! `p.group` is the workgroup count; workgroup `g` owns+//! `[g * slice, min((g + 1) * slice, p.count))` with `slice = ceil(count / groups)`.+//! 64 lanes grid-stride within the slice, each keeping its local (value, index) maximum+//! with strict `>` (first index wins); a shared 64-entry reduction folds them with the+//! same tie-break lane 0 of the single-stage shader used (equal values compare indices).+//! Lane 0 stores `(value, lo = id % 2048, hi = id / 2048)` — both exactly representable,+//! like the final pair. `PER_LANE` must equal `ARGMAX_PER_LANE` in `nets`. #include "common.glsl"+#define PER_LANE 64u shared uint best_idx[64]; shared float best_val[64]; void main() {     uint lane = gl_LocalInvocationID.x;-    uint lanes = 64u;-    // Grid-stride over the row: with one workgroup this is one pass.+    uint group = gl_WorkGroupID.x;+    uint groups = max(p.group, 1u);+    uint slice = (p.count + groups - 1u) / groups;+    uint first = group * slice;+    uint end = min(first + slice, p.count);+    // Grid-stride within this workgroup's slice: with one workgroup this is one pass.     float mine_val = -65504.0;     uint mine_idx = 0u;-    for (uint i = lane; i < p.count; i += lanes) {+    uint lanes = 64u;+    for (uint i = first + lane; i < end; i += lanes) {         float v = float(arena[p.in0 + i]);         if (v > mine_val) {             mine_val = v;@@ -43,9 +43,10 @@ void main() {     best_val[lane] = mine_val;     best_idx[lane] = mine_idx;     barrier();-    // Lane 0 folds the 64 lane-maxima. Each lane holds its own first index, but lanes interleave,-    // so an equal value from a later lane can still be the earlier index - the tie compares-    // indices, which is what keeps the FIRST index globally, matching the host `argmax` loop.+    // Lane 0 folds the 64 lane-maxima. Each lane holds its own first index, but lanes+    // interleave, so an equal value from a later lane can still be the earlier index - the+    // tie compares indices, which is what keeps the FIRST index globally, matching the+    // host `argmax` loop.     if (lane == 0u) {         float top_val = best_val[0];         uint top_idx = best_idx[0];@@ -55,7 +56,8 @@ void main() {                 top_idx = best_idx[l];             }         }-        arena[p.out_at] = float16_t(float(top_idx % 2048u));-        arena[p.out_at + 1u] = float16_t(float(top_idx / 2048u));+        arena[p.out_at + group * 3u] = float16_t(top_val);+        arena[p.out_at + group * 3u + 1u] = float16_t(float(top_idx % 2048u));+        arena[p.out_at + group * 3u + 2u] = float16_t(float(top_idx / 2048u));     } }
library/ml/src/main/rust/shaders/argmax_fold.comp
diff --git a/library/ml/src/main/rust/shaders/argmax_fold.comp b/library/ml/src/main/rust/shaders/argmax_fold.compnew file mode 100644index 0000000000..0c5e4d5da6--- /dev/null+++ b/library/ml/src/main/rust/shaders/argmax_fold.comp@@ -0,0 +1,43 @@+#version 450+//! Greedy argmax over a logits row, second stage: fold `argmax.comp`'s partials.+//!+//! One workgroup reads the `p.in_c` triples `(value, lo, hi)` the first stage wrote and+//! stores the winner as TWO fp16 values: `lo = id % 2048`, `hi = id / 2048`. Both are+//! exactly representable (fp16 integers are exact to 2048; ids < 262144 give hi < 128);+//! the host reconstructs `hi * 2048 + lo`.+//!+//! Ties keep the FIRST index (strict `>` with an index comparison on equality),+//! matching the host loop's `value > best.0` and the first stage's own tie-break.+#include "common.glsl"+shared uint best_idx[64];+shared float best_val[64];+void main() {+    uint lane = gl_LocalInvocationID.x;+    uint groups = max(p.in_c, 1u);+    // Grid-stride over the triples: one workgroup covers all 64 at most, usually fewer.+    float mine_val = -65504.0;+    uint mine_idx = 0u;+    for (uint g = lane; g < groups; g += 64u) {+        float v = float(arena[p.in0 + g * 3u]);+        uint idx = uint(float(arena[p.in0 + g * 3u + 1u])) + 2048u * uint(float(arena[p.in0 + g * 3u + 2u]));+        if (v > mine_val || (v == mine_val && idx < mine_idx)) {+            mine_val = v;+            mine_idx = idx;+        }+    }+    best_val[lane] = mine_val;+    best_idx[lane] = mine_idx;+    barrier();+    if (lane == 0u) {+        float top_val = best_val[0];+        uint top_idx = best_idx[0];+        for (uint l = 1u; l < 64u; l++) {+            if (best_val[l] > top_val || (best_val[l] == top_val && best_idx[l] < top_idx)) {+                top_val = best_val[l];+                top_idx = best_idx[l];+            }+        }+        arena[p.out_at] = float16_t(float(top_idx % 2048u));+        arena[p.out_at + 1u] = float16_t(float(top_idx / 2048u));+    }+}
library/ml/src/main/rust/src/nets/madlad_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_extra.rs b/library/ml/src/main/rust/src/nets/madlad_extra.rsindex 38c0fa29cd..864a9f8993 100644--- a/library/ml/src/main/rust/src/nets/madlad_extra.rs+++ b/library/ml/src/main/rust/src/nets/madlad_extra.rs@@ -306,7 +306,7 @@ mod tests {     #[test]     fn the_head_is_four_even_splits_over_disjoint_class_ranges() {         // Together the four splits are the whole vocabulary, which the device argmax reduces-        // over in one pass. Even splits: 256,000 = 4 x 64,000.+        // over in two stages. Even splits: 256,000 = 4 x 64,000.         let source = Shapes::new(TENSORS);         let plan = build(&source, Mode::DecodeStep { src_len: LEN })             .expect("the step builds");@@ -319,6 +319,14 @@ mod tests {             })             .collect();         assert_eq!(argmax, vec![VOCAB]);+        // And the fold over the partials is there exactly once.+        assert_eq!(+            plan.ops+                .iter()+                .filter(|op| matches!(op, Op::Dispatch { kind: Kind::ArgmaxFold, .. }))+                .count(),+            1+        );         assert_eq!(split_classes(0) * HEAD_SPLITS as u32, VOCAB);     } 
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex ac52cd306c..233770fe3f 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -330,7 +330,17 @@ pub enum Kind {     /// a token; this reduces on the device and reads back one value instead     /// of 512 KB of logits. See `shaders/argmax.comp`. The full-logits path     /// (Kotlin sampling) is untouched — this serves greedy decoding only.+    ///+    /// The first of two stages: many workgroups each reduce a slice of the row to a+    /// `(value, lo, hi)` partial, and [`Kind::ArgmaxFold`] folds the partials to the+    /// winning index. See [`Builder::argmax`].     Argmax,+    /// Fold [`Kind::Argmax`]'s partials to the winning index as two fp16 lanes.+    ///+    /// Reads the `(value, lo, hi)` triples the first stage wrote and stores+    /// `lo = id % 2048`, `hi = id / 2048`, keeping the FIRST index on ties.+    /// See `shaders/argmax_fold.comp`.+    ArgmaxFold,     /// An [`Act`] applied on its own, for a value no convolution produced. See     /// `shaders/activate.comp`.     ///
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 cfb760bb0d..4c46c74353 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -330,6 +330,7 @@ impl Kind {             | Kind::Softcap             | Kind::Quantize             | Kind::Argmax+            | Kind::ArgmaxFold             | Kind::GatedActivate => {}             // A scalar (`mul_scalar`) or a low/high pair (`clamp`) at `act_weight`.             Kind::MulScalar | Kind::Clamp => {@@ -417,6 +418,10 @@ impl Kind {             // One id per position per lane, so the read is `in_c * out_w` and not `dense` -             // `in_w` here is the *table's* row count.             Kind::Embed => one(push.in0, push.in_c * push.out_w),+            // The whole logits row, whatever the group count. See `Builder::argmax`.+            Kind::Argmax => one(push.in0, dense),+            // One `(value, lo, hi)` triple per group: `in_c` carries the group count.+            Kind::ArgmaxFold => one(push.in0, push.in_c * 3),             // One row in. Not `dense`: `in_h` here is the cache's capacity, not a spatial extent.             Kind::CacheWrite => one(push.in0, push.count),             // Convolutions, whose store may also add a folded residual and a folded@@ -461,7 +466,6 @@ impl Kind {             | Kind::Activate             | Kind::GatedActivate             | Kind::MulScalar-            | Kind::Argmax             | Kind::Clamp => one(push.in0, dense),             // As above, plus a folded residual addend (see `Push::res`): the             // post-norm `add(x, branch)` the fusion moved into this store.
library/ml/src/main/rust/src/nets/mod_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part10.rs b/library/ml/src/main/rust/src/nets/mod_part10.rsindex 2483d76f1d..e141f6e2e3 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -28,7 +28,8 @@ impl Node {             | Node::ConcatPositions { out, .. }             | Node::Concat { out, .. } => *out,             | Node::Softcap { out, .. } => *out,-            | Node::Argmax { out, .. } => *out,+            | Node::Argmax { out, .. }+            | Node::ArgmaxFold { out, .. } => *out,             | Node::Quantize { out, .. } => *out,             | Node::Activate { out, .. }             | Node::GatedActivate { out, .. } => *out,@@ -63,6 +64,7 @@ impl Node {             | Node::Softmax { input, .. }             | Node::Softcap { input, .. }             | Node::Argmax { input, .. }+            | Node::ArgmaxFold { input, .. }             | Node::Quantize { input, .. }             | Node::GatedActivate { input, .. }             | Node::Activate { input, .. }
library/ml/src/main/rust/src/nets/mod_part11.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part11.rs b/library/ml/src/main/rust/src/nets/mod_part11.rsindex 044ece26ef..a49bce5429 100644--- a/library/ml/src/main/rust/src/nets/mod_part11.rs+++ b/library/ml/src/main/rust/src/nets/mod_part11.rs@@ -51,6 +51,34 @@ pub(crate) mod tests {             "the Q2_K gemv shader and Rust disagree on channels per workgroup"         );     }++    /// `ARGMAX_PER_LANE` must equal `PER_LANE` in the argmax partials shader, and the+    /// group counts must put NLLB's and MADLAD's vocabularies in the multi-workgroup+    /// regime with room to spare.+    #[test]+    fn the_argmax_geometry_matches_its_shader() {+        let path =+            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders").join("argmax.comp");+        let source = std::fs::read_to_string(&path).expect("the argmax shader reads");+        let per_lane = source+            .lines()+            .find_map(|line| {+                line.trim_start().strip_prefix("#define PER_LANE").and_then(|rest| {+                    rest.trim().trim_end_matches('u').parse::<u32>().ok()+                })+            })+            .unwrap_or_else(|| panic!("argmax.comp declares no PER_LANE"));+        assert_eq!(per_lane, ARGMAX_PER_LANE);+        // One lane's share at full occupancy: 64 lanes x 64 groups x PER_LANE.+        assert_eq!(64 * 64 * ARGMAX_PER_LANE, 262_144);+        // Both shipping vocabularies reduce over dozens of groups, not one.+        assert_eq!(argmax_groups(256_206), 63);+        assert_eq!(argmax_groups(256_000), 63);+        // Ragged and small rows still dispatch at least one workgroup.+        assert_eq!(argmax_groups(262_143), 64);+        assert_eq!(argmax_groups(1_000), 1);+        assert_eq!(argmax_groups(0), 1);+    }     /// `CONV_POINT_INT8_TILE` must equal `TILE` in the int8 tiled shader.     ///     /// Rust dispatches one workgroup per `TILE x TILE` block and the shader owns that block, so a
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex dcda3e8944..ad8cabebdc 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -328,10 +328,18 @@ pub(crate) enum Node {     },     /// The argmax of a logits row: the winning index as two fp16 lanes     /// (`lo = id % 2048`, `hi = id / 2048`). See [`Kind::Argmax`].+    ///+    /// The first of the two stages [`Builder::argmax`] emits: `out` holds one+    /// `(value, lo, hi)` triple per workgroup, which [`Node::ArgmaxFold`] folds.     Argmax {         input: Id,         out: Id,     },+    /// Fold [`Node::Argmax`]'s partials to the winning index. See [`Kind::ArgmaxFold`].+    ArgmaxFold {+        input: Id,+        out: Id,+    },     /// `clamp(round(x / scale), -128, 127) * scale`. See [`Kind::Quantize`].     Quantize {         input: Id,
library/ml/src/main/rust/src/nets/mod_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part3.rs b/library/ml/src/main/rust/src/nets/mod_part3.rsindex 9ece7ecbb6..92e79a03ed 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -69,6 +69,22 @@ const ROW_REDUCE_MIN_LEN: u32 = 64; /// Invocations per workgroup: `local_size_x` in `shaders/common.glsl`. const ROW_REDUCE_LANES: u32 = 64; +/// Logits each lane of [`Builder::argmax`]'s first stage scans per pass.+///+/// 64 lanes × 64 workgroups × this many cover 262,144 logits at one element per+/// lane per iteration. Larger keeps the fold's partial count down; smaller wastes+/// less on ragged tails. **Must equal `PER_LANE` in `shaders/argmax.comp`.**+const ARGMAX_PER_LANE: u32 = 64;++/// Workgroups [`Builder::argmax`]'s first stage reduces a row of `count` logits with.+///+/// Enough that every lane has work (`PER_LANE` each), capped so the fold's partials+/// fit one workgroup's 64 lanes. The device and the host interpreter share this, so+/// the group boundaries — and therefore the tie-breaks — agree by construction.+pub(crate) fn argmax_groups(count: u32) -> u32 {+    count.div_ceil(ROW_REDUCE_LANES * ARGMAX_PER_LANE).clamp(1, ROW_REDUCE_LANES)+}+ /// Whether `rows` rows of `len` elements reduce one workgroup per row, as /// `(Push::kw, invocations)`. fn row_reduce(rows: u32, len: u32) -> (u32, u32) {
library/ml/src/main/rust/src/nets/mod_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6.rs b/library/ml/src/main/rust/src/nets/mod_part6.rsindex 454dcbc3d2..a914ca7476 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -245,9 +245,17 @@ impl<'a> Builder<'a> {     /// neither the value nor the bits past id 2048). The host reconstructs     /// `hi * 2048 + lo`. Ties keep the FIRST index (strict `>` in the     /// shader), matching the host `argmax` loop.+    ///+    /// Two dispatches: [`Node::Argmax`] reduces the row to one `(value, lo, hi)`+    /// triple per workgroup (see [`argmax_groups`]), then [`Node::ArgmaxFold`]+    /// folds the triples. One workgroup over 262k logits leaves the GPU idle;+    /// 63 workgroups do not.     pub fn argmax(&mut self, input: Id) -> Id {+        let groups = argmax_groups(self.shape_of(input).len());+        let partials = self.tensor(Shape::new(groups * 3, 1, 1));+        self.nodes.push(Node::Argmax { input, out: partials });         let out = self.tensor(Shape::new(2, 1, 1));-        self.nodes.push(Node::Argmax { input, out });+        self.nodes.push(Node::ArgmaxFold { input: partials, out });         out     } 
library/ml/src/main/rust/src/nets/mod_part9b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9b.rs b/library/ml/src/main/rust/src/nets/mod_part9b.rsindex 1b7942cf98..1171ea9ec6 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -294,8 +294,14 @@ impl<'a> Builder<'a> {             }             Node::Argmax { input, out } => {                 let si = shape(*input);-                // One scalar out: the winning index as fp16 bits. The input-                // is the concatenated logits row (all chunks, vocab-wide).+                let so = shape(*out);+                // One `(value, lo, hi)` triple per workgroup: the partials+                // [`Node::ArgmaxFold`] folds. Groups from the shared helper, so the+                // device and the host interpreter split the row identically.+                // (`mod_part9b.rs` is inlined into `crate::nets`, so the helper is+                // a bare name here, not `super::`.)+                let groups = argmax_groups(si.len()).max(1);+                // The input is the concatenated logits row (all chunks, vocab-wide).                 ops.push(Op::Dispatch {                     kind: Kind::Argmax,                     push: Push {@@ -304,13 +310,33 @@ impl<'a> Builder<'a> {                         in_c: si.c,                         in_h: si.h,                         in_w: si.w,-                        out_c: 1,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        group: groups,+                        count: si.len(),+                        ..Push::default()+                    },+                    // One workgroup of 64 per group.+                    invocations: groups * 64,+                });+            }+            Node::ArgmaxFold { input, out } => {+                let si = shape(*input);+                let groups = si.len() / 3;+                ops.push(Op::Dispatch {+                    kind: Kind::ArgmaxFold,+                    push: Push {+                        in0: at(*input)?,+                        out: at(*out)?,+                        in_c: groups,+                        out_c: 2,                         out_h: 1,                         out_w: 1,-                        count: si.len(),+                        count: groups,                         ..Push::default()                     },-                    // 64 lanes per workgroup, grid-stride over the row.+                    // One workgroup folds every triple.                     invocations: 64,                 });             }
library/ml/src/main/rust/src/nets/nllb_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra.rs b/library/ml/src/main/rust/src/nets/nllb_extra.rsindex d1ca2fc72f..c8752ab1df 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra.rs@@ -249,8 +249,9 @@ mod tests {         // Three residuals per layer — half of which fold into their producing         // convolution's store. See `Builder::add`.         assert_eq!(counts.get("Add"), Some(&18), "{counts:?}");-        // And the greedy pick, on the device.+        // And the greedy pick, on the device: the partials reduce plus the fold.         assert_eq!(counts.get("Argmax"), Some(&1), "{counts:?}");+        assert_eq!(counts.get("ArgmaxFold"), Some(&1), "{counts:?}");         assert_no_aliasing(&plan);     } @@ -380,7 +381,7 @@ mod tests {             .collect();         assert_eq!(heads, vec![64_052, 64_052, 64_051, 64_051]);         assert_eq!(heads.iter().sum::<u32>(), VOCAB);-        // The argmax runs over all of them at once, in id order.+        // The argmax runs over all of them at once, in id order, then folds the partials.         let argmax: Vec<_> = plan             .ops             .iter()@@ -390,6 +391,13 @@ mod tests {             })             .collect();         assert_eq!(argmax, vec![VOCAB]);+        assert_eq!(+            plan.ops+                .iter()+                .filter(|op| matches!(op, Op::Dispatch { kind: Kind::ArgmaxFold, .. }))+                .count(),+            1+        );     }      #[test]
library/ml/src/main/rust/src/nets/reference_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part1.rs b/library/ml/src/main/rust/src/nets/reference_part1.rsindex 95805ee246..2b0966dd19 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -67,6 +67,7 @@ impl Reference {                     Kind::CacheWrite => self.cache_write(push),                     Kind::Softcap => self.softcap(push),                     Kind::Argmax => self.argmax(push),+                    Kind::ArgmaxFold => self.argmax_fold(push),                     Kind::Quantize => self.quantize(push),                     Kind::Activate => self.activate(push),                     Kind::GatedActivate => self.gated_activate(push),
library/ml/src/main/rust/src/nets/reference_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part2.rs b/library/ml/src/main/rust/src/nets/reference_part2.rsindex dc1d135971..4d9675ef11 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -256,18 +256,50 @@ impl Reference {      /// The argmax of a logits row, as the host reads it back.     ///-    /// Mirrors `shaders/argmax.comp`: strict `>` over the row keeps the FIRST-    /// index on ties, stored as `lo = id % 2048`, `hi = id / 2048` fp16-    /// values. See `Builder::argmax`.+    /// The first of the two stages [`Builder::argmax`](super::Builder::argmax) emits,+    /// mirroring `shaders/argmax.comp`: the row splits into [`argmax_groups`](super::argmax_groups)+    /// slices and each workgroup keeps its slice's first maximum (strict `>`), stored+    /// as a `(value, lo, hi)` triple with `lo = id % 2048`, `hi = id / 2048`.+    /// See `Builder::argmax`.     fn argmax(&mut self, p: &Push) -> Result<(), String> {         let len = (p.in_c * p.in_h * p.in_w).max(1);+        let groups = super::argmax_groups(len).max(1);+        let slice = len.div_ceil(groups);+        for group in 0..groups {+            let mut top_val = f32::NEG_INFINITY;+            let mut top_idx = 0u32;+            let end = (group + 1) * slice;+            for i in group * slice..end.min(len) {+                let value = self.load(p.in0, i)?;+                if value > top_val {+                    top_val = value;+                    top_idx = i;+                }+            }+            let at = p.out + group * 3;+            self.store(at, 0, top_val)?;+            self.store(at, 1, (top_idx % 2048) as f32)?;+            self.store(at, 2, (top_idx / 2048) as f32)?;+        }+        Ok(())+    }++    /// Fold [`Reference::argmax`]'s partials to the winning index.+    ///+    /// Mirrors `shaders/argmax_fold.comp`: the greatest value wins, ties keep the+    /// FIRST index, stored as `lo = id % 2048`, `hi = id / 2048` fp16 values.+    /// See `Builder::argmax`.+    fn argmax_fold(&mut self, p: &Push) -> Result<(), String> {+        let groups = p.in_c.max(1);         let mut top_val = f32::NEG_INFINITY;         let mut top_idx = 0u32;-        for i in 0..len {-            let value = self.load(p.in0, i)?;-            if value > top_val {+        for group in 0..groups {+            let at = p.in0 + group * 3;+            let value = self.load(at, 0)?;+            let index = self.load(at, 1)? as u32 + 2048 * self.load(at, 2)? as u32;+            if value > top_val || (value == top_val && index < top_idx) {                 top_val = value;-                top_idx = i;+                top_idx = index;             }         }         self.store(p.out, 0, (top_idx % 2048) as f32)?;
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 6101c11606..2cf4cb918d 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part8.rs@@ -87,3 +87,47 @@ fn a_net_uploads_only_the_window_its_plan_reads() {     both.rebuild(early).expect("the covered plan installs");     matches("a covering net rebuilt", &host_early, &both.infer_raw(&input).expect("it runs")); }++/// A logits row at NLLB scale, with the peak tied across workgroup slices.+///+/// `count` logits of `spread` values with the maximum planted at `peaks`: the device must+/// report the FIRST peak whatever slice it falls in. The winners are also asserted as the+/// `[lo, hi]` pair the host reconstructs with `hi * 2048 + lo`.+fn argmax_fixture(count: usize, peaks: &[u32]) -> (Plan, Vec<u8>, Vec<f32>) {+    let mut logits = spread(count, 0.7);+    let peak = logits.iter().fold(f32::NEG_INFINITY, |top, &v| top.max(v)) + 1.0;+    for &at in peaks {+        logits[at as usize] = peak;+    }+    let source = Invented::new(0);+    let mut builder = Builder::new(&source);+    let row = builder.input(Shape::new(count as u32, 1, 1));+    let id = builder.argmax(row);+    let plan = builder.finish(&[id]).expect("the argmax plan builds");+    (plan, source.into_data(), logits)+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_two_stage_argmax_keeps_the_first_of_ties_across_slices() {+    // 262,144 = 64 groups of 4,096: the full multi-workgroup regime, with the peak tied+    // across the first slice boundary, a middle slice and the last element, plus a ragged+    // count and a small row that reduces in a single group. (No peak at index 0: the+    // `[0, 0]` answer that gives is indistinguishable from an unwritten tensor, which the+    // parity guard refuses.)+    for (count, peaks) in [+        (262_144usize, vec![4096u32, 131_073, 262_143]),+        (262_143usize, vec![7u32, 200_000]),+        (1_000usize, vec![999u32, 3]),+    ] {+        let (plan, data, logits) = argmax_fixture(count, &peaks);+        let want = peaks.iter().copied().min().expect("a peak");+        let host = run_multi(&plan, &data, &[&logits]).expect("the interpreter runs");+        let got = on_device(plan, data, &[&logits]);+        matches(&format!("a two-stage argmax over {count} logits"), &host, &got);+        let pair = got.into_iter().next().expect("one output");+        assert_eq!(pair.len(), 2, "the [lo, hi] pair");+        let id = pair[1] as u32 * 2048 + pair[0] as u32;+        assert_eq!(id, want, "the first peak of {count} logits");+    }+}
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 15dd37f1d9..db4cb69045 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -87,10 +87,11 @@ const CONV_POINT_INT4: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_int4.comp.spv")); const CONV_VEC_Q2K: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_q2k.comp.spv")); const ARGMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax.comp.spv"));+const ARGMAX_FOLD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax_fold.comp.spv")); /// Every shader, in the order `Shaders::create` destructures them (the Q2_K pair, /// `QUANTIZE`, and the `compute_pipeline` / `shader_module` helpers live in /// `pipeline_extra.rs` for length).-pub(crate) const SPIRV: [&[u8]; 46] = [+pub(crate) const SPIRV: [&[u8]; 47] = [     CONV,     CONV_TRANSPOSE,     MAXPOOL,@@ -137,6 +138,7 @@ pub(crate) const SPIRV: [&[u8]; 46] = [     CONV_Q2K,     QUANTIZE,     ARGMAX,+    ARGMAX_FOLD, ];  /// Descriptors in one set: the arena, the weights as fp16, the weights as words, the step params.@@ -217,6 +219,7 @@ pub struct Shaders {     pub(crate) rmsnorm: vk::Pipeline,     pub(crate) quantize: vk::Pipeline,     pub(crate) argmax: vk::Pipeline,+    pub(crate) argmax_fold: vk::Pipeline, }  /// One net's descriptor sets, over the device-wide [`Shaders`].
library/ml/src/main/rust/src/vulkan/pipeline_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rsindex e3ba1ea032..91f7d8d136 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs@@ -168,6 +168,7 @@ impl Shaders {             conv_q2k,             quantize,             argmax,+            argmax_fold,         ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) {             Ok(all) => all,             Err(built) => {@@ -228,6 +229,7 @@ impl Shaders {             conv_q2k,             quantize,             argmax,+            argmax_fold,         })     } @@ -280,6 +282,7 @@ impl Shaders {             Kind::Rotary => self.rotary,             Kind::Quantize => self.quantize,             Kind::Argmax => self.argmax,+            Kind::ArgmaxFold => self.argmax_fold,         }     } @@ -333,6 +336,7 @@ impl Shaders {             self.clamp,             self.quantize,             self.argmax,+            self.argmax_fold,         ] {             device.destroy_pipeline(pipeline, None);         }