Skip to content
Optimal Lab

AI Engineering · interactive

The KV cache

To pick each new token, attention needs a key and a value for every token before it. Keep them, and each step only does work for the newest token. Throw them away, and every step starts over. Switch between the two and watch the counters.

Prefill

with KV cache

The capital of France is Paris

tokenkey (K)value (V)this step
Thecomputed
·capitalcomputed
·ofcomputed
·Francecomputed
·iscomputed

Rows computed so far, no cache5

Rows computed so far, with cache5

Prefill: the model reads all 5 prompt tokens at once, computes a key and a value for each, and produces “Paris”.

5 rows this step · 5 total
  1. 1

    The prompt tokens are processed together, in parallel. Each gets a key and a value, and they're stored. This is why the first token takes longest.

    5 rows computed, the same with or without a cache

  2. 2

  3. 3

  4. 4

  5. 5