KV Cache Explained
Volume III, Chapter 15 — Part I. Autoregressive inference optimization: prefill vs. decode phases, KV cache memory analysis, MQA/GQA, and complexity reduction from quadratic to linear per generated token.
Prerequisites
Table of Contents
- Learning Objectives
- Prerequisites
- Notation
- Core Intuition
- Autoregressive Generation
- The Redundancy Problem
- KV Cache Mechanism
- Prefill vs. Decode Phases
- Memory Analysis
- Multi-Query and Grouped-Query Attention
- Worked Examples
- Connection to the Broader Curriculum
- Common Pitfalls and Misconceptions
- Research Perspective
- Summary of Takeaways
- Exercises
Learning Objectives
After reading this chapter, you should be able to:
- Describe autoregressive generation as iterative Self-Attention over growing sequences.
- Explain why naive recomputation costs per step .
- Define the KV cache and reduce per-token cost to attention over cached keys/values.
- Compute KV cache memory: .
- Compare MHA, MQA, and GQA cache requirements.
Prerequisites
- Self-Attention — Q/K/V projections
- RoPE — position encoding in cached K
Notation
- — Current decode step and total sequence length
- — Cached key and value tensors
- — Layers, heads, and key dimension
- — Batch size
- — Total KV cache memory
- — Prompt (prefill) length
Core Intuition
LLMs generate text one token at a time. At step , Self-Attention needs all previous keys and values. Without caching, recomputing K/V for tokens at every step wastes work across generation.
The KV cache stores computed for ; each new step computes only the new token's Q, K, V and attends over the cache. This is essential for practical inference latency.
Series context. Volume III, Chapter 15 (Inference).
KV-Cache in Autoregressive Generation
Autoregressive Generation
Definition 1 (Autoregressive Model).
Definition 2 (Generation Step). At step , compute logits from , sample .
Each step runs full Transformer forward pass on sequence of length .
The Redundancy Problem
Proposition 1 (Naive Cost). At decode step , computing for all positions costs per layer. Summing over generation steps yields total attention-related work per layer.
Proof. At step , a full forward pass processes a sequence of length . Key and value projections require operations per layer (with ). Summing:
Observation. Keys and values for positions are identical to their values at step — weights are frozen during inference and prior token representations do not change. Recomputing them at every step is pure redundancy.
KV Cache Mechanism
Definition 3 (KV Cache). Store per layer:
Decode step for new token :
- Compute (single token only)
- Append:
- Attention:
Theorem 1. Per decode step: attention vs. for full recomputation matrix operations at length .
Prefill vs. Decode Phases
Definition 4 (Prefill). Process prompt in parallel — compute and fill entire cache at once. Cost: — one-time.
Definition 5 (Decode). Generate tokens one at a time using cache. Cost per token: where grows.
Proposition 2. Prefill is compute-bound (parallel); decode is memory-bandwidth-bound (sequential, cache-heavy).
Memory Analysis
Definition 6 (KV Cache Memory).
where = batch size, = layers, = heads, = sequence length, factor 2 for K and V.
Example. Llama 70B: , , , , FP16:
Often exceeds weight memory for long contexts.
Multi-Query and Grouped-Query Attention
Definition 7 (MQA). Share single across all heads; only Q is per-head. Cache reduced by factor .
Definition 8 (GQA). KV head groups; each group of query heads shares KV. Interpolates MHA ↔ MQA.
Used in Llama 2/3, PaLM — critical for long-context inference with Flash Attention.
Worked Examples
Example 1: Cache Growth
After 1000 tokens, cache stores 1000 key vectors per head per layer.
Example 2: MQA Savings
64-head MHA → MQA: 64× KV memory reduction.
Connection to the Broader Curriculum
- Self-Attention — mechanism
- RoPE — apply rotation when writing to cache
- Flash Attention — IO-efficient attention
- Quantization — INT8/FP8 KV cache
Common Pitfalls and Misconceptions
Pitfall 1: KV cache memory scales linearly with context — limits long sequences.
Pitfall 2: RoPE position must be correct when reading cached K.
Pitfall 3: Prefill and decode have different bottlenecks.
Pitfall 4: Batch inference multiplies cache by .
Research Perspective
The KV cache is implicit in any efficient autoregressive implementation but was formalized in the context of transformer inference scaling. Multi-Query Attention (Shazeer, 2019) demonstrated that sharing key and value heads across query heads reduces cache bandwidth with minimal quality loss. Grouped-Query Attention (Ainslie et al., 2023) interpolates between MHA and MQA and is now standard in Llama 2/3 and related architectures. PagedAttention (Kwon et al., 2023) applies virtual-memory paging to KV storage, eliminating fragmentation in batched serving. Quantized and compressed KV caches (INT8, FP8) remain active research for extending context length under fixed memory budgets.
Summary of Takeaways
- Cache — Store K, V per layer
- Decode — per step vs. naive
- Memory — (3)
- MQA/GQA — Reduce cache by grouping
Next: RAG
Exercises
Exercise 1. Derive total naive cost over generation steps by summing per-step costs as in equation (2).
Exercise 2. Compute (4) for given model config.
Exercise 3. MQA vs. MHA memory for Llama 7B.
Exercise 4. Prefill vs. decode bottleneck analysis.
Exercise 5. RoPE indexing with cache at position .
Exercise 6. PagedAttention conceptually.
Exercise 7. Batch size effect on (3).
Exercise 8. Connect to Flash Attention memory complexity.