What is the KV cache in autoregressive transformer decoding? How does it change the cost of generating each token, and how much memory does it need for a 32-layer model with , a context of 4096 tokens, and fp16 values?
Sequence models and transformers, Inference
Level L3 Intermediate. Length Medium. Nature Th+Mat Both.
What's being asked
Whether you understand what is recomputed during decoding, can do the memory arithmetic, and know why decoding becomes memory-bound (limited by memory speed rather than compute).
Key idea
In a causal model the keys and values of past tokens never change, so they are stored and reused. Each new token computes only its own query, key and value, . For layers, context length and model width , memory per sequence.
Steps
- Why caching is exact: with a causal mask, and for do not depend on later tokens. Recomputing them at every step is wasted work.
- Per-token cost at step , per layer: without a cache you rerun the whole prefix, . With a cache it is for the new projections plus to attend over cached keys.
- Over generated tokens: with the cache, against without.
- Memory: per sequence. A batch of 16 needs 32 GiB, often more than the weights.
- Consequences and fixes: decoding reads the whole cache at every step, so it is memory-bandwidth-bound. Multi-query and grouped-query attention share across heads, which shrinks the cache by for heads and key–value groups. Cache quantisation, paged allocation and sliding-window attention cut memory further.
Common mistakes
- Caching queries. Past queries are never needed again.
- Forgetting the factor 2 (keys and values) or the number of layers.
- Thinking the cache approximates the model. It gives identical outputs.
How long your answer should be
About 3 minutes; one memory calculation.
Last checked on 4 December 2026.
Read this
- Dive into Deep Learning: The KV Cache and Cache Reduction: Section 11.3.1 (cached forward pass, exact equivalence, quadratic-to-linear speed-up), 11.3.2 'Memory Capacity and the Hardware Roofline' (cache size formula over layers, heads, length, bytes) and 11.3.3 (GQA, sliding windows).
- Transformer Inference Arithmetic (kipply): 'kv cache' and 'capacity' sections: 2 * 2 * n_layers * n_heads * d_head bytes per token in fp16 (k and v, 2 bytes each), a worked capacity budget against weight memory, and why small-batch decoding is memory-bandwidth-bound.
Previous in Sequence models and transformers: In an RNN encoder–decoder for translation, what is the bottleneck problem, and how does attention fix it? What are the equations for the context vector at decoder step , and what is the context vector for scores over three encoder states with (scalar) values ?
Next in Sequence models and transformers: Skip-gram with negative sampling uses the loss , where is the centre-word vector, the true context vector and the vectors of sampled negative words. Derive . Then, for , and one negative , what are the gradient and the result of one SGD step with learning rate ?