Skip to content
Transformers and LLMs Advanced 36 min read

KV cache, FlashAttention, MQA/GQA/MLA

Attention is cheap in arithmetic and expensive in memory traffic. Every trick on this page — caching keys and values, computing attention in tiles that never leave the chip, and sharing or compressing what gets cached — is the same move: stop moving bytes you don't need to move.

10,000 ft

A trained transformer is only useful if you can run it, and running it means generating one token at a time. Done naively, every new token would recompute the whole prefix; the KV cache removes that redundancy, and in doing so turns LLM inference into a problem of memory capacity and memory bandwidth rather than arithmetic. FlashAttention solved the matching problem in training and prefill: the \(n \times n\) attention matrix was being written to and read back from slow GPU memory, so it computes exact attention in on-chip tiles instead. MQA, GQA and MLA shrink the cache itself by sharing or compressing keys and values across heads. Together these ideas decide how long a context a model can serve, how many users fit on one GPU, and what a token costs. They lean on the GPU memory hierarchy and the streaming softmax, and they feed straight into serving systems and long context.

2,000 ft

  1. Prefill. The prompt's \(n\) tokens go through the model in one parallel pass. Every layer computes keys and values for every prompt token and stores them: that store is the KV cache.
  2. Decode. Each new token computes its own query, key and value, appends its key and value to the cache, and attends over everything cached. Work per step grows linearly with context, not quadratically.
  3. The bottleneck moves. A decode step reads every weight and every cached key/value from GPU memory to do very little arithmetic per byte. Speed is set by bytes moved, and the cache grows with context × batch.
  4. FlashAttention computes \(\operatorname{softmax}(QK^\top/\sqrt{d})V\) in tiles that live in fast on-chip SRAM, using an online softmax, so the \(n \times n\) matrix never touches slow memory. Same answer, far fewer bytes.
  5. MQA/GQA let many query heads share one key/value head (cache ÷ 4–64). MLA caches one small latent vector per token and rebuilds keys and values from it (DeepSeek-V2: cache −93.3%).
  6. Cache management — paging, prefix sharing, quantisation and eviction — squeezes more sequences into the same memory.

Prefill fills the cache in one parallel pass; each decode step reads all of it and adds one row
Prefill fills the cache in one parallel pass; each decode step reads all of it and adds one row. prompt (n tokens), prefill all n tokens in parallel compute-bound, KV cache K, V for every layer and every past token, decode step 1 new token: q, k, v, attend: q against all cached K, V memory-bound, next token, write n rows, append 1 row, read all rows, q, feed backPrefill fills the cache in one parallel pass; each decode step reads all of it and adds one row. prompt (n tokens), prefill all n tokens in parallel compute-bound, KV cache K, V for every layer and every past token, decode step 1 new token: q, k, v, attend: q against all cached K, V memory-bound, next token, write n rows, append 1 row, read all rows, q, feed back

Ground level

Two phases with opposite bottlenecks

Generating a reply has two phases that stress a GPU in opposite ways.

Prefill processes the prompt. All \(n\) prompt tokens are known, so every layer runs big matrix–matrix products: \((n \times d)\) activations times \((d \times d)\) weights. Each weight loaded from memory is used \(n\) times. With \(n\) in the thousands, the GPU's tensor cores are the limit — prefill is compute-bound, and its latency is what you feel as time to first token.

Decode produces the reply one token at a time, because token \(t+1\) depends on token \(t\). Each step pushes a single vector through every layer: matrix–vector products. Every weight is loaded from memory, used for one multiply-add, and discarded. The GPU spends most of its time waiting for bytes. Decode is memory-bound, and its speed is what you feel as tokens per second.

Almost everything on this page follows from that asymmetry. The decoding page introduced the loop; here we open up the cost of each turn of it.

The KV cache

In a causal decoder, the key and value of token \(j\) at layer \(\ell\) depend only on tokens \(1..j\) — the mask forbids looking ahead. So once computed, they never change. Without a cache, step \(t\) would recompute keys and values for all \(t\) tokens in every layer and re-score all \(t^2\) pairs, although only the last row of the output is new. With a cache:

  1. compute \(\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t\) for the new token only;
  2. append \(\mathbf{k}_t, \mathbf{v}_t\) to the layer's cache \(K_{1:t}, V_{1:t}\);
  3. output \(\operatorname{softmax}(\mathbf{q}_t K_{1:t}^\top/\sqrt{d_h})\,V_{1:t}\).

The result is bit-for-bit the same computation as the uncached forward pass restricted to the last row. The code in Build it generates 512 tokens with a single head of width 64 both ways: outputs agree, and the cached version does 318 times fewer FLOPs (1.47 × 10¹⁰ against 4.62 × 10⁷). The saving grows linearly with length, because the uncached cost is cubic in the number of tokens generated and the cached cost is quadratic.

Why cache keys and values but not queries? A query is used once — by its own token, at its own step. Keys and values are used by every later token. And why not cache attention outputs? Because the output for a past position never needs recomputing either, but it is not what a new token needs: the new token needs to compare itself with every past key and blend every past value.

How big the cache gets

Per token, each layer stores one key and one value vector per key/value head:

\[ \text{KV bytes per token} = 2 \times n_\text{layers} \times h_{kv} \times d_h \times b, \]

with \(b\) bytes per number (2 for BF16). Multiply by context length and by the number of sequences in the batch for the total. Real configurations (real output of the third snippet in Build it; Llama 2 7B was trained with a 4K context, so its 128K figure is hypothetical):

Model Attention per token 128K-token context
Llama 2 7B (arXiv:2307.09288) MHA, 32 KV heads × 128 512 KiB 64.0 GiB
Llama 3 8B (arXiv:2407.21783) GQA, 8 KV heads × 128 128 KiB 16.0 GiB
Llama 3 70B GQA, 8 KV heads, 80 layers 320 KiB 40.0 GiB
DeepSeek-V3 (arXiv:2412.19437) MLA, 512 + 64 numbers per layer 68.6 KiB 8.6 GiB
DeepSeek-V3 if it had used MHA 128 heads × 128 3,904 KiB 488 GiB
Llama 2 7B · MHA512 Llama 3 70B · GQA320 Llama 3 8B · GQA128 DeepSeek-V3 · MLA68.6 DeepSeek-V3 if MHA3,904 (off scale) KiB of KV cache per token, BF16. One GiB = 1,048,576 KiB.
Bytes cached per token. GQA cuts Llama's cache 4× against MHA at the same width; MLA cuts DeepSeek-V3's 57× against the MHA it would otherwise need.

