Skip to content

CUDA: dequantize q4_0/q8_0 K/V tiles in the FA MMA kernel for small multi-sequence batches (pin branch on b11642) - #303

Open
danielhanchen wants to merge 3 commits into
base/upstream-2639a3b4efrom
fa-q8-small-batch
Open

danielhanchen wants to merge 3 commits into
base/upstream-2639a3b4efrom
fa-q8-small-batch

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

With a quantized KV cache (q4_0 / q8_0) and 3 to 16 tokens per ubatch (multi-sequence decode, e.g. -np 4 --kv-unified), the CUDA flash-attention dispatcher leaves the vector kernel for the MMA f16 kernel, and the MMA path first converts the whole K and V views to f16 for every layer on every step. On a 4-slot server that was 56 dequantize_block_q8_0_f16 launches per decode step and the largest single kernel of the session (23.7% of GPU time on an L4).

This change lets the MMA kernel dequantize q4_0 / q8_0 K/V tiles as it loads them, for 3 to 16 tokens, so the whole-view conversion is gone. It builds on the in-kernel dequant proof of concept in ggml-org#30202 (am17an) and addresses the points raised in its review: the head dim 512 path without GQA, the GQA check, sparse kernels for quantized KV, generated instead of hand-written instance files, and no test-only env knobs. 1-2 token steps stay on the vector kernel, and the tile loader uses a fixed trip count with unroll 4 (a per-element loader lost at 4 streams).

Pin branch: upstream b11642 (2639a3b) + this one commit. Independent of #269; it also merges cleanly onto #269's head and onto ggml-org master 36140db.

Scope

NVIDIA Ampere or newer, K and V of the same type (q4_0 or q8_0), head dims 128 / 256 / 512, 3 to 16 tokens. Kernel selection is otherwise unchanged: single-stream decode, prefill, f16 KV, Turing, Volta and AMD take exactly the same path as before.

Correctness

  • test-backend-ops -o FLASH_ATTN_EXT: 5586/5586 pass against CPU on B200 and L4, including 1,782 new cases (head dims 64-512, GQA 1-8, 1 to 17 tokens, f16 / q8_0 / q4_0, a mask with 4 sequences in one unified cache, sinks, softcap, ALiBi, no mask).
  • nsys kernel census: the new kernel runs and the decode-time conversions are gone, on the test shapes and on two real models.
  • KLD against the unchanged build equals base vs base (same PPL, KLD 0, 100% top-1) for Qwen3-0.6B with q8_0 and q4_0 KV and for gemma-4-E2B (SWA layers at dim 256, global at 512), at 1, 4 and 16 tokens per step and 4 sequences in a unified cache.
  • Greedy multi-sequence text byte-identical to base at 1/2/4/8/16 streams (20/20).

Performance (Colab L4, one session, 3 interleaved rounds, median)

Case Base Patched
llama-server, 4 streams, ~640-token contexts 7.31 ms/token 6.71 ms (+8% tok/s)
llama-server, 4 streams, ~1.7k-token contexts 10.00 ms 7.83 ms (+20% tok/s)
batched-bench, 16 streams 14.6 ms 10.1 ms
batched-bench, 8 streams, 1536-token prompts 18.6 ms 9.8 ms
1 stream, pp512, pp2048 within noise

One reproducible regression: batched-bench at 3 streams with 512-token prompts is +0.23 ms (+4.4%); 3 streams with 128-token prompts and every 4+ stream cell improve. No threshold was added for it.

Not covered

T4 (gated off; compiled for sm_75 only), A100 / H100 / sm_120 at runtime (compile only), compute-sanitizer, and the interaction with #269's batch-invariant mode (checked by reading the code).

…atches

For 3 or more queries per ubatch (multi-sequence decode) with a quantized
KV cache, the MMA FlashAttention path first converted the entire K and V
views to f16 every layer and every step. With a unified KV cache that view
is the whole pool, so the conversion grows with the pool's high-water mark
and costs more than the attention itself.

