Lesson 5: Shrinking the cache: MQA, GQA, MLA · Workbook
Shrinking the cache: MQA, GQA, MLA: the workbook
The full working behind lesson 5: where the cache size comes from, how MQA, GQA, MLA and sliding windows each shrink it, what the papers report each one costs, real models compared, and seven exercises to check yourself.
Every generated token reads the whole KV cache: the stored keys and values of every earlier token, kept so they are not recomputed at each step. (The KV cache lesson covers how it works.) For Llama 3.1 8B in BF16 that cache is 131 KB per token, so a single 32,768-token conversation holds 4.29 GB of it, and an 80 GB H100 has room for only 18 such conversations even before the weights are loaded.
A note on units: as everywhere in this course, sizes are decimal (1 KB is 1,000 bytes, 1 GB is 109 bytes), so 131,072 bytes × 32,768 = 4.29 GB, and the H100’s memory is 80 × 109 bytes.
There are three ways to make the cache smaller without making the model smaller. Store fewer key and value heads (MQA and GQA). Store a compressed version of them and expand it on the fly (MLA). Or store fewer tokens (sliding-window attention). Every model in this lesson uses at least one of these. This lesson works out what each saves, using real configs, and what the papers report each one costs in quality.
Where the cache size comes from
In standard multi-head attention (MHA), each layer splits its work into heads. Each head has its own query, key and value projections of size , the head dimension. When a token passes through a layer, its key and value vectors for every head are written to the cache, so that later tokens can attend to it. Per token, per layer, that is
where the 2 counts K and V, and is the number of key/value heads. In MHA, . Multiply by the number of layers and the bytes per number to get bytes per token.
Llama 3.1 8B has 32 query heads of dimension 128 and 32 layers. If it used MHA, it would store 8,192 numbers per token per layer, or 524 KB per token in BF16. A 32,768-token conversation would need 17.2 GB, and only 4 of them would fit in an H100’s memory. The real model stores a quarter of that, because it uses grouped-query attention.
Notice what is in the formula and what is not. The cache does not depend on the hidden size or the MLP width. It depends only on how many K/V heads each layer keeps, how wide they are and how many layers there are. That is why it can be cut without shrinking the rest of the model.
Multi-query attention: one shared K/V head
Shazeer (2019) asked whether every query head needs its own keys and values. In multi-query attention (MQA), all query heads keep their own query projections but share a single key head and a single value head. The cache shrinks by a factor of : for a Llama 3.1 8B shape, from 8,192 to 256 numbers per layer.
The motivation was decode speed, not memory capacity. As the roofline lesson showed, each decode step must read the whole cache, so a smaller cache is a faster step. On a translation model running on a TPUv2, the paper reports that the decoder’s time per token fell from 46 µs with MHA to 3.8 µs with MQA. Quality dropped slightly: dev-set BLEU (a translation-quality score) on WMT14 English-German went from 26.7 to 26.5. The paper also tried the obvious alternative, fewer heads or narrower heads, and found it lost more quality than MQA did.
The GQA paper adds that MQA can make fine-tuning unstable. A small quality drop plus that instability left room for a middle ground.
Grouped-query attention: the middle ground
Grouped-query attention (GQA), from Ainslie et al. (2023), divides the query heads into groups. Each group shares one K head and one V head, so . With one group, GQA is MQA. With groups, it is MHA. Everything between trades cache size against quality.
The paper’s results on T5-XXL (an 11B-parameter encoder-decoder model), after converting an MHA checkpoint and continuing training for 5% of the original pre-training compute (which they call uptraining), make the case:
| Model | Inference time per sample | Average quality score |
|---|---|---|
| MHA | 1.51 s | 47.2 |
| MQA | 0.24 s | 46.6 |
| GQA, 8 groups | 0.28 s | 47.1 |
Numbers quoted from Table 1 of the GQA paper. Quality is the average over its summarization, translation and question-answering tasks.
GQA with 8 groups kept almost all of MHA’s quality at close to MQA’s speed. Every model in this lesson except DeepSeek’s uses it. Llama 3.1 8B keeps 8 K/V heads for 32 query heads, Llama 3.1 70B keeps 8 for 64, and Qwen2.5 7B keeps 4 for 28. Mistral 7B keeps 8 for 32.
The lesson page has a slider that steps through every group count for Llama 3.1 8B’s shape, from MHA to MQA.
Multi-head latent attention: compress instead of share
GQA and MQA save memory by making heads share. DeepSeek-V2 (2024) took a different path. Multi-head latent attention (MLA) keeps a full set of 128 key and value heads but never stores them. Each layer projects the token’s hidden state down to a small latent vector of size , and caches only that. When attention needs keys and values, it projects the latent back up.
That alone would cost extra compute at every step, but the paper points out that the up-projection for keys can be folded into the query projection, and the one for values into the output projection. With that rearrangement, attention works directly on the cached latents and never builds full keys and values.
One complication is position. All the models in this lesson encode token position with rotary position embeddings (RoPE), which rotate queries and keys by an amount that depends on their position. The paper explains that RoPE is incompatible with the folding trick: the rotation sits between the two projections that need to merge. Their fix is to keep a separate, small key of size that carries the rotary position information. It is one key shared by all heads, and it is cached next to the latent.
So per token, per layer, MLA caches
DeepSeek-V2 and DeepSeek-V3 both use and , with 128 heads of dimension 128. In GQA terms, with heads of dimension 128, that cache is the size of
which is how the DeepSeek-V2 paper describes it: the cache of GQA with only 2.25 groups. Against a hypothetical MHA with the same 128 heads of dimension 128 (32,768 numbers per layer), it is 57 times smaller. The paper’s own matched MHA baseline (Appendix D.2) was narrower, and there MLA’s cache was about 4% of MHA’s, roughly 25 times smaller.
DeepSeek-V3 has 61 layers, so its cache is 35,136 numbers per token, or 70.3 KB in BF16. That is about half of Llama 3.1 8B’s 131 KB, for a model the V3 report describes as having 671B total parameters. DeepSeek-V3 is a mixture-of-experts (MoE) model: it uses only a fraction of its weights for each token, so its total parameter count overstates the work per token. Its cache, though, is set by attention alone.
One practical trap: DeepSeek-V3’s config.json lists num_key_value_heads as 128. A tool that plugs that into the standard formula, , overestimates the cache many times over. The config has no head_dim, so the result depends on what the tool assumes: with = hidden_size / num_attention_heads = 56 it reports 14,336 numbers per layer, 25 times too many. An engine that expands MLA into plain MHA stores 128 × (128 + 64 + 128) = 40,960, 71 times too many. For MLA models, read kv_lora_rank () and qk_rope_head_dim () instead.
What MLA costs in quality
The DeepSeek-V2 paper reports that MLA did better than MHA, not worse. In Appendix D.2 they trained matched pairs of MoE models that differed only in attention. On a model of about 250B total parameters, MLA scored higher on all four benchmarks they report (for example MMLU 59.0 against 57.5; MMLU and C-Eval are multiple-choice knowledge benchmarks in English and Chinese) while its cache was 34.6K numbers per token against 860.2K. That 34.6K is for the ablation model, not the released DeepSeek-V2, but it equals 576 × 60 = 34,560, the same per-layer cache over DeepSeek-V2’s 60 layers. On the smaller pair (about 16B total) MLA was ahead on three of four benchmarks and behind on C-Eval, 50.9 against 51.6.
These are results from one lab, on its own architecture and data. Treat them as evidence that compressing the cache need not cost quality, not as a guarantee that MLA beats MHA everywhere.
Sliding windows cap the length
The three methods above shrink each token’s entry. Sliding-window attention (SWA) caps the number of entries instead. Each token attends only to the previous tokens, so nothing older than ever needs to stay in the cache.
Mistral 7B v0.1 uses . The paper describes a rolling buffer cache of fixed size : the keys and values of token go in slot , overwriting the token that just left the window. Its per-token entry is the same 131 KB as Llama 3.1 8B’s, since it also has 8 K/V heads of dimension 128 and 32 layers. But a 32,768-token sequence holds only 4,096 tokens, 537 MB instead of 4.29 GB, a factor of 8. The paper reports that same 8x saving at 32K tokens, and says it came “without impacting the model quality.”
Information from further back is not entirely lost. Each layer can see tokens back into the layer below it, so after layers a token can draw on information from up to tokens earlier. For Mistral 7B that is 131,072 tokens, the roughly 131K the paper cites. But that information arrives indirectly, through other tokens’ hidden states, so it is weaker than direct attention. The window also does nothing for short conversations: below 4,096 tokens, the cache is exactly as large as without it.
Comparing real models
Here is what the formulas give for each model at a 32,768-token context, with a BF16 cache, counting only the cache against an H100’s 80 GB:
| Model | Attention | Cache per token | One 32K sequence | 32K sequences in 80 GB |
|---|---|---|---|---|
| Llama 3.1 8B as MHA* | MHA, 32 K/V heads | 524 KB | 17.2 GB | 4 |
| Llama 3.1 70B | GQA, 8 K/V heads | 328 KB | 10.7 GB | 7 |
| Llama 3.1 8B | GQA, 8 K/V heads | 131 KB | 4.29 GB | 18 |
| Mistral 7B v0.1 | GQA, window 4,096 | 131 KB | 537 MB | 149 |
| DeepSeek-V3 | MLA | 70.3 KB | 2.30 GB | 34 |
| Qwen2.5 7B | GQA, 4 K/V heads | 57.3 KB | 1.88 GB | 42 |
* Hypothetical. The last column ignores the weights, as if they lived on other GPUs, so models of different sizes can be compared on cache alone. DeepSeek-V3’s weights need many GPUs in any case. On a single H100 that also holds Llama 3.1 8B’s 16.1 GB of BF16 weights, with 10% held back as in lesson 4, the count for Llama 3.1 8B drops from 18 to 13.
The lesson page draws this table as bars, with a choice of context length (to see the sliding window take effect) and of cache precision (FP8 halves every per-token size and roughly doubles the counts).
A few things stand out.
- GQA is the baseline now. The hypothetical MHA version of Llama 3.1 8B fits 4 sequences; the real one fits 18. That factor of 4 comes entirely from sharing K/V heads.
- Cache size tracks attention design, not parameter count. DeepSeek-V3 is the largest model here by far and has one of the smallest caches per token. Qwen2.5 7B, with only 4 K/V heads and 28 layers, is smaller still.
- The window wins at long context, and only there. At 32,768 tokens Mistral 7B fits 149 sequences against Llama 3.1 8B’s 18, from identical per-token entries. At 4K tokens the two are equal.
What a smaller cache buys
A smaller cache pays off in three ways, and the later lessons on continuous batching and paged memory build on all of them.
More concurrent sequences. Memory not spent on cache can hold more users’ caches. Since decode throughput grows with batch size (lesson 1), this is often the biggest gain.
Faster decode steps at long context. Each step reads every cached byte. Halving the cache halves that part of the step.
Attention stops being purely memory-bound. The quantity to watch is FLOPs per byte of cache read during decode. For one new token and one cached token in one layer, each query head does a dot product with the key and a weighted sum with the value. Counting 2 FLOPs per multiply-add, as in the roofline lesson, that is 2 × 2 × × FLOPs against 2 × × × 2 bytes, so intensity in BF16 is . With MHA, every head reads its own K and V, so intensity is low: 1 FLOP per byte. GQA reuses each K/V head across its group, so Llama 3.1 8B gets 4. With MLA and the projections folded in, all 128 heads work on the same 576 cached numbers. Each head scores against all 576 but sums only the 512-number latent, because the RoPE key is a key and carries no value. That is 2 × 128 × (576 + 512) = 278,528 FLOPs against 576 × 2 = 1,152 bytes, about 242 FLOPs per byte. That is close to the H100’s ridge point of 295 from the roofline lesson. MLA’s attention at decode can be limited by compute as well as bandwidth, which no MHA or GQA model in this lesson comes close to: for them, intensity in BF16 is about the number of query heads per K/V head.
And the costs, as the papers report them:
- MQA loses a little quality (Shazeer: 26.7 to 26.5 BLEU) and, per the GQA paper, can make fine-tuning unstable.
- GQA with 8 groups is close to MHA in the GQA paper’s uptraining experiments. But in DeepSeek-V2’s Appendix D.1, where 7B dense models were trained from scratch on 1.33T tokens, MHA scored clearly higher than both GQA with 8 groups and MQA (MMLU 45.2, 41.2 and 37.9). Different setups give different answers; there is no single quality cost for GQA.
- MLA adds projection work and a more complex kernel, and its quality claims come mainly from its authors.
- A sliding window changes what the model can attend to directly. It is an architecture decision made at training time, not a serving setting.
None of these can be applied to a trained model as a switch. GQA’s uptraining is the cheapest path, and even that is extra training.
Check yourself
Work each one out before opening the answer. Every number comes from the same formulas as the figures.
Exercise 1. Llama 3.1 70B has 64 query heads and 8 K/V heads of dimension 128, over 80 layers. How many query heads share each K/V head, and how large would its BF16 cache per token be with MHA? Enter the MHA cache size per token in KB.
Show the worked answer
8 query heads per K/V head. With MHA it would keep 64 K/V heads, 8 times as many, so the cache would grow from 328 KB to 2.62 MB per token. A single 32K-token sequence would need 2,621,440 bytes × 32,768 = 85.9 GB, more than the H100’s 80 GB (80 × 109 bytes).
Exercise 2. DeepSeek-V3 caches a 512-number latent and a 64-number RoPE key per token per layer, over 61 layers. How large is the BF16 cache for one 128K-token (131,072-token) conversation? Compare Llama 3.1 70B at the same length. Enter the DeepSeek-V3 figure in GB.
Show the worked answer
576 × 61 × 2 bytes = 70,272 bytes per token, so 9.21 GB for the conversation. Llama 3.1 70B needs 42.9 GB, about 5 times more, even though it is the much smaller model.
Exercise 3. Mistral 7B v0.1 and Llama 3.1 8B store the same 131 KB per token. At what context length do their per-sequence caches start to differ, and by what factor do they differ at 32K tokens?
Show the answer
They are identical up to the window, 4,096 tokens. After that Mistral’s cache stays fixed while Llama’s keeps growing. At 32,768 tokens the ratio is 4.29 GB / 537 MB = 8×, the 8x the Mistral paper reports.
Exercise 4. One H100 (80 GB, with 10% held back as in lesson 4) serves Llama 3.1 8B with BF16 weights and a BF16 cache. How many 32K-token conversations can it hold at once? How many if the model used MHA? Enter the first figure, for Llama 3.1 8B as built.
Show the worked answer
The weights take 16.1 GB and the reserve 8.00 GB, leaving 55.9 GB for the cache. At 4.29 GB per conversation that is 13 conversations. With MHA each conversation needs 17.2 GB, so only 3 fit. (Activations come out of the same space, so the true numbers are a little lower.)
Exercise 5. During decode, roughly how many FLOPs does attention do per byte of cache it reads, for Llama 3.1 8B (GQA, BF16) and for DeepSeek-V3 (MLA with the projections folded in)? Which side of the H100's ridge point is each on?
Show the answer
Llama 3.1 8B: each cached K/V head serves 4 query heads, giving 4 FLOPs per byte, far below the ridge of 295, so firmly memory-bound. DeepSeek-V3: all 128 heads score against the same 576 cached numbers and sum the 512-number latent, so 2 × 128 × (576 + 512) FLOPs over 576 × 2 bytes, giving about 242 FLOPs per byte, just below the ridge. A smaller cache does more than save memory: it changes which resource limits attention.
Exercise 6. From lesson 4: Llama 3.1 8B stores 131 KB of KV cache per token in BF16. How much cache does one conversation at its full 131,072-token context need? Enter GB.
Show the worked answer
17.2 GB: 131,072 bytes × 131,072 tokens = 17,179,869,184 bytes. With every query head keeping its own K and V it would be 68.7 GB, and DeepSeek-V3’s latent cache needs 9.21 GB at the same length.
Exercise 7. From lesson 1: an H100 does about 989.4 trillion BF16 FLOPs per second and reads 3.35 TB per second from memory. How many FLOPs must a kernel do per byte it reads before arithmetic, not memory, sets its speed?
Show the worked answer
About 295 FLOPs per byte, the ridge point: (989.4 × 1012) / (3.35 × 1012). Anything below it, such as decode reading the KV cache in Exercise 5, waits on memory, not arithmetic.
Sources
- Shazeer (2019). Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150. Multi-query attention. Table 1 (WMT14 EN-DE quality) and Table 2 (TPUv2 time per token)
- Ainslie, Lee-Thorp, de Jong, Zemlyanskiy, Lebrón, Sanghai (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP 2023. Grouped-query attention and uptraining. arXiv:2305.13245. Table 1 (T5-XXL quality and inference time)
- DeepSeek-AI (2024). DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model. arXiv:2405.04434. Multi-head latent attention. Section 2.1 and Table 1 (KV cache per token), Appendix D (MHA, GQA, MQA and MLA ablations)
- DeepSeek-AI (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437. Section 4.2: 61 layers, d_c = 512, d_h^R = 64, 128 heads of dimension 128
- Jiang, Sablayrolles, Mensch, Bamford et al. (2023). Mistral 7B. arXiv:2310.06825. Sliding-window attention with W = 4096 and a rolling buffer cache
- DeepSeek-V3 config.json (Hugging Face). kv_lora_rank 512, qk_rope_head_dim 64, num_hidden_layers 61
- DeepSeek-V2 config.json (Hugging Face). kv_lora_rank 512, qk_rope_head_dim 64, num_hidden_layers 60
- Llama 3.1 8B, Llama 3.1 70B, Mistral 7B v0.1 and Qwen2.5 7B config.json files. Linked from src/lib/models.ts; the Llama files are gated behind Meta's license