Inference Engineering

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 nhn_h heads. Each head has its own query, key and value projections of size dhd_h, 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

cache per token per layer=2⋅nkv⋅dh numbers,\text{cache per token per layer} = 2 \cdot n_{kv} \cdot d_h \ \text{numbers},

where the 2 counts K and V, and nkvn_{kv} is the number of key/value heads. In MHA, nkv=nhn_{kv} = n_h. 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 nhn_h: 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 gg groups. Each group shares one K head and one V head, so nkv=gn_{kv} = g. With one group, GQA is MQA. With nhn_h 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:

ModelInference time per sampleAverage quality score
MHA1.51 s47.2
MQA0.24 s46.6
GQA, 8 groups0.28 s47.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 cKVc^{KV} of size dcd_c, 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 dhRd_h^R 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

dc+dhR=512+64=576 numbers.d_c + d_h^R = 512 + 64 = 576 \ \text{numbers}.

DeepSeek-V2 and DeepSeek-V3 both use dc=512d_c = 512 and dhR=64d_h^R = 64, with 128 heads of dimension 128. In GQA terms, with heads of dimension 128, that cache is the size of

5762×128=2.25 groups,\frac{576}{2 \times 128} = 2.25 \ \text{groups},

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, 2⋅nkv⋅dh2 \cdot n_{kv} \cdot d_h, overestimates the cache many times over. The config has no head_dim, so the result depends on what the tool assumes: with dhd_h = 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 (dcd_c) and qk_rope_head_dim (dhRd_h^R) 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 WW tokens, so nothing older than WW ever needs to stay in the cache.

Mistral 7B v0.1 uses W=4096W = 4096. The paper describes a rolling buffer cache of fixed size WW: the keys and values of token ii go in slot i mod Wi \bmod W, 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 WW tokens back into the layer below it, so after kk layers a token can draw on information from up to W×kW \times k 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:

ModelAttentionCache per tokenOne 32K sequence32K sequences in 80 GB
Llama 3.1 8B as MHA*MHA, 32 K/V heads524 KB17.2 GB4
Llama 3.1 70BGQA, 8 K/V heads328 KB10.7 GB7
Llama 3.1 8BGQA, 8 K/V heads131 KB4.29 GB18
Mistral 7B v0.1GQA, window 4,096131 KB537 MB149
DeepSeek-V3MLA70.3 KB2.30 GB34
Qwen2.5 7BGQA, 4 K/V heads57.3 KB1.88 GB42

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

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 × nhn_h × dhd_h FLOPs against 2 × nkvn_{kv} × dhd_h × 2 bytes, so intensity in BF16 is nh/nkvn_h / n_{kv}. 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:

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.

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.

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.

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

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?

FLOPs per byte
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

  1. 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)
  2. 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)
  3. 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)
  4. 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
  5. Jiang, Sablayrolles, Mensch, Bamford et al. (2023). Mistral 7B. arXiv:2310.06825. Sliding-window attention with W = 4096 and a rolling buffer cache
  6. DeepSeek-V3 config.json (Hugging Face). kv_lora_rank 512, qk_rope_head_dim 64, num_hidden_layers 61
  7. DeepSeek-V2 config.json (Hugging Face). kv_lora_rank 512, qk_rope_head_dim 64, num_hidden_layers 60
  8. 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

Back to lesson 5: Shrinking the cache: MQA, GQA, MLA