FIELD GUIDE 12
What Is KV Cache? Faster LLM Generation,
Explained
Do the old work once, keep the receipts.
00 Short answer
The quick
version.
Short answer: a KV cache (key-value cache) is memory where a transformer language model stores the attention keys and values it has already computed for earlier tokens. When the model generates the next token, it only computes the key and value for that one new token, appends them to the cache, and reuses everything else. Without the cache, the model would recompute keys and values for the whole text at every step. The KV cache makes generation much faster, at the cost of GPU memory that grows with every token in the conversation.
01 Why it matters
\1
Language models write one token at a time. Each new token is predicted from everything before it, then appended, then the model runs again for the next one. This is called autoregressive generation.
Inside each layer, attention lets the newest token look back at all earlier tokens. For that it needs three vectors:
- a query (Q) from the current token: "what am I looking for?"
- a key (K) from every token so far: "what do I contain?"
- a value (V) from every token so far: "what do I pass on if you pick me?"
Here's the key observation. In a decoder-only model with a causal mask, an earlier token can never look at later tokens. So the keys and values of earlier tokens never change once they're computed. Computing them again for every new token is pure repeated work.
The KV cache simply keeps them:
| Without a KV cache | With a KV cache | |
|---|---|---|
| Step for token t | Recompute K and V for all t tokens in every layer | Compute Q, K, V for the 1 new token; read the rest from the cache |
| Work per new token | Grows with the whole sequence length | Mostly the new token, plus reading the cache |
| Memory | Small | Grows linearly with tokens × layers |
| Output | Same | Same (the cache is an exact optimization) |
02 Why it matters
\1
Only the current token's query is needed at each step: it's the one asking the question. Old queries were used once to produce old outputs and are never needed again. Old keys and values, on the other hand, are read by every future token. So the cache holds K and V. Hence the name.
03 How it works
\1
Take the prompt "The cat sat on the" and imagine the model will write "mat".
- Prefill. The model processes the whole prompt in one parallel pass. In every layer it computes K and V for all five prompt tokens and writes them to the cache. It also produces the first output token's probabilities.
- Decode step 1. The new token ("mat") goes through the model alone. Each layer computes its Q, K and V, appends K and V to that layer's cache, and runs attention with the new query against all cached keys. The output predicts the next token.
- Decode step 2, 3, … Repeat: one token in, one K and V appended per layer, one token out.
- End of request. The cache is freed, or kept for reuse if the serving system supports prompt caching.
A toy sketch of one attention head (NumPy-style, no batching):
k_cache, v_cache = [], [] # one pair of lists per layer and head
def attend_next(x_new, Wq, Wk, Wv):
q = x_new @ Wq # only the new token's query
k_cache.append(x_new @ Wk) # store this token's key
v_cache.append(x_new @ Wv) # store this token's value
K, V = np.stack(k_cache), np.stack(v_cache)
weights = softmax(q @ K.T / np.sqrt(K.shape[-1]))
return weights @ V # mix of all values so far
The attention weights come from a softmax over the query-key scores. Real implementations preallocate tensors and handle many heads, layers and requests at once, but the idea is the same.
04 Code
\1
- Prefill processes all prompt tokens in parallel. It's compute-heavy and mostly decides the time to first token. A long prompt means a longer prefill and a bigger cache before the first word appears.
- Decode generates one token per step. Each step does relatively little math but has to read the whole cache (and the model weights) from GPU memory. That's why decoding is usually limited by memory bandwidth, and why a bigger cache slows each step a little.
This split is why serving systems measure "time to first token" and "tokens per second" separately.
05 Worked example
\1
For a standard multi-head attention model, the cache size is:
KV cache bytes = 2 (K and V) × layers × KV heads × head dimension × bytes per number × tokens × sequences in the batch
Take the published configuration of Llama 2 7B: 32 layers, 32 attention heads, head dimension 128 (hidden size 4,096). Stored in 16-bit precision (2 bytes per number):
- Per token: 2 × 32 × 32 × 128 × 2 bytes = 524,288 bytes ≈ 0.5 MiB
- For a 4,096-token sequence: 0.5 MiB × 4,096 = 2 GiB
- For 8 such sequences in one batch: 16 GiB
For comparison, the model's 7 billion weights at 2 bytes each take roughly 13–14 GB. So with long contexts and many users, the KV cache can rival or exceed the size of the model itself. That's the main reason long context windows are expensive to serve, and why so much research goes into shrinking the cache.
(This is arithmetic from the public config, not a benchmark. Real memory use also depends on the serving framework, padding and allocation strategy.)

