Transformer KV Cache Memory and Autoregressive Decoding
A transformer KV cache stores the attention key and value vectors computed for every previous token, separately at every transformer layer. During text generation, the model reuses those stored vectors instead of calculating them again for the same prefix.
That reuse makes autoregressive decoding—generating one token at a time—much faster. It also makes the cache one of the main limits on context length and the number of requests a GPU can serve at once.
The problem: generation repeats the prefix
A language model generates text autoregressively: it predicts the next token, adds that token to the sequence, then predicts the next one. A token is a model-sized piece of text, such as a word, part of a word, or punctuation mark.
At each step, a transformer uses attention, a calculation that lets the current token compare itself with earlier tokens and retrieve relevant information from them. For example, when generating the end of a sentence, the current token may need to attend to a noun introduced many words earlier.
Without a cache, the model could process the entire sequence again for every new token:
- Process the prompt and generate token
A. - Process the prompt plus
Ato generate tokenB. - Process the prompt plus
AandBto generate tokenC.
This repeatedly recomputes the internal representations of the prompt and previously generated text. A long prompt therefore causes the same work to be performed again and again.
What attention stores
Attention derives three vectors from each token:
- A query represents what the current token is looking for.
- A key represents what information a token can be matched on.
- A value is the information returned when that token is selected.
The model compares the current query with earlier keys. High-scoring keys cause the corresponding values to contribute more strongly to the current result.
The KV cache stores the keys and values, but not normally the queries. A query is needed only for the current decoding step, while an earlier token’s key and value can be reused by every later token.
This storage exists for every attention layer, not just for the model’s input or output layer. If the model has 32 layers and the sequence contains 1,000 tokens, the cache contains key and value data for 32 layer-specific versions of each of those 1,000 positions.
A useful conceptual shape for the cache is:
[batch, layers, sequence positions, KV heads, head dimension]
Implementations may arrange or split these dimensions differently for efficiency, but the contents are the same: a key and a value for each cached position in each layer and attention head, or each shared group of heads.
How decoding uses the cache
Generation usually has two phases.
1. Prefill the prompt
The model processes the supplied prompt as a batch. For each layer, it computes keys and values for all prompt tokens and places them in the cache. This phase can process many tokens in parallel, so it is often efficient on a GPU.
2. Decode one token at a time
For the next token, the model computes that token’s hidden representation, query, key, and value. It appends the new key and value to the cache. The new query then attends to the cached keys and reads from the cached values, including the newly appended position where appropriate.
The model produces a probability distribution for the next token, selects or samples one, and repeats the process. On the next step, it computes only the new token’s layer states; the keys and values for the prefix are already available.
The cache removes repeated prefix computation. It does not make attention independent of sequence length: each new query still has to examine an increasingly long set of cached keys and values.
With caching, the attention work for one generated token still grows with the context length, but the expensive work of rebuilding every earlier layer representation is avoided. This is why a decoding implementation commonly has a past_key_values, KV cache, or similar entry in a trace, configuration, or error message.
Why the cache consumes so much memory
The approximate cache size is:
2 × layers × sequence length × KV heads × head dimension × bytes per element × batch size
The 2 accounts for keys and values. For example, with 32 layers, 32 KV heads, a head dimension of 128, 8,192 cached tokens, and 16-bit elements, one request requires roughly 4 GiB of KV data before implementation overhead. Eight simultaneous requests would require roughly 32 GiB just for their caches.
The cache grows in two directions:
- Longer context: every prompt and generated token adds entries.
- More concurrent sequences: every request needs its own entries, even when requests use the same model weights.
This memory is separate from the model’s weights. A model can fit in GPU memory while its requested context length or batch size still causes an out-of-memory failure because the KV cache fills the remaining space.
Engineering trade-offs
A serving system must reserve enough cache capacity for expected prompts and generated output. If it reserves too much per request, it wastes memory on short requests; if it reserves too little, requests may stop, be rejected, or spill data to slower memory.
Several optimizations change the size or management of this storage:
- Grouped-query attention shares keys and values among groups of query heads, reducing the number of KV heads.
- Multi-query attention uses one shared key/value set for all query heads, reducing it further.
- Lower-precision cache formats use fewer bytes per element, usually with a quality and implementation trade-off.
- Paged attention stores cache blocks in non-contiguous memory pages, making it easier to grow, release, and share space among requests.
These techniques do not eliminate the cache’s basic cost. Each active token still needs layer-specific key and value data. That is why context-length settings, maximum sequence lengths, batch limits, and “KV cache exhausted” errors are ultimately memory-management decisions as much as model-quality decisions.