Skip to content

ggml-cuda: fused q8_0/q4_0/f8_e4m3 KV dequant in the MMA flash-attention kernels - #31802

Open
diabluz wants to merge 34 commits into
ggml-org:masterfrom
diabluz:feat/fused-quant-kv-mma
Open

diabluz wants to merge 34 commits into
ggml-org:masterfrom
diabluz:feat/fused-quant-kv-mma

Conversation

@diabluz

@diabluz diabluz commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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-f16 kernels for q8_0, q4_0 and recently f8_e4m3 (f16 KV is unaffected, as is every other cache type). Also honors the #29510 flash_attn_ext_rows row-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):

  • Dense 27B: +17.6% @32k → +33.9% @64k → +63% @131k → +79% @171k same-route — vs best case for master still +7%;
  • Qwen3.6-35B-A3B MoE: +2 → +34% same-route — vs best case +9%;
  • 27B IQ4_XS (smaller weights, KV reads dominate): +4 → +49% — vs best case +12%;
  • Gemma-4-26B-A4B, one 24 GB card: +21.6% at 8k → +61% @64k same-route, the steepest curve of a ten-model campaign — vs best case +29% (3-GPU rig);
  • Nemotron-30B (fused at head 128): +1 → +14%;
  • Mistral-Small, +69% @48k with the fused kernel not even running (outside the gate; the companion vec-gather change does all of it) — against best case +11%;
  • Muse-Glimmer, sliding-window, single GPU: +7%

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_FUSED runtime 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.

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES, OpenCode was used as the coding assistant for this work (implementation, benchmark harnesses, and validation runs); all benchmarks, methodology decisions, and the final review are my own.

@diabluz
diabluz requested a review from a team as a code owner November 6, 2026 12:39
@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Nov 6, 2026
@Green-Sky

Copy link
Copy Markdown
Collaborator

This fails to compile on my machine.

build/source/ggml/src/ggml-cuda/template-instances/../fattn-mma-f16.cuh(1417): error: static assertion failed with "fused dequant requires the multi-stage pipeline"
      static_assert(!q_K && !q_V || nstages > 1, "fused dequant requires the multi-stage pipeline");
          detected during:
            instantiation of "void flash_attn_ext_f16_process_tile<DKQ,DV,ncols1,ncols2,nwarps,use_logit_softcap,V_is_K_view,use_sparse,needs_fixup,is_fixup,fused_K,fused_V>(const float2 *, const half2 *, const half2 *, const half *, const int32_t *, const float *, float2 *, float2 *, float, float, float, uint3, int, int, int, int, int, int, int, int, int, int, int, int) [with DKQ=256, DV=256, ncols1=1, ncols2=8, nwarps=4, use_logit_softcap=false, V_is_K_view=false, use_sparse=false, needs_fixup=false, is_fixup=false, fused_K=2, fused_V=2]" at line 2112
            instantiation of "void flash_attn_ext_f16<DKQ,DV,ncols1,ncols2,use_logit_softcap,V_is_K_view,use_sparse,fused_K,fused_V>(const char *, const char *, const char *, const char *, const char *, const int *, const int *, float *, float2 *, float, float, float, float, uint32_t, float, int32_t, uint3, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int64_t, int32_t, int32_t, int64_t, int32_t, int32_t, int32_t, int32_t, int32_t, int64_t) [with DKQ=256, DV=256, ncols1=1, ncols2=8, use_logit_softcap=false, V_is_K_view=false, use_sparse=false, fused_K=2, fused_V=2]" at line 2324
            instantiation of "void ggml_cuda_flash_attn_ext_mma_f16_case<DKQ,DV,ncols1,ncols2>(ggml_backend_cuda_context &, ggml_tensor *) [with DKQ=256, DV=256, ncols1=1, ncols2=8]" at line 11 of /build/source/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu

@diabluz

diabluz commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

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.

@diabluz
diabluz marked this pull request as draft November 6, 2026 13:35
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).
@diabluz
diabluz force-pushed the feat/fused-quant-kv-mma branch from ac6b6c7 to 956f38e Compare November 6, 2026 14:44
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.
@diabluz
diabluz force-pushed the feat/fused-quant-kv-mma branch from 956f38e to 0c1543e Compare November 6, 2026 15:33
@diabluz

