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.
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 and 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:
Without a cache: recompute every position, every step
this step: 5 rowsWith a KV cache: compute only the new position
this step: 5 rowsTotal K/V rows computed so far (one row = one token through every layer)
Prefill costs the same either way: every prompt token has to go through the model once.
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 (from the lab below):
| Context | No cache | With KV cache | Ratio |
|---|---|---|---|
| 128 | 1.70 TFLOP | 13.3 GFLOP | 128× |
| 2,048 | 29.3 TFLOP | 14.3 GFLOP | 2,048× |
| 32,768 | 996 TFLOP | 30.4 GFLOP | 32,768× |
The ratio is exactly : without a cache, you redo the work for all 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:
The 2 is for K and V. For Llama-2-7B (, , , 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 🟢
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 * BYTESpython labs/m01/1.5/kv_flops.pyLlama-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 answered1.What property of attention makes the KV cache possible?
2.Why is the query not cached?
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.Which phase does the KV cache speed up?