Chapter 3 · Model Architecture 3.6
Efficient Attention: MQA, GQA, MLA and FlashAttention
Attention has two bottlenecks: the KV cache that decoding rereads at every step, and the N×N score matrix of training and prefill. MQA, GQA and MLA shrink the KV cache; FlashAttention cuts memory traffic with tiling and online softmax, and its output is identical to standard attention.
After this page you will be able to
- Tell the two bottlenecks of attention apart: the KV cache read again and again during decoding, and the N×N score matrix in training and prefill.
- Work out how many K/V entries MHA, MQA, GQA and MLA cache per token, and where each one saves.
- Explain how FlashAttention cuts memory traffic with tiling and online softmax while returning exactly the same result as standard attention.
- Verify online softmax and MLA's matrix absorption in code.
- Choose an attention variant for a given scenario and avoid the common traps.
On this page
- Two bottlenecks, two kinds of fix
- What determines the KV cache size
- MQA and GQA: share K/V across query heads
- What shrinking the K/V heads costs
- MLA: don’t keep fewer heads, compress K and V together
- Try it: the KV cache of attention variants
- FlashAttention: same result, less memory traffic
- Other ideas: look at only part of the sequence
- Hands-on code: check the online softmax and the matrix absorption
- What to choose, and common pitfalls
- Summary and exercises
- Quick check
- Further reading
- FAQ
Attention costs come from two different places. During training and prefill, the model computes an score matrix over the whole sequence, and the bottleneck is reading and writing it in GPU memory. During token-by-token decoding, every step rereads the keys and values of the entire history, and the bottleneck is the size of the KV cache. MQA, GQA and MLA attack the second problem by shrinking what each token must cache; FlashAttention attacks the first by computing attention in blocks with an online softmax, and its result is identical to standard attention.
Two bottlenecks, two kinds of fix
| Phase | Bottleneck | Depends on | Remedy |
|---|---|---|---|
| Training, long-sequence prefill | An score matrix that is written to and read from GPU memory repeatedly | The square of the sequence length | FlashAttention |
| Token-by-token decoding | Every step reads all historical K and V | KV cache size: layers, K/V heads, head dimension, sequence length | MQA, GQA, MLA, cache quantization, PagedAttention |
How large is the score matrix of one head? In FP16 (2 bytes) it is 32 MiB at , 2 GiB at and 32 GiB at . A standard implementation writes the scores to GPU memory, reads them back for the softmax, writes the result , and reads it back to multiply by , so both matrices are written and read once. , , and the output, by contrast, hold only numbers each, and is typically 64 to 128, far smaller than .
Because the problems differ, the fixes stack: FlashAttention does not change the size of the KV cache, and GQA and MLA do not change how one attention computation moves data.
What determines the KV cache size
During decoding the keys and values of past tokens never change, so they are cached. Each head has numbers for K and for V, so one layer and one token need numbers ( is the number of query heads). There are three structural ways to shrink it: fewer K/V heads, compress each K/V, or cache fewer tokens. MQA and GQA take the first, MLA the second and sliding windows the third; on top of that you can lower the precision of each number, which is cache quantization.
| Design | Numbers cached per layer and token | Meaning |
|---|---|---|
| MHA | Every query head has its own K and V | |
| GQA | query heads split into groups, one K/V per group | |
| MQA | One K/V shared by all query heads, GQA with | |
| MLA | A latent vector ( numbers) plus a RoPE key ( numbers) |
For the same shape the designs differ enormously. The table uses BF16 (2 bytes per number); layers, heads and head dimension come from each model’s paper or public configuration, and every row follows from the formulas above:
| Model | Attention design | Per token | Cache at 128K tokens |
|---|---|---|---|
| Llama 2 7B | MHA (32 K/V heads) | 512 KiB | 64 GiB (extrapolated with the same shape) |
| Llama 3 8B | GQA (8 K/V heads) | 128 KiB | 16 GiB |
| Llama 3 70B | GQA (8 K/V heads) | 320 KiB | 40 GiB |
| Llama 3 405B | GQA (8 K/V heads) | 504 KiB | 63 GiB |
| DeepSeek-V2 | MLA (, ) | 67.5 KiB | 8.44 GiB |
| DeepSeek-V3 | MLA (, ) | 68.6 KiB | 8.58 GiB |
All three Llama 3 sizes use 8 K/V heads (Table 3 of the Llama 3 paper), so the per-token cache varies with depth and head dimension, not with the number of query heads. DeepSeek-V3 has 128 query heads; with MHA each token would need about 3.81 MiB, while MLA needs 68.6 KiB, 1/56.9 of that.
MQA and GQA: share K/V across query heads
Multi-query attention (MQA), proposed by Shazeer in 2019, makes all query heads share a single K and V. The motivation is that incremental decoding is limited by memory bandwidth: smaller K/V tensors mean less data to read per step, and the paper reports much faster decoding with only minor quality degradation.
Grouped-query attention (GQA), proposed by Ainslie et al. in 2023, sits between MHA and MQA: the query heads are split into groups and each group shares one K/V pair. is MQA and is MHA. The GQA paper also gives a recipe for converting an existing MHA checkpoint: mean-pool the K and V heads within each group, then continue pretraining with the original recipe for 5% of the original steps.
Most open models today chose GQA: Llama 2’s 34B and 70B use it, all three Llama 3 sizes have 8 K/V heads, and so does Mistral 7B. The Llama 2 paper also names an engineering reason to prefer GQA over MQA: with tensor parallelism over 8 GPUs, MQA has fewer K/V heads than GPUs and can no longer be sharded by head, so the single K/V head must be duplicated on every GPU, which makes the cache as large as GQA’s anyway.
What shrinking the K/V heads costs
Three papers ran controlled comparisons, and their conclusions do not fully agree:
| Source | Setup | Result |
|---|---|---|
| GQA paper (Table 1) | T5-XXL (encoder-decoder), MHA checkpoint uptrained for 5% | Average score MHA 47.2, GQA-8 47.1, MQA 46.6; inference time per sample per TPUv4 chip 1.51 s, 0.28 s, 0.24 s |
| Llama 2 paper (Appendix A.2.1, Table 18) | 30B scale, 150B tokens each, FFN widened to match parameter counts | GQA comparable to MHA on most tasks and better than MQA on average |
| DeepSeek-V2 paper (Table 8) | 7B dense models, 1.33T tokens each, layers adjusted to align parameter counts | MMLU (5-shot) MHA 45.2, GQA-8 41.2, MQA 37.9; BBH (3-shot) 37.0, 35.6, 33.2 |
The benchmarks, model scales, training budgets and ways of matching parameter counts all differ, so the numbers are not directly comparable. The safe reading is that fewer K/V heads buy a proportional cache reduction, and the quality cost has no universal value: the DeepSeek team saw a clear gap on harder benchmarks. Whether to use GQA, and with how many groups, should be tested at your own scale and on your own evaluations.
MLA: don’t keep fewer heads, compress K and V together
Multi-head latent attention (MLA) comes from DeepSeek-V2. Instead of reducing the number of heads, it jointly compresses K and V into one low-dimensional latent vector and caches only that:
Here is the layer input of token , is the latent vector, is the down-projection, and are the up-projections that restore the keys and values of all heads, and is much smaller than . At inference only is cached.
Better still, restoring the full K and V is not necessary. Let and (of shape ) be the slices of the up-projections for head , and the attention weight of head from position to position . Then the score and the output can be written as
The first identity moves to the query side, so scores are computed directly in the latent space. The second sums the latent vectors first and multiplies by afterwards, and can be merged with the output projection ahead of time. The paper calls this absorbing the matrices; it means inference never has to reconstruct K and V for the prefix. The code below checks both identities numerically.
Why a separate RoPE key. RoPE acts on queries and keys and depends on position. Applying it directly to would place a position-dependent rotation between and ; matrix multiplication does not commute, so the absorption above no longer works and the keys of the whole prefix would have to be recomputed. DeepSeek-V2’s fix is decoupled RoPE: a small -dimensional query per head and one key shared by all heads, , carry the position. The key of head is and the scores are scaled by . That key is cached too, so MLA stores numbers per layer and token.
DeepSeek-V2 sets and , so its cache equals that of GQA with 2.25 groups (). Both DeepSeek-V2 and V3 use , and , which is 576 numbers per layer and token, 1/56.9 of an MHA with 128 query heads (32768 numbers). The DeepSeek-V2 abstract reports a 93.3% smaller KV cache than DeepSeek 67B.
The appendix also compares MLA with MHA in the same MoE architecture (Table 9, only the attention differs):
| Scale | Cache per token (MHA → MLA) | MMLU (5-shot) | BBH (3-shot) |
|---|---|---|---|
| Small MoE (about 16B parameters, 1.33T tokens) | 110.6K → 15.6K numbers (14%) | 48.7 → 50.0 | 37.9 → 39.0 |
| Large MoE (about 250B parameters, 420B tokens) | 860.2K → 34.6K numbers (4%) | 57.5 → 59.0 | 46.6 → 50.7 |
These are the DeepSeek team’s own ablations at modest training budgets, and the conclusion is that MLA is better than MHA with a much smaller cache. Keep the source in mind, and remember that, like the GQA comparison above (Table 8), it describes their setup.
Try it: the KV cache of attention variants
Pick a model shape, change the GQA group count, the MLA latent size, the context length, the cache precision and the KV budget, and watch how the cache of each design changes and how many sequences a given memory budget can hold at once.
- With the defaults (Llama 3 8B shape, 32K context, BF16, 40 GiB budget), MHA needs 16 GiB per sequence and fits 2; GQA () needs 4 GiB and fits 10; MQA needs 512 MiB and fits 80; MLA needs 1.13 GiB and fits 35.
- Switch to Llama 3 70B at 128K: MHA needs 320 GiB, GQA () 40 GiB, MQA 5 GiB and MLA 11.25 GiB. A 40 GiB budget holds exactly one GQA sequence and not even one MHA sequence.
- Switch to DeepSeek-V3 at 128K: the hypothetical MHA is 488 GiB, MLA is 8.58 GiB, about 1.8% of MHA (1/56.9), and the “Equivalent GQA groups” column reads 2.25.
- Drag to 256 and to 0: the MLA row’s equivalent group count becomes 1.00 and its cache equals MQA’s. The MLA cache depends only on , not on .
- Set the cache precision to FP8 / INT8 and every number halves: the GQA cache of Llama 3 70B at 128K drops from 40 GiB to 20 GiB. Cache quantization stacks with the attention design.
FlashAttention: same result, less memory traffic
A GPU has two levels of memory: large but slow GPU memory (HBM), and a small but much faster on-chip SRAM. Standard attention writes the two intermediates and to HBM and reads them back, and element-wise operations such as softmax have low arithmetic intensity, so the time is dominated by data movement (arithmetic intensity and the roofline are explained in GPUs and the Roofline Model). FlashAttention (Dao et al., 2022) makes the algorithm IO-aware: it splits , and into blocks, loads one small block at a time into SRAM, performs the matrix multiplications and the softmax there, and writes only the final output back to HBM, all fused into a single GPU kernel.
The difficulty is that a softmax needs the maximum and the sum of a whole row. FlashAttention uses an online softmax: as the blocks of a row arrive it keeps only three quantities, the running maximum , the normalizer and the unnormalized output , and updates them with each new block:
After the last block the output is . The old accumulators only need to be multiplied by the scalar to move them to the new maximum, so a whole row of scores is never stored. In the backward pass FlashAttention does not save and ; it saves the output and the per-row statistics and recomputes the blocks of and from , and when needed, a form of selective gradient checkpointing.
The paper analyzes the IO complexity (Theorem 2). With sequence length , head dimension and SRAM size (), standard attention needs HBM accesses and FlashAttention needs ; it also proves that no exact attention algorithm can asymptotically do better for all SRAM sizes. A measured example (Figure 2 of the paper: GPT-2 medium, sequence length 1024, head dimension 64, 16 heads, batch size 64, A100, forward plus backward):
| Metric | Standard attention | FlashAttention | Change |
|---|---|---|---|
| Compute | 66.6 GFLOPs | 75.2 GFLOPs | 13% more |
| HBM traffic | 40.3 GB | 4.4 GB | down to about 1/9.2 |
| Runtime | 41.7 ms | 7.3 ms | 5.7× faster |
The FLOPs went up because the backward pass recomputes the scores, but attention on a GPU is limited by memory traffic, so when the traffic falls the time falls with it. The end-to-end numbers in the abstract are 15% faster than the MLPerf 1.1 record on BERT-large (sequence length 512) and 3× faster on GPT-2 (sequence length 1K). Memory use also drops from quadratic to linear in the sequence length.
The next two generations apply the same idea to the hardware more completely:
| Version | Improvement | Reported result |
|---|---|---|
| FlashAttention-2 (2023) | Fewer non-matmul FLOPs, parallelism over the sequence length, better work split between thread blocks and warps | About 2× faster than FlashAttention, 50% to 73% of the theoretical peak FLOPs/s on an A100; up to 225 TFLOPs/s (72% model FLOPs utilization) when training GPT-style models end to end |
| FlashAttention-3 (2024) | For the H100: overlaps computation and data movement through the asynchrony of Tensor Cores and TMA, adds FP8 | On an H100 SXM5, FP16 forward is 1.5 to 2.0× faster than FlashAttention-2 (backward 1.5 to 1.75×), reaching up to 740 TFLOPs/s (75% utilization); FP8 reaches close to 1.2 PFLOPs/s; the paper says FlashAttention-2 reaches only 35% utilization on an H100 |
In PyTorch you do not need to call these kernels yourself: torch.nn.functional.scaled_dot_product_attention can use FlashAttention-2 and other optimized kernels on CUDA (see the function’s documentation).
Other ideas: look at only part of the sequence
Several other approaches change different things:
| Method | What it changes | Exact? | Example |
|---|---|---|---|
| FlashAttention | Block order of the computation and GPU memory traffic | Exact | Built into mainstream training and inference frameworks |
| Sliding-window attention | Each position sees only the previous tokens | Changes the model | Mistral 7B, |
| GQA, MQA | Number of K/V heads | Changes the model, needs training | Llama 2 70B, Llama 3 |
| MLA | The representation of K/V, a low-rank latent | Changes the model, needs training | DeepSeek-V2, V3 |
| Linear attention, SSMs | Drops the softmax and compresses the history into a fixed-size state | Lossy, changes the model, needs training | Mamba, Qwen3-Next, see State Space Models and Hybrid Architectures |
| KV cache quantization | Numeric precision of the cache | Lossy | See the quantization page |
| PagedAttention | How cache memory is managed | Exact | vLLM, see the KV cache page |
In sliding-window attention every position in every layer attends only to the previous tokens, yet stacking layers still lets information travel further: after layers it can move up to tokens. Mistral 7B has 32 layers and , so the theoretical attention span at the last layer is about 131K tokens (). Because each position only needs the K/V of the last tokens, the cache can be a rolling buffer of fixed size ; the paper says this cuts cache memory by 8× on a 32K-token sequence (). A span that information can theoretically reach is not the same as a length the model uses well, a point that comes back with long contexts.
Hands-on code: check the online softmax and the matrix absorption
The first snippet implements blocked, online-softmax attention in NumPy and compares it with the full version. It is a teaching version; the real FlashAttention fuses the whole loop into one GPU kernel and runs it in SRAM:
import numpy as np
def naive_attention(Q, K, V):
S = Q @ K.T / np.sqrt(Q.shape[1]) # the full N×N score matrix, all stored
P = np.exp(S - S.max(axis=1, keepdims=True))
P /= P.sum(axis=1, keepdims=True)
return P @ V
def tiled_attention(Q, K, V, block=128):
N, d = Q.shape
O = np.empty_like(Q)
for i in range(0, N, block): # outer loop: one block of Q at a time
q = Q[i:i + block]
m = np.full(len(q), -np.inf) # running max score per row
l = np.zeros(len(q)) # running softmax denominator (relative to m)
acc = np.zeros((len(q), d)) # running unnormalized output per row
for j in range(0, N, block): # inner loop: sweep over the blocks of K and V
s = q @ K[j:j + block].T / np.sqrt(d) # only a small block×block score tile
m_new = np.maximum(m, s.max(axis=1))
scale = np.exp(m - m_new) # rescale old accumulators to the new max
p = np.exp(s - m_new[:, None])
l = l * scale + p.sum(axis=1)
acc = acc * scale[:, None] + p @ V[j:j + block]
m = m_new
O[i:i + block] = acc / l[:, None]
return O
rng = np.random.default_rng(0)
N, d = 1000, 64
Q, K, V = (rng.normal(size=(N, d)) * 3 for _ in range(3)) # scaled up to make the softmax sharper
out_naive = naive_attention(Q, K, V)
out_tiled = tiled_attention(Q, K, V, block=128)
print(f"max abs error: {np.abs(out_naive - out_tiled).max():.1e}")
print(f"full score matrix {N * N * 8 / 2**20:.1f} MiB, the tiled version holds {128 * 128 * 8 / 2**10:.0f} KiB at a time")
Output:
max abs error: 3.0e-14
full score matrix 7.6 MiB, the tiled version holds 128 KiB at a time
The widget below shrinks that comparison to one query and 8 keys, and you can walk it block by block: only three quantities are ever kept (the running maximum m, the denominator l and the unnormalised output a), each new block first multiplies the two old accumulators by the conversion factor e^(m−m’) and then adds its own contribution. After the last block a / l matches the whole-row result digit for digit; tick the common-bug box to see how far the output drifts when the factor is skipped. The two numbers the page prints (7.6 MiB and 128 KiB) can be recomputed for other sequence lengths.
The two implementations agree to floating-point error: tiling changes where the intermediate data lives, not the result.
The second snippet checks MLA’s matrix absorption. With random matrices it computes the output once by “restore K and V, then run attention” and once by “absorb and work in the latent space”, and compares the two (the RoPE part is left out, so it only tests the two identities above):
import numpy as np
rng = np.random.default_rng(0)
d, n_h, d_h, d_c, T = 256, 8, 32, 48, 10 # toy sizes: hidden dim, heads, head dim, KV latent dim, length
H = rng.normal(size=(T, d)) # hidden state of every token
W_DKV = rng.normal(size=(d_c, d)) / np.sqrt(d) # down-projection d -> d_c
W_UK = rng.normal(size=(n_h, d_h, d_c)) / np.sqrt(d_c) # per-head K up-projection
W_UV = rng.normal(size=(n_h, d_h, d_c)) / np.sqrt(d_c) # per-head V up-projection
W_Q = rng.normal(size=(n_h, d_h, d)) / np.sqrt(d)
W_O = rng.normal(size=(d, n_h * d_h)) / np.sqrt(n_h * d_h)
C = H @ W_DKV.T # the cached latents: T × d_c, the only thing stored
t = T - 1 # the position being generated; causal attention sees 0..t
def softmax(s):
e = np.exp(s - s.max())
return e / e.sum()
# Way 1: restore K and V first, then run standard multi-head attention
heads = []
for h in range(n_h):
q = W_Q[h] @ H[t]
K, V = C @ W_UK[h].T, C @ W_UV[h].T # T × d_h
heads.append(softmax(K @ q / np.sqrt(d_h)) @ V)
u_explicit = W_O @ np.concatenate(heads)
# Way 2: absorb. W_UK goes into the query, W_UV into the output projection; K and V are never restored
u_absorbed = np.zeros(d)
for h in range(n_h):
q_abs = W_UK[h].T @ (W_Q[h] @ H[t]) # d_c-dimensional: the query lives in the latent space
p = softmax(C @ q_abs / np.sqrt(d_h)) # score = c_j · q_abs
u_absorbed += (W_O[:, h * d_h:(h + 1) * d_h] @ W_UV[h]) @ (p @ C)
print(f"max abs error between the two ways: {np.abs(u_explicit - u_absorbed).max():.1e}")
print(f"numbers cached per token and layer: MHA {2 * n_h * d_h}, MLA {d_c} (without the RoPE part)")
Output:
max abs error between the two ways: 6.1e-16
numbers cached per token and layer: MHA 512, MLA 48 (without the RoPE part)
The results match before and after absorption, so at inference MLA can store only and never has to restore the K and V of each prefix token.
What to choose, and common pitfalls
| Goal | Common choice | Notes |
|---|---|---|
| Training, long-sequence prefill | FlashAttention or a framework’s fused kernel | Exact, no quality cost |
| Training from scratch with deployment in mind | GQA, typically 8 K/V heads | The choice of Llama 2 70B, Llama 3 and Mistral 7B |
| An existing MHA checkpoint whose cache you want to shrink | Mean-pool the K/V heads into GQA, then continue training briefly | The GQA paper’s recipe, 5% of the original pretraining steps on T5-XXL |
| The cache is still the bottleneck (very long contexts, high concurrency) | MLA, cache quantization, sliding windows | MLA needs matching inference kernels (absorbed matrices, decoupled RoPE) and framework support varies, so check before committing |
Common mistakes:
- Counting only the K/V heads, forgetting depth and head dimension. The cache is proportional to : with 8 K/V heads each, Llama 3 405B needs 504 KiB per token and the 8B model only 128 KiB.
- Expecting FlashAttention to save KV cache. It saves intermediates like the score matrix and memory traffic; the cache size does not change at all.
- Assuming GQA is always nearly free. The three experiments above give different answers; the result depends on scale, training budget and evaluation.
- Fewer K/V heads than GPUs under tensor parallelism. The K/V must then be duplicated across GPUs, which eats into the savings.
- Leaving the RoPE key out of the MLA cache. Counting only underestimates it: .
- Reading “equivalent GQA groups” as equal quality. It only says the caches have the same size, not that the models are equally capable.
Summary and exercises
Key points:
- Attention has two bottlenecks: training and prefill are limited by the memory traffic of the score matrix, decoding by the size of the KV cache.
- Per layer and token, MHA caches numbers, GQA , MQA and MLA ; the DeepSeek-V2 and V3 setting equals GQA with 2.25 groups.
- The quality cost of fewer K/V heads depends on the setup: nearly lossless on T5-XXL, a clear gap in DeepSeek’s 7B ablation; in DeepSeek’s own ablation MLA shrank the cache and raised the scores at the same time.
- FlashAttention is exact: tiling and online softmax cut HBM traffic to , and it does not reduce the KV cache.
Quick check
1. A model has L layers, H query heads and head dimension d_h and uses MHA. How many numbers does the KV cache hold per token?
- H·d_h
- 2·H·d_h·L
- 2·H·d_h
- H·L
K and V each have H·d_h numbers, so one layer needs 2·H·d_h, multiplied by the number of layers L. For GQA, replace H with the number of groups g.
2. What is the main reason FlashAttention is faster than standard attention?
- It reduces the data moved between HBM and the on-chip SRAM
- It uses a low-rank approximation to cut the computation
- It only computes the most important tokens
- It shrinks the KV cache
In the paper’s example it even does 13% more computation, yet HBM traffic falls to about 1/9.2 and the time is 5.7× shorter. It is an exact algorithm and does not change the KV cache size.
3. Which statements are correct? (multiple choice)
- GQA with one group is MQA, and with H groups it is MHA
- Besides the latent vector, the MLA cache also holds a small key that carries RoPE
- MLA caches the full K and V at lower precision
- An MHA checkpoint can be turned into GQA by mean-pooling its K/V heads and training a little longer
MLA caches a d_c-dimensional latent vector and a d_R-dimensional RoPE key, not low-precision K and V. The other three come from the definition of GQA and the GQA paper’s conversion recipe.
4. DeepSeek-V3 has d_h = 128, d_c = 512 and d_R = 64. How many numbers does MLA cache per layer and token, and how many GQA groups is that equivalent to?
- 512 numbers, 2 groups
- 576 numbers, 2.25 groups
- 1024 numbers, 4 groups
- 64 numbers, 0.25 groups
The cache holds d_c + d_R = 576 numbers; one GQA group caches 2·d_h = 256 numbers, and 576 ÷ 256 = 2.25.
Exercises:
- A model has 32 layers, 32 query heads and head dimension 128, and caches in BF16. How many KiB per token does MHA need, and how many does GQA with need? How many GiB does one 16K-token sequence take in each case?
- In the widget choose Llama 3 70B, 128K context, BF16 and a 40 GiB budget. How many GiB does each of the four designs take, and how many sequences does each fit?
- Why is FlashAttention faster even though it does more FLOPs than the standard implementation?
- What goes wrong if MLA applies RoPE directly to the reconstructed key ?
Reference answers
- MHA: bytes bytes KiB, and a 16K sequence takes GiB. GQA with : bytes KiB, so a 16K sequence takes 1 GiB, 1/8 of MHA ().
- MHA 320 GiB (does not fit, 0 sequences), GQA () 40 GiB (1 sequence), MQA 5 GiB (8 sequences), MLA 11.25 GiB (3 sequences).
- The backward pass does not store and and recomputes them from blocks, so the FLOPs increase; but attention on a GPU is limited by memory traffic, HBM traffic falls to about 1/9.2, and the total time drops to about 1/5.7.
- The rotation depends on position and would sit between the query projection and . Matrix multiplication does not commute, so can no longer be absorbed into the query side and inference would have to recompute the keys of every prefix token. That is why MLA puts position into a small separate decoupled RoPE key and caches it next to the latent vector.
Further reading
-
Related pages: Modern LLM architecture, KV cache, Long context (these techniques in the cost accounting of a 128K window) and Attention basics.
-
Paper explainers on this site: FlashAttention, LLaMA, DeepSeek-V2 (where MLA was introduced, with a numerical check of absorption and decoupled RoPE) and DeepSeek-V3 (MLA).
-
Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019): MQA.
-
Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023): GQA and the 5% uptraining recipe; Table 1 above comes from this paper, and the paper breakdown recomputes its averages and the Llama 3 KV cache.
-
DeepSeek-AI, DeepSeek-V2 (2024) and DeepSeek-V3 Technical Report (2024): the MLA formulas, the cache comparison table (Table 1) and the ablations (Tables 8 and 9).
-
Touvron et al., Llama 2 (2023) and Llama Team, The Llama 3 Herd of Models (2024): the GQA ablation and the model configurations.
-
Dao et al., FlashAttention (2022), with a paper breakdown that goes through every experiment; Dao, FlashAttention-2 (2023); Shah et al., FlashAttention-3 (2024).
-
Jiang et al., Mistral 7B (2023): sliding-window attention and the rolling-buffer cache.
-
Why window attention collapses once the first tokens are evicted, and the StreamingLLM fix of keeping them: see the paper breakdown.
-
DeepSeek-AI, DeepSeek-V3.2 (2025): DSA, sparse attention from a lightning indexer plus top-k; the paper breakdown recomputes the indexer’s parameters and the per-token FLOPs and rebuilds DSA’s two training stages on a tiny byte-level model.
-
DeepSeek-AI, DeepSeek-V4.1-Flash (2026): CSA2 lets only 4 of 40 layers generate global KV while the rest reuse the cache and the selection, and a hierarchical indexer confines later layers to a candidate pool; the paper breakdown rebuilds the 890 bytes per token, the layer plan and the indexer’s scoring work from the public configs.
-
Yuan et al., Native Sparse Attention (NSA) (2025): DeepSeek’s trainable sparse attention, whose hardware-friendly block sparsity benefits both training and inference.
-
Luo et al., SageAttention3 (2025): quantizes the intermediate results of attention itself, further reducing attention’s memory-bandwidth footprint.
FAQ
- What is the difference between MQA, GQA and MLA?
- In standard multi-head attention (MHA) every query head has its own K and V. MQA lets all query heads share one K/V pair, GQA lets each group of query heads share one, and MLA does not cache K/V at all but a low-dimensional latent vector plus a small RoPE key. The numbers cached per layer and token are 2·H·d_h, 2·g·d_h, 2·d_h and d_c + d_R respectively (H is the number of query heads, g the number of groups, d_h the head dimension).
- How much quality does GQA lose?
- It depends on the setup, and there is no single number. The GQA paper converted a T5-XXL MHA checkpoint to GQA-8 with 5% extra training and got an average score of 47.1 against 47.2. In Llama 2's ablation (30B scale, 150B tokens) GQA matched MHA on most tasks. In DeepSeek-V2's 7B dense ablation (1.33T tokens) MHA scored 45.2 on MMLU against 41.2 for GQA-8, a clear gap. So GQA is not free; scale, training budget and how hard the benchmark is all change the gap, and you should test it in your own setting.
- Is FlashAttention an approximation?
- No. FlashAttention computes the same result as standard attention. It only splits the computation into blocks and accumulates them with an online softmax in the GPU's on-chip SRAM, so the N×N score matrix is never written back to GPU memory. What it saves is memory traffic and footprint, not FLOPs. In the paper's GPT-2 medium example the FLOPs rise slightly from 66.6 to 75.2 GFLOPs (the backward pass recomputes scores) while HBM traffic drops from 40.3 GB to 4.4 GB.
- Does FlashAttention reduce the KV cache?
- No. FlashAttention optimizes the intermediate results and memory traffic of one attention computation. The KV cache size is set by the number of layers, K/V heads, head dimension and sequence length, and is shrunk by GQA, MLA, sliding windows or cache quantization. The two kinds of optimization address different problems and can be combined.
- Why does MLA cache a separate RoPE key?
- Applying RoPE directly to the keys MLA reconstructs would put a position-dependent rotation between the query projection and the key up-projection. Matrix multiplication does not commute, so the trick of absorbing the key up-projection into the query no longer works, and inference would have to recompute the keys of every prefix token. DeepSeek-V2 carries position in a small separate part of the key instead (d_R is 64 in DeepSeek-V2 and V3) and caches it next to the latent vector.