Transformer Key-Value Cache During Text Generation
A transformer key-value (KV) cache stores the attention data computed for earlier tokens so an autoregressive model can generate the next token without recomputing attention for the entire conversation each time.
Autoregressive means that the model produces one token at a time, using the tokens already produced as context. The cache is an inference-time optimization: it speeds up generation, at the cost of memory that grows with the context length.
The problem: every new token depends on the past
A transformer is built from layers containing self-attention. Self-attention lets each token compare itself with other tokens in the sequence and use the relevant information from them.
For each token, an attention layer creates three vectors:
- A query, which represents what this token is looking for.
- A key, which represents what information this token offers for matching.
- A value, which contains the information passed along if the token is relevant.
Attention compares a token's query with the keys of earlier tokens. The resulting scores determine how much of each earlier token's value contributes to the current token's output. A causal transformer is restricted to the current token and the past; it cannot look into the future.
Without a cache, generating a token would involve running the model again on the complete sequence:
input: "The service returned"
next: "a"
input: "The service returned a"
next: "500"
input: "The service returned a 500"
next: "error"
The second pass would recalculate the keys and values for The service returned, even though those earlier tokens have not changed. As the response grows, more and more of the same work is repeated.
What the cache stores
During the first pass, often called prefill, the model processes the prompt and produces the key and value vectors for every token in every transformer layer. It keeps those vectors in the KV cache.
The cache is not normally a copy of the original text or token IDs. It is a set of intermediate numeric tensors, usually one key tensor and one value tensor per layer. A tensor is a multidimensional array of numbers.
Conceptually, one layer's cache might look like this:
| Item | Shape (conceptually) | Meaning |
|---|---|---|
| Keys | tokens × attention heads × head size | Matching data for past tokens |
| Values | tokens × attention heads × head size | Information retrieved from past tokens |
An attention head is one independent attention calculation within a layer. The head size is the number of values in one head's vector. Real implementations arrange these dimensions differently in memory, but the contents are equivalent.
The cache is maintained separately for each active request. A long-running chat, a large batch of requests, or several beam-search candidates can therefore consume substantial memory.
How one generation step uses it
After prefill, the model generates one new token. At each layer, it computes the new token's hidden representation and then creates only that token's new query, key, and value.
The layer then:
- Appends the new key and value to the cached keys and values.
- Compares the new query with all cached keys, including the new key.
- Uses those attention scores to combine the cached values.
- Passes the result to the next layer.
The important asymmetry is that the new query must inspect the whole available history, but the history's keys and values do not need to be recreated. The cache grows by one position per generated token.
The cache avoids recomputing prior key and value projections. It does not let the model skip all work for earlier tokens during the initial prompt pass, and it does not make each new token independent of the context.
The model still runs all of its layers for every new token. It also still performs attention against the growing history. With a cache, that attention work grows roughly with the current context length for each generated token, rather than rebuilding the representations of every previous token first.
Position handling must also remain consistent. Models use positional information to distinguish, for example, token 20 from token 200. In models using rotary position embedding, commonly called RoPE, the position-dependent transformation is applied consistently when keys are created and when queries are compared with them. Implementations may cache keys before or after that transformation depending on the model and kernel, but the cached representation must match the attention calculation.
Why memory grows with context length
For every token retained in the context, the cache stores a key and a value for every layer. A rough memory estimate is:
cache bytes ≈
2 × layers × tokens × key/value heads × head size × bytes per number
The first 2 accounts for keys and values. For example, with 32 layers, 4,096 context tokens, 8 key/value heads, head size 128, and two-byte numbers:
2 × 32 × 4096 × 8 × 128 × 2 ≈ 512 MiB
That is for one request. Increase the context to 8,192 tokens and the cache is approximately twice as large. Increase the batch size to eight requests and it is approximately eight times as large, assuming all requests use that capacity.
Some models have as many key/value heads as attention heads. Others use multi-query attention, which shares keys and values across query heads, or grouped-query attention, which shares them among groups. These designs reduce KV-cache memory while preserving multiple query heads. Cache data may also use lower-precision numbers or be moved between devices, with corresponding performance and quality trade-offs.
What the cache explains in practice
A request's memory usage often rises as its prompt and generated response become longer. Serving systems may report this as KV-cache usage, reserved cache blocks, or a context-length limit. When the cache cannot fit in GPU memory, the system may reject the request, reduce the batch, evict old context, use lower precision, or move some data elsewhere.
The cache is therefore a deliberate trade: it spends memory proportional to the number of retained tokens to avoid repeatedly spending compute on tokens whose attention keys and values are already known.