Skip to content
StackDecode
LLM Library
Running and Using LLMsAnimated

The KV Cache

Remembering the keys and values of earlier tokens.

The idea

Without a cache the model would recompute attention inputs for every previous token at each step. Caching keys and values makes each step do only the new token's work, at the price of GPU memory.

Watch it work

Press play, pause, or step through. Some animations have settings you can change.

WITHOUT KV cachet1computeattention work so far: 1 token computations
  • computed
  • cached

Token 1: with no cache the model recomputes keys and values for all 1 tokens again.

token:
1
work:
1
1/16

Without a cache the work grows with the square of the length; with it, linearly.

Step by step

  1. 1Compute K and V for the new token
  2. 2Append to the cache
  3. 3Attend over the cached keys and values
  4. 4Repeat for each token

Where it is used

All generation.

Watch out for

The cache grows with context length and with the number of users.