Two things to notice. The cache scales with layers × KV heads × head width, not with parameters: Llama 3 70B has almost 9× the parameters of 8B but only 2.5× the cache per token. And at long context the cache rivals the weights — a single 128K-token conversation with Llama 3 70B needs 40 GiB of cache on top of 140 GB of BF16 weights.

Decode is a bandwidth problem

At each decode step the GPU must stream all the weights (shared by every sequence in the batch) and each sequence's own cache from high-bandwidth memory (HBM). The arithmetic is tiny by comparison: about \(2N\) FLOPs per token for \(N\) parameters. So the time of a step is roughly

\[ t_\text{step} \approx \frac{\text{weight bytes} + B \times \text{cache bytes per sequence}}{\text{HBM bandwidth}}. \]

Worked example. Llama 3 8B in BF16 (about 8.0B parameters, 16.1 GB) on an H100 SXM, which NVIDIA lists at 3.35 TB/s of HBM bandwidth and 1,979 BF16 TFLOP/s with sparsity — so about 989 TFLOP/s dense (NVIDIA H100). Each sequence holds 8,192 tokens of context (128 KiB × 8,192 = 1.07 GB of cache).

batch \(B\) weights read cache read step time tokens/s FLOPs per byte
1 16.1 GB 1.1 GB 5.11 ms 196 0.9
8 16.1 GB 8.6 GB 7.36 ms 1,087 5.2
32 16.1 GB 34.4 GB 15.05 ms 2,126 10.2
64 16.1 GB 68.7 GB 25.31 ms 2,529 12.1

Read the table from three angles:

  • Batching is nearly free at first. Going from 1 to 8 sequences multiplies throughput by 5.5 for 44% more latency, because the weights are read once for the whole batch.
  • The cache then takes over. Each sequence's cache is private, so its bytes do not amortise. At batch 32 the cache is twice the weights; at batch 64 the step is dominated by it — and 16.1 + 68.7 = 84.8 GB no longer fits in the H100's 80 GB at all.
  • The GPU is starving. An H100 needs about 989 × 10¹² / 3.35 × 10¹² ≈ 295 FLOPs per byte to keep its tensor cores busy (the ridge point of the roofline). Decode delivers 1–12. Without GQA (4× the cache), batch 32 wouldn't fit either.

This is why the rest of the page — and most of LLM serving — is about the cache. Shrinking it per token (GQA, MLA, quantisation) raises the batch you can fit and cuts the bytes per step; managing it well (paging) stops memory being wasted.

FlashAttention: exact attention that respects the memory hierarchy

The cache solves decode. Training and prefill have a different problem: the \(n \times n\) score matrix.

Standard attention as written in a framework runs as separate kernels: compute \(S = QK^\top\) and write it to HBM; read \(S\), apply mask and softmax, write \(P\); read \(P\) and \(V\), write \(O\). For one head with \(n = 8{,}192\) that is a 67-million-entry matrix written and read twice in the forward pass and more in the backward. The FLOPs are unavoidable; the traffic is not. A GPU has two very different memories: on an A100, "40-80GB of high bandwidth memory (HBM) with bandwidth 1.5-2.0TB/s" and "192KB of on-chip SRAM per each of 108 streaming multiprocessors with bandwidth estimated around 19TB/s" (Dao et al., §2.1). Every round trip of \(S\) through HBM costs far more time than computing it.

FlashAttention (Dao, Fu, Ermon, Rudra, Ré, 2022) fuses the whole computation into one kernel that works on tiles:

  1. Split \(Q\) into row blocks of \(B_r\) queries and \(K, V\) into blocks of \(B_c\) keys, small enough that a \(Q\) block, a \(K\) block, a \(V\) block and a \(B_r \times B_c\) score tile all fit in SRAM.
  2. For each query block, stream the key/value blocks through SRAM. For each pair compute the score tile, update a running row maximum \(m\), a running softmax denominator \(\ell\) and a running un-normalised output \(\tilde{O}\), rescaling the old values whenever the maximum grows.
  3. When all key blocks have passed, divide \(\tilde{O}\) by \(\ell\) and write the finished output block to HBM — along with the per-row log-sum-exp \(m + \log \ell\) for the backward pass.
FlashAttention: tiles stream through on-chip SRAM; the n × n matrix never reaches HBM
FlashAttention: tiles stream through on-chip SRAM; the n × n matrix never reaches HBM. HBM (80 GB, ~3 TB/s), Q blocks, K, V blocks, O + log-sum-exp (written once), SRAM per SM (~200 KB, ~19 TB/s), score tile B_r × B_c, running max m, sum ℓ, output Õ, load once per block, stream, rescale + accumulate, normalise, writeFlashAttention: tiles stream through on-chip SRAM; the n × n matrix never reaches HBM. HBM (80 GB, ~3 TB/s), Q blocks, K, V blocks, O + log-sum-exp (written once), SRAM per SM (~200 KB, ~19 TB/s), score tile B_r × B_c, running max m, sum ℓ, output Õ, load once per block, stream, rescale + accumulate, normalise, write

The online softmax that makes step 2 exact is the same one derived on the numerical computing page: when a new tile raises the row maximum from \(m\) to \(m'\), multiply the old \(\ell\) and \(\tilde O\) by \(e^{m - m'}\) before adding the new terms. The maths section proves it is exact; the code checks it against the naive formula to \(6 \times 10^{-16}\).

