Lab

KV cache

KV cache: The stored keys and values of every token a model has already read, kept so each new token needs only its own key and value computed.

When a model writes text, every new token needs to look back at all the earlier ones through attention. To do that it needs their keys and values. Recomputing them for the whole text at every step would waste a great deal of work, so the runtime keeps them. That store is the KV cache.

With the cache, each step computes the key and value for the new token only, adds them to the cache, and scores the new token’s query against every cached key. The work saved grows with the length of the text.

The cost is memory, and it grows with every token. For each token, the cache holds a key and a value for every layer and every key/value head:

bytes per token = 2 × layers × KV heads × head size × bytes per value

For example, Llama 3.1 8B at f16 stores 128 KiB per token, so a long conversation can need more memory for its cache than for a quantised copy of the weights.

That is why model designers try to shrink it: grouped-query attention lets several query heads share one key/value head, and runtimes can also store the cache at lower precision, at some cost in accuracy.

The explainer steps through the cache filling up and works out its size for real models. For what that means on your own hardware, see memory for weights and KV cache.

See it working

Explore it in How attention decides what matters

See how a token chooses which earlier tokens to look at, step by step, and why grouped-query attention shrinks the KV cache.

Open the explainer