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 dmodel=4096, 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, q,k,v. For L layers, context length n and model width d, memory =2×L×n×d×bytes=2⋅32⋅4096⋅4096⋅2 B=2 GiB per sequence.

Steps

  1. Why caching is exact: with a causal mask, kj=WKxj and vj=WVxj for j<t do not depend on later tokens. Recomputing them at every step is wasted work.
  2. Per-token cost at step t, per layer: without a cache you rerun the whole prefix, O(td2+t2d). With a cache it is O(d2) for the new projections plus O(td) to attend over t cached keys.
  3. Over n generated tokens: O(nd2+n2d) with the cache, against O(n2d2+n3d) without.
  4. Memory: 2 (K,V)×32×4096×4096×2 bytes=231 B=2 GiB per sequence. A batch of 16 needs 32 GiB, often more than the weights.
  5. Consequences and fixes: decoding reads the whole cache at every step, so it is memory-bandwidth-bound. Multi-query and grouped-query attention share K,V across heads, which shrinks the cache by h/g for h heads and g key–value groups. Cache quantisation, paged allocation and sliding-window attention cut memory further.

Common mistakes

How long your answer should be

About 3 minutes; one memory calculation.

Last checked on 4 December 2026.

Read this

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 t, and what is the context vector for scores [2,0,1] over three encoder states with (scalar) values h=[1,2,3]?
Next in Sequence models and transformers: Skip-gram with negative sampling uses the loss J=−log⁡σ(uo⊤vc)−∑k=1Klog⁡σ(−uk⊤vc), where vc is the centre-word vector, uo the true context vector and uk the vectors of K sampled negative words. Derive ∂J/∂vc. Then, for vc=(1,0), uo=(0.5,0.5) and one negative u1=(1,−1), what are the gradient and the result of one SGD step with learning rate 0.1?