Pidoku

Attention Kernels: FlashAttention-3/4, Decode Attention, FlashInfer, FlashMLA

Module 25 Lesson 25.f 1h 35m Difficulty 5/5

Prerequisites 13.l, 12.g, 12.l, 25.a, 25.b


Before you start: words you need#

WordPlain meaning
Online softmaxComputing softmax block by block with a running maximum and sum, so the full score matrix is never stored (13.l).
Non-matmul FLOPsThe exponentials, maxima and rescaling in softmax. They run on slower units than the tensor cores.
MUFU / SFUThe multi-function (special-function) unit that computes exp2, reciprocals and similar. Far slower than the tensor cores.
Decode attentionAttention for one (or a few) new query tokens against a long KV cache. Memory-bound for most models.
Split-KVSplitting one sequence’s KV cache across several CTAs and merging their partial results (FlashDecoding, 13.l).
Plan / runFlashInfer’s two-phase API: plan looks at the batch’s lengths once and builds a balanced work schedule on the CPU; run launches kernels that follow it.
MLAMulti-head latent attention (12.g): all heads share one compressed latent KV vector per token.
Sparse attention (DSA)DeepSeek Sparse Attention: an indexer picks the top-k past tokens for each query, and attention reads only those.

1. What is it?#

Lesson 13.l explained what FlashAttention computes and how it evolved. This lesson is about how the kernels are built on Hopper and Blackwell, and about the separate family of decode kernels that serve most of an inference fleet’s attention time:

Kernel familyRegimeMain problem it solvesWhere in 2026
FlashAttention-3prefill on Hopperkeep tensor cores busy while softmax runs on slow unitsflash-attn (Hopper), vLLM/SGLang backends
FlashAttention-4prefill on Blackwellsoftmax and rescaling became the bottleneck once MMA doubledflash-attn-4 (CuTe DSL), FlashInfer, vLLM
Decode kernels (FlashInfer, TRT-LLM trtllm-gen, XQA)decodestream the KV cache at full HBM bandwidth with ragged, paged batchesevery engine
FlashMLAMLA prefill and decode, dense and sparseMLA decode is compute-bound, not memory-bound; sparse top-k KVDeepSeek V3.2–V4.1 serving on SM100

Facts checked on 13 November 2026: FlashInfer 0.7.4 (11 November 2026); FlashMLA’s 30 September 2026 release removed Hopper support (older commit kept for it).


2. Why does it matter?#

Attention is the part of a transformer whose cost grows with context. At 32 K+ tokens, decode attention can take more step time than all the GEMMs (12.h), and long-context, reasoning and agent workloads push contexts ever longer. Unlike GEMMs, attention cannot be batched across requests: every request has its own KV cache, so adding requests adds bytes, not reuse.

It is also where generations of hardware differ most. The same online-softmax algorithm needed a different kernel design on Ampere (FA-2), Hopper (FA-3) and Blackwell (FA-4), and MLA and sparse attention need different designs again. An engine’s attention backend choice (18.c) is often worth more than any other single setting.


3. Simple analogy#

Prefill attention is a chef cooking a banquet: lots of identical dishes, the stove (tensor cores) is the bottleneck, and the trick is to plate one dish (softmax) while the next is cooking.

Decode attention is a librarian answering one question per reader by re-reading that reader’s entire personal file. Readers do not share files, so a faster brain does not help; only a faster trolley (HBM bandwidth) and smaller files (GQA, MLA, FP8 KV) do. MLA is the odd case: every reader’s file is short and shared by 128 assistants who each ask their own question about it, so the librarian’s thinking becomes the bottleneck again.


4. Tiny example: is decode attention memory- or compute-bound?#

For each KV token read, decode attention does 2 × (d_K + d_V) FLOPs per query head (QKᵀ and PV). The program compares the FLOPs per byte of KV cache with the B200’s ridge points.

Go
// decodeai.go — arithmetic intensity of decode attention for MHA, GQA and MLA,
// per byte of KV cache read, compared with the B200's ridge points.
package main

import "fmt"

type variant struct {
	name    string
	qHeads  int // query heads
	kvHeads int // K/V heads actually stored (1 latent "head" for MLA)
	dK, dV  int // per-head dims of K (incl. RoPE part) and V
	shared  bool
}

