Inference from scratch · Part 2

Stop recomputing the past.

Same Llama 3.2 1B, same NVIDIA L4, one change: a KV cache. In Part 1, every new token re-ran the whole model over the entire sequence. Now each token computes only what's new, and reuses everything else.

4.4× faster
5.8 → 25.4 tokens/sec over 2,048 tokens
313 → 1.3 ms
attention at token 2,048
70% idle
GPU now mostly waits on Python

What you'll notice when you build one

Flat instead of exploding

Time per token, without and with the cache. Without it, each token is slower than the last. With it, the 2,048th token costs about the same as the 1st.

0100200300400ms408 ms58 ms12505007501k1.25k1.5k1.75k2k2,048
Attention: 313 ms → 1.3 ms. At token 2,048, attention got 235× cheaper. It still grows with the sequence, but linearly and tiny: 0.4 ms → 1.3 ms.
But the first tokens didn't get faster. Around 60 ms either way. Part 1 already showed why: early on, the GPU was mostly waiting for Python, and the cache doesn't touch that.

What the cache actually saves

Attention compares each token's query (q) with the key (k) of every token up to and including itself. Here's the work for generating token 6.

Without a cache
Recompute all 21 scores, every token
k1k2k3k4k5k6q1q2q3q4q5q6
With a KV cache
Compute 6 new scores, reuse the rest
K, V from cachenewk1k2k3k4k5k6q1q2q3q4q5q6

The rows above the newest one never change: earlier tokens can't look ahead at later ones, so their results were final the moment they were produced. That's why the cache stores K and V for every past token, and nothing from the old queries.

Now the GPU mostly waits

The same breakdown as Part 1, with the cache. The GPU's work per token shrank to ~12 ms. The grey part, the GPU idle while Python sends it the next operation, did not shrink. Later in the sequence it even grew, because it's no longer hidden behind long stretches of GPU work.

020406080ms705812505007501k1.25k1.5k1.75k2k2,048

These are the 10 profiled tokens, which also carry the profiler's own overhead (~58 ms each). Across the whole run, tokens averaged ~39 ms, and the GPU sat idle 70% of the time.

Part 1's GPU was busy 98% of the time. Now it's busy about 20%. Busy wasn't good there: it was busy redoing work. The cache removed that work, and exposed the next bottleneck. Each token still launches hundreds of small operations from Python, one at a time, and the GPU finishes each one before the next arrives.

Inside the GPU: it's now just reading weights

With one token at a time, there's very little math left. What's left is reading the model.

~2.5 GBmodel weights read for every token
300 GB/sL4 memory bandwidth
≥ 8 msper token, just to read them once

The measured GPU time is about 12 ms per token, not far above that floor. So decoding is now limited by how fast the GPU can read memory, not how fast it can multiply. That's the opposite of the prompt (prefill) step, where many tokens share one read of the weights.

Details that are easy to get wrong

The idea of a KV cache is simple. These are the parts that only became obvious once I wrote one.

01

You only need the newest query

Each step feeds just one token through the model. Its query is the only one that matters: older queries already produced their tokens, and their rows of the attention matrix will never change. So you cache keys and values, never queries.

02

The causal mask disappears during generation

The mask exists so a token can't see the future. During generation, the single new token is the latest one; everything in the cache is its past. There's nothing to mask. The mask only matters for the prompt, when many tokens go in at once.

if num_input_tokens > 1:   # prompt only
    scores = scores + causal_mask
03

Cache keys after RoPE, at the right position

Llama encodes position by rotating queries and keys (RoPE). The cache stores keys already rotated, so they're never touched again. The new token must be rotated using its real position in the sequence, not position 0. Get that wrong and nothing crashes; the model just quietly gets worse.

cos = cos_cached[start_pos : start_pos + n]   # not [0 : n]
04

Cache 8 heads, not 32

Llama 3.2 uses grouped-query attention: 32 query heads share 8 key/value heads. Store the 8 and expand them only when computing attention. That makes the cache 4× smaller: 32 KB per token across all 16 layers. 2,048 tokens is just 64 MB, but the full 128K context would be 4 GB, which is why serving systems obsess over cache memory.

05

Allocate once, write in place

Appending with torch.cat copies the whole cache on every token, in every layer. Pre-allocating one buffer and writing each new key and value into its slot keeps the cache update at about 0.04 ms per token, the "KV write" column below.

self.k[layer, :, start_pos : end_pos] = xk   # in place, no copy

Every operation, with and without the cache

All 16 layers, each operation summed across layers, in the order they run. Start with the speedup view, then flip to the raw milliseconds. Token 1 is the prompt, the same work either way, so everything there is about 1×.

