What is the KV cache in transformer inference?
hardAnswer
- During autoregressive generation, tokens are produced one at a time.
- For each layer, the K and V projections of all previously generated tokens are cached; only the new token's Q, K, V are computed each step.
- Time per new token drops from to O(n).
- Memory cost: per sequence — often dominates GPU memory in long-context serving.
- Techniques: MQA/GQA (share K/V across heads), Paged attention (vLLM), sliding-window caches.
Check yourself — multiple choice
- Cache is only for training
- Cache K, V of prior tokens during autoregressive generation → O(n) per new token; memory dominant → MQA/GQA/Paged
- Same as gradient checkpointing
- KV cache removes attention
KV cache: reuse K/V of past tokens → O(n) per step; memory optimizations = MQA/GQA/Paged.
#attention#transformers#efficient-attention
Practise Deep Learning
214 interview questions in this topic.
Related questions
- Why is standard self-attention O(n²) in sequence length?
- How do Performer / Linformer / linear attention reduce O(n²)?
- What is sparse / sliding-window attention?
- How do Longformer / BigBird combine sparse and global attention?
- What is Flash Attention?
- Attention is quadratic in sequence length. Why is FlashAttention still a major win without changing that?