func main() {
	vs := []variant{
		{"MHA, 32 heads, d=128", 32, 32, 128, 128, false},
		{"GQA, 64 q / 8 kv, d=128", 64, 8, 128, 128, false},
		{"MLA absorbed, 128 heads", 128, 1, 576, 512, true}, // K = 512 latent + 64 RoPE; V = latent
	}
	const ridgeBF16, ridgeFP8 = 2250.0 / 8.0, 4500.0 / 8.0 // dense TFLOP/s / (TB/s) on B200
	fmt.Printf("ridge points: BF16 %.0f, FP8 %.0f FLOP/byte\n\n", ridgeBF16, ridgeFP8)
	fmt.Println("variant                   query tokens  KV bytes/token  FLOP/byte (BF16 KV)  (FP8 KV)")
	for _, v := range vs {
		for _, q := range []int{1, 2} { // 2 = one draft token verified with MTP / speculative decoding
			flops := float64(q*v.qHeads) * 2 * float64(v.dK+v.dV) // QK^T and PV per KV token
			elems := v.kvHeads * (v.dK + v.dV)
			if v.shared {
				elems = v.kvHeads * v.dK // V is the first 512 dims of the same latent vector
			}
			bf16 := float64(elems * 2)
			fmt.Printf("%-25s %12d  %14.0f  %19.0f  %8.0f\n", v.name, q, bf16, flops/bf16, flops/(bf16/2))
		}
	}
}
ridge points: BF16 281, FP8 562 FLOP/byte

variant                   query tokens  KV bytes/token  FLOP/byte (BF16 KV)  (FP8 KV)
MHA, 32 heads, d=128                 1           16384                    1         2
MHA, 32 heads, d=128                 2           16384                    2         4
GQA, 64 q / 8 kv, d=128              1            4096                    8        16
GQA, 64 q / 8 kv, d=128              2            4096                   16        32
MLA absorbed, 128 heads              1            1152                  242       484
MLA absorbed, 128 heads              2            1152                  484       967
  • MHA and GQA decode are deeply memory-bound (1–32 FLOP/byte against a ridge near 280). The kernel’s only job is to stream KV at full bandwidth and not waste the tensor cores’ tiny share.
  • MLA decode sits at the ridge. With FP8 KV and BF16 maths (FlashMLA’s approach: dequantise in registers, compute in BF16), it is past the BF16 ridge: compute-bound. That is why FlashMLA looks like a prefill kernel, and why DeepSeek publishes its decode results in TFLOP/s.
  • Speculative decoding and MTP double the intensity for free: verifying 2 tokens reads the KV once (12.n, 13.n).

5. Technical explanation#

Why attention is harder than GEMM#

A GEMM is one matmul; an attention tile is two matmuls with a softmax between them, and the softmax’s exponentials run on the SFU. The FA-3 paper quotes the H100’s imbalance: 989 TFLOP/s of FP16 matmul against 3.9 TFLOP/s of special functions. For head dimension 128, a tile of attention does 512 matmul FLOPs per exponential (4 × d), but at that ratio of throughputs an exponential costs as much time as ~250 matmul FLOPs, so the exponentials alone would take about a third of the time unless they overlap with the matmuls.

FlashAttention-3 (Hopper), the kernel view#

  • Warp specialisation (25.b): a producer warp issues TMA loads of K and V tiles into a ring; two (or three) consumer warpgroups each own a block of query rows.
  • Ping-pong between warpgroups: named barriers force warpgroup 1’s softmax to run while warpgroup 2’s wgmmas run, and vice versa.
  • Intra-warpgroup overlap: within one warpgroup, issue S_next = Q·K_{j+1}ᵀ (async wgmma) before computing softmax on S_j, then wait. Costs registers, hides more.
  • FP8: FP8 wgmma needs the B operand K-major, so V must be transposed in shared memory (done in-kernel with ldmatrix/stmatrix); incoherent processing multiplies Q and K by a random Hadamard matrix to spread outliers before quantising, cutting FP8 error. The paper reports close to 1.2 PFLOP/s FP8 on H100.

FlashAttention-4 (Blackwell), the kernel view#

13.l lists FA-4’s algorithmic changes; in kernel terms:

  • S = QKᵀ and O += PV are tcgen05.mma into TMEM; P (the probabilities) is written back into TMEM and used as the A operand of the second MMA, so it never touches shared memory.
  • Separate softmax warpgroups read S from TMEM (tcgen05.ld), compute exponentials partly with a cubic polynomial on the FMA units (to offload the SFU), and write P.
  • A correction warpgroup rescales O only when the running max grew by more than a threshold, off the critical path.
  • Written in CuTe DSL; released March 2026 (pip install flash-attn-4), with forward and backward on SM100. Up to ~1.6 PFLOP/s BF16 on B200 (authors’ figure).

Decode kernels#

