Skip to content

CUDA: sparse flash attention decode for a q8_0 K/V cache - #33682

Open
milescoviello wants to merge 4 commits into
ggml-org:masterfrom
milescoviello:qwen4exp-qsa-kv-rows
Open

milescoviello wants to merge 4 commits into
ggml-org:masterfrom
milescoviello:qwen4exp-qsa-kv-rows

Conversation

@milescoviello

@milescoviello milescoviello commented Dec 4, 2026 •

Copy link
Copy Markdown

Overview

Sparse flash attention decode (the n_kv_max hint, as set by the qwen4exp QSA layers) now also takes the sparse MMA kernel when the K/V cache is q8_0. The index lists are computed before the f16 conversion and only the listed rows are converted with the kv_rows row converter, so a quantized cache no longer goes to the dense vec kernel, which reads every cell.

With a q8_0 cache, decode on Qwen4-35B-A3B at 128k goes from 68 to 122 t/s on an RTX 5090 Laptop GPU and from 108 to 137 t/s on an RTX PRO 6000. An f16 cache already took the sparse kernel, so this brings q8_0 close to the f16 speed rather than above it (98% of f16 at 128k on Ada/Ampere, measured by @wOvAN), with half the KV memory. The graph is unchanged, so the other backends keep the mask path. Cache types without a row converter (q4_0 and others) stay on the vec kernel; a vec-over-rows path for them can follow in a separate PR.

The CUDA change is by @ServeurpersoCom. The first commits of this PR changed the qwen4exp graph to attend to the selected cells as K/V rows instead. Review showed that this gives the prompt and decode graphs different topologies, so every prompt ubatch after a decode reallocated, and that it gives no gain on Metal, so that approach was dropped and src/ is unchanged from master.

Additional information

Tested on an RTX 5090 Laptop GPU (sm_120) with Qwen4-35B-A3B IQ4_XS, all layers on the GPU. test-backend-ops -o FLASH_ATTN_EXT passes on CUDA (4640/4640). "Before" is the same build with the new dispatch disabled.

llama-bench, tg128 t/s

-fa 1 -p 0 -n 128 -r 2

K/V d16384 d65536 d131072
q8_0 before 124.82 92.26 67.91
q8_0 this PR 142.41 135.64 121.93
q4_0 before 127.25 93.00 68.06
q4_0 this PR 130.07 92.89 67.68
Prompt after decode, server, KL divergence

llama-batched-bench -npp 32768 -ntg 32 -npl 1,1,2,2,1 -pps -kvu, q8_0: T_PP 6.68, 6.61, 6.64, 6.64, 6.64 s, no graph reallocations.

llama-server -c 262144 -ctk q8_0 -ctv q8_0, 256 greedy tokens after a filler prompt: 135.6 t/s at 7k, 124.8 at 91k, 110.4 at 183k. A recall test with 10 codes at depths 5% to 95% (two of them changed later in the text) is 10/10 at 200k tokens, with the answer generated at 112 t/s (42 t/s before).

KL divergence against an f16 reference (llama-perplexity on wiki.test.raw, -c 20480 --chunks 1), with one token per ubatch (-ub 1) so that every scored token is a decode step: 0.01795 +/- 0.00073 before (PPL ratio 1.0040), 0.01833 +/- 0.00076 with this PR (PPL ratio 1.0033). With -ub 4 both take the sparse MMA kernel and give the same result (0.016658).

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES. The first graph-level version, the measurements and this description were made with Claude Opus 5.5 (Claude Code), at my request. The CUDA commit is by @ServeurpersoCom.

Written with Claude Opus 5.5

At decode QSA keeps ~2k cells, but the mask path still runs attention
over the whole cache. With a quantized cache this is the dense vec
kernel, so decode slows down with depth. List the selected cells as
K/V rows (ggml_flash_attn_ext_rows) instead, gated by a fused-op probe.

Assisted-by: Claude Opus 5.5
@milescoviello
milescoviello requested review from a team as code owners December 4, 2026 10:06
@github-actions github-actions Bot added the model Model specific label Dec 4, 2026

