4.4MHA vs MQA vs GQA vs MLA
Four ways to organize attention heads, compared by the one number that dominates long-context serving, the KV cache per token, and what each costs in quality.
The head count is a memory decision
In multi-head attention a layer runs several attention “heads” side by side, each with its own query, key and value projections. Llama-2-7B has 32 heads of size 128 in each of its 32 layers. During generation, every one of those heads contributes a key vector and a value vector per token to the KV cache: numbers per token per layer.
Queries are different. They are used once, for the current token, and thrown away. So a natural question is whether every query head really needs its own keys and values. If several query heads could look at the same keys and values, the cache would shrink by that factor, and so would the memory traffic that makes decoding slow. That one question has produced four designs, in roughly historical order:
- MHA (multi-head attention): one K/V head per query head. The original Transformer design.
- MQAMulti-query attention (MQA)An attention variant in which all query heads share a single key head and a single value head, shrinking the KV cache by a factor equal to the number of heads. (multi-query attention, Shazeer 2019): one K/V head shared by all query heads.
- GQAGrouped-query attention (GQA)Attention in which groups of query heads share one key/value head, shrinking the KV cache. MQA is the extreme case of one shared KV head. (grouped-query attention, Ainslie et al. 2023): query heads in groups, one K/V head per group. MHA and MQA are its two extremes.
- MLAMulti-head latent attention (MLA)DeepSeek's attention variant that compresses keys and values into a small latent vector per token, greatly reducing KV-cache size. (multi-head latent attention, DeepSeek-V2, 2024): cache a low-rank latent vector from which every head’s keys and values can be reconstructed.
Eight students (the query heads) are writing essays, and each needs reference material (keys and values). In MHA, every student gets a personal copy of their own reference book: eight books on the shelf. In MQA, the whole room shares one book. It saves a lot of shelf space, but everyone must make do with the same material. GQA is the compromise: students sit at tables of four, one book per table.
MLA is cleverer: the shelf holds one dense summary pamphlet (the latent), and each student has a personal lens (an up-projection) that reconstructs exactly the view of the material they need. At exam time you can even grind each lens into the student’s glasses (the absorption trick), so nobody ever prints the reconstructed books. The shelf space is the KV cache.
MQA and GQA: sharing heads
Multi-query attention keeps all the query heads but uses a single key projection and a single value projection. Each query head still computes its own attention pattern, because the queries differ, but every head reads the same keys and values. The cache shrinks by a factor equal to the number of heads: 32× for a Llama-2-7B-shaped model. Shazeer introduced it specifically because incremental decoding was bottlenecked by loading keys and values from memory. The price is some quality loss and, reportedly, less stable training.
Grouped-query attention interpolates. With 32 query heads and 8 KV heads, each KV head serves a group of 4 query heads, and the cache is 4× smaller than MHA. The GQA paper showed that GQA gets close to MHA quality at close to MQA speed. It also showed that an existing MHA checkpoint can be “uptrained” into GQA by mean-pooling the K and V heads within each group and then continuing training with about 5% of the original pretraining compute. GQA is now the default for most open dense models: Llama 3 (8 KV heads), Qwen3 (4 to 8 KV heads), Mistral and many others.
Grouped-query attention: query heads are split into groups; each group shares one K head and one V head.
MLA: compress, then reconstruct
DeepSeek’s multi-head latent attention takes a different route. Instead of sharing heads, it compresses. For each token, the hidden state is projected down to a small latent vector
and only this latent is cached. The per-head keys and values are produced from it by up-projections: and for each head . In DeepSeek-V2 and V3, (the config’s kv_lora_rank), while 128 heads of size 128 would otherwise need numbers per token per layer.
Unlike MQA, every head still gets distinct keys and values, because each head has its own up-projection. The paper argues this keeps MHA-level expressiveness, and its ablations report MLA matching or beating MHA while caching far less.
The absorption trick. Reconstructing all 128 heads’ keys for every cached token at every step would be expensive. But look at an attention score:
Matrix multiplication is associative, so can be folded into the query side: each head maps its query into the 512-dimensional latent space once, then dots it directly with the cached latents. Likewise can be folded into the output projection. At inference, attention runs directly over the compressed cache, behaving like a multi-query attention whose single shared “head” is the latent.
Decoupled RoPE. There’s a snag. RoPE rotates queries and keys by position-dependent angles. A rotation sitting between and depends on the positions involved, so it can’t be folded into a fixed matrix, and absorption breaks. DeepSeek’s fix is to carry position separately: a small extra key of dimension , with RoPE applied, shared across all heads and cached alongside the latent, plus a matching RoPE part on each head’s query. Each score is then the sum of a content part (through the latent, absorbable) and a position part (through the small RoPE key). Per token per layer, the cache holds numbers.
DeepSeek-V2 reported that, compared with its earlier DeepSeek 67B model, MLA and its other changes cut the KV cache by 93.3% and raised maximum generation throughput by up to 5.76×. MLA also compresses the queries with their own low-rank bottleneck (rank 1536 in V3), which saves activation memory in training but doesn’t affect the cache.
DeepSeek-V3: 61 layers, 128 query heads, MLA with kv_lora_rank 512 + RoPE key 64, head dim 128.
Faded bars are hypothetical: the same layers and head size, rebuilt with a different attention variant.
Things to try:
- DeepSeek-V3. Its MLA cache is about 69 KiB per token in BF16. Rebuilt with full MHA over its 128 heads it would need about 3.8 MiB: 57× more. At 128K context that is the difference between about 8.6 GiB and about 488 GiB per sequence.
- Llama-3-70B versus Llama-2-7B. The 70B model has more than twice as many layers, but because of GQA with 8 KV heads its cache per token (320 KiB) is smaller than the 7B MHA model’s (512 KiB).
- Falcon-7B. An early MQA model: a single KV head of size 64 gives just 8 KiB per token.
- Compare MQA with MLA on any model. MQA caches even less than MLA. MLA’s advantage is not the smallest possible cache, but a much smaller cache without giving up per-head keys and values.
Choosing a variant in practice
For a new dense model of moderate size, GQA is the safe default: it is supported by every inference engine and kernel library, it costs little quality, and the number of KV groups is a simple dial between memory and expressiveness. MQA survives mainly in smaller models where every byte of cache matters. MLA shines when the head count is large and contexts are long, which is exactly the regime of big MoE models serving 128K-token conversations, but it needs specialized kernels (the absorbed form changes the shapes of the matrix multiplies) and a little care with positional encoding. Its compressed cache also makes serving cheaper in a second way: when caches are moved between machines, for example from prefill workers to decode workers, fewer bytes have to travel. Kimi K2 is one example of a later model family that adopted MLA, and you’ll meet others in Part 5.
MATH CORNER · optionalPer-token cache size, variant by variant
Let be the number of layers, the number of query heads, the head dimension, the number of KV heads (groups) in GQA, the MLA latent size, the decoupled RoPE dimension and the bytes per number. Numbers cached per token:
Multiply by for bytes. MLA has no factor of 2 because one latent serves both keys and values.
Worked example at DeepSeek-V3’s dimensions (, , , , , BF16 so ):
| variant | numbers per layer | × 61 layers | bytes per token | 32K-token sequence |
|---|---|---|---|---|
| MHA (128 KV heads) | 32,768 | 1,998,848 | 3.81 MiB | 122 GiB |
| GQA (8 KV heads) | 2,048 | 124,928 | 244 KiB | 7.6 GiB |
| MQA (1 KV head) | 256 | 15,616 | 30.5 KiB | 0.95 GiB |
| MLA (512 + 64) | 576 | 35,136 | 68.6 KiB | 2.1 GiB |
The DeepSeek-V2 paper puts this another way: MLA’s cache equals that of GQA with only 2.25 groups (), while its quality is reported to be stronger than MHA.
Why absorption works. For head , with the content part of the query,
The bracketed vector is computed once per head per step, so the score against every cached token is a dot product in the 512-dimensional latent space. RoPE would insert a position-dependent rotation between and , giving , where depends on the positions involved and can’t be precomputed into one matrix. Hence the separate -dimensional RoPE key.
In code
GQA is a small change to standard attention: compute fewer K/V heads and repeat each one across its group of query heads.
import torch, torch.nn.functional as F
def gqa_attention(x, Wq, Wk, Wv, n_q_heads, n_kv_heads):
B, T, d = x.shape
dh = d // n_q_heads
q = (x @ Wq).view(B, T, n_q_heads, dh).transpose(1, 2) # (B, Hq, T, dh)
k = (x @ Wk).view(B, T, n_kv_heads, dh).transpose(1, 2) # (B, Hkv, T, dh) ← cached
v = (x @ Wv).view(B, T, n_kv_heads, dh).transpose(1, 2) # (B, Hkv, T, dh) ← cached
group = n_q_heads // n_kv_heads
k = k.repeat_interleave(group, dim=1) # each KV head serves `group` query heads
v = v.repeat_interleave(group, dim=1)
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return y.transpose(1, 2).reshape(B, T, d)
# n_kv_heads == n_q_heads → MHA; n_kv_heads == 1 → MQA
Only k and v before repeat_interleave go into the cache, which is the whole point. Optimized kernels skip the explicit repeat and index the shared heads directly.
- “GQA and MQA reduce the number of attention heads.” The number of query heads, and therefore of distinct attention patterns, is unchanged. Only the number of key/value heads, and the cache, shrinks.
- “MLA has the smallest possible KV cache.” MQA caches less. MLA’s selling point is a small cache that still gives every head its own keys and values, which the DeepSeek-V2 paper reports performs at least as well as MHA.
- “MLA must decompress the whole cache at every step.” Thanks to the absorption trick, the up-projections can be folded into the query and output projections, so attention runs directly on the compressed latents.
- “These variants make attention cheaper to compute.” Their main benefit is memory: a smaller cache and less data to read per decoding step. FLOPs for the attention scores themselves change much less.
Check your understanding
Q1.A model has 64 query heads, 8 KV heads, head dim 128 and 80 layers. How many numbers per token does its KV cache hold?
Q2.What exactly do query heads share in grouped-query attention?
Q3.Why can't MLA simply apply RoPE to the keys reconstructed from the latent?
Q4.DeepSeek-V3 caches 576 numbers per token per layer. Which statement is correct?
Q5.You convert a trained MHA model into GQA. According to the GQA paper, what's a cheap way to do it?
Further reading
- paperFast Transformer Decoding: One Write-Head is All You Need — Shazeer, 2019: multi-query attention.
- paperGQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — Ainslie et al., 2023: grouped-query attention and uptraining.
- paperDeepSeek-V2 (introduces multi-head latent attention) — Low-rank KV compression, decoupled RoPE and the KV-cache comparison table.
- paperDeepSeek-V3 Technical Report — MLA at 671B scale.
- codeDeepSeek-V3 config.json — kv_lora_rank 512, qk_rope_head_dim 64, 61 layers, 128 heads.