diabluz commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

This fails to compile on my machine.

build/source/ggml/src/ggml-cuda/template-instances/../fattn-mma-f16.cuh(1417): error: static assertion failed with "fused dequant requires the multi-stage pipeline"
      static_assert(!q_K && !q_V || nstages > 1, "fused dequant requires the multi-stage pipeline");
          detected during:
            instantiation of "void flash_attn_ext_f16_process_tile<DKQ,DV,ncols1,ncols2,nwarps,use_logit_softcap,V_is_K_view,use_sparse,needs_fixup,is_fixup,fused_K,fused_V>(const float2 *, const half2 *, const half2 *, const half *, const int32_t *, const float *, float2 *, float2 *, float, float, float, uint3, int, int, int, int, int, int, int, int, int, int, int, int) [with DKQ=256, DV=256, ncols1=1, ncols2=8, nwarps=4, use_logit_softcap=false, V_is_K_view=false, use_sparse=false, needs_fixup=false, is_fixup=false, fused_K=2, fused_V=2]" at line 2112
            instantiation of "void flash_attn_ext_f16<DKQ,DV,ncols1,ncols2,use_logit_softcap,V_is_K_view,use_sparse,fused_K,fused_V>(const char *, const char *, const char *, const char *, const char *, const int *, const int *, float *, float2 *, float, float, float, float, uint32_t, float, int32_t, uint3, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int64_t, int32_t, int32_t, int64_t, int32_t, int32_t, int32_t, int32_t, int32_t, int64_t) [with DKQ=256, DV=256, ncols1=1, ncols2=8, use_logit_softcap=false, V_is_K_view=false, use_sparse=false, fused_K=2, fused_V=2]" at line 2324
            instantiation of "void ggml_cuda_flash_attn_ext_mma_f16_case<DKQ,DV,ncols1,ncols2>(ggml_backend_cuda_context &, ggml_tensor *) [with DKQ=256, DV=256, ncols1=1, ncols2=8]" at line 11 of /build/source/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu

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.

@Green-Sky

Copy link
Copy Markdown
Collaborator

Yea it compiles now, but I am assuming this is not helping on my sm_75 device. :)

@zarbis

zarbis commented Nov 7, 2026

Copy link
Copy Markdown

@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.
@diabluz

diabluz commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@diabluz can you provide your test script? I want to try it for myself. Also, does it help with k8v4 setup?

Hi zarbis, very good point,with some iterations (with OpenCode) just pushed a version that supports K q8_0 / V q4_0.
For testing apart form llama-bench I run aiperf (from NVIDIA), then I give the results to OpenCode for analysis. I also check with https://github.com/tonyd2wild/2Wild-Coding-Agent-Latency-Monitor so I keep a history and see the generated output.

@zarbis

zarbis commented Nov 8, 2026 •

Copy link
Copy Markdown

Did the test on RTX 5080:

llama-server \
    --port 9931 \
    --offline \
    --gpu-layers all \
    --parallel 1 \
    --flash-attn 1 \
    --batch-size 2048 \
    --ubatch-size 1024 \
    --cache-type-k q8_0 \
    --cache-type-v q4_0 \
    --ctx-size 100000 \
    -m Swift-1.5-Qwen3.8-27B-GSQ-RCO-IQ2_XS.gguf
ctx_depth_decode

So there seems to be SLIGHT improvement deep into long context (getting to the limits of what my card can fit), but nowhere near values you have for 27B model.

@diabluz
diabluz marked this pull request as ready for review November 8, 2026 10:13
@diabluz

diabluz commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Did the test on RTX 5080:

So there seems to be SLIGHT improvement deep into long context (getting to the limits of what my card can fit), but nowhere near values you have for 27B model.

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)

Context TG plain (no kv-unified) TG with --kv-unified PP (both runs) VRAM/GPU
16.3k 16.4 / 17.0 (−3.5%) 17.8 (+4.7%) / 16.1 −3.7% −308 MiB
32.7k 14.4 / 14.4 (0%) 16.7 (+16.0%) / 13.3 +2.7% −308 MiB
65.4k 11.7 / 11.7 (0%) 15.1 (+29.1%) / 10.1 +12.0% −308 MiB
91.8k 10.2 / 10.1 (+1%) 13.9 (+37.6%) / 8.4 +17.0% −308 MiB