@am17an am17an left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The approach looks right to me, reusing ggml_flash_attn_ext_rows without backend changes. A few things:

  1. The probe can enable the path without testing it. resolve_fused_ops reserves the probe graph with n_tokens = n_seq_max, but the rows path is only built for n_tokens <= 4. With -kvu -np 5 or more, no QSA layer emits a LLM_FUSED_OP_FLASH_ATTN_KV_ROWS node in the probe graph, the device check loop finds nothing, and fused_sel_rows is set to true. Decode then uses rows on a backend that was never checked for that K/V type. The probe should be built with at most 4 tokens, or the gate should not depend on n_tokens while probing.

  2. f16 at 16k is ~4% slower (147.86 -> 142.59 in the table). For an f16 cache CUDA already takes the sparse path via n_kv_max, and rows replaces it. Since the gain is for quantized caches, should the rows path only be used when K or V is quantized, or have a higher threshold for f16?

  3. n_tokens <= 4 and n_kv >= 4*GGML_PAD(n_sel, 256) should be named constants with a short comment on where they come from. With --spec-draft-n-max 4 or more, MTP verify silently goes back to the mask path.

  4. Metal/Vulkan are enabled by the probe but not measured. Given that kv_rows was slower than -INF skipping on Metal in #29510, I would either get a Metal number or keep this to CUDA for now. Does this work with -sm tensor? The scatter path has a workaround for the meta backend, and the new row/mask tensors need to be replicated across devices.

Minor:

  • inp->mctx->get_k(ctx0, il)->ne[3] == 1 creates a view in ctx0 per QSA layer just to read the stream count; this can come from the KV context or cparams.kv_unified.
  • top_score / live_pool / live_tail / live duplicate the scatter path below; they could be computed once after the optional sort.

@wOvAN

wOvAN commented Dec 4, 2026

Copy link
Copy Markdown

We hit the same effect on CUDA and it is much larger than -37% here: with two active sequences, one of them decodes 5-10x slower at long context. Independent data points below in case they help scope this PR, plus one question at the end.

Setup: llama.cpp b12973 (59b716523), unsloth/Qwen4-35B-A3B-GGUF (Qwen3.8-Flash-Next family, arch qwen4exp, indexer_top_k = 2048, 30 recurrent layers + 11 sparse-attention layers), 2x RTX 4080 + RTX 3090 with --split-mode layer, -fa on -c 524288 -b 4096 -ub 1024 --parallel 2 --cache-type-k f16 --cache-type-v f16 --spec-type draft-mtp --spec-draft-n-max 1. The ggml/llama side is the b12973 tarball; the CUDA backend in our image is built from ee4671584, 24 commits behind, so nothing in the ranges this PR touches is missing on our side. Your body says the CUDA sparse decode is only taken for f16 K/V, which is exactly our configuration, and the penalty is still 10x.

The measured shape: when two slots are both deep, the first sequence's decode step grows with its own n_kv - 48.6 ms/token at 32k, 71.9 at 48k, 155.9 at 100k, about 1.5 ms per 1k tokens, and 850 at 240k - while the second sequence stays at solo speed (11-16 ms/token). Solo decode at the same depth is healthy (12.75 ms/token at 100k, 14.30 at 240k), so the walk over cells beyond the sequence's own selection only appears once a second sequence is active. It is not the scheduler: with "priority": 1 on the slow slot the numbers do not move and both slots end up with bit-identical draft acceptance (0.98438, 126 accepted / 128 generated), so the two sequences do the same amount of work in 10x the wall time.

One question: this PR builds sel_rows inside build_qsa_sel, and the indexer still scores all pooled blocks of the cache - qwen4exp.cpp#L882-L885 - which is the O(total cache) part that commit 1 of #32247 ("score only the k-pools of the ubatch sequences") addressed. Is that scoping planned as a follow-up to this PR? We ask because the numbers below also reproduce with --no-kv-unified, where the row-list path of #29510 is not the mechanism, so the read side alone may not close it for us.

Matrix, all rows on the same instance, 2 concurrent /completion requests of N prompt tokens each, 256 tokens generated, greedy, per-slot numbers from `print_timing`
profile slot 0 slot 1
solo, N = 100k 78.45 t/s -
solo, N = 240k 69.95 t/s -
100k + 20k (second request starts 30 s later) 29.28 (at 20k) 69.85 (at 100k)
32k + 32k 20.58 68.78
48k + 48k 13.91 65.32
100k + 100k, --kv-unified 6.42 61.94
100k + 100k, --kv-unified, "priority": 1 on slot 0 6.43 63.86
100k + 100k, --kv-unified, --cache-ram 0 6.61 58.17
100k + 100k, --no-kv-unified 12.21 84.28
240k + 240k, --kv-unified 1.18 55.64
240k + 240k, --no-kv-unified 2.17 90.78

