A decoder has 32 layers, 32 query heads of dimension 128 (dmodel=4096) and stores keys and values in 16-bit floats (2 bytes). How large is the KV cache for one sequence of 4096 tokens with multi-head attention (MHA), grouped-query attention with 8 KV heads (GQA), and multi-query attention (MQA, one KV head)? How many parameters does GQA save in the K and V projections?

Sequence models and transformers, Inference
Level L3 Intermediate. Length Medium. Nature Mat Mathematical.

What's being asked

Whether you can count the cache entries per token and see how sharing key and value heads reduces memory and parameters.

Key idea

KV cache bytes =2 (K and V)×L×n×hkv×dh×bytes, so the cache is proportional to the number of KV heads hkv.

Steps

  1. MHA has hkv=32. Per token per layer, K and V together store 2×32×128=8192 numbers.
  2. MHA cache: 2×32×4096×32×128×2 bytes =231 bytes =2 GiB.
  3. GQA with hkv=8: each KV head is shared by 4 query heads. Cache =2 GiB×8/32=0.5 GiB.
  4. MQA with hkv=1: cache =2 GiB/32=64 MiB.
  5. Parameters: in MHA, WK and WV are each 4096×4096, so 2×16,777,216=33,554,432 per layer. In GQA they are 4096×(8×128)=4096×1024, so 2×4,194,304=8,388,608 per layer.
  6. Saving per layer: 25,165,824. Over 32 layers: 805,306,368, about 0.8 billion parameters.
  7. Smaller cache means less memory traffic per generated token (decoding is memory-bound) and a larger batch size at the same GPU memory. The quality loss from GQA is small; MQA loses a little more.

Common mistakes

How long your answer should be

Half a page of arithmetic; 4–5 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: Let a=softmax(s) be attention weights over scores s. Derive the Jacobian ∂ai/∂sj and the backward rule ∂L/∂s=a⊙(g−(a⊤g)1) where g=∂L/∂a. For a=(0.7,0.2,0.1) and g=(1,0,−1), compute ∂L/∂s, and again for the peaky a=(0.98,0.01,0.01). What does this say about saturated attention?
Next in Sequence models and transformers: Show that the cross-entropy of a model q on text from the true distribution p equals H(p)+KL(p∥q), so perplexity can never go below 2H(p). Why can the perplexities of two models with different tokenisers not be compared directly, and how do you convert to bits per character? For a model with perplexity 20 per token and 4.5 characters per token, what is the bits per character?