The KV cache

75 min4 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • 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
Part 1 of 4about 15 min
Why a cache helps

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), and self.proj is the output layer.

forward(x, cache=None) returns (y, cache).

  • x is (B, T_new, C): the new tokens only.
  • cache is None or 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_past to T_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 to T_past + T_new tokens.

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) and x of 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, y2 and y3 side by side equal the full pass's y. The problem comes in four levels:

  1. A pass with no cache: causal attention that returns the keys and values it computed.
  2. One token at a time after a prompt, with the cache growing on the time axis.
  3. Chunks of several new tokens with a cache, where the causal mask shifts.
  4. CachedAttention(n_embd, n_head, n_kv_head): the cache keeps only n_kv_head key/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.

Decoding with and without a KV cacheInteractive
Thecatsatonthemat
Queries
every position's
The
cat
sat
Keys
cache: one row added per token
The
cat
sat
Values
cache: one row added per token
The
cat
sat
Prefill: the whole prompt at once
computed this step read from cache
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]))
Predict

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?

Pick one to see what it prints.
Pick an answer above to see the rest

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 CMultiply-adds
q, k and v projections, for one token3 · C²
output projection1 · C²
MLP, up to 4C and back down8 · C²
each token you run through it12 · C²
attention: one query scores t keys, then blends t values2 · t · C

Now the cost of the next token, after t tokens of context:

no cache:12 t C2+2 t2Cwith a cache:12 C2+2 t C\begin{aligned} \text{no cache:} &\quad 12\,t\,C^2 + 2\,t^2 C \\ \text{with a cache:} &\quad 12\,C^2 + 2\,t\,C \end{aligned}

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")
Predict

At C = 768 and t = 1,000 tokens of context, how many times cheaper is one cached step than one uncached step?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

With a cache, does step 10,000 cost the same as step 10?

Pick an answer above to see the rest
Part 1 done
Part 2 of 4about 11 min
What the cache holds

The cache holds keys and values, never queries

What exactly goes in the cache?

The cache of a GPT with 12 blocks, after the cat sat on
keys (4, 4)
thecatsatonblock 1kkkkblock 2kkkk……………block 12kkkk
values (4, 4)
thecatsatonblock 1vvvvblock 2vvvv……………block 12vvvv

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 ownAt on's own stepAt every later step
query q3scored against every key so farnever read again
key k3scored by q3scored by q4, q5, q6, ...
value v3blended by q3's scoresblended by q4, q5, q6, ...

A query is read once, at its own step. Keys and values are read by every later token.

Predict

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.

Pick an answer above to see the rest

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.

Predict

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?

Pick an answer above to see the rest

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, TpastT_\text{past} cached tokens and TnewT_\text{new} new ones, here is where a cached step starts:

TensorShapeWhat 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.

Part 2 done
Part 3 of 4about 20 min
The mask, and the cache you return

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])
The cached step is the last row of the full pass
full pass (4, 4)
thecatsatonthe1000cat1100sat1110on1111
cached step for on (1, 4)
thecatsatonon1111

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, TpastT_\text{past} cached tokens and TnewT_\text{new} new ones:

TensorShapeWhat 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())
Predict

tril(diagonal=n) keeps the entries where the column minus the row is at most n. What does the first line print?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

One new token on 6 cached. Does the mask hide anything?

Pick an answer above to see the rest

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)
Predict

After k = torch.cat([cache_k, k_new], dim=2), what is cache_k.shape?

Pick one to see what it prints.
Pick an answer above to see the rest

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())
Predict

One causal pass over all three tokens, no cache. What comes out?

Pick one to see what it prints.
Pick an answer above to see the rest

Three bugs, three wrong answers, and no errors

Cache bugs rarely crash. They give wrong numbers quietly.

Predict

Step 3 with plain tril(), no offset. Which keys does the new query score?

Pick an answer above to see the rest
Part 3 done
Part 4 of 4about 29 min
Prefill, decode and memory

Prefill runs the prompt once, decode runs one token per step

Generation with a cache has two phases, and they cost different things.

Prefill, onceDecode, once for each new token
Tokens inthe whole prompt, the cat sat1 per sequence, like on
T_newthe prompt's length1
The cachefilled in every layer1 row added in every layer
The mathmatrix times matrix1 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.

Predict

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?

Pick an answer above to see the rest

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:

PieceShapeWhat 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.

Predict

Pass 3 feeds the, after the cat sat on. Which row of the position table does it read?

Pick an answer above to see the rest
Predict

Step 2 crops to cat sat on the. Which position is cat at now?

Pick an answer above to see the rest

How much memory the cache takes

The cache saves compute, and it costs memory.

Predict

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?

Pick an answer above to see the rest

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.

Predict

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?

Pick an answer above to see the rest

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:

Query heads sharing key/value heads, in Llama 3 8B's shapeInteractive
0123
kv 0
4567
kv 1
891011
kv 2
12131415
kv 3
16171819
kv 4
20212223
kv 5
24252627
kv 6
28293031
kv 7
query head key/value head, the part that is cached
Cache per token
128 KiB
Per 8,192-token sequence
1 GiB
Sequences in 65 GiB
65
Query heads per kv head
4
grouped-query: each group of 4 query heads shares one key/value head. The cache is 2 × 32 layers × 8 × 128 × 2 bytes = 131,072 bytes per token.

Multi-query attention (Shazeer, 2019) shares one key head and one value head across all the query heads.

Predict

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?

Pick an answer above to see the rest

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:

Paged blocks on one GPU
GPU blocks (1, 8)
01234567ABBABB
RequestIts blocks, in order
A0, 3
B1, 2, 4, 5
Predict

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?

Pick an answer above to see the rest

Fewer bytes per number

Another way to fit more cache is to store each number in fewer bits.

Predict

Store the keys and values in 8 bits instead of 16. How much does one 8,192-token sequence of Llama 3 8B need?

Pick an answer above to see the rest

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.

Check yourself
5 questions
  1. 1.Why does the cache hold keys and values but never queries?

  2. 2.The cache is (B, H, T_past, d) and the new keys are (B, H, 1, d). Which line grows the cache?

  3. 3.With 3 tokens cached, you feed 2 new tokens at once, so the scores are 2 by 5. Which mask is right?

  4. 4.Whenever a cache comes in, your forward returns that cache instead of the grown one. You prefill a 4-token prompt and then decode 3 tokens. What happens?

  5. 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.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source

MLE technical screen (Sep 2026): what a KV cache is.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-10-10Source

The primary serving metric was batch size combined with KV cache utilization.

News·The Pragmatic Engineer (Gergely Orosz, with OpenAI's Evan Morikawa)·2024-02-20Source

Practice

Sources (6)
  1. Attention Is All You Need · arXiv 1706.03762 · Jun 12, 2017
    “consuming the previously generated symbols as additional input when generating the next”
  2. 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.”
  3. 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”
  4. 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.”
  5. 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”
  6. 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.”