8.3 — Grouped-query and multi-query attention (GQA / MQA)
Goal: Derive the GQA / MQA mask on the multi-head attention design: K and V projections are shared across groups of query heads. Quantify the KV-cache shrink as a function of the group count g, and the quality loss it costs. Connect to why Llama-3, Mistral, Qwen, and most 2024+ frontier dense models adopted it.
1. Why this session exists
The KV-cache analysis of 6.14 ended with a numerical wall: for LLaMA-7B at a -token context, the KV cache is GB per sequence in fp16 — larger than the model parameters themselves. The cache is dominated by the count , and the only freely-tunable factor among those (without changing the model's hidden size , the depth , or the served context ) is the number of distinct K and V projections per layer.
The structural observation behind grouped-query attention (GQA) and multi-query attention (MQA): there is no rule that says each query head must have its own and . We can share K and V across groups of query heads, paying a small quality cost and getting a linear reduction in KV-cache size and in decode-step memory bandwidth.
This session derives the construction, counts the savings, and places GQA / MQA as the standard choice in 2024+ frontier dense models (Llama-3, Mistral, Qwen, Gemma). MLA, the more aggressive 2024 alternative used by DeepSeek, is the subject of §8.5.
2. The design space: from MHA to MQA
Standard multi-head attention (MHA, 6.4) has query heads, key heads, and value heads — one of each per head index . Multi-query attention (MQA, Shazeer 2019[2], arXiv:1911.02150) shares one K head and one V head across all query heads. Grouped-query attention (GQA, Ainslie et al. 2023, arXiv:2305.13245) generalises: partition the query heads into groups of heads each, and use one K and one V projection per group, shared across the queries in that group.
Parameterise by the number of KV groups :
| Variant | | K, V heads | Comment | |---|---:|---:|---| | MQA | | each | Most aggressive sharing | | GQA-2 | | each | Two K, two V across all query heads | | GQA- | | each | K-heads, V-heads | | MHA | | each | No sharing — recover standard MHA |
GQA- is MHA; GQA- is MQA. So the choice is a single integer .
2.1 The forward pass, formally
Fix hidden size , query heads , group count , per-head dimension . Define the projection matrices:
The matrix has the same shape as in MHA; the and matrices have width instead of , i.e. they output (not ) K-heads. Given :
Reshape: , , . Now per query head we need to pick which K, V to use. Group head to KV group
i.e. the first query heads use K, V group ; the next query heads use group ; etc. Per query head, apply scaled dot-product attention (6.2) with the shared K and V of its group:
Concatenate the heads, project: . The output shape matches MHA. So GQA is a drop-in replacement for MHA at the level of input/output signatures; the change is interior to MHA.
3. KV-cache shrink: the headline win
The KV-cache equation of 6.14 §4 was
where is bytes per element. With GQA-, the K, V tensors per layer have only (not ) heads. So
The cache shrinks by factor . For MQA (), this is — a reduction for . For GQA- in a model, this is .
Numerical example. LLaMA-3-70B uses GQA- with , , , . At :
The MHA version would not fit on an 80 GB H100 even for batch size 1; the GQA- version leaves GB for model weights and activations. This is the operational reason for GQA's adoption: it makes long-context serving with batch parallelism feasible on standard 80 GB accelerators.
3.1 Compute count and parameter count
Parameter count of the attention sub-layer, with , , :
For (MHA) this is — the value of 6.4 §3. For (MQA) it is — about half of MHA. Per-layer parameter savings are modest; the dominant win is the KV cache.
FLOPs per training-time forward pass per layer (compare 6.12):
- Projections ( output): . For MQA this is instead of — half.
- Score matmul per head: per head, heads . Independent of .
- Mix with : . Independent of .
So the dominant FLOPs (the terms) are the same for MQA, GQA, and MHA at training time. Decode-time FLOPs are dominated by the projections, which do shrink slightly with . But the headline number is the KV-cache memory and the bandwidth to read it during decode.
3.2 Decode bandwidth, the operational metric
At decode, per generated token, we read and from HBM, perform a single-query attention of shape , and discard most of the multiplied-out result. The bandwidth cost per layer per step is
For MQA, , so decode-step KV bandwidth drops by . Combined with the (model-parameter-fixed) bandwidth to read the layer's weights, this gives a clean wall-clock decode speedup that scales with until the parameter-reading bandwidth dominates. For LLaMA-3-70B (), the empirical decode-step speedup vs the hypothetical MHA-70B is – depending on context length and batch.
4. The quality cost
The harder question: how much quality do we lose by tying K, V across query heads?
Ainslie et al. (2023)[1] measured this empirically by uptraining MHA checkpoints into GQA and MQA. The recipe:
- Take an existing MHA-trained checkpoint with K and V heads.
- Mean-pool the K-heads down to K-heads (and same for V): each group's K is the average of the original K's it absorbs.
- Continue training for a small fraction () of the original training budget with the GQA mask in place.
Result: with , post-uptraining quality is within perplexity of the original MHA checkpoint on standard benchmarks. With (MQA), quality drops a measurable – perplexity. The interpretation: collapsing all heads to a single K, V pair loses some of the per-head specialisation observed in trained MHA models (6.4 §4), but still has enough specialisation to recover most of the quality.
This is the empirical sweet spot the field converged on:
| Model | | | Variant | |---|---:|---:|---| | LLaMA-1, LLaMA-2-7B | 32 | 32 | MHA | | LLaMA-2-34B / 70B | 56 / 64 | 8 | GQA- | | LLaMA-3 (all sizes ≥ 8B) | 32 / 64 | 8 | GQA- | | Mistral-7B | 32 | 8 | GQA- | | Qwen-2 | 32 / 64 | 8 | GQA- | | Gemma-2 | 32 / 48 | 8 / 16 | GQA- / GQA- | | Falcon-180B | 64 | 1 | MQA | | PaLM (early) | — | 1 | MQA |
GQA- is the de facto 2024–2026 default for dense decoder-only models. MQA still appears in a few large dense models (Falcon-180B, PaLM); the empirical view is that at very large , even has enough effective capacity, but the point gives a quality-cost insurance policy with little additional cache.
5. Uptraining vs from-scratch
A model can be either trained from scratch with GQA or uptrained from an MHA checkpoint. Three observations.
(a) From-scratch training is no harder than MHA training. Same losses, same recipes, same hyperparameters. The only change is the per-layer projection shapes. LLaMA-3 was trained from scratch with GQA-; no pre-existing MHA checkpoint was involved.
(b) Uptraining from MHA works and is cheap. The mean-pool initialisation closes most of the gap with of original training compute. The technique is useful when an organisation already has an MHA model and wants to shrink its KV cache without retraining from scratch — LLaMA-2-70B's GQA variant was produced this way.
(c) The MHA → GQA transition is unidirectional. Once trained with groups, the model has internalised the group structure; you cannot recover the lost K, V diversity by "unpooling" the projections. This matters for serving: a model trained with cannot be served with to recover MHA quality at inference time.
6. Where GQA fits with the rest of Chapter 8
GQA is one of two attention-side KV-cache shrinkers; MLA (§8.5) is the other. They differ in their structural device:
- GQA shrinks the number of K, V heads — fewer projections, but each is full per-head-dimension.
- MLA shrinks the dimension of K, V via a low-rank latent — the number of heads is preserved (in the -side count), but K and V are stored compressed and decompressed at attention time.
They are not mutually exclusive (one could imagine GQA combined with MLA), but in practice no model uses both: GQA is the simpler, more widely-adopted option in dense Western LLMs, and MLA is DeepSeek's choice for their V2/V3/R1 lineage. We will derive MLA carefully in §8.5 to compare.
The other Chapter 8 sessions are orthogonal to the GQA/MLA choice: SwiGLU (§8.4) touches the FFN, MoE (§8.6) replaces the FFN with a router-plus-experts, Mamba (§8.7) replaces attention entirely with an SSM, hybrids (§8.8) mix Mamba and attention layers. Frontier dense models in 2026 typically combine GQA- + SwiGLU + RMSNorm + RoPE inside the block diagram of 8.1 §6.
7. What we keep going forward
Three takeaways for the rest of the chapter:
-
GQA- is parameterised by one integer. Replace K-heads and V-heads with K-heads and V-heads; tie groups of query heads to each KV group. Default .
-
The shrink is exactly in KV cache and decode-step KV bandwidth. That is the operational reason it became the 2024+ default.
-
Quality cost is small ( perplexity) at for dense models in the B–B range, after either from-scratch training or -budget uptraining from MHA.
GQA is the first of three KV-cache treatments in Chapter 8. The next, SwiGLU (§8.4), shifts to the FFN side; MLA (§8.5) returns to attention with a more aggressive compression.
(a) Write down the GQA forward pass of §2.1 in full notation, including the projection shapes and the group-assignment formula. Verify that recovers MHA and recovers MQA.
(b) Derive of §3.1. Show that at you recover the MHA value , and at you get for large .
(c) For LLaMA-3-70B at with batch , compute the KV cache size in (i) MHA and (ii) GQA- in fp16. Use . Which fits in GB of HBM?
(d) Argue why decode-step FLOPs shrink only modestly with , but decode-step wall-clock latency shrinks substantially. Cite the bandwidth-bound nature of decode from 8.1 §3.
(e) The mean-pool uptraining recipe of §4 takes an MHA checkpoint and produces a GQA checkpoint. Why does mean-pooling specifically (vs e.g. concatenation, sum, random subset) preserve quality?
(f) State, in two sentences each, the difference between GQA and MLA as KV-cache shrinkers. (You may peek ahead at §8.5's session goal; we will derive MLA in detail there.)
References
- [1]
Ainslie, J., Lee-Thorp, J., de Jong, M., et al. (2023). "GQA: Training generalized multi-query transformer models from multi-head checkpoints". arXiv:2305.13245 — Grouped-query attention; the modern default in LLaMA-2-70B, LLaMA-3, Mistral, Qwen (6.14 §5.1; full treatment Cap 8.3).
↩ - [2]
Shazeer, N. (2019). "Fast transformer decoding: One write-head is all you need" (MQA). arXiv:1911.02150 — Multi-query attention (8.3).
↩