#version 450 //! 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 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 //! //! `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 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]; shared float best_val[64]; void main() { uint lane = gl_LocalInvocationID.x; 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; 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; mine_idx = i; } } 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. 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 + group * 2u] = float16_t(float(top_idx % 2048u)); arena[p.out_at + group * 2u + 1u] = float16_t(float(top_idx / 2048u)); } }