Log inStart free
LESSON 29.02 · 6 STAGES · 2 CONTROLS · 2 CHECKS

Why the KV cache exists

See how keeping old keys and values saves a model from redoing its work.


EXPLAINER · 29.02 · INFERENCE BAY
01
Stage 1 of 6 · Read the past
Each pass writes one token. The new token reads the keys and values of all 519 tokens so far.
Explain it simply

A model writes one token per pass. To pick it, the newest token looks back at all 519 tokens so far. Each token offers a key, a label to match, and a value, the content it passes on. The model needs every key and value again on each pass.

The last pass of the chat reply. The new token on the right links to the prompt block of 512 tokens and to 6 reply tokens.

prefill, tokens run, K and V, KV cacheoutput tokens, time with the cacherepeated or wrong workK and V read from the cache
Toy: 4 requests, an 8B model (Llama 3 8B shape), one H100, ideal roofline; a tiny random 2-layer model checks K and V
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
chat
Pick the request whose reply the model writes.
causal
Pick which tokens each token may read.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
o=softmax(q K⊤d) V\sy{o}{out}{o} = \mathrm{softmax}\Big(\frac{\sy{q}{data}{q}\,\sy{k}{data}{K}^{\top}}{\sqrt{d}}\Big)\,\sy{v}{data}{V}
K, V: P+N−1=512+8−1=519 rows in each layerK,\ V:\ P + N - 1 = 512 + 8 - 1 = 519\ \text{rows in each layer}

The output mixes every value, weighted by how well its key matches.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
# One reply without and with a KV cache, on an ideal roofline: an 8B model (Llama 3 8B shape), BF16, one H100.
LAYERS, D, HEADS, KV_HEADS, HEAD_DIM, FFN, VOCAB = 32, 4096, 32, 8, 128, 14336, 128256
BYTES = 2                    # BF16
PEAK, BW = 989e12, 3.35e12   # FLOP/s and HBM bytes/s

layer_w = LAYERS * (2 * D * HEADS * HEAD_DIM + 2 * D * KV_HEADS * HEAD_DIM + 3 * D * FFN)
head_w = VOCAB * D
weight_bytes = (layer_w + head_w) * BYTES          # every pass reads all of them
kv_per_token = LAYERS * 2 * KV_HEADS * HEAD_DIM * BYTES   # 128 KiB of K and V
attn_per_pos = 4 * HEADS * HEAD_DIM * LAYERS

def pass_time(new, cached):
    """One forward pass: `new` tokens run through the model, `cached` tokens read from the KV cache."""
    flops = 2 * layer_w * new + 2 * head_w + attn_per_pos * (new * cached + new * (new + 1) // 2)
    nbytes = weight_bytes + new * D * BYTES + cached * kv_per_token + new * kv_per_token
    return max(flops / PEAK, nbytes / BW)

def reply(P, N):
    """Pass p writes output token p. Without a cache it runs all P + p - 1 tokens; with one, only the newest."""
    none = [(P + p - 1, pass_time(P + p - 1, 0)) for p in range(1, N + 1)]
    cache = [(P, pass_time(P, 0))] + [(1, pass_time(1, P + p - 2)) for p in range(2, N + 1)]
    return none, cache

def ms(v):
    return f"{v:.1f}" if v >= 10 else f"{v:.2f}"

requests = {"chat": (512, 8), "summary": (3072, 16), "short question": (96, 12), "code": (1024, 10)}
request = "chat"
P, N = requests[request]

none, cache = reply(P, N)
print(f"token runs: no cache {sum(n for n, _ in none)}, cache {sum(n for n, _ in cache)}")
# token runs: no cache 4124, cache 519
print(f"time: no cache {ms(sum(t for _, t in none) * 1e3)} ms, cache {ms(sum(t for _, t in cache) * 1e3)} ms")
# time: no cache 58.8 ms, cache 38.8 ms
print(f"cache after the reply: {(P + N - 1) * kv_per_token / 1e6:.1f} MB")
# cache after the reply: 68.0 MB
none, cache = reply(P, 4096)
print(f"4096-token reply: no cache {sum(t for _, t in none):.1f} s, cache {sum(t for _, t in cache):.1f} s")
# 4096-token reply: no cache 156.6 s, cache 18.8 s

Copy it into a file and run it. Change request to match the controls.

Common mix-ups

MYTHThe KV cache saves GPU memory.

FIXIt costs memory to save work: 128 KiB per token, 405 MB for the summary. Each later pass then runs 1 token, not 3,087.

MYTHThe KV cache makes every reply faster.

FIXThe short question takes 53.8 ms both ways: each pass waits on the weight reads. The cache pays off as the text grows.

Predict, then reveal
0 / 2 REVEALED
Q01With the causal mask and no cache, which request repeats the most work?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With a full mask, does the cache still give the same result?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. Each new token needs the keys and values of every earlier token.
  2. A causal mask keeps those keys and values fixed, so the KV cache reuses them.
  3. The cache spends 128 KiB per token so each later pass runs one token.