Repository navigation
CUDA: sparse flash attention decode for a q8_0 K/V cache - #33682
milescoviello wants to merge 4 commits into
Conversation
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
am17an
left a comment
There was a problem hiding this comment.
The approach looks right to me, reusing ggml_flash_attn_ext_rows without backend changes. A few things:
-
The probe can enable the path without testing it.
resolve_fused_opsreserves the probe graph withn_tokens = n_seq_max, but the rows path is only built forn_tokens <= 4. With-kvu -np 5or more, no QSA layer emits aLLM_FUSED_OP_FLASH_ATTN_KV_ROWSnode in the probe graph, the device check loop finds nothing, andfused_sel_rowsis 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 onn_tokenswhile probing. -
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? -
n_tokens <= 4andn_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 4or more, MTP verify silently goes back to the mask path. -
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] == 1creates a view inctx0per QSA layer just to read the stream count; this can come from the KV context orcparams.kv_unified.top_score/live_pool/live_tail/liveduplicate the scatter path below; they could be computed once after the optional sort.
|
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 ( 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 One question: this PR builds 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`
All rows use Ruled out by measurement on this host:
Two notes on the workarounds listed in #32181 for our case: Reproducer: start the server as above, then fire two requests at the same time with a long filler prompt (N tokens) and AI disclosure: the measurements and this comment were gathered by an AI agent (Claude) operating this deployment; a human reviewed them. Written with Claude |
|
Follow-up with one more measurement, because it suggests the unified path here is not "same numbers, just slower". We switched this deployment to 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, decode probe, same instance before and after the layout change; accept = accepted / drafted tokens
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 |
|
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
|
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.
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)
Prompt after decode,
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 |
|
Tested on 2x RTX 5060 Ti 16GB (SM120, 36 SM) with Benchmark: Decode (
Notes:
AI-assisted: drafted with an AI coding agent and polished with agy, measurements run and checked by me |
|
@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
|
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.
Written with Claude Opus 5.5 |
|
Non-CUDA data point: on ROCm/HIP (RX 7900 XT, gfx1100) the rows path made decode at depth about 2x slower for us. Setup
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 ( 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. |
|
@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: llama.cpp/ggml/src/ggml-cuda/fattn.cu Lines 770 to 772 in a4e5552 With Written with Claude Opus 5.5 |
|
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. |
|
@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 I will push it here unless you have already started on it. Written with Claude Opus 5.5 |
|
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 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 |
|
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 :) |
|
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 |
|
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,
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. |
|
@Sheepdog-01 thank you for checking both modes, that is good to know for the HIP side. Written with Claude Opus 5.5 |
|
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)
setup and commandsModel: 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). 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 |
|
@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 |
|
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 |
|
@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. |
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.
Overview
Sparse flash attention decode (the
n_kv_maxhint, 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_EXTpasses 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 2Prompt 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-perplexityon 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 4both take the sparse MMA kernel and give the same result (0.016658).Requirements
Written with Claude Opus 5.5