Highlights

Contents

Part IV
04

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.

YOU ARE HEREMODERN DECODER BLOCKATTENTION HALFRMSNormq, k, v projRoPE (q, k)GQA: 8 q, 2 kvSDPAFlash kernelo proj+MLP HALFRMSNormgate, up projSiLU(g) ⊙ udown proj+residual stream: x + Attn(Norm(x)), then h + MLP(Norm(h))what changed since GPT-2: positions, norm, MLP, K/V sharing, the attention kernel, and no biases

#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, HkvH_{kv}. 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.

MHAevery query head has its own K/Vq0q1q2q3q4q5q6q78 K/V headsGQA (Finch-24)groups of 4 share one K/Vq0q1q2q3q4q5q6q72 K/V headsMQAall heads share one K/Vq0q1q2q3q4q5q6q71 K/V headK/V projection size and KV cache are proportional to the number of K/V heads: 8 : 2 : 1
Figure 2.25The sharing spectrum for 8 query heads. MHA gives each query head its own keys and values; GQA lets groups of four share; MQA makes all eight share one. Matching colours show a group.

Query heads in the same group still ask different questions, because each has its own slice of WQW_Q 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 HH H/gH / g (groups of gg) 1
Finch K and V projections 512×512512 \times 512 each 512×128512 \times 128 each 512×64512 \times 64 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 kk and vv come out as (B,2,T,64)(B, 2, T, 64) while qq is (B,8,T,64)(B, 8, T, 64). The simplest fix, before attention runs, is to copy each key/value head so there is one copy per query head in its group:

(B,Hkv,T,dh)→ repeat_interleave(H/Hkv, dim=1) (B,H,T,dh)(B, H_{kv}, T, d_h) \xrightarrow{\ \texttt{repeat\_interleave}(H / H_{kv},\ \texttt{dim}=1)\ } (B, H, T, d_h)

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 ii ends up reading key/value head ⌊i/g⌋\lfloor i / g \rfloor, where g=H/Hkvg = H / H_{kv} is the group size: heads 0, 1, 2 and 3 read key/value head 0, heads 4 to 7 read key/value head 1.

MATCHING SHAPES: EACH K/V HEAD IS REPEATED FOR ITS GROUP OF QUERY HEADSkv 0kv 1(B, 2, T, 64)kv 0→ q0kv 0→ q1kv 0→ q2kv 0→ q3kv 1→ q4kv 1→ q5kv 1→ q6kv 1→ q7(B, 8, T, 64)repeat_interleave(4, dim=1): kv 0 fills slots 0 to 3, kv 1 fills 4 to 7
Figure 2.26Expanding two key/value heads to eight. Each one is repeated four times in a row, so query heads 0 to 3 read the first and 4 to 7 read the second.

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.

WHICH K/V HEAD DOES QUERY HEAD i READ? 8 QUERY HEADS, 2 K/V HEADSq0q1q2q3q4q5q6q7repeat_interleave (i // 4)00001111.repeat (i % 2)01010101same shape, no error, half the heads read the wrong keys
Figure 2.27Which key/value head each query head reads. The correct grouping gives runs of the same head; tiling with .repeat interleaves them, so four of the eight query heads read the wrong one.
python
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,1

That 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.

KV CACHE PER SEQUENCE: 32 LAYERS, HEAD SIZE 128, 16-BITcontext length (tokens)bytesMHA (32): 64 GiBGQA (8): 16 GiBMQA (1): 2 GiB80 GB GPU032,76865,53698,304131,072
Figure 2.28KV cache per sequence against context length for 32, 8 and 1 key/value heads. At 128k tokens the MHA cache alone nearly fills an 80 GB GPU; GQA-8 is a quarter of that.

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.

BYTES READ PER GENERATED TOKEN: WEIGHTS + KV CACHE, LLAMA 3 8B SIZE, ONE SEQUENCE8,192 tokensMHA20.4 GB ≈ 10.2 ms at 2 TB/sGQA17.1 GB ≈ 8.6 ms at 2 TB/s32,768 tokensMHA33.2 GB ≈ 16.6 ms at 2 TB/sGQA20.4 GB ≈ 10.2 ms at 2 TB/s131,072 tokensMHA84.8 GB ≈ 42.4 ms at 2 TB/sGQA33.2 GB ≈ 16.6 ms at 2 TB/sgrey: weights (16.1 GB) coloured: KV cache
Figure 2.29Bytes read from memory for each generated token, weights plus cache, for one sequence. At short contexts the weights dominate and GQA barely matters; at long contexts GQA's smaller cache cuts the total sharply.

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.

THE TRADE-OFF, SKETCHED: SPEED ACROSS, QUALITY UP (ILLUSTRATIVE)decoding speed →qualityMHAGQA-8MQAnearly MHA quality at nearly MQA speed
Figure 2.30The trade-off, sketched. GQA with eight key/value groups keeps nearly all of MHA's quality while getting most of MQA's speed. (Illustrative.)

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.

CONVERTING AN MHA CHECKPOINT TO GQA: AVERAGE EACH GROUP, THEN TRAIN A LITTLE MOREk0k1k2k3k4k5k6k7mean of k0 to k3mean of k4 to k7k′0k′1same for valuesthen "uptrain" with about5% of the original compute
Figure 2.31Uptraining. Each group of key heads is averaged into one new key head (values likewise), then training continues briefly to adapt.

#Section 21Sharp Edges of GQA

HH must divide by HkvH_{kv}. 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 (B,Hkv,T,dh)(B, H_{kv}, T, d_h) version and expand on the fly, or let the kernel handle it.

CACHE THE SHARED HEADS, NOT THEIR COPIESFinch-24, one token in one layer, 16-bit K + Vstore 2 KV headsKV 0KV 1512 bytesreuseQ 0reads KV 0Q 1reads KV 0Q 2reads KV 0Q 3reads KV 0Q 4reads KV 1Q 5reads KV 1Q 6reads KV 1Q 7reads KV 1store 8 expanded heads2,048 bytes = 4×sharing saves memory only if the cache keeps the sharing
Figure 2.32Finch-24 stores two KV heads per token per layer. At 64 numbers per head and two bytes per number, K and V together take 512 bytes. Storing eight expanded heads takes 2,048 bytes and loses the fourfold saving. Across eight layers these become 4,096 and 16,384 bytes per token.

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 HkvH_{kv}-shaped tensors with enable_gqa=True or to FlashAttention directly.