KV Cache & Attention Optimization
AI Engineer path · lesson 104 of 124Watch the KV cache turn quadratic recomputation into linear, then work the 2 × B × S × L × H × M formula that makes it 54 GB for a single Llama 2 13B batch — and see how Character.AI stacked three techniques to cut theirs by over twenty times.
Key insight
The cache scales with batch size as well as sequence length, which is what makes it a serving problem rather than a per-request one. Every extra concurrent user costs you another full sequence of keys and values, so the cache — not the weights — is usually what caps how many people you can serve at once.
Why the cache exists
Order what happens on each decoding step with a KV cache.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
The KV cache exists because, across generation steps, previous tokens' key and value vectors:
The short version
Reading a book aloud, where before every word you re-read every page so far. The KV cache is the margin notes you make as you go: one note per page, written once, glanced at thereafter. The notes make the reading fast — and eventually the notes outweigh the book.
In more depth
KV Cache & Attention Optimization
Generating a token means attending to every token before it — and those tokens' key and value vectors never change. The KV cache stores them, turning quadratic recomputation into linear.
The trade
The formula
KV cache bytes = 2 × B × S × L × H × MB batch · S sequence length · L layers · H model dimension · M bytes per value. The leading 2 is because you store both a key and a value.
Worked example — Llama 2 13B (40 layers, dimension 5,120), batch 32, sequence 2,048, 2 bytes:
2 × 32 × 2,048 × 40 × 5,120 × 2 = **54 GB**
The number that makes the point: Pope et al. (2022) calculated 3 TB for a 500B+ model with multi-head attention at batch 512, context 2,048 — three times the size of that model's weights.
Three buckets of optimization
1. Redesign the mechanism (training/finetuning only — it changes the architecture):
| Technique | Who | Cuts |
|---|---|---|
| Multi-query attention | Shazeer, 2019 | Shares KV across all query heads |
| Grouped-query attention | Ainslie et al., 2023 | Groups of heads share KV — the dial between MQA and MHA |
| Cross-layer attention | Brandon et al., 2024 | Shares KV across adjacent layers (3 layers ⇒ 3× smaller) |
| Local windowed attention | Beltagy et al., 2020 | 1,000-token window on 10,000-token sequences ⇒ 10× |
Character.AI (2024): average conversation carries 180 messages; combining multi-query, interleaved local/global and cross-layer attention cut their KV cache over 20×. They compose because each cuts a different dimension.
2. Optimise the cache (inference time): PagedAttention (Kwon et al., 2023, vLLM) — non-contiguous blocks, removing fragmentation and enabling prefix sharing; KV cache quantization; adaptive compression; selective KV cache.
3. Write kernels: FlashAttention (Dao et al., 2022) fuses operations so intermediates stay in SRAM. Exact, not approximate. FlashAttention-3 followed for H100s.
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required