What it buys. The paper's Theorem 2: standard attention "requires \(\Theta(Nd+N^2)\) HBM accesses, while FlashAttention … requires \(\Theta(N^2d^2M^{-1})\)", where \(M\) is the SRAM size, and Proposition 3 shows no exact algorithm can do asymptotically better for all \(M\) between \(d\) and \(Nd\). Concretely, for GPT-2 medium attention (sequence 1,024, head width 64, 16 heads, batch 64, forward plus backward on an A100), standard attention did 66.6 GFLOPs with 40.3 GB of HBM traffic in 41.7 ms; FlashAttention did more arithmetic — 75.2 GFLOPs — but only 4.4 GB of traffic, in 7.3 ms (Figure 2). Fewer bytes beat fewer FLOPs.

The extra FLOPs come from the backward pass, which needs the attention probabilities \(P\). Rather than store the \(n \times n\) matrix, FlashAttention recomputes each tile of \(P\) from \(Q\), \(K\) and the saved log-sum-exp — a deliberate trade of cheap arithmetic for expensive memory. Activation memory for attention becomes linear in \(n\) instead of quadratic, which is what made long-context training practical.

FlashAttention-2 (Dao, 2023) kept the algorithm and fixed the work partitioning: fewer non-matmul FLOPs (rescale the output once at the end rather than every step), parallelism across the sequence as well as batch and heads, and splitting work among warps by queries rather than by keys so warps don't have to exchange partial sums. The result: "around 2× speedup compared to FlashAttention, reaching 50-73% of the theoretical maximum FLOPs/s on A100" (arXiv:2307.08691).

FlashAttention-3 (Shah, Bikshandi, Zhang, Thakkar, Ramani, Dao, 2024) targets Hopper GPUs, where FlashAttention-2 reached only 35% utilisation. It uses the H100's asynchronous tensor cores and memory-copy engine so that data movement, matmuls and softmax overlap (producer and consumer warps, ping-pong scheduling between warp groups), and adds FP8 with block quantisation. It reports 1.5–2.0× over FA2, "with FP16 reaching up to 740 TFLOPs/s (75% utilization), and with FP8 reaching close to 1.2 PFLOPs/s" (arXiv:2407.08608).

Flash-Decoding (Dao, Haziza, Massa, Sizov, 2023) adapts the idea to decode, where there is only one query row per sequence and FlashAttention's parallelism over query blocks has nothing to parallelise. It splits the keys into chunks processed by different thread blocks, each producing a partial \((m, \ell, \tilde O)\), then merges them with the same rescaling rule (PyTorch blog). That merge being exact for any split is the key mathematical fact; it is also what lets ring attention spread one sequence over many GPUs.

Two different 'efficient attentions'

FlashAttention does not change what is computed — it is exact, and its FLOPs are still \(O(n^2)\). It changes where the intermediate data lives. Approximate methods (sparse, low-rank, linear attention) change what is computed to cut the FLOPs. The first family won in practice for contexts up to hundreds of thousands of tokens; the second is the subject of long context and beyond transformers.

Sharing keys and values: MQA and GQA

The multi-head attention page defined the variants; here is why they exist. In the cache formula, \(h_{kv}\) is the only factor you can cut without making the model shallower or narrower.

Multi-query attention (Shazeer, 2019) keeps \(h\) query heads but a single key head and value head. Shazeer's argument was exactly the bandwidth argument above: incremental decoding is slow because of "the memory-bandwidth cost of repeatedly loading the large 'keys' and 'values' tensors", and MQA divides those tensors by \(h\) (arXiv:1911.02150). PaLM used it, as did Falcon-7B. Its cost is quality and training instability at scale: one key/value subspace must serve every head's question.

Grouped-query attention (Ainslie et al., 2023) interpolates: \(h_{kv}\) groups, each shared by \(h/h_{kv}\) query heads. The GQA paper also showed that an existing MHA checkpoint can be converted by mean-pooling the key and value heads in each group and "uptraining" with about 5% of the original pre-training compute (arXiv:2305.13245). With 8 KV heads it reaches quality close to MHA at a speed close to MQA, which is why Llama 2 70B, Llama 3 at every size, Mistral and most open models since use it.

GQA also helps the arithmetic intensity of the attention itself. In decode, a cached key is read once and used by \(h/h_{kv}\) query heads instead of one, so the attention kernel does \(h/h_{kv}\) times more FLOPs per byte of cache read. Kernels exploit this by loading a KV head once into SRAM and serving its whole query group.

Multi-head latent attention

GQA shares; multi-head latent attention (MLA), introduced in DeepSeek-V2 (2024), compresses. Instead of caching keys and values, each token caches one low-dimensional latent vector \(\mathbf{c}_t\), from which every head's key and value are linear functions:

\[ \mathbf{c}_t^{KV} = W^{DKV}\mathbf{h}_t \in \mathbb{R}^{d_c},\qquad \mathbf{k}_{t,i}^{C} = W_i^{UK}\mathbf{c}_t^{KV},\qquad \mathbf{v}_{t,i}^{C} = W_i^{UV}\mathbf{c}_t^{KV}, \]

with \(d_c \ll h\,d_h\) ("D" for down-projection, "U" for up). DeepSeek-V2 uses \(h = 128\) heads of \(d_h = 128\) but \(d_c = 512\): the 32,768 numbers MHA would cache per layer become 512.

The absorption trick is what makes this cheap at inference. Head \(i\)'s score with past token \(j\) is

\[ \mathbf{q}_{t,i}^\top \mathbf{k}_{j,i}^C = \mathbf{q}_{t,i}^\top W_i^{UK}\mathbf{c}_j^{KV} = \big(W_i^{UK\top}\mathbf{q}_{t,i}\big)^\top \mathbf{c}_j^{KV}. \]

So instead of up-projecting every cached latent into a key (cost proportional to context length), you project the one new query down into latent space and dot it with the cached latents directly. Likewise the up-projection to values merges into the output projection: \(W^O_i W_i^{UV}\) is a fixed matrix you can precompute. In the paper's words, "\(W^{UK}\) can be absorbed into \(W^Q\), and \(W^{UV}\) can be absorbed into \(W^O\)". Attention then runs entirely on the 512-dimensional latents — effectively MQA with one shared 512-wide key/value head, but with per-head expressivity restored by the absorbed matrices. The second snippet of Build it checks the absorbed and naive forms agree.

