Skip to content

ggml, hip, vulkan, qwen4exp : QSA sparse attention as two ops with first-class quantized KV (builds on #219) - #276

Open
gaetan-puleo wants to merge 99 commits into
masterfrom
qsa-rewrite
Open

gaetan-puleo wants to merge 99 commits into
masterfrom
qsa-rewrite

Conversation

@gaetan-puleo

@gaetan-puleo gaetan-puleo commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Rewrite of #219: QSA (the sparse attention of qwen4exp / Qwen3.8-Flash-Next) runs on two new ggml ops, GGML_OP_SPARSE_ATTN_PLAN and GGML_OP_SPARSE_ATTN, with kernels for CPU, HIP and Vulkan. Every KV cache type takes the fast path, not only f16, and the old masked and maskless QSA routes are deleted.

Status: ready for review. Head 37ccb75, 99 commits on master 58e69e5. Owner decisions dated 2026-11-12. Follow-ups: #286 (MTP gates), #287 (performance).

Why

On master only an f16 KV cache is fast with QSA:

  • q8_0 at -c 131072 -ub 4096 reserves a 21,579 MiB ROCm0 compute buffer, against 4,133 MiB for f16.
  • Prefill on real text at 131k runs at 0.13–0.23× of f16.
  • q4_0, bf16 and mixed K/V stay on the masked route. Vulkan q8_0 runs at 0.42–0.56× of its own f16 at 32k depth.

#219 (iggy, closed by its author) fixed q8_0 on HIP only. It left these problems on the existing path:

  • a possible silent CPU fallback;
  • a non-deterministic atomicCAS dedup in qsa_decode;
  • kernel scratch taken from ctx.pool(), outside the reserve;
  • image ubatches overrunning the reserve by up to +1.9 GiB.

What changes

Ops (ggml.h, ggml.c, CPU reference in ggml-cpu/sparse-attn.cpp)

  • SPARSE_ATTN_PLAN turns the selected rows into an integer plan. Its output is bit-identical on CPU, HIP and Vulkan.
  • SPARSE_ATTN attends over the planned rows. The Hadamard rotation of quantized caches is applied inside the op.
  • All scratch lives in the op's own get_alloc_size over-allocation, so it is counted in the reserve. Nothing uses ctx.pool().
  • RPC supports both ops. A client now rejects an rpc-server older than protocol 8.1.

HIP (ggml-cuda/sparse-attn-*)

Vulkan (ggml-vulkan.cpp, vulkan-shaders/sparse_attn*)

  • Three tiers: coopmat, scalar, and portable (no subgroup-size or 46 KB shared-memory requirement).
  • supports_op is true only where a pipeline was created.

Model (src/models/qwen4exp.cpp, llama-context.cpp, llama-memory-hybrid-idx.*)

  • Compact ubatches use complete blocks plus tail rows.
  • Non-compact (image) ubatches keep qwen4exp : q8_0 K/V for the QSA selected-key kernels, share score-strip input views #219's token-expanded selection as a row producer. They are re-split to at most 512 tokens and reserved in multi-sequence contexts.
  • The MTP draft uses the same ops, policies and guard as the main model.
  • A placement guard runs after every reserve and every graph allocation. A QSA node placed on the wrong device becomes an init or decode error, never a silent CPU fallback.

Deleted (about 1,700 lines)

  • HIP: qsa-prefill.cu, qsa-decode.cu, qsa-decode-wmma.cuh, and the QSA and maskless branches of fattn.cu.
  • Vulkan: flash_attn_sel*.comp and the maskless FA dispatch.
  • llama: the masked half of build_attn_qsa, the selected-key probe, LLAMA_QSA_SELECTED_KEY, LLAMA_QSA_DENSE_SHORTCUT, and the q/out rotation nodes.
  • Test cases: QSA_PREFILL, QSA_DECODE and their _MASKLESS variants.
  • ggml_flash_attn_ext_add_top_k now asserts a mask. Its callers (deepseek4, glm5-next) were checked.

Reading guide

area code tests start with
ops + CPU + RPC +970 / −14 +3,317 / −368 ggml.h (op contract), ggml-cpu/sparse-attn.cpp, tests/sparse-attn-ref.h
HIP +4,308 / −1,076 +472 sparse-attn.cuh, sparse-attn-plan.cu, sparse-attn-attend-g4.cu(h), -g1.cu(h), dispatch in ggml-cuda.cu
Vulkan +2,249 / −1,003 +747 ggml-vulkan.cpp (sparse-attn section), sparse_attn_cm.comp, sparse_attn_plan_rows.comp
model / llama +1,596 / −275 +2,386 / −7 qwen4exp.cpp (build_attn_qsa), llama-context.cpp (reserve, guard), llama-memory-hybrid-idx.cpp

About 43 % of the added lines are tests. The four areas depend on each other in this order: ops, then HIP and Vulkan (independent of each other), then model. The PR can be split along those lines if reviewers prefer.

Notes on the history:

User-visible behaviour changes

  • f16 output is no longer bit-identical to master. Pinned KLD against qwen4exp : q8_0 K/V for the QSA selected-key kernels, share score-strip input views #219 is +1.37e-4, inside the 2.0e-4 band. Short image prompts give the same text as master.
  • Backends without a SPARSE_ATTN kernel fail at init on a QSA model. This covers CUDA, Metal, SYCL, OpenCL, CANN, MUSA, WebGPU, and Vulkan devices that cannot create any tier. The message names the remedies: -ngl 0, --no-kv-offload, or a HIP / Vulkan build. QSA models no longer run on those backends.
  • New init errors: -sm tensor with QSA, and n_ctx_seq above 2,097,156 cells.
  • --cache-type-k-idx auto gives the indexer a q8_0 cache when -ctk is below 8 bits. The flag stays as an override. qwen4exp session files saved with a sub-8-bit -ctk or with -fa off must be re-saved.
  • -nkvo: f16, q8_0, q4_0 and bf16 copy K/V to the GPU each graph, as qwen4exp : q8_0 K/V for the QSA selected-key kernels, share score-strip input views #219 does. Other types are pinned to the CPU.
  • Test switches: two new environment variables, GGML_CUDA_SA_FORCE and GGML_VK_SA_FORCE, for the tests only.

Results

Measured on a Strix Halo machine (Radeon 8060S, gfx1151, RADV), with Qwen3.8-Flash-Next UD-Q4_K_XL, a qwen4exp vision model with its mmproj, and the MTP sidecar. Performance figures compare against master.

result
op tests ROCm0 SPARSE_ATTN 1439/1439 across 9 forced tiers, PLAN 185/185. Vulkan0 SPARSE_ATTN 772/772 across 4 tiers, PLAN 92/92. FLASH_ATTN_EXT identical to master case by case.
ctest 21/21 QSA subsets on HIP, Vulkan and CPU
HIP prefill f16 1.00–1.08×, q8_0 1.02–2.77×
HIP decode f16 0.998–1.000×, q8_0 0.99–1.13×
Vulkan prefill f16 0.998–1.003×. q8_0 1.02–1.12× at 4k depth, 1.66–2.15× at 32k
Vulkan decode 0.997–1.068×
MTP decode (default draft, 32k depth) f16 1.040×, q8_0 1.168×
memory every KV type within f16 + 0.27 MiB (HIP, 9 types, main + MTP). Device high-water equal to #219. Default 4-slot server at c262144: 1,648 MiB main
quality PPL identical across rebases. Pinned KLD against #219 inside the band for 6 KV types. Image answers correct for 18/18 KV types and prompts. -np 2 with images: 0 reserve overruns
HIP VGPR gate 0 spills, 6,824 kernels

Known limitations

Rollback

Revert the merge commit. There is no runtime switch back to the masked route. The per-cell prefer_dense and G policies are backend tables, so a cell can be flipped back to dense with a one-line change.

Evidence

Everything is on the qsa-rewrite-evidence branch, under scripts/qsa-validation/evidence/final219/. It holds the plan, the measurements, the proof reports (PROOF-.md, REBASE.md) and the lab harnesses. The previous, much longer version of this description, with the full gate tables against #219, is saved there as PR276-description-v2.md.

Reviewed with Claude (Opus 5.5).

https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ

gaetan-puleo added a commit that referenced this pull request Nov 12, 2026
PROOF-final.md is the partial proof on the pre-trim head 4d40d7f (paused).
PROOF-final2.md is the end-to-end proof of PR #276 head 49a6d75 (trimmed,
rebased on master 50c2c8c) on strix-002: KLD, images, -np 2, MTP, perf vs
master, depth 266240, the f16 V-pack cap (AT-O) and Vulkan model runs.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
@gaetan-puleo
gaetan-puleo force-pushed the qsa-rewrite branch 2 times, most recently from 7e7c75b to e2bed0b Compare November 13, 2026 05:05
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
REBASE3.md: rebase onto b620b0d (#272 conflict, its regression test) and
verification. PROOF-final3.md: remaining coverage gates (M1, M2, M5, M6,
AT-O at ub512/1024, Q1-C, Q3, Q4, Q8, Q11, P1, P4, Vulkan decode).
REBASE4.md: rebase onto 1dd4c92 (#271 deleted with the maskless path,
#225/#249/#254 kept), the M5 multi-slot reserve fix and its verification.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
@gaetan-puleo
gaetan-puleo marked this pull request as ready for review November 13, 2026 05:06
gaetan-puleo added a commit that referenced this pull request Nov 13, 2026
iggy and others added 11 commits November 13, 2026 09:42
…ip input views

hip: qsa_decode (wmma) and qsa_prefill read q8_0 K/V. The decode kernel
dequantizes in registers; the prefill pack converts while packing (the direct
f16 path is skipped for q8_0). Both use the same half product as
dequantize_block_q8_0_f16. Complete-block selection now also takes q8_0 K/V
when every QSA layer runs on ROCm (selected_key_q8), so a q8_0 cache no longer
falls back to the masked per-cell top-k.

qwen4exp: the masked top-k path took a fresh view of the KQ mask and the QSA
bias for every 512-query score strip in every layer. The scheduler gives each
view of a host input its own copy, kept for the whole graph, so this made
n_layers x n_strips copies. With Signal-3.8-Flash-Next Q4_K_XL, -ub 4096 and a
q8_0 cache, the ROCm0 compute buffer was 7193 MiB at 32k (vs 3009 before
bb030af) and grew about 0.15 MiB per context cell (~41 GB at 262k), so the
MTP draft context hit OOM. The views are now built once per graph and shared:
2969 MiB at 32k, 10.7 GB at 262k. Perplexity is bit-identical.

[qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b)
onto base ea5285d (origin/master, "Merge pull
request #251"). Dry-run before the import: temporary index from
git read-tree ea5285d, then git apply --cached --check of 68da419,
b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary
index after its check; resulting tree 449aba6). #234 (head 7774790) is
not in the base (git merge-base --is-ancestor), so no conflict resolution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F4rLkt7MokKFKji9hxCaev
(cherry picked from commit 68da419)
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…tests

- selected_key_attn now comes from a probe op with the real K/V types, at
  one query and at 513 (past the decode kernels). selected_key_q8 and the
  "ROCm" backend-name check are gone: a q8_0 cache on a model whose GQA
  ratio is not 12 (q8_0 decode is WMMA-only) or on Vulkan (flash_attn_sel
  is f16-only) now takes the masked route instead of falling back to CPU.
  LLAMA_QSA_SELECTED_KEY=1 forces the selected-key route for q8_0 too.
- The QSA attention log line names the cache types it was decided for.
- strip_views is keyed on the strip size too, which varies with the
  layer's compress ratio.
- test-backend-ops: q8_0 and mixed K/V variants of the maskless QSA
  decode and prefill tests.

[qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b)
onto base ea5285d (origin/master, "Merge pull
request #251"). Dry-run before the import: temporary index from
git read-tree ea5285d, then git apply --cached --check of 68da419,
b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary
index after its check; resulting tree 449aba6). #234 (head 7774790) is
not in the base (git merge-base --is-ancestor), so no conflict resolution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F
(cherry picked from commit b604475)
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
qsa_prefill_impl1 packed the whole q8_0 K and V cache to f16 on every
ubatch in every QSA layer, because the direct reads were f16-only: O(n_kv)
work per ubatch and f16-sized pool buffers, eating into what a q8_0 cache
saves. qsa3_attn_kernel now takes a Q8 flag: a direct K chunk (dims 32w ..
32w+31 of a key) is exactly q8_0 block w, loaded as aligned dwords and
realigned (the block offset is wave-uniform); direct V reads each key's
byte and scale. Both dequantize in registers with the decode kernel's
exact half conversion, so every QSA_DIRECT mode stays bit-identical to the
pack (llama-perplexity KLD vs QSA_DIRECT=0 at the floor of identical runs;
test-backend-ops passes in modes 0/1/2/auto). Mixed K/V types still pack.

The auto heuristic is shared with f16: K direct, V direct too when the
attention is small against the cache. q8_0 at b/ub 4096 (Signal-3.8-
Flash-Next Q4_K_XL): K direct 1347 / 1272 t/s vs pack 1350 / 1284 at
pp4096 depth 0 / 32k, within noise.

[qsa-rewrite W0] Imported unchanged from PR #219 (head 94e0868, base 13a279b)
onto base ea5285d (origin/master, "Merge pull
request #251"). Dry-run before the import: temporary index from
git read-tree ea5285d, then git apply --cached --check of 68da419,
b604475, 94e0868 in order: OK, OK, OK (each applied to the temporary
index after its check; resulting tree 449aba6). #234 (head 7774790) is
not in the base (git merge-base --is-ancestor), so no conflict resolution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MVWHkbGaTYszPeocGAku4F
(cherry picked from commit 94e0868)
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…QKL_SPLIT

[qsa-rewrite W12] Validation tooling for the QSA quality gates (PLAN-v3 §13 W12, §15).

--kl-divergence now prints, after each chunk,

  QKLD_CHUNK <chunk, 0-based> all=<mean> lo=<mean> nlo=<n> hi=<mean> nhi=<n>

at %.9e, computed straight from that chunk's kld_values. The existing table
is cumulative over chunks and printed with 5 decimals, which is too coarse
for the paired per-chunk statistics of the gates (R1-Q8: the 5-decimal
table gave a paired SE of 0.82e-5 where full precision gives 4.69e-6).
lo / hi are the means over chunk positions < QKL_SPLIT and >= QKL_SPLIT
(default 2048).

QKL_TAIL=N scores the last N positions of each chunk instead of the second
half (2 <= N <= n_ctx - 1, rejected otherwise). It applies to the base
recording (perplexity with --kl-divergence-base) and to --kl-divergence;
the base file does not record N, so the base and its arms must use the
same N.

Without the variables the scored window is unchanged; the only addition is
the QKLD_CHUNK line. The line format is the one of the R1-AV lab hunk
(EV/r1av/r1av_full.diff), so the committed analyzers under
scripts/qsa-validation parse PR219-arm and new-arm logs alike.

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ntity of a self-replay)

[qsa-rewrite W12] The self-replay check of the QSA quality references was
stated as "per-chunk KLD 0 (<= 3.7e-7, the uint16 base quantization)"
(PLAN-v3 §13 W12, §16.5). 3.7e-7 is the largest chunk R1-UB observed, not
a bound: on W0-lab the ref16t0, vref8t0 and ref2k self-replays print
4.672e-7, 3.787e-7 and 7.508e-7, and the ref16t0 chunks equal R1-E's own
round-1 self-replay at %.9e. A KLD against a uint16 base cannot show bit
identity.

QKL_HASH=1 prints `QKL_HASH {base|kld} <chunk> <hash> n=<floats>` after
each chunk: a 64-bit FNV-1a hash (4 interleaved lanes) of the bits of the
logits the KLD scores, in the base recording and under --kl-divergence.
A replay is bit-identical iff the hashes match chunk by chunk. Off by
default (it reads every scored logit once more).

scripts/qsa-validation/w12: phase S (re-record every reference and its
self-replay with QKL_HASH=1; the analyzer gates on hash equality and on
the re-recorded reference reproducing the campaign's self-replay at
%.9e, and reports the 3.7e-7 figure without gating on it); the
direct-form base self-checks other than H3's q4_0 are reported, not gated.

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
Two ops for QSA sparse attention over quantized or float K/V caches
(PLAN-v3 §2, §3, §13 W1):

- ggml_sparse_attn_plan(sel, n_kv, G): canonicalises per-query selection
  rows (I32 [n_sel, n_q, 1, n_stream], any order, duplicates, -1 and
  out-of-range values) into a grouped plan, G in {1, 4}: a 64-byte header
  ("QSAP", version 1, n_bad), then counts / quads (strictly ascending
  physical quad ids) / masks (bit 4*j + c), 256-byte aligned sections,
  every byte defined. ggml_sparse_attn_plan_get_layout / _nbytes /
  _scratch_nbytes give the layout; the sort/dedup scratch is not part of
  dst.
- ggml_sparse_attn(q, k, v, plan, scale, rot_q, rot_o): attention of each
  query over its plan cells with the numeric contract documented in
  ggml.h (K/V to_float rounded to f16, q through H_q, x scale in f32,
  rounded to f16; f32 scores; online softmax with P rounded to f16 for PV
  and l summed from the f32 p; acc / l and H_o in f32). Build-time asserts
  include the quad bound k->ne[1], v->ne[1] >= 4*ceil(n_kv/4).

Touchpoints:
- the two enum values are appended right before GGML_OP_COUNT (no op value
  moves); GGML_OP_NAME / GGML_OP_SYMBOL static asserts 101 -> 103;
- ggml-rpc.h: RPC_PROTO_MINOR_VERSION 0 -> 1 and its static_assert (the
  hello only compares major/minor and deserialize does no op validation);
- ggml_op_alloc_size_may_expand += both ops (GPU backends over-allocate
  dst for the plan scratch and the attend workspace);
- meta (tensor-split) backend: supports_op is false for both ops and the
  split-state switch aborts with a named message instead of "not
  implemented";
- ggml-cpu: forward dispatch, n_tasks (all threads: the plan has two
  phases separated by a barrier) and work sizes; supports_op of SPARSE_ATTN
  requires a to_float for K and V.

CPU forwards (ggml-cpu/sparse-attn.cpp, a TU of its own compiled with
-ffp-contract=off so that s += q*k and acc += p*v are never fused):
- plan: phase 1 per query row (valid cells, sort only when not already
  strictly ascending, unique) into the work-buffer scratch, barrier, phase 2
  per group (k-way merge by quad, mask OR, pad to a multiple of 4 with
  mask-0 entries on the last quad);
- attend: threaded over (stream, query, kv head) items; each visited K/V
  cell is dequantized once per kv head and used by the r query heads;
  scores summed sequentially over d with the r heads in the vector lanes;
  H_q / H_o are the butterfly order of ggml-cpu's hinted Hadamard mul_mat.

Verified (logs strix-002:~/dev/wt_rewrite_logs/W1, ~/dev/wt_lab/w1/res):
the CPU op is bit-equal to R1-M-Lab A's bands_ref.h O_CON on the wiki d4k,
SYN 262k and 7 UNI fixtures for every pair of {f32, f16, bf16, q8_0, q4_0}
(3.35e9 values, 0 different, G1 == G4), and within the contract-vs-f64 and
CPU-FA bands (scripts/qsa-validation/summaries/w1_ocon.md, next commits).

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…, determinism runs

test-backend-ops (PLAN-v3 §14.1):
- test_sparse_attn_plan: n_q {1,2,8,127,128,129,512,513,4096} x n_sel
  {1,257,2051,4096} x n_kv {4,2051,4096,65536,270336,1048576}, rows
  ascending / permuted / duplicates / -1 / out-of-range / all -1 / mixed /
  complete quads, G {1,4}, 1-2 streams, plain / interleaved / strided rows
  (169 cases). err() is an exact whole-dst comparison (max error 0) and
  verify_reference() memcmps the dst with the C3 oracle on every backend.
- test_sparse_attn: every pair of the 9 types of S, both V-loader regimes
  for every S_fast pair, n_q up to 4096, all-visible rows, n_kv 2051 with
  views of 2052 rows ending at their buffer's end (K last or V last),
  n_kv up to 1048576 and 2^21 + 4 (f16 / q8_0), GQA 4/8/12, rotations,
  2 streams, empty rows, poison (NaN / inf values and scales in cells no
  query selects, reach of a padded quad asserted on the plan), V-side
  overflow (bf16, q8_0, stored inf; finite-only NMSE plus the expected
  inf set), a non power-of-two scale, and the QSA_*_MASKLESS shapes with
  their cell formulas, including the q8_0 / mixed K/V case list #219 added
  (301 cases). run_whole_graph with fusion_test_nodes = {attend}. On the
  CPU backend the bound is 0 and verify_reference() checks the output bit
  for bit against the O_CON host reference; on other backends the bound is
  the §14.2 band of the class the dispatch census reports (keys
  sa_attend/G4/..., sa_attend/G1/.../splits<n>, listed by the census proc
  ggml_backend_debug_dispatch_census_list, a NULL-terminated key array the
  GPU work items implement); no class is a FAIL.
- determinism hook n_determinism_runs (2 for both ops): backend1 is
  computed again and its compared outputs memcmp'd with the first run.
- --fail-unsupported: a "not supported" result FAILS unless the case is on
  its backend's expected-unsupported list (Vulkan: G = 4, K/V views past
  1 GiB); engagement checks become mandatory (implied opt-in, a missing
  census proc fails).

tests/sparse-attn-ref.h: the C3 oracle (C3's std::map cpu_plan, G and
streams generalised, ggml.h layout) and O_CON (R1-M-Lab A's
oracle_group(O_CON), generalised); both test TUs are built with
-ffp-contract=off.

tests/test-sparse-attn-plan-oracle.cpp (ctest): 1080 synthetic plans
memcmp'd against the C3 oracle (dst pre-filled with 0xA5), the
over-allocation check (a buffer type whose get_alloc_size over-allocates
both ops allocates and computes through ggml-alloc without the
ggml-backend.cpp alloc-size assert, same output), and captured rows files
(C3 / C5 record format, --shuffle as c3_plan).

Results (strix-002:~/dev/wt_rewrite_logs/W1): SPARSE_ATTN_PLAN 169/169 and
SPARSE_ATTN 301/301 on CPU with --fail-unsupported in the CPU-only, HIP and
Vulkan builds; a mutated reference (P not rounded / a stray mask bit) fails
85/91 and 24/40 of the selected cases; plan vs C3 oracle on the
recaptured C3 rows 288/288 identical.

Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
GGML_OP_SPARSE_ATTN_PLAN on HIP (PLAN-v3 §2.1, §6.2, §13 W2), whole dst
byte-identical to the CPU op and to the C3 oracle:

- sparse-attn-plan.cu: three kernels on the op's stream, no pool use.
  sa_plan_init writes the header (n_bad = 0) and the zero gaps;
  sa_plan_rows (one block per query row) validates, counts n_bad and, for
  a row whose valid cells are not already strictly ascending with every
  invalid entry after them, sorts (in-place bitonic network in its flip
  form, no power-of-two padding) and dedups it into the scratch; a row
  already in that form only gets a marker and is read from sel by the
  merge; sa_plan_merge<G> (512 lanes for G = 4, 256 for G = 1) merges the
  G sorted rows of a group by quad with C3's ASC lane split, then writes
  the ggml.h padding up to cap (16/8-byte stores). Rows or groups too
  long for LDS run the same algorithms on global memory
  (GGML_CUDA_SA_PLAN_GLOBAL=1 forces it for tests).
  Ported from the union builder qsa3_rows_kernel / qsa3_merge_kernel
  (qsa-prefill.cu:28-240; git blame at ea5285d: Piotr Wilkin and Gaetan
  Puleo, no #219 line) and C3's sa_merge<ASC, 512>.
- supports_op true on every HIP device (integer kernels); false on CUDA
  builds (D22). get_alloc_size = max dst over the G table + the sort /
  dedup scratch (§2.1, P2-15); compute asserts that dst owns that
  over-allocation.
- sparse-attn-census.h: the census keys are generated from the G table
  that also instantiates and dispatches the merge (sa_plan/G1,
  sa_plan/G4), plus qsa_expand (counted where the fused expand runs).
  HIP procs ggml_backend_debug_dispatch_census_{reset,count,get,list,skip};
  GGML_CUDA_DISPATCH_CENSUS_LOG=1 prints the census at exit.
- HIP graphs: the census ids dispatched while a graph is captured are
  recorded into ggml_cuda_graph::census_ids and counted again at every
  replay, so the census counts launches with graphs on or off (in-model
  llama-bench: qsa_expand=267 either way).

Results (strix-002, gfx1151): -o SPARSE_ATTN_PLAN -b ROCm0
--fail-unsupported 185/185 with graphs on, graphs off and the forced
global-memory kernels; C3 harness on recaptured d131k rows, G4
0.719 ms/layer text, 0.831 random (gate <= 1.0), every layer bit-exact
vs the CPU op and the C3 oracle; 0 VGPR spills, 0 scratch, -Werror clean
(scripts/qsa-validation/summaries/w2_plan_c3.md).

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
- test_sparse_attn_plan checks the dispatch census on GPU backends: the
  compare ran exactly one sa_plan/G<group> dispatch and none of the
  other group (required under --fail-unsupported or
  GGML_SA_TEST_REQUIRE_CENSUS=1; the CPU reference backend is exempt).
- 16 cases with n_sel 9000 (2 x n_sel x 4 B is past a block's LDS on
  gfx1151), 2 streams, rows asc / perm / dup / mix, n_kv 4096 and 65536,
  G 1 and 4: they reach the global-memory rows kernel of the HIP plan
  without forcing it.

ROCm0 185/185 (graphs on / off / GGML_CUDA_SA_PLAN_GLOBAL=1), CPU 185/185
in the HIP, Vulkan and CPU-only builds. Mutants of the HIP kernels
(padding quad 0, no dedup, n_bad not counted) fail 149 / 87 / 94 cases.

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…#219)

The element conversions and the K / V loaders of the HIP sparse-attention
WMMA kernels (PLAN-v3 §2.2 contract item 1, §6.2, D8, D10):

- sparse-attn-q8.cuh: sa_q8x2_to_h2 is PR #219's qsa3_q8x2_to_h2 /
  qd_q8x2_to_h2 (qsa-prefill.cu / qsa-decode-wmma.cuh of 94e0868), one
  copy instead of three; C18 checked it bit-equal to
  dequantize_block_q8_0_f16 (4905 prefill + 4320 decode bitwise checks).
  sa_q4x2_to_h2 is C18's q4_0 trick (0x6400 | q, minus 1032).
  sa_bf2_to_h2 / sa_bf1_to_h convert bf16 with one RNE rounding and
  +-inf on overflow (the op contract and to_fp16); C18's helper
  saturated to +-65504, this one does not.
- sparse-attn-loaders.cuh: the type ids of the WMMA tiers, the split K
  piece loaders (half-wave dequant + v_permlanex16, C18 "X"), the
  split-gather direct V loaders, the per-cell select of masked V, and
  the traits: K split for every type in the G4 attend (C18 measured
  f16 split = direct: 12.43 / 12.60 ms wiki d4k, 16.32 / 16.33 d131k;
  direct f16 K does not fit 192 VGPRs in the GQA 12 instances with a
  direct quantized V); V pack-limit trait default CAPPED for every type
  (packed iff n_kv < 64 * n_q, OWNER decision 2026-11-05).

Not used by any TU yet (the G4 attend lands next).

Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
GGML_OP_SPARSE_ATTN with a G = 4 plan on RDNA3.5 (PLAN-v3 §6.2, §13 W3),
rot_q = rot_o = 0; G1 (W4), generic / portable tiers (W5) and the in-op
rotation (W10) stay unsupported (supports_op false).

- sparse-attn-attend-g4.cuh: sa_attend_g4<KT, VT, VL, EPI, GQA>, the PR
  qsa3_attn_kernel body (qsa-prefill.cu at 94e0868, as C18 took it
  over: Q prologue, WMMA order, online softmax, 2 barriers, epilogue)
  with the loaders of sparse-attn-loaders.cuh, no mask path, EPI plain
  or gated (+ f16 / bf16 aux store for an MMB reader) as a template,
  rows = 4 queries x GQA {4, 8, 12}, streams on grid.z, the ggml.h plan
  layout, q * scale in f32. Masked-off cells contribute nothing: K / V
  of cells no query of the group attends are zeroed by select, scores of
  cells the row's query does not attend are -inf. A non-finite V half
  of a cell attended by only some queries of the group would give
  0 * inf = NaN to the others through the shared PV WMMA, so it is taken
  out of the WMMA: packed V by sa_pack_v (written as 0, quad flagged),
  direct V by an in-loop check (one packed FMA per dword) that flags the
  block; sa_attend_fixup recomputes the blocks that touch a flagged quad
  or were flagged, with the CPU op's per-cell arithmetic. The fixup keeps
  the WMMA loop free of exact-path code, which did not fit 192 VGPRs at
  GQA 12; the check lives in the pack for packed V because in the loop
  it cost about 4 % of the kernel time on the C18 rows (W3 lab).
- sparse-attn-attend-g4-{f16,bf16,q8_0,q4_0}.cu: the 4 x 48 attend and
  4 x 8 fixup instances, one TU per K type.
- sparse-attn-pack.cu: sa_pack_v<T> (the PR qsa_pack_v indexing, per
  stream and kv head) into the attend dst over-allocation (no pool),
  with the quad flags and an any-flag for the fixup.
- sparse-attn-attend-g4.cu: sa_select (instance, V loader), supports_op,
  get_alloc_size = round_up(nbytes, 256) + max over G {1, 4} and
  n_q' <= n_q (and runtime n_kv' <= n_kv) of the workspace: CAPPED pack
  min(4 ceil(n_kv / 4), 64 n_q) cells x 512 B x n_head_kv x n_stream
  with its flags, or the direct path's per-(block, wave) flags; dispatch;
  the test switch
  GGML_CUDA_SA_FORCE=vpacked|vdirect, and the census skip for the keys a
  forced process cannot dispatch.
- sparse-attn-census.h: keys generated from the instance tables:
  sa_attend/G4/<KT>/<VT>/<packed|direct>/<plain|gated>/gqa<n> (the §6.2
  key is the prefix of its 3 gqa instances), sa_fixup/G4/<KT>/<VT>/<EPI>,
  sa_pack/<VT>.
- ggml-cuda.cu: get_alloc_size / compute / supports_op cases; the gate
  fusion matcher SPARSE_ATTN -> [views] -> CONT(gate) -> SIGMOID -> MUL
  (the FA branch stays until W13), with the overlap check extended to
  the plan and the node's own workspace; the census skip proc consults
  the forcing switch.
- common.cuh / ggml-cuda.cu: the HIP graph node properties include the
  source types. Two graphs whose only change is an F16 <-> BF16 source
  (same pointers, ne, nb) were replayed with the stale kernel: found by
  the W3 cases (bf16 V after f16 V at equal addresses, NMSE 0.5).

Resources: 228 sparse-attn kernels, 0 spills, 0 scratch (-Werror TU
builds, scripts/hip/gcn-cdna-vgpr-check.py parse_assembly).

The kernel body, the q8_0 helper it calls and the direct-V switch
n_kv >= 64 * n_q port #219 code.

Co-authored-by: Iggy Jackson <iggy@theiggy.com>
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
Only the removed LLAMA_QSA_TRACE / LLAMA_STRICT_RESERVE output read it.

Assisted-by: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
ggml_cuda_sa_g1_launch and ggml_cuda_sa_gen_g1_launch copied the same 22
fields from the launch parameters; both now call sa_g1_args_from
(sparse-attn-attend-g1.cuh). The generic launcher still sets kt_g / vt_g on
top. Same arguments, same launches.

Not compiled here (no hipcc): needs a HIP build.

Assisted-by: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
The comment join had glued each '// ---- <section> ----' rule to the first
line of the section's description; each header is now '// ---- <section>: ...'.

Assisted-by: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
The test hook ggml_backend_debug_vk_sa_binding_limit reported
min(maxStorageBufferRange - align, suballocation block), 1 GiB on RADV,
while supports_op checks each SPARSE_ATTN / SPARSE_ATTN_PLAN binding
against maxStorageBufferRange (near 4 GiB on RADV). test-sparse-attn-vk
built a K/V view just past 1 GiB, expected a refusal and got support.

A binding up to maxStorageBufferRange works: ggml-alloc gives a tensor
larger than the block a buffer of its own, and four test-backend-ops cases
already run past 1 GiB on Vulkan (f16 and q8_0 K/V views past INT32_MAX
bytes, f32 K/V at 1M cells). So the hook now reports the limit supports_op
applies; the dst + workspace allocation keeps its suballocation block check.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… after a restore

The rewrite's compact predicate (qsa_key_2d, the duplicate (pos, y, x)
key check) and the scan's ranking read the image x/y of the indexer
cells. The indexer cache has no rope of its own, so its saved state has
no x/y, and llama_memory_hybrid_idx::state_read takes them from the
attention cache (ext_2d_copy, from master). This checks it on the
hybrid-idx memory of a qwen4exp model without weights: slot 0 holds
text, an 8x8 image and text (slot 1 text as well, with two slots); slot
0 is saved and restored into a fresh memory.

- every restored indexer cell has the x/y of its attention cell, and the
  63 2D cells of the image are 2D again;
- the compact verdict of the next text ubatch is the one before the save:
  compact with one slot, 2-D cells with another sequence with two.

Without the ext_2d_copy call the restored image cells all sit at x = y
= 0, and the next ubatch of the one-slot memory is non-compact
(duplicate (pos, y, x) key), which a single-sequence context turns into
a decode error.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
Under --fail-unsupported the QSA_EXPAND cases required a "QSA_EXPAND"
census count on every backend with a census proc. The HIP census counts
the fused expand as "qsa_expand", so `-o QSA_EXPAND -b ROCm0
--fail-unsupported` failed all 56 cases with no compare error. Pass the
label to engagement_required, as the QSA_SCORE check does: the HIP skip
proc reports it is not a HIP key and the check is skipped there, while
Vulkan still requires one QSA_EXPAND dispatch per strip.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
… QSA layers

Since the TE rows read their visibility from the KQ mask (the Vulkan TOPK_QSA
fusion), qwen4exp_te_select built a [1, n_kv, n_query, n_stream] view of the
strip's mask in every QSA layer. The mask is a host input, and the scheduler
gives every view of a host input that a device node reads its own device
copy, allocated with the split's other inputs at its start. So the
non-compact reserve of a multi-slot context held one mask-sized copy per QSA
layer (12 x n_ctx x 1 KiB f16 at ub512 on the main context, 1 on the MTP
context) next to the copy the mask cast reads. Default llama-server (4 slots,
c262144, f16): main compute buffer 4720.02 MiB, MTP 1889.02 MiB.

The view is now built once per strip and graph (qwen4exp_te_vis_cells, shared
through te_vis like strip_views), and the mask cast of expanded's ADD reads it
too, so one device copy serves every layer and both reads. The cast stays per
layer: the fusion needs it single-use. With an f32 mask the ADD's reshape of
the view is shared too (that route had the same per-layer copy before). The
view node is expanded into the graph ahead of the chain: between the chain's
CONT and the cast it keeps the Vulkan TOPK_QSA pattern (consecutive nodes)
from matching (test-backend-ops census TOPK_QSA ...,strip=te: 0/3 without
that, 3/3 with it). Same default server: 1648.02 / 1633.02 MiB, the values
before the TE rows read the mask. test-qsa-te-rows and test-backend-ops
QSA_TE_STRIP build the strip the same way.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
The rewrite rebased onto master 1dd4c92, plus the TE-rows mask fix
(f54eb9f). The master commits past b620b0d (#225, #249, #254, #271,
#282, #288) touch no HIP file and the fix touches only src/ and tests/,
so the baseline should hold; this commit is the regeneration that checks
it.

Pinned image rocm/dev-ubuntu-26.04@sha256:4f5ed1bf..., git archive of
f54eb9f (the head before this commit), the two build steps of
hip-quality-check.yml in a clean build directory
(scripts/qsa-validation/harness/w13/vgpr_in_image.sh of the evidence
branch, unchanged):
- -Werror -Wno-tautological-compare build: rc 0; 18 warnings, none
  fatal under the CI flags (the same 18 as on the previous base);
- test_vgpr_check.py: 21 tests OK;
- EXPORT_METRICS On build: rc 0, 167 *.lto.s.

Checker against the committed baseline: PASS, 6824 kernels across 162
TUs, 0 VGPR-spilling symbols, 11 SGPR-spilling symbols, all 11 bounded
by baseline entries (3 sgpr_lane_spill, 8 sgpr_lane_spill_slower).
Regeneration with scripts/hip/README.md's python, verbatim:
minimum_kernel_count 6824 -> 6824, TUs 162 -> 162, copies 7164 -> 7164,
no TU count changed. Only source_revision moves, 6805faa -> f54eb9f
(and three TU keys move in the file's key order, values unchanged); the
file equals the previous regeneration (7e7c75b) except for
source_revision. Checker against the regenerated baseline: PASS.

The compiler string is the image's (AMD clang 24.0.0git d6f6cb691863).
The regeneration python and the checker ran on the host, reading the
image's assembly, as in W13.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
test-sparse-attn-vk, test-sparse-attn-rot and test-qsa-guard called setenv and
unsetenv, which the Windows CRT does not declare: set the variables through a
test_setenv helper that uses _putenv_s there, as test-qsa-fast does. The
Hadamard fill counts bits with std::bitset instead of __builtin_popcount.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
…ND_DL builds

test-sparse-attn-plan-oracle, test-sparse-attn-checks and test-qsa-guard call
the CPU backend directly (ggml_backend_cpu_init, ggml_backend_cpu_set_n_threads,
ggml_graph_compute_with_ctx), which a GGML_BACKEND_DL build does not link: the
Windows Vulkan CI failed to link them. Build them under NOT GGML_BACKEND_DL AND
GGML_CPU, as test-barrier and test-quantize-fns are.

Assisted-by: Claude Opus 5.5

Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
@dzannotti dzannotti added the in-review We are reviewing. label Nov 13, 2026
@dzannotti dzannotti added verifying Building and running the PR to verify its claims. and removed in-review We are reviewing. labels Nov 13, 2026
@dzannotti dzannotti self-assigned this Nov 13, 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 two ops are correct and deterministic on ROCm, Vulkan and CPU, and on ROCm the PR is a large win. But on current master it makes Vulkan q8_0/q4_0 prefill slower, the Vulkan portable tier lost the device in our run, one ctest now fails on head only, and the branch conflicts with master after #201.

Direction

Accept after work. The design is right, and it fixes the #219 problems we flagged: no pool scratch, no atomicCAS dedup, no silent CPU fallback, and on ROCm the q8_0 compute buffer at c131072 ub4096 drops from 21.5 GiB to 4.1 GiB. Where the new op has no tuned tier (non-RADV Vulkan, non-RDNA3.5 HIP, CUDA/Metal/SYCL), and for Vulkan q8_0/q4_0 until #287 closes the gap, it must not replace master's working route. After the rebase, consider landing it as ops+CPU+RPC, then HIP, Vulkan, and llama/qwen4exp. 16k lines in one PR is hard to review and hard to bisect.

Asks

  1. Blocking. Vulkan q8_0/q4_0 prefill is 5-7% slower than current master at depth 12000-64000 (table below). Master already has the #271 typed FA path there, so the "1.02-2.15x" claim does not hold today. Keep master's route for those cells (for example through ggml_backend_vk_sparse_attn_prefer_dense, ggml-vulkan.cpp:11129) until the sparse attend is at parity, and measure the claim again against current master. #287 tracks the gap to f16, not this gap to master.
  2. Blocking. The portable tier must not be a default path. On gfx1151 with GGML_VK_SA_FORCE=portable, pp2048 ub4096 ran at 0.08x of master at depth 0. At depth 32000 the compute ring timed out twice and the run died with ErrorDeviceLost. Every Vulkan device without the cm or scalar tier (ggml-vulkan.cpp:4483-4507, for example 32-lane NVIDIA and Intel) gets this tier. The forced HIP portable tier (non-RDNA3.5, sparse-attn-attend-g4.cu:127) ran at 0.62x for f16 at depth 32000. Fall back to master's masked FLASH_ATTN_EXT route there, and on backends without the op (CUDA, Metal, SYCL), instead of the portable tier or an init error. At minimum, split the portable dispatch so that it cannot hit the ring timeout.
  3. Blocking. test-qwen4exp-mtp-cache-only (tests/CMakeLists.txt:245) passes on master and fails on head on both GPU builds. The guard rejects the tiny model: its GQA ratio is not in {4, 8, 12} on HIP, and its head size is not 256 on Vulkan. Give the test a supported shape (or let it use the fallback from ask 2), and fix the PR body, which says that master fails it too. Also fix the Vulkan message, which tells a Vulkan user to "use a ... Vulkan build".
  4. Blocking. Rebase onto master c054baa8e. It conflicts with #201 (EXL3) in ggml.h/ggml.c (op enum), ggml-rpc.h (version and op count), ggml-cpu.c, ggml-cpu.cpp, ggml-cuda.cu, src/models/models.h and the VGPR baseline JSON. EXL3 also changes qwen4exp, so run the SPARSE_ATTN suites and one end-to-end qwen4exp check again after the rebase.
  5. Should fix. The SPARSE_ATTN/PLAN cases fail under test-backend-ops -j 4 (310 on ROCm0, 114 on Vulkan0; all pass with -j 1), because the workers share the dispatch census. Make them -j safe, and put the test hooks behind one compile-time define: the census, the per-call getenv of GGML_CUDA_SA_FORCE, rot_dump, and the vpack pipelines. In RPC, RPC_PROTO_MIN_SERVER_MINOR_VERSION 1 (ggml-rpc.h:14) makes every new client reject every 8.0 server, for every model. Accept 8.0 servers and report the two sparse ops as unsupported there. Also check the plan header offsets, counts and quad indices on the server before the attend reads them.
  6. Should fix. 77 of 99 commits have no Assisted-by: trailer. Several commit messages and the PR body contain a host name, home paths and a private model name, and so does the qsa-rewrite-evidence branch in this repo. A split or a squash per area, with clean messages, fixes all of this at once.

Nits: the ggml.h text says every backend matches the CPU op exactly, but the WMMA tiers match within a band. ggml.h:2651 is a 542-character comment line. QWEN4EXP_SHORTCUT_PIN_DEFAULT makes the scheduler-placement branch dead code. Vulkan q8_0 is +95 MiB over f16 at c131072 ub4096, not +184 MiB.

Correctness

PASS on the numerics, FAIL on the test suites (asks 3 and 5).

  • Op level: SPARSE_ATTN 1439/1439 and PLAN 185/185 on ROCm0, on the default and 8 forced tiers, with HIP_LAUNCH_BLOCKING unset and =1. Vulkan0 772/772 and 92/92 on the default and 6 tiers. The CPU passes too. The plan bytes are identical on CPU, ROCm and Vulkan, and 5 separate runs are identical. FLASH_ATTN_EXT and MUL_MAT_HADAMARD are unchanged against master.
  • Model level (Qwen3.8-Flash-Next Gyro-M TQ2_0): prompt tokens identical, and every SPARSE_ATTN node is on the GPU for 9 KV types. The f16 KLD against master over 16k context is inside master's own batch-size noise on both backends, and every quantized type is within 0.001 KLD of master's same type. No NaN at 32k. The VGPR gate shows 0 spills in 6824 kernels.
  • Non-QSA models (a dense and a hybrid) have byte-identical logits, tokens, greedy output and compute buffers on both backends.

Performance

llama-bench pp2048, -b 4096 -ub 4096 -r 5, 2 alternated rounds, tok/s. The stddev is 0.4-4.6 on every row at depth.

backend, KV depth master PR change
ROCm f16 32000 998.7 1006.9 +0.8%
ROCm q8_0 32000 564.7 997.9 +76.7%
ROCm q8_0 64000 382.8 982.9 +156.8%
Vulkan f16 32000 1021.7 1023.6 +0.2%
Vulkan q8_0 12000 1035.4 958.5 -7.4%
Vulkan q8_0 32000 1011.7 943.5 -6.7%
Vulkan q8_0 64000 957.8 904.7 -5.5%
Vulkan q4_0 32000 1012.8 951.3 -6.1%
Vulkan f16, portable tier forced 0 1119.6 91.6 -91.8%

Decode (tg128) is neutral or better on both backends, with ROCm q8_0 at depth 32000 +13.9%. At -ub 512, Vulkan q8_0 is -3.7% to -5.0% at depth.

Verification

Strix Halo (gfx1151), ROCm and Vulkan (RADV). This review covers head 37ccb7509. We tested b128e0fb1 merged into master 58e69e504, and that tree is byte-identical to 37ccb7509 (same 99 patches, rebased). We compared it against master 58e69e504. Master has since moved to c054baa8e, and the PR conflicts with it (ask 4).

Not tested

Images (no mmproj for this family here), real non-gfx1151 HIP and non-RADV Vulkan hardware (forced tiers only), sessions, RPC, partial -ngl, and MTP at 32k depth.

Thanks for the rewrite; the op contract and the tests make this much easier to check than the old routes.

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. Strix Halo, Radeon 8060S (gfx1151), 128 GB unified memory. ROCm 10.1.0-3 (hipconfig 7.16.26385), AMD clang 24.0.0git d6f6cb691863. Mesa RADV 26.0.8 (mesa-vulkan-drivers 26.0.8-1ubuntu0.3), libvulkan1 1.4.341. cmake 4.2.3, gcc 15.2.0, Ninja.

Compared

  • PR head reviewed: 37ccb7509 (live). The tested tree is e31ad0597, which is b128e0fb1 (the head when the review started) merged with --no-ff into master 58e69e504. git diff e31ad0597 37ccb7509 is empty, and git range-diff shows all 99 patches identical.
  • Base: master 58e69e504. Merge base of b128e0fb1: 1dd4c926c (5 commits behind; the merge was clean).
  • Current master c054baa8e (after #201 and #285): git merge-tree reports conflicts in ggml/include/ggml-rpc.h, ggml/include/ggml.h, ggml/src/ggml-cpu/ggml-cpu.c, ggml/src/ggml-cpu/ggml-cpu.cpp, ggml/src/ggml-cuda/ggml-cuda.cu, ggml/src/ggml.c, scripts/hip/gfx1151-vgpr-baseline.json and src/models/models.h. Not resolved by us: the RPC version, the op order and the VGPR baseline are the author's choice.

Build

Same flags on both sides, all targets:

cmake -G Ninja -S <tree> -B <tree>/build-hip -DCMAKE_BUILD_TYPE=Release -DGGML_HIP=ON -DGGML_VULKAN=OFF -DGPU_TARGETS=gfx1151 -DCMAKE_HIP_COMPILER=$(hipconfig -l)/clang -DCMAKE_PREFIX_PATH=$(hipconfig -R)
cmake -G Ninja -S <tree> -B <tree>/build-vk -DCMAKE_BUILD_TYPE=Release -DGGML_VULKAN=ON -DGGML_HIP=OFF

Head HIP -Werror: the same HIP line plus -DCMAKE_HIP_FLAGS="-Werror -Wno-tautological-compare", target ggml-hip: clean. VGPR gate: the same HIP line plus -DGGML_HIP_EXPORT_METRICS=On -DCMAKE_HIP_FLAGS="" on both trees, checked with master's scripts/hip/gcn-cdna-vgpr-check.py. GGML_RPC is off in these flags, so the RPC tests were not built.

Models

  • agentionai/Qwen3.8-Flash-Next-Gyro-GGUF, Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf, sha256 7aa36d15131d255179ab6c87fa9c9f81a0b541fc9e81e959d4c3e29eb20feb5f. qwen4exp, 12 QSA layers. Always run with -lm none -lzm on-direct -ngl 99 -fa on.
  • MTP sidecar mtp-Qwen3.8-Flash-Next-Q4_K_M.gguf, sha256 8087dbb39fc73f79ac069b1debe4069a44b73ada900c8bd761569d43a5a90231.
  • Qwen/Qwen2.5-1.5B-Instruct-GGUF, qwen2.5-1.5b-instruct-q4_k_m.gguf, sha256 6a1a2eb6d15622bf3c96857206351ba97e1af16c30d7a74ee38970e434e9407e (dense).
  • ibm-granite/granite-4.0-h-1b-GGUF, granite-4.0-h-1b-Q4_K_M.gguf, sha256 da3d737121a96f3c9a316685212376257a7f167b74380855666dd488d6af3bcb (hybrid).
  • Corpora tests/corpus/correctness-{code,numeric,prose,structured}.txt, identical in both trees (sha256 dec1127a..., d9f08d94..., c90398f2..., c21947b3...).

Commands

  • Ops: test-backend-ops test -b <dev> -o SPARSE_ATTN and -o SPARSE_ATTN_PLAN with GGML_SA_TEST_REQUIRE_CENSUS=1. ROCm0: default plus GGML_CUDA_SA_FORCE= vpacked, vdirect, generic, portable, fixup, g1, g4, plan_global, with HIP_LAUNCH_BLOCKING unset and =1. Vulkan0: default plus GGML_VK_SA_FORCE= scalar, portable, portable_sg32, vdirect, vstaged, vpack. Also -b CPU. Determinism: the default tier in 5 separate processes per backend.
  • Base vs head: test-backend-ops test -b <dev> -o FLASH_ATTN_EXT (and MUL_MAT_HADAMARD), with HLB unset and =1 on ROCm. Full suite: test-backend-ops test -b <dev> -j 4. ctest -L main -E 'test-opt|test-llama-archs', test-llama-archs -b <dev> -a qwen4exp, test-vk-exact.
  • Placement and buffers: GGML_SCHED_DEBUG=2 llama-completion -m <model> -c 131072 -b 4096 -ub 4096 -ctk <k> -ctv <v> -n 4 -v.
  • Logits: llama-debug -f <corpus> -c 16384 -b 16384 -ub 512 -ctk f16 -ctv f16 --save-logits, base twice (A/A), then head.
  • KLD: the reference is master f16 on the same backend. Short: llama-perplexity -f <corpus> -c 2048 -b 2048 -ub 2048, with the floor = master at -ub 512. Long: the 4 corpora joined, -c 16384 -b 512 -ub 512, with the floor = master at -ub 2048 (extra floors at ub 1024 and 256). The KV types are f16, q8_0, q4_0, bf16 and q8_0 K / f16 V, on both sides.
  • Greedy: llama-completion -f <corpus> -n 256 --temp 0 --seed 1 -no-cnv --ignore-eos -c 16384, base twice.
  • Perf: llama-bench -m <model> -p 2048 -d 0,12000,32000,64000 -n 0 -r 5 -b <B> -ub <B> -ctk <t> -ctv <t> with B 4096 and 512. Decode: -p 0 -n 128 -d 0,32000. Base and head alternated, 2 rounds. The portable stand-in uses GGML_VK_SA_FORCE=portable or GGML_CUDA_SA_FORCE=portable on head only (master has no such tier).
  • Long tail: -ub 1/500/4096/8192; -ngl 0; -nkvo (llama-bench -p 512 -n 32 -d 0,16000); llama-perplexity -c 4096 -b 16384 -ub 2048 -np 4, with and without -kvu; MTP with llama-speculative-simple --spec-type draft-mtp -md <sidecar> -c 16384 -b 16384 -ub 2048 -n 256 --temp 0.

Results

Compute buffer at c131072, b/ub 4096 (MiB):

K/V ROCm0 master ROCm0 PR Vulkan0 master (first/final) Vulkan0 PR (first/final)
f16/f16 4133.44 4133.44 6303.09 / 6063.89 5926.94 / 5883.78
q8_0/q8_0 21514.53 4133.70 6303.36 / 6048.98 6022.08 / 5924.08
q4_0/q4_0 21514.53 4133.70 6303.36 / 6048.98 6022.08 / 5924.08
bf16/bf16 21418.27 4133.44 26212.27 / 26242.27 5926.94 / 5883.78
q8_0/f16 21514.52 4133.69 6303.34 / 6062.97 5927.19 / 5884.03
f16/q8_0 21418.28 4133.45 6303.11 / 6048.73 5926.95 / 5883.80
iq4_nl/iq4_nl 4809.01 (50 graph splits, CPU attention) 4133.70 6303.36 / 6048.98 6022.08 / 5924.08

Graph splits are 2 on head for every type on both backends, and every SPARSE_ATTN / SPARSE_ATTN_PLAN node is on the GPU. At -ub 8192 -c 16384, the Vulkan head buffer is 4216.12 MiB against 3896.99 MiB on master (+319 MiB). On ROCm it is equal. No head buffer grew after the reserve at ub 1, 500, 4096 or 8192.

Final f32 logits, f16 KV, head against master (last position): code KL 7.3e-5 / 1.4e-4 (ROCm / Vulkan), numeric 1.4e-2 / 2.2e-3, prose 2.5e-4 / 3.4e-4, structured 1.9e-2 / 5.1e-3. The argmax is the same in every case. Master A/A is byte-identical on all 4 corpora, and so are the prompt tokens.

KLD, long (16k context, sparse path), Mean KLD against master f16:

ROCm0 Vulkan0
floor (master ub2048; ub1024/256) 0.004532 (0.004359 / 0.005167) 0.005310 (0.005738 / 0.005104)
PR f16 0.005069 0.004181
q8_0 master / PR 0.004943 / 0.004698 0.005642 / 0.005692
q4_0 master / PR 0.015382 / 0.015062 0.014143 / 0.014943
bf16 master / PR 0.005293 / 0.004587 0.004963 / 0.005215
q8_0 K, f16 V master / PR 0.004900 / 0.004984 0.005053 / 0.004763

The PPL ratio is within 0.998-1.002 for every row. The short runs (-c 2048) take the all-visible shortcut, so they do not exercise the sparse attend. There, PR f16 against master f16 is 0.000000 on every corpus on both backends. At 32k context on ROCm: PR f16 0.002455, PR q8_0 0.002797, master q8_0 0.002830, with no nan.

Greedy, 256 tokens: master A/A is identical. The PR output differs from master on 4/4 corpora on ROCm and on 2/4 on Vulkan, as expected from the logit change. The text stays coherent.

pp2048 tok/s, avg (stddev) for round 1 / round 2:

backend KV ub depth master PR
ROCm0 f16 4096 0 1114.29(20.06) / 1102.90(22.08) 1100.44(16.45) / 1103.68(22.09)
ROCm0 f16 4096 12000 1016.41(1.01) / 1011.87(1.40) 1018.96(1.56) / 1020.06(1.81)
ROCm0 f16 4096 32000 999.91(3.31) / 997.39(3.76) 1007.33(3.51) / 1006.45(3.72)
ROCm0 f16 4096 64000 990.22(5.42) / 988.91(5.29) 995.62(6.28) / 995.88(4.51)
ROCm0 q8_0 4096 0 1075.18(13.87) / 1078.62(19.92) 1094.94(22.42) / 1093.78(24.05)
ROCm0 q8_0 4096 12000 796.94(0.41) / 796.55(0.54) 1011.73(0.69) / 1012.11(1.02)
ROCm0 q8_0 4096 32000 564.91(0.71) / 564.44(0.60) 998.28(1.58) / 997.42(1.82)
ROCm0 q8_0 4096 64000 382.89(0.51) / 382.72(0.66) 983.11(2.85) / 982.70(2.85)
ROCm0 f16 512 0 806.88(4.40) / 808.55(8.89) 809.43(8.73) / 809.83(8.81)
ROCm0 f16 512 32000 693.43(2.89) / 693.39(2.42) 723.83(3.30) / 724.07(3.42)
ROCm0 q8_0 512 0 805.38(8.12) / 805.72(8.91) 817.70(10.75) / 817.60(10.88)
ROCm0 q8_0 512 32000 468.71(1.19) / 469.14(0.88) 715.56(2.28) / 716.11(3.08)
ROCm0 q8_0 512 64000 327.77(1.35) / 327.98(0.88) 708.68(4.37) / 709.55(4.72)
Vulkan0 f16 4096 0 1134.34(31.06) / 1118.88(26.47) 1114.59(21.72) / 1116.81(26.80)
Vulkan0 f16 4096 12000 1049.93(3.56) / 1045.16(3.27) 1046.56(4.10) / 1045.35(3.86)
Vulkan0 f16 4096 32000 1023.19(4.58) / 1020.20(4.22) 1024.81(3.92) / 1022.32(2.16)
Vulkan0 f16 4096 64000 975.96(4.57) / 974.26(3.00) 980.50(2.14) / 978.89(3.40)
Vulkan0 q8_0 4096 0 1104.66(21.40) / 1110.20(25.34) 1106.81(23.68) / 1108.81(21.56)
Vulkan0 q8_0 4096 12000 1035.96(4.70) / 1034.92(3.39) 959.40(3.98) / 957.60(3.60)
Vulkan0 q8_0 4096 32000 1011.11(1.61) / 1012.35(3.49) 945.55(0.66) / 941.40(4.17)
Vulkan0 q8_0 4096 64000 958.57(2.92) / 956.98(2.58) 904.75(3.40) / 904.71(2.37)
Vulkan0 q8_0 512 12000 713.72(1.15) / 713.98(1.87) 677.88(1.25) / 677.82(1.34)
Vulkan0 q8_0 512 32000 695.72(2.11) / 696.33(1.44) 664.89(3.06) / 663.78(0.61)
Vulkan0 q8_0 512 64000 668.29(2.04) / 667.59(1.54) 643.27(4.63) / 643.74(2.67)

An earlier, partial Vulkan run (stopped for reasons unrelated to the PR) agrees with these numbers within 1%.

Other KV types, pp2048 ub4096, d0 / d32000, master -> PR: ROCm0 q4_0 1083.1 -> 1098.7 / 567.8 -> 1003.0, bf16 1088.0 -> 1100.6 / 571.5 -> 1006.9, q8_0 K f16 V 1085.0 -> 1099.5 / 566.7 -> 1002.1. Vulkan0 q4_0 1119.3 -> 1110.3 / 1012.8 -> 951.3 (0.939x), bf16 1059.1 -> 1090.0 / 300.3 -> 1001.1, q8_0 K f16 V 1088.1 -> 1085.0 / 1015.8 -> 994.7 (0.979x).

tg128: ROCm0 f16 27.76 -> 27.76 (d0), 26.07 -> 26.09 (d32000). ROCm0 q8_0 27.56 -> 27.58, 22.70 -> 25.86. Vulkan0 f16 31.76 -> 31.75, 28.76 -> 28.85. Vulkan0 q8_0 31.55 -> 31.54, 28.44 -> 28.58.

Portable tiers, forced, pp2048 ub4096, master's normal route -> PR portable:

  • Vulkan f16: d0 1119.6 -> 91.6 (0.082x). q8_0: d0 1118.0 -> 91.6. At d32000 the f16 run hit ring comp_1.1.0 timeout twice, then reset compute queue and vk::Queue::submit: ErrorDeviceLost. One retry at pp512 ub512 d0 ran clean at 277.3 against 852.1 (0.33x).
  • HIP: f16 d0 1112.7 -> 1108.0, d32000 997.9 -> 617.0 (0.62x). q8_0 d0 1086.0 -> 802.0 (0.74x), d32000 564.9 -> 617.5.

Long tail (ROCm0 / Vulkan0):

  • HIP_LAUNCH_BLOCKING=1 model logits are byte-identical to unset.
  • -ngl 0: pp 0.94x, tg 0.98x of master.
  • -nkvo: pp512 at d16000 +5% / +13% for f16 and +9.5% / +10% for q8_0; tg equal.
  • -np 4: PPL equal, speed equal or better. Load time is +190 to +439 ms (+7 to +10%).
  • MTP sidecar at 11-12k prompt depth: -3% to +13%, following the acceptance rate, which moves with the changed output. The new ops run in the draft context on both backends.

Suites:

check master PR
test-backend-ops full, ROCm0 -j 4 40572/40572 41722/42032 (310 SPARSE_ATTN/PLAN, shared census; pass at -j 1)
test-backend-ops full, Vulkan0 -j 4 44194/44194 44696/44810 (114, same cause)
FLASH_ATTN_EXT ROCm0 (HLB unset/=1) / Vulkan0 4051 / 4051 / 5383 all pass same
ctest HIP 2 fail (tokenizers-ggml-vocabs, grammar-parser) same 2 + test-qwen4exp-mtp-cache-only
ctest Vulkan 3 fail (same 2 + test-llama-context) same 3 + test-qwen4exp-mtp-cache-only
new QSA/sparse-attn ctests (18) n/a all pass on both GPU builds
test-vk-exact 11 known failures the same 11
test-llama-archs -a qwen4exp pass pass
VGPR gate PASS, 6288 kernels PASS with the PR JSON, 6824 kernels, 0 VGPR spills. With master's JSON the only misses are the deleted qsa-* files

Deleted cases: QSA_PREFILL, QSA_DECODE and their MASKLESS variants (166 cases on ROCm0, 250 on Vulkan0). No other op lost GPU cases.

Correctness

check method result
changed ops, all tiers test-backend-ops SPARSE_ATTN / PLAN PASS (ROCm HLB unset and =1, Vulkan, CPU)
determinism 5 processes + in-process memcmp; logits A/A PASS
plan bytes equal across backends PLAN cases memcmp against CPU and host reference PASS
full backend suite test-backend-ops -j 4 FAIL (test harness, ask 5)
ctest -L main FAIL (test-qwen4exp-mtp-cache-only, ask 3)
test-vk-exact binary same as master
HIP -Werror, VGPR gate build, gate script PASS
placement, no CPU fallback GGML_SCHED_DEBUG=2, 9 KV types PASS
f32 logits + tokens, 4 corpora llama-debug tokens identical, logits changed (expected), quantified above
KLD/PPL short and long llama-perplexity PASS (inside master's batch noise)
greedy decode with A/A llama-completion differs, as expected; coherent
non-QSA models logits, tokens, greedy, buffers byte-identical
performance llama-bench ROCm PASS; Vulkan FAIL (q8_0/q4_0 -5..-7%)
portable tiers (stand-in) forced env Vulkan 0.08x and device lost at d32000; HIP 0.62x
images, sessions, RPC, partial -ngl, server -np 2 - not run

Findings in full

  • Vulkan q8_0/q4_0 regression against current master: see the tables. Master's q8_0 runs at 0.99x of its own f16 at depth on Vulkan; the PR's q8_0 runs at 0.92-0.94x of its own f16.
  • Portable tier as a default: ggml-vulkan.cpp:4483-4507 sets portable on any device with 12 invocations and 2 KB of shared memory. The scalar tier needs 64-lane subgroups, and cm needs RDNA3 + RADV. On HIP, sparse-attn-attend-g4.cu:127 sends every non-RDNA3.5 device to portable. sparse-attn-portable.cu is compiled only for HIP, so CUDA has no tier and qwen4exp fails at init there.
  • supports_op on Vulkan returns true once the tier gate passes. The pipeline compiles later, so a compile failure becomes a runtime abort, not the init error the description promises.
  • ggml_backend_sched_reserve_size (ggml-backend.cpp:2285) no longer resets. That is an upstream function, and its public contract changes. Prefer a fork-only variant.
  • About 550 lines of QSA logic are inside sched_reserve, graph_reserve and process_ubatch in llama-context.cpp. A fork file with a few hook calls would keep upstream syncs cheap.
  • Vulkan scalar tier: sa_sg64 does not require full subgroups when the driver has size control without computeFullSubgroups. HIP: one non-finite V value flags a whole quad for the fixup kernel on every step (sparse-attn-pack.cu:34-52). Both backends: a misaligned view offset passes supports_op and aborts at dispatch.
  • test-qsa-guard is built but not registered with ctest. test-sparse-attn-vk and test-sparse-attn-rot exit 0 when the GPU is missing, so a skip counts as a pass.
  • include/llama.h:428 adds type_k_idx in the middle of llama_context_params (ABI).

Claims

claim result
ROCm0 SPARSE_ATTN 1439/1439 on 9 tiers, PLAN 185/185 reproduced
Vulkan0 SPARSE_ATTN 772/772, PLAN 92/92 reproduced (the 667 G4 cases are HIP only)
PLAN output bit-identical on CPU, HIP and Vulkan reproduced
deterministic, no atomicCAS dedup reproduced
no silent CPU fallback reproduced for the sparse ops
scratch inside the reserve reproduced (no buffer growth after the reserve)
master q8_0 21,579 MiB vs f16 4,133 MiB on ROCm0 reproduced (21514.53 vs 4133.44)
every KV type within f16 + 0.27 MiB on HIP reproduced (+0.26 max)
Vulkan q8_0/q4_0 +184 MiB over f16 not reproduced (+95 / +40 MiB)
HIP prefill f16 1.00-1.08x, q8_0 1.02-2.77x reproduced (0.99-1.05x, 1.02-2.57x up to 64k)
HIP decode f16 0.998-1.000x, q8_0 0.99-1.13x reproduced
Vulkan prefill f16 0.998-1.003x reproduced
Vulkan prefill q8_0 1.02-2.15x not reproduced against current master (0.93x at 32k)
Vulkan decode 0.997-1.068x reproduced (1.000-1.005x)
MTP decode at 32k depth not tested at 32k; mixed at 12k
HIP VGPR gate 0 spills, 6,824 kernels reproduced
f16 no longer bit-identical, KLD in band reproduced
ctest QSA subsets pass reproduced; but test-qwen4exp-mtp-cache-only is a new failure
test-qwen4exp-mtp-cache-only fails on master too not reproduced on GPU builds (master passes)
image ubatch reserve overrun fixed not tested

Not tested

  • Images and mmproj: no mmproj for this model family on the test machine.
  • Real non-gfx1151 HIP and non-RADV Vulkan hardware: only the forced portable tiers on gfx1151.
  • Session save/load, RPC (GGML_RPC is not in the build flags), partial -ngl, llama-server -np 2 with two prompts.
  • MTP at 32k depth, and the qwen35 27B parity.
  • Op-level SPARSE_ATTN timing: test-backend-ops perf has no cases for these ops.
  • The rebased tree on master c054baa8e.

@dzannotti dzannotti added risk:high Risk: high waiting-user We asked the author for something. and removed verifying Building and running the PR to verify its claims. labels Nov 13, 2026
@dzannotti dzannotti assigned gaetan-puleo and unassigned dzannotti Nov 13, 2026
@gaetan-puleo

gaetan-puleo commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review. A first thought on ask 2, about keeping master's masked FLASH_ATTN_EXT route as a fallback on backends that have no SPARSE_ATTN kernel. This is not a final decision; I would like your view before choosing.

My argument against restoring it for CUDA, Metal, SYCL and the like is that this fork does not support those backends in any case:

  • The README's "Supported backends" lists Vulkan (RADV on the RDNA 3.5 iGPU), HIP (gfx1151), CPU, ZenDNN and RPC.
  • CUDA, Metal, SYCL, CANN, OpenCL and WebGPU are still in the tree, unmodified, but nobody builds or tests them here.

Keeping the masked route only for them would mean two QSA routes to maintain and test, for backends nobody runs on this hardware. Today, such a backend fails at init with an explicit message and never falls back to the CPU silently. The message names what does work: -ngl 0 (the CPU op runs anywhere), --no-kv-offload, or a HIP or Vulkan build. That looks acceptable to me for unsupported backends, but I can see the case for keeping master's behaviour there, and I am open to it if you think a load failure is worse than two routes.

The rest of asks 1 and 2 is about the backends we do support: Vulkan q8_0/q4_0 at depth against #271, and the portable tiers on HIP and Vulkan. That is a separate question, and I will come back to it with the rebase onto current master.

@gaetan-puleo

Copy link
Copy Markdown
Collaborator Author

@dzannotti I replied on ask 2 (the masked FLASH_ATTN_EXT fallback for backends without a SPARSE_ATTN kernel) in the comment above. I would like your view on it before I choose.

@dzannotti

Copy link
Copy Markdown
Collaborator

@gaetan-puleo Agreed on ask 2 for the backends we do not support. A clear load-time error that names -ngl 0, --no-kv-offload and the HIP / Vulkan builds is fine for CUDA, Metal, SYCL and the rest. Two QSA routes for backends nobody runs here is not worth the cost.

One thing to check before you rebase: an upstream sync is in progress, and upstream reworked the same area since our base. See ggml-org#30965 (qwen4exp QSA selection without the kq_mask), ggml-org#31009 (glm5-next QSA without kq_mask), ggml-org#30640 (fused QSA mask op) and ggml-org#31243 (k-pool sparse selection). Upstream may already drop the masked route for some cases. Please align with what upstream does there, so that we do not carry a fork-only design that the next sync has to undo. When the sync PR is open, I will link it here with the files where it overlaps #276.

The Vulkan tiers (asks 1 and 2) can wait for your rebase, as you suggest.

@dzannotti

Copy link
Copy Markdown
Collaborator

As promised, the upstream sync is up as a draft: #293 (upstream to e574a17, including the QSA rework ggml-org#30965, ggml-org#31009, ggml-org#30640 and ggml-org#31243).

A trial merge of this PR (head 37ccb75) onto the sync tip conflicts in 23 files:

  • Hard: ggml/src/ggml-vulkan/ggml-vulkan.cpp (FA path, plus supports_op next to upstream's TOP_K_MASK), src/llama-context.cpp (the QSA placement guard sits where upstream now has the scheduler reuse), src/models/qwen4exp.cpp (QSA graph).
  • Medium: ggml/src/ggml-cuda/common.cuh (upstream moved ggml_cuda_graph to graph.cuh), ggml/src/ggml-cuda/fattn.cu, ggml/src/ggml-cuda/ggml-cuda.cu, ggml/src/ggml-cpu/ggml-cpu.cpp, src/llama-kv-cells.h, and modify/delete on qsa-decode.cu / qsa-prefill.cu (the sync moved the top-k source from src[5] to src[6]; take your delete and check the replacement reads src[6]).
  • Easy: ggml-rpc.h (RPC version and op count: the sync has 102 ops, so with your two ops it becomes 104), ggml.h, ggml.c, ggml-backend.cpp, ggml-cpu.c, fwht.comp, vulkan-shaders-gen.cpp, llama-kv-cache.h, llama-memory-hybrid-idx.cpp, models.h, tests/CMakeLists.txt, tests/test-backend-ops.cpp, and gfx1151-vgpr-baseline.json (regenerate it after the merge).

This PR also conflicts with current master in 8 files, so the cheaper order is: #293 lands first, then you rebase onto it. The full per-file table is in the "QSA / #276" comment on #293. #293 is still a draft: it has open HIP and Vulkan validation items, so do not rebase yet.

@dzannotti

Copy link
Copy Markdown
Collaborator

@gaetan-puleo #293 (the upstream sync) is now merged, so this PR can rebase. We tried to rebase head 37ccb7509 onto master f2230a8e4 (1151 commits ahead of the PR's base 58e69e504). We stopped and did not push, because some conflicts are in real logic and we will not guess them.

A trial merge conflicts in 24 files.

Real logic (please resolve these yourself):

  • src/models/qwen4exp.cpp, build_attn_qsa, 2 hunks. Master now has a per-layer rotation (inp->self_k_rot[il], inp->self_v_rot[il]) where the PR reads inp->self_k_rot->ne[0] for rot_q / rot_o. Master also has the upstream maskless selected-key route (qwen4exp : build the QSA selection without the kq_mask ggml-org/llama.cpp#30965, qsa_inps[...]->maskless) beside the masked ggml_set_rows route. The PR replaces both with ggml_sparse_attn. Please decide how SPARSE_ATTN relates to the upstream maskless route, as discussed above, so that the next sync does not have to undo a fork-only design.
  • src/llama-context.cpp, 7 hunks. One hunk is about 370 lines of the PR's QSA guard and reserve code against master's vocab-subset code.
  • ggml/src/ggml-vulkan/ggml-vulkan.cpp, 7 hunks (FA path and supports_op), and ggml/src/ggml-cuda/fattn.cu, 2 hunks (dispatch).
  • ggml/src/ggml-cuda/qsa-decode.cu and qsa-prefill.cu: modify/delete. Keep your delete. Master moved the top-k source of the FLASH_ATTN_EXT op from src[5] to src[6], so check that your replacement code reads the right source.

Mechanical (op enum, op counts, lists, moved code):

  • ggml/include/ggml.h, ggml/src/ggml.c, ggml/include/ggml-rpc.h (RPC version and op count), ggml/src/ggml-backend.cpp, ggml/src/ggml-cpu/ggml-cpu.c, ggml/src/ggml-cpu/ggml-cpu.cpp, ggml/src/ggml-cuda/common.cuh (upstream moved ggml_cuda_graph to graph.cuh), ggml/src/ggml-cuda/ggml-cuda.cu, ggml/src/ggml-cuda/fwht.cu, vulkan-shaders/fwht.comp, vulkan-shaders-gen.cpp, src/llama-kv-cache.h, src/llama-kv-cells.h, src/llama-memory-hybrid-idx.cpp, src/models/models.h, tests/CMakeLists.txt, tests/test-backend-ops.cpp.
  • scripts/hip/gfx1151-vgpr-baseline.json: regenerate it after the rebase.

Master also removed the non-fused GDN path (ggml-org#32078) and rewrote the qwen4exp conv-state writes (ggml-org#30878, ggml-org#31660). Run the qwen4exp end-to-end check again after the rebase.

The asks in our review still stand. For ask 2, the load-time error on backends without the op (CUDA, Metal, SYCL) is fine, as agreed above. The Vulkan q8_0/q4_0 numbers (ask 1) and the portable tier (ask 2) must be measured against the new master. A split into ops + CPU + RPC, then HIP, Vulkan and llama/qwen4exp (as suggested in the review) would also make this rebase smaller.

Review made with AI on behalf of the strix-llama.cpp maintainers.

@dzannotti

Copy link
Copy Markdown
Collaborator

Branch is 1176 commits behind master and does not rebase cleanly, so we did not push. Please rebase onto current master (2c3dc19).
The first commit (f4ef456, SPARSE_ATTN ops) already conflicts in ggml/include/ggml.h, ggml/include/ggml-rpc.h, ggml/src/ggml.c, ggml/src/ggml-backend.cpp, ggml/src/ggml-cpu/ggml-cpu.c and ggml-cpu.cpp: master is at RPC proto 10.0.3 with the EXL3 ops, so the new ops and the RPC version bump need your call. Later commits were not tried.
Still waiting on the asks in the last review.

@Nathanw1014

Copy link
Copy Markdown

Thanks Gaetan (and Iggy for #219). I reviewed the ops, the CPU reference and the Vulkan side and ran it on Strix Halo. I didn't build or read the HIP part.

Correctness looks good on Vulkan. On 8060S with RADV (Mesa 26.2.4), head 37ccb75 passes:

  • SPARSE_ATTN_PLAN + SPARSE_ATTN 864/864 on the default tier;
  • SPARSE_ATTN 772/772 forced to scalar, portable, portable_sg32 and vpack;
  • 0 failures in 10 repeated runs;
  • FLASH_ATTN_EXT 5383/5383, with the same case list as base 58e69e5;
  • test-sparse-attn-vk, plan-oracle (1081/1081 identical) and the sparse-attn-checks sections.

Performance against the actual merge base. Qwen3.8-Flash-Next trunc8 UD-Q4_K_XL (a cut-down 73B variant, not the full model), llama-bench -fa 1 -ub 2048 -p 2048 -n 64, base/head/head/base. Base 58e69e5, head 37ccb75:

test f16 base -> head q8_0 base -> head
pp2048 d0 8697 -> 8634 (-0.7%) 8657 -> 8576 (-0.9%)
pp2048 d4096 8741 -> 8758 (+0.2%) 8663 -> 8175 (-5.6%)
pp2048 d32768 8398 -> 8478 (+0.9%) 8339 -> 7928 (-4.9%)
tg64 d4096 / d32768 112.1 / 108.9 -> 110.7 / 110.2 109.3 / 108.4 -> 110.3 / 109.0

The dispatch census confirms the new kernels run (sa_attend/vk/cm/direct/q8_0/q8_0).

On this base, q8_0 is already at f16 speed (0.99x at 32k). #270 added quantized K/V to the maskless Vulkan path before 58e69e5. I couldn't reproduce "master runs q8_0 at 0.42-0.56 of its own f16 at d32k" on this base. That gap does show up against ea5285d (before #270): there an earlier revision of this PR went 3386 -> 6846 for q8_0 pp2048 at 32k. Against the real base, Vulkan q8_0 prefill at depth is about 5% slower here and f16 is flat. Which base commit, ub and model were the Vulkan rows measured with?

Findings

  1. ggml-vulkan.cpp:11157: prefer_dense is only true on the cm tier. On the scalar and portable tiers, the f16 dense shortcut (qwen4exp.cpp:1964) therefore runs the sparse op, although ggml-backend.h:231 documents dense f16 as the default. With coopmat disabled on both builds, the census at d0 shows sa_attend/vk/scalar/staged/f16/f16 where the cm tier dispatches nothing, and pp2048 d0 drops 3874 -> 3613 (-6.7%) for both f16 and q8_0. It is flat at d8192.
  2. Portable tier speed. Devices without a 64-lane subgroup (NVIDIA, most Intel) only get sparse_attn_portable. Forced on this GPU, it runs at 0.05-0.07x of the cm tier: pp2048 d8192 8598 -> 452, tg32 d8192 108.3 -> 5.1. For comparison, base with coopmat off still does 3559 pp and 108.9 tg here. On master these devices fall back to masked top-k FA (llama-memory-hybrid-idx.cpp:133 in base). The PR deletes that route with no switch back, so this looks like a large regression for them. I haven't measured on NVIDIA hardware. Maybe keep dense FA or the masked route as the fallback there?
  3. qwen4exp.cpp:1766 with llama-context.cpp:1116-1135: with -nkvo, a GPU layer and f16/q8_0/q4_0/bf16 K/V, plan and attend are pinned to the layer's GPU without a supports_op check. On a backend without the ops (Metal, SYCL, OpenCL), that becomes an init error, although the CPU route in the next branch would work. The message then suggests --no-kv-offload, which was already set.
  4. ggml-vulkan.cpp:22814: with the "top_k without mask" gate removed, a maskless FLASH_ATTN_EXT with src[5] now passes supports_op and runs dense over every cell. Only a hand-built graph can reach it now (old RPC clients refuse 8.1 servers), so this is minor. Returning false for src[5] && !src[3] would still be safer.
  5. ggml-cpu/sparse-attn.cpp:306-315, 377: the attend trusts the plan header (off_*, cap, counts, quads). A plan written via SET_TENSOR over RPC can read out of bounds. Vulkan takes offsets and cap from the host layout but still trusts the counts and quads. Recomputing the layout from op_params and bounding counts and quads is cheap.
  6. Small:
    • llama-kv-cache.cpp:361 lets n_rot_k grow past 256, while ggml_sparse_attn asserts 64/128/256 (a head-512 variant would abort).
    • There are no test-backend-ops perf cases for the new ops.
    • The TOPK_QSA alloc-dep change in ggml_vk_graph_optimize (:21816) could use a line in the description.

The plan shader, the workspace-after-dst scheme and the split merge all read correct to me. Nice work on the tier gating and the test hooks.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants