L1 Beginner · Module 1: The LLM forward pass, for inference engineers

1.5The KV cache: why it exists

Without a cache, generating token n means recomputing all n tokens before it. The KV cache stores each token's keys and values once, which makes every decode step cost one token of compute, and turns memory into the resource that limits a serving engine.

✦ Interactive~20 min

By the end you will be able to

  • ✓Explain why recomputing the full sequence each step wastes work
  • ✓Say exactly what the KV cache stores, and why Q and other activations are not cached
  • ✓Compute the KV cache size per token from a model config
  • ✓Describe the compute-for-memory trade the cache makes

The loop in 1.4 calls model(tokens) on the whole sequence every step. At step 500 it pushes 500 tokens through every layer to learn one new thing: the logits of the last position. The other 499 positions produce exactly the same results they produced on the previous step.

The waste, and the fix

Chapter 1.3 ended with the key fact: because of the causal mask, adding a token never changes anything computed for earlier tokens. The only thing a new token needs from the past is, in every layer, the keys and values of all earlier positions.

So store them. After computing ktk_t and vtv_t for a token in each layer, append them to a per-layer buffer. On the next step, run only the newest token through the model, and let its query attend over the stored keys and values:

qn⏟new⋅[ k0,…,kn−1⏟from cache, kn⏟new ]⊤⟹weights⋅[ v0,…,vn−1, vn ]\underbrace{q_{n}}_{\text{new}} \cdot \big[\,\underbrace{k_0, \dots, k_{n-1}}_{\text{from cache}},\ \underbrace{k_n}_{\text{new}}\,\big]^\top \quad\Longrightarrow\quad \text{weights} \cdot \big[\,v_0, \dots, v_{n-1},\ v_n\,\big]
step 0 · prefill the prompt · sequence length 5

Without a cache: recompute every position, every step

this step: 5 rows

With a KV cache: compute only the new position

this step: 5 rows

Total K/V rows computed so far (one row = one token through every layer)

no cache
5
KV cache
5

Prefill costs the same either way: every prompt token has to go through the model once.

fig. 1.5Generating 9 tokens after a 5-token prompt. Top: the uncached loop pushes every position through the model on every step. Bottom: with a KV cache, prefill fills the cache once, then each step computes one new row.

This is what turns generation into the two phases you met in 0.2: prefill computes K and V for the whole prompt and fills the cache, and each decode step adds one row.

What it saves

For a 7B model, the work to produce the token after a context of length nn (from the lab below):

Context nnNo cacheWith KV cacheRatio
1281.70 TFLOP13.3 GFLOP128×
2,04829.3 TFLOP14.3 GFLOP2,048×
32,768996 TFLOP30.4 GFLOP32,768×

The ratio is exactly nn: without a cache, you redo the work for all nn positions to get one new one. Over a whole generation, total work goes from quadratic in length to linear.

What it costs

The cache is not free. Every token in every active request keeps its keys and values in GPU memory:

KV bytes per token=2×L×nkv×dh×bytes per value\text{KV bytes per token} = 2 \times L \times n_{kv} \times d_h \times \text{bytes per value}

The 2 is for K and V. For Llama-2-7B (L=32L = 32, nkv=32n_{kv} = 32, dh=128d_h = 128, BF16), that is 0.5 MiB per token. A single 4,096-token conversation holds 2 GiB of cache, and 32 such conversations would need 64 GiB, more than the model’s own 13 GB of weights.

Lab: count the FLOPs and bytes 🟢

labs/m01/1.5/kv_flops.py
def flops_no_cache(n): # re-run all n tokens
return n * WEIGHT_FLOPS_PER_TOKEN + L * 2 * (2 * n * n * D)
def flops_with_cache(n): # run only the newest token
return WEIGHT_FLOPS_PER_TOKEN + L * 2 * (2 * n * D)
def kv_bytes(n):
return 2 * L * n * D * BYTES
Terminal window
python labs/m01/1.5/kv_flops.py
output
Llama-2-7B: 32 layers, d_model 4096 -> 13.2 GFLOP of weight math per token
context n no cache KV cache ratio KV memory
128 1.70 TFLOP 13.3 GFLOP 128x 0.06 GiB
512 6.90 TFLOP 13.5 GFLOP 512x 0.25 GiB
2048 29.26 TFLOP 14.3 GFLOP 2048x 1.00 GiB
8192 143.43 TFLOP 17.5 GFLOP 8192x 4.00 GiB
32768 995.95 TFLOP 30.4 GFLOP 32768x 16.00 GiB
Generating 2,048 tokens from scratch: 29.2 PFLOP without a cache, 0.028 PFLOP with one.
Per-token KV cost: 0.50 MiB. That trade, FLOPs for bytes, is what the rest of this course manages.

To see the cache work in real code, run the full model in 1.6.

Sources

Check your understanding

0 / 4 answered
  1. 1.What property of attention makes the KV cache possible?

  2. 2.Why is the query not cached?

  3. 3.A model has 40 layers, 8 KV heads of size 128, and stores the cache in BF16. How many bytes of KV cache per token?

  4. 4.Which phase does the KV cache speed up?