KV-Cache: Theory & Derivation
Why autoregressive transformers need a KV-cache: derivation from the attention computation, memory growth analysis, the relationship between KV-cache size and inference latency, and how cache enables O(Td) per-step generation.
Prerequisites
Table of Contents
- Learning Objectives
- Notation
- Core Intuition
- The Redundancy in Autoregressive Attention
- KV-Cache: Formal Derivation
- Memory Growth Analysis
- Inference Latency with KV-Cache
- Prefill vs Decode Phases
- Multi-Layer KV-Cache
- Common Pitfalls
- Summary
- Exercises
Learning Objectives
- Identify the redundant computation in naive autoregressive attention.
- Derive the KV-cache update rule and show it reduces per-step complexity from to .
- Compute KV-cache memory as a function of , , , and .
- Distinguish prefill (compute-bound) from decode (memory-bound) phases.
- Analyze how KV-cache size limits maximum batch size and context length.
Notation
- — cached keys up to step
- — cached values up to step
- — query at current step
- — number of layers, — number of heads
Core Intuition
In autoregressive generation, the model generates one token at a time. At step , it needs to compute attention over all previous tokens . Without caching, this means recomputing all keys and values from scratch at every step — redundant work per step, total. The KV-cache stores previously computed keys and values, so each step only computes the new token's key/value and appends them.
KV-Cache During Generation
The Redundancy in Autoregressive Attention
Naive approach at step : Given all tokens :
- Compute from all tokens.
- Compute attention: .
- Take only the last row (the new token's output).
Problem: Steps 1 and 2 have already been done for tokens at the previous step. We're recomputing and redundantly.
Total naive cost: — same as full-sequence attention.
KV-Cache: Formal Derivation
Key observation: The projections and depend only on token , not on future tokens (due to causal masking).
Cache update at step :
Attention at step (only for the new token):
Per-step cost: Computing is . Over heads: .
Total cost for generating tokens: — same total FLOPs but now incrementally distributed, avoiding at each step.
Memory Growth Analysis
At step , the KV-cache stores:
Factor 2: one for keys, one for values.
Example: LLaMA-2 70B ( GQA groups, , FP16):
For tokens: per request.
For tokens: — may exceed GPU memory for a single request!
Inference Latency with KV-Cache
Without cache: At step , load all token representations through layers. Cost: per step.
With cache: At step , only process 1 new token through layers + one attention dot product against cached entries. Cost: per step.
The KV read at each layer is:
At large , this KV read dominates the per-step latency (memory-bandwidth-bound).
Prefill vs Decode Phases
Prefill phase (processing the prompt):
- All prompt tokens processed in parallel (one forward pass, batch of tokens).
- Compute-bound (large GEMM operations).
- Populates the KV-cache for all prompt tokens.
Decode phase (generating tokens one by one):
- Single token processed per step.
- Memory-bandwidth-bound (loading KV-cache + model weights for tiny batch).
- Latency: dominated by memory reads.
Time to first token (TTFT): Determined by prefill time. Inter-token latency (ITL): Determined by decode step time.
Multi-Layer KV-Cache
Each of the layers maintains its own KV-cache (keys and values are layer-specific since they depend on that layer's hidden state):
Important: KV-cache cannot be shared across layers because depends on the layer- representation.
However, with GQA/MQA, the number of distinct K/V heads is reduced:
- MHA: per token per K and V
- GQA: per token (where )
- MQA: per token
Common Pitfalls
Pitfall 1. Forgetting that KV-cache grows linearly with context. For a 128K context window, the cache alone can exceed the model weights in memory.
Pitfall 2. Not accounting for KV-cache in batch size planning. With concurrent requests: total KV memory = . This often limits max batch size.
Pitfall 3. Assuming KV-cache is only relevant for generation. During prefill, the cache must be written — this write bandwidth can bottleneck short-prompt, long-generation workloads.
Summary
- KV-cache eliminates redundant key/value computation during autoregressive generation.
- Reduces per-step complexity from to but introduces linear memory growth.
- Cache size per token: elements (with GQA).
- Prefill = parallel, compute-bound. Decode = sequential, memory-bound.
- KV-cache size often determines max context length and batch size.
Exercises
Exercise 1. Compute the KV-cache memory (in GB) for GPT-3 175B () at in FP16.
Exercise 2. Derive the total FLOPs saved by using KV-cache vs naive recomputation for generating tokens.
Exercise 3. For a GPU with 80 GB memory and a model taking 40 GB, compute the maximum batch size at context length with per-token cache of 320 KB.
Exercise 4. Explain why the decode phase is memory-bandwidth-bound while prefill is compute-bound.
Exercise 5. Compute the speedup from using GQA () vs MHA () in terms of KV-cache memory and attention compute during decode.