Decode attention has one (or a few) query rows per request against thousands of KV tokens, in pages (12.l). The engineering is about parallelism and bandwidth, not tensor-core tricks:

  1. Pack the GQA group into the MMA’s rows. With 8 query heads per KV head, treat the 8 heads as 8 “rows” of one query tile, so each KV page is read once for all 8 (TensorRT-LLM’s XQA kernel and FlashInfer do this). With speculative decoding, the draft tokens add rows too.
  2. Split-KV across CTAs when batch × KV heads is too small to fill 148 SMs, then merge partial (output, log-sum-exp) pairs (13.l). FlashInfer calls the merge “attention state composition” and exposes merge_state so engines can also combine shared-prefix and suffix attention.
  3. Paged loads. Each page’s address comes from the block table. On Hopper and Blackwell, kernels use TMA per page (or Blackwell’s tile::gather4 for scattered rows); some use cp.async for small pages. Page size trades fragmentation against load efficiency (12.l).
  4. Load balancing across ragged lengths. One request with 128 K tokens and 63 with 500 tokens must not leave 147 SMs idle while one finishes. FlashInfer’s plan step (on the CPU, once per batch) cuts long requests into chunks and assigns work evenly; run follows the plan, so the kernel itself stays CUDA-graph friendly.
  5. Low-precision KV. FP8 (and, in vLLM v0.32.0, NVFP4 on SM8x/SM12x) KV halves or quarters the bytes; the kernel dequantises in registers (13.h).

FlashInfer as a kernel system#

FlashInfer (MLSys 2025 paper; 0.7.4 in November 2026) is less one kernel than a library and compiler for attention variants:

  • A block-sparse representation that covers paged, ragged, prefix-shared (cascade) and sparse KV layouts with one kernel template.
  • JIT-compiled variants: logits soft-capping, sliding window, attention sinks, custom masks, as template parameters. flashinfer download-kernels installs pre-built cubins to avoid cold-start JIT.
  • Multiple backends behind one API. BatchDecodeWithPagedKVCacheWrapper(..., backend=...) accepts auto, fa2, fa3, trtllm-gen, cute-dsl and cudnn; on SM100/SM103 auto picks NVIDIA’s trtllm-gen kernels for most decode cases (and cuDNN for 2–4-token speculative verification rows when cudnn-frontend 1.30+ is installed). The lower-level trtllm_batch_decode_with_kv_cache picks trtllm-gen on SM100/SM103 and NVIDIA’s xqa kernels on Hopper and SM120/121.
  • POD-Attention: one kernel that runs a prefill chunk and decode requests together, so chunked prefill (12.k) does not need two launches.
Python
import flashinfer
wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper(workspace, "NHD", backend="auto")
wrapper.plan(kv_indptr, kv_indices, kv_last_page_len,
             num_qo_heads=64, num_kv_heads=8, head_dim=128, page_size=16,
             q_data_type=torch.bfloat16, kv_data_type=torch.float8_e4m3fn)
out = wrapper.run(q, paged_kv_cache)          # CUDA-graph safe; plan once per batch shape

FlashMLA and sparse MLA#

  • Dense MLA decode (DeepSeek-V3 era): the “absorbed” form multiplies the up-projection into the query, so all 128 heads attend to the same 576-dimensional latent (512 + 64 RoPE). Section 4 shows why it is compute-bound; FlashMLA’s 2025 deep-dive reports up to 660 TFLOP/s on H800 with a ping-pong-like schedule between two warpgroups.
  • Sparse MLA (DeepSeek V3.2 onwards): a lightning indexer (FP8/FP4 scoring kernels in DeepGEMM) chooses 2,048 past tokens per query; the attention kernel gathers only those rows of the FP8 (or FP4) KV cache. Prefill and decode become gather-heavy: TMA gather and careful page layouts matter more than raw MMA speed.
  • Status (November 2026): FlashMLA now targets SM100/SM103 and Huawei Ascend 950 and powers DeepSeek-V4.1. Its README reports up to 1,350 TFLOP/s sparse prefill and 1,024 TFLOP/s sparse decode on B200 with CUDA 13.3, and a fused Q-norm/RoPE/attention/RoPE/FP8-cast kernel at up to 1,460 (prefill) and 950 (decode) TFLOP/s — DeepSeek’s figures. The 30 September 2026 release dropped Hopper and V3/V3.2/V4.0 and changed the FP8/FP4 KV format.

6. Under the hood: one FA-4-style forward tile on Blackwell#

roles (one CTA, a 128-row Q tile, KV tiles of 128):
  load warp      TMA Q once; ring of K_j, V_j tiles                   (mbarriers kv_full/kv_empty)
  MMA warp       S_j = Q K_jᵀ  -> TMEM[S]         (tcgen05.mma, commit -> s_full)
                 O  += P_j V_j  (A = P in TMEM)   (tcgen05.mma, commit -> o_ready, kv_empty)
  softmax WGs    wait s_full; tcgen05.ld S_j; m_new = max(m, rowmax S_j)
                 P_j = exp2(S_j - m_new) (part SFU, part polynomial on FMA)
                 l = l*exp2(m - m_new) + rowsum P_j; tcgen05.st P_j -> TMEM; arrive p_full
  correction WG  if m_new - m > threshold: tcgen05.ld O; O *= exp2(m - m_new); tcgen05.st O
  epilogue       after last j: O / l -> BF16 -> smem -> TMA store; also write LSE (for split-KV)