TG columns: branch / master. KU-column % = branch vs master plain.
Plain-column % = branch vs master (same run).

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:

Op Q rows kv_rows? Path taken Fused?
Prefill / large ubatch — any mode > 2 no MMA ✅ yes
Decode, no --kv-unified ≤ 2 no VEC kernel ❌ never
Decode, with --kv-unified any yes MMA (forced — VEC can't gather) ✅ yes

@zarbis

zarbis commented Nov 8, 2026 •

Copy link
Copy Markdown

@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.

ctx_depth_decode

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 --parallel 1 --kv-unified should be a no-op thing though...

EDIT: Since numbers look strange I did another run, but it's consistent with overall picture:
ctx_depth_decode

@diabluz
diabluz marked this pull request as draft November 10, 2026 07:37
diabluz and others added 5 commits November 11, 2026 01:33
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.
@zarbis

zarbis commented Nov 13, 2026

Copy link
Copy Markdown

The savings should be linear in ctx size: on the 27B I measure −982 MiB at 262k, for 64k you would save around ~240 MiB.

That's great improvement for VRAM-poors like me!

Now I wonder whether this condition:

This is a very interesting discovery, --kv-unified has to be used to get the full potential.

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 --parallel 1 --kv-unified is an effective no-op and I can live with it).

diabluz and others added 2 commits November 14, 2026 19:26
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
@zarbis

zarbis commented Nov 14, 2026 •

Copy link
Copy Markdown

The savings should be linear in ctx size: on the 27B I measure −982 MiB at 262k, for 64k you would save around ~240 MiB.

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%)!

diabluz and others added 4 commits November 15, 2026 09:22
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.
diabluz and others added 4 commits November 17, 2026 23:52
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.
@am17an

am17an commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

@diabluz if you're interested please suggest a patch to #31234 for CUDA, please let me know if you will do it. Otherwise I will

@diabluz

diabluz commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

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):

27b-kv-legs 35b-kv-legs gemma2g-kv-legs gemma-kv-legs iq4xs-kv-legs mistral1g-kv-legs mistral-kv-legs muse1g-kv-legs muse2g-kv-legs nemotron-kv-legs

ps. for information, I use this build command line (just to avoid compiling all quants):

cmake -B build -DGGML_NATIVE=ON -DGGML_CUDA=ON -DGGML_CUDA_FA_QUANTS="q8_0-q8_0;q8_0-q4_0;f8_e4m3-f8_e4m3;q8_0-f8_e4m3;f8_e4m3-q4_0"

And I run the server normally as:

CUDA_SCALE_LAUNCH_QUEUES=2x llama-server -m <model.gguf> -c -ngl -1 -fa on [--kv-unified]
--fit off -lm none -np [1|4] -b 2048 -ub -ctk -ctv [--split-mode tensor ] --threads 16 --log-verbosity 4

@diabluz

diabluz commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@diabluz if you're interested please suggest a patch to #31234 for CUDA, please let me know if you will do it. Otherwise I will

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!

diabluz and others added 3 commits November 19, 2026 20:24
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.
@srelus

srelus commented Nov 24, 2026 •

Copy link
Copy Markdown

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:

  • Single RTX 4090 Founders Edition (SM 8.9)

  • Context window: 262,144 tokens

  • Q4_0 K/V cache

  • DFlash2, 4 draft tokens

  • Parallel = 1, without --kv-unified

  • Temperature = 1.0, reasoning effort = xhigh

  • Real-world coding workload through Codex

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/s

Average 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.

@diabluz

diabluz commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

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.

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,
Cheers.

@edwardyoon

Copy link
Copy Markdown

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.

diabluz and others added 2 commits November 26, 2026 17:07
…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
@diabluz

diabluz commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Independent data point for the fused quantized-KV approach:
[...]
experiencing upstream cherry pick hell, I hope this will be merged soon.

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!

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants