KV Cache
Generating a 500-token answer means running the model 500 times. Without help, each of those runs would redo the attention arithmetic for every token already in front of it. The KV cache is what makes that unnecessary: the keys and values computed for a token are stored the first time and reused by every token after it.
Two phases, one cacheAttention turns each token into a query, a key and a value. A past token's key and value do not change when new text is appended, so they are computed once and kept per layer and per head:
- Prefill — the whole prompt goes through in one pass and fills the cache. This phase is compute-bound.
- Decode — each new token attends against the cache and appends its own entry. This phase is bound by memory bandwidth rather than arithmetic, which is why generation feels slow on hardware that is barely working.
The cache grows linearly with sequence length and with the number of concurrent requests, and at long context it can rival the weights themselves. That single fact drives much of modern serving design: Grouped-Query Attention shrinks it by sharing keys and values across query heads, paged attention in vLLM stops it fragmenting memory, cache quantization halves it, and prompt caching reuses a prefilled prefix instead of rebuilding it.
Why it is not optionalDrop the cache and the cost of producing a sequence becomes quadratic in its length instead of linear, which puts long answers and long documents out of reach at any sensible price.
The KV cache stores the key and value vectors computed for every token already processed, so each newly generated token attends to the past instead of recomputing it. It turns the cost of producing a sequence from quadratic to linear in its length, splitting inference into a compute-bound prefill and a bandwidth-bound decode. Its size grows with context length and batch size, which makes it the main memory constraint in LLM serving.
When you write a long message, you don't re-read the whole page before each new word — you keep what you have read in your head. A language model needs the same trick. It writes one word at a time, and each time it has to take account of everything before it. The KV cache is its short-term memory: a worked-out record of the text so far, kept aside so the model doesn't start from the beginning on every single word. It is why replies stream out smoothly instead of slowing to a crawl, and why very long conversations eat so much of a server's memory.