Contents
Figure 1: Grouped-Query and Multi-Query Attention Explained — the same queries, fewer stored keys and values, and a cache small enough to serve more than one user per GPU
You read that Llama 3 70B uses 64 query heads but only 8 key-value heads, and you wonder why anyone would throw away heads on purpose. The answer has nothing to do with training quality and everything to do with serving cost.
Every token a model generates drags a growing cache of keys and values through GPU memory, and that cache sets how many users one GPU can handle. This post covers what the cache costs, how multi-query and grouped-query attention shrink it, and the arithmetic that makes the choice obvious.
Why the KV Cache Matters
When a model generates text, it reuses work. It computes the keys and values for each past token once and stores them in a KV cache, so each new token only needs its own query, key, and value. That saves computation, but it creates a memory problem.
Every decoding step must read the entire cache from GPU memory. Autoregressive decoding becomes bandwidth-bound: the arithmetic units wait while memory delivers weights and the whole KV cache, one token at a time. That is the same lesson as FlashAttention — the bottleneck is traffic, not maths.
The cache size follows a simple formula:
KV cache bytes = 2 × layers × kv_heads × head_dim × sequence_length × bytes_per_value
The leading 2 covers keys and values. The kv_heads term is the one MQA and GQA attack.
The Baseline: Multi-Head Attention
In standard multi-head attention (MHA), every query head has its own key head and its own value head. A model with 64 query heads caches 64 key heads and 64 value heads in every layer.
Separate heads help because each one can attend to different relationships — that is the point of multi-head self-attention. But notice the cost: the cache grows with the full head count, and so does the bandwidth every decode step needs.
Multi-Query Attention (MQA)
Noam Shazeer proposed multi-query attention in 2019, in a paper titled Fast Transformer Decoding: One Write-Head is All You Need [1]. The idea is extreme: keep all the query heads, but share one key head and one value head across all of them. The queries still ask different questions; they all read the same lookup table.
The target was exactly the decoding bottleneck. Shazeer framed slow decoding as the memory-bandwidth cost of repeatedly loading large keys and values [1]. The cost is a small quality degradation compared with MHA — a trade that is worth it whenever serving dominates.
Grouped-Query Attention (GQA)
Ainslie and colleagues at Google proposed a middle path in 2023 [2]. Grouped-query attention divides the query heads into groups, and each group shares a single key head and a single value head. GQA-g denotes grouped-query attention with g groups.
The two extremes fall out as special cases:
g = 1: one group, so every query head shares one K/V pair. That is MQA.g = number of heads: every head gets its own group. That is MHA.
The interesting zone sits in between. The paper reports that uptrained GQA achieves quality close to multi-head attention while running almost as fast as multi-query attention [2].
There is also a scaling argument. Larger models generally increase their head counts, so MQA becomes an increasingly aggressive cut as models grow. GQA keeps the same proportional reduction in bandwidth and capacity at any size, which is why GQA became the default rather than MQA.
Converting Existing Models
The paper also contributes a conversion recipe. You can uptrain an existing multi-head checkpoint into an MQA or GQA model using about 5% of the original pretraining compute [2]: mean-pool the key and value projections within each group, then continue training briefly to let the model adapt.
Models can also train with GQA from scratch, and Llama 2 70B did exactly that — the first widely used open model to ship with it.
See It in Code
Here is a NumPy implementation where a single parameter, n_kv_heads, covers all three variants. One detail matters: Wk and Wv must be sized for n_kv_heads, not n_heads, because the projection matrices themselves shrink. That is the same saving the cache gets, applied to the weights:
import numpy as np
def softmax(x):
x = x - x.max(-1, keepdims=True); e = np.exp(x); return e / e.sum(-1, keepdims=True)
def gqa(x, Wq, Wk, Wv, n_heads, n_kv_heads):
T, C = x.shape
d = Wq.shape[1] // n_heads
q = (x @ Wq).reshape(T, n_heads, d).transpose(1, 0, 2) # (H, T, d)
k = (x @ Wk).reshape(T, n_kv_heads, d).transpose(1, 0, 2) # (Hkv, T, d)
v = (x @ Wv).reshape(T, n_kv_heads, d).transpose(1, 0, 2)
group = n_heads // n_kv_heads
k = np.repeat(k, group, axis=0) # each KV head serves `group` query heads
v = np.repeat(v, group, axis=0)
s = q @ k.transpose(0, 2, 1) / np.sqrt(d)
s = np.where(np.triu(np.ones((T, T), bool), 1), -np.inf, s) # causal mask
out = softmax(s) @ v
return out.transpose(1, 0, 2).reshape(T, n_heads * d)
The key lines are the two np.repeat calls. Each stored KV head is duplicated at compute time so every query head in its group can use it, but only the small version lives in the cache.
With 8 query heads, d = 4, and 6 tokens, here is what the cache holds per layer:
kv_heads=8 (MHA): out (6, 32), cached elements/layer=384
kv_heads=4: out (6, 32), cached elements/layer=192
kv_heads=2: out (6, 32), cached elements/layer=96
kv_heads=1 (MQA): out (6, 32), cached elements/layer=48
Same output shape, one eighth of the cache at the MQA extreme. Setting n_kv_heads = n_heads must reproduce ordinary multi-head attention exactly, so I checked that against a separate MHA implementation: allclose returned True with a maximum difference of 0.0 — bit-identical, as it should be, since no arithmetic changes, only which heads share inputs.
Production kernels avoid the np.repeat copy by indexing the grouped heads directly, but the maths is identical.
What It Saves in Real Models
Now the arithmetic that matters. I computed the KV cache for a Llama-2-70B-like configuration: 80 layers, head dimension 128, fp16, batch size 1.
| Context | MHA (64 KV heads) | GQA (8 KV heads) | MQA (1 KV head) |
|---|---|---|---|
| 4,096 tokens | 10.74 GB | 1.34 GB | 0.17 GB |
| 32,768 tokens | 85.90 GB | 10.74 GB | 1.34 GB |
At 32K context, plain MHA would need 86 GB for a single sequence — more than an entire 80 GB GPU, before weights, activations, or a second user. GQA with 8 KV heads cuts that eightfold.
The same factor applies to bandwidth. Llama 3 70B stores 327,680 bytes of KV per token with 8 KV heads, against 2,621,440 bytes if it kept all 64. Since decode latency is set by how much you must read per step, an eight-times smaller cache is an eight-times smaller read.
For a smaller example, a Mistral-7B-like setup (32 layers, 8 KV heads, head dimension 128) needs 4.29 GB at 32K tokens, versus 17.18 GB with full MHA at 32 query heads.
A smaller cache means more than lower latency: it means more concurrent requests per GPU. Eight-times less KV traffic per sequence means roughly eight times more sequences can share the same bandwidth budget — which is why GQA is a serving decision, not a modelling curiosity. Real throughput also depends on weights, batching, and kernel efficiency, so treat the factor as an upper bound rather than a promise.
Who Uses What
Adoption tells the story:
| Model | Query heads | KV heads | Notes |
|---|---|---|---|
| Llama 2 7B / 13B | 32 | 32 | Plain MHA |
| Llama 2 70B | 64 | 8 | GQA, the first mainstream open example |
| Llama 3 8B | 32 | 8 | GQA at every size |
| Llama 3 70B | 64 | 8 | GQA at every size |
| Mistral 7B | 32 | 8 | Four queries per group |
Llama 2 shipped GQA only on the 70B model, because the cache bottleneck bites hardest at the largest size. Llama 3 moved all sizes to GQA [3], and 8 KV heads became the de facto default across open-weight families — small enough to save memory, large enough to keep quality.
Other Ways to Shrink the Cache
Sharing heads is not the only lever:
- Cross-layer attention (CLA) shares key-value activations across layers, reducing the cache along a different axis, and composes with MQA and GQA [5].
- Multi-head latent attention (MLA) projects keys and values into a smaller latent space and caches the latent rather than full per-head K/V, which is what DeepSeek-V2 uses [4].
- KV-cache quantisation stores the cache in int8 or lower, trading a little accuracy for a large memory cut.
- FlashAttention does not shrink the cache, but it makes the reads that remain far more efficient, and the two are routinely combined.
What GQA Does Not Change
Keep the claims honest:
- Queries stay full-size. Compute for the score matrix does not shrink; only the stored keys and values do.
- Prefill remains compute-heavy. The savings show up mostly during token-by-token decoding.
- Quality is not free. The loss is small and usually worth it, but it is not zero.
- Fewer KV parameters. The key and value projection matrices shrink too, which changes the parameter budget — the toy code above shows why.
Common Pitfalls
- Assuming fewer KV heads means fewer query heads. The queries stay put.
- Picking
n_kv_headsthat does not dividen_heads. The grouping needs an integer ratio. - Using query heads in the cache formula. It uses KV heads — that is the whole point.
- Sizing
Wk/Wvforn_heads. The reshape then fails, or the saving silently disappears. - Expecting a speedup at short context. The benefit grows when decoding is bandwidth-bound.
- Retraining from scratch when uptraining would do. About 5% of pretraining compute converts a checkpoint.
- Trusting back-of-envelope numbers without the config. Layers, head dimension, and dtype change the totals.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Hands-On Large Language Models | its attention and generation chapters visualise exactly where the KV cache lives and why it grows with context. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read the attention and decoding chapters after this post. Seeing the cache drawn as a tensor that accumulates one row per token makes the eight-times saving feel like an obvious engineering choice rather than a trick.
Wrapping Up
MQA shares one key-value head across all query heads and cuts the cache hardest. GQA shares one per group, keeping quality close to full multi-head attention while capturing most of MQA's savings. Because decoding is memory-bandwidth-bound, a smaller KV cache means faster generation and more users per GPU — which explains why GQA became the default in modern open models.
The one formula to keep: 2 × layers × kv_heads × head_dim × seq_len × bytes. Plug in your model's numbers and the design choice stops being abstract.
Run the NumPy comparison above with n_kv_heads set to 8, 4, 2, and 1. The output shape never changes; only the cache does.
Frequently Asked Questions
What is the difference between MQA and GQA?
Multi-query attention keeps every query head but shares a single key head and a single value head across all of them. Grouped-query attention divides query heads into groups and gives each group its own key and value head, so MQA is the case with one group and standard multi-head attention is the case where every head is its own group.
Why does sharing KV heads not hurt quality much?
The queries stay independent, so each head still asks its own question and produces its own output slice. What is shared is the lookup table the queries read from. The GQA paper found that uptrained GQA reaches quality close to multi-head attention while running close to multi-query speed.
How much memory does the KV cache save?
The saving is exactly the ratio of query heads to KV heads. Llama 3 70B has 64 query heads and 8 KV heads, so its cache is one eighth the size of an equivalent multi-head model: 2.68 GB instead of 21.5 GB for a single 8K-token sequence in fp16.
Does GQA speed up prefill as well as decoding?
Mostly decoding. Prefill processes the whole prompt at once and is compute-heavy, so shrinking the cache barely changes it. Decoding generates one token at a time and must re-read the entire cache each step, which is exactly the memory-bandwidth cost that a smaller cache reduces.
Can I convert an existing multi-head model to GQA?
Yes. The GQA paper uptrains multi-head checkpoints into grouped-query models using about 5% of the original pretraining compute, by mean-pooling the key and value projections within each group and continuing training briefly.
Sources
[1]Shazeer, Fast Transformer Decoding: One Write-Head is All You Need — multi-query attention and the bandwidth argument for decoding: arxiv.org[2]Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — the grouping scheme, uptraining recipe, and 5% compute figure: arxiv.org[3]Meta AI, The Llama 3 Herd of Models — GQA at every size, with the 8B and 70B head configurations: arxiv.org[4]DeepSeek-AI, DeepSeek-V2 — multi-head latent attention and caching a compressed latent instead of full K/V: arxiv.org[5]Brandon et al., Reducing Transformer Key-Value Cache Size with Cross-Layer Attention — sharing KV activations across layers: arxiv.org
