KV Cache

14 min read

A language model writes its answer one small piece at a time. The KV cache saves its earlier work, so it does not repeat that work at every step. This is the main reason AI chat answers appear fast.

New words

Autoregressive
The model uses its own earlier output as the input for the next step.
Attention
The way a token looks back at earlier tokens to find what matters.
Causal
A token can look only at earlier tokens, never at later ones.
KV cache
A store of saved notes (K and V) about every earlier token.
Prefill
The first phase, where the model reads your whole prompt at once.
Decode
The second phase, where the model writes the answer one token at a time.
Memory bandwidth
How much data can move from memory to the chip in one second.

What you will learn

  1. How an LLM writes: one token at a time
  2. Query, Key and Value in simple words
  3. The waste: doing the same work again and again
  4. See it: with and without a cache
  5. Prefill and decode: the two phases
  6. In code
  7. The price: memory
  8. How engineers shrink the cache
  9. Key takeaways

10 quiz questions at the end.

Start this lesson

The full lesson, with interactive demos and the quiz, opens after you sign in with Google. It is free.

All lessons · Back to the roadmap