Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / argmax_fold.comp
argmax_fold.comp48 lines · 2.2 KiBRaw
| 1 | #version 450 |
| 2 | //! Greedy argmax over a logits row, second stage: re-read the candidates, keep the greatest. |
| 3 | //! |
| 4 | //! One workgroup reads the `p.in_c` candidate indices (`lo + 2048 * hi` pairs) the first |
| 5 | //! stage wrote, loads each candidate's logit from the row at `p.in1` in fp32, and stores |
| 6 | //! the winner as TWO fp16 values: `lo = id % 2048`, `hi = id / 2048`. Both are exactly |
| 7 | //! representable (fp16 integers are exact to 2048; ids < 262144 give hi < 128); the host |
| 8 | //! reconstructs `hi * 2048 + lo`. |
| 9 | //! |
| 10 | //! Re-reading rather than comparing stored values is what keeps near-ties exact: a value |
| 11 | //! the fp16 store would round is compared here at the fp32 the row holds, with strict `>` |
| 12 | //! so ties keep the FIRST index — exactly the single-stage scan, whatever the slices were. |
| 13 | #include "common.glsl" |
| 14 | shared uint best_idx[64]; |
| 15 | shared float best_val[64]; |
| 16 | void main() { |
| 17 | uint lane = gl_LocalInvocationID.x; |
| 18 | uint groups = max(p.in_c, 1u); |
| 19 | // Grid-stride over the candidates: one workgroup covers all 64 at most, usually fewer. |
| 20 | // `p.in1` is the logits row; `p.in0` the candidate pairs. Lanes with no candidate keep |
| 21 | // (-65504, 0), which only wins an all-minimum row whose answer is index 0 anyway. |
| 22 | float mine_val = -65504.0; |
| 23 | uint mine_idx = 0u; |
| 24 | for (uint g = lane; g < groups; g += 64u) { |
| 25 | uint idx = uint(float(arena[p.in0 + g * 2u])) + 2048u * uint(float(arena[p.in0 + g * 2u + 1u])); |
| 26 | float v = float(arena[p.in1 + idx]); |
| 27 | if (v > mine_val) { |
| 28 | mine_val = v; |
| 29 | mine_idx = idx; |
| 30 | } |
| 31 | } |
| 32 | best_val[lane] = mine_val; |
| 33 | best_idx[lane] = mine_idx; |
| 34 | barrier(); |
| 35 | // Lane 0 folds the 64 lane-maxima with the same first-index tie-break as the row scan. |
| 36 | if (lane == 0u) { |
| 37 | float top_val = best_val[0]; |
| 38 | uint top_idx = best_idx[0]; |
| 39 | for (uint l = 1u; l < 64u; l++) { |
| 40 | if (best_val[l] > top_val || (best_val[l] == top_val && best_idx[l] < top_idx)) { |
| 41 | top_val = best_val[l]; |
| 42 | top_idx = best_idx[l]; |
| 43 | } |
| 44 | } |
| 45 | arena[p.out_at] = float16_t(float(top_idx % 2048u)); |
| 46 | arena[p.out_at + 1u] = float16_t(float(top_idx / 2048u)); |
| 47 | } |
| 48 | } |