Repository navigation
Conversation
Assisted-by: OpenCode
Assisted-by: OpenCode
Assisted-by: OpenCode
|
This fails to compile on my machine. |
|
Hello Green-Sky, thanks a lot for checking, I should have built for all architectures first, I did for sm_89 (Ada) and sm_120a (Blackwell) only. I'll take a look. |
The fused quantized-KV flash-attention kernel assumed the KV rows it needs are always contiguous. Upstream's flash_attn_ext_rows work (ggml-org#29510) broke that assumption: with kv-unified + multi-slot serving, each request's rows are gathered through a row-index list, and the fused kernel ignored the list and read consecutive rows instead. Symptom: in multi-slot serving the kernel attended to other sequences' cache rows - logits looked plausible but were wrong, producing repetition loops and premature stops (4 of 12 long-generation runs on Qwen3.6-35B, np4; 0 of 12 with the fused kernel off). Single-slot traffic was safe by luck: there the row list happens to be contiguous, which is why all earlier np1 tests matched master bit-for-bit. Fix: gather K/V rows through the index list exactly like upstream's unfused loader (clamping negative padding to zero), at all three load sites. Verified bit-exact vs the unfused kernel across 8 op shapes, and 12/12 multi-slot requests clean end-to-end. Memory win kept (660 vs 1140 MiB).
ac6b6c7 to
956f38e
Compare
The fused K/V template args were instantiated on architectures without the multi-stage async loader (pre-Ampere, HIP), tripping a static_assert at compile time. Clamp fused_K/V to NONE when nstages <= 1. Purely compile-time where cp.async exists: sm_89 kernels are byte-identical before and after.
956f38e to
0c1543e
Compare
Hello Green-Sky, thanks again for checking, just wanted to let you know that I have pushed the fix and as far as I could test it compiles on all architectures, unfortunately I cannot test on an Ampere GPU, but tested again on Ada (3 x RTX 2000 Ada SFF over P2P on a PEX PCIe backplane at 4.0 x8) with q8_0 improvement +10%, on a dual RTX 4000 Pro on a Alienware Aurora R12 dual motherboard PCIe 4.0 x8 (slower than P2P), also q8_0 with this I see around %20 improvement in speed and less latency, this patch should help on multi-GPU setups with quantized KV. |
|
Yea it compiles now, but I am assuming this is not helping on my sm_75 device. :) |
|
@diabluz can you provide your test script? I want to try it for myself. Also, does it help with k8v4 setup? |
K and V now qualify independently, so K q8_0 + V q4_0 uses each side's own dequant template. Kernel unchanged; dispatch covers all four combinations, staging sized max(K,V). Validated bit-exact vs unfused and vs pre-change outputs; -0.7 GiB/GPU on 27B, speed neutral. Note: mixed pairs also want GGML_CUDA_FA_QUANTS to include q8_0-q4_0 and q4_0-q8_0, else they take the f16-dequant fallback.
Hi zarbis, very good point,with some iterations (with OpenCode) just pushed a version that supports K q8_0 / V q4_0. |
Hello zarbis, I did check with your parameters and found a similar behavior on a single RTX 2000 Ada, with an advantage in 308MB in VRAM savings (e.g. you could increase ctx by around 112000), but not much in token generation. Now the difference compared to my tests is that I always used --kv-unified, and if used I do see an advantage compared to the master version (I know for parallel = 1 makes little sense but it changes the way how kv is processed, more on this at the bottom): Swift-1.5-27B-IQ2_XS — branch vs master, 1× GPU, spec off (bit-tight)
TG columns: branch / master. KU-column % = branch vs master plain. This is a very interesting discovery, --kv-unified has to be used to get the full potential. By the way I started working on this to optimize the traffic between GPUs in a multi-GPU scenario (using tensor split mode). I will run some more benchmarks on the double RTX 4000 Pro setup. ps. --kv-unified changes the op routing during decode: it switches KV to a shared index-addressed pool and goes through the MMA path thus using these changes (Note that this is for decoding, while for prompt processing it's always used), on quantized KV:
|
|
@diabluz did a re-run with 32/64/128k and --kv-unified=true|false My original tests are blue and green here - consistently showing almost no difference.
While indeed your setup (red) beats current upstream default (blue) by real margin, the most the gap you observed is due to how slow --kv-unified=true is on master (orange). So your PR fixes your case significantly, while providing slight performance boost to baseline, which seems like a win to me! PS: To be honest, I do not understand how there is any difference, since to me EDIT: Since numbers look strange I did another run, but it's consistent with overall picture: |
Makes gemma-4 compatible with both fast KV paths: stage raw q8_0/q4_0 bytes per 256-value chunk inside the single-stage 512 kernels (full-width multi-stage tiles exceed smem); inert below Ampere. Add FATTN_VEC_CASE(512) so Q-rows<=2 decode takes the vector kernel. gemma-4-26B: TG +7/+16/+31 % at 16/32/64k depth, -954 MiB/GPU, PPL bit-exact, unit sweep bit-exact.
…quant at head 128 The vec kernel now reads K/V rows through the kv_rows list like the MMA kernel, so unified-cache decode on fused-ineligible quantized models takes vec speed (+9/+25/+38 % TG at 16/32/65k, Mistral-Small). The fused dequant route also covers DKQ=DV=128 heads via an 8 B cp.async staging helper (rows are 8-aligned there): +10/+21/+36 % depth decode on the first eligible model (Nemotron-3-Nano-Omni, k8v4). Unit sweeps byte-exact vs CPU ref; testops FLASH_ATTN_EXT green; fused 256/512 and f16-KV routes byte-frozen.
Sync window: aa75ff3..a1a68eb (57 upstream commits). Three of them touch our patched fattn files: - 9d7b2d7 head sizes 40/72 (ggml-org#30285): 5 hand-resolved conflicts in fattn-mma-f16.cuh — fused paths kept byte-frozen, upstream clamps taken only in the unfused branches; - 77e2db8 sm70 FA config cases (ggml-org#27997): same regions, taken verbatim; - 9e9619d OCP FP8 vec pairs (ggml-org#28413): auto-merged clean. Divergence floor unchanged: 3 files +487/-44 vs the merged upstream tip.
Per-side q8_0/q4_0/f8_e4m3 (9 combos). 27B f8 depth decode +7.8/+15.2/+29.9 % vs the f16-dequant fallback (16/32/65k), Meta buffer 728.52 -> 270.52 MiB, np4+MTP@262k loads with ~1 GiB headroom. Unit 95/95 + 76/76, testops green, PPL bit-identical, q8/q4 routes byte-frozen.
That's great improvement for VRAM-poors like me! Now I wonder whether this condition:
is an actual necessity or just some leftover from older times? It would be great if your improvement would apply universally (although for me specifically |
Keeps the earlier vec kv_rows gather (Mistral kvu +23...+46%) but compiles it out of the kernels that don't use it, recovering the ~1% nkvu decode regression; f16/bf16 pairs never receive a kv_rows list, so their gather variant is not instantiated
Yeah, this checks out. I've looked into allocations at 100k context, and savings are around 400MiB: -Log: logs/Swift-1.5-27B:IQ2_XS (MTP).log
+Log: logs/Swift-1.5-27B:IQ2_XS (MTP)-fused-quant-kv-mma.log
Shards: (inferred from log)
Swift-1.5-Qwen3.8-27B-GSQ-RCO-IQ2_XS-mtp.gguf: 8.17 GiB
---------------------------------------------- --------
Total: 8.17 GiB
Total (headers): 8.16 GiB
Category Count Total GiB Device GiB Host GiB Disk GiB
------------------- ------ ------------ ------------ ------------ ------------
TENSORS 866 8.16 8.16 0.00 0.00
Dense FFN 195 5.03 5.03 0.00 0.00
Attention 328 1.65 1.65 0.00 0.00
Output 2 0.63 0.63 0.00 0.00
SSM 336 0.55 0.55 0.00 0.00
Embeddings 1 0.26 0.26 0.00 0.00
MTP 4 0.04 0.04 0.00 0.00
KV CACHE (100k) - 2.64 2.64 0.00 0.00
SOURCE-DERIVED* - 1.22 1.22 0.00 0.00
SSM Scratch - 0.97 0.97 0.00 0.00
CUBLAS Workspaces - 0.25 0.25 0.00 0.00
-CUDA - 0.73 0.73 0.00 0.00
RECURRENT STATE - 0.58 0.58 0.00 0.00
+CUDA - 0.32 0.32 0.00 0.00
------------------- ------ ------------ ------------ ------------ ------------
-Total 866 13.33 13.33 0.00 0.00
+Total 866 12.92 12.92 0.00 0.00
Might not look much, but these savings allow me to significantly increase context window I can start this model with on my machine from 115k to 148k! That's a lot when OpenCode's system prompt is 7k and compaction starts at 80% window. Usable context window grows from 85k to 110k (+30%)! |
It missed the sparse check, so the f16 scratch was skipped while the sparse kernel still ran, reading quantized KV as raw f16 -> crash (QSA + q8_0 KV).
Resolved fattn-vec.cuh conflict (keep both sides); synced fused gate's gqa-opt mirror with upstream's mask->ne[2] == 1 check.
The sparse kernels now run the fused dequant: the chunk staging gathers K/V through the sparse index list (same row resolution as load_tile) and the gate covers the sparse family, so sparse quantized-KV ops no longer route through the f16 copy and no longer reserve its scratch. The launch grid takes the unfused instance's occupancy, keeping the stream-K seams where the f16 route places them: fused output stays bit-identical. FUSED=0 now reproduces upstream kernel selection exactly. Byte-identical serving shas vs master (default, FUSED=0, master binary); compute_75 + 13-arch sweeps warning-free.
…kv-mma # Conflicts: # ggml/src/ggml-cuda/fattn-mma-f16.cuh
Split fused single-stage chunk staging into two half-chunk slots so the next cp.async group is in flight while the current one is dequantized (same staging bytes: smem and VRAM unchanged). Gated to 16 B-aligned half-row bytes — only f8_e4m3 qualifies; the 8 B cp.async lane measured slower than the wait it hides, so q8_0/q4_0 keep the original sequence (SASS-verified bit-identical). f8 stage reads become uint4-wide (16 values/load, same pairs, swizzle, and stores). gemma-4 fused-512 f8: per-op fused-vs-copy penalty +51% -> +13%, model PP gap vs master -13.5% -> -4.0% at 64k; q8 routes unchanged.
|
Added a few changes and optimizations, mainly fused KV dequant in the sparse MMA kernels , pipelining cp operations to recover some prefill speed (w.r.t. the master), merged latest additions (including PR #32407 "Rotate K/V read order for better L2 cache hit rates"), consistency checks, extended CI, etc. (Updated Nov 20th, improved mistral TG) Latest plots (soon more single GPU tests):
ps. for information, I use this build command line (just to avoid compiling all quants):
And I run the server normally as:
|
Hello, thanks a lot, as it escapes a little bit the scope of #31234 I don't feel so confident it should go there (or that it would be accepted) but sure we can try, would you please be so kind to suggest it? thanks! |
…p on the general route
Decode attention with small gqa groups (2-4) never got the fused dequant path because it only existed at the wide Q tile — Mistral-Small is the case this frees. Fused now also covers the 128/256 tiles at the small widths when there is no logit softcap; everything else keeps the old route. Kernels and the scratch-size prediction agree, checked byte-exact in the unit battery. Mistral decode gets up to +12% at 48k context, more with longer prompts; all other models unchanged, bit for bit where it matters.
|
Excellent work! I wanted to share some independent results and thank you for this contribution. I adapted the Q4_0 fused KV dequantization approach from your PR to my customized llama.cpp build (b10659), using Qwen3.8-27B GSQ-RCO IQ3_S with DFlash2 speculative decoding. Test configuration:
End-to-end A/B/A benchmark at approximately 120K input tokens: Configuration | Decode -- | -- Fused ON | 91.85 t/s Fused OFF | 59.83 t/s Fused ON (repeat) | 91.08 t/sAverage decode improvement: +52.87%. Nsight Systems confirmed that the two separate Q4_0 dequantization kernel launches were eliminated. The combined Flash Attention kernel execution time decreased from 98.594 µs to 46.881 µs, corresponding to a 2.10× speedup in the targeted operation. All six numerical backend tests passed against the CPU reference, covering KV lengths of 4,096, 16,384 and 120,832 tokens with five query tokens and a head dimension of 256. I also successfully tested a real coding workload with 231,245 input tokens, reaching 59.90 t/s and a final context of 239,712 tokens without truncation. My initial backport deliberately retains the existing scratch buffer allocations, so VRAM consumption remains unchanged at 19,900 MiB. Removing those unnecessary allocations is the next step. Interestingly, speculative decoding allows this optimization to deliver substantial gains even without unified KV. Thank you again for sharing your work. This is one of the most effective CUDA optimizations I have tested for long-context inference on a single consumer GPU. I hope these independent results provide additional evidence in favor of merging your PR. |
Hello @srelus, wow!! Nice! happy to hear, I will play with DFlash2 myself, as haven't tried it. So cool, great results and work, and thanks for your words and support, much appreciated, |
|
Independent data point for the fused quantized-KV approach: I use an similar in-tile dequant to avoid O(n_kv) f16 cast per decode step in my fork (MMA flash-attn, q8_0 K/V, MTP verify batches of 4-5 tokens, ~260k ctx, ~100k kv cache, Qwen3.8 27B, RTX 5090). Reverting to the f16-conversion path costs me ~38.5% decode (~130 -> ~80 t/s). experiencing upstream cherry pick hell, I hope this will be merged soon. |
…d-tile refactor: a new file, fattn-fused-load.cuh, now holds the fused load tags and the flash_attn_load_tile_impl specializations, merging the branch's dequant definitions into upstream's new loader definitions. Assisted-by: OpenCode
Cool, I also had to do some merging/migration to the new definitions and took me a while but they are definitely going in the right direction. Still this PR/branch deviates a bit in style I guess but hopefully we will converge, in the meantime I'm trying to isolate the changes even more. Glad that you could use it! |













Overview
For quantized KV, flash-attention currently runs a separate dequantization pass that materializes the full K/V as f16 in scratch memory before the MMA kernels can read it. This PR fuses that conversion directly into the
fattn-mma-f16kernels for q8_0, q4_0 and recently f8_e4m3 (f16 KV is unaffected, as is every other cache type). Also honors the #29510flash_attn_ext_rowsrow-list gather, so it stays correct with kv-unified multi-slot serving.The reason to have this is that this copy is pure overhead: one read of the quantized blocks plus two extra trips through memory (write the f16 copy, read it back). Fusing removes the round-trip, and the win grows with context depth because the KV read dominates decode as the context grows. Measured on 3-4x RTX 2000 Ada (sm_89), it also frees ~0.5-1 GiB/GPU by eliminating the f16 FA scratch - on this box that is the difference between the 262k/np4 preset loading or OOMing on 3x16 GiB, depending on the model.
Testing
Branch build vs pure-master control, same trunk commit, q8_0/f8_e4m3 KV, mixture of Nvidia Ada GPUs (using P2P over PCIe 4.0):
[edited with latest results - Nov 21th 2026]
Each result is quoted twice: against master on the same kv-unified route (what the presets actually run) and against the best case for master — master with kv-unified drops (see #32226), where its own vec kernels read quantized KV directly and dodge the f16 copy. The first is the realistic comparison (same config); the second is the master best case for fair comparison. VRAM savings scale with ctx size.
Wins, q8_0 KV (best case for master, at deepest depth — 64k unless noted):
f8_e4m3 KV behaves like q8 on the same route (+33…+50% at depth), and master's best case barely helps — +33/+34/+50/+29% on the gqa 6–16 models, because upstream's native vec-f8 decode (#28413) reaches only gqa ≤ 4 shapes, where the best case is genuine parity (Mistral: +4%).
End-to-end (35B-A3B, 32k prompts, streaming, cold, pinned seed): decode +20.5% vs master spec-off, +6% with draft-MTP (within the ±5% acceptance lottery, so the conservative figure is quoted), first token +1.1%, and −496 MiB/GPU; the Meta compute buffer dropping 1140→660 MiB at np4 is what makes the 262k-context preset fit on 3 GPUs at all.
VRAM savings, branch vs master The branch reserves less VRAM than master on every model using a quantized KV cache, and the saving is a fixed amount, identical at 8k and 64k depth, because it is the f16 dequant-scratch reservation made once at startup, not something that grows with context. The size depends on the model shape. The dense head-256/512 models gain the most: Qwen3.8-27B saves 982 MiB (per GPU) and Gemma-4-26B 953 MiB per GPU. Qwen3.6-35B-A3B saves 480 MiB/GPU. Nemotron saves 192 MiB, Mistral-Small 128 MiB, the sliding-window Muse 40–56 MiB. Where the compute buffer is dominated by other ops (the IQ4_XS 27B) the visible saving shrinks to ~250 MiB, since the buffer is sized max-over-ops. With f16 KV the branch-vs-master difference is exactly 0 MiB on all ten models at all depths: outside the fused gate the patch costs and saves nothing. f8_e4m3 KV tracks q8_0 closely (±60 MiB within each model) — the memory story is the same either way.
Correctness: output bit-identical to master at np1 (greedy/seeded continuations to 4096 tokens, per-token logprobs); fused-vs-unfused bit-exact logits on 8 adversarial shapes; the single real defect found during development (np4 row-list gather reading wrong cache rows) was caught by a differential harness and regression-tested exactly where it broke — 12/12 long generations clean over 3 fresh-server rounds at np4+kv-unified+MTP, 64/64 clean on a 4-GPU np6 soak. Gated-out models are untouched: MiB-identical VRAM, timing within ±0.6%, verified across all ten models.
Additional information
Conceptually similar to #29846 (dequantize quantized KV inline in the flash-attention kernels instead of a separate pass) — some merit and acknowledgements there. Here the changes were kept minimal: the diff vs master is 4 files +689/−48 (initially two files +329/−17), confined to the fused-gated path (mainly fattn-mma-f16.cuh kernel templates); everything outside the gate dispatches unchanged — verified byte-identical, from SASS on the null-list vec kernels to output shas with the fused gate off. It also adds/merged the #29510 kv_rows row-list gather (which is what makes fused attention correct under kv-unified multi-slot serving), f8_e4m3 support and a
GGML_CUDA_FATTN_MMA_FUSEDruntime toggle for A/B. That said, I know this overlaps territory that was already declined once, and I would understand if it is closed again — the numbers above are at least on record here, and the branch stays maintained either way.More tests and benchmarks ongoing.