06 How it works
\1
- Multi-query attention (MQA): all query heads share a single key head and value head, so the cache shrinks by the number of heads. Proposed by Shazeer (2019).
- Grouped-query attention (GQA): a middle ground where groups of query heads share K and V heads. For example, a model with 64 query heads and 8 KV heads keeps an eighth of the cache of full multi-head attention. Described by Ainslie et al. (2023) and used in many recent open models, including Llama 2 70B.
- Quantized KV cache: store K and V in 8-bit or lower precision instead of 16-bit, roughly halving memory or better, with a possible small quality cost.
- PagedAttention: introduced with the vLLM serving system (Kwon et al., 2023). It stores the cache in fixed-size blocks, like pages in an operating system, so memory isn't wasted on reserved-but-unused space and sequences can share common prefixes.
- Sliding-window attention: each layer attends only to the last N tokens, so the cache stops growing past that window. Mistral 7B is a well-known example.
- Prefix (prompt) caching: if many requests start with the same long system prompt or document, the server keeps that prefix's KV cache and reuses it instead of running prefill again. Several API providers offer this as "prompt caching", often at a lower price for the cached part.
- Eviction and compression: research methods that drop or merge the cache entries for tokens that attract little attention. These trade some exactness for memory.
07 Compare
\1
The context window is the maximum number of tokens a model can attend to. The KV cache is the memory that holds those tokens' keys and values while the model works. A longer context means a bigger cache, so the cache is one of the practical limits on how long a context a provider can afford to offer, and how many users a GPU can serve at once.
The KV cache is not long-term memory. It lasts for one request (or one cached prefix) and is thrown away afterward. It also doesn't change what the model knows. Retrieval systems like RAG add knowledge by putting text into the prompt, which then gets its own cache entries.
08 In practice
\1
- Hugging Face Transformers:
model.generate()uses the cache by default (use_cache=True), and the cached tensors are exposed aspast_key_values. - Serving frameworks (vLLM, TensorRT-LLM, llama.cpp and others) manage the cache for you and expose settings such as maximum batch size, maximum context length and cache precision. Running out of KV cache memory is a common reason a server limits concurrent requests.
- Encoder-decoder models (like the original transformer used for translation) also cache the cross-attention keys and values computed once from the encoder output.
If you want to see the attention step the cache speeds up, try the attention lesson and the transformer block lesson. For a whole forward pass, see how a transformer works.
FAQ What is kv cache / quick answers
Questions,
answered.
Short explanations with the limits left visible.
01 / answerWhat is KV cache in simple terms?
It's memory where a language model saves the attention keys and values of tokens it has already processed, so that for each new token it only computes the new token's key and value instead of redoing the whole text.
02 / answerWhy is it called a KV cache?
Because it stores the K (key) and V (value) vectors from attention. Queries aren't cached, since only the current token's query is needed at each step.
03 / answerDoes the KV cache change the model's output?
No. In standard use it's an exact optimization: the output is the same as recomputing everything, just faster. Approximate techniques like cache eviction or aggressive quantization can change results slightly.
04 / answerWhy does the KV cache use so much memory?
It grows with every token, in every layer, for every sequence in the batch. In the Llama 2 7B example, it's about 0.5 MiB per token in 16-bit precision, or about 2 GiB for one 4,096-token sequence.
05 / answerWhat is the difference between prefill and decode?
Prefill processes the whole prompt at once and fills the cache; it determines time to first token. Decode generates one token per step, reading the cache each time; it determines tokens per second.
06 / answerIs the KV cache used during training?
Not in the usual sense. In training, the model processes whole sequences in parallel with a causal mask, so there's no step-by-step generation to speed up. The KV cache is an inference (generation) technique.
07 / answerWhat are MQA and GQA?
They're attention variants that share key and value heads across query heads: one shared KV head in multi-query attention, a few in grouped-query attention. Both shrink the KV cache a lot with a small quality trade-off.
08 / answerWhat is prompt caching?
It's reusing the KV cache of a repeated prompt prefix, such as a long system prompt or document, across requests, so the server doesn't recompute it. Some API providers bill cached input tokens at a lower rate.
Sources Papers / official docs
Read the
sources.
- Vaswani et al., Attention Is All You Need (2017). https://arxiv.org/abs/1706.03762
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019), multi-query attention. https://arxiv.org/abs/1911.02150
- Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023). https://arxiv.org/abs/2305.13245
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023). https://arxiv.org/abs/2309.06180
- Touvron et al., Llama 2: Open Foundation and Fine-Tuned Chat Models (2023), model configurations. https://arxiv.org/abs/2307.09288
- Hugging Face Transformers documentation, caching /
past_key_values. https://huggingface.co/docs/transformers/main/en/kv_cache