For q4_0/q8_0 K/V (same type), head sizes 128/256/512 and up to 16 queries,
on NVIDIA Ampere or newer, the MMA kernel now dequantizes the K/V tiles as it
loads them, into the same f16 shared memory layout, and launch_fattn skips
the conversion and its scratch buffer. The tile loader has a compile-time
trip count and is unrolled by 4 so that several global loads per thread are
in flight. The tile shapes are the ones the f16 path selects for the same
batch. The vector/MMA/tile selection is unchanged, so single-query decode,
prefill, other GPUs and the sparse kernels keep their current paths. The
tile loader is adapted from ggml-org#30202.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T05:01:45.236951Z 34a66f4 Manual request
🔒 Security Review ✅ Completed 2026-10-20T22:21:21.200702Z 1368b42 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1368b423e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +11675 to +11680
for (int hs : { 64, 128, 256, 512, }) {
for (int nr2 : { 1, 2, 4, 6, 8, }) {
for (int kv : { 113, 512, 1024, }) {
for (int nb : { 1, 2, 3, 4, 5, 8, 9, 16, 17, }) {
for (ggml_type type_KV : { GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, }) {
test_cases.emplace_back(new test_flash_attn_ext(hs, hs, 2, {nr2, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, type_KV, type_KV));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reduce the exhaustive flash-attention test matrix

This Cartesian product adds 1,620 evaluation cases here, and the following loops bring the total increase to 1,782 cases. The unfiltered test-backend-ops invocation in ci/run.sh runs this evaluation matrix for applicable backends, so this change increases the suite from 3,804 to 5,586 cases (about 47%), including many costly kv=1024/hs=512 combinations. Keep a small boundary-focused set that covers each dispatch width, quant type, and relevant head size rather than multiplying every parameter value.

Useful? React with 👍 / 👎.

The quantized K/V path is only selected on Ampere or newer
(ggml_cuda_flash_attn_ext_mma_q_supported), but its template instances were
also compiled for older architectures. For Turing the tile widths 8 and 16
use nbatch_K2 = 96, and 256 % 96 != 0 fails the static_assert of the
quantized K tile loader, which broke sm_75 builds and the default fat binary.

Compile the quantized kernels as NO_DEVICE_CODE when AMPERE_MMA_AVAILABLE
is not defined, keeping the host specializations so fat binaries link.
flash_attn_ext_f16_process_tile now deduces the K/V type from the type
of its K pointer, so the kernel's process_tile call sites keep their
upstream text and the Turing/Volta guard no longer wraps them. On
architectures without quantized tile loading the kernel instantiates
the f16 path for quantized K/V, which is never launched there, as
before. Also move test_flash_attn_ext_multi_seq after
test_flash_attn_ext_large_logits. No functional change.
@LeoBorcherding

LeoBorcherding commented Nov 17, 2026 •

Copy link
Copy Markdown

Ran this on an RTX PRO 6000 Blackwell Server Edition (sm_120, CUDA 13.0, driver 580.82, Colab), one of the "not covered" archs. Base 2639a3b4e, this PR 34a66f42b and #315 d491f33d6, each built with -DCMAKE_CUDA_ARCHITECTURES=120.

  • test-backend-ops -o FLASH_ATTN_EXT -b CUDA0: 5586/5586 (base 3993/3993).
  • Greedy llama-batched -kvu --temp 0 -n 64 at 4 and 16 streams, Qwen3-0.6B / Llama-3.2-1B / Phi-3.5-mini (all Q8_0): byte-identical to base, 6/6.

ms per decode step, llama-batched-bench -fa on -ctk q8_0 -ctv q8_0 -kvu -npp 512 -ntg 64, median of 3 interleaved rounds (spread under 0.4%):

model streams base this PR change
Qwen3-0.6B (D 128) 1 1.65 1.65 0
3 2.13 2.18 +2.6%
4 2.38 2.30 -3.4%
8 3.14 2.97 -5.4%
16 5.02 4.70 -6.5%
Llama-3.2-1B (D 64) 1-16 within 0.1% (out of scope, as expected)
Phi-3.5-mini (D 96) 1-16 within 0.1% (out of scope, as expected)

#303 Qwen3-0.6B decode, sm_120 and A100

The 3-stream regression from the body reproduces here (+2.6% vs +4.4% on the L4). Gains are smaller than on the L4, which is expected on a card this much faster at 512-token contexts.

The gate this PR adds, as read from fattn.cu#L313-L350; the same predicate decides whether the f16 scratch is allocated:

$$g = \mathbb{1}[\text{Ampere+}]\ \mathbb{1}[t_K = t_V \in {q4_0, q8_0}]\ \mathbb{1}[D \in {128,256,512}]\ \mathbb{1}[n_q \le 16]\ \mathbb{1}[\neg(D > 256 \wedge g_2 = 1)]$$

HIP is unchanged: test-backend-ops -o FLASH_ATTN_EXT -b ROCm0 passes 5586/5586 (base 3993/3993, every base case still OK) on an RX 9060 XT (gfx1200, Linux, ROCm 10.1), on a Radeon 8060S (gfx1151, Linux, HIP 7.16) and on an R9700 (gfx1201, Windows 11, ROCm 7.1). One side effect there: base's fattn-mma*.cu glob in ggml/src/ggml-hip/CMakeLists.txt picks up this PR's 26 new fattn-mma-q-instance-* files, so the HIP build compiles them for nothing. #315's narrower fattn-mma-f16* glob drops them again.

A100 40GB (sm_80) and T4 (sm_75), same base, Colab, CUDA 13.0. I added 1,340 extra FLASH_ATTN_EXT cases to every tree (GQA 3/5/7/12/16, KV 1/31/255/257/4097/16384, D512, softcap, sinks, no mask, ALiBi, permuted K/V, all 10 K/V type pairs):

A100 T4
test-backend-ops -o FLASH_ATTN_EXT 6926/6926 (base 5333/5333) 6926/6926
compute-sanitizer memcheck / racecheck 0 errors / 0 hazards 0 errors / 0 hazards
KLD vs base, wikitext-2, Qwen3-0.6B / Llama-3.2-1B / Phi-3.5 / gemma-2-2b / gpt-oss-20b, q8_0 and q4_0, ub 4/16/17 0 (base vs base floor) 0
greedy llama-batched -kvu, np 4 and 16, 17 models byte-identical to base byte-identical

ms per decode step at 16 streams on the A100, q4_0 / q8_0 KV, % vs base: Qwen3-0.6B -15.1 / -9.3, Qwen3-8B -8.4 / -5.3, Llama-3.1-8B -8.9 / -5.0, Phi-4-mini -11.3 / -7.6, gemma-3-4b -9.8 / -5.7. The 3-stream regression doesn't show on A100 (Qwen3-0.6B npl 3: -3.3% q8_0, -7.0% q4_0). On Turing the gate is off, so T4 is within 0.4% of base everywhere.

One mismatch with the body: it says 1-2 token steps stay on the vector kernel, but for quantized K/V that only holds on Ada and newer. On Ampere and Turing, base picks the vector kernel at 1 token only (fattn.cu#L648-L663), and the new gate only checks the upper bound (fattn.cu#L342), so a 2-stream step on an A100 takes the new kernel. It's mixed there: Qwen3-0.6B q4_0 -2.3%, Qwen3.5-0.8B q8_0 +1.9%. A Q->ne[1] >= 3 floor on pre-Ada, or a body fix, would square it.

Not run: H100 (Colab refused it), llama-server.

@LeoBorcherding

Copy link
Copy Markdown

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Setup repeatedly failed. Update the setup script or commit, then try again later.
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@LeoBorcherding

Copy link
Copy Markdown

@codex review

@LeoBorcherding LeoBorcherding left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Codex: the only finding is a P2 at tests/test-backend-ops.cpp:11680, that the FA matrix grows by 1,782 cases. The count is right; on sm_120 FLASH_ATTN_EXT went from 3993 to 5586. ci/run.sh:643 runs test-backend-ops -b CPU unfiltered under a 3600 s timeout, so the cost lands on CPU CI too, not only on GPU nodes. I'd keep a case for each dispatch width, quant type and head dim, and drop the full kv=1024 x hs=512 cross product, which is most of the added time. The rerun asked above is against 34a66f42b after a setup failure.

Kernel side: the in-kernel path is gated to Ampere+ with K and V of the same type, head dims 128/256/512 and 3 to 16 queries; every other shape takes the old selection. On sm_120 it passes all 5586 cases, the greedy text is byte-identical to base, and Qwen3-0.6B decode is 3.4 / 5.4 / 6.5% faster at 4 / 8 / 16 streams. The 3-stream regression from the body reproduces (+2.6%), and since it's consistent across L4 and sm_120, I'd gate 3 queries back to the conversion path rather than leave it. Numbers and setup are in the comment above.

Not run: A100/H100, compute-sanitizer, llama-server.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 34a66f42be

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

LeoBorcherding added a commit to LeoBorcherding/llama.cpp that referenced this pull request Nov 17, 2026
…timings (source line moved off the axes)

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants