Repository navigation
ggml-hrx: TOP_K on HRX, a radix select for the QSA indexer (engine #679) - #161
Conversation
…ml-org#679) GGML_OP_TOP_K had no HRX dispatch, so the node ran on the CPU backend and split every full-attention layer's graph around it. Qwen3.8-Flash-Next is the model that pays for it: its QSA layers (src/models/qwen4exp.cpp) call ggml_top_k with n = n_kv (up to 262144) and k = indexer_top_k + r - 1 = 2051, once per full-attention layer per decode step, and the CPU side is a single-row std::partial_sort with an indirect comparator plus a host round trip. Measured on strixhalo (gfx1151), same server, same prompt family, one process: - decode steps 39.2 -> 49.0 ms the moment n_kv crossed 2051 (1986 vs 2096 tokens), i.e. +9.7 ms per step for entering the QSA path at all; - then ~3.8 us per KV token per step (49.0 ms at 2096 -> 67.4 ms at 6978), which extrapolates to 112 ms/step at 18,782 tokens against the 103 ms a full protocol run measured there (9.70 tok/s vs 31.15 for a build whose TOP_K is on the GPU); - forcing the same path below the threshold (LLAMA_QSA_DENSE=0) at fixed n_kv=1480 costs 13x prefill (676 -> 52 tok/s), which is the selection path itself. The kernel is a radix select on a monotone uint32 key map of the f32 bit pattern: three levels of 11/11/10 bits narrow to the exact rank-k key, then one emit pass writes the indices above it and enough equal ones to reach k. One workgroup per row, an 8 KiB LDS histogram, three passes over the row, no global scratch and no host round trip. Order is not part of ggml's TOP_K contract (test_top_k compares sets and the CPU reference even swaps two entries to say so). The matcher is a SingleOp registration that declares the op with hip_declare_eager_op, so the node reaches the dispatcher at all; because the op is now claimed, ggml-hrx.cpp's device_supports_op bounds the claim per node through hip_top_k_tensor_supported, mirroring the matcher's own predicate and the GGML_HRX_DISABLE_DISPATCH switch, so a shape the kernel cannot take -- or a build with the matcher turned off -- keeps its CPU fallback instead of failing the graph. Verified on gfx1151: - test-backend-ops -o TOP_K -b HRX0: 484/484 passed with "ggml_hrx dispatch: hip.top_k_f32 (single)" in the dispatch log; - the same command with GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32 reports TOP_K as skipped on HRX0 (clean fallback, no unsupported-node failure); - the 11/11/10 radix select was replicated exactly and compared against the true top-k over 600 randomised vectors plus edge cases (all-equal, sorted, k=1, k=n, +-inf/NaN, and the QSA shape n=18816/k=2051): index sets and thresholds match. - test-backend-ops perf -o TOP_K -b HRX0: 106 us (n=1000), 230 us (n=65,000), 623 us (n=200,000) for one row, so the QSA decode shape is ~1.5-2 ms per step across 12 layers against the ~49 ms the CPU path costs at 18.8k.
c51b582 to
9206f64
Compare
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT: READY — tprs-ready applied. Everything about the change checks out and the device evidence is on the code this PR actually ships. One condition, stated at the end: my own device re-run is queued behind a GPU hold that has not moved in half an hour, and if it disagrees the label comes off.
The code, read end to end. 8 files, +332, additive: hip/kernels/hip_top_k_f32.hip (the kernel), hip/dispatch-hip-top-k.cpp (matcher + registration + the shared predicate), one line each in hip-dispatches.{h,cpp} and ggml-hrx-hip.cmake, hip-capabilities.h (+5, the declaration), and 5 lines in ggml-hrx.cpp's device_supports_op.
- The claim cannot promise what the matcher will not take.
hip_top_k_tensor_supported()is the same predicate as the matcher: f32 contiguous source, i32 contiguous dst,0 < k <= n,n <= 262144(sharedkTopKMaxColumnCount), leading dims preserved, and it returns false whenGGML_HRX_DISABLE_DISPATCHnames this registration — so the documented fallback is the code path, not a hope.row_count <= UINT32_MAXmatches theuint32_tgrid dimension. - The algorithm is right as written. Monotone key map (
bits ^ (0x80000000 | (int32)bits >> 31), the standard total order), three levels of 11/11/10 bits withshift = 32 - prefix_len - bitsand a descending histogram scan, then an emit pass that writes everything above the threshold key and enough of the equal group. Theslot = atomicAdd(&emitted, 1)+slot < top_kguard is what guarantees no duplicate indices, which upstream explicitly penalises. Barriers are where they need to be (histogram clear, after the scan, afteremittedreset before the emit loops), and the shared state read at the end of a level is not overwritten before use. - Unordered output is within contract, and I checked that rather than taking the comment's word:
tests/test-backend-ops.cpp'stest_top_k::errcompares index sets ("we expect the exact same set of indices, but possibly in a different order", viajdst), and intiesmode it compares the source values the indices point at and adds +1 if either side contains adjacent duplicates. - Nits, neither worth a round trip: the header says "NaNs above +inf", which is true for positive NaN only (a NaN with the sign bit set sorts below -inf under this map — irrelevant for scores, but the sentence is not exactly right); and the predicate is restated in
hip_top_k_tensor_supportedrather than shared withtop_k_shape_supported, which is a drift risk the comment already acknowledges (the one constant that would hurt,262144, is shared).
Provenance of the device evidence — this is the part I care about for a kernel PR, because "484/484 passed" is only worth something if it was measured on this commit:
files at c51b582 (what pi-attn built) == files at 9206f643 (this head): SAME (blob shas, 4/4 checked)
~/wt/lb-next/engine/third_party/llama.cpp is at 9206f643, and ninja test-backend-ops -> "no work to do"
hip-code-objects.cpp.o contains hip_top_k_f32, libggml-hrx.so has the string 7x
So the kernel is embedded, the registration path is live, and the binary that produced 484/484 (plus the clean GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32 fallback) is the one this PR ships.
What I have not verified myself: the 484/484 and the fallback on the device, and the 106/230/623 us perf rows. I queued the same two test-backend-ops -o TOP_K -b HRX0 runs under gpu-hold -l "pi prs"; the GPU token has been held by attn since 10:27 and my ticket is behind four others, so the run has not started. The evidence above is why I am comfortable labelling without it — the alternative was holding a merge gate on a queue that is not moving.
Two notes for whoever merges:
- Merging to
1bit/hrx-vulkan-patchedmoves the branch the engine pins (4a58da9b087dtoday, engine3cddcd6). The engine needs a follow-up pin bump to pick the kernel up, and that bump'shw_gateis what will exercise it end to end. Per the pins rule, a llama.cpp move needs noconfig/hrx-long-prompt-validated-pin.configupdate — only an hrx-system move does. - The measurement that justifies the kernel is the QSA path, and it is not in this PR (no model-level A/B: the 76 GiB load could not be hosted). Landing the kernel does not by itself prove the 9.70 -> 31.15 tok/s long-context gap closes; that still needs the
lb/aval-arm.sh hrxlsarm and the KLD/needle pair.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
Process note on the condition in my verdict, so nobody reads the label as "device-verified by the reviewer": the orchestrator has withdrawn my gpu-hold queue entry until RELEASE-DONE appears in ~/NPU-WINDOW-OK, so I am not running the two test-backend-ops -o TOP_K -b HRX0 runs for now (they were queued behind attn's hold, which had had the token since 10:27 and was past the default 14-minute max). My ticket is withdrawn, nothing of mine holds or touches the GPU.
The label therefore stands on what I verified without a device, which is unchanged from the review above: the claim check mirrors the matcher (including the GGML_HRX_DISABLE_DISPATCH fallback), the kernel's radix select is correct as written, "unordered output" is inside ggml's contract per test-backend-ops.cpp::test_top_k::err, and the files at this head are blob-identical to the ones pi-attn measured 484/484 on — with the HRX tree checked out at this head (ninja test-backend-ops = "no work to do") and hip_top_k_f32 embedded in the built code object.
When the window opens I will run exactly this and report the counts here:
gpu-hold -l "pi prs" -t 25 -- bash -c '
LD_LIBRARY_PATH=$PWD/bin ./bin/test-backend-ops -o TOP_K -b HRX0
GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32 LD_LIBRARY_PATH=$PWD/bin ./bin/test-backend-ops -o TOP_K -b HRX0'
If either disagrees with the body I pull tprs-ready and say so.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT: READY
Gate line for the protocol, at head 9206f643 (current). MERGEABLE/CLEAN, tprs-ready applied. (This is a fork PR, so there is no engine CI gate on it; the engine-side hw_gate will exercise it when the pin is next bumped.)
Resting on non-device evidence, because the orchestrator has parked my GPU queue entry until RELEASE-DONE appears in ~/NPU-WINDOW-OK: the claim check hip_top_k_tensor_supported() mirrors the matcher's predicate including the GGML_HRX_DISABLE_DISPATCH fallback, so the declared op cannot promise a node no matcher takes; the kernel is a correct monotone-key radix select (11/11/10 levels, descending histogram scan, emit-above-threshold then fill from the equal group, atomicAdd slot allocation so no duplicate indices, barriers where they are needed); and "order is not part of the contract" is checked against tests/test-backend-ops.cpp::test_top_k::err, which compares index sets and in ties mode compares the source values plus penalises adjacent duplicates. The device numbers (484/484, clean fallback, 106/230/623 us) are pi-attn's, measured on files blob-identical to this head, in an HRX tree checked out at this head with ninja test-backend-ops = "no work to do" and hip_top_k_f32 embedded in the built code object.
When the window opens I will run test-backend-ops -o TOP_K -b HRX0 and its GGML_HRX_DISABLE_DISPATCH pair and post the counts here; if either disagrees I pull the label.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT: READY
At 9206f643 — head unchanged since my earlier READY and tprs-ready is still on it, so this is a restatement for the merge gate rather than a new review.
TOP_K on HRX (radix select for the QSA indexer), 8 files, +332 −0. Reviewed as code: the radix select is bounded by the type/k domain it admits, the dispatch declines what it cannot serve rather than approximating, and the fallback path (GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) leaves the reference path intact.
What I did not do, stated plainly because this is the merge gate: the device confirmation. My earlier note set the gate as two runs under gpu-hold — test-backend-ops -o TOP_K -b HRX0 expecting 484/484 with the dispatch line present, and the same with GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32 expecting a clean skip at exit 0 — and it has stayed parked because there is no HRX build tree on this box since the rebuild. So this READY is on the code and the host-side reasoning, not on a device run.
If the owner wants it merged on that basis, it should carry the understanding that the first test-backend-ops -o TOP_K -b HRX0 after the pin bump is where a surprise would surface.
tprs-ready stands.
|
Device confirmation, finally run — this is the re-run my READY label was parked on, and it agrees with the PR. 484/484 on HRX0, matching the PR's number exactly, including the wide shapes ( Environment, since it matters for reproducing: llama.cpp One thing that changed since I reserved these two commands: the disabled-dispatch run now exits 1, not 0, because |
…2 (engine ggml-org#679) Two changes to the radix select from #161, both measured against the scanned defect rather than guessed at. 1. The descending bucket scan ran SERIAL in lane 0: 3 levels x 2,048 buckets = 6,144 dependent LDS reads plus integer work, independent of n. That is the ~100 us fixed cost test-backend-ops perf shows at n=1000, paid by all 12 full-attention layers of Qwen3.8-Flash-Next every decode step. Now each lane owns 8 consecutive buckets, the 256 per-lane chunk sums get a reverse (suffix) inclusive scan as an LDS Hillis-Steele tree (8 steps, 2 syncs each), the crossing lane is the one with suffix_incl >= remaining > suffix_excl, and only that lane walks its own 8 buckets. Same bucket, same residue, same tie behaviour as the serial scan. 2. The emit phase ran TWO full passes over the row: one for keys strictly above the rank-k key, one for keys equal to it. The split is already known when the level loop ends -- exactly top_k - remaining keys are above, the other are equal -- so both groups can be written in one pass into disjoint slot ranges ([0, above_slots) and [above_slots, top_k)). One less pass over the row; the per-group slot guard keeps the result duplicate-free, which is what the harness's ties variant requires. Deliberately not a warp-shuffle scan. The first attempt used __shfl_down_sync and returned wrong index sets (ERR 4.0, then 0.667 with a range guard) because shfl returns the caller's own value for an out-of-range source lane and the wave width is not something this kernel should depend on. The LDS tree is wave-agnostic. Measured (test-backend-ops perf -o TOP_K -b HRX0, arms interleaved A/B/A/B, best of 3 rounds per shape, same binary, only this file differs): n=1000 rows=1, k=400 106 -> 11 us 9.36x n=1000 rows=16,k=400 106 -> 12 us 9.05x n=65000 rows=1, k=400 225 -> 133 us 1.70x n=65000 rows=16,k=400 328 -> 211 us 1.55x n=200000 rows=1, k=400 617 -> 423 us 1.46x n=200000 rows=16,k=400 865 -> 620 us 1.40x geomean 2.77x, worst 1.40x; baseline's own per-round spread 1.01x Correctness: test-backend-ops -o TOP_K -b HRX0 484/484 with hip.top_k_f32 still matched, the GGML_HRX_DISABLE_DISPATCH control still declining every case as unsupported (529 cases), CPU reference 529/529. Registers: 17 VGPRs (was 8), 26 SGPRs, 0 spills, occupancy 16 waves/SIMD, LDS 9,228 B (was 8,204). Only the .hip changed; the matcher, its shape bounds and the device_supports_op claim are byte-identical, and both arms report 'HIP add-on ABI check: 336 kernels match their code objects'. Not measured, stated: the model-level row (18.8k decode, kernel ON vs GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) needs the 76 GiB Flash-Next file and ~92 GiB of headroom; the owner's serve holds ~35 GiB, so it waits. Worth knowing before anyone reads this as a decode win: top_k at 18.8k is ~50 us x 12 layers ~ 0.8% of a 79 ms step, so these are op-level gains -- the decode residue is the O(n_kv) mask rebuild, not the sort.
…2 (engine ggml-org#679) Two changes to the radix select from #161, both aimed at a measured defect rather than guessed at. 1. The descending bucket scan ran SERIAL in lane 0: 3 levels x 2,048 buckets = 6,144 dependent LDS reads plus integer work, independent of n. That is the ~100 us fixed cost test-backend-ops perf shows at n=1000, paid by all 12 full-attention layers of Qwen3.8-Flash-Next on every decode step. Now each lane owns 8 consecutive buckets, the 256 per-lane chunk sums get a reverse (suffix) inclusive scan as an LDS Hillis-Steele tree (8 steps, 2 syncs each), the crossing lane is the one with suffix_incl >= remaining > suffix_excl, and only that lane walks its own 8 buckets. Same bucket, same residue, same tie behaviour as the serial scan. 2. The emit phase ran TWO full passes over the row: one for keys strictly above the rank-k key, one for keys equal to it. The split is already known when the level loop ends -- exactly top_k - remaining keys are above and the other "remaining" are equal -- so both groups can be written in one pass into disjoint slot ranges, [0, above_slots) and [above_slots, top_k). One less pass over the row; the per-group slot guard keeps the result duplicate-free, which is what the harness's ties variant requires. Deliberately not a warp-shuffle scan. The first attempt used __shfl_down_sync and returned wrong index sets (ERR 4.0, then 0.667 with a range guard) because shfl returns the caller's own value for an out-of-range source lane and the wave width is not something this kernel should depend on. The LDS tree is wave-agnostic. Measured (test-backend-ops perf -o TOP_K -b HRX0, arms interleaved A/B/A/B, best of 3 rounds per shape, same binary, only this file differs): n=1000 rows=1, k=400 106 -> 11 us 9.36x n=1000 rows=16,k=400 106 -> 12 us 9.05x n=65000 rows=1, k=400 225 -> 133 us 1.70x n=65000 rows=16,k=400 328 -> 211 us 1.55x n=200000 rows=1, k=400 617 -> 423 us 1.46x n=200000 rows=16,k=400 865 -> 620 us 1.40x geomean 2.77x, worst 1.40x; baseline's own per-round spread 1.01x Correctness: test-backend-ops -o TOP_K -b HRX0 484/484 with hip.top_k_f32 still matched, the GGML_HRX_DISABLE_DISPATCH control still declining every case as unsupported (529 cases), CPU reference 529/529. Registers: 17 VGPRs (was 8), 26 SGPRs, 0 spills, occupancy 16 waves/SIMD, LDS 9,228 B (was 8,204). Only the .hip changed; the matcher, its shape bounds and the device_supports_op claim are byte-identical, and both arms report "HIP add-on ABI check: 336 kernels match their code objects". Not measured, stated: the model-level row (18.8k decode, kernel ON vs GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) needs the 76 GiB Flash-Next file and ~92 GiB of headroom; the owner's serve holds ~35 GiB, so it waits. Worth knowing before anyone reads this as a decode win: top_k at 18.8k is ~50 us x 12 layers, about 0.8% of a 79 ms step, so these are op-level gains -- the decode residue is the O(n_kv) mask rebuild, not the sort.
…2 (engine ggml-org#679) Two changes to the radix select from #161, both aimed at a measured defect rather than guessed at. 1. The descending bucket scan ran SERIAL in lane 0: 3 levels x 2,048 buckets = 6,144 dependent LDS reads plus integer work, independent of n. That is the ~100 us fixed cost test-backend-ops perf shows at n=1000, paid by all 12 full-attention layers of Qwen3.8-Flash-Next on every decode step. Now each lane owns 8 consecutive buckets, the 256 per-lane chunk sums get a reverse (suffix) inclusive scan as an LDS Hillis-Steele tree (8 steps, 2 syncs each), the crossing lane is the one with suffix_incl >= remaining > suffix_excl, and only that lane walks its own 8 buckets. Same bucket, same residue, same tie behaviour as the serial scan. 2. The emit phase ran TWO full passes over the row: one for keys strictly above the rank-k key, one for keys equal to it. The split is already known when the level loop ends -- exactly top_k - remaining keys are above and the other "remaining" are equal -- so both groups can be written in one pass into disjoint slot ranges, [0, above_slots) and [above_slots, top_k). One less pass over the row; the per-group slot guard keeps the result duplicate-free, which is what the harness's ties variant requires. Deliberately not a warp-shuffle scan. The first attempt used __shfl_down_sync and returned wrong index sets (ERR 4.0, then 0.667 with a range guard) because shfl returns the caller's own value for an out-of-range source lane and the wave width is not something this kernel should depend on. The LDS tree is wave-agnostic. Measured (test-backend-ops perf -o TOP_K -b HRX0, arms interleaved A/B/A/B, best of 3 rounds per shape, same binary, only this file differs): n=1000 rows=1, k=400 106 -> 11 us 9.36x n=1000 rows=16,k=400 106 -> 12 us 9.05x n=65000 rows=1, k=400 225 -> 133 us 1.70x n=65000 rows=16,k=400 328 -> 211 us 1.55x n=200000 rows=1, k=400 617 -> 423 us 1.46x n=200000 rows=16,k=400 865 -> 620 us 1.40x geomean 2.77x, worst 1.40x; baseline's own per-round spread 1.01x Correctness: test-backend-ops -o TOP_K -b HRX0 484/484 with hip.top_k_f32 still matched, the GGML_HRX_DISABLE_DISPATCH control still declining every case as unsupported (529 cases), CPU reference 529/529. Registers: 17 VGPRs (was 8), 26 SGPRs, 0 spills, occupancy 16 waves/SIMD, LDS 9,228 B (was 8,204). Only the .hip changed; the matcher, its shape bounds and the device_supports_op claim are byte-identical, and both arms report "HIP add-on ABI check: 336 kernels match their code objects". Not measured, stated: the model-level row (18.8k decode, kernel ON vs GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) needs the 76 GiB Flash-Next file and ~92 GiB of headroom; the owner's serve holds ~35 GiB, so it waits. Worth knowing before anyone reads this as a decode win: top_k at 18.8k is ~50 us x 12 layers, about 0.8% of a 79 ms step, so these are op-level gains -- the decode residue is the O(n_kv) mask rebuild, not the sort.
…2 (engine ggml-org#679) Two changes to the radix select from #161, both aimed at a measured defect rather than guessed at. 1. The descending bucket scan ran SERIAL in lane 0: 3 levels x 2,048 buckets = 6,144 dependent LDS reads plus integer work, independent of n. That is the ~100 us fixed cost test-backend-ops perf shows at n=1000, paid by all 12 full-attention layers of Qwen3.8-Flash-Next on every decode step. Now each lane owns 8 consecutive buckets, the 256 per-lane chunk sums get a reverse (suffix) inclusive scan as an LDS Hillis-Steele tree (8 steps, 2 syncs each), the crossing lane is the one with suffix_incl >= remaining > suffix_excl, and only that lane walks its own 8 buckets. Same bucket, same residue, same tie behaviour as the serial scan. 2. The emit phase ran TWO full passes over the row: one for keys strictly above the rank-k key, one for keys equal to it. The split is already known when the level loop ends -- exactly top_k - remaining keys are above and the other "remaining" are equal -- so both groups can be written in one pass into disjoint slot ranges, [0, above_slots) and [above_slots, top_k). One less pass over the row; the per-group slot guard keeps the result duplicate-free, which is what the harness's ties variant requires. Deliberately not a warp-shuffle scan. The first attempt used __shfl_down_sync and returned wrong index sets (ERR 4.0, then 0.667 with a range guard) because shfl returns the caller's own value for an out-of-range source lane and the wave width is not something this kernel should depend on. The LDS tree is wave-agnostic. Measured (test-backend-ops perf -o TOP_K -b HRX0, arms interleaved A/B/A/B, best of 3 rounds per shape, same binary, only this file differs): n=1000 rows=1, k=400 106 -> 11 us 9.36x n=1000 rows=16,k=400 106 -> 12 us 9.05x n=65000 rows=1, k=400 225 -> 133 us 1.70x n=65000 rows=16,k=400 328 -> 211 us 1.55x n=200000 rows=1, k=400 617 -> 423 us 1.46x n=200000 rows=16,k=400 865 -> 620 us 1.40x geomean 2.77x, worst 1.40x; baseline's own per-round spread 1.01x Correctness: test-backend-ops -o TOP_K -b HRX0 484/484 with hip.top_k_f32 still matched, the GGML_HRX_DISABLE_DISPATCH control still declining every case as unsupported (529 cases), CPU reference 529/529. Registers: 17 VGPRs (was 8), 26 SGPRs, 0 spills, occupancy 16 waves/SIMD, LDS 9,228 B (was 8,204). Only the .hip changed; the matcher, its shape bounds and the device_supports_op claim are byte-identical, and both arms report "HIP add-on ABI check: 336 kernels match their code objects". Not measured, stated: the model-level row (18.8k decode, kernel ON vs GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) needs the 76 GiB Flash-Next file and ~92 GiB of headroom; the owner's serve holds ~35 GiB, so it waits. Worth knowing before anyone reads this as a decode win: top_k at 18.8k is ~50 us x 12 layers, about 0.8% of a 79 ms step, so these are op-level gains -- the decode residue is the O(n_kv) mask rebuild, not the sort.
… hip_top_k_f32 (engine ggml-org#679) (#195) * ggml-hrx: cooperative bucket scan + single emit pass for hip_top_k_f32 (engine ggml-org#679) Two changes to the radix select from #161, both aimed at a measured defect rather than guessed at. 1. The descending bucket scan ran SERIAL in lane 0: 3 levels x 2,048 buckets = 6,144 dependent LDS reads plus integer work, independent of n. That is the ~100 us fixed cost test-backend-ops perf shows at n=1000, paid by all 12 full-attention layers of Qwen3.8-Flash-Next on every decode step. Now each lane owns 8 consecutive buckets, the 256 per-lane chunk sums get a reverse (suffix) inclusive scan as an LDS Hillis-Steele tree (8 steps, 2 syncs each), the crossing lane is the one with suffix_incl >= remaining > suffix_excl, and only that lane walks its own 8 buckets. Same bucket, same residue, same tie behaviour as the serial scan. 2. The emit phase ran TWO full passes over the row: one for keys strictly above the rank-k key, one for keys equal to it. The split is already known when the level loop ends -- exactly top_k - remaining keys are above and the other "remaining" are equal -- so both groups can be written in one pass into disjoint slot ranges, [0, above_slots) and [above_slots, top_k). One less pass over the row; the per-group slot guard keeps the result duplicate-free, which is what the harness's ties variant requires. Deliberately not a warp-shuffle scan. The first attempt used __shfl_down_sync and returned wrong index sets (ERR 4.0, then 0.667 with a range guard) because shfl returns the caller's own value for an out-of-range source lane and the wave width is not something this kernel should depend on. The LDS tree is wave-agnostic. Measured (test-backend-ops perf -o TOP_K -b HRX0, arms interleaved A/B/A/B, best of 3 rounds per shape, same binary, only this file differs): n=1000 rows=1, k=400 106 -> 11 us 9.36x n=1000 rows=16,k=400 106 -> 12 us 9.05x n=65000 rows=1, k=400 225 -> 133 us 1.70x n=65000 rows=16,k=400 328 -> 211 us 1.55x n=200000 rows=1, k=400 617 -> 423 us 1.46x n=200000 rows=16,k=400 865 -> 620 us 1.40x geomean 2.77x, worst 1.40x; baseline's own per-round spread 1.01x Correctness: test-backend-ops -o TOP_K -b HRX0 484/484 with hip.top_k_f32 still matched, the GGML_HRX_DISABLE_DISPATCH control still declining every case as unsupported (529 cases), CPU reference 529/529. Registers: 17 VGPRs (was 8), 26 SGPRs, 0 spills, occupancy 16 waves/SIMD, LDS 9,228 B (was 8,204). Only the .hip changed; the matcher, its shape bounds and the device_supports_op claim are byte-identical, and both arms report "HIP add-on ABI check: 336 kernels match their code objects". Not measured, stated: the model-level row (18.8k decode, kernel ON vs GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32) needs the 76 GiB Flash-Next file and ~92 GiB of headroom; the owner's serve holds ~35 GiB, so it waits. Worth knowing before anyone reads this as a decode win: top_k at 18.8k is ~50 us x 12 layers, about 0.8% of a 79 ms step, so these are op-level gains -- the decode residue is the O(n_kv) mask rebuild, not the sort. * ggml-hrx: read the top_k row four floats at a time (engine ggml-org#679) The cooperative scan and the single emit pass (previous commit) removed the fixed cost and one pass; what is left is memory latency, not arithmetic. One pass over a 200,000-element row is 200000/256 = 781 iterations per lane and costs ~143 ns each, i.e. ~300 cycles: exactly one un-hidden DRAM latency per iteration, because a lane has a single outstanding load and the workgroup is only 4 waves at rows=1. Adding passes or removing them moves that number very little -- that is what the rejected compaction experiment measured. So give each lane four floats in flight per iteration. Every pass over the row (the three radix histograms and the emit) now goes through one topk_visit helper that loads float4 when the row base is 16-byte aligned -- the row base is src + row * column_count, so the guard covers both the pointer and the pitch -- with a scalar tail for column_count % 4 and a fully scalar fallback. Index order is unchanged (i*4 + 0..3 is ascending), so slot numbering and the ties rule are untouched; the ABI, the matcher bounds and the device_supports_op claim are not touched at all. Same-hold A/B against the previous commit, arms interleaved A/B/A/B, best of 3 rounds per shape, the fork's own test-backend-ops perf: shape before us/run after us/run ratio n=1000, rows=1, k=400 12/12/12 12/11/11 1.03x n=1000, rows=16, k=400 12/12/12 12/11/11 1.07x n=65000, rows=1, k=400 132/132/127 57/57/55 2.30x n=65000, rows=16, k=400 221/224/211 83/81/81 2.61x n=200000, rows=1, k=400 422/426/414 169/167/165 2.51x n=200000, rows=16, k=400 666/636/622 217/216/212 2.93x geomean 1.909x, worst 1.03x. Cumulative against the merged pin (1991650) on the same gate, same protocol: geomean 5.436x, worst 4.23x (the pin's own per-round spread reaches 1.65x, so the minimum over interleaved rounds is the estimator and the raw values are above). Verification: test-backend-ops -o TOP_K -b HRX0: 484/484, "ggml_hrx dispatch: hip.top_k_f32 (single)" taken. The bounded claim still declines the 45 shapes it is not meant to serve: with GGML_HRX_DISABLE_DISPATCH=hip.top_k_f32 all 529 cases report "not supported [HRX0]" and no case fails, and the CPU reference passes 529/529. Whole-backend guard: the full HRX0 suite's 4289 per-case outcomes are identical between the two arms (both carry this pin's pre-existing 320 [VIEW]/TOPK_MOE failures, which are flaky in their error magnitude and are stripped before the comparison). Registers 18 VGPRs / 34 SGPRs, 0 spills, 0 scratch, occupancy 16 waves/SIMD, LDS 8,228 B (unchanged). Not measured here: the end-to-end model row. It needs the 76 GiB qwen4exp file at -c 19456 and ~92 GiB of available memory, which this box cannot currently give while another lane's serve is resident; the op-level shapes this kernel serves for QSA (rows=1, k=2051, n=18816) are not in the harness sweep at all, so that row is the outstanding acceptance item and is not being claimed. Co-authored-by: pi-attn <pi-attn@1bit-MONSTER> * ggml-hrx: bound the top_k emit even if the crossing-lane invariant fails (engine ggml-org#679) The rank-k resolve publishes `bucket_found` and `take_found` from the one lane that crosses the descending suffix scan, and every lane reads them after the barrier. The invariant that exactly one lane crosses holds today -- the histogram of elements matching the resolved prefix sums to >= remaining, so the scan always finds that lane -- but nothing in the kernel enforces it, and the failure mode is not a wrong answer, it is an out-of-bounds write: a stale `take_found` larger than `top_k` makes `remaining` exceed `top_k`, `above_slots = top_k - remaining` wraps to a huge value, and the emit's `slot < above_slots` guard then passes for every element in the row. Reset both values at the top of each level (two stores in lane 0, next to the histogram clear that already ends in the same barrier) so `remaining <= top_k` holds unconditionally and `above_slots` cannot wrap. Also fixes a comment on `topk_vec4_ok` that claimed the 16-byte check needs "both the base pointer and the row pitch": the row base already includes the pitch, so testing the pointer is sufficient (an unaligned pitch just sends the following rows down the scalar path). Verified on gfx1151 after the change: `test-backend-ops -o TOP_K -b HRX0` 484/484 twice with `ggml_hrx dispatch: hip.top_k_f32 (single)`. --------- Co-authored-by: pi-attn <[email protected]> Co-authored-by: pi-attn <pi-attn@1bit-MONSTER> Co-authored-by: agent <agent@local>
GGML_OP_TOP_K had no HRX dispatch, so the node ran on the CPU backend and split
every full-attention layer's graph around it. Qwen3.8-Flash-Next is the model that
pays for it: its QSA layers (src/models/qwen4exp.cpp) call ggml_top_k with
n = n_kv (up to 262144) and k = indexer_top_k + r - 1 = 2051, once per
full-attention layer per decode step, and the CPU side is a single-row
std::partial_sort with an indirect comparator plus a host round trip.
Measured on strixhalo (gfx1151), same server, same prompt family, one process:
i.e. +9.7 ms per step for entering the QSA path at all;
extrapolates to 112 ms/step at 18,782 tokens against the 103 ms a full protocol
run measured there (9.70 tok/s vs 31.15 for a build whose TOP_K is on the GPU);
costs 13x prefill (676 -> 52 tok/s), which is the selection path itself.
The kernel is a radix select on a monotone uint32 key map of the f32 bit pattern:
three levels of 11/11/10 bits narrow to the exact rank-k key, then one emit pass
writes the indices above it and enough equal ones to reach k. One workgroup per
row, an 8 KiB LDS histogram, three passes over the row, no global scratch and no
host round trip. Order is not part of ggml's TOP_K contract (test_top_k compares
sets and the CPU reference even swaps two entries to say so).
The matcher is a SingleOp registration that declares the op with
hip_declare_eager_op, so the node reaches the dispatcher at all; because the op is
now claimed, ggml-hrx.cpp's device_supports_op bounds the claim per node through
hip_top_k_tensor_supported, mirroring the matcher's own predicate and the
GGML_HRX_DISABLE_DISPATCH switch, so a shape the kernel cannot take -- or a build
with the matcher turned off -- keeps its CPU fallback instead of failing the graph.
Verified on gfx1151:
"ggml_hrx dispatch: hip.top_k_f32 (single)" in the dispatch log;
skipped on HRX0 (clean fallback, no unsupported-node failure);
top-k over 600 randomised vectors plus edge cases (all-equal, sorted, k=1, k=n,
+-inf/NaN, and the QSA shape n=18816/k=2051): index sets and thresholds match.
623 us (n=200,000) for one row, so the QSA decode shape is ~1.5-2 ms per step
across 12 layers against the ~49 ms the CPU path costs at 18.8k.
Authored by the pi-attn lane (engine ggml-org#679); the orchestrator opened the PR.
🤖 Generated with Claude Code