KV Cache
Decoding reuses every past key and value instead of recomputing them. What that saves, why decoding waits on memory, and how models shrink the cache.
Jump to a section
The work a decoder would otherwise repeat
A language model writes one token at a time. To produce token 1,001 it runs attention for that position, and attention needs a key and a value vector for every token before it: all 1,000 of them, in every layer.
Those 1,000 keys and values are exactly the ones the model computed on the previous step, and the step before that. A causal decoder never lets an earlier position see a later one, so appending a new token cannot change anything about the old ones. Recomputing them would mean pushing the whole prefix back through the key and value projections of every layer, every step, for no new information.
The KV cache is the obvious fix: keep each layer's keys and values as they are produced, and on the next step compute them only for the new token. The new token's query is still compared against every cached key, and the output is still a weighted sum over every cached value. What disappears is the repeated projection work, not the attention itself.
What the cache costs
Every cached token stores one key and one value per KV head, in every layer. For a single sequence:
The leading 2 is the key and the value. The last factor is the storage width: 2 for bf16, 1 for an FP8 cache.
Llama 3 8B has 32 layers, 8 KV heads and a head dimension of 128. In bf16 that is bytes, or 128 KiB, for every token in the context. An 8,192-token conversation holds 1 GiB of cache. At the 128K context Llama 3.1 supports, one sequence holds 16 GiB, roughly the size of the model's own bf16 weights.
That is per sequence. A server running 32 conversations at 8K tokens needs 32 GiB of cache on top of the weights, which is why serving systems talk about cache capacity far more than about FLOPs.
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, bytes_per_element=2):
return 2 * layers * kv_heads * head_dim * tokens * bytes_per_element
per_token = kv_cache_bytes(32, 8, 128, 1)
assert per_token == 128 * 1024 # 128 KiB per token
assert kv_cache_bytes(32, 8, 128, 8192) == 2**30 # 1 GiB at 8K tokens
assert kv_cache_bytes(32, 8, 128, 131072) == 16 * 2**30
assert kv_cache_bytes(32, 32, 128, 1) == 4 * per_token # no head sharingWhy decoding waits on memory
Generating one token with an 8B model takes about two FLOPs per parameter, around 16 GFLOPs. An H100 does roughly 990 TFLOPS of dense bf16 work, so the arithmetic finishes in about 16 microseconds.
But every one of those parameters has to be read from memory for that token. Reading 16 GB at the H100's 3.35 TB/s takes about 4.8 milliseconds, three hundred times longer than the maths. At batch size one, a decoder spends nearly all of its time waiting for bytes.
The cache adds to that bill. At 128K tokens a single Llama 3.1 8B sequence makes the GPU read 16 GiB of cache on every step, as much as the weights again. Batching amortises the weight reads across requests, but each request brings its own cache, so long contexts stay expensive no matter how you batch.
Making the cache smaller
Almost every change to modern attention layouts is about this number.
Share the keys and values. Multi-query attention gives every query head one shared key and value head. Grouped-query attention, used by Llama 3, shares each KV head among a group of query heads; 32 query heads over 8 KV heads is a 4x smaller cache than plain multi-head attention would need. Llama 2 7B, which had no head sharing, used 512 KiB per token.
Store fewer bits. An FP8 cache halves the memory and the bandwidth again. Quality usually holds up well, but it is a measurement to make on your own model, not a free switch.
Keep fewer tokens. Mistral 7B attends over a sliding window of 4,096 tokens and keeps the cache in a rolling buffer, so memory stops growing with the conversation. Information older than the window can still flow forward through the layers, but no single layer can look back further than the window.
Waste less of what you allocate. Reserving a maximum-length buffer for every request strands memory that short requests never use. vLLM's PagedAttention stores the cache in fixed-size blocks, like virtual memory pages. Almost nothing is stranded, requests with the same prompt can share blocks, and the paper reports two to four times the serving throughput of earlier systems.
In code
A minimal single-head version makes the bookkeeping visible. It preallocates storage, writes each new key and value at the next free position, and attends over the filled prefix only.
1import torch
2from torch import Tensor
3
4
5class KVCache:
6 """Keys and values for one attention head of one sequence."""
7
8 def __init__(self, max_tokens: int, d: int) -> None:
9 self.k = torch.empty(max_tokens, d)
10 self.v = torch.empty(max_tokens, d)
11 self.length = 0
12
13 @torch.no_grad()
14 def attend(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
15 # q, k, v: (d,) for the newest token. Store first, so it can attend to itself.
16 self.k[self.length], self.v[self.length] = k, v
17 self.length += 1
18 keys, values = self.k[: self.length], self.v[: self.length]
19 weights = torch.softmax(keys @ q / q.numel() ** 0.5, dim=0)
20 return weights @ values
21
22
23cache, d = KVCache(max_tokens=16, d=64), 64
24for _ in range(5):
25 out = cache.attend(torch.randn(d), torch.randn(d), torch.randn(d))
26assert cache.length == 5 and out.shape == (d,)Real implementations hold one of these per layer and per KV head, batch many sequences together, and replace the preallocated tensor with pages. The logic per step stays the same: write one key and value, read all of them.
Where it goes wrong
Most cache bugs produce tensors with valid shapes and wrong numbers, so they rarely crash.
Positions. With rotary embeddings, the new token's query and key must be rotated by its true position in the sequence, not by 0 because the input tensor has length one. A cache that forgets the offset produces fluent text that slowly loses track of order.
Padding. When sequences of different lengths share a batch, each one has its own cache length. Attention must mask the empty slots of shorter sequences, or they will attend to garbage.
Changed prefixes. The cache is only valid for the exact tokens, weights and position scheme that produced it. Editing an earlier message, swapping a LoRA adapter, or changing the system prompt invalidates every entry after the first changed token.
Reused prefixes. The same property is an opportunity. Requests that start with an identical system prompt can share its cached entries, which is what prompt caching in commercial APIs sells.
Sources and further reading
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019): the memory-bandwidth argument and multi-query attention.
- Ainslie et al., GQA (2023): grouped key and value heads and their quality trade-off.
- Kwon et al., Efficient Memory Management for LLM Serving with PagedAttention (2023): paged cache storage in vLLM.
- Jiang et al., Mistral 7B (2023): sliding-window attention with a rolling buffer cache.
- Llama Team, The Llama 3 Herd of Models (2024): the 8B configuration used for the numbers above.
Keep going
Ask your own question about KV Cache, or start a guided session on it: six short pages, from the big picture to code you can run.