TL;DR
A KV cache keeps the keys and values that a transformer has already computed for earlier tokens. When the model generates the next token, it only computes a query, key and value for that one new token, then attends over the stored keys and values. Without the cache, every generated token would redo the work for the whole prefix. The price is memory: the cache grows with every token, in every layer.
Where you'll see it: inside every LLM serving stack (vLLM, TensorRT-LLM, llama.cpp and similar), where it decides how many requests fit on a GPU and how long a context can be.
Intuition
Notes instead of re-reading
Imagine a student writing an essay from a long textbook, one sentence at a time. A careless student re-reads the whole book before every sentence. A sensible one takes notes the first time through and, for each new sentence, only reads the new source material and checks the notes. The notes are the cache. They hold work that was already done and that will not change.
An Autoregressive Model generates one token at a time, and each token depends on all earlier tokens. Those earlier tokens never change once written, so the attention inputs derived from them never change either. Recomputing them at every step is pure waste. The KV cache is the notebook for a transformer.
Why keys and values, and not queries? A new token needs its own query, because the query asks what this token is looking for. But every past token's key and value are fixed numbers that other tokens will read. The query of a past token is only needed when that token was itself the newest one, so it can be thrown away. Only the keys and values are worth keeping.
- multi-head, 32 KV heads
- grouped, 8 KV heads
The math
Attention at one step
Recall attention for a sequence. Each token has an input vector , and the layer computes
where , and are learned matrices. The symbol is the width of a key, and the output for token is
Here is the matrix whose rows are , and has rows . The softmax gives one weight per past position, and the output is the weighted average of the values.
The cached update
Notice that and are just and with one extra row. So the cache update is
At each step the model computes one , one and one , appends the last two to the cache, and attends. Nothing already in the cache is recomputed.
The cost, with and without the cache
Let the sequence grow to tokens. Count how many key-and-value projections (the products and ) are computed.
- Without a cache, step projects all past tokens again. The total is , which grows as .
- With a cache, step projects only token . The total is .
The attention scores themselves still cost at step , so the total attention work is quadratic either way. What the cache removes is the repeated projection of past tokens, which would otherwise multiply the per-token work by the length of the prefix.
The memory cost
For each token, each layer stores one key and one value vector. If the model has layers, a model width of , and each stored number takes bytes (2 for 16-bit floats), then one token costs
The factor 2 is for keys and values. For a sequence of tokens, the cache is times this. The size is linear in and independent of how many tokens you generate later, so it is set by how long the context gets.
Worked examples
Use a single attention head with width , so the scale is 1. Keys and values are plain numbers. Token 1 has key and value , token 2 has key and value , token 3 has key and value .
- Step 1. The cache holds only token 1: keys , values . The query is , so the single weight is and the output is .
- Step 2. Append token 2. The cache is keys , values . Token 2 has query . Scores are .
- The softmax weights are and .
- Output .
- Step 3. Append token 3. The cache is keys , values . The query is , so the scores are .
- Weights are about , and . Output .
Interpretation: at step 3 the model computed one new key and one new value, and . The entries and were read from the cache. The output is pulled most strongly towards the value because the query matches the newest key best.
Take a model with layers and width , stored in 16-bit floats (), with one key and one value per model dimension. This is a typical configuration for a model of about seven billion parameters, and the numbers are illustrative rather than measured from a specific checkpoint.
- Bytes per token bytes, which is 512 KiB.
- For a 4,096-token sequence: .
- For a batch of 16 such sequences served together: .
- The weights of the model itself are roughly 14 GB in 16-bit precision, which is smaller than this cache at batch 16.
Interpretation: at modest batch sizes and context lengths the cache can outgrow the model weights. That is why serving systems spend most of their effort on managing it. If the model shares key and value heads so that only 8 heads of width 128 are stored (grouped-query attention, see Grouped-Query Attention), the same 4,096-token sequence needs 512 MiB instead of 2 GiB.
Generate tokens.
- Without a cache: key-and-value projections.
- With a cache: projections.
- The cache does about 500 times less projection work here.
Interpretation: the saving grows with length, which is why the cache matters most for long generations. It does not change the output at all, only the cost.
Tradeoffs and failure modes
The cache is almost always worth it during generation. The practical question is how to keep its memory under control.
| Situation | Problem | Better choice |
|---|---|---|
| Long context (tens of thousands of tokens) | The cache dominates GPU memory | Share key and value heads (Grouped-Query Attention), or cap the window (Sliding Window Attention) |
| Many concurrent requests | Preallocating the maximum length for each one wastes memory | Allocate the cache in small blocks on demand, as in PagedAttention |
| Many requests with the same system prompt | The same prefix is cached again for each user | Reuse the cached prefix across requests |
| Training or scoring a fixed text | No generation step exists, and the whole sequence is processed in parallel | Do not use a cache; use masked attention over the full sequence |
| Lower-quality output is acceptable | Cache entries use too much memory | Quantize the cache to 8-bit or lower, accepting a small error |
Failure modes to watch for:
- Out of memory. The cache is allocated per sequence and per layer. A request that asks for a longer output than planned can take a server down or force it to evict other requests.
- Leaking between requests. If the cache is not cleared when a request ends, the next user's tokens can attend to the previous user's text. This is a real security bug, not just a wrong answer.
- Position errors after truncation. If old entries are removed to make room, the remaining tokens must keep their original position information, or the model reads the wrong distances. Methods that drop entries therefore need care with Positional Encoding.
- Stale results after editing. If the prompt in the middle changes, every cached entry after the change is invalid and must be recomputed.
History
The transformer paper of 2017 by Vaswani and colleagues described the decoder as attending over previously generated outputs. Because earlier tokens' keys and values do not change during generation, decoder implementations can store them rather than recompute them. The cache is an implementation technique rather than a result of one paper.
Noam Shazeer's 2019 note on multi-query attention showed that sharing one key and one value head across all query heads makes the cache much smaller, with a modest loss in quality. Ainslie and colleagues in 2023 proposed grouped-query attention as a middle path between one shared head and one head per query. Both target the same bottleneck: the memory the cache occupies during decoding.
In 2023 the vLLM project and its paper on PagedAttention (see Efficient Memory Management for LLM Serving with PagedAttention (vLLM)) applied operating-system ideas of paged memory to the cache. Storing the cache in fixed-size blocks avoids most of the waste from preallocating the maximum length for each request. Exact figures for memory waste and throughput gains depend on the workload, and are not repeated here.
Check yourself
QuestionWhy does the cache store keys and values but not queries?Show answer
A query is used once, by the token that produced it, to look up what that token needs at its own step. Keys and values of past tokens are read again by every later token, and they do not change once computed. Storing queries would save nothing, because no later step reads them.
QuestionA model has 24 layers and width 2048, stored in 16-bit floats. How many bytes does one token add to the cache?Show answer
Bytes per token bytes. That is 192 KiB. The first factor 2 is for keys and values, and the last factor 2 is the number of bytes in a 16-bit float.
QuestionGenerating 500 tokens without a cache requires how many key-and-value projections, and with a cache how many?Show answer
Without a cache it is . With a cache it is 500, one per generated token.
QuestionWhy can a cache that is correct at the start of a conversation become wrong later?Show answer
If the text earlier in the context changes, for example when the prompt is edited or the middle of a conversation is removed, the keys and values computed from the old text no longer describe the new context. Every entry from the changed point onwards must be recomputed.
QuestionExplain why shrinking the cache can reduce the cost of serving a model even when the arithmetic stays the same.Show answer
Serving is often limited by memory rather than compute. The cache for each active sequence takes up GPU memory, and that memory limits how many sequences can run at once. A smaller cache lets more sequences share the same GPU, so the same hardware can serve more users, even though each attention step does the same arithmetic.
Sources
- Vaswani et al., Attention Is All You Need (2017)
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019)
- Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023)
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023)