All rows use --spec-type draft-mtp --spec-draft-n-max 1, except the --spec-type none row called out below. 100k + 100k with --spec-type none gives 12.61 vs 68.98, and solo decode is 98.54 t/s at 100k with --spec-type none.

Ruled out by measurement on this host:

  • speculative decoding: with --spec-type none the asymmetry stays (12.61 vs 68.98 at 100k + 100k); --spec-draft-n-max 3 makes it worse (850 ms/token) but is not needed for it;
  • arrival order: sending the request for slot 1 first does not change the victim, it is still slot 0;
  • scheduler priority: see above, identical acceptance counters;
  • --cache-ram 0 (the RAM prompt cache; ~1.5 ms per 1k tokens of own context is close to PCIe bandwidth, which made it a good candidate);
  • unified KV: --no-kv-unified is about 2x better at 100k and 240k, but does not remove it.

Two notes on the workarounds listed in #32181 for our case: --cache-idle-slots needs the prompt cache, and with the multimodal projector the server logs cache_reuse is not supported by multimodal, it will be disabled, so idle conversations cannot be parked in RAM; --no-kv-unified costs the 2x prefill throughput we measured with unified KV (2300 t/s per slot for 100k + 100k wall 44 s with --no-kv-unified, 1180 t/s per slot wall 83 s with --kv-unified), and as the table shows it does not remove the decode asymmetry here.

Reproducer: start the server as above, then fire two requests at the same time with a long filler prompt (N tokens) and n_predict: 256, and read prompt eval time / eval time per slot from the server log. Filler content is irrelevant, a repeated word list works; ignore_eos is not honored by /v1/chat/completions, so use /completion for forced-length runs.

AI disclosure: the measurements and this comment were gathered by an AI agent (Claude) operating this deployment; a human reviewed them.

Written with Claude

@wOvAN

wOvAN commented Dec 4, 2026

Copy link
Copy Markdown

Follow-up with one more measurement, because it suggests the unified path here is not "same numbers, just slower".

We switched this deployment to --no-kv-unified (keeping n_ctx_slot at 262144 by passing -c 524288 with --parallel 2) and re-ran our decode probe on the same instance, same build, same three GPUs, f16 KV, --spec-type draft-mtp --spec-draft-n-max 1. Speed moved the way the previous comment describes, but the MTP acceptance counters moved a lot more: the target accepts the MTP draft roughly twice as often once the sequences stop sharing cache cells. With n_predict = 128 at 32k depth, the draft is proposed 163 times with 72 accepted under --kv-unified, and 69 times with 57 accepted under --no-kv-unified.

We read that as the target's hidden states differing between the two layouts, not as a scheduling effect - the draft layer is fed by the target, so a 44 % to 83 % jump in agreement from a cache-layout change alone means the numbers going into attention are not the same. To be fair about what this does and does not prove: acceptance also depends on the generation trajectory, and our accuracy battery (29 greedy single-answer tasks, --reps 2) is 29/29 with stable = 1.000 on both layouts, so we cannot say which layout is closer to correct, only that the unified path changes target output and not just its speed. If the kpool scoring of #32247 lands on top of this, the acceptance numbers may be a cheap way to check that it does what it says.

decode probe, same instance before and after the layout change; accept = accepted / drafted tokens
probe prefill t/s decode t/s accept
tg128@32768 3319.6 -> 3608.6 (+8.7 %) 107.46 -> 122.02 (+13.5 %) 0.442 -> 0.826
tg128@65536 3952.9 -> 4321.9 (+9.3 %) 86.55 -> 103.77 (+19.9 %) 0.313 -> 0.658
tg512@32768 4843.7 -> 5288.2 (+9.2 %) 106.71 -> 124.10 (+16.3 %) 0.457 -> 0.832
pair_tg256@32768 (2 slots) 9115.5 -> 9157.0 (+0.5 %) 90.03 -> 113.53 (+26.1 %) 0.349 -> 0.786

The 32k prompts are ~45.6k tokens, the 64k one ~89.5k (the probe pads with a fixed prose corpus). Peak VRAM 43159 -> 46359 MiB. The pair probes in this table are at 32k, where the per-slot decode asymmetry of the previous comment is not visible yet; at 100k and 240k the asymmetry is present on both layouts.

AI disclosure: the measurements and this comment were gathered by an AI agent (Claude) operating this deployment; a human reviewed them.

Written with Claude

@ServeurpersoCom
ServeurpersoCom self-requested a review December 4, 2026 13:20
@ServeurpersoCom

