Explainer
KV cache
Saved keys and values for every earlier token, kept so a model does not recompute them each time it writes a new token.
Inside each attention layer, every token produces a key, a label that other tokens are compared against, and a value, the content it passes on. A chat model lets each token draw only on earlier tokens, so once a token's keys and values are worked out they never change. The model therefore stores them in the key-value cache, also called the KV cache, attention cache or past key values (Hugging Face caching explanation).
- Saved. The keys and values of every earlier token, in every layer.
- Still computed at each step. The new token's query (what it is looking for), key and value, and its comparison with every saved key.
- Not saved. The attention weights, how much each earlier token counts for the new one. They are worked out afresh at every step.
Every token adds one key and one value per key-value head in every layer. With ordinary full attention, a chat twice as long needs about twice the cache while the weights stay the same size, so a long chat can run out of memory on a model that handles short ones. Reusing a stored beginning across separate requests is called prefix caching in a serving engine and prompt caching at a hosted provider.
Going deeper
For a simple model, the size per token is 2 (a key and a value) × layers × key-value heads × head size × bytes per number. Designs that cut it include sharing keys and values across heads (grouped-query attention), layers that keep only a recent window (sliding-window attention), compression and storing the cache in fewer bits.
In the long read: why keys and values can be cached. Next, Grouped-query attention, then try Estimate the KV cache.