Faster with the cacheSlower with the cacheDarker means a bigger change≈ too small to compare
Attention blockFeed-forward blockOutput
TokenEmbeddingNormQ projK projV projRoPEKV writeAttentionO projNormGate + UpSiLU × mulDownFinal normLM headSamplingGPU busyWaiting on PythonTotal
1≈1×1×1.2×1.2×1×new1.2×1×1×1×1.6×1×1×1×1×1×0.86×0.9×
2505.0×2.3×1.5×1.4×1.4×2.0×new6.0×1.5×2.1×1.7×8.0×1.5×2.0×1×1×1.7×0.82×1.0×
50015×4.1×2.9×3.1×3.2×4.0×new30×2.9×4.3×2.4×25×2.6×3.0×1×1.3×3.7×0.28×0.9×
75020×5.1×2.9×3.1×3.1×4.9×new77×3.0×5.0×3.1×53×3.4×4.5×1×1.3×6.9×0.10×1.5×
1,00013×6.4×4.0×5.5×5.4×6.3×new135×4.0×6.3×3.8×84×4.2×5.5×1×1.3×12×0.11×2.6×
1,25020×7.9×5.6×6.0×5.8×7.5×new173×5.7×8.0×5.4×123×5.7×6.5×1×1.3×18×0.11×3.6×
1,50023×9.6×6.2×6.1×6.0×9.1×new200×6.2×9.7×6.7×178×6.4×8.0×1×1.3×23×0.16×4.8×
1,75023×11×7.3×7.1×6.9×11×new243×7.4×11×7.3×204×7.5×9.5×1×1.3×28×0.13×5.9×
2,00027×13×7.4×9.8×9.9×12×new264×7.5×14×7.4×246×8.2×12×1×1.7×34×0.14×7.2×
2,04827×12×7.7×9.4×9.6×12×new235×7.6×14×7.8×266×8.5×11×1×1.3×33×0.13×7.0×
Attention blockFeed-forward blockOutput
TokenEmbeddingNormQ projK projV projRoPEKV writeAttentionO projNormGate + UpSiLU × mulDownFinal normLM headSamplingGPU busyWaiting on PythonTotal
10.0080.340.590.210.210.360.040.410.620.324.510.052.190.022.070.0311.9857.5469.52
2500.0020.270.580.160.160.310.040.380.580.274.300.042.090.022.070.0311.2949.3060.59
5000.0020.270.580.160.160.310.040.520.580.274.300.042.090.022.070.0311.4454.5165.95
7500.0020.270.580.160.160.310.040.600.580.274.300.042.090.022.070.0311.5345.9757.50
1,0000.0030.270.580.160.160.310.040.760.580.274.300.042.090.022.070.0311.6945.4757.16
1,2500.0030.270.580.160.160.310.040.870.580.274.300.042.090.022.070.0311.8046.8458.64
1,5000.0030.270.580.160.160.310.041.020.580.274.300.042.090.022.070.0311.9546.3358.28
1,7500.0030.270.580.160.160.310.041.070.580.274.300.042.090.022.070.0311.9946.8358.82
2,0000.0030.270.580.160.160.310.041.230.580.274.300.042.090.022.070.0312.1745.3757.54
2,0480.0030.270.580.160.160.310.041.330.580.274.300.042.090.022.070.0312.2646.2358.49
Attention blockFeed-forward blockOutput
TokenEmbeddingNormQ projK projV projRoPEKV writeAttentionO projNormGate + UpSiLU × mulDownFinal normLM headSamplingGPU busyWaiting on PythonTotal
10.0040.370.630.250.260.39—0.480.640.354.730.082.200.022.070.0312.6049.7762.37
2500.010.620.890.230.230.63—2.270.870.567.150.323.220.042.090.0319.4040.5959.99
5000.031.111.710.490.511.23—15.371.711.1510.431.015.350.062.080.0442.7015.2857.98
7500.041.371.670.490.501.53—46.151.721.3513.252.117.170.092.080.0480.104.4784.57
1,0000.041.732.330.880.871.94—102.482.341.6916.553.348.740.112.080.04145.704.85150.55
1,2500.062.133.260.960.922.33—150.393.292.1723.094.9111.820.132.080.04208.305.32213.62
1,5000.072.583.580.970.962.82—204.293.612.6128.677.1313.400.162.080.04273.807.36281.16
1,7500.072.974.221.141.103.29—260.224.273.1031.488.1515.740.192.080.04339.006.22345.22
2,0000.083.504.321.561.583.87—324.674.333.6731.759.8317.040.232.090.05409.706.57416.27
2,0480.083.374.481.511.533.79—312.964.383.7233.7210.6217.760.222.100.04401.606.18407.78

By the last token, attention is 235× cheaper and the feed-forward block about 10×, because each step now pushes one token through the model instead of the whole sequence. "Waiting on Python" is the one column that gets worse: it was hidden behind the GPU's busy work before, and now it's exposed. The no-cache numbers are the same run as Part 1.