Repository navigation
Conversation
…ip input views hip: qsa_decode (wmma) and qsa_prefill read q8_0 K/V. The decode kernel dequantizes in registers; the prefill pack converts while packing (the direct f16 path is skipped for q8_0). Both use the same half product as dequantize_block_q8_0_f16. Complete-block selection now also takes q8_0 K/V when every QSA layer runs on ROCm (selected_key_q8), so a q8_0 cache no longer falls back to the masked per-cell top-k. qwen4exp: the masked top-k path took a fresh view of the KQ mask and the QSA bias for every 512-query score strip in every layer. The scheduler gives each view of a host input its own copy, kept for the whole graph, so this made n_layers x n_strips copies. With Signal-3.8-Flash-Next Q4_K_XL, -ub 4096 and a q8_0 cache, the ROCm0 compute buffer was 7193 MiB at 32k (vs 3009 before bb030af) and grew about 0.15 MiB per context cell (~41 GB at 262k), so the MTP draft context hit OOM. The views are now built once per graph and shared: 2969 MiB at 32k, 10.7 GB at 262k. Perplexity is bit-identical. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4rLkt7MokKFKji9hxCaev
728427c to
68da419
Compare
Review of 68da419, measured on Strix HaloI measured this head against its merge base 13a279b, both built in the same session.
1. q8_0 is not at parity with f16PR q8_0 compared with PR f16, in t/s. The PR's f16 numbers match base. b/ub 4096:
ub 512, b 4096:
Depth 200k (b/ub 4096):
2. Where the gap comes fromPer-op GPU time from
3. Correctness
4. Memory, confirmedROCm0 compute buffer,
5. Code issues
Checked and fine
Reviewed with Claude (Opus 5.5). Two subagents reviewed the code; every number above was measured on a Strix Halo machine. |
gaetan-puleo
left a comment
There was a problem hiding this comment.
Check comment on top
|
My build/run setup |
f16 KV: no regression from this PR (master vs PR vs merge base)Someone on Discord reported f16 getting slower from halo/master to this PR. I can't reproduce it. When all three builds use the same ROCm, f16 performance on this PR matches master and the merge base to within noise. t/s, shown as round 1 / round 2:
|
q8_0 KV: master vs PR vs merge baseSame setup and order as the f16 comment above, with
Master and the base give the same q8_0 numbers. The three Vulkan commits since the base don't affect ROCm. Where this PR helps:
Where it's slower: with the default ub 512 at depth 0, pp4096 is 6% behind master. This matches the review's ub 512 finding.
q8_0 vs f16 on this PR at the default ubatch, from the two comments: −6% at pp4096 depth 0, −4% at pp4096 @ d32768, and −1.5% for tg128 @ d32768. |
…tests - selected_key_attn now comes from a probe op with the real K/V types, at one query and at 513 (past the decode kernels). selected_key_q8 and the "ROCm" backend-name check are gone: a q8_0 cache on a model whose GQA ratio is not 12 (q8_0 decode is WMMA-only) or on Vulkan (flash_attn_sel is f16-only) now takes the masked route instead of falling back to CPU. LLAMA_QSA_SELECTED_KEY=1 forces the selected-key route for q8_0 too. - The QSA attention log line names the cache types it was decided for. - strip_views is keyed on the strip size too, which varies with the layer's compress ratio. - test-backend-ops: q8_0 and mixed K/V variants of the maskless QSA decode and prefill tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F
qsa_prefill_impl1 packed the whole q8_0 K and V cache to f16 on every ubatch in every QSA layer, because the direct reads were f16-only: O(n_kv) work per ubatch and f16-sized pool buffers, eating into what a q8_0 cache saves. qsa3_attn_kernel now takes a Q8 flag: a direct K chunk (dims 32w .. 32w+31 of a key) is exactly q8_0 block w, loaded as aligned dwords and realigned (the block offset is wave-uniform); direct V reads each key's byte and scale. Both dequantize in registers with the decode kernel's exact half conversion, so every QSA_DIRECT mode stays bit-identical to the pack (llama-perplexity KLD vs QSA_DIRECT=0 at the floor of identical runs; test-backend-ops passes in modes 0/1/2/auto). Mixed K/V types still pack. The auto heuristic is shared with f16: K direct, V direct too when the attention is small against the cache. q8_0 at b/ub 4096 (Signal-3.8- Flash-Next Q4_K_XL): K direct 1347 / 1272 t/s vs pack 1350 / 1284 at pp4096 depth 0 / 32k, within noise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F
|
Thanks for the thorough review. I pushed two commits on top of 68da419 and rewrote the description. Each point below says what happened to it. The repack cost at depth (§2) is fixed by
Parity claim and the ub 512 slowdown (§1): I removed the parity claim from the description and put in interleaved tables against master. ub 512 at depth 0 against master's dense q8_0 kernel went from −4.5% to −3% at pp4096, and is −2% at pp8192. It's listed as remaining. Code issues (§5), fixed in
Tests (§3): I added q8_0 and mixed-type variants of
Masked-route output change (§3): this is now stated in the description, with your KLD numbers. |
…the QSA selected-key kernels halo-box#219 by Iggy Jackson, taken locally for STASH-025 (q8_0 KV on Vulkan, lab only), 2026-11-04. Conflict with halo-box#234 in ggml/src/ggml-cuda/qsa-prefill.cu (halo-box#234 removes QSA_DIRECT and the packed-K path that halo-box#219 extends to q8_0) taken as halo-box#219's version, unbuilt: this tree builds Vulkan only. Assisted-by: Claude Code
flash_attn_sel (scalar) and flash_attn_sel_cm (RDNA3 WMMA) read f16 K/V only, so with a q8_0 cache the qwen4exp QSA layers fall back to the masked route, whose dequantized copies grow with the visible KV range. Both kernels now take K and V each as f16 or q8_0 (four variants per GQA) and dequantize q8_0 to f16 in the kernel: the scalar one while it stages the key block in shared memory, the WMMA one while it builds the K and V fragments from 16-bit words (a q8_0 row is only 2-byte aligned). Strides are passed in elements of each type, i.e. in q8_0 blocks. test-backend-ops QSA_DECODE_MASKLESS / QSA_PREFILL_MASKLESS, including the q8_0 cases from halo-box#219: 79/79 on a Radeon 890M (gfx1150, RADV), WMMA and, with GGML_VK_DISABLE_COOPMAT=1, scalar. Worst NMSE against the FP64 oracle: 8.6e-8 for q8_0 (f16 4.9e-8; the CPU backend's q8_0 1.6e-6). Assisted-by: Claude Code
|
Vulkan side for this PR: q8_0 K/V in the maskless selected-key kernels With this PR, a q8_0 K/V cache still takes the masked QSA route on Vulkan. There,
On Qwen3.8-Flash-Next (GSQ-RCO IQ3_XXS,
Our production server has run q8_0 K/V this way since 2026-11-06. The commit sits on master 62a3f41 plus this PR squashed. It does not compile on this PR's current head, because If you would rather have it as a separate PR on top of yours after the rebase, say so and we'll open one. Written by Claude Code (an AI agent), measured on rcfa's Strix Point machine; rcfa owns it. |
dzannotti
left a comment
There was a problem hiding this comment.
Verdict
Changes requested. The q8_0 kernels give correct results in every op test we ran, on both backends. But the new direct q8_0 K+V prefill kernel spills registers, and the branch conflicts with current master.
Direction
Accept after work. A q8_0 K/V cache on the QSA selected-key path is useful on Strix Halo for long contexts, and the shared strip views fix a real compute-buffer growth. The gate and probe changes in src/models/qwen4exp.cpp and src/llama-memory-hybrid-idx.cpp edit the same lines as #271, so the PR that lands second will conflict. Please coordinate with the author of #271. We prefer the probe in this PR, because it checks both 1 and 513 queries. The log text of #271 is clearer, since it says whether the backend or the cache type is missing.
Asks
- Blocking.
ggml/src/ggml-cuda/qsa-prefill.cu: the instantiationqsa3_attn_kernel<true, 8, true, true>(q8_0 K and V both direct) has 28 VGPR spills and 116 bytes of scratch per lane on gfx1151. The spill gate inscripts/hippasses on master and fails with this PR. The variant that reads K direct and packs V (<true, 8, false, true>) has no spills. Either remove the spills (fewer live registers in theDIRECT_V && Q8path), or pack V for q8_0 and use only that variant. Then show numbers for the case it serves (n_q > 512 and n_kv > 64 * n_q). - Blocking. Rebase onto master. Master commit d8f3d1d removed
QSA_DIRECT,qsa_pack_kand the packed-K launch, soqsa-prefill.cuconflicts in 3 hunks. We resolved it locally and tested that resolution (see the details block), but we could not push it to your branch. The core change: K is always read direct (f16, or q8_0 through theQ8flag), V is direct only whenk->type == v->type && n_q * 64 < n_kv, and mixed K/V types read K direct and pack V.qsa_pack_kandQSA_DIRECTare not needed. tests/test-backend-ops.cpp: the q8_0 prefill cases with 70, 130 and 200 queries go toqsa_decode, which takes up to 512 queries. So no test reaches the direct q8_0 prefill path. Please add maskless cases with more than 512 queries and n_kv > 64 * n_q (for example 513 queries on 40064 keys). Please also add masked q8_0 cases forQSA_PREFILLandQSA_DECODE. With this PR a masked q8_0 op runs on the QSA kernels and not on the dense q8_0 kernel, so its output changes (you measured KLD 0.0136).- Should fix.
src/llama-memory-hybrid-idx.cpp: the probe with 513 queries also changes f16 routing. On HIP, an f16 model with a GQA ratio other than 12 now takes the masked route. Before, it took the maskless route, and ubatches of more than 512 queries ran attention on the CPU. This is a fix. Please state it in the commit message, together with the masked q8_0 output change. - Should fix. Commits: AGENTS.md asks for an
Assisted-by:trailer, notCo-Authored-Bywith session links. After the rebase, the message of the third commit still describesQSA_DIRECTmodes. Consider squashing, because later commits remove most of what the first commit adds toqsa-prefill.cu.
Nits: qsa_q8_to_h and qsa3_q8x2_to_h2 do the same conversion in one file. A plain map lookup can replace the strip_view lambda.
Correctness
FAIL on ROCm, because of the spill gate (ask 1). INCOMPLETE on Vulkan, because no model-level checks ran. Every op test passed on the PR rebased onto master:
- ROCm: all QSA and FLASH_ATTN_EXT cases, with
HIP_LAUNCH_BLOCKINGunset and set to 1. This includes 172 extra cases we added: mixed types, masked q8_0, two streams, and the direct prefill path. - Both full backend suites: no new failures.
- Vulkan reports the q8_0 cases as not supported, with no failures.
test-llama-archs -a qwen4exppasses on both backends. - On a random-weight qwen4exp model, the f32 logits are byte-identical to master with f16 and q8_0 caches, on both backends.
- The
-WerrorHIP build is clean.
We have no qwen4exp model small enough to run here, so the logit parity, KLD/PPL and decode checks on a real model did not run.
Performance
Op level only, ROCm, graphs off, 2 alternated rounds, GQA 12, 2051 selected keys. No f16 case is slower beyond the spread. The prefill row at 270k keys uses the kernel that spills.
| Case | master f16 (us) | PR f16 (us) | f16 change (spread) | PR q8_0 (us) |
|---|---|---|---|---|
| prefill maskless, 2048 q, 32k keys | 30851 | 32088 | +4.0% (8.6%) | 34887 |
| prefill maskless, 2048 q, 65k keys | 35488 | 35685 | +0.6% (1.9%) | 38365 |
| prefill maskless, 2048 q, 270k keys | 56418 | 56260 | -0.3% (0.4%) | 53326 |
| decode maskless, 1 q, 32k keys | 34.2 | 34.2 | 0.0% | 41.5 |
| decode maskless, 512 q, 65k keys | 6007 | 6025 | +0.3% | 8793 |
llama-bench did not run, so the end-to-end claims against master q8_0 are not reproduced.
Verification
Strix Halo (gfx1151), ROCm and Vulkan. We rebased the PR (60 commits behind) onto master 0c1021e and compared it with master at the same commit, with the same build flags.
Not tested
A real qwen4exp model: logits, KLD/PPL, greedy decode, llama-bench, and the memory figures.
Thanks for the detailed measurements and for answering the earlier review point by point.
Review made with AI on behalf of the strix-llama.cpp maintainers.
Full verification (for reproduction and agents)
Environment
Ubuntu 26.04.1, kernel 7.0.0-43-generic. ROCm 10.1.0-3 (hipconfig 7.16.26385), AMD clang 24.0.0git d6f6cb69. Mesa RADV 26.0.8 (Radeon 8060S). cmake 4.2.3, gcc 15.2.0.
Compared
- master tip: 0c1021e
- PR head: 94e0868
- merge base: 13a279b (60 commits behind master)
- rebased head (local, not pushed): b68e92a2a3d1a9d6ed12a8a41fccdd7f89e520d3
Rebase
The only conflicting file is ggml/src/ggml-cuda/qsa-prefill.cu. Master d8f3d1d removed the QSA_DIRECT gate, qsa_pack_k and the packed-K launch.
- Commit 1 (q8_0 packs only): we kept the PR's
qsa_q8_to_h,qsa_pack_k<q8>andqsa_pack_v<q8>, and droppedQSA_DIRECT. f16/f16 follows master (K direct, V direct whenn_q*64 < n_kv). Any q8_0 K or V packs both and launchesqsa3_attn_kernel<false, 8>. - Commit 3 (direct q8_0 reads): K is always direct, and the kernel is chosen by
k->type. V is direct only when the types are equal andn_q*64 < n_kv, otherwiseqsa_pack_v<v is q8_0>. We removedqsa_pack_kand the packed-K launch again. The result is the same: pack and direct use the same conversion. Our extra mixed-type cases pass. - The other files merged cleanly.
Resolved block in qsa_prefill_impl1:
const bool k_q8 = k->type == GGML_TYPE_Q8_0;
const bool qsa_direct = k->type == v->type && (size_t) n_q * 64 < (size_t) nk;
ggml_cuda_pool_alloc<uint16_t> packed_v(ctx.pool(), qsa_direct ? 0 : ggml_nelements(v));
if (!qsa_direct) {
const uint32_t count_v=ggml_nelements(v)/4;
auto * pack_v = v->type==GGML_TYPE_Q8_0 ? qsa_pack_v<true> : qsa_pack_v<false>;
pack_v<<<(count_v+255)/256,256,0,ctx.stream()>>>((const char *)v->data,packed_v.get(),v->nb[1],v->nb[2],nk,count_v);
CUDA_CHECK(cudaGetLastError());
}
...
if (!qsa_direct) {
ggml_cuda_kernel_launch(k_q8 ? qsa3_attn_kernel<true, 8, false, true> : qsa3_attn_kernel<true, 8, false>, launch, (const float *) q->data, (const uint16_t *) k->data, packed_v.get(), ...);
} else {
ggml_cuda_kernel_launch(k_q8 ? qsa3_attn_kernel<true, 8, true, true> : qsa3_attn_kernel<true, 8>, launch, (const float *) q->data, (const uint16_t *) k->data, (const uint16_t *) v->data, ...);
}
qsa_pack_k is deleted, and so is the QSA_DIRECT read. We could not push the rebase to the PR branch, so please apply this resolution in your own rebase.
Build
HIP: cmake -S <tree> -B <tree>/build-hip -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_HIP=ON -DGGML_VULKAN=OFF -DGPU_TARGETS=gfx1151 -DCMAKE_HIP_COMPILER=$(hipconfig -l)/clang -DCMAKE_PREFIX_PATH=$(hipconfig -R)
Vulkan: cmake -S <tree> -B <tree>/build-vk -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_VULKAN=ON -DGGML_HIP=OFF
-Werror: HIP flags + -DCMAKE_HIP_FLAGS="-Werror -Wno-tautological-compare", target ggml-hip
Spill gate: HIP flags + -DGGML_HIP_EXPORT_METRICS=On -DCMAKE_HIP_FLAGS="", target ggml-hip, then
python3 scripts/hip/gcn-cdna-vgpr-check.py <tree>/build-hip-metrics --baseline scripts/hip/gfx1151-vgpr-baseline.json --compiler-version "<clang --version line 1>"
Models
We found no official qwen4exp GGUF below 66 GB. The smallest is UD-IQ1_S in unsloth/Qwen3.8-Flash-Next-GGUF. The synthetic model was written by test-llama-archs -a qwen4exp -o <file> with random weights. The state tests used Qwen2.5-1.5B-Instruct Q4_K_M and granite-4.0-h-1b Q4_K_M; they do not reach the qwen4exp code.
Commands
test-backend-ops test -b ROCm0 -o {QSA_DECODE_MASKLESS,QSA_PREFILL_MASKLESS,QSA_DECODE,QSA_PREFILL,FLASH_ATTN_EXT,QSA_EXPAND,QSA_SCORE,QSA_STRIP,TOPK_QSA} # HIP_LAUNCH_BLOCKING unset and =1
test-backend-ops test -b ROCm0 -j 4 # unset and =1
test-backend-ops test -b Vulkan0 -o <same ops>; test-backend-ops test -b Vulkan0 -j 4
ctest --test-dir <build> --output-on-failure -L main -E 'test-opt|test-llama-archs'
test-vk-exact
test-llama-archs -b {ROCm0,Vulkan0} -a qwen4exp; test-llama-archs --mtp-cache-only -s 1234
test-llama-context -m <model> -ngl 99 -c 1024 -fa on -ctk {f16,q8_0} -ctv {f16,q8_0}
llama-debug -m <synthetic qwen4exp> -f <prose corpus, first 33%> -c 4096 -b 4096 -ub 2048 -ngl 99 -fa on -ctk {f16,q8_0} -ctv {f16,q8_0} --save-logits --logits-output-dir <dir>; cmp
GGML_CUDA_DISABLE_GRAPHS=1 test-backend-ops perf -b ROCm0 -o {QSA_PREFILL_MASKLESS,QSA_DECODE_MASKLESS,QSA_PREFILL,QSA_DECODE} # temporary perf cases, 2 rounds alternated
GGML_CUDA_DISABLE_GRAPHS=1 scripts/bench-history/ops-perf.sh <build>/bin/test-backend-ops ROCm0 <log> scripts/bench-history/perf-cases.txt
Results
| Op (ROCm, OK / not supported) | master | PR |
|---|---|---|
| QSA_DECODE_MASKLESS | 34 / 0 | 52 / 1 (q8_0 GQA 4, as intended) |
| QSA_PREFILL_MASKLESS | 14 | 26 |
| QSA_DECODE | 92 | 92 |
| QSA_PREFILL | 26 | 26 |
| FLASH_ATTN_EXT | 4051 / 1343 | 4051 / 1343 |
| QSA_EXPAND / QSA_SCORE / QSA_STRIP / TOPK_QSA | 56 / 13 / 6 / 4 | same |
- The counts are the same with
HIP_LAUNCH_BLOCKINGunset and set to 1. There are no failures, and no case passes only with=1. - Full ROCm suite: master 40417/40417, PR 40447/40447 plus 1 not supported, with both settings.
- Full Vulkan suite: 43847/43847 on both sides. The PR adds 31 q8_0 QSA cases, all reported as not supported.
- ctest: the same results on both sides.
test-tokenizers-ggml-vocabsfails on both sides because it needs network vocab files. On Vulkan,test-llama-contextalso fails on both sides. test-vk-exact: the same 11 checks fail on both sides.test-llama-context: q8_0 fails one case ("rf", context creation) on both sides and both backends. f16 passes.
Extra cases (temporary, PR side only, ROCm, unset and =1): 172/172 OK.
- Mixed K/V types with
n_q*64 < n_kv: (130 q, 32768 keys, f16/q8_0), (200, 65536, q8_0/f16), (200, 65536, f16/q8_0). - Masked q8_0 decode: 1, 9, 64 and 512 queries, also non-interleaved, GQA 4, and 40064 keys.
- Masked q8_0 prefill: 513 and 640 queries, mixed types.
- Two-stream maskless prefill: f16, q8_0 and mixed types (compared with the CPU).
- Direct q8_0 prefill: (513, 40064) interleaved and not, and (600, 65536).
Correctness
| Check | Method | Result |
|---|---|---|
| Changed ops, ROCm | test-backend-ops, HLB unset and =1 | PASS |
| Full suite, ROCm | test-backend-ops -j 4, HLB unset and =1 | PASS |
| Changed ops, Vulkan | test-backend-ops | PASS (q8_0 not supported, as intended) |
| Full suite, Vulkan | test-backend-ops -j 4 | PASS |
| test-vk-exact | both sides | same as master |
| test-llama-archs qwen4exp | ROCm0, Vulkan0 | PASS |
| -Werror HIP build | ggml-hip | PASS |
| VGPR spill gate | scripts/hip checker | FAIL: qsa3_attn_kernel<true,8,true,true>, 28 spill saves, 116 scratch bytes/lane (master PASS) |
| State save/load | test-llama-context, f16 and q8_0 | same as master (does not reach qwen4exp) |
| f32 logit parity, prompt tokens, 4 corpora | llama-debug + cmp | not run: no qwen4exp model |
| f32 logit parity, synthetic qwen4exp | llama-debug + cmp, f16 and q8_0, both backends | byte-identical |
| KLD/PPL short and long | llama-perplexity | not run: no qwen4exp model |
| Multi-step greedy decode | llama-completion | not run: no qwen4exp model |
| llama-bench depths 0-64000 | llama-bench | not run: no qwen4exp model |
Performance
QSA op perf (ROCm, us/run, mean of 2 alternated rounds, graphs off, GQA 12, 2051 selected keys):
| Case | master f16 | PR f16 | f16 change (spread) | PR q8_0 | q8_0 vs f16 |
|---|---|---|---|---|---|
| prefill maskless, 2048 q, 32k | 30851 | 32088 | +4.0% (8.6%) | 34887 | +8.7% |
| prefill maskless, 2048 q, 65k | 35488 | 35685 | +0.6% (1.9%) | 38365 | +7.5% |
| prefill maskless, 2048 q, 270k (direct) | 56418 | 56260 | -0.3% (0.4%) | 53326 | -5.2% |
| prefill maskless, 513 q, 40k (direct) | 15584 | 15665 | +0.5% (1.3%) | 18429 | +17.6% |
| decode maskless, 1 q, 32k | 34.2 | 34.2 | 0.0% | 41.5 | +21% |
| decode maskless, 4 q, 65k | 68.0 | 68.2 | +0.3% | 82.0 | +20% |
| decode maskless, 512 q, 65k | 6007 | 6025 | +0.3% | 8793 | +46% |
- Masked f16 cases changed by 1.5% or less.
ops-perf.shon ROCm0: 11 of 377 cases differ by more than 3%, all in ops this PR does not touch (noise, 1 run).ops-perf.shon Vulkan0 is incomplete. ACOL2IM_1Dperf case loses the device on master and on this PR alike; the PR does not touch it.
Findings in full
- Spill in
qsa3_attn_kernel<true, 8, true, true>(ask 1). The other new instantiations have 0 spills:<true,8,false,true>: 192 VGPR, 8 wavesqsa_decode_wmma_partial<true>: 102 VGPR, 12 wavesqsa_pack_v<true>: 18 VGPR
- The PR's q8_0 prefill tests run on
qsa_decode, becauseqsa_decodetakes up to 512 queries (ask 3). - The masked q8_0 route now runs on the QSA kernels and its output changes. No test covers it (ask 3).
- The probe with 513 queries changes f16 routing for GQA ratios other than 12 on HIP (ask 4).
- The q8_0 dequantization matches
dequantize_block_q8_0_f16bit for bit. We checked all 256 quant values against all 65536 half scales on the host. The direct K reads stay inside the 272-byte row and are 16-byte aligned. - The strip-view map belongs to the per-graph object, so a cached view cannot outlive its context. The key (input, first query, strip size) is sufficient.
- Overlap with #271: the
qwen4exp.cpphunks are line-identical. Inllama-memory-hybrid-idx.cpp, #271 probes f16 first, then the cache type, with 1 query only. This PR probes the cache type with 1 and 513 queries.
Claims
- q8_0 K/V in the QSA decode (WMMA, GQA 12) and prefill kernels: reproduced at op level.
- q8_0 GQA 4 decode reported as not supported: reproduced.
- Mixed K/V types on prefill: reproduced, with the extra cases.
- f16 output unchanged: reproduced at op level and on the synthetic model.
- f16 speed unchanged: reproduced at op level.
- Strip-view sharing keeps the math: reproduced on the synthetic model only.
- Compute-buffer and KV memory figures: not tested.
- End-to-end q8_0 speed against master (+10% to +2.1x): not tested.
- KLD figures: not tested.
- Vulkan takes the masked route for q8_0: consistent with the op results (q8_0 not supported); not tested end to end.
Not tested
- Any real qwen4exp model, because the smallest official GGUF is 66 GB. This covers logits, KLD/PPL, decode,
llama-bench, memory, and an end-to-endLLAMA_QSA_SELECTED_KEYrun. - Vulkan op perf: the pre-existing
COL2IM_1Ddevice loss interrupted it.
|
Thanks for this PR and for the detailed answers during the review. The work continues in #276 (draft). It moves QSA attention to two ggml ops, Your three commits are the first three of #276 and keep you as author. Parts of them carry over into the new path:
Reviews on #276 are welcome. |
…refer_dense policies PLAN-v3 W4 (D3, D9, D10, §5, §6.2). - sparse-attn-attend-g1.cuh / .cu: sa_attend_g1<KT, VT, GQA> for every S_fast pair (f16, bf16, q8_0, q4_0) and GQA 4 / 8 / 12, 48 instances. The body is the decode kernel qsa_decode_wmma_partial (qsa-decode-wmma.cuh; git blame at the base: Piotr Wilkin 114 lines, Iggy Jackson 44, delgon 3), as C18's decode harness took it over. The loaders are those of C18 decision 2: - V is LDS-staged and transposed through a wave-private slot, for every type; - K is direct for f16 and q8_0. The q8_0 K loader is #219's decode q8 K loader (qsa-decode-wmma.cuh:63-74, from 68da419 = 509e8ee on this branch), taken as is; - K is split with v_permlanex16 for q4_0 and bf16. The cells come from the G = 1 plan (ascending quads with masks) instead of atomicCAS-deduplicated index rows, so the output is a function of the inputs. q * scale is computed in f32 and then rounded to f16 (op contract). Masked and padding cells are never loaded and score -inf. Streams and kv heads sit on grid.x. - The shape-only split count sa_g1_splits(n_q, n_sel, n_kv) is #219's decode rule (qsa-decode.cu:134-145, step 64), clamped to the plan's chunks and to grid.y. Split z takes chunks [z*len, (z+1)*len), len = ceil(C/S). With one split the attend writes dst itself. - sparse-attn-merge.cu: sa_merge_splits, a fixed-order merge with #219's qsa_decode_merge arithmetic; empty splits are skipped by select. - sa_select / get_alloc_size: the G1 partials [n_stream][n_q][n_head][splits][258] sit in the dst over-allocation (D12: no pool). The reserve takes the max over G in {1, 4} and over every n_q' <= n_q, because the G1 partials are not monotone in n_q (R1-C). - Census: keys sa_attend/G1/<KT>/<VT>/splits<class>/gqa<n>, with the classes 1, 2-5, 6-16, 17-33 and 34+ of the §14.2 band table, and the key sa_merge. 469 keys in all, so the ids recorded into HIP graphs are now uint16_t. - Procs ggml_backend_sparse_attn_group and ggml_backend_sparse_attn_prefer_dense (typedefs in ggml-backend.h), resolved per device. The group policy keeps the default n_q < 128 ? 1 : 4 until the AT-A rule lands (next commits). The shortcut has its own G (default rule until AT-W7PERF). GGML_CUDA_SA_FORCE=g1|g4 is read at every call. prefer_dense is a per-(pair, D4 n_q band) table whose default is dense for f16/f16 only. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
PLAN-v3 W4 (§14.1, §14.2, U34).
- New cases:
- the W4 n_q set {1, 2, 4, 8, 9, 64, 65, 66, 127, 263} x 1 and 2 streams x
every S_fast type with G1;
- every compiled G1 census key: S_fast^2 x GQA {4, 8, 12} x the 5 split
classes, at n_q 1 and n_sel 17 / 257 / 513 / 2051 / 4096;
- complete-quad rows;
- the G1 variants of the ported #219 shapes that PR219 ran through
qsa_decode: 512 x 257, 512 x 2051, 129 x 257, 130 x 32k, 200 x 64k and
130 x 270336. These are from #219's b604475 case list; their G4 variants
were already listed.
- sa_band_row: rows for the G1 split classes 6-16 (1.58e-7) and > 33 (1.69e-7).
Both are measured on the PR-verbatim decode kernel with R2-BOP's bands_dec:
- UNI fixtures: 12 shapes x 2 types x 3 seeds;
- TBO: the 88 G1 test dumps.
The existing UNI rows hold over the TBO dumps.
- The suite census coverage is gated only on unfiltered runs. A -p filter cannot
reach every key, so it is reported but not gated.
- GGML_SA_TEST_DUMP_MAX_KV (default 65536) caps the size of TBO dumps.
Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ric|portable PLAN-v3 §13 W5 (§5 "HIP tier selection per arch", §6.1, §6.2). Generic tier (sparse-attn-generic.cu): the G4 and G1 WMMA attends instantiated with K = V = SA_T_GEN, whose loaders convert every element of any type of S (f16, bf16, q8_0, q4_0, f32, q4_1, q5_0, q5_1, iq4_nl) through one runtime switch over the ggml type (sa_any_elem / sa_any_piece / sa_any_quad4, sparse-attn-loaders.cuh): to_float computed exactly as ggml-quants.c in f32, then one RNE rounding to f16, the CPU op's value. It runs every pair with a member outside S_fast, and every pair under GGML_CUDA_SA_FORCE=generic. Instances: sa_attend_g4<GEN, GEN, packed|direct, plain, 4|8|12>, sa_attend_fixup<GEN, GEN, plain>, sa_attend_g1<GEN, GEN, 4|8|12>, and sa_pack_v<SA_T_GEN> in sparse-attn-pack.cu. Workspaces are the S_fast layouts, so get_alloc_size is unchanged; no gated instance (gate_ok false, the MUL runs unfused). The generic K and direct-V conversions run after the barriers (the S_fast raw loads run before): converting before them spilled the GQA 12 instances; the direct-V GQA 12 instance targets 7 waves per EU (209 VGPRs, no scratch) instead of 8. Portable tier (sparse-attn-portable.cu): one scalar kernel, block (stream, query, kv head), thread d = dim d, no WMMA / v_permlanex16 / cross-lane operation (only __syncthreads and LDS), any plan G, any type of S via sa_any_elem; the CPU op's per-cell arithmetic with FP contraction off. It runs on every HIP arch other than RDNA3.5 (the WMMA tiers stay selected on GGML_CUDA_CC_IS_RDNA3_5 only) and under GGML_CUDA_SA_FORCE=portable; no workspace. sa_select (sparse-attn-attend-g4.cu) picks the tier; GGML_CUDA_SA_FORCE is parsed once (vpacked, vdirect, generic, portable; g1 / g4 stay the group policy's). The census gains sa_generic/G4/<VL>/gqa<n>, sa_generic/G1/splits<c>/gqa<n>, sa_generic/fixup, sa_generic/pack and sa_portable/G<g> (494 keys); the census skip proc now takes the device, so a HIP arch that runs the portable tier excludes the WMMA keys and RDNA3.5 excludes the portable keys unless forced. The generic G4 / G1 instances are the kernel bodies ported from PR #219's qsa3_attn_kernel / qsa_decode_wmma_partial in W3 / W4, extended here with the generic loader. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…e tiers The Vulkan half of the sparse attention rewrite (PLAN-v3 §5, §6.3, W6). No graph uses the ops yet (W7). Plan (sparse_attn_plan_rows.comp): G = 1, whole dst bit-exact to the CPU op. 32-bit storage only, no subgroup operation, its own host gate (up to 256 invocations, (WG + WG / 16 + 2) * 4 B shared). The sort runs in the storage buffer, so n_sel has no shared-memory limit. Attend, three tiers through one shape-only selection (ggml_vk_sa_select: supports_op, get_alloc_size, census, dispatch): - cm (sparse_attn_cm.comp, from flash_attn_sel_cm.comp): RADV RDNA3 WMMA fragments over plan entries. Masked and padding cells are selected to zero K and V and score -inf, so stored NaN or inf cannot reach the output. Packed f16 loaders for bf16, q8_0 and q4_0, flash_attn_dequant.glsl for f32, q4_1, q5_0, q5_1, iq4_nl. V direct is shipped for every type; staged and the dequant-once pack arm run under GGML_VK_SA_FORCE only (AT-B3). - scalar (sparse_attn.comp, from flash_attn_sel.comp): other 64-lane devices. - portable (sparse_attn_portable.comp): every other device. No extension, no subgroup operation, K and V read as 32-bit words, one invocation per query head, 2 KiB of shared memory, the CPU op's arithmetic with NoContraction. supports_op is true only when a pipeline exists for the shape on this device and every binding fits maxStorageBufferRange. The workspace has its own descriptor at round_up(nbytes, minStorageBufferOffsetAlignment), included in get_alloc_size, and every sparse node starts with an unconditional ggml_vk_sync_buffers, because the barrier tracker computes its ranges with ggml_nbytes and cannot see it. H_q runs in the kernels in fwht.comp's butterfly order; H_o is a dispatch of fwht.comp (FWHT_INPLACE: one binding). Split-K merge: sparse_attn_reduce.comp, without the clamp of flash_attn_split_k_reduce.comp, so a V that overflows f16 keeps its +-inf. Also: the policy procs (G = 1, prefer_dense default), the census (sa_plan/G1, sa_attend/vk/<tier>/<VL>/<KT>/<VT>, sa_merge/vk/splits<class>, sa_pack/vk/<T>, the list proc, skip by tier and forcing switch), GGML_VK_SA_FORCE, GGML_VK_SA_CAP_MASK and GGML_VK_SA_MAX_Q test switches. The old sel pipelines stay until W13 (the AT-B2 reference). sa_q8x2 / sa_q4x2 in sparse_attn_load.glsl adapt the q8 bit trick of PR #219 (qsa3_q8x2_to_h2, via ggml-cuda/sparse-attn-q8.cuh). Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…, guard, fit probe, trace Graph switch of PLAN-v3 §13 W7. - Compact CB rows and the shortcut's all-visible rows go to ggml_sparse_attn_plan + ggml_sparse_attn for every K/V pair (rot 0: rotation stays in the graph until W10). Shortcut: backend prefer_dense policy per (pair, n_q band), LLAMA_QSA_PREFER_DENSE for AT-W7PERF. G from the backend group policy. Split streams on ne[3] at any n_tps. The rows are named qsa_rows_cb-<il> / qsa_rows_av-<il>; the all-visible rows are built once per graph, read through a view per layer. The plan node is expanded right after its rows, before the OVL kind-4 region. - Eligibility no longer tests the cache types, the probe, the 1M bound, -fa or -nkvo. The probe, LLAMA_QSA_SELECTED_KEY and selected_key_attn are gone. qwen4exp's hybrid-idx cache keeps V not transposed under any -fa (D21). Non-compact ubatches keep the old masked route until W8. - Init errors: QSA with --split-mode tensor, n_ctx_seq above the tested 2^21 + 4 cells. - Pins (D15): plan and attend on the backend of the device of the layer's K buffer, the CPU for a host K buffer, or the named host-KV copy route; the shortcut attention over a host K buffer per AT-W7PERF (d). - Guard (§10): split_only pass per reserve graph (main, MTP, fit probe) and a runtime pass per new graph, over llama's gf, with supports_op on the pinned device, one consumer per plan and a non-vacuity count. - Fit probe (§7.1.7): no_alloc reserves take the per-backend max over every reserve graph. - LLAMA_QSA_TRACE=1 (§14.3): producer x route x context per executed ubatch, CPU counts and guard counters at exit; the tools print the backend dispatch census at exit as QSA_CENSUS <key> <count>. The init log line with the K/V types adapts #219's b604475. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
The four test classes exercised FLASH_ATTN_EXT + src[5] on PR #219's QSA kernels (qsa-prefill.cu, qsa-decode.cu), which W13 deletes; the maskless form (src[5] without a mask) can no longer be built once ggml_flash_attn_ext_add_top_k asserts a mask (PLAN-v3 §2.3, §11). Their coverage lives in the SPARSE_ATTN / SPARSE_ATTN_PLAN cases of PLAN-v3 §14.1: the #219 shapes and cell formulas (SA_ROWS_PR, SA_ROWS_PRBLK), the q8_0 and mixed K/V list of b604475, poison, duplicates, deep caches and GQA 4/8/12. QSA_SCORE, QSA_STRIP and QSA_EXPAND stay. Comments that named the deleted classes or kernels by symbol now name their source by commit and file. Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… and the maskless FA dispatch PLAN-v3 §11 (ggml-cuda). QSA layers run GGML_OP_SPARSE_ATTN_PLAN + GGML_OP_SPARSE_ATTN since W7/W8, so nothing builds a FLASH_ATTN_EXT that these kernels take. Deleted: - qsa-prefill.cu/.cuh, qsa-decode.cu/.cuh, qsa-decode-wmma.cuh (with QSA_DIRECT, GGML_QSA_RANKSORT, QSA_DECODE_MAX_QUERIES); - fattn.cu: the QSA dispatch in ggml_cuda_flash_attn_ext, the abort for a maskless selected-key op, the maskless branch of ggml_cuda_flash_attn_ext_supported, ggml_cuda_qsa_gate_ok, and the QSA exclusion in ggml_cuda_fa7_gate_ok; - ggml-cuda.cu: the qsa-prefill branch of the FA gate fusion (the gate fusion of QSA layers is the SPARSE_ATTN one, W3); the FA one keeps fa7; - common.cuh: GGML_QSA_MAX_KEYS. A maskless FLASH_ATTN_EXT + src[5] can no longer be built (the next ggml commit asserts a mask), so no op reaches the dense kernels with its visibility only in src[5]. #219's pieces that the rewrite keeps live in sparse-attn-q8.cuh (q8 -> half), sparse-attn-attend-g1.cuh (decode q8 K loader) and sparse-attn-attend-g4.cuh (block-w q8 K addressing), ported earlier with Co-authored-by trailers; their provenance comments now name the #219 kernels by file and commit, not by symbol. Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
PLAN-v3 §2.3. The top-k list is a hint that backends may ignore, so the kq_mask must carry the same selection; a FLASH_ATTN_EXT with src[5] and no mask (the maskless form PR #219's QSA kernels took) attended to the whole cache on any kernel that ignored the list. QSA's maskless selection is now GGML_OP_SPARSE_ATTN_PLAN + GGML_OP_SPARSE_ATTN, and the only remaining caller, DSA (deepseek4.cpp:760 through build_attn_mha), passes a mask, as does test_flash_attn_ext_top_k. glm5-next passes its selection as the kq_mask and no top_k (glm5-next.cpp:1083). Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… lies
The online softmax of the CPU op starts with mx = -inf. When a row's first
attended cell (ascending order) scored exactly -inf, `sc > mx` was false,
so p = expf(-inf - -inf) = NaN, l became NaN and the row was written as 0.
The same -inf cell after a finite one gave p = 0 and a normal row, so the
reference result depended on cell order. The HIP portable tier, the G4
exact fixup, the Vulkan portable tier and the O_CON host oracle copied that
arithmetic. The HIP G4 / G1 WMMA attends took p = 0 and wrote the softmax
over the other cells, and the G4 result even depended on whether an
unrelated V half of the block made the fixup recompute it. By code
reading (not run), the Vulkan cm attend gave NaN for a step whose live
cells all scored -inf (corr = exp(-inf - -inf)), and the scalar tier for
such a block (weight = exp(-inf - -inf)).
A -inf score comes from an f16 K or q element at +-inf (ggml.h item 1: a
bf16 / f32 / q8_0 K value past 65504, or a stored f16 -inf) times a q
element of the other sign.
The rule (ggml.h item 3) is now: a cell whose score is -inf has p = 0
wherever it lies; a row whose cells all score -inf has l = 0 and gives 0.
- CPU op, O_CON (sparse-attn-ref.h), HIP portable, HIP G4 fixup, Vulkan
portable: p = (s == -inf) ? 0 : exp(s - m).
- Vulkan scalar: weight = (s == -inf) ? 0 : exp(s - new_max); an invalid key
already scores -inf there.
- Vulkan cm: the exponentials are taken against m_ref = 0 when the step's
running max is still -inf, so a -inf cell gets 0 and a NaN cell keeps NaN.
Every result that had no -inf score in a row's first step is unchanged
bit for bit (the selects only differ when the running max is -inf).
Test: test-backend-ops SPARSE_ATTN ",leadneginf" (f16 / q8_0 / bf16;
G1 n_q 1 n_sel 2051, n_q 9 n_sel 48, n_q 66 n_sel 257; G4 n_q 4 and 66).
Query 0 selects cells 0 .. 15 (the first 4 quads: the whole first step of
the HIP G4 / G1 and Vulkan cm attends), whose K rows of KV head 0 score
-inf. The CPU check requires the KV head 0 rows to equal, bit for bit,
O_CON over the rows without those cells, which has no -inf arithmetic.
- Before: CPU 15/15 FAIL ("query 0 rows of KV head 0 zero; 3072 values
... differ"); with the CPU fixed and the Vulkan portable shader not,
lavapipe FAILs the 9 G1 cases (ERR 0.94 / 0.092).
- After: CPU 15/15 OK, lavapipe 9/9 OK (G4: not supported on Vulkan).
- HIP ROCm0 and RADV: NOT RUN (~/gpu.lock held by a process of an
earlier step).
The touched HIP / Vulkan tiers and O_CON adapt PR #219's code (their file
headers; commits c0ef4a8, 3b93e6a, 06d8072, 4e6328f).
Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ning max is -inf ggml.h item 5: a row with an attended cell whose score is NaN gives 0 (the CPU op: l is NaN, `l > 0 ? acc / l : 0`). The G4 and G1 WMMA attends build the step max with fmaxf, which drops a NaN. In a step whose live cells of a row all scored NaN (or -inf) before any finite score, mnew / next stayed -inf and `p = mnew == -inf ? 0 : exp2f(...)` gave the NaN cell weight 0: the row came out as the softmax over its other cells. G1 does the same at the first chunk of every split. No fixup or merge step looks for a NaN K. The exponentials are now taken against mref = 0 when the running max is still -inf: a -inf (or masked) cell gives exp2f(-inf) = 0 and a NaN cell keeps exp2f(NaN) = NaN, so l becomes NaN and the epilogue / split-K merge (which keeps a NaN split, d7e4656) writes 0. With a finite running max p is computed as before, so every other result is unchanged bit for bit. The per-element select is replaced by one select per step. The kernels' online softmax is PR #219's (qsa3_attn_kernel and the decode WMMA partial of 94e0868, as sparse-attn-attend-g4.cuh / -g1.cuh say). Test: test-backend-ops SPARSE_ATTN ",leadnan" (the lead shapes of the previous commit): cells 0 .. 15 of query 0 have NaN K rows (KV head 0), so they fill query 0's first step; the CPU check requires query 0's KV head 0 rows to be 0 and its KV head 1 rows not. - CPU 15/15 OK and lavapipe 9/9 OK, before and after (the CPU and portable tiers were right). - HIP ROCm0: NOT RUN (~/gpu.lock held by a process of an earlier step). Expected before: the G4 / G1 cases FAIL (finite rows against the CPU's 0); after: OK. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ip input views hip: qsa_decode (wmma) and qsa_prefill read q8_0 K/V. The decode kernel dequantizes in registers; the prefill pack converts while packing (the direct f16 path is skipped for q8_0). Both use the same half product as dequantize_block_q8_0_f16. Complete-block selection now also takes q8_0 K/V when every QSA layer runs on ROCm (selected_key_q8), so a q8_0 cache no longer falls back to the masked per-cell top-k. qwen4exp: the masked top-k path took a fresh view of the KQ mask and the QSA bias for every 512-query score strip in every layer. The scheduler gives each view of a host input its own copy, kept for the whole graph, so this made n_layers x n_strips copies. With Signal-3.8-Flash-Next Q4_K_XL, -ub 4096 and a q8_0 cache, the ROCm0 compute buffer was 7193 MiB at 32k (vs 3009 before bb030af) and grew about 0.15 MiB per context cell (~41 GB at 262k), so the MTP draft context hit OOM. The views are now built once per graph and shared: 2969 MiB at 32k, 10.7 GB at 262k. Perplexity is bit-identical. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4rLkt7MokKFKji9hxCaev (cherry picked from commit 68da419) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…tests - selected_key_attn now comes from a probe op with the real K/V types, at one query and at 513 (past the decode kernels). selected_key_q8 and the "ROCm" backend-name check are gone: a q8_0 cache on a model whose GQA ratio is not 12 (q8_0 decode is WMMA-only) or on Vulkan (flash_attn_sel is f16-only) now takes the masked route instead of falling back to CPU. LLAMA_QSA_SELECTED_KEY=1 forces the selected-key route for q8_0 too. - The QSA attention log line names the cache types it was decided for. - strip_views is keyed on the strip size too, which varies with the layer's compress ratio. - test-backend-ops: q8_0 and mixed K/V variants of the maskless QSA decode and prefill tests. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F (cherry picked from commit b604475) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
qsa_prefill_impl1 packed the whole q8_0 K and V cache to f16 on every ubatch in every QSA layer, because the direct reads were f16-only: O(n_kv) work per ubatch and f16-sized pool buffers, eating into what a q8_0 cache saves. qsa3_attn_kernel now takes a Q8 flag: a direct K chunk (dims 32w .. 32w+31 of a key) is exactly q8_0 block w, loaded as aligned dwords and realigned (the block offset is wave-uniform); direct V reads each key's byte and scale. Both dequantize in registers with the decode kernel's exact half conversion, so every QSA_DIRECT mode stays bit-identical to the pack (llama-perplexity KLD vs QSA_DIRECT=0 at the floor of identical runs; test-backend-ops passes in modes 0/1/2/auto). Mixed K/V types still pack. The auto heuristic is shared with f16: K direct, V direct too when the attention is small against the cache. q8_0 at b/ub 4096 (Signal-3.8- Flash-Next Q4_K_XL): K direct 1347 / 1272 t/s vs pack 1350 / 1284 at pp4096 depth 0 / 32k, within noise. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F (cherry picked from commit 94e0868) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…, determinism runs
test-backend-ops (PLAN-v3 §14.1):
- test_sparse_attn_plan: n_q {1,2,8,127,128,129,512,513,4096} x n_sel
{1,257,2051,4096} x n_kv {4,2051,4096,65536,270336,1048576}, rows
ascending / permuted / duplicates / -1 / out-of-range / all -1 / mixed /
complete quads, G {1,4}, 1-2 streams, plain / interleaved / strided rows
(169 cases). err() is an exact whole-dst comparison (max error 0) and
verify_reference() memcmps the dst with the C3 oracle on every backend.
- test_sparse_attn: every pair of the 9 types of S, both V-loader regimes
for every S_fast pair, n_q up to 4096, all-visible rows, n_kv 2051 with
views of 2052 rows ending at their buffer's end (K last or V last),
n_kv up to 1048576 and 2^21 + 4 (f16 / q8_0), GQA 4/8/12, rotations,
2 streams, empty rows, poison (NaN / inf values and scales in cells no
query selects, reach of a padded quad asserted on the plan), V-side
overflow (bf16, q8_0, stored inf; finite-only NMSE plus the expected
inf set), a non power-of-two scale, and the QSA_*_MASKLESS shapes with
their cell formulas, including the q8_0 / mixed K/V case list #219 added
(301 cases). run_whole_graph with fusion_test_nodes = {attend}. On the
CPU backend the bound is 0 and verify_reference() checks the output bit
for bit against the O_CON host reference; on other backends the bound is
the §14.2 band of the class the dispatch census reports (keys
sa_attend/G4/..., sa_attend/G1/.../splits<n>, listed by the census proc
ggml_backend_debug_dispatch_census_list, a NULL-terminated key array the
GPU work items implement); no class is a FAIL.
- determinism hook n_determinism_runs (2 for both ops): backend1 is
computed again and its compared outputs memcmp'd with the first run.
- --fail-unsupported: a "not supported" result FAILS unless the case is on
its backend's expected-unsupported list (Vulkan: G = 4, K/V views past
1 GiB); engagement checks become mandatory (implied opt-in, a missing
census proc fails).
tests/sparse-attn-ref.h: the C3 oracle (C3's std::map cpu_plan, G and
streams generalised, ggml.h layout) and O_CON (R1-M-Lab A's
oracle_group(O_CON), generalised); both test TUs are built with
-ffp-contract=off.
tests/test-sparse-attn-plan-oracle.cpp (ctest): 1080 synthetic plans
memcmp'd against the C3 oracle (dst pre-filled with 0xA5), the
over-allocation check (a buffer type whose get_alloc_size over-allocates
both ops allocates and computes through ggml-alloc without the
ggml-backend.cpp alloc-size assert, same output), and captured rows files
(C3 / C5 record format, --shuffle as c3_plan).
Results (strix-002:~/dev/wt_rewrite_logs/W1): SPARSE_ATTN_PLAN 169/169 and
SPARSE_ATTN 301/301 on CPU with --fail-unsupported in the CPU-only, HIP and
Vulkan builds; a mutated reference (P not rounded / a stray mask bit) fails
85/91 and 24/40 of the selected cases; plan vs C3 oracle on the
recaptured C3 rows 288/288 identical.
Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
GGML_OP_SPARSE_ATTN_PLAN on HIP (PLAN-v3 §2.1, §6.2, §13 W2), whole dst byte-identical to the CPU op and to the C3 oracle: - sparse-attn-plan.cu: three kernels on the op's stream, no pool use. sa_plan_init writes the header (n_bad = 0) and the zero gaps; sa_plan_rows (one block per query row) validates, counts n_bad and, for a row whose valid cells are not already strictly ascending with every invalid entry after them, sorts (in-place bitonic network in its flip form, no power-of-two padding) and dedups it into the scratch; a row already in that form only gets a marker and is read from sel by the merge; sa_plan_merge<G> (512 lanes for G = 4, 256 for G = 1) merges the G sorted rows of a group by quad with C3's ASC lane split, then writes the ggml.h padding up to cap (16/8-byte stores). Rows or groups too long for LDS run the same algorithms on global memory (GGML_CUDA_SA_PLAN_GLOBAL=1 forces it for tests). Ported from the union builder qsa3_rows_kernel / qsa3_merge_kernel (qsa-prefill.cu:28-240; git blame at ea5285d: Piotr Wilkin and Gaetan Puleo, no #219 line) and C3's sa_merge<ASC, 512>. - supports_op true on every HIP device (integer kernels); false on CUDA builds (D22). get_alloc_size = max dst over the G table + the sort / dedup scratch (§2.1, P2-15); compute asserts that dst owns that over-allocation. - sparse-attn-census.h: the census keys are generated from the G table that also instantiates and dispatches the merge (sa_plan/G1, sa_plan/G4), plus qsa_expand (counted where the fused expand runs). HIP procs ggml_backend_debug_dispatch_census_{reset,count,get,list,skip}; GGML_CUDA_DISPATCH_CENSUS_LOG=1 prints the census at exit. - HIP graphs: the census ids dispatched while a graph is captured are recorded into ggml_cuda_graph::census_ids and counted again at every replay, so the census counts launches with graphs on or off (in-model llama-bench: qsa_expand=267 either way). Results (strix-002, gfx1151): -o SPARSE_ATTN_PLAN -b ROCm0 --fail-unsupported 185/185 with graphs on, graphs off and the forced global-memory kernels; C3 harness on recaptured d131k rows, G4 0.719 ms/layer text, 0.831 random (gate <= 1.0), every layer bit-exact vs the CPU op and the C3 oracle; 0 VGPR spills, 0 scratch, -Werror clean (scripts/qsa-validation/summaries/w2_plan_c3.md). Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…#219) The element conversions and the K / V loaders of the HIP sparse-attention WMMA kernels (PLAN-v3 §2.2 contract item 1, §6.2, D8, D10): - sparse-attn-q8.cuh: sa_q8x2_to_h2 is PR #219's qsa3_q8x2_to_h2 / qd_q8x2_to_h2 (qsa-prefill.cu / qsa-decode-wmma.cuh of 94e0868), one copy instead of three; C18 checked it bit-equal to dequantize_block_q8_0_f16 (4905 prefill + 4320 decode bitwise checks). sa_q4x2_to_h2 is C18's q4_0 trick (0x6400 | q, minus 1032). sa_bf2_to_h2 / sa_bf1_to_h convert bf16 with one RNE rounding and +-inf on overflow (the op contract and to_fp16); C18's helper saturated to +-65504, this one does not. - sparse-attn-loaders.cuh: the type ids of the WMMA tiers, the split K piece loaders (half-wave dequant + v_permlanex16, C18 "X"), the split-gather direct V loaders, the per-cell select of masked V, and the traits: K split for every type in the G4 attend (C18 measured f16 split = direct: 12.43 / 12.60 ms wiki d4k, 16.32 / 16.33 d131k; direct f16 K does not fit 192 VGPRs in the GQA 12 instances with a direct quantized V); V pack-limit trait default CAPPED for every type (packed iff n_kv < 64 * n_q, OWNER decision 2026-11-05). Not used by any TU yet (the G4 attend lands next). Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
GGML_OP_SPARSE_ATTN with a G = 4 plan on RDNA3.5 (PLAN-v3 §6.2, §13 W3), rot_q = rot_o = 0; G1 (W4), generic / portable tiers (W5) and the in-op rotation (W10) stay unsupported (supports_op false). - sparse-attn-attend-g4.cuh: sa_attend_g4<KT, VT, VL, EPI, GQA>, the PR qsa3_attn_kernel body (qsa-prefill.cu at 94e0868, as C18 took it over: Q prologue, WMMA order, online softmax, 2 barriers, epilogue) with the loaders of sparse-attn-loaders.cuh, no mask path, EPI plain or gated (+ f16 / bf16 aux store for an MMB reader) as a template, rows = 4 queries x GQA {4, 8, 12}, streams on grid.z, the ggml.h plan layout, q * scale in f32. Masked-off cells contribute nothing: K / V of cells no query of the group attends are zeroed by select, scores of cells the row's query does not attend are -inf. A non-finite V half of a cell attended by only some queries of the group would give 0 * inf = NaN to the others through the shared PV WMMA, so it is taken out of the WMMA: packed V by sa_pack_v (written as 0, quad flagged), direct V by an in-loop check (one packed FMA per dword) that flags the block; sa_attend_fixup recomputes the blocks that touch a flagged quad or were flagged, with the CPU op's per-cell arithmetic. The fixup keeps the WMMA loop free of exact-path code, which did not fit 192 VGPRs at GQA 12; the check lives in the pack for packed V because in the loop it cost about 4 % of the kernel time on the C18 rows (W3 lab). - sparse-attn-attend-g4-{f16,bf16,q8_0,q4_0}.cu: the 4 x 48 attend and 4 x 8 fixup instances, one TU per K type. - sparse-attn-pack.cu: sa_pack_v<T> (the PR qsa_pack_v indexing, per stream and kv head) into the attend dst over-allocation (no pool), with the quad flags and an any-flag for the fixup. - sparse-attn-attend-g4.cu: sa_select (instance, V loader), supports_op, get_alloc_size = round_up(nbytes, 256) + max over G {1, 4} and n_q' <= n_q (and runtime n_kv' <= n_kv) of the workspace: CAPPED pack min(4 ceil(n_kv / 4), 64 n_q) cells x 512 B x n_head_kv x n_stream with its flags, or the direct path's per-(block, wave) flags; dispatch; the test switch GGML_CUDA_SA_FORCE=vpacked|vdirect, and the census skip for the keys a forced process cannot dispatch. - sparse-attn-census.h: keys generated from the instance tables: sa_attend/G4/<KT>/<VT>/<packed|direct>/<plain|gated>/gqa<n> (the §6.2 key is the prefix of its 3 gqa instances), sa_fixup/G4/<KT>/<VT>/<EPI>, sa_pack/<VT>. - ggml-cuda.cu: get_alloc_size / compute / supports_op cases; the gate fusion matcher SPARSE_ATTN -> [views] -> CONT(gate) -> SIGMOID -> MUL (the FA branch stays until W13), with the overlap check extended to the plan and the node's own workspace; the census skip proc consults the forcing switch. - common.cuh / ggml-cuda.cu: the HIP graph node properties include the source types. Two graphs whose only change is an F16 <-> BF16 source (same pointers, ne, nb) were replayed with the stale kernel: found by the W3 cases (bf16 V after f16 V at equal addresses, NMSE 0.5). Resources: 228 sparse-attn kernels, 0 spills, 0 scratch (-Werror TU builds, scripts/hip/gcn-cdna-vgpr-check.py parse_assembly). The kernel body, the q8_0 helper it calls and the direct-V switch n_kv >= 64 * n_q port #219 code. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…refer_dense policies PLAN-v3 W4 (D3, D9, D10, §5, §6.2). - sparse-attn-attend-g1.cuh / .cu: sa_attend_g1<KT, VT, GQA> for every S_fast pair (f16, bf16, q8_0, q4_0) and GQA 4 / 8 / 12, 48 instances. The body is the decode kernel qsa_decode_wmma_partial (qsa-decode-wmma.cuh; git blame at the base: Piotr Wilkin 114 lines, Iggy Jackson 44, delgon 3), as C18's decode harness took it over. The loaders are those of C18 decision 2: - V is LDS-staged and transposed through a wave-private slot, for every type; - K is direct for f16 and q8_0. The q8_0 K loader is #219's decode q8 K loader (qsa-decode-wmma.cuh:63-74, from 68da419 = 509e8ee on this branch), taken as is; - K is split with v_permlanex16 for q4_0 and bf16. The cells come from the G = 1 plan (ascending quads with masks) instead of atomicCAS-deduplicated index rows, so the output is a function of the inputs. q * scale is computed in f32 and then rounded to f16 (op contract). Masked and padding cells are never loaded and score -inf. Streams and kv heads sit on grid.x. - The shape-only split count sa_g1_splits(n_q, n_sel, n_kv) is #219's decode rule (qsa-decode.cu:134-145, step 64), clamped to the plan's chunks and to grid.y. Split z takes chunks [z*len, (z+1)*len), len = ceil(C/S). With one split the attend writes dst itself. - sparse-attn-merge.cu: sa_merge_splits, a fixed-order merge with #219's qsa_decode_merge arithmetic; empty splits are skipped by select. - sa_select / get_alloc_size: the G1 partials [n_stream][n_q][n_head][splits][258] sit in the dst over-allocation (D12: no pool). The reserve takes the max over G in {1, 4} and over every n_q' <= n_q, because the G1 partials are not monotone in n_q (R1-C). - Census: keys sa_attend/G1/<KT>/<VT>/splits<class>/gqa<n>, with the classes 1, 2-5, 6-16, 17-33 and 34+ of the §14.2 band table, and the key sa_merge. 469 keys in all, so the ids recorded into HIP graphs are now uint16_t. - Procs ggml_backend_sparse_attn_group and ggml_backend_sparse_attn_prefer_dense (typedefs in ggml-backend.h), resolved per device. The group policy keeps the default n_q < 128 ? 1 : 4 until the AT-A rule lands (next commits). The shortcut has its own G (default rule until AT-W7PERF). GGML_CUDA_SA_FORCE=g1|g4 is read at every call. prefer_dense is a per-(pair, D4 n_q band) table whose default is dense for f16/f16 only. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
PLAN-v3 W4 (§14.1, §14.2, U34).
- New cases:
- the W4 n_q set {1, 2, 4, 8, 9, 64, 65, 66, 127, 263} x 1 and 2 streams x
every S_fast type with G1;
- every compiled G1 census key: S_fast^2 x GQA {4, 8, 12} x the 5 split
classes, at n_q 1 and n_sel 17 / 257 / 513 / 2051 / 4096;
- complete-quad rows;
- the G1 variants of the ported #219 shapes that PR219 ran through
qsa_decode: 512 x 257, 512 x 2051, 129 x 257, 130 x 32k, 200 x 64k and
130 x 270336. These are from #219's b604475 case list; their G4 variants
were already listed.
- sa_band_row: rows for the G1 split classes 6-16 (1.58e-7) and > 33 (1.69e-7).
Both are measured on the PR-verbatim decode kernel with R2-BOP's bands_dec:
- UNI fixtures: 12 shapes x 2 types x 3 seeds;
- TBO: the 88 G1 test dumps.
The existing UNI rows hold over the TBO dumps.
- The suite census coverage is gated only on unfiltered runs. A -p filter cannot
reach every key, so it is reported but not gated.
- GGML_SA_TEST_DUMP_MAX_KV (default 65536) caps the size of TBO dumps.
Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ric|portable PLAN-v3 §13 W5 (§5 "HIP tier selection per arch", §6.1, §6.2). Generic tier (sparse-attn-generic.cu): the G4 and G1 WMMA attends instantiated with K = V = SA_T_GEN, whose loaders convert every element of any type of S (f16, bf16, q8_0, q4_0, f32, q4_1, q5_0, q5_1, iq4_nl) through one runtime switch over the ggml type (sa_any_elem / sa_any_piece / sa_any_quad4, sparse-attn-loaders.cuh): to_float computed exactly as ggml-quants.c in f32, then one RNE rounding to f16, the CPU op's value. It runs every pair with a member outside S_fast, and every pair under GGML_CUDA_SA_FORCE=generic. Instances: sa_attend_g4<GEN, GEN, packed|direct, plain, 4|8|12>, sa_attend_fixup<GEN, GEN, plain>, sa_attend_g1<GEN, GEN, 4|8|12>, and sa_pack_v<SA_T_GEN> in sparse-attn-pack.cu. Workspaces are the S_fast layouts, so get_alloc_size is unchanged; no gated instance (gate_ok false, the MUL runs unfused). The generic K and direct-V conversions run after the barriers (the S_fast raw loads run before): converting before them spilled the GQA 12 instances; the direct-V GQA 12 instance targets 7 waves per EU (209 VGPRs, no scratch) instead of 8. Portable tier (sparse-attn-portable.cu): one scalar kernel, block (stream, query, kv head), thread d = dim d, no WMMA / v_permlanex16 / cross-lane operation (only __syncthreads and LDS), any plan G, any type of S via sa_any_elem; the CPU op's per-cell arithmetic with FP contraction off. It runs on every HIP arch other than RDNA3.5 (the WMMA tiers stay selected on GGML_CUDA_CC_IS_RDNA3_5 only) and under GGML_CUDA_SA_FORCE=portable; no workspace. sa_select (sparse-attn-attend-g4.cu) picks the tier; GGML_CUDA_SA_FORCE is parsed once (vpacked, vdirect, generic, portable; g1 / g4 stay the group policy's). The census gains sa_generic/G4/<VL>/gqa<n>, sa_generic/G1/splits<c>/gqa<n>, sa_generic/fixup, sa_generic/pack and sa_portable/G<g> (494 keys); the census skip proc now takes the device, so a HIP arch that runs the portable tier excludes the WMMA keys and RDNA3.5 excludes the portable keys unless forced. The generic G4 / G1 instances are the kernel bodies ported from PR #219's qsa3_attn_kernel / qsa_decode_wmma_partial in W3 / W4, extended here with the generic loader. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…e tiers The Vulkan half of the sparse attention rewrite (PLAN-v3 §5, §6.3, W6). No graph uses the ops yet (W7). Plan (sparse_attn_plan_rows.comp): G = 1, whole dst bit-exact to the CPU op. 32-bit storage only, no subgroup operation, its own host gate (up to 256 invocations, (WG + WG / 16 + 2) * 4 B shared). The sort runs in the storage buffer, so n_sel has no shared-memory limit. Attend, three tiers through one shape-only selection (ggml_vk_sa_select: supports_op, get_alloc_size, census, dispatch): - cm (sparse_attn_cm.comp, from flash_attn_sel_cm.comp): RADV RDNA3 WMMA fragments over plan entries. Masked and padding cells are selected to zero K and V and score -inf, so stored NaN or inf cannot reach the output. Packed f16 loaders for bf16, q8_0 and q4_0, flash_attn_dequant.glsl for f32, q4_1, q5_0, q5_1, iq4_nl. V direct is shipped for every type; staged and the dequant-once pack arm run under GGML_VK_SA_FORCE only (AT-B3). - scalar (sparse_attn.comp, from flash_attn_sel.comp): other 64-lane devices. - portable (sparse_attn_portable.comp): every other device. No extension, no subgroup operation, K and V read as 32-bit words, one invocation per query head, 2 KiB of shared memory, the CPU op's arithmetic with NoContraction. supports_op is true only when a pipeline exists for the shape on this device and every binding fits maxStorageBufferRange. The workspace has its own descriptor at round_up(nbytes, minStorageBufferOffsetAlignment), included in get_alloc_size, and every sparse node starts with an unconditional ggml_vk_sync_buffers, because the barrier tracker computes its ranges with ggml_nbytes and cannot see it. H_q runs in the kernels in fwht.comp's butterfly order; H_o is a dispatch of fwht.comp (FWHT_INPLACE: one binding). Split-K merge: sparse_attn_reduce.comp, without the clamp of flash_attn_split_k_reduce.comp, so a V that overflows f16 keeps its +-inf. Also: the policy procs (G = 1, prefer_dense default), the census (sa_plan/G1, sa_attend/vk/<tier>/<VL>/<KT>/<VT>, sa_merge/vk/splits<class>, sa_pack/vk/<T>, the list proc, skip by tier and forcing switch), GGML_VK_SA_FORCE, GGML_VK_SA_CAP_MASK and GGML_VK_SA_MAX_Q test switches. The old sel pipelines stay until W13 (the AT-B2 reference). sa_q8x2 / sa_q4x2 in sparse_attn_load.glsl adapt the q8 bit trick of PR #219 (qsa3_q8x2_to_h2, via ggml-cuda/sparse-attn-q8.cuh). Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…, guard, fit probe, trace Graph switch of PLAN-v3 §13 W7. - Compact CB rows and the shortcut's all-visible rows go to ggml_sparse_attn_plan + ggml_sparse_attn for every K/V pair (rot 0: rotation stays in the graph until W10). Shortcut: backend prefer_dense policy per (pair, n_q band), LLAMA_QSA_PREFER_DENSE for AT-W7PERF. G from the backend group policy. Split streams on ne[3] at any n_tps. The rows are named qsa_rows_cb-<il> / qsa_rows_av-<il>; the all-visible rows are built once per graph, read through a view per layer. The plan node is expanded right after its rows, before the OVL kind-4 region. - Eligibility no longer tests the cache types, the probe, the 1M bound, -fa or -nkvo. The probe, LLAMA_QSA_SELECTED_KEY and selected_key_attn are gone. qwen4exp's hybrid-idx cache keeps V not transposed under any -fa (D21). Non-compact ubatches keep the old masked route until W8. - Init errors: QSA with --split-mode tensor, n_ctx_seq above the tested 2^21 + 4 cells. - Pins (D15): plan and attend on the backend of the device of the layer's K buffer, the CPU for a host K buffer, or the named host-KV copy route; the shortcut attention over a host K buffer per AT-W7PERF (d). - Guard (§10): split_only pass per reserve graph (main, MTP, fit probe) and a runtime pass per new graph, over llama's gf, with supports_op on the pinned device, one consumer per plan and a non-vacuity count. - Fit probe (§7.1.7): no_alloc reserves take the per-backend max over every reserve graph. - LLAMA_QSA_TRACE=1 (§14.3): producer x route x context per executed ubatch, CPU counts and guard counters at exit; the tools print the backend dispatch census at exit as QSA_CENSUS <key> <count>. The init log line with the K/V types adapts #219's b604475. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
The four test classes exercised FLASH_ATTN_EXT + src[5] on PR #219's QSA kernels (qsa-prefill.cu, qsa-decode.cu), which W13 deletes; the maskless form (src[5] without a mask) can no longer be built once ggml_flash_attn_ext_add_top_k asserts a mask (PLAN-v3 §2.3, §11). Their coverage lives in the SPARSE_ATTN / SPARSE_ATTN_PLAN cases of PLAN-v3 §14.1: the #219 shapes and cell formulas (SA_ROWS_PR, SA_ROWS_PRBLK), the q8_0 and mixed K/V list of b604475, poison, duplicates, deep caches and GQA 4/8/12. QSA_SCORE, QSA_STRIP and QSA_EXPAND stay. Comments that named the deleted classes or kernels by symbol now name their source by commit and file. Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… and the maskless FA dispatch PLAN-v3 §11 (ggml-cuda). QSA layers run GGML_OP_SPARSE_ATTN_PLAN + GGML_OP_SPARSE_ATTN since W7/W8, so nothing builds a FLASH_ATTN_EXT that these kernels take. Deleted: - qsa-prefill.cu/.cuh, qsa-decode.cu/.cuh, qsa-decode-wmma.cuh (with QSA_DIRECT, GGML_QSA_RANKSORT, QSA_DECODE_MAX_QUERIES); - fattn.cu: the QSA dispatch in ggml_cuda_flash_attn_ext, the abort for a maskless selected-key op, the maskless branch of ggml_cuda_flash_attn_ext_supported, ggml_cuda_qsa_gate_ok, and the QSA exclusion in ggml_cuda_fa7_gate_ok; - ggml-cuda.cu: the qsa-prefill branch of the FA gate fusion (the gate fusion of QSA layers is the SPARSE_ATTN one, W3); the FA one keeps fa7; - common.cuh: GGML_QSA_MAX_KEYS. A maskless FLASH_ATTN_EXT + src[5] can no longer be built (the next ggml commit asserts a mask), so no op reaches the dense kernels with its visibility only in src[5]. #219's pieces that the rewrite keeps live in sparse-attn-q8.cuh (q8 -> half), sparse-attn-attend-g1.cuh (decode q8 K loader) and sparse-attn-attend-g4.cuh (block-w q8 K addressing), ported earlier with Co-authored-by trailers; their provenance comments now name the #219 kernels by file and commit, not by symbol. Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
PLAN-v3 §2.3. The top-k list is a hint that backends may ignore, so the kq_mask must carry the same selection; a FLASH_ATTN_EXT with src[5] and no mask (the maskless form PR #219's QSA kernels took) attended to the whole cache on any kernel that ignored the list. QSA's maskless selection is now GGML_OP_SPARSE_ATTN_PLAN + GGML_OP_SPARSE_ATTN, and the only remaining caller, DSA (deepseek4.cpp:760 through build_attn_mha), passes a mask, as does test_flash_attn_ext_top_k. glm5-next passes its selection as the kq_mask and no top_k (glm5-next.cpp:1083). Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… lies
The online softmax of the CPU op starts with mx = -inf. When a row's first
attended cell (ascending order) scored exactly -inf, `sc > mx` was false,
so p = expf(-inf - -inf) = NaN, l became NaN and the row was written as 0.
The same -inf cell after a finite one gave p = 0 and a normal row, so the
reference result depended on cell order. The HIP portable tier, the G4
exact fixup, the Vulkan portable tier and the O_CON host oracle copied that
arithmetic. The HIP G4 / G1 WMMA attends took p = 0 and wrote the softmax
over the other cells, and the G4 result even depended on whether an
unrelated V half of the block made the fixup recompute it. By code
reading (not run), the Vulkan cm attend gave NaN for a step whose live
cells all scored -inf (corr = exp(-inf - -inf)), and the scalar tier for
such a block (weight = exp(-inf - -inf)).
A -inf score comes from an f16 K or q element at +-inf (ggml.h item 1: a
bf16 / f32 / q8_0 K value past 65504, or a stored f16 -inf) times a q
element of the other sign.
The rule (ggml.h item 3) is now: a cell whose score is -inf has p = 0
wherever it lies; a row whose cells all score -inf has l = 0 and gives 0.
- CPU op, O_CON (sparse-attn-ref.h), HIP portable, HIP G4 fixup, Vulkan
portable: p = (s == -inf) ? 0 : exp(s - m).
- Vulkan scalar: weight = (s == -inf) ? 0 : exp(s - new_max); an invalid key
already scores -inf there.
- Vulkan cm: the exponentials are taken against m_ref = 0 when the step's
running max is still -inf, so a -inf cell gets 0 and a NaN cell keeps NaN.
Every result that had no -inf score in a row's first step is unchanged
bit for bit (the selects only differ when the running max is -inf).
Test: test-backend-ops SPARSE_ATTN ",leadneginf" (f16 / q8_0 / bf16;
G1 n_q 1 n_sel 2051, n_q 9 n_sel 48, n_q 66 n_sel 257; G4 n_q 4 and 66).
Query 0 selects cells 0 .. 15 (the first 4 quads: the whole first step of
the HIP G4 / G1 and Vulkan cm attends), whose K rows of KV head 0 score
-inf. The CPU check requires the KV head 0 rows to equal, bit for bit,
O_CON over the rows without those cells, which has no -inf arithmetic.
- Before: CPU 15/15 FAIL ("query 0 rows of KV head 0 zero; 3072 values
... differ"); with the CPU fixed and the Vulkan portable shader not,
lavapipe FAILs the 9 G1 cases (ERR 0.94 / 0.092).
- After: CPU 15/15 OK, lavapipe 9/9 OK (G4: not supported on Vulkan).
- HIP ROCm0 and RADV: NOT RUN (~/gpu.lock held by a process of an
earlier step).
The touched HIP / Vulkan tiers and O_CON adapt PR #219's code (their file
headers; commits c0ef4a8, 3b93e6a, 06d8072, 4e6328f).
Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ning max is -inf ggml.h item 5: a row with an attended cell whose score is NaN gives 0 (the CPU op: l is NaN, `l > 0 ? acc / l : 0`). The G4 and G1 WMMA attends build the step max with fmaxf, which drops a NaN. In a step whose live cells of a row all scored NaN (or -inf) before any finite score, mnew / next stayed -inf and `p = mnew == -inf ? 0 : exp2f(...)` gave the NaN cell weight 0: the row came out as the softmax over its other cells. G1 does the same at the first chunk of every split. No fixup or merge step looks for a NaN K. The exponentials are now taken against mref = 0 when the running max is still -inf: a -inf (or masked) cell gives exp2f(-inf) = 0 and a NaN cell keeps exp2f(NaN) = NaN, so l becomes NaN and the epilogue / split-K merge (which keeps a NaN split, d7e4656) writes 0. With a finite running max p is computed as before, so every other result is unchanged bit for bit. The per-element select is replaced by one select per step. The kernels' online softmax is PR #219's (qsa3_attn_kernel and the decode WMMA partial of 94e0868, as sparse-attn-attend-g4.cuh / -g1.cuh say). Test: test-backend-ops SPARSE_ATTN ",leadnan" (the lead shapes of the previous commit): cells 0 .. 15 of query 0 have NaN K rows (KV head 0), so they fill query 0's first step; the CPU check requires query 0's KV head 0 rows to be 0 and its KV head 1 rows not. - CPU 15/15 OK and lavapipe 9/9 OK, before and after (the CPU and portable tiers were right). - HIP ROCm0: NOT RUN (~/gpu.lock held by a process of an earlier step). Expected before: the G4 / G1 cases FAIL (finite rows against the CPU's 0); after: OK. Co-authored-by: Iggy Jackson <iggy@theiggy.com> Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ip input views hip: qsa_decode (wmma) and qsa_prefill read q8_0 K/V. The decode kernel dequantizes in registers; the prefill pack converts while packing (the direct f16 path is skipped for q8_0). Both use the same half product as dequantize_block_q8_0_f16. Complete-block selection now also takes q8_0 K/V when every QSA layer runs on ROCm (selected_key_q8), so a q8_0 cache no longer falls back to the masked per-cell top-k. qwen4exp: the masked top-k path took a fresh view of the KQ mask and the QSA bias for every 512-query score strip in every layer. The scheduler gives each view of a host input its own copy, kept for the whole graph, so this made n_layers x n_strips copies. With Signal-3.8-Flash-Next Q4_K_XL, -ub 4096 and a q8_0 cache, the ROCm0 compute buffer was 7193 MiB at 32k (vs 3009 before bb030af) and grew about 0.15 MiB per context cell (~41 GB at 262k), so the MTP draft context hit OOM. The views are now built once per graph and shared: 2969 MiB at 32k, 10.7 GB at 262k. Perplexity is bit-identical. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4rLkt7MokKFKji9hxCaev (cherry picked from commit 68da419) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…tests - selected_key_attn now comes from a probe op with the real K/V types, at one query and at 513 (past the decode kernels). selected_key_q8 and the "ROCm" backend-name check are gone: a q8_0 cache on a model whose GQA ratio is not 12 (q8_0 decode is WMMA-only) or on Vulkan (flash_attn_sel is f16-only) now takes the masked route instead of falling back to CPU. LLAMA_QSA_SELECTED_KEY=1 forces the selected-key route for q8_0 too. - The QSA attention log line names the cache types it was decided for. - strip_views is keyed on the strip size too, which varies with the layer's compress ratio. - test-backend-ops: q8_0 and mixed K/V variants of the maskless QSA decode and prefill tests. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F (cherry picked from commit b604475) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
qsa_prefill_impl1 packed the whole q8_0 K and V cache to f16 on every ubatch in every QSA layer, because the direct reads were f16-only: O(n_kv) work per ubatch and f16-sized pool buffers, eating into what a q8_0 cache saves. qsa3_attn_kernel now takes a Q8 flag: a direct K chunk (dims 32w .. 32w+31 of a key) is exactly q8_0 block w, loaded as aligned dwords and realigned (the block offset is wave-uniform); direct V reads each key's byte and scale. Both dequantize in registers with the decode kernel's exact half conversion, so every QSA_DIRECT mode stays bit-identical to the pack (llama-perplexity KLD vs QSA_DIRECT=0 at the floor of identical runs; test-backend-ops passes in modes 0/1/2/auto). Mixed K/V types still pack. The auto heuristic is shared with f16: K direct, V direct too when the attention is small against the cache. q8_0 at b/ub 4096 (Signal-3.8- Flash-Next Q4_K_XL): K direct 1347 / 1272 t/s vs pack 1350 / 1284 at pp4096 depth 0 / 32k, within noise. [qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b) onto base ea5285d (origin/master, "Merge pull request #251"). Dry-run before the import: temporary index from git read-tree ea5285d, then git apply --cached --check of 68da419, b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary index after its check; resulting tree 449aba6). #234 (head 7774790) is not in the base (git merge-base --is-ancestor), so no conflict resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F (cherry picked from commit 94e0868) Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
Overview
hip: q8_0 K/V for the QSA selected-key kernels
qsa_decode(WMMA) dequantizes q8_0 in registers.qsa_prefillreads q8_0 rows directly and dequantizes in registers.alignbyte/perm.QSA_DIRECT=0, still pack, converting while packing.dequantize_block_q8_0_f16. AllQSA_DIRECTmodes are bit-identical to each other.qwen4exp: selected-key routing follows the cache type
selected_key_attncomes from a probe op that uses the real K/V types. It probes at 1 query and at 513, past the decode kernels.flash_attn_selis f16-onlyLLAMA_QSA_SELECTED_KEY=1forces the selected-key route for q8_0 too.QSA attention:log line now names the cache types.qwen4exp: score-strip input views are shared
-ub 4096and a q8_0 cache, the ROCm0 compute buffer was 7193 MiB at 32k (vs 3009 before bb030af). It grew about 0.15 MiB per context cell (~41 GB at 262k), so the MTP draft context hit OOM.Measurements
b/ub 4096 (t/s, round 1 / round 2)
Deep context, b/ub 4096, d131072 (PR only, interleaved)
Master q8_0 needs a 21.5 GiB compute buffer at 131k with b/ub 4096 (masked route), so it isn't compared here.
The remaining pp512 gap at depth is inside the QSA attention op.
GGML_CUDA_OP_PROFshows 86 ms vs 62 ms across the 12 QSA layers, the same with direct reads or with packing: it is the per-key dequantization in the kernel's inner loop. Over the whole graph that is about 4% of GPU time.ub 512, depth 0 (llama-bench defaults)
Master runs this case on the dense q8_0 FA kernel. On the PR, q8_0 uses the QSA kernels. The gap was −6% before the direct reads.
Memory
ROCm0 compute buffer,
llama-perplexityreserve, b/ub 4096 (measured in the review of 68da419):The KV cache itself, at 8k on Signal: 192 + 24 MiB with f16, 102 + 12.75 MiB with q8_0. That is about 27 KiB per cell with f16 and 14.3 KiB with q8_0, so ~3.1 GiB saved at 262k. With direct reads, q8_0 no longer allocates f16-sized pack buffers per QSA layer.
Correctness:
QSA_DECODE_MASKLESSandQSA_PREFILL_MASKLESS:QSA_DIRECT= 0, 1, 2 and auto. The existing QSA cases still pass.QSA_DIRECT=1/2/autoagainstQSA_DIRECT=0(pack) gives the same KLD as a run compared with itself (mean −0.000004, max 0.000004 from the stored-logit format), with identical per-chunk PPL.ggml_cuda_flash_attn_extsends any FA op withsrc[5]that the QSA checks accept to the QSA kernels, so a masked q8_0 op now runs on QSA prefill/decode instead of the dense q8_0 kernel.LLAMA_QSA_SELECTED_KEY=0.Additional information
Requirements
belong in halo-box/llama.cpp instead
flash_attn_sel's type check)