Grouped-Query Attention
Generation repeatedly reads stored attention history. GQA reduces how much history each layer keeps. Distinct queries share grouped keys and values, making correct head assignment and compact cache storage essential.
#Section 17Decoding Is a Memory-Reading Contest
Chapter 1, Section 62, drew the line between prefill and decode. Prefill processes the whole prompt at once and is limited by arithmetic. Decode generates one token per step and is limited by memory: every step must read every weight of the model, plus the entire KV cache, from the GPU’s main memory, to do a small amount of arithmetic for a single token.
At long contexts, retained keys and values can rival model weights in storage. Reading that history on every decode step becomes a bottleneck.
So during long-context generation, most of the time per token is spent reading keys and values. Shrinking the cache makes generation faster, not just cheaper in memory. The cache size is proportional to the number of key/value heads, . Grouped-query attention reduces exactly that number.
#Section 18The Spectrum: MHA, GQA, MQA
In multi-head attention, MHA, every query head has its own key head and value head: Finch-19 has 8 of each. At the other extreme, multi-query attention, MQA, proposed by Noam Shazeer in 2019 in Fast Transformer Decoding: One Write-Head is All You Need, keeps all 8 query heads but gives them a single shared key head and value head. The cache shrinks by a factor of 8, but quality drops noticeably, and training can be less stable, because one key/value head has to serve every kind of question.
Grouped-query attention, GQA, introduced by Joshua Ainslie and colleagues at Google in 2023, sits in between. The query heads are split into groups, and each group shares one key/value head. Finch-24 has 8 query heads in 2 groups of 4, so 2 key/value heads. Llama 3 8B has 32 query heads in 8 groups of 4. Mistral 7B uses the same 32 and 8; Qwen 2.5 7B uses 28 query heads and 4 key/value heads, groups of 7.
Query heads in the same group still ask different questions, because each has its own slice of and so its own query vector. They just look the answers up in the same keys and read the same values. In effect, GQA says: the questions need diversity, but the index and the contents can be shared across a few questions without much loss.
| MHA | GQA | MQA | |
|---|---|---|---|
| Key/value heads | (groups of ) | 1 | |
| Finch K and V projections | each | each | each |
| Cache per token, Finch | 16,384 bytes | 4,096 bytes | 2,048 bytes |
| Quality | best | close to MHA | noticeably lower |
| Used by | GPT-2, Llama 1, Finch-19 | Llama 2 70B, Llama 3, Mistral, Qwen, Finch-24 | PaLM, Falcon 7B |
#Section 19Making the Shapes Line Up
Attention code written for MHA expects as many key and value heads as query heads. With GQA, the projections produce fewer: Finch-24's and come out as while is . The simplest fix, before attention runs, is to copy each key/value head so there is one copy per query head in its group:
Key/value head 0 is copied into slots 0 to 3 and key/value head 1 into slots 4 to 7. The shapes now match for attention. Query head ends up reading key/value head , where is the group size: heads 0, 1, 2 and 3 read key/value head 0, heads 4 to 7 read key/value head 1.
The silent bug
The order of copies matters, and there are two PyTorch functions that both produce the right shape. repeat_interleave(4, dim=1) repeats each head in place, giving the order 0, 0, 0, 0, 1, 1, 1, 1, which is correct. .repeat(1, 4, 1, 1) tiles the whole block, giving 0, 1, 0, 1, 0, 1, 0, 1. The shapes are identical, nothing crashes, and half the query heads are now paired with the wrong keys and values. The model loads and runs and gives worse answers with no error anywhere.
def repeat_kv(x, n_rep): # x: (B, H_kv, T, d)
B, H_kv, T, d = x.shape
if n_rep == 1:
return x
x = x[:, :, None, :, :].expand(B, H_kv, n_rep, T, d) # no copy yet
return x.reshape(B, H_kv * n_rep, T, d) # 0,0,0,0,1,1,1,1That helper, close to the one in Hugging Face's Llama code, does the same as repeat_interleave using expand, which creates a view without copying, followed by a reshape. Modern attention kernels can skip even that: PyTorch's scaled_dot_product_attention with enable_gqa=True (since PyTorch 2.5) and FlashAttention both accept fewer key/value heads directly and handle the sharing inside, with no copy at all.
#Section 20What It Saves
The cache
Fewer KV heads reduce the history retained per position. This can make longer contexts or more concurrent sequences fit.
The speed
When weights dominate reads, reducing the cache helps little. As history grows, shared KV heads remove a larger share of memory traffic. Measure latency instead of converting a storage ratio directly into a speed claim.
The quality
The GQA paper measured the trade-off on T5 models. With 8 key/value heads, GQA came close to the quality of full MHA while running nearly as fast as MQA. That combination, most of the speed for very little quality loss, is why it became the standard.
Converting an MHA checkpoint
GQA can reuse an MHA checkpoint. The GQA paper's recipe, called uptraining, converts an existing MHA model: split the key heads into groups and replace each group by the mean of its heads, do the same for the value heads, then continue training for a short while, about 5% of the original pretraining compute in the paper, so the model adapts to the shared heads. The query heads and everything else stay as they were.
#Section 21Sharp Edges of GQA
must divide by . Every group has to be the same size, so the number of query heads must be a multiple of the number of key/value heads. 32 and 8 works; 32 and 6 does not.
.repeat versus repeat_interleave. Covered above, and worth repeating: correct shapes, wrong pairing, no error. Test it once by checking that query head 0 and query head 3 receive identical keys and query head 4 receives different ones.
Caching the repeated tensor. If you expand the key/value heads first and then store the expanded tensor in the cache, you have thrown away the entire memory saving. Cache the small version and expand on the fly, or let the kernel handle it.
More GPUs than key/value heads. Large models split heads across GPUs (tensor parallelism). With 8 GPUs and only 4 key/value heads, some key/value heads must be duplicated onto more than one GPU. Serving frameworks handle this, but it affects memory planning.
Kernels can skip the copy. When the attention kernel supports grouped heads natively, passing already-expanded keys and values wastes memory bandwidth for nothing. Pass -shaped tensors with enable_gqa=True or to FlashAttention directly.