Two TMEM buffers for S let the MMA warp compute S_{j+1} while softmax works on S_j: the Blackwell version of FA-3’s intra-warpgroup overlap, without spending registers.


7. Performance implications#

  • Prefill attention should reach 60–75 % of dense peak on Hopper (FA-3) and Blackwell (FA-4). If your engine’s prefill attention is far below, check the backend (18.c) and the head dimension: only some (64, 128, 192/128 for MLA prefill, 256) have tuned kernels.
  • Decode attention should reach 70–90 % of HBM bandwidth at long contexts. At short contexts (< 1 K) per-request overheads dominate, and that is where fused or persistent designs (25.j) and CUDA graphs matter.
  • Load imbalance shows as a long tail in Nsight Systems: most CTAs finish early, a few run long. Fix with split-KV or a plan-based scheduler, not with a faster inner loop.
  • MLA is different. Treat MLA decode like a GEMM: tensor-core utilisation, not DRAM throughput, is the metric.

8. Production implications#

  • Backend selection is a deployment decision. vLLM v0.32.0 lists FLASH_ATTN, FLASHINFER, TRITON_ATTN, the MLA family (FLASHINFER_MLA, CUTLASS_MLA, FLASH_ATTN_MLA, FLASHMLA, TRITON_MLA, …) and ROCm’s AITER backends (18.c). Pin it, and benchmark it per model and GPU.
  • Feature combinations narrow the choice. Sliding window + sinks + FP8 KV + speculative decoding may leave only one backend that supports all of them, and not the fastest one.
  • Kernel-format coupling. FP8/FP4 KV layouts are kernel-specific. FlashMLA’s September 2026 format change is a reminder: a library upgrade can invalidate cached or transferred KV (disaggregation, KV offload; 14.k). Treat the KV format as a versioned interface.
  • JIT and cubin caches must be warm in the image (FlashInfer download-kernels).
  • Numerics differ by backend. Different split-KV choices give slightly different results; with batch invariance requirements (28.c) you may need a fixed-split mode.

9. Common mistakes#

  1. Optimising decode attention for FLOPs. For MHA/GQA it is bytes; measure GB/s.
  2. Treating MLA decode like GQA decode. It is compute-bound; a bandwidth-optimal kernel is wrong.
  3. Ignoring the plan cost. FlashInfer’s plan runs on the CPU; calling it every step for an unchanged batch wastes host time. Engines call it once per batch composition.
  4. Benchmarking uniform lengths. Real batches are ragged; load balancing is the hard part.
  5. Assuming a head dimension is supported because the model loads; it may fall back to a slow generic kernel.
  6. Forgetting LSE outputs when composing split or cascade attention; merging without log-sum-exp is wrong.
  7. Upgrading an attention library without re-checking KV cache formats in disaggregated or offloaded deployments.

10. Hands-on exercise#

  1. Extend the Go program with your production model’s attention shape (heads, KV heads, head dim, KV dtype) and decide whether its decode attention is memory- or compute-bound on your GPU.
  2. With FlashInfer 0.7.4, benchmark BatchDecodeWithPagedKVCacheWrapper for 64 requests × 8 K tokens and for 63 × 500 + 1 × 128 K tokens with backend="fa2" and "auto". Convert to GB/s. Explain the difference between the two batches.
  3. Run FlashAttention-4’s forward benchmark on a B200 for head dims 64 and 128 at 8 K and 32 K sequence length; compare with torch.nn.functional.scaled_dot_product_attention.
  4. Read FlashMLA’s docs/20250422-new-kernel-deep-dive.md and draw its two-warpgroup schedule.

11. Interview questions#

  1. Why are attention kernels harder to make fast than GEMMs on Hopper and Blackwell?
  2. What did FA-3 change to overlap softmax with matmul, and what did FA-4 change for Blackwell?
  3. Why is GQA decode memory-bound but MLA decode compute-bound? Show the arithmetic.
  4. How does FlashInfer’s plan/run split help with ragged batches and CUDA graphs?
  5. What does “attention state composition” mean, and where is it used?
  6. How do sparse-attention kernels (DSA) differ from dense ones?
  7. Your decode attention reaches 45 % of HBM bandwidth. What do you check?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in