AI / ML Theory
Chapter 8 · 24 min

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 128k128k-token context, the KV cache is 6767 GB per sequence in fp16 — larger than the model parameters themselves. The cache is dominated by the count 2⋅L⋅h⋅dh⋅T2 \cdot L \cdot h \cdot d_h \cdot T, and the only freely-tunable factor among those (without changing the model's hidden size d=hdhd = h d_h, the depth LL, or the served context TT) 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 WKW_K and WVW_V. 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 hh query heads, hh key heads, and hh value heads — one of each per head index ℓ∈{1,…,h}\ell \in \{1, \dots, h\}. Multi-query attention (MQA, Shazeer 2019[2], arXiv:1911.02150) shares one K head and one V head across all hh query heads. Grouped-query attention (GQA, Ainslie et al. 2023, arXiv:2305.13245) generalises: partition the hh query heads into gg groups of h/gh/g 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 g∈{1,2,…,h}g \in \{1, 2, \dots, h\}:

| Variant | gg | K, V heads | Comment | |---|---:|---:|---| | MQA | 11 | 11 each | Most aggressive sharing | | GQA-2 | 22 | 22 each | Two K, two V across all query heads | | GQA-gg | gg | gg each | gg K-heads, gg V-heads | | MHA | hh | hh each | No sharing — recover standard MHA |

GQA-hh is MHA; GQA-11 is MQA. So the choice is a single integer gg.

2.1 The forward pass, formally

Fix hidden size dd, query heads hh, group count g∣hg \mid h, per-head dimension dh=d/hd_h = d/h. Define the projection matrices:

WQ∈Rd×d,WK∈Rd×gdh,WV∈Rd×gdh,WO∈Rd×d.W_Q \in \mathbb{R}^{d \times d}, \qquad W_K \in \mathbb{R}^{d \times g d_h}, \qquad W_V \in \mathbb{R}^{d \times g d_h}, \qquad W_O \in \mathbb{R}^{d \times d}.

The WQW_Q matrix has the same shape as in MHA; the WKW_K and WVW_V matrices have width gdhg d_h instead of hdh=dh d_h = d, i.e. they output gg (not hh) K-heads. Given X∈RT×dX \in \mathbb{R}^{T \times d}:

Q=XWQ∈RT×hdh,K=XWK∈RT×gdh,V=XWV∈RT×gdh.Q = X W_Q \in \mathbb{R}^{T \times h d_h}, \quad K = X W_K \in \mathbb{R}^{T \times g d_h}, \quad V = X W_V \in \mathbb{R}^{T \times g d_h}.

Reshape: Q→T×h×dhQ \to T \times h \times d_h, K→T×g×dhK \to T \times g \times d_h, V→T×g×dhV \to T \times g \times d_h. Now per query head ℓ∈{1,…,h}\ell \in \{1, \dots, h\} we need to pick which K, V to use. Group head ℓ\ell to KV group

 group(ℓ)=⌈ℓ⋅gh⌉∈{1,…,g}, \boxed{\ \text{group}(\ell) = \left\lceil \frac{\ell \cdot g}{h} \right\rceil \in \{1, \dots, g\}, \ }

i.e. the first h/gh/g query heads use K, V group 11; the next h/gh/g query heads use group 22; etc. Per query head, apply scaled dot-product attention (6.2) with the shared K and V of its group:

headℓ=Attn ⁣(Q:,ℓ,:, K:,group(ℓ),:, V:,group(ℓ),:)∈RT×dh.\text{head}_\ell = \text{Attn}\!\left( Q_{:, \ell, :}, \ K_{:, \text{group}(\ell), :}, \ V_{:, \text{group}(\ell), :} \right) \in \mathbb{R}^{T \times d_h}.

Concatenate the hh heads, project: GQA(X)=Concat(head1,…,headh)WO∈RT×d\text{GQA}(X) = \text{Concat}(\text{head}_1, \dots, \text{head}_h) W_O \in \mathbb{R}^{T \times d}. 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

#bytesKV=2⋅bpe⋅L⋅h⋅dh⋅T⋅batch,\#\text{bytes}_\text{KV} = 2 \cdot \text{bpe} \cdot L \cdot h \cdot d_h \cdot T \cdot \text{batch},

where bpe\text{bpe} is bytes per element. With GQA-gg, the K, V tensors per layer have only gg (not hh) heads. So

 #bytesKVGQA=2⋅bpe⋅L⋅g⋅dh⋅T⋅batch. \boxed{\ \#\text{bytes}_\text{KV}^\text{GQA} = 2 \cdot \text{bpe} \cdot L \cdot g \cdot d_h \cdot T \cdot \text{batch}. \ }

The cache shrinks by factor h/gh/g. For MQA (g=1g = 1), this is h×h\times — a 32×32\times reduction for h=32h = 32. For GQA-88 in a h=64h = 64 model, this is 8×8\times.

Numerical example. LLaMA-3-70B uses GQA-88 with h=64h = 64, L=80L = 80, d=8192d = 8192, dh=128d_h = 128. At T=32kT = 32k:

KV (MHA)=2⋅2⋅80⋅64⋅128⋅32768=86 GB,\text{KV (MHA)} = 2 \cdot 2 \cdot 80 \cdot 64 \cdot 128 \cdot 32768 = 86 \text{ GB}, KV (GQA-8)=2⋅2⋅80⋅8⋅128⋅32768=11 GB.\text{KV (GQA-8)} = 2 \cdot 2 \cdot 80 \cdot 8 \cdot 128 \cdot 32768 = 11 \text{ GB}.

The MHA version would not fit on an 80 GB H100 even for batch size 1; the GQA-88 version leaves ∼70\sim 70 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 WQ∈Rd×dW_Q \in \mathbb{R}^{d \times d}, WK,WV∈Rd×gdhW_K, W_V \in \mathbb{R}^{d \times g d_h}, WO∈Rd×dW_O \in \mathbb{R}^{d \times d}:

#θGQA=d2+2d⋅gdh+d2=2d2+2d2⋅gh=2d2(1+gh).\#\theta_\text{GQA} = d^2 + 2 d \cdot g d_h + d^2 = 2 d^2 + 2 d^2 \cdot \frac{g}{h} = 2 d^2 \left( 1 + \frac{g}{h} \right).

For g=hg = h (MHA) this is 4d24 d^2 — the value of 6.4 §3. For g=1g = 1 (MQA) it is 2d2+2d2/h≈2d22 d^2 + 2 d^2 / h \approx 2 d^2 — 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 (Q,K,V,Q, K, V, output): 2d2T+2⋅2d2(g/h)T+2d2T≈4d2T(1+g/(2h))2 d^2 T + 2 \cdot 2 d^2 (g/h) T + 2 d^2 T \approx 4 d^2 T (1 + g/(2h)). For MQA this is ≈4d2T\approx 4 d^2 T instead of 8d2T8 d^2 T — half.
  • Score matmul QK⊤/dhQ K^\top / \sqrt{d_h} per head: 2T2dh2 T^2 d_h per head, hh heads =2T2d= 2 T^2 d. Independent of gg.
  • Mix with VV: 2T2d2 T^2 d. Independent of gg.

So the dominant FLOPs (the T2dT^2 d 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 gg. 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 K∈RT×gdhK \in \mathbb{R}^{T \times g d_h} and V∈RT×gdhV \in \mathbb{R}^{T \times g d_h} from HBM, perform a single-query attention of shape 1×T1 \times T, and discard most of the multiplied-out result. The bandwidth cost per layer per step is

#bytes-readstepKV=2⋅bpe⋅g⋅dh⋅T=2⋅bpe⋅d⋅T⋅(g/h).\#\text{bytes-read}^\text{KV}_\text{step} = 2 \cdot \text{bpe} \cdot g \cdot d_h \cdot T = 2 \cdot \text{bpe} \cdot d \cdot T \cdot (g/h).

For MQA, g/h=1/hg/h = 1/h, so decode-step KV bandwidth drops by h×h\times. Combined with the (model-parameter-fixed) bandwidth to read the layer's weights, this gives a clean wall-clock decode speedup that scales with h/gh/g until the parameter-reading bandwidth dominates. For LLaMA-3-70B (h=64,g=8h = 64, g = 8), the empirical decode-step speedup vs the hypothetical MHA-70B is ∼5\sim 5–8×8\times 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:

  1. Take an existing MHA-trained checkpoint with hh K and V heads.
  2. Mean-pool the hh K-heads down to gg K-heads (and same for V): each group's K is the average of the h/gh/g original K's it absorbs.
  3. Continue training for a small fraction (∼5%\sim 5\%) of the original training budget with the GQA mask in place.

Result: with g=8g = 8, post-uptraining quality is within ∼0.1\sim 0.1 perplexity of the original MHA checkpoint on standard benchmarks. With g=1g = 1 (MQA), quality drops a measurable 0.30.3–0.70.7 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 g=8g = 8 still has enough specialisation to recover most of the quality.

This is the empirical sweet spot the field converged on:

| Model | hh | gg | Variant | |---|---:|---:|---| | LLaMA-1, LLaMA-2-7B | 32 | 32 | MHA | | LLaMA-2-34B / 70B | 56 / 64 | 8 | GQA-88 | | LLaMA-3 (all sizes ≥ 8B) | 32 / 64 | 8 | GQA-88 | | Mistral-7B | 32 | 8 | GQA-88 | | Qwen-2 | 32 / 64 | 8 | GQA-88 | | Gemma-2 | 32 / 48 | 8 / 16 | GQA-88 / GQA-1616 | | Falcon-180B | 64 | 1 | MQA | | PaLM (early) | — | 1 | MQA |

GQA-88 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 hh, even g=1g = 1 has enough effective capacity, but the g=8g = 8 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-88; 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 ∼5%\sim 5\% 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 gg 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 g=8g = 8 cannot be served with g=64g = 64 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 QQ-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-88 + 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:

  1. GQA-gg is parameterised by one integer. Replace hh K-heads and hh V-heads with gg K-heads and gg V-heads; tie groups of h/gh/g query heads to each KV group. Default g=8g = 8.

  2. The shrink is exactly h/gh/g in KV cache and decode-step KV bandwidth. That is the operational reason it became the 2024+ default.

  3. Quality cost is small (≲0.1\lesssim 0.1 perplexity) at g=8g = 8 for dense models in the 77B–7070B range, after either from-scratch training or ∼5%\sim 5\%-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.

Self-test

(a) Write down the GQA forward pass of §2.1 in full notation, including the projection shapes and the group-assignment formula. Verify that g=hg = h recovers MHA and g=1g = 1 recovers MQA.

(b) Derive #θGQA=2d2(1+g/h)\#\theta_\text{GQA} = 2 d^2 (1 + g/h) of §3.1. Show that at g=hg = h you recover the MHA value 4d24 d^2, and at g=1g = 1 you get ≈2d2\approx 2 d^2 for large hh.

(c) For LLaMA-3-70B at T=128kT = 128k with batch 44, compute the KV cache size in (i) MHA and (ii) GQA-88 in fp16. Use h=64,L=80,dh=128h = 64, L = 80, d_h = 128. Which fits in 640640 GB of HBM?

(d) Argue why decode-step FLOPs shrink only modestly with gg, 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. [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. [2]

    Shazeer, N. (2019). "Fast transformer decoding: One write-head is all you need" (MQA). arXiv:1911.02150 — Multi-query attention (8.3).

    ↩