Decoupled RoPE. RoPE breaks absorption: it multiplies the key by a position-dependent rotation \(R_j\), giving \(\mathbf{q}^\top R_t^\top R_j W^{UK}\mathbf{c}_j\), and the rotation sits between \(\mathbf{q}\) and \(W^{UK}\), so \(W^{UK}\) can no longer be folded into a fixed query projection. DeepSeek's fix carries position in a small separate channel: each head gets an extra \(d_h^R = 64\) query dimensions with RoPE applied, and all heads share one 64-dimensional RoPE key per token, which is cached alongside \(\mathbf{c}_t\). Per layer and token the cache is \(d_c + d_h^R = 576\) numbers. The paper puts it as \((d_c + d_h^R)\,l \approx \tfrac92 d_h\,l\) elements, "equal to GQA with only 2.25 groups", while reporting quality above MHA in its ablations — and an overall KV cache 93.3% smaller than DeepSeek 67B with 5.76× the maximum generation throughput (arXiv:2405.04434). DeepSeek-V3 keeps the same MLA dimensions across 61 layers, which is the 68.6 KiB per token in the table above.

Four ways to spend the KV budget (per layer, per token)
Four ways to spend the KV budget (per layer, per token). MHA h key heads + h value heads 2·h·d_h numbers, GQA h_kv shared groups 2·h_kv·d_h numbers, MQA 1 shared key + value head 2·d_h numbers, MLA latent c (d_c) + RoPE key (d_R) keys/values rebuilt by absorbed matrices, share across groups, one group, compress, don't shareFour ways to spend the KV budget (per layer, per token). MHA h key heads + h value heads 2·h·d_h numbers, GQA h_kv shared groups 2·h_kv·d_h numbers, MQA 1 shared key + value head 2·d_h numbers, MLA latent c (d_c) + RoPE key (d_R) keys/values rebuilt by absorbed matrices, share across groups, one group, compress, don't share

Managing the cache

A cache that fits on paper can still waste memory in practice. Four families of technique, each with a landmark system:

  • Paging. Early servers reserved a contiguous slab per request sized for the maximum possible output. Kwon et al. measured that "only 20.4% - 38.2% of the KV cache memory is used to store the actual token states in the existing systems". PagedAttention stores the cache in fixed-size blocks (16 tokens by default in vLLM) located through a per-sequence block table, exactly like virtual memory pages; waste falls to the last partial block, and blocks can be shared copy-on-write between sequences (parallel samples, beam search). vLLM reported 2–4× throughput over FasterTransformer and Orca at the same latency (arXiv:2309.06180).
  • Prefix sharing. Many requests share a prefix — a system prompt, a few-shot block, a long document under discussion. SGLang's RadixAttention keeps finished caches in a radix tree keyed by token prefix and reuses them across requests (arXiv:2312.07104). API "prompt caching" discounts are the commercial face of this.
  • Quantisation. Store keys and values in 8, 4 or even 2 bits. KIVI found keys have outlier channels and values do not, so it quantises keys per channel and values per token, reaching 2 bits with "almost the same quality" and 2.6× lower peak memory (arXiv:2402.02750).
  • Eviction and structure. Keep only the keys that matter. H2O keeps recent tokens plus "heavy hitters" that accumulate the most attention (arXiv:2306.14048); StreamingLLM found that keeping just the first few tokens — attention sinks, which soak up attention mass the softmax must put somewhere — plus a recent window lets models stream up to 4 million tokens stably (arXiv:2309.17453). Architectures build this in: Mistral 7B's sliding-window layers (arXiv:2310.06825), Gemma 3's mix of mostly local layers with short windows and occasional global layers, chosen explicitly "to reduce the KV-cache memory that tends to explode with long context" (arXiv:2503.19786), and cross-layer attention, which shares key/value heads between adjacent layers for another 2× (arXiv:2405.12981).
PagedAttention: logical cache blocks map to any free physical block
PagedAttention: logical cache blocks map to any free physical block. sequence A logical blocks 0,1,2, sequence B (same prompt) logical blocks 0,1, block tables, physical block 7 (shared prompt), physical block 1, physical block 3, physical block 9, A0, B0, A1, A2, B1PagedAttention: logical cache blocks map to any free physical block. sequence A logical blocks 0,1,2, sequence B (same prompt) logical blocks 0,1, block tables, physical block 7 (shared prompt), physical block 1, physical block 3, physical block 9, A0, B0, A1, A2, B1

Eviction is lossy, and the loss is task-dependent

Dropping keys works well for perplexity on ordinary text, where most attention is local. It fails exactly when an old, rarely-attended token suddenly matters — a name defined 50,000 tokens back, the needle in a haystack test. Evaluate eviction and quantisation on retrieval tasks over your real context lengths, not on perplexity alone.

History

From recomputation to latent caches

2017 — Autoregressive transformer decoders cache past keys and values from the first implementations; the cost is not yet a concern at 512-token contexts. 2018 — Milakov and Gimelshein publish the one-pass online softmax (arXiv:1805.02867). 2019 — Shazeer proposes multi-query attention to cut decode bandwidth. 2021 — Rabe and Staats show attention needs only \(O(\sqrt{n})\) memory with chunking and a running softmax (arXiv:2112.05682). May 2022 — FlashAttention adds the IO-aware, hardware-level view and becomes the default kernel. 2023 — GQA (May), FlashAttention-2 (July), PagedAttention/vLLM (September), StreamingLLM's attention sinks (September), Flash-Decoding (October), SGLang's RadixAttention (December). 2024 — DeepSeek-V2 introduces MLA (May); FlashAttention-3 for Hopper (July). 2025 — DeepSeek open-sources FlashMLA kernels; MLA spreads to other open models built on DeepSeek's architecture.

First principles

Why a cache is valid at all. Causal masking means the hidden state of token \(j\) at every layer is a function of tokens \(1..j\) only. Appending token \(t > j\) cannot change it. So \(K\) and \(V\) rows, once computed, are final. In a bidirectional encoder every token's representation depends on every other token, and appending one invalidates everything — which is why BERT-style models have no KV cache.

