The KV cache
- Why generating without a cache runs the whole text again at every step, and what one new token costs with a cache
- What the cache keeps (keys and values, in every layer, never queries), and why the old entries never go stale
- Where the new keys go (the time axis), with the shape of every tensor in a cached step
- Why the mask needs an offset when new tokens come after cached ones, the classic bug
- Prefill and decode, and why decode waits on memory, not on arithmetic
- How big the cache gets for a real model, and how fewer key/value heads and paged memory shrink it
A KV cache for decoding one token at a time
A KV cache keeps the keys and values that attention already computed for earlier tokens, so a model that writes text one token at a time doesn't compute them again. Candidates report it two ways: as the follow-up in an ML debugging round, after they fixed a small GPT, and as a question in a technical screen, What is a KV cache?
This lesson first shows why a cache saves work and why the saved keys and values never go stale. Then it builds the cached step one piece at a time, each with a small task: where the new keys go, the shapes, the shifted mask and the cache you return. It ends on what the cache costs in memory and how serving systems shrink it. The whole problem comes back at the end, as the lesson's practice, from a blank file. It reads:
Write
CachedAttention(n_embd, n_head), causal multi-head self-attention that can take a sequence in pieces.self.qkv = nn.Linear(C, 3 * C)makes the queries, keys and values, the heads are(B, n_head, T, C // n_head), andself.projis the output layer.
forward(x, cache=None)returns(y, cache).
xis(B, T_new, C): the new tokens only.cacheisNoneor a pair(k, v), each(B, n_head, T_past, head_dim): the keys and values of every earlier token.- The new tokens sit at positions
T_pasttoT_past + T_new - 1. They attend to every past token, and causally to each other.- Return
y,(B, T_new, C), and the cache grown toT_past + T_newtokens.Feeding a sequence in pieces must give exactly what one full pass gives.
Fed in pieces, the sequence must give what one full pass gives
The problem's own example feeds five tokens whole, then as a prompt of three and two single tokens:
Call, with attn = CachedAttention(16, 2)andxof shape(1, 5, 16)yKeys in the cache y, cache = attn(x)(1, 5, 16)(1, 2, 5, 8)y1, cache = attn(x[:, :3])(1, 3, 16)(1, 2, 3, 8)y2, cache = attn(x[:, 3:4], cache)(1, 1, 16)(1, 2, 4, 8)y3, cache = attn(x[:, 4:5], cache)(1, 1, 16)(1, 2, 5, 8)
y1,y2andy3side by side equal the full pass'sy. The problem comes in four levels:
- A pass with no cache: causal attention that returns the keys and values it computed.
- One token at a time after a prompt, with the cache growing on the time axis.
- Chunks of several new tokens with a cache, where the causal mask shifts.
CachedAttention(n_embd, n_head, n_kv_head): the cache keeps onlyn_kv_headkey/value heads, each shared by a group of query heads.
Watch the third number in the last column. That's the time axis, and it grows by one token with each cached call, from 3 to 5.
Without a cache, every step runs the whole text again
A model that writes text one token at a time repeats almost all of its work at every step. The KV cache removes that repeated work, and serving systems rely on it to run a model at speed.
This lesson follows one generation: the prompt the cat sat, then on, the and mat, one token per step.
@torch.no_grad()
def generate(model: nn.Module, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
"""idx: (B, T) token ids. Returns (B, T + max_new_tokens)."""
for _ in range(max_new_tokens):
# the whole window, every step
logits, _ = model(idx[:, -model.block_size:])
# keep the last row
next_id = logits[:, -1].argmax(dim=-1, keepdim=True)
idx = torch.cat([idx, next_id], dim=1)
return idx
This is the plain way to generate text. Each step runs every token through every layer, keeps the scores at the last position, and throws the rest away. To write mat, it runs the cat sat on the through every layer again, and all of it comes out exactly as on the step before.
A KV cache keeps the keys and values of the tokens already seen, so each step runs only the newest token.
Step through the generation and watch what each step computes. Then turn the cache off and watch the whole text so far get computed again at every step.
- Scores this step
- 6
- Total, with cache
- 6
- Total, without
- 6
Write runs_no_cache(prompt, new) and runs_cached(prompt, new): how many tokens go through the model to write new tokens after a prompt of prompt tokens, without a cache and with one.
Old tokens never change, because of the causal mask
Why is it safe to keep old results? Because of the causal mask.
import math
import torch
def attend(x: torch.Tensor, causal: bool = True) -> torch.Tensor:
"""x: (T, d), each token's query, key and value. Returns (T, d)."""
T = x.size(0)
att = x @ x.T / math.sqrt(x.size(1))
if causal:
mask = torch.ones(T, T, dtype=torch.bool).tril()
att = att.masked_fill(~mask, float("-inf"))
return att.softmax(dim=-1) @ x
torch.manual_seed(0)
# 5 tokens, 4 numbers each
x = torch.randn(5, 4)
print(torch.allclose(attend(x[:4]), attend(x)[:4]))
print(torch.allclose(attend(x[:4], causal=False), attend(x, causal=False)[:4]))
Run attend on the first 4 tokens, then on all 5, and compare the first 4 outputs. What do the two lines print, with the mask and without it?
What a step costs, with and without a cache
Count the work in multiply-adds, one multiply and one add each, for a block of width C:
| One block, width C | Multiply-adds |
|---|---|
| q, k and v projections, for one token | 3 · C² |
| output projection | 1 · C² |
| MLP, up to 4C and back down | 8 · C² |
| each token you run through it | 12 · C² |
| attention: one query scores t keys, then blends t values | 2 · t · C |
Now the cost of the next token, after t tokens of context:
Without a cache, all t tokens go through the block, and t queries each read t keys. With a cache, one token goes through, and its one query reads t keys.
C, t = 768, 1000
# no cache
print(f"{12 * t * C**2 + 2 * t**2 * C:,}")
# with a cache
print(f"{12 * C**2 + 2 * t * C:,}")
no_cache = sum(12 * t * C**2 + 2 * t**2 * C for t in range(1, 1025))
cached = sum(12 * C**2 + 2 * t * C for t in range(1, 1025))
print(round(no_cache / 1e12, 1), "trillion")
print(round(cached / 1e9, 1), "billion")
print(round(no_cache / cached), "times less")
At C = 768 and t = 1,000 tokens of context, how many times cheaper is one cached step than one uncached step?
With a cache, does step 10,000 cost the same as step 10?
The cache holds keys and values, never queries
What exactly goes in the cache?
keys (4, 4)values (4, 4)The next token, the, adds one column to both, in every block.
Each block keeps its own pair of tensors, the keys and the values of every token so far, because each block sees different inputs. Block 5's keys come from vectors that four blocks have already changed.
Queries are not in the cache. Here is why, for on, token 3:
| On's own | At on's own step | At every later step |
|---|---|---|
| query q3 | scored against every key so far | never read again |
| key k3 | scored by q3 | scored by q4, q5, q6, ... |
| value v3 | blended by q3's scores | blended by q4, q5, q6, ... |
A query is read once, at its own step. Keys and values are read by every later token.
Why not store each layer's input instead, and make the keys and values from it when needed? That's half the memory: C numbers per token, not 2C.
New keys go on the time axis, after the old ones
Each step adds the new token's key and value to the cache.
# B=2, H=4 heads, 3 cached tokens, d=8
cache_k = torch.randn(2, 4, 3, 8)
# the same, for 1 new token
k_new = torch.randn(2, 4, 1, 8)
k = torch.cat([cache_k, k_new], dim=2)
print(k.shape)
torch.Size([2, 4, 4, 8])
After the heads are split, a key tensor is (B, H, T, d). Time is the only axis that grows: past first, then new.
In (B, T, C), time is axis 1. You cat on dim=1 after the head split, with 4 tokens cached and 1 new. What happens?
Every shape in a cached step
Here is the start of a cached forward pass:
# T counts the new tokens only
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v))
if cache is not None:
# past first, then new, on the time axis
k = torch.cat([cache[0], k], dim=2)
v = torch.cat([cache[1], v], dim=2)
The three lines of code before the if are plain multi-head attention. Two things are new: x holds only the new tokens, and a cache may come in, holding the keys and values of everything before them.
With H heads, head size d = C / H, cached tokens and new ones, here is where a cached step starts:
| Tensor | Shape | What it is |
|---|---|---|
x | (B, T_new, C) | the new tokens only |
q, k, v | (B, H, T_new, d) | after the split, view and transpose |
cache[0], cache[1] | (B, H, T_past, d) | keys and values of every earlier token |
Every other shape follows from these and the code. The mask is one grid, new tokens by keys, shared by every batch entry and every head.
In the editor, shapes lists six tensors of one cached step, for a batch of 2, 4 heads of size 8, 5 cached tokens and 2 new ones. Fill in each shape, with numbers or with the letters B, H, d, C, T_past and T_new.
The scores have one row for each new token
With a cache, the score matrix changes shape.
# the keys of 4 tokens, after the cat
k = torch.randn(2, 4, 4, 8)
# the new token's query
q = torch.randn(2, 4, 1, 8)
print((q @ k.transpose(-2, -1)).shape)
torch.Size([2, 4, 1, 4])
full pass (4, 4)cached step for on (1, 4)Rows are queries, columns are keys, and 1 means the query may read the key.
The cached step computes only the last row of the full pass. That is where the saving comes from.
Order matters in the cat. Column j of the scores has to be position j, because the mask is built on that. Past first, then new.
Here is every shape in a cached step, with H heads of size d, cached tokens and new ones:
| Tensor | Shape | What it is |
|---|---|---|
x | (B, T_new, C) | the new tokens only |
q, k, v | (B, H, T_new, d) | after the split, view and transpose |
cache[0], cache[1] | (B, H, T_past, d) | keys and values of every earlier token |
k, v after the cat | (B, H, T_past + T_new, d) | past first, then new |
q @ k.transpose(-2, -1) | (B, H, T_new, T_past + T_new) | new queries scored against every key |
mask | (T_new, T_past + T_new) | broadcasts over B and H |
att @ v | (B, H, T_new, d) | one blended value per new token |
y | (B, T_new, C) | after transpose, reshape and proj |
In the editor, q and k hold one query and one key for each of the 4 tokens of the cat sat on. Set full, every query against every key, then step, the last query against every key, then same.
New tokens sit after the cached ones, so the mask shifts
The causal mask has to change shape too.
print(torch.ones(2, 5, dtype=torch.long).tril(diagonal=3))
print(torch.ones(2, 5, dtype=torch.long).tril())
tril(diagonal=n) keeps the entries where the column minus the row is at most n. What does the first line print?
One new token on 6 cached. Does the mask hide anything?
Return the cache you built
Each call has to hand the grown cache back for the next step.
cache_k = torch.randn(2, 4, 3, 8)
k_new = torch.randn(2, 4, 1, 8)
k = torch.cat([cache_k, k_new], dim=2)
print(cache_k.shape)
print(k.shape)
After k = torch.cat([cache_k, k_new], dim=2), what is cache_k.shape?
A worked example: three tokens, one at a time
Here is the whole cached step, worked by hand on three tokens.
q = torch.tensor([[1, 0], [0, 1], [1, 1]], dtype=torch.float64)
k = torch.tensor([[1, 0], [1, 1], [0, 1]], dtype=torch.float64)
v = torch.tensor([[10, 0], [0, 10], [10, 10]], dtype=torch.float64)
# one token per step
for t in range(3):
# the cache after the append
keys, values = k[:t + 1], v[:t + 1]
w = (q[t] @ keys.T / math.sqrt(2)).softmax(dim=-1)
print(w.round(decimals=2).tolist(), (w @ values).round(decimals=1).tolist())
[1.0] [10.0, 0.0]
[0.33, 0.67] [3.3, 6.7]
[0.25, 0.5, 0.25] [5.0, 7.5]
Each step adds one key and one value, then scores one new query against everything stored. Now run all three tokens through one causal pass, with no cache:
mask = torch.ones(3, 3, dtype=torch.bool).tril()
w = (q @ k.T / math.sqrt(2)).masked_fill(~mask, float("-inf")).softmax(dim=-1)
print((w @ v).round(decimals=1).tolist())
One causal pass over all three tokens, no cache. What comes out?
Three bugs, three wrong answers, and no errors
Cache bugs rarely crash. They give wrong numbers quietly.
Step 3 with plain tril(), no offset. Which keys does the new query score?
Prefill runs the prompt once, decode runs one token per step
Generation with a cache has two phases, and they cost different things.
| Prefill, once | Decode, once for each new token | |
|---|---|---|
| Tokens in | the whole prompt, the cat sat | 1 per sequence, like on |
T_new | the prompt's length | 1 |
| The cache | filled in every layer | 1 row added in every layer |
| The math | matrix times matrix | 1 row per sequence times a matrix |
Pope et al. (2022) call the two phases prefill and decode. Prefill runs the whole prompt in one pass on an empty cache: every prompt token is known up front, so it's big matrix-times-matrix work, which GPUs do well. That pass is most of the wait before the first token appears. Decode reads every weight matrix and the whole cache from GPU memory, to do one row of arithmetic per sequence.
Decode waits on memory, not on arithmetic
Multiply n rows by one C × C weight matrix, 2 bytes per number. A FLOP is one floating-point operation: one multiply or one add.
Decode multiplies one row per sequence by each C × C weight matrix, read once from memory. With a batch of 8 sequences, how many FLOPs do you get per byte read?
Both phases are one loop
The two phases don't need two code paths.
class Block(nn.Module):
def forward(
self, x: torch.Tensor, cache: tuple[torch.Tensor, torch.Tensor] | None = None
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
"""x: (B, T_new, C). Returns the output and the grown cache."""
a, cache = self.attn(self.ln1(x), cache)
x = x + a
return x + self.mlp(self.ln2(x)), cache
@torch.no_grad()
def generate(model: nn.Module, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
"""idx: (B, T) prompt ids. Returns (B, T + max_new_tokens)."""
caches = [None] * len(model.blocks)
# the first pass is prefill: the whole prompt
x, past = idx, 0
for _ in range(max_new_tokens):
T = x.size(1)
h = model.embed(x, past)
for i, block in enumerate(model.blocks):
h, caches[i] = block(h, caches[i])
# every later pass: one token
x = model.lm_head(model.ln_f(h[:, -1:])).argmax(dim=-1)
idx = torch.cat([idx, x], dim=1)
past += T
return idx
model.embed(x, past) adds each token's row of tok_emb to the row of pos_emb for the position that token sits at. The first pass feeds the prompt, and every later pass feeds the one token just picked. Read the argmax line from the inside out:
| Piece | Shape | What it is |
|---|---|---|
h[:, -1:] | (B, 1, C) | the last position only |
ln_f, lm_head | (B, 1, V) | a score for every token |
argmax(dim=-1) | (B, 1) | the top token's id: the next input |
Picking the top-scoring token is greedy decoding. That (B, 1) tensor of ids is the next pass's whole input, so from the second pass on, T is 1.
Pass 3 feeds the, after the cat sat on. Which row of the position table does it read?
Step 2 crops to cat sat on the. Which position is cat at now?
How much memory the cache takes
The cache saves compute, and it costs memory.
Llama 3 8B keeps a key and a value, in 32 layers, for 8 key/value heads of 128 numbers, at 2 bytes a number. How much cache does one token take?
How many requests fit
The cache's size decides how many requests fit on one GPU. Take one GPU with 80 GiB and sequences of 8,192 tokens: the weights take about 15 GiB, which leaves about 65 GiB for the cache, if you ignore activations and overhead. With 8 key/value heads, each sequence needs 1 GiB, so 65 fit.
Give each of the 32 query heads its own key and value, as plain multi-head attention does. How many 8K sequences fit in the 65 GiB now?
Fewer key/value heads: multi-query and grouped-query attention
Once the cache works, interviewers ask about its size. There are three answers, each with its paper, and this is the first.
Llama 3 8B has 32 query heads. Pick how many key/value heads they share:
- Cache per token
- 128 KiB
- Per 8,192-token sequence
- 1 GiB
- Sequences in 65 GiB
- 65
- Query heads per kv head
- 4
Multi-query attention (Shazeer, 2019) shares one key head and one value head across all the query heads.
Llama 3 8B's shape needs 128 KiB a token with 8 key/value heads. Multi-query attention keeps 1. How much a token now?
Paged attention keeps the cache in small blocks
One buffer per request, reserved at the longest it might get, leaves most of it empty: request A uses 6 of its 24 slots, and request B 13. Paged memory hands out blocks of 4 slots as each request grows, wherever they are free:
GPU blocks (1, 8)| Request | Its blocks, in order |
|---|---|
| A | 0, 3 |
| B | 1, 2, 4, 5 |
With one buffer per request, A uses 6 of its 24 slots and B 13 of 24. What share of the reserved memory holds tokens?
Fewer bytes per number
Another way to fit more cache is to store each number in fewer bits.
Store the keys and values in 8 bits instead of 16. How much does one 8,192-token sequence of Llama 3 8B need?
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.Why does the cache hold keys and values but never queries?
2.The cache is
(B, H, T_past, d)and the new keys are(B, H, 1, d). Which line grows the cache?3.With 3 tokens cached, you feed 2 new tokens at once, so the scores are 2 by 5. Which mask is right?
4.Whenever a cache comes in, your
forwardreturns that cache instead of the grown one. You prefill a 4-token prompt and then decode 3 tokens. What happens?5.Llama 3 8B has 32 layers, 8 key/value heads and a head size of 128. How much KV cache does one 8,192-token sequence need in 16-bit?
Where this shows up
The reports behind this lesson, each with its source.
Same April 2026 MLE report, ML debug round: fix a broken miniGPT in PyTorch until it generates correct text, then implement a KV cache.
MLE technical screen (Sep 2026): what a KV cache is.
The primary serving metric was batch size combined with KV cache utilization.
Practice
Sources (6)
- Attention Is All You Need · arXiv 1706.03762 · Jun 12, 2017
“consuming the previously generated symbols as additional input when generating the next”
- Efficiently Scaling Transformer Inference · arXiv 2211.05102 · Nov 9, 2022
“At small batch sizes and sequence lengths, the time to load weights dominates. At larger batch sizes and sequence lengths (e.g. 2048+ tokens with batch size 512+), the time to load the KV cache dominates.”
- The Llama 3 Herd of Models · arXiv 2407.21783 · Jul 31, 2024
“with 8 key-value heads to improve inference speed and to reduce the size of key-value caches during decoding”
- Fast Transformer Decoding: One Write-Head is All You Need · arXiv 1911.02150 · Nov 6, 2019
“We propose a variant called multi-query attention, where the keys and values are shared across all of the different attention "heads", greatly reducing the size of these tensors and hence the memory bandwidth requirements of incremental decoding.”
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints · arXiv 2305.13245 · May 22, 2023
“a generalization of multi-query attention which uses an intermediate (more than one, less than number of query heads) number of key-value heads”
- Efficient Memory Management for Large Language Model Serving with PagedAttention · arXiv 2309.06180 · Sep 12, 2023
“existing systems struggle because the key-value cache (KV cache) memory for each request is huge and grows and shrinks dynamically. When managed inefficiently, this memory can be significantly wasted by fragmentation and redundant duplication, limiting the batch size.”