KV Cache & Attention Optimization
6 min read.
Watch 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.
Think of it this way: 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.
Red is computed now, green is read from the cache. 3 projections in total, 1 at the last step. Work grows linearly with the output length.
Check your understanding
Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.
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
Quiz
20 questionsThe KV cache exists because, across generation steps, previous tokens' key and value vectors:
Done with this lesson?
Sign in free to keep your progress, streak and quiz scores.