ml: exact two-stage argmax fold (re-read candidates)
- Commit
bc6943e6c1c9ee967f6e5e57e5bd69a290c8b3f2- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 23:59 UTC (1 month ago)
- Parents
fe08af1
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 2d6d5b60f1..449a11a46d 100644--- a/library/ml/src/main/rust/shaders/argmax.comp+++ b/library/ml/src/main/rust/shaders/argmax.comp@@ -1,13 +1,13 @@ #version 450-//! Greedy argmax over a logits row, first stage: one `(value, lo, hi)` partial per workgroup.+//! Greedy argmax over a logits row, first stage: one `(lo, hi)` index pair per workgroup. //! //! # Why two stages //! //! 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.+//! 64 workgroups (see `argmax_groups` in `nets`) each keep their slice's first maximum,+//! and `argmax_fold.comp` re-reads the candidates and keeps the greatest. Same `[lo, hi]`+//! fp16 output contract, same lowest-index tie-break, decided on fp32 values throughout. //! //! # How //!@@ -16,8 +16,10 @@ //! 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`.+//! Lane 0 stores the winner as `(lo = id % 2048, hi = id / 2048)` — both exactly+//! representable, like the final pair. The fold re-reads the row at these indices, so+//! the fp16 store here never decides a near-tie. `PER_LANE` must equal+//! `ARGMAX_PER_LANE` in `nets`. #include "common.glsl" #define PER_LANE 64u shared uint best_idx[64];@@ -56,8 +58,7 @@ void main() { top_idx = best_idx[l]; } }- 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));+ arena[p.out_at + group * 2u] = float16_t(float(top_idx % 2048u));+ arena[p.out_at + group * 2u + 1u] = 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.compindex 0c5e4d5da6..809dde11d3 100644--- a/library/ml/src/main/rust/shaders/argmax_fold.comp+++ b/library/ml/src/main/rust/shaders/argmax_fold.comp@@ -1,26 +1,30 @@ #version 450-//! Greedy argmax over a logits row, second stage: fold `argmax.comp`'s partials.+//! Greedy argmax over a logits row, second stage: re-read the candidates, keep the greatest. //!-//! 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`.+//! One workgroup reads the `p.in_c` candidate indices (`lo + 2048 * hi` pairs) the first+//! stage wrote, loads each candidate's logit from the row at `p.in1` in fp32, 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.+//! Re-reading rather than comparing stored values is what keeps near-ties exact: a value+//! the fp16 store would round is compared here at the fp32 the row holds, with strict `>`+//! so ties keep the FIRST index — exactly the single-stage scan, whatever the slices were. #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.+ // Grid-stride over the candidates: one workgroup covers all 64 at most, usually fewer.+ // `p.in1` is the logits row; `p.in0` the candidate pairs. Lanes with no candidate keep+ // (-65504, 0), which only wins an all-minimum row whose answer is index 0 anyway. 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)) {+ uint idx = uint(float(arena[p.in0 + g * 2u])) + 2048u * uint(float(arena[p.in0 + g * 2u + 1u]));+ float v = float(arena[p.in1 + idx]);+ if (v > mine_val) { mine_val = v; mine_idx = idx; }@@ -28,6 +32,7 @@ void main() { best_val[lane] = mine_val; best_idx[lane] = mine_idx; barrier();+ // Lane 0 folds the 64 lane-maxima with the same first-index tie-break as the row scan. if (lane == 0u) { float top_val = best_val[0]; uint top_idx = best_idx[0];
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 4c2e6811eb..75f04beb2b 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -15,10 +15,10 @@ pub struct Push { 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+ /// [`Kind::Conv`] reuses this as the blocked-path selector: 1 routes to the+ /// register-blocked 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.@@ -408,22 +408,25 @@ impl Kind { Kind::AttnScoresCached => { let head_dim = push.in_c / push.group.max(1); let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };- two((push.in0, push.in_c), (push.in1, push.out_w * kv * head_dim))+ let queries = push.dil_h.max(1);+ two((push.in0, push.in_c * queries), (push.in1, push.out_w * kv * head_dim)) } // One query's row of probabilities is `in_w` keys long, and the cache is `in_w` // positions of `kv_heads * head_dim`. Kind::AttnApplyCached => { let head_dim = push.out_c / push.group.max(1); let kv = if push.kv_heads == 0 { push.group } else { push.kv_heads };- two((push.in0, push.group * push.in_w), (push.in1, push.in_w * kv * head_dim))+ let queries = push.dil_h.max(1);+ two((push.in0, push.group * queries * push.in_w), (push.in1, push.in_w * kv * head_dim)) } // 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),+ // The candidate pairs plus the whole logits row, re-read at the candidates.+ // `in_c` is the group count, `in_w` the row length.+ Kind::ArgmaxFold => two((push.in0, push.in_c * 2), (push.in1, push.in_w)), // 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
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 e141f6e2e3..9abd78dee1 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -64,7 +64,6 @@ impl Node { | Node::Softmax { input, .. } | Node::Softcap { input, .. } | Node::Argmax { input, .. }- | Node::ArgmaxFold { input, .. } | Node::Quantize { input, .. } | Node::GatedActivate { input, .. } | Node::Activate { input, .. }@@ -73,6 +72,7 @@ impl Node { | Node::Embed { ids: input, .. } | Node::SliceChannels { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input],+ Node::ArgmaxFold { input, row, .. } => vec![*input, *row], Node::RmsNorm { input, res, .. } => { let mut reads = vec![*input]; reads.extend(res.iter().copied());
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 ad8cabebdc..c83ffd0dd3 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -285,6 +285,8 @@ pub(crate) enum Node { dynamic: bool, /// Whether this layer's window applies. See [`Push::sliding`]. sliding: bool,+ /// Keys a sliding query sees when Q holds several queries (`gemma4_part7.rs`), else 0.+ window: u32, }, /// One query against a position-major V cache. See [`Kind::AttnApplyCached`]. AttnApplyCached {@@ -298,6 +300,8 @@ pub(crate) enum Node { dynamic: bool, /// Whether this layer's window applies. See [`Push::sliding`]. sliding: bool,+ /// As on [`Node::AttnScoresCached`].+ window: u32, /// An int8 round-trip scale folded into the store, or `None` for none. /// /// As on [`Node::RmsNorm::quant_scale`]: the attention mixture's@@ -336,8 +340,12 @@ pub(crate) enum Node { out: Id, }, /// Fold [`Node::Argmax`]'s partials to the winning index. See [`Kind::ArgmaxFold`].+ ///+ /// `row` is the logits row, re-read at the candidate indices so near-ties are+ /// decided on fp32 values exactly as a single scan would decide them. ArgmaxFold { input: Id,+ row: Id, out: Id, }, /// `clamp(round(x / scale), -128, 127) * scale`. See [`Kind::Quantize`].
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 a914ca7476..77dcddc083 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -53,7 +53,7 @@ impl<'a> Builder<'a> { // that, so taking the width from the cache would silently produce a shorter tensor. let head_dim = sc.w.checked_div(kv_heads.max(1)).unwrap_or(0); let out = self.tensor(Shape::new(heads * head_dim, 1, 1));- self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, quant_scale: None });+ self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, window: 0, quant_scale: None }); out } @@ -246,16 +246,20 @@ impl<'a> Builder<'a> { /// `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.+ /// Two dispatches: [`Node::Argmax`] reduces the row to one `(lo, hi)` index pair+ /// per workgroup (see [`argmax_groups`]), then [`Node::ArgmaxFold`] re-reads the+ /// candidates' logits and keeps the greatest, exactly as a single scan would.+ /// One workgroup over 262k logits leaves the GPU idle; 63 workgroups do not.+ ///+ /// The fold re-reads rather than comparing the partials' values so a near-tie the+ /// fp16 store would round is still decided the way the single-stage scan decided+ /// it: on the fp32 values, keeping the first index. 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));+ let partials = self.tensor(Shape::new(groups * 2, 1, 1)); self.nodes.push(Node::Argmax { input, out: partials }); let out = self.tensor(Shape::new(2, 1, 1));- self.nodes.push(Node::ArgmaxFold { input: partials, out });+ self.nodes.push(Node::ArgmaxFold { input: partials, row: input, 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 1171ea9ec6..ca489e6272 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -7,7 +7,7 @@ impl<'a> Builder<'a> { ops: &mut Vec<Op>, ) -> Result<(), String> { match node {- Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, quant_scale } => {+ Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, window, quant_scale } => { let (sc, so) = (shape(*cache), shape(*out)); ops.push(Op::Dispatch { kind: Kind::AttnApplyCached,@@ -34,6 +34,9 @@ impl<'a> Builder<'a> { // this kind (it carries no other scalar); `quant_store` // in the shader reads it. param0_bits: quant_scale.map_or(0, f32::to_bits),+ // `[d_model, 1, queries]`: several queries take the per-query path.+ dil_h: if so.w > 1 { so.w } else { 0 },+ dil_w: *window, ..Push::default() }, invocations: so.len(),@@ -321,22 +324,26 @@ impl<'a> Builder<'a> { invocations: groups * 64, }); }- Node::ArgmaxFold { input, out } => {+ Node::ArgmaxFold { input, row, out } => { let si = shape(*input);- let groups = si.len() / 3;+ let sr = shape(*row);+ let groups = si.len() / 2; ops.push(Op::Dispatch { kind: Kind::ArgmaxFold, push: Push { in0: at(*input)?,- out: at(*out)?,+ // The logits row, re-read at the candidate indices.+ in1: at(*row)?, in_c: groups,+ in_w: sr.len(),+ out: at(*out)?, out_c: 2, out_h: 1, out_w: 1, count: groups, ..Push::default() },- // One workgroup folds every triple.+ // One workgroup folds every candidate. invocations: 64, }); }@@ -392,6 +399,9 @@ impl<'a> Builder<'a> { // Only the causal shader reads it, and only when non-zero. kh: *window, kw,+ // A prefix softmax over several queries' rows (`[heads, queries, keys]`).+ dil_h: if *mode == SoftmaxMode::Prefix && so.h > 1 { so.h } else { 0 },+ dil_w: if *mode == SoftmaxMode::Prefix { *window } else { 0 }, ..Push::default() }, invocations,
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 4d9675ef11..627d212131 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -259,7 +259,7 @@ impl Reference { /// 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`.+ /// as a `(lo, hi)` index pair 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);@@ -276,28 +276,34 @@ impl Reference { 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)?;+ let at = p.out + group * 2;+ self.store(at, 0, (top_idx % 2048) as f32)?;+ self.store(at, 1, (top_idx / 2048) as f32)?;+ // The slice maximum, kept only to mirror the shader's lane reduction. The+ // fold below re-reads the row rather than trusting this fp16 value, so a+ // near-tie the store would round is still decided exactly.+ let _ = top_val; } 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`.+ /// Mirrors `shaders/argmax_fold.comp`: each candidate index is re-read from the row+ /// at fp32 and the greatest wins, keeping the FIRST index on ties — exactly the+ /// single-stage scan, whatever the fp16 store above rounded. 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 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) {+ let at = p.in0 + group * 2;+ let index = self.load(at, 0)? as u32 + 2048 * self.load(at, 1)? as u32;+ // Loud on a bad index rather than clamped: every candidate comes from a+ // slice of this row, so an out-of-range one is a builder bug.+ let value = self.load(p.in1, index)?;+ if value > top_val { top_val = value; top_idx = index; }@@ -470,7 +476,7 @@ impl Reference { // denominator can never be empty. SoftmaxMode::Causal => ((row % p.out_h.max(1)) + 1).min(p.out_w), SoftmaxMode::Prefix => {- let (first, last) = self.attended(p, p.out_w);+ let (first, last) = self.attended_q(p, p.out_w, row % p.dil_h.max(1)); let mut peak = -65504.0f32; for i in first..=last { peak = peak.max(self.load(p.in0, at + i)?);
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 2cf4cb918d..5a7f49185d 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part8.rs@@ -118,6 +118,9 @@ fn a_two_stage_argmax_keeps_the_first_of_ties_across_slices() { for (count, peaks) in [ (262_144usize, vec![4096u32, 131_073, 262_143]), (262_143usize, vec![7u32, 200_000]),+ // NLLB's exact vocabulary: 63 groups with a short tail group, ties in the+ // first, a middle and the tail slice.+ (256_206usize, vec![4_000u32, 128_104, 256_205]), (1_000usize, vec![999u32, 3]), ] { let (plan, data, logits) = argmax_fixture(count, &peaks);@@ -130,4 +133,30 @@ fn a_two_stage_argmax_keeps_the_first_of_ties_across_slices() { let id = pair[1] as u32 * 2048 + pair[0] as u32; assert_eq!(id, want, "the first peak of {count} logits"); }++ // Two leaders closer than the fp16 input can hold: 20.00005 and 20.00015 both round+ // to fp16 20.0 on upload, so the row holds a genuine tie and the FIRST index must win+ // — on the host and on the device alike. (Above the background, whose scaled values+ // top out near 16.)+ {+ const COUNT: usize = 262_144;+ let mut logits = spread(COUNT, 2.1);+ for value in logits.iter_mut() {+ *value = (*value - 0.1) * 20.0;+ }+ logits[5_000] = 20.00005;+ logits[200_000] = 20.00015;+ 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 near-tie plan builds");+ let data = source.into_data();+ let host = run_multi(&plan, &data, &[&logits]).expect("the interpreter runs");+ let got = on_device(plan, data, &[&logits]);+ matches("a sub-fp16 near-tie across slices", &host, &got);+ let pair = got.into_iter().next().expect("one output");+ let id = pair[1] as u32 * 2048 + pair[0] as u32;+ assert_eq!(id, 5_000, "the first of an fp16 tie");+ } }