Why decode must be memory-bound. Arithmetic intensity is FLOPs divided by bytes moved. A matrix–vector product with a \(d \times d\) weight matrix in BF16 does \(2d^2\) FLOPs and reads \(2d^2\) bytes: intensity 1. Batching \(B\) sequences turns it into a matrix–matrix product with intensity about \(B\) for the weights, but attention over the cache stays at about \(h/h_{kv}\) per sequence because each sequence reads its own cache. Hardware ridge points are in the hundreds of FLOPs per byte. No software trick changes this ratio except reusing bytes more: batching (weights), GQA/MLA (cache), or speculative decoding (several tokens verified per weight read).

Why tiling can be exact. Softmax looks global: every output needs the sum over the whole row. But the triple \((m, \ell, \tilde{\mathbf{o}})\) — running max, rescaled sum, rescaled weighted sum — is a sufficient statistic for a row, and two partial triples over disjoint key sets combine exactly (derived below). Combining is associative and commutative, so any order and any split of the keys gives the same answer up to rounding. This algebraic fact underlies FlashAttention (split over key tiles in sequence), Flash-Decoding (split over key chunks in parallel) and ring attention (split over devices).

What breaks if you share too much. One key/value head per layer means every query head must find its information in the same \(d_h\)-dimensional subspace. Heads that need different "views" of the past — one tracking syntax, one tracking entities — now compete. GQA's groups and MLA's absorbed per-head matrices are two answers to the same question: how to keep per-head views while storing shared bytes.

Why compress through a latent rather than share. Sharing fixes \(h_{kv}\) subspaces in advance. A latent of width \(d_c\) is a learned basis from which every head reads its own linear projection. MQA is the special case where every head's projection is the same; MLA lets them differ at no extra cache cost, since the per-head matrices live in the weights, not the cache.

The maths

Decode step cost. For a dense decoder with \(N\) parameters, \(L\) layers, \(h\) query heads, \(h_{kv}\) KV heads of width \(d_h\), context \(t\) and \(b\) bytes per number:

\[ \text{FLOPs} \approx 2N + 4\,L\,h\,d_h\,t, \qquad \text{bytes} \approx bN + 2\,b\,L\,h_{kv}\,d_h\,t . \]

The second FLOP term is the scores (\(\mathbf{q}K^\top\), \(2hd_ht\) per layer) plus the weighted sum (\(2hd_ht\)). The cache term in bytes overtakes the weights when \(t > N/(2Lh_{kv}d_h)\): for Llama 3 8B, \(8.0 \times 10^9 / (2 \cdot 32 \cdot 8 \cdot 128) \approx 122{,}000\) tokens per sequence, or \(122{,}000/B\) tokens each across a batch of \(B\).

Derivation: the online softmax is exact, and partial states merge

Fix one query row with scores \(s_1, \dots, s_n\) and values \(\mathbf{v}_1, \dots, \mathbf{v}_n\). The target is

\[ \mathbf{o} = \frac{\sum_j e^{s_j}\mathbf{v}_j}{\sum_j e^{s_j}}. \]

For any subset \(A\) of positions define the state \(\sigma(A) = (m_A, \ell_A, \tilde{\mathbf{o}}_A)\) with

\[ m_A = \max_{j \in A} s_j,\qquad \ell_A = \sum_{j\in A} e^{s_j - m_A},\qquad \tilde{\mathbf{o}}_A = \sum_{j \in A} e^{s_j - m_A}\mathbf{v}_j . \]

Every exponent is \(\le 0\), so nothing overflows. For disjoint \(A, B\) let \(m = \max(m_A, m_B)\). Since \(e^{s_j - m} = e^{m_A - m}e^{s_j - m_A}\) for \(j \in A\),

\[ \ell_{A\cup B} = e^{m_A - m}\ell_A + e^{m_B - m}\ell_B,\qquad \tilde{\mathbf{o}}_{A\cup B} = e^{m_A - m}\tilde{\mathbf{o}}_A + e^{m_B - m}\tilde{\mathbf{o}}_B . \]

This merge \(\oplus\) is associative and commutative (it is exactly the arithmetic of the full sums, written relative to a moving reference point). FlashAttention's inner loop is \(\sigma \leftarrow \sigma \oplus \sigma(\text{tile})\); Flash-Decoding computes \(\sigma\) of chunks in parallel and reduces with \(\oplus\). At the end,

\[ \frac{\tilde{\mathbf{o}}_{1:n}}{\ell_{1:n}} = \frac{e^{-m}\sum_j e^{s_j}\mathbf{v}_j}{e^{-m}\sum_j e^{s_j}} = \mathbf{o}, \qquad \log \sum_j e^{s_j} = m + \log \ell_{1:n}. \]

The log-sum-exp is all the backward pass needs to rebuild any probability: \(P_{ij} = \exp(s_{ij} - \text{LSE}_i)\).

Derivation: FlashAttention's HBM traffic

Let SRAM hold \(M\) numbers. Choose key blocks of \(B_c = \Theta(M/d)\) rows and query blocks of \(B_r = \Theta(\min(M/d, d))\) rows so that one \(Q\), \(K\), \(V\) block and a \(B_r \times B_c\) tile fit. In the original algorithm the outer loop runs over the \(T_c = N/B_c\) key/value blocks (each loaded once: \(\Theta(Nd)\) in total) and the inner loop over all query blocks, reading \(Q\) and reading and writing \(O\) and the statistics — \(\Theta(Nd)\) per outer iteration. Total:

\[ \Theta(Nd) + T_c \cdot \Theta(Nd) = \Theta\!\left(\frac{N}{M/d}\,Nd\right) = \Theta\!\left(\frac{N^2 d^2}{M}\right). \]

Standard attention writes and reads \(S\) and \(P\): \(\Theta(N^2)\), plus \(\Theta(Nd)\) for \(Q, K, V, O\). The ratio is \(d^2/M\); with \(d = 64\)–\(128\) and \(M\) in the tens of thousands of numbers, it is well below 1. FlashAttention-2 swaps the loops (queries outer), so each output block is written once and the statistics never leave SRAM, with the same asymptotic bound.

GQA. With \(h\) query heads and \(h_{kv}\) KV heads, query head \(i\) uses KV head \(g(i) = \lfloor i\,h_{kv}/h \rfloor\). Cache per token per layer: \(2h_{kv}d_h\) numbers. Attention FLOPs per decode step are unchanged (\(4hd_ht\) per layer); bytes fall by \(h/h_{kv}\), so the attention kernel's intensity rises by \(h/h_{kv}\).

MLA, in full (DeepSeek-V2 §2.1 notation, one layer, token \(t\), head \(i\)):

\[ \begin{aligned} \mathbf{c}_t^{KV} &= W^{DKV}\mathbf{h}_t, & \mathbf{k}^C_{t,i} &= W^{UK}_i\mathbf{c}_t^{KV}, & \mathbf{v}^C_{t,i} &= W^{UV}_i\mathbf{c}_t^{KV},\\ \mathbf{k}^R_t &= \operatorname{RoPE}_t\!\big(W^{KR}\mathbf{h}_t\big), & \mathbf{q}^R_{t,i} &= \operatorname{RoPE}_t\!\big(W^{QR}_i\mathbf{c}^Q_t\big), & \mathbf{q}^C_{t,i} &= W^{UQ}_i\mathbf{c}^Q_t,\\ \mathbf{k}_{j,i} &= [\mathbf{k}^C_{j,i};\, \mathbf{k}^R_j], & \mathbf{q}_{t,i} &= [\mathbf{q}^C_{t,i};\, \mathbf{q}^R_{t,i}], & \mathbf{c}^Q_t &= W^{DQ}\mathbf{h}_t, \end{aligned} \]
\[ \mathbf{o}_{t,i} = \sum_{j \le t}\operatorname{softmax}_j\!\left(\frac{\mathbf{q}_{t,i}^\top\mathbf{k}_{j,i}}{\sqrt{d_h + d_h^R}}\right)\mathbf{v}^C_{j,i},\qquad \mathbf{u}_t = W^O[\mathbf{o}_{t,1};\dots;\mathbf{o}_{t,h}]. \]

Cached per token: \(\mathbf{c}^{KV}_t \in \mathbb{R}^{d_c}\) and \(\mathbf{k}^R_t \in \mathbb{R}^{d_h^R}\). The score splits as \(\mathbf{q}^{C\top}_{t,i}W^{UK}_i\mathbf{c}_j + \mathbf{q}^{R\top}_{t,i}\mathbf{k}^R_j\): the first term absorbs \(W^{UK}_i\) into the query, the second is ordinary RoPE attention with one shared key head. (The queries are also compressed, through \(\mathbf{c}^Q_t\) of width \(d_c' = 1536\), to save activation memory in training; this does not affect the cache.)

Shapes for one decode step of MLA with absorption, \(h = 128\): absorbed query \((h, d_c) = (128, 512)\) plus RoPE query \((128, 64)\); cache \((t, 576)\); scores \((128, t)\); latent output \((128, 512)\); then \((128 \times 512) \to d\) through the precomputed \(W^O_i W^{UV}_i\).

Build it

Three NumPy programs (NumPy 2, no GPU needed): a KV cache, a FlashAttention forward pass, and a cache calculator with an MLA absorption check.

1. A KV cache is exact, and saves almost all the work.

import numpy as np
rng = np.random.default_rng(0)
d, T = 64, 512                                   # model width, tokens to generate
W_Q, W_K, W_V = (rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(3))
X = rng.standard_normal((T, d))                  # stand-in for the token vectors fed in, one per step

def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)

def attend_all(X):                               # no cache: recompute K, V for the whole prefix
    Q, K, V = X @ W_Q, X @ W_K, X @ W_V
    S = Q @ K.T / np.sqrt(d)
    S = np.where(np.tril(np.ones((len(X), len(X)), bool)), S, -np.inf)
    return softmax(S) @ V

flops_nocache = flops_cache = 0
K_cache = np.empty((0, d)); V_cache = np.empty((0, d)); outs = []
for t in range(1, T + 1):
    # without a cache, step t re-projects all t tokens and re-scores every pair
    flops_nocache += 3 * 2 * t * d * d + 2 * 2 * t * t * d
    # with a cache, step t projects only the new token and scores it against t keys
    x = X[t - 1:t]
    K_cache = np.vstack([K_cache, x @ W_K]); V_cache = np.vstack([V_cache, x @ W_V])
    q = x @ W_Q
    outs.append(softmax(q @ K_cache.T / np.sqrt(d)) @ V_cache)
    flops_cache += 3 * 2 * d * d + 2 * 2 * t * d

print("cached output == full recompute:", np.allclose(np.vstack(outs), attend_all(X)))
print(f"FLOPs without cache: {flops_nocache:.3e}")
print(f"FLOPs with cache:    {flops_cache:.3e}   ({flops_nocache / flops_cache:.0f}x fewer)")
print("cache holds", K_cache.size + V_cache.size, "numbers = 2 * T * d =", 2 * T * d)
cached output == full recompute: True
FLOPs without cache: 1.471e+10
FLOPs with cache:    4.620e+07   (318x fewer)
cache holds 65536 numbers = 2 * T * d = 65536

2. FlashAttention's forward pass: tiles plus an online softmax.

import numpy as np
rng = np.random.default_rng(1)
N, d, Br, Bc = 1024, 64, 128, 128               # sequence, head dim, query-tile rows, key-tile cols
Q, K, V = (rng.standard_normal((N, d)) for _ in range(3))
scale = 1 / np.sqrt(d)

def naive(Q, K, V):                              # materialises the full N x N matrix
    S = Q @ K.T * scale
    P = np.exp(S - S.max(1, keepdims=True))
    return (P / P.sum(1, keepdims=True)) @ V

def flash_forward(Q, K, V):
    O = np.zeros((N, d)); L = np.zeros(N)        # output and log-sum-exp (saved for backward)
    for i in range(0, N, Br):                    # each query tile is independent (one thread block)
        q = Q[i:i + Br]
        m = np.full(len(q), -np.inf)             # running row max
        l = np.zeros(len(q))                     # running softmax denominator
        acc = np.zeros((len(q), d))              # running un-normalised output
        for j in range(0, N, Bc):                # stream key/value tiles through "SRAM"
            s = q @ K[j:j + Bc].T * scale        # (Br, Bc) scores: the only N^2-sized piece, one tile at a time
            m_new = np.maximum(m, s.max(1))
            p = np.exp(s - m_new[:, None])
            corr = np.exp(m - m_new)             # rescale what we accumulated under the old max
            l = corr * l + p.sum(1)
            acc = corr[:, None] * acc + p @ V[j:j + Bc]
            m = m_new
        O[i:i + Br] = acc / l[:, None]
        L[i:i + Br] = m + np.log(l)
    return O, L

O, L = flash_forward(Q, K, V)
print("max |flash - naive| =", np.abs(O - naive(Q, K, V)).max())
S = Q @ K.T * scale
print("saved log-sum-exp matches:", np.allclose(L, np.log(np.exp(S - S.max(1, keepdims=True)).sum(1)) + S.max(1)))
print(f"largest score block held at once: {Br}x{Bc} = {Br*Bc:,} numbers, vs N^2 = {N*N:,}")
max |flash - naive| = 6.38378239159465e-16
saved log-sum-exp matches: True
largest score block held at once: 128x128 = 16,384 numbers, vs N^2 = 1,048,576

3. Cache sizes, and MLA's absorption trick.

import numpy as np
KiB, GiB = 1024, 1024**3
# (layers, numbers cached per token per layer) -- 16-bit numbers, 2 bytes each
configs = {
    "Llama 2 7B   (MHA, 32 KV heads)": (32, 2 * 32 * 128),
    "Llama 3 8B   (GQA, 8 KV heads)":  (32, 2 * 8 * 128),
    "Llama 3 70B  (GQA, 8 KV heads)":  (80, 2 * 8 * 128),
    "DeepSeek-V3  (MLA, d_c+d_R=576)": (61, 512 + 64),
    "DeepSeek-V3  if it used MHA":     (61, 2 * 128 * 128),
}
for name, (L, per_layer) in configs.items():
    b = 2 * L * per_layer
    print(f"{name}: {b / KiB:7.1f} KiB/token | 128K ctx: {b * 131072 / GiB:6.1f} GiB")

# MLA "absorption": attend in the latent space without ever building per-head keys/values
rng = np.random.default_rng(0)
n, d_c, d_h, n_h, d = 6, 32, 16, 4, 64           # tokens, latent, head dim, heads, model width
C = rng.standard_normal((n, d_c))                # cached latents c_j (one row per past token)
q = rng.standard_normal((n_h, d_h))              # the new token's per-head queries
W_UK = rng.standard_normal((n_h, d_c, d_h))      # latent -> key, per head
W_UV = rng.standard_normal((n_h, d_c, d_h))      # latent -> value, per head
W_O = rng.standard_normal((n_h, d_h, d))         # per-head output projection

def softmax(z): e = np.exp(z - z.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)
# naive: up-project every cached latent into keys and values for every head
K = np.einsum('jc,hcd->hjd', C, W_UK); V = np.einsum('jc,hcd->hjd', C, W_UV)
A = softmax(np.einsum('hd,hjd->hj', q, K) / np.sqrt(d_h))
y_naive = np.einsum('hj,hjd,hde->e', A, V, W_O)
# absorbed: fold W_UK into the query and W_UV into W_O; scores and sums happen on the latents
q_lat = np.einsum('hd,hcd->hc', q, W_UK)         # (n_h, d_c)
A2 = softmax(q_lat @ C.T / np.sqrt(d_h))
W_OV = np.einsum('hcd,hde->hce', W_UV, W_O)      # (n_h, d_c, d): precomputed once, offline
y_abs = np.einsum('hj,jc,hce->e', A2, C, W_OV)
print("absorbed MLA == naive MLA:", np.allclose(y_naive, y_abs))
Llama 2 7B   (MHA, 32 KV heads):   512.0 KiB/token | 128K ctx:   64.0 GiB
Llama 3 8B   (GQA, 8 KV heads):   128.0 KiB/token | 128K ctx:   16.0 GiB
Llama 3 70B  (GQA, 8 KV heads):   320.0 KiB/token | 128K ctx:   40.0 GiB
DeepSeek-V3  (MLA, d_c+d_R=576):    68.6 KiB/token | 128K ctx:    8.6 GiB
DeepSeek-V3  if it used MHA:  3904.0 KiB/token | 128K ctx:  488.0 GiB
absorbed MLA == naive MLA: True

In PyTorch you rarely write any of this: torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True) dispatches to a FlashAttention-style fused kernel when shapes and dtypes allow, and accepts enable_gqa=True in recent versions for grouped heads. The flash-attn package exposes the kernels directly, including a variable-length interface that packs sequences of different lengths without padding.

Things to try

  • In snippet 2, process the key tiles in reverse or random order. The answer should not change — why? Then implement Flash-Decoding: compute \((m, \ell, \tilde{\mathbf{o}})\) for four key chunks independently and merge them with the rule in The maths.
  • Add a causal mask to snippet 2. Which \((i, j)\) tile pairs can you skip entirely? What fraction of the work is that for \(N = 1024\), \(B_r = B_c = 128\)?
  • Turn snippet 1 into GQA: 8 query heads sharing 2 KV heads. Count cached numbers and check the output equals MHA with each KV head repeated 4 times.
  • Quantise K_cache in snippet 1 to int8 per token, then per channel, and compare the output error. Now plant one channel with 20× larger values in W_K (an outlier) and repeat. Which scheme survives?
  • Using the decode-cost formulas, find the batch size at which Llama 3 70B (140 GB of weights, 320 KiB per token) spends equal bytes on weights and cache at 32K context.

In practice

  • Measure the two phases separately. Time to first token is prefill (compute-bound; FlashAttention and big matmuls). Inter-token latency is decode (bandwidth-bound; cache size, batch, weight bytes). Optimisations for one rarely help the other.
  • Budget memory as weights + cache + activations. The serving engine allocates whatever is left after the weights to the KV cache, and that pool sets the maximum concurrent tokens. For a long-context product, \(h_{kv}\), \(d_h\), layer count and cache precision decide capacity more than parameter count.
  • Defaults as of 2026. FlashAttention-class fused kernels everywhere; GQA with 8 KV heads in most open dense models; MLA in DeepSeek-family models; paged caches with prefix reuse in vLLM and SGLang; FP8 KV caches common in production on Hopper and Blackwell GPUs.
  • Watch the head width. Fused kernels are tuned for \(d_h \in \{64, 128\}\) (and 256 in newer releases). An exotic head size can silently fall back to a slow path.
  • Prefix reuse changes prompt design. Put stable content (system prompt, tools, long documents) first and variable content last so that caches can be shared; a timestamp at the top of a prompt defeats every prefix cache.

Common misconceptions

  • "FlashAttention is an approximation." It is exact; the outputs differ from the naive kernel only by floating-point rounding. It reduces memory traffic, not FLOPs.
  • "FlashAttention makes attention linear-time." Memory becomes linear in \(n\); compute stays quadratic.
  • "The KV cache is part of the model's size." It is per-request state, created at inference time, and for long contexts it can exceed the weights.
  • "MQA/GQA make attention cheaper to compute." The FLOPs are the same; the bytes read per step shrink.
  • "MLA must be slower because it reconstructs keys and values." With absorption, nothing is reconstructed at decode time; attention runs on the latents directly.

Check yourself

A model has 40 layers, 40 query heads, 8 KV heads and d_h = 128. What is its KV cache per token in BF16, and for a batch of 16 sequences of 16K tokens?

\(2 \times 40 \times 8 \times 128 \times 2 = 163{,}840\) bytes = 160 KiB per token. Batch: \(16 \times 16{,}384 \times 160\) KiB \(= 40\) GiB.

Why is decoding one token at a time memory-bound even though prefill on the same GPU is compute-bound?

Prefill multiplies \(n \times d\) activations by \(d \times d\) weights, reusing each loaded weight \(n\) times (intensity about \(n\)). Decode multiplies a single vector by each weight matrix (intensity about 1 per sequence), and reads a per-sequence cache that no other sequence can reuse. GPU ridge points are hundreds of FLOPs per byte, so decode waits on memory.

FlashAttention does more FLOPs than standard attention. How can it be several times faster?

Its runtime is dominated by HBM traffic, not arithmetic. It never writes the \(n \times n\) score and probability matrices to HBM, and in the backward pass it recomputes them tile by tile from \(Q\), \(K\) and the saved log-sum-exp. In the paper's GPT-2 medium benchmark: 75.2 vs 66.6 GFLOPs, but 4.4 vs 40.3 GB of HBM traffic, 7.3 vs 41.7 ms.

Show that two partial softmax states over disjoint key sets can be merged exactly.

With \(m = \max(m_A, m_B)\): \(\ell = e^{m_A-m}\ell_A + e^{m_B-m}\ell_B\) and \(\tilde{\mathbf{o}} = e^{m_A-m}\tilde{\mathbf{o}}_A + e^{m_B-m}\tilde{\mathbf{o}}_B\). Each term re-expresses its partial sums of \(e^{s_j}\) relative to the common reference \(m\); the final output \(\tilde{\mathbf{o}}/\ell\) is the exact softmax-weighted average.

Why does RoPE stop MLA's key up-projection from being absorbed into the query, and how does DeepSeek work around it?

RoPE rotates each key by a matrix \(R_j\) depending on its position, so the score becomes \(\mathbf{q}^\top R_t^\top R_j W^{UK}\mathbf{c}_j\): a position-dependent factor sits between the query and \(W^{UK}\), so no single fixed matrix can be folded into the query projection. DeepSeek keeps the compressed part position-free and adds a small separate RoPE channel: per-head RoPE queries and one shared 64-dimensional RoPE key per token, cached alongside the latent.

Hard: in decode with GQA (h = 64 query heads, h_kv = 8), what is the arithmetic intensity of the attention kernel over the cache, in FLOPs per byte, for BF16? What does MLA with absorption give for h = 128, d_c = 512, d_R = 64?

GQA: per cached token and layer, bytes read \(= 2 \cdot 8 \cdot 128 \cdot 2 = 4096\); FLOPs \(= 4 \cdot 64 \cdot 128 = 32{,}768\); intensity 8 (that is, \(h/h_{kv}\)). MLA: bytes \(= 576 \cdot 2 = 1152\); FLOPs per head are about \(2(d_c + d_R)\) for the score and \(2d_c\) for the latent weighted sum, so \(128 \times 2 \times (576 + 512) = 278{,}528\); intensity about 242. MLA turns the cache read into something close to compute-bound, which is why DeepSeek reports large throughput gains and why dedicated kernels (FlashMLA) exist.

Hard: StreamingLLM keeps the first four tokens plus a recent window. Why do the first tokens matter if they are semantically unimportant?

Softmax weights must sum to one, so a head that has nothing useful to attend to must still put its mass somewhere. Models learn to park it on the first tokens, which every later position can see. Evicting them changes the softmax denominator for every query and shifts the mass onto other tokens, corrupting the outputs — perplexity explodes. Keeping them as sinks preserves the distribution the model was trained on.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads

  • Long context — what happens when \(n\) reaches hundreds of thousands: positions, sparse and ring attention, and whether models use the context they accept.
  • Mixture of experts — the other half of DeepSeek's architecture: cutting FLOPs per token as MLA cuts cache bytes.
  • Beyond transformers — architectures whose "cache" is a fixed-size state that never grows.
  • Serving LLMs — continuous batching, speculative decoding and the engines built on paged caches.
  • How a GPU works — the memory hierarchy and roofline behind every number on this page.