Copy link
Copy Markdown
Contributor

Tested with Qwen4-35B-A3B UD-Q8_K_XL, q8_0 K/V, all layers on an RTX PRO 6000, llama-bench tg64, same binary with and without LLAMA_SEL_ROWS_DISABLE.

Without this PR (mask path): 162 t/s at depth 0, 142 at 32k, 108 at 128k.

With this PR (rows path): 165 t/s at depth 0, 151 at 32k, 144 at 128k.

+1 on am17an's first point, it is the one that can bite: n_tokens_probe is n_tokens_per_seq*n_seqs, so with -np 5 or more the probe graph has no rows node, the device check loop finds nothing and the path gets enabled on a backend that was never checked.

@milescoviello would you be OK if I push commits on your branch to address am17an's review and finish the PR? I can also get the Metal numbers on an M5 Max.

- probe with one sequence, use the rows with one K/V stream only
- use the rows only for a quantized cache
- name the thresholds, allow up to 8 tokens per ubatch
- share the index and liveness code of the rows and scatter paths

Assisted-by: Claude Opus 5.5
@milescoviello

Copy link
Copy Markdown
Author

Thanks for the review. I pushed a commit for all points, and while testing it I found a problem with the approach itself, described in the last paragraph.

  1. The probe now reserves one sequence (n_seqs_max = 1 in llm_fused_op_probe), so its graph has the rows nodes. There was a second gap: without a unified cache and with several sequences, the full-cache context of the probe has several streams, so the rows were not built there but could still be used at decode. The rows are now used only with one K/V stream in total (kv_unified || n_seq_max == 1), so the probe and decode build the same graph.
  2. The rows are now used only when K or V is quantized, f16 keeps the mask path.
  3. The thresholds are named constants with a comment. At 128k, rows were faster up to 16 tokens per ubatch, so the limit is now 8, which covers --spec-draft-n-max up to 7 (numbers below).
  4. I have no Apple GPU, so Metal numbers from the M5 Max would be very welcome. For -sm tensor, test-llama-archs passes for qwen4exp on CUDA, CPU and Meta with the rows limits removed for the test (rows graphs built for n_tokens 1 to 64, NMSE vs CPU 8.6e-08, the mask path gives 8.9e-08).

The two minor points are done: the stream check uses cparams, and the optional sort comes first, so both paths share the index and liveness tensors.

The problem: decode with rows and prompt processing with the mask have different graph topologies. After a decode step, the next prompt reallocates on every ubatch, because the first ubatch after the switch reserves for its own small n_kv and each following one is larger. With llama-batched-bench at 32k, every prompt after the first decode takes 8.3 s instead of 6.5 s. llama-server logs one "same size" reallocation per prompt ubatch, although its prefill speed did not change in my runs. This looks like the topology issue from the kv_rows review in #29510. I see two ways out: do the gather inside the CUDA FA dispatch for quantized K/V when n_kv_max is set, so the graph stays the same (CUDA only, no probe), or keep the graph change and reserve the worst case again when the batch type switches. Which one would you prefer?

@ServeurpersoCom yes, feel free to push to the branch, thanks for testing. @wOvAN this PR does not change the indexer scoring, and it does not apply to an f16 cache or to several streams, so it will not help your case. Scoping the scoring to the ubatch sequences is not part of it.

Measurements (RTX 5090 Laptop GPU, Qwen4-35B-A3B IQ4_XS, q8_0 K/V)

llama-batched-bench -npp 131072 -ntg 32 -npl 1,2,4,8,16 -pps -kvu, S_TG t/s, with the token limit raised to 16 for this run:

B mask rows
1 70.65 123.46
2 113.45 205.13
4 183.39 267.87
8 260.83 352.06
16 328.85 376.36

Prompt after decode, llama-batched-bench -npp 32768 -ntg 32 -npl 1,1,2,2,1 -pps -kvu, T_PP in s:

run 1 2 3 4 5
mask 6.70 6.50 6.51 6.54 6.57
rows 6.69 8.32 8.28 8.43 8.27

llama-bench tg128 at d65536 with the pushed commit: q8_0 97.67 (mask) and 139.41 (rows), f16 140.84 and 138.75 (both on the mask path now).

Written with Claude Opus 5.5

@sunboaooo-blip

sunboaooo-blip commented Dec 4, 2026 •

Copy link
Copy Markdown

Tested on 2x RTX 5060 Ti 16GB (SM120, 36 SM) with Qwen4-35B-A3B UD-Q4_K_M (master 9cc2807b vs PR head da1bfb91).

Benchmark:
llama-bench -d 0,65536,131072 -sm layer -ngl 99 -ncmoe 1 -fa 1 -p 2048 -n 128 -r 2, run with -ctk q8_0 -ctv q8_0 and with f16 KV

Decode (q8_0 KV):

  • 64K: 57.2 -> 79.4 t/s (+39%)
  • 128K: 42.5 -> 74.3 t/s (+75%)

Notes:

  • With LLAMA_SEL_ROWS_DISABLE=1 on the same build, it drops back to 42.7 t/s, so the gain comes from the new path.
  • f16 KV and prompt processing are unchanged.
  • 128K needle check (draft-mtp, temp 0) passes 3/3 on both master and this PR.

AI-assisted: drafted with an AI coding agent and polished with agy, measurements run and checked by me

@milescoviello

Copy link
Copy Markdown
Author

@sunboaooo-blip thank you for the run, the numbers are in the description now.

Written with Claude Opus 5.5

The one-sequence probe graph is not valid for other indexer models or for
several K/V streams (test-llama-context).

Assisted-by: Claude Opus 5.5
@milescoviello

Copy link
Copy Markdown
Author

The ubuntu test failure came from my second commit: the one-sequence probe graph is not valid for deepseek4, nor for qwen4exp with several K/V streams. Fixed in fff2f3d, the probe now runs only for k-pool indexer models with one K/V stream, which are the only cases that can use the rows.

test-llama-context with GGML_SCHED_DEBUG_REALLOC=1 passes on CPU for all 156 test models, and the rows path still engages on CUDA (q8_0 tg128 at d65536: 94.1 mask, 140.7 rows).

Written with Claude Opus 5.5

@Sheepdog-01

Copy link
Copy Markdown

Non-CUDA data point: on ROCm/HIP (RX 7900 XT, gfx1100) the rows path made decode at depth about 2x slower for us.

Setup

  • ROCm 10.2, HIP build (GGML_HIP=ON, GGML_CUDA_FA_ALL_QUANTS=ON, GGML_HIP_GRAPHS=ON, GGML_HIP_NO_VMM=ON).
  • b12973 (59b7165), alone and with this PR's commit cherry-picked (it applied cleanly).
  • Qwen4-35B-A3B UD-IQ3_XXS, with the PLE table on CPU (--ple ... -ot per_layer_token_embd=CPU).
  • llama-server -fa on -ctk q4_0 -ctv q4_0 -np 2 -c 393216 -ub 256 -b 2048, so kv_unified = 'false'. No speculative decoding.
  • Measurement: 512 decoded tokens after a prompt of the given length, temp 1.0 / top_p 0.95 / top_k 20, one request at a time. Same binary with and without LLAMA_SEL_ROWS_DISABLE=1.
tg t/s (512 tokens) d0 d43K d100K d167K
b12973 62.5 54.6 48.6 42.3
b12973 + this PR 62.9 29.9 22.0 16.8
b12973 + this PR, LLAMA_SEL_ROWS_DISABLE=1 63.0 54.9 49.0 42.5

Prefill is unchanged: about 1.80K t/s at 43K, 1.08–1.10K at 100K and 0.73–0.74K at 167K in all three runs. Since the env toggle restores the base numbers, the slowdown comes from the rows path itself.

With MTP (--spec-type draft-mtp,ngram-mod --spec-draft-n-max 1, 2x150K, two expert layers on CPU), prose decode went from 73.0 / 62.8 / 55.6 to 74.0 / 35.3 / 25.7 t/s at d0 / 43K / 100K. Draft acceptance was the same in both builds (~0.5–0.6).

I haven't profiled it, so I can't say which kernel is slow on HIP. If it can't be fixed there, a backend check that keeps HIP on the mask path might be the simplest option. I'm happy to run a build or profile it if that helps.

@milescoviello

Copy link
Copy Markdown
Author

@Sheepdog-01 thank you, that matches the probe gap from the review. In the CUDA/HIP backend, FA over K/V rows is NVIDIA only, so on HIP the op is not supported and the scheduler runs it on the CPU:

if (!(GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask)) {
return BEST_FATTN_KERNEL_NONE;
}

With -np 2 and no unified cache, the probe of the first commit had no rows node to check, so it enabled the path. Since fff2f3d the rows are only used with one K/V stream, so your command keeps the mask path, and with -kvu the probe sees the CPU fallback and disables it. If you have time, a run of the current head with and without -kvu would confirm that on HIP.

Written with Claude Opus 5.5

@ServeurpersoCom

Copy link
Copy Markdown
Contributor

Metal numbers on an M5 Max, same model and settings (Qwen4-35B-A3B UD-Q8_K_XL, q8_0 K/V), same binary with and without LLAMA_SEL_ROWS_DISABLE.

Decode does not gain on Metal: llama-bench tg64 is 60.3 t/s with the mask and 55.8 with rows at 32k, 58.8 and 60.5 at 128k, and llama-batched-bench decode at 32k goes from about 66 to 64 t/s.

The prompt after decode costs a bit here too: 18.0 s against 18.5 s with -ub 512, 15.65 s against 15.78 s with -ub 2048.

So the gain is CUDA only, which points to your first option: the gather inside the CUDA FA dispatch keeps the graph unchanged and leaves Metal on the mask path.

@milescoviello

Copy link
Copy Markdown
Author

@ServeurpersoCom thank you for the Metal numbers, that settles it. I will move the gather into the CUDA FA dispatch: for quantized K/V with n_kv_max set and a few queries, compact the mask to row indices with the existing flash_attn_mask_to_sparse_indices, gather the mask values, and run the vec kernel over those rows. The graph stays the same, so the probe, the cparams and the qwen4exp changes go away, and Metal, Vulkan and HIP keep the mask path.

I will push it here unless you have already started on it.

Written with Claude Opus 5.5

@ServeurpersoCom

Copy link
Copy Markdown
Contributor

I have it ready and will push it here now: the sparse indices are computed before the f16 conversion and only the listed rows are converted with the kv_rows row converter, so a q8_0 cache takes the existing sparse MMA path. The qwen4exp, cparams and probe changes go away, src/ is the same as master, and only the CUDA dispatch changes, so Metal, Vulkan and HIP keep the mask path.

Same setup as my earlier numbers: decode goes from 108 to 137 t/s at 128k, the prompt after decode takes 3.08 s against 3.09 s on master with -ub 512, and test-backend-ops FLASH_ATTN_EXT passes on CUDA.

Only q8_0 has a row converter for now, so q4_0 stays on the vec path like on master; your vec-over-rows idea could cover the other types in a follow-up.

The CUDA sparse decode gathers the selected cells in the MMA kernel,
but it was taken for f16 K/V only: a quantized cache went to the vec
kernel over the whole n_kv, so decode slowed down with depth.

Compute the sparse indices before the f16 conversion and convert only
the listed rows, with the row converter of kv_rows, so that a q8_0
cache takes the sparse path too. The graph is the same as on master,
so the qwen4exp rows path is removed: no fused-op probe, no graph
change between decode and prompt processing, and no effect on the
other backends.
@ServeurpersoCom
ServeurpersoCom requested a review from a team as a code owner December 4, 2026 16:21
@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Dec 4, 2026
@milescoviello

Copy link
Copy Markdown
Author

@ServeurpersoCom great, thank you. I will test your head on my RTX 5090 Laptop GPU (q8_0, decode at depth and with MTP) and post the numbers here.

The vec-over-rows version is ready on my side (q8_0 and q4_0, up to 8 queries, with test-backend-ops cases for 2/4/8 queries and a 2051-row list, all passing), so I can open it as a follow-up for the other cache types once this one is in.

Written with Claude Opus 5.5

@ServeurpersoCom

Copy link
Copy Markdown
Contributor

Sounds good, q4_0 and the other types in the follow-up. This is now a CUDA only PR, you can update the title and description with your numbers :)

@milescoviello milescoviello changed the title qwen4exp : attend to the selected cells as K/V rows at decode CUDA: sparse flash attention decode for a q8_0 K/V cache Dec 4, 2026
@milescoviello

Copy link
Copy Markdown
Author

Updated the title and description with the numbers from my RTX 5090 Laptop GPU: q8_0 decode at 128k goes from 68 to 122 t/s, the prompt after a decode is unchanged with no reallocations, test-backend-ops FLASH_ATTN_EXT passes, and KL divergence at decode is the same as before.

Written with Claude Opus 5.5

@Sheepdog-01

Copy link
Copy Markdown

Confirmed on HIP with the current head (f61908c). I used the same setup as above (7900 XT, ROCm 10.2, Qwen4-35B-A3B UD-IQ3_XXS, q4_0 K/V, -c 393216 -np 2 -ub 256, 512 decoded tokens per depth, one request at a time), and this time no env toggles.

tg t/s d0 d43K d100K d167K
b12973, split cache (from above) 62.5 54.6 48.6 42.3
head, split cache 63.2 55.3 48.8 42.5
b12973, -kvu 62.3 54.4 48.6 42.3
head, -kvu 63.0 54.9 49.0 42.4

The head matches the base within noise in both modes, so the rows path no longer engages on HIP and nothing falls back to the CPU. Prefill was unchanged as well. Thanks for the quick fix.

@milescoviello

Copy link
Copy Markdown
Author

@Sheepdog-01 thank you for checking both modes, that is good to know for the HIP side.

Written with Claude Opus 5.5

@wOvAN

wOvAN commented Dec 4, 2026

Copy link
Copy Markdown

Ada/Ampere data point, since every decode number in this thread so far is Blackwell or HIP: the gain reproduces on q8_0, f16 is untouched, and on these cards the sparse path lands on f16 parity rather than above it. Posting the matrix because "+50 %" reads as a general decode win, and on 2x RTX 4080 + RTX 3090 it is not one for a deployment that is already on f16.

The gate fires on this geometry (gqa_ratio 8, DKQ = DV = 256, Turing MMA), so q8_0 decode is on the new path: +11.2 % at 32k and +51.7 % at 128k, prefill unchanged. The nuance is in the crossed row: the base with f16 decodes at 99.2 t/s at 128k and the base with q8_0 at 64.4 t/s, so on Ada/Ampere the dense path is 35 % slower with a quantized cache, and this PR brings q8_0 to 97.6 t/s, which is 98 % of the f16 base. In other words the +51.7 % closes the q8_0 deficit and does not overtake f16, so there is no decode reason to move a deployment from f16 to q8_0 on these GPUs. Your 68 -> 122 t/s at 128k is Blackwell, where the dense q8_0 path is weaker, so the two data sets are consistent rather than contradictory.

The f16 control, which is the case from am17an's review (f16 lost 4 % at 16k): all six f16 rows are inside +-0.4 % at 32k and 128k and prefill is flat at both cache types, so we see no regression at all on sm_86/sm_89. The kernel selection is not logged at llama-bench verbosity, so the +51.7 % on q8_0 plus the flat f16 is our evidence that the path engaged only where it is meant to.

matrix (llama-bench, 2 reps, tg128 and pp512, t/s)
cache depth base tg128 PR tg128 delta base pp512 PR pp512 delta
q8_0 0 120.3 +-0.7 120.2 +-0.3 -0.1 % 4306.5 +-111.6 4315.7 +-121.6 +0.2 %
q8_0 32768 98.5 +-0.3 109.6 +-2.1 +11.2 % 3831.0 +-31.7 3843.9 +-23.8 +0.3 %
q8_0 131072 64.4 +-0.3 97.6 +-0.2 +51.7 % 2901.3 +-174.3 2889.6 +-169.8 -0.4 %
f16 0 120.6 +-0.9 120.6 +-0.9 -0.0 % 4301.1 +-56.6 4282.8 +-80.7 -0.4 %
f16 32768 113.2 +-0.2 113.0 +-0.1 -0.1 % 3828.8 +-83.0 3815.0 +-63.5 -0.4 %
f16 131072 99.2 +-0.5 99.2 +-0.0 -0.0 % 3003.0 +-176.3 3003.6 +-155.0 +0.0 %
setup and commands

Model: unsloth/Qwen4-35B-A3B-GGUF (Qwen3.8-Flash-Next family, arch qwen4exp, indexer_top_k = 2048, 11 sparse-attention layers, 16 heads / 2 KV heads so DKQ = DV = 256), loaded with all layers on GPU (33.74 GiB). GPUs: 2x RTX 4080 (16 GiB each) + RTX 3090 (24 GiB), --split-mode layer, driver 615.71.09.

