Skip to content

qwen4exp : q8_0 K/V for the QSA selected-key kernels, share score-strip input views - #219

Closed
iggy wants to merge 3 commits into
halo-box:masterfrom
iggy:fix-q8-kv-quant-memory-usage
Closed

iggy wants to merge 3 commits into
halo-box:masterfrom
iggy:fix-q8-kv-quant-memory-usage

Conversation

@iggy

@iggy iggy commented Oct 25, 2026 •

Copy link
Copy Markdown

Overview

hip: q8_0 K/V for the QSA selected-key kernels

  • Decode: qsa_decode (WMMA) dequantizes q8_0 in registers.
  • Prefill, direct reads: qsa_prefill reads q8_0 rows directly and dequantizes in registers.
    • A direct K chunk (dims 32w..32w+31 of one key) is exactly q8_0 block w. It is loaded as aligned dwords and realigned with alignbyte/perm.
    • A direct V read takes each key's quant byte and scale.
  • Prefill, packing: mixed K/V types, and QSA_DIRECT=0, still pack, converting while packing.
  • Exactness: every path uses the same half product as dequantize_block_q8_0_f16. All QSA_DIRECT modes are bit-identical to each other.
  • No full-cache repack: the auto heuristic is the f16 one. That removes the full-cache f16 repack per ubatch and its f16-sized pool buffers, which an earlier version of this PR did.

qwen4exp: selected-key routing follows the cache type

  • selected_key_attn comes from a probe op that uses the real K/V types. It probes at 1 query and at 513, past the decode kernels.
  • A q8_0 cache gets complete-block selection where the kernels take it: HIP with GQA 12.
  • Elsewhere it takes the masked route instead of falling back to CPU:
    • Vulkan, whose flash_attn_sel is f16-only
    • other GQA ratios, because q8_0 decode is WMMA-only
  • LLAMA_QSA_SELECTED_KEY=1 forces the selected-key route for q8_0 too.
  • The QSA attention: log line now names the cache types.

qwen4exp: score-strip input views are shared

  • Problem: 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 × n_strips copies.
  • Measured: 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). It grew about 0.15 MiB per context cell (~41 GB at 262k), so the MTP draft context hit OOM.
  • Fix: the views are now built once per graph and shared. That gives 2969 MiB at 32k and 10.7 GB at 262k.
  • Cache key: input, first query and strip size. The strip size varies with the layer's compress ratio.

Measurements

Device:     Ryzen AI Max+ 395, 128 GB
Kernel:     7.1.5
Backend:    ROCm 10.1 (AMD clang 24.0.0git)
Build:      -DGGML_HIP=ON -DGPU_TARGETS=gfx1151 -DGGML_HIP_GRAPHS=ON -DGGML_HIP_NO_VMM=ON, Release
Baseline:   halo/master f5c0a7a34 (merge base 13a279bfa gives the same ROCm numbers)
Change:     this branch, built in the same session with the same toolchain
Model:      Signal-3.8-Flash-Next-AP Q4_K_XL (qwen4exp)
Bench:      llama-bench -ngl 99 -fa 1 -b 4096 -ub 4096 -r 3, two rounds alternating master / PR

b/ub 4096 (t/s, round 1 / round 2)

test master f16 PR f16 master q8_0 PR q8_0 PR q8_0 vs master q8_0 PR q8_0 vs f16
pp512 1067 / 1066 1066 / 1067 1048 / 1050 1049 / 1048 0% −1.7%
pp4096 1367 / 1365 1364 / 1366 1224 / 1229 1351 / 1351 +10% −1.1%
tg32 27.57 / 27.59 27.57 / 27.59 27.36 / 27.39 27.37 / 27.35 0% −0.8%
pp512 @ d32768 907 / 870 871 / 905 530 / 531 867 / 866 +63% −2.4%
pp4096 @ d32768 1286 / 1286 1285 / 1282 592 / 593 1268 / 1270 +2.1× −1.2%
tg32 @ d32768 25.40 / 25.39 25.39 / 25.40 19.65 / 22.12 24.91 / 24.94 +19% −1.9%
  • f16: PR and master are the same to within noise, and output is bit-identical.
  • pp @ d32768 is noisy: about ±13–55 t/s within a run. The two pp512 @ d32768 f16 rounds trade places between master and PR.

Deep context, b/ub 4096, d131072 (PR only, interleaved)

test PR f16 PR q8_0 q8_0 vs f16
pp512 862 / 855 759 / 800 −9%
pp4096 1197 / 1201 1175 / 1190 −1.4%
tg32 24.31 / 24.34 23.37 / 23.38 −4%

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_PROF shows 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 q8_0 PR q8_0
pp4096 1011 / 1004 976 / 975 (−3%)
pp8192 955 / 954 936 / 937 (−2%)

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-perplexity reserve, b/ub 4096 (measured in the review of 68da419):

c32768 c131072
master f16 4084 MiB 4133 MiB
master q8_0 6809 MiB OOM (needs 21578 MiB)
PR q8_0 4084 MiB 4134 MiB

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:

  • test-backend-ops (ROCm0): new q8_0 and mixed K/V variants of QSA_DECODE_MASKLESS and QSA_PREFILL_MASKLESS:
    • Decode: 1/9/64/512 queries, interleaved and not, and 32k keys.
    • Prefill: 129/513/640 queries, plus 32k/64k keys on the direct path.
    • All pass with QSA_DIRECT = 0, 1, 2 and auto. The existing QSA cases still pass.
    • The q8_0 GQA-4 decode case reports not supported, as intended.
  • llama-perplexity, q8_0, c8192 b/ub 4096:
    • QSA_DIRECT=1/2/auto against QSA_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.
  • f16: bit-identical to master (KLD 0, measured in the review).
  • The masked q8_0 route changes output.
    • ggml_cuda_flash_attn_ext sends any FA op with src[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.
    • This applies with images in the cache, at depth > 1M, and with LLAMA_QSA_SELECTED_KEY=0.
    • The review measured KLD 0.0136 between master and the PR on that route, with 97.1% same top-1. It is slightly closer to f16 than before. It is not bit-identical.

Additional information

  • This originally came out of a plan to make a ROCm-specific KV quant type. The robit went through a bunch of iterations on that and came up empty, so nobody needs to try that again.
  • q8_0 is not at full parity with f16:
    • about 1–2.5% behind at b/ub 4096 up to 32k
    • 9% behind for short prompts at 131k depth
    • 4% behind for decode at 131k

Requirements

  • I have read and agree with the contributing guidelines
  • This change is Strix Halo specific, or justified by measurements on Strix Halo. General llama.cpp improvements
    belong in halo-box/llama.cpp instead
  • AI usage disclosure: Claude (Opus 5.5) wrote the code, ran the benchmarks and wrote this description
  • What was NOT verified:
    • any model other than q38fn (Signal-3.8-Flash-Next)
    • Vulkan (only by reading flash_attn_sel's type check)
    • a qwen4exp model with GQA ≠ 12 end to end (only the test-backend-ops case)

@iggy
iggy marked this pull request as draft October 25, 2026 17:51
@iggy
iggy marked this pull request as ready for review October 25, 2026 18:31
…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
@iggy
iggy force-pushed the fix-q8-kv-quant-memory-usage branch from 728427c to 68da419 Compare October 31, 2026 22:31
@gaetan-puleo

gaetan-puleo commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Review of 68da419, measured on Strix Halo

I measured this head against its merge base 13a279b, both built in the same session.

  • What changes for users: q8_0 K/V on long contexts goes from unusable to usable. At 32k depth q8_0 prefill is ~2.6x faster than master; at 200k it is ~8x. Decode at 32k goes from 21.5 to 24.0 t/s. The compute buffer now matches f16, where master fails to allocate at 131k.
  • Correctness: the new q8_0 test cases pass, and f16 output is bit-identical to master. I found no wrong-output bug.
  • The "q8_0 at parity with f16" claim does not hold. q8_0 is 2-7% behind f16 across prompt sizes, and 11% behind at pp512 with 200k context. At ub 512, depth 0, it is slower than master q8_0 for pp4096-8192. Details and causes are below.
Device:   Ryzen AI Max+ 395, 128 GB LPDDR5X-8000
Kernel:   7.2.4-200.fc44.x86_64
Backend:  ROCm 10.1 (/opt/rocm/core-10.1 clang), -DGGML_HIP=ON -DGPU_TARGETS=gfx1151 -DCMAKE_BUILD_TYPE=Release
Baseline: 13a279bfa (merge base), Change: 68da4191d
Model:    Qwen3.8-Flash-Next UD-Q4_K_XL
Bench:    llama-bench -ngl 99 -fa 1 -lzm on-direct -n 0, -r 3 or 4, -ctk/-ctv f16 or q8_0

1. q8_0 is not at parity with f16

PR q8_0 compared with PR f16, in t/s. The PR's f16 numbers match base.

b/ub 4096:

prompt depth 0: f16 / q8_0 Δ depth 32k: f16 / q8_0 Δ
pp512 noisy (±571) 1229 / 1154 −6.1%
pp1024 1928 / 1869 −3.1% 1614 / 1573 −2.6%
pp2048 2140 / 2046 −4.4% 1814 / 1772 −2.3%
pp4096 2122 / 2077 −2.1% 1907 / 1881 −1.4%
pp8192 2037 / 1991 −2.3% 1895 / 1864 −1.6%
pp16384 1990 / 1948 −2.1% 1874 / 1850 −1.3%

ub 512, b 4096:

prompt depth 0: f16 / q8_0 / base q8_0 depth 32k: f16 / q8_0 Δ
pp512 1593 / 1552 / 1553 1236 / 1158 −6.3%
pp2048 1553 / 1535 / 1532 1227 / 1150 −6.3%
pp4096 1408 / 1369 / 1434 1235 / 1166 −5.6%
pp8192 1361 / 1315 / 1347 1243 / 1157 −6.9%
pp16384 1319 / 1248 / 1148 1228 / 1141 −7.1%
  • ub 512, depth 0, pp4096 and pp8192: this PR's q8_0 is slower than master's q8_0, by −4.5% and −2.4%. That is a regression in that configuration.
  • ub 512 at 32k depth: q8_0 is −6 to −7% below f16. The description says the ub 512 gap is "within about one standard deviation"; I could not reproduce that.
  • ub 8192: q8_0 is −1.5 to −1.9% below f16 (pp8192 and pp16384, depth 0 and 32k).

Depth 200k (b/ub 4096):

base f16 PR f16 PR q8_0 base q8_0
pp512 1105 1100 981 (−11%) 144
pp2048 1574 1564 1505 (−4.4%) 180
pp4096 1665 noisy 1619 (−2.8%) 182
pp8192 1621 1621 1591 (−1.8%) 177
tg32 21.3 22.1 21.0 12.3

2. Where the gap comes from

Per-op GPU time from GGML_CUDA_OP_PROF=1, PR f16 → PR q8_0, summed over one ubatch:

QSA FA Hadamard K/V rot gate (unfused) total
pp4096 d32k −4.8 ms +20.4 +17.7 +37 ms
pp4096 d0 −2.4 +20.8 +17.8 +36 ms
pp2048 d0 +20.7 (dense FA, no QSA at 2048 keys) +11.8 +9.4 +37 ms
pp512 d200k +27.6 (65.4 → 93.0, +42%) +1.1 +1.0
  • Up to 32k, the new q8_0 QSA kernels are not the problem. They are as fast as f16. The gap comes from what a quantized cache brings with it.
    • Hadamard rotation: the extra K/V rotation matmuls (attn_rot) cost ~20 ms per pass.
    • Lost FA + gate fusion: the rotation of the FA output (self_v_rot) sits between FLASH_ATTN_EXT and the gate, so that fusion never matches. The unfused gate costs another ~18 ms.
    • Both mechanisms predate this PR, but they are why "parity" is not reached.
  • At depth, the cost does come from this PR. qsa_prefill_impl1 forces both packs whenever K/V are not f16 (kv_f16). At pp512 with 200k context, f16 takes the qsa_direct route (512*64 < n_kv) and packs nothing. q8_0 dequantizes and packs the whole K and V cache in every QSA layer for every ubatch. That cost is O(n_kv) and grows to 1M. It also allocates ggml_nelements(k) halves of pool memory, f16-sized, which eats into the memory a q8_0 cache is meant to save.
    • Possible fix: a direct-read path that dequantizes q8_0 rows in the qsa3 loader, like the decode WMMA kernel already does.

3. Correctness

  • q8_0 kernel tests: I added q8_0 type_kv variants of test_qsa_decode_maskless / test_qsa_prefill_maskless. Decode covers 1/9/64/512 queries and prefill 129/513 queries up to 65536 keys, interleaved and not. All 24 cases pass on ROCm0. The existing QSA_DECODE (94) and QSA_PREFILL (28) cases still pass.
    • The PR itself adds no q8_0 test case. Please add some; I can share the diff if useful.
  • Perplexity and KLD: c8192, b/ub 4096, 2 chunks, KLD against base f16 logits.
    • PR f16 is bit-identical to base f16 (KLD 0).
    • PR q8_0 selected-key: KLD 0.0126, against base q8_0 at 0.0132.
    • ub 256, which runs the decode kernel: PR q8_0 0.0144, PR f16 0.0140, base q8_0 0.0138.
    • Mixed -ctk q8_0 -ctv f16: runs, KLD 0.0124.
  • The masked route changes output for q8_0, which the description does not mention. "Perplexity is bit-identical" is only true for f16.
    • Evidence: with LLAMA_QSA_SELECTED_KEY=0 and q8_0, base vs PR gives KLD 0.0136 and same top-1 97.1%. Base with the env var is bit-identical to base without it, so the difference comes from the PR.
    • Why: ggml_cuda_flash_attn_ext (fattn.cu:1154-1158) sends any FA op with src[5] that the QSA support checks accept to the QSA kernels, mask or not. The masked q8_0 op used to run on the dense q8_0 FA kernel and now runs on QSA prefill/decode. That applies to images in the cache, depth > 1M, and the env override.
    • The new result is slightly closer to f16, so this is probably fine, but please state it.
  • The strip-view sharing alone is bit-identical: base vs PR with f16 and LLAMA_QSA_SELECTED_KEY=0 gives KLD 0 at ub 4096 and ub 1024.

4. Memory, confirmed

ROCm0 compute buffer, llama-perplexity reserve with b/ub 4096:

c32768 c131072
base f16 4083.69 MiB 4133.44 MiB
base q8_0 6809.41 MiB OOM (needs 21578 MiB)
PR q8_0 4083.95 MiB 4133.70 MiB
PR q8_0, masked route (LLAMA_QSA_SELECTED_KEY=0) 5105.41 MiB 7026.53 MiB

5. Code issues

  1. selected_key_q8 is a backend-name check, not a probe. See llama-memory-hybrid-idx.cpp.
    • Why it matters: qsa_selected_key_supported probes with F16 K/V. q8_0 decode is WMMA-only and needs q->ne[2] == 12*k->ne[2]; f16 has the non-WMMA fallback.
    • Measured: the new GQA-4 q8_0 decode case reports not supported [ROCm0].
    • Failure scenario: a qwen4exp model with n_head/n_head_kv != 12 and a q8_0 cache is routed to block selection. Its decode and small-ubatch QSA ops are then rejected by both kernels, ggml_cuda_flash_attn_ext_supported returns false, and the op silently runs on CPU every token.
    • Suggested fix: probe with the real type_k/type_v, at n_q=1 and at n_q=128, instead of comparing the reg name to "ROCm". Q38FN has ratio 12, so it is not affected today.
  2. strip_views is keyed on (src, first) only (qwen4exp.cpp:1604).
    • kq_mask is the same tensor in every layer, but strip = qwen4exp_score_strip(..., n_blocks, ...) depends on n_blocks, which depends on the layer's compress ratio.
    • Failure scenario: in a model with mixed ratios at long context, or with split streams, where strip = n_tps is halved per ratio, two layers ask for the same key with different n_query. The second layer gets the first layer's view, and ggml_reshape_3d(mask, n_kv, n_query, n_stream) asserts.
    • Q38FN uses a single ratio (4), so it is latent. Adding n_query to the key costs nothing.
  3. Minor: with LLAMA_QSA_SELECTED_KEY=1 forced, selected_key_q8 is computed before the override and stays false. f16 is forced onto selected-key and q8_0 silently is not.
  4. Minor (pre-existing): the QSA attention: selected-key kernels log line prints on base for q8_0 even though the route taken is masked. Now that the route depends on the cache type, it would help if the line reflected the route actually used.

Checked and fine

  • 0x6400 conversion: it gives exactly q. A single half multiply by d matches dequantize_block_q8_0_f16 (__hmul2) bit for bit.
  • Operand layout: the WMMA K operand layout, block w = wave, and the V pair qs[r]/qs[16+r] all match the f16 indexing.
  • Launcher vs support check: the decode launcher's wmma condition is identical to the q8_0 gate in supported_dev, so q8_0 can never reach the f16-only qsa_decode_partial.
  • Split streams and mixed K/V: split-stream nb[3] byte offsets and mixed K/V types in the prefill pack are handled correctly.
  • Scheduler and map lifetime: strip_views lives with the graph build. The scheduler does key input copies per view (ggml-backend.cpp sched), so the memory fix works the way the description says.

Reviewed with Claude (Opus 5.5). Two subagents reviewed the code; every number above was measured on a Strix Halo machine.

@gaetan-puleo gaetan-puleo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check comment on top

@iggy

iggy commented Nov 1, 2026

Copy link
Copy Markdown
Author

@iggy

iggy commented Nov 1, 2026

Copy link
Copy Markdown
Author

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.

Device:   Ryzen AI Max+ 395, 128 GB, Linux 7.1.5
Backend:  ROCm 10.1 (AMD clang 24.0.0git), -DGGML_HIP=ON -DGPU_TARGETS=gfx1151 -DGGML_HIP_GRAPHS=ON -DGGML_HIP_NO_VMM=ON, Release
Builds:   master f5c0a7a34, PR 68da4191d, merge base 13a279bfa (all built with the same toolchain in the same session)
Model:    Signal-3.8-Flash-Next-AP Q4_K_XL (qwen4exp)
Bench:    llama-bench -ngl 99 -fa 1 -ctk f16 -ctv f16 -r 3; default b/ub (2048/512), and -b 4096 -ub 4096
Order:    two rounds, alternating master → PR → base, so drift hits all three equally

t/s, shown as round 1 / round 2:

test master PR base
pp512 1036 / 1067 1066 / 1067 1067 / 1067
pp4096 954 / 995 992 / 993 994 / 994
tg128 28.51 / 28.53 28.48 / 28.52 28.52 / 28.52
pp512 @ d32768 904 / 903 880 / 903 904 / 902
pp4096 @ d32768 907 / 907 908 / 907 908 / 908
tg128 @ d32768 26.21 / 26.26 26.21 / 26.25 26.26 / 26.24
b/ub 4096 pp4096 1355 / 1341 1356 / 1356 1349 / 1356
b/ub 4096 pp4096 @ d32768 1280 / 1255 1257 / 1256 1253 / 1243
  • No build is consistently behind. Each gap above is a single run that doesn't repeat in the other round. Master's slow round 1 came from being benchmarked first.
  • This matches the code. For f16 the prefill and decode paths are unchanged. The q8_0 code only runs through the new type checks, and the review above found f16 output bit-identical to the base.
  • Watch for two traps when comparing:
    • ROCm version. Comparing a 10.0 build with a 10.1 build changes the compiler and runtime along with the code.
    • Noise at b/ub 4096 with depth. pp4096 @ d32768 shows ±63–73 t/s within a single -r 3 run on every build. One bad repetition moves the mean by about 2%.

@iggy

iggy commented Nov 1, 2026

Copy link
Copy Markdown
Author

q8_0 KV: master vs PR vs merge base

Same setup and order as the f16 comment above, with -ctk q8_0 -ctv q8_0. t/s, shown as round 1 / round 2. Δ compares the PR with master using the mean of both rounds.

test master PR base Δ PR vs master
pp512 1050 / 1049 995 / 1047 1048 / 1047 −2.6% (round 2: −0.2%)
pp4096 1016 / 1005 919 / 977 1005 / 1005 −6.2%
tg128 28.43 / 28.35 28.37 / 28.36 28.36 / 28.36 0%
pp512 @ d32768 554 / 559 784 / 863 558 / 558 +48%
pp4096 @ d32768 536 / 537 844 / 870 537 / 536 +60%
tg128 @ d32768 22.85 / 22.86 25.87 / 25.87 22.85 / 22.85 +13%
b/ub 4096 pp4096 1209 / 1210 1348 / 1337 1201 / 1213 +11%
b/ub 4096 pp4096 @ d32768 578 / 584 1238 / 1246 587 / 584 +2.1×

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:

  • At depth, q8_0 gets much faster: +48–60% prefill at the default ubatch, 2.1× at b/ub 4096, and +13% decode at 32k.
  • At b/ub 4096, q8_0 is close to f16: 1343 vs 1356 t/s at depth 0, and 1242 vs 1257 at 32k.

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.

  • Why: qsa_prefill_impl1 repacks the whole q8_0 K and V cache to f16 on every ubatch, because the direct-read paths are f16-only. With 512-token ubatches that pack runs 8 times per 4096-token prompt.
  • The PR also varies more between rounds at ub 512: 784 vs 863 at pp512 @ d32768, and 919 vs 977 at pp4096. Master and base are steady there.
  • Fix: a q8_0 direct-read path in the prefill loader, like the one the decode WMMA kernel already has. It should remove this cost and the f16-sized pool allocation. That's the next change for this PR.

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.

iggy and others added 2 commits November 1, 2026 16:32
…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
@iggy

iggy commented Nov 1, 2026

Copy link
Copy Markdown
Author

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 hip : q8_0 direct K/V reads in qsa_prefill, which is your suggested fix.

  • What changed: qsa3_attn_kernel reads q8_0 K and V directly and dequantizes in registers with the decode kernel's half conversion, so it no longer repacks the whole cache every ubatch.
    • A direct K chunk is exactly q8_0 block w.
    • The block's offset is the same across a wave, so it loads aligned dwords and realigns them.
  • Heuristic: auto now uses the f16 heuristic, which removes the O(n_kv) pack and its f16-sized pool buffers.
  • Exactness: all QSA_DIRECT modes are bit-identical to the pack.
  • pp512 at 131k depth with b/ub 4096 is still 9% behind f16. The profile shows the per-key dequantization in the inner loop costing about what the pack did (QSA FA 86 vs 62 ms over 12 layers, either way), so I've stated that in the description rather than claiming parity.
  • Up to 32k at b/ub 4096, q8_0 is now 1–2.5% behind f16. Against master's q8_0 it is +10% at depth 0, about +63% to 2.1× at 32k, and +19% for tg.

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 qwen4exp : probe selected-key support with the cache types, q8_0 QSA tests:

  1. selected_key_q8 and the "ROCm" name check are gone.
    • qsa_selected_key_supported probes with the cache's real K/V types, at 1 query and at 513.
    • A GQA-4 model with a q8_0 cache, or Vulkan with q8_0, now takes the masked route instead of running attention on CPU.
  2. strip_views is keyed on (input, first query, strip size).
  3. LLAMA_QSA_SELECTED_KEY=1 now forces the selected-key route for q8_0 as well, because the type now feeds the probe rather than a flag that is checked later.
  4. The QSA attention: log line prints the K/V types it was decided for. The masked/selected wording now matches the route the cache type actually takes.

Tests (§3): I added q8_0 and mixed-type variants of test_qsa_decode_maskless / test_qsa_prefill_maskless, written separately from your /tmp/pr219_patch.py.

  • They cover direct-path shapes: 130/200 queries against 32k/64k keys.
  • All pass on ROCm0 with QSA_DIRECT = 0, 1, 2 and auto. The GQA-4 q8_0 case reports not supported.

Masked-route output change (§3): this is now stated in the description, with your KLD numbers.

rcfa pushed a commit to rcfa/strix-llama.cpp that referenced this pull request Nov 6, 2026
…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
rcfa added a commit to rcfa/strix-llama.cpp that referenced this pull request Nov 6, 2026
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
@rcfa

rcfa commented Nov 7, 2026

Copy link
Copy Markdown

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, flash_attn_sel and
flash_attn_sel_cm read f16 K/V only, and this PR's q8_0 maskless cases are reported as "not supported". We wrote
the Vulkan side as one commit that touches only Vulkan files:
rcfa/strix-llama.cpp@93e3aff93.

  • Both kernels take K and V each as f16 or q8_0, giving four variants per GQA.
  • They dequantize q8_0 to f16 in the kernel. The scalar kernel does it while it stages the key block in shared
    memory. The WMMA kernel does it while it builds the K and V fragments from 16-bit words, because 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 -b Vulkan0 -o QSA_DECODE_MASKLESS,QSA_PREFILL_MASKLESS, which includes this PR's q8_0 cases, on a
Radeon 890M (gfx1150, Strix Point, RADV, Mesa 26.1.6): 79/79 with WMMA, and 79/79 with
GGML_VK_DISABLE_COOPMAT=1. The worst NMSE against the FP64 oracle is 8.6e-8 for q8_0. For comparison, f16 gives
4.9e-8 and the CPU backend's q8_0 1.6e-6.

On Qwen3.8-Flash-Next (GSQ-RCO IQ3_XXS, -c 524288 -np 4 -kvu -ub 2048, MTP, Strix Point), q8_0 through these
kernels against f16:

  • GTT at load: 13.69 GiB against 20.00.
  • pp16k: 269.0 t/s against 266.8.
  • pp2048 at 32k depth: 248.5 t/s against 239.0. The masked route gave 176.6.
  • Decode at 35k: 20.11 t/s against 20.73.
  • Perplexity at -c 4096: 7.0913 against 7.0952.

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
that head predates #234, which changed the context the hunks need. Once this PR is rebased onto master, it should
cherry-pick cleanly. Our squash resolved the ggml-cuda/qsa-prefill.cu conflict with #234 by taking this PR's side
and was never built for CUDA. So please don't take our branch as a rebase of this PR. Only the Vulkan commit is
meant for you.

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 dzannotti added in-review We are reviewing. verifying Building and running the PR to verify its claims. and removed in-review We are reviewing. labels Nov 10, 2026

@dzannotti dzannotti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Blocking. ggml/src/ggml-cuda/qsa-prefill.cu: the instantiation qsa3_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 in scripts/hip passes 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 the DIRECT_V && Q8 path), 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).
  2. Blocking. Rebase onto master. Master commit d8f3d1d removed QSA_DIRECT, qsa_pack_k and the packed-K launch, so qsa-prefill.cu conflicts 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 the Q8 flag), V is direct only when k->type == v->type && n_q * 64 < n_kv, and mixed K/V types read K direct and pack V. qsa_pack_k and QSA_DIRECT are not needed.
  3. tests/test-backend-ops.cpp: the q8_0 prefill cases with 70, 130 and 200 queries go to qsa_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 for QSA_PREFILL and QSA_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).
  4. 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.
  5. Should fix. Commits: AGENTS.md asks for an Assisted-by: trailer, not Co-Authored-By with session links. After the rebase, the message of the third commit still describes QSA_DIRECT modes. Consider squashing, because later commits remove most of what the first commit adds to qsa-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_BLOCKING unset 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 qwen4exp passes 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 -Werror HIP 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> and qsa_pack_v<q8>, and dropped QSA_DIRECT. f16/f16 follows master (K direct, V direct when n_q*64 < n_kv). Any q8_0 K or V packs both and launches qsa3_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 and n_q*64 < n_kv, otherwise qsa_pack_v<v is q8_0>. We removed qsa_pack_k and 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_BLOCKING unset 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-vocabs fails on both sides because it needs network vocab files. On Vulkan, test-llama-context also 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.sh on ROCm0: 11 of 377 cases differ by more than 3%, all in ops this PR does not touch (noise, 1 run).
  • ops-perf.sh on Vulkan0 is incomplete. A COL2IM_1D perf case loses the device on master and on this PR alike; the PR does not touch it.

Findings in full

  1. 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 waves
    • qsa_decode_wmma_partial<true>: 102 VGPR, 12 waves
    • qsa_pack_v<true>: 18 VGPR
  2. The PR's q8_0 prefill tests run on qsa_decode, because qsa_decode takes up to 512 queries (ask 3).
  3. The masked q8_0 route now runs on the QSA kernels and its output changes. No test covers it (ask 3).
  4. The probe with 513 queries changes f16 routing for GQA ratios other than 12 on HIP (ask 4).
  5. The q8_0 dequantization matches dequantize_block_q8_0_f16 bit 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.
  6. 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.
  7. Overlap with #271: the qwen4exp.cpp hunks are line-identical. In llama-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-end LLAMA_QSA_SELECTED_KEY run.
  • Vulkan op perf: the pre-existing COL2IM_1D device loss interrupted it.

@dzannotti dzannotti added risk:medium Risk: medium waiting-user We asked the author for something. and removed verifying Building and running the PR to verify its claims. labels Nov 11, 2026
@iggy iggy closed this Nov 11, 2026
@gaetan-puleo

Copy link
Copy Markdown
Collaborator

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, SPARSE_ATTN_PLAN and SPARSE_ATTN. They read f16, bf16, q8_0, q4_0 and the other KV types directly, so the masked route, the source of the quantized-KV memory blow-up, can be removed for every type, not only q8_0.

Your three commits are the first three of #276 and keep you as author. Parts of them carry over into the new path:

  • strip_views and its key are kept as they are. Without them, a deep image ubatch costs about +1.1 GiB of ROCm0 compute buffer.
  • The exact q8 → half helpers and your decode q8 K loader are reused in the decode kernel. The block-wise addressing of the direct q8 K read is adapted to the prefill kernel's register layout.
  • Your n_q·64 < n_kv direct-V threshold is the default for every V type.
  • Your q8_0 and mixed-type test shapes are ported to the new op's tests.

Reviews on #276 are welcome.

gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…, 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
… 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
… 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…, 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…#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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…, 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
… 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
… 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
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
…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
gaetan-puleo pushed a commit that referenced this pull request Nov 13, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CUDA ggml model risk:medium Risk: medium testing waiting-user We asked the author for something.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants