Skip to content
LearnAI

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.

⏱ 15 minAdvanced

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: 2×32×128=8,1922 \times 32 \times 128 = 8{,}192 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:

ANALOGY· Reference books in a study room

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.

INTERACTIVEWho shares what
Variant
KV groups

Grouped-query attention: query heads are split into groups; each group shares one K head and one V head.

query heads (never cached)cached per token, per layer ↓q1q2q3q4q5q6q7q8K1 V1K2 V2
numbers cached per token per layer (8 heads, head dim 128)512 / 2,048 (25.0% of MHA)
query heads
8
K/V heads cached
2
query heads per K/V
4
formula
2·g·d_h
Eight query heads and the K/V heads they read from. Switch between variants and GQA group counts; the bar shows how many numbers each token adds to the cache per layer. In MLA, toggle between the training view (K and V rebuilt per head) and the absorbed inference view.

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 hth_t is projected down to a small latent vector

ctKV=WDKVht∈Rdc,c_t^{KV} = W^{DKV} h_t \in \mathbb{R}^{d_c},

and only this latent is cached. The per-head keys and values are produced from it by up-projections: kt,i=WiUKctKVk_{t,i} = W^{UK}_i c_t^{KV} and vt,i=WiUVctKVv_{t,i} = W^{UV}_i c_t^{KV} for each head ii. In DeepSeek-V2 and V3, dc=512d_c = 512 (the config’s kv_lora_rank), while 128 heads of size 128 would otherwise need 2×128×128=32,7682 \times 128 \times 128 = 32{,}768 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:

qt,i⊤ks,i=qt,i⊤WiUKcs=((WiUK)⊤qt,i)⊤cs.q_{t,i}^\top k_{s,i} = q_{t,i}^\top W^{UK}_i c_s = \big( (W^{UK}_i)^\top q_{t,i} \big)^\top c_s .

Matrix multiplication is associative, so WiUKW^{UK}_i 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 WiUVW^{UV}_i 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 qq and WUKW^{UK} 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 ktRk^R_t of dimension dR=64d_R = 64, 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 dc+dR=512+64=576d_c + d_R = 512 + 64 = 576 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.

INTERACTIVEKV cache per token for real models

DeepSeek-V3: 61 layers, 128 query heads, MLA with kv_lora_rank 512 + RoPE key 64, head dim 128.

MHA128 KV heads3.81 MiB/tokenGQA8 KV heads244 KiB/tokenMQAsingle KV head30.5 KiB/tokenMLA (actual)from config68.6 KiB/token

Faded bars are hypothetical: the same layers and head size, rebuilt with a different attention variant.

Cache dtype
DeepSeek-V3 per token
68.6 KiB
70,272 bytes
one 32,768-token sequence
2.14 GiB
vs full MHA
1.8%
56.9× smaller
Pick a model to see its actual KV cache per token (orange, computed from its published config) next to hypothetical versions of the same model with other attention variants. Then set a context length.

Things to try:

  1. 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.
  2. 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).
  3. Falcon-7B. An early MQA model: a single KV head of size 64 gives just 8 KiB per token.
  4. 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 LL be the number of layers, nhn_h the number of query heads, dhd_h the head dimension, gg the number of KV heads (groups) in GQA, dcd_c the MLA latent size, dRd_R the decoupled RoPE dimension and bb the bytes per number. Numbers cached per token:

MHA:2 nh dh LGQA:2 g dh LMQA:2 dh LMLA:(dc+dR) L\begin{aligned} \text{MHA:}\quad & 2\, n_h\, d_h\, L \\ \text{GQA:}\quad & 2\, g\, d_h\, L \\ \text{MQA:}\quad & 2\, d_h\, L \\ \text{MLA:}\quad & (d_c + d_R)\, L \end{aligned}

Multiply by bb for bytes. MLA has no factor of 2 because one latent serves both keys and values.

Worked example at DeepSeek-V3’s dimensions (L=61L = 61, nh=128n_h = 128, dh=128d_h = 128, dc=512d_c = 512, dR=64d_R = 64, BF16 so b=2b = 2):

variantnumbers per layer× 61 layersbytes per token32K-token sequence
MHA (128 KV heads)32,7681,998,8483.81 MiB122 GiB
GQA (8 KV heads)2,048124,928244 KiB7.6 GiB
MQA (1 KV head)25615,61630.5 KiB0.95 GiB
MLA (512 + 64)57635,13668.6 KiB2.1 GiB

The DeepSeek-V2 paper puts this another way: MLA’s cache equals that of GQA with only 2.25 groups (576=2×2.25×128576 = 2 \times 2.25 \times 128), while its quality is reported to be stronger than MHA.

Why absorption works. For head ii, with qt,iCq^C_{t,i} the content part of the query,

(qt,iC)⊤ks,iC=(qt,iC)⊤WiUKcs=((WiUK)⊤qt,iC)⊤cs.(q^C_{t,i})^\top k^C_{s,i} = (q^C_{t,i})^\top W^{UK}_i c_s = \big((W^{UK}_i)^\top q^C_{t,i}\big)^\top c_s .

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 RR between qq and WiUKW^{UK}_i, giving q⊤R WiUKcsq^\top R\, W^{UK}_i c_s, where RR depends on the positions involved and can’t be precomputed into one matrix. Hence the separate dRd_R-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.

COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. 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?

  2. Q2.What exactly do query heads share in grouped-query attention?

  3. Q3.Why can't MLA simply apply RoPE to the keys reconstructed from the latent?

  4. Q4.DeepSeek-V3 caches 576 numbers per token per layer. Which statement is correct?

  5. Q5.You convert a trained MHA model into GQA. According to the GQA paper, what's a cheap way to do it?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.