Builds: base a4e5552 (this PR's base) and head f61908c, compiled with the same toolchain inside nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04, -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES='86;89' -DGGML_CUDA_FA_ALL_QUANTS=ON. The two CUDA backends differ as expected: libggml-cuda.so.1.2.0 md5 e2ef615248aa7ea56ddfdfbb435189f4 (base) and 6dcf8b968240746d1e7507030583ad81 (PR).

llama-bench -m Qwen4-35B-A3B-UD-Q4_K_XL-00001-of-00002.gguf \
  -ngl 99 -sm layer -fa on -ctk q8_0 -ctv q8_0 \
  -b 4096 -ub 1024 -d 0,32768,131072 -p 512 -n 128 -r 2 -o json

Notes on the method: llama-bench has no speculative decoding, so this isolates the kernel from the MTP trajectory; single slot, so the multi-sequence QSA problem in #32181 is out of scope here and this PR is not expected to change it. The metric in this build's JSON is avg_ts (tokens/s); avg_ns is the whole test time. We did not measure 16k, and we did not measure KL: the f16 conclusion is speed only.

AI disclosure: the builds and measurements were produced by an AI agent (Claude) operating this deployment; a human reviewed them.

Written with Claude

@milescoviello

Copy link
Copy Markdown
Author

@wOvAN thank you for the Ada/Ampere matrix, and for the f16 control on sm_86/sm_89.

Your reading is right. With an f16 cache decode already took the sparse MMA kernel, so this PR does not make q8_0 faster than f16: it removes the dense pass over the whole cache that a q8_0 cache used to fall back to, so q8_0 lands near the f16 speed. The reason to choose q8_0 is memory, half the KV size, which on a 24 GB card is what lets the full context fit with the model on the GPU. I have added a sentence saying this to the description so the numbers are not read as a general decode win.

Written with Claude Opus 5.5

@milescoviello

Copy link
Copy Markdown
Author

A note on the two red checks, since neither comes from this change.

ubuntu-22-hip-quality-check flags flash_attn_ext_vec<256, 1, F8_E4M3, F8_E4M3, ...> at 257 VGPRs (limit 256). The same kernel is flagged with the same 257 on #33595 and #33612, which do not touch FlashAttention. This PR changes only host code in fattn-common.cuh (launch_fattn) and the kernel choice in fattn.cu, so the device code of the vec kernel is the same as on master. #33653 is reworking that check.

webgpu-nvidia is the segfault in test-llama-archs on the WebGPU backend that also fails on recent master runs.

Written with Claude Opus 5.5

@ServeurpersoCom

Copy link
Copy Markdown
Contributor

@JohannesGaessler could you take a look at this one? am17an approved it, it only touches the CUDA FA dispatch so a q8_0 K/V cache takes the sparse MMA kernel at decode.

bowmanjd added a commit to bowmanjd/franken-llama that referenced this pull request Dec 5, 2026
We upgraded llama.cpp to tag b13014 and bundled six small patches for Qwen4-35B-A3B and dual-GPU Inkling-2-Mini so we can retire the older b12631 Unsloth fork.

Upstream b13014 already merges Qwen4 support (#33626), fused MTP eh_proj (#33702), full-width MTP hidden-state normalization (#33778), Vega20 MMVQ-to-MMQ speculative verify tuning (#33448), and the main Inkling-2 speedups (compact/indexed FA bias, fused glue kernels, float4 depth_mix, and nvfp4 pass-through).

On top of b13014, we apply six targeted patches gated to tag b13014 (so future version bumps disable them automatically):
- pr33058-looped-layer-split.patch (ggml-org/llama.cpp#33058): count weight-holding layers for -ts/-ngl and colocate pass-2/3 KV slots with physical weights so dual-GPU Inkling-2 keeps its 17-split placement.
- pr33682-cuda-sparse-fa-q8.patch (ggml-org/llama.cpp#33682): run sparse MMA flash attention decode with q8_0 K/V caches on CUDA instead of falling back to the dense vec kernel at long context.
- pr33707-cuda-qwen4-hc-post-fusion.patch (ggml-org/llama.cpp#33707): fuse the 3-op SIGMOID -> SCALE -> DSV4_HC_POST chain in ggml-cuda (CUDA and HIP), cutting 160 kernel launches per token on Qwen4.
- pr33767-mtp-no-pipeline-parallel.patch (ggml-org/llama.cpp#33767): disable pipeline parallelism on the single-block MTP draft context to save ~170 MiB VRAM on multi-GPU setups.
- pr33760-server-reasoning-effort-off.patch (ggml-org/llama.cpp#33760): set enable_thinking=false when a request passes reasoning_effort=off so Qwen4's chat template does not reject the request.
- furnace-lazy-prefetch.patch (sixvolts/llamacpp-gfx906-furnace@66f59a5f): when --load-mode auto sees lazy tensors such as Qwen4's engram table, read GPU weights via staging buffers with POSIX_FADV_DONTNEED and prefetch the lazy rows into RAM page cache asynchronously so weight uploads do not evict the engram table.

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

CUDA Related to the CUDA backend ggml changes relating to the ggml tensor library for machine learning model Model specific

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants