Linear algebra for LLMsPart 5: Attention, one operation at a time
GQA and the KV cache
7 min
Generating one token at a time
To generate token , the model needs the new token’s query against the keys of all earlier tokens, and their values. Those earlier keys and values never change (the mask means old tokens never see new ones), so instead of recomputing them every step, the model stores them: the KV cache.
Write
Its size
2 for keys and values, times the layers , times the key/value heads , times the head width, times bytes per number. Multiply by the number of tokens (and by the batch size) for the total.
Write
With one K/V per query head
A Llama 2 7B-shaped model uses standard multi-head attention: every query head has its own keys and values. Half a megabyte per token: 4,096 tokens take 2 GiB, for one sequence.
Grouped-query attention
GQA lets groups of query heads share one key/value head. Llama 3 8B has 32 query heads and 8 KV heads: each KV head serves 4 query heads. The cache shrinks 4×, and , shrink from to .
Write
MHA, GQA, MQA
| Variant | KV heads | Cache vs MHA |
|---|---|---|
| multi-head (MHA) | 1× | |
| grouped-query (GQA) | ||
| multi-query (MQA) | 1 |
Fewer KV heads means less memory and less data to read per generated token; the queries keep their full count.
✏️ Your turn
Size a cache
How big is the cache for one sequence? (FP8 is 1 byte per number.)
Work it out on paper, then go to the next card to check.
Answer: 2 GiB
Why it matters
In a transformer
During generation, every step reads the whole cache (and all the weights) from memory to do a little math with it. Long contexts and big batches make the cache the largest thing in memory after the weights, which is why serving systems page it, compress it, and quantize it.
📌 Recap
GQA and the KV cache in one card
- Generation caches past keys and values instead of recomputing them.
- Per token: .
- MHA: . GQA: groups share K/V. MQA: one K/V head.
- Llama 3 8B in BF16: 128 KiB per token.
Write