Skip to content

5.7 Inference

ready≈ 14 hoursNeeds: 4.6, 5.1
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (KV cache animation, Quantization explorer, Speculative decoding demo)
  4. 4 Do
  5. 5 Check

Two phases. Processing the prompt (prefill) is one big batch of matrix multiplications, compute-bound like training. Generating then produces one token per forward pass, and each pass reads every weight from memory to do a few FLOPs per weight: decoding sits far left of the ridge in the 5.1 roofline. Batching many sequences, storing fewer bytes and verifying several tokens per pass all attack that (Pope et al. 2022).

The KV cache. Past keys and values never change, so they are stored and each new token computes one row of attention. The cache grows with layers × KV heads × head size × tokens × batch, and for long contexts it outgrows the weights. Multi-query attention shares one key/value head among all query heads (Shazeer 2019); grouped-query attention shares each among a group, nearly matching full quality (Ainslie et al. 2023).

Quantization. Storing weights in 8 or 4 bits halves or quarters the bytes read per token. Absmax quantization scales each block so its largest value maps to the largest integer, so a few outliers ruin precision for everything sharing their scale. Remedies are per-channel or per-group scales, keeping outlier features in 16 bits (Dettmers et al. 2022, LLM.int8()), and choosing rounding to minimise each layer’s output error (Frantar et al. 2022, GPTQ).

Speculative decoding. A small draft model proposes γ tokens; the large model scores all of them in one pass. An accept/reject rule keeps a prefix of the drafts and samples one token from the target, and the output is distributed exactly as the target’s alone (Leviathan et al. 2023; Chen et al. 2023).

Why speculative sampling is exactstep 1 of 5
  1. x∼q,accept with probability min⁡(1,p(x)q(x))x \sim q, \quad \text{accept with probability } \min\Big(1, \frac{p(x)}{q(x)}\Big)

KV cache animation

What the cache saves and how memory grows

Static view on small screens. Open this page on a laptop to interact.

TheThecatcatsatsatononthethematmatandandthenthenititfellfellfastfastasleepasleepKVstored
step 6: 1 query against 6 cached keys; 1 new key/value pair total so far: 21 attention scores and 6 token projections (grows like T²/2 and T)
cache size for
weights (bf16)
12.6 GiB
KV cache (bf16)
32.0 GiB

Generating one token needs its query against the keys and values of every earlier token. Those never change, so a cache stores them: each step then computes one new row of attention scores instead of the whole triangle. The price is memory: 2 × layers × KV heads × head size × tokens × batch numbers, which for long contexts and large batches exceeds the weights themselves. Grouped-query attention shares each key/value head among several query heads (LLaMA-3 uses 8 for 32 query heads), cutting the cache by that factor.

Top: the triangle of attention scores for a twelve-word sentence, with a slider for the token being generated and a button turning the cache on or off. With the cache only the newest row is computed and earlier keys and values are stored; without it every earlier row and key/value pair is recomputed. A readout counts the total work. Bottom: bars comparing the bf16 size of the weights with the KV cache for LLaMA-2 7B, LLaMA-3 8B (grouped-query) or a one-head variant, with sliders for context length and batch size. Keyboard: Tab to the slider and use the arrow keys; Tab to the buttons and press Enter.

Quantization explorer

Rounding error and outliers

Static view on small screens. Open this page on a laptop to interact.

input column 0–127 · dots: original weight · filled: quantized · lines: error · grey: grid levels of group 2
scheme (4 bits)RMS errorerror / weight scalebits per weight with fp16 scales, 4096 × 4096 layer
per tensor2.02e-21.0124.000
per column5.06e-30.2534.004
per group of 329.60e-30.4804.500

A 16 × 128 weight matrix with typical weights of size 0.02. Absmax quantization maps the largest magnitude in each block to the largest integer, so the step size is set by the biggest value. Turn on the outlier columns (25× larger, as some channels in LLMs are): one scale for the whole tensor then rounds almost every ordinary weight to zero. A scale per column isolates the outliers; groups of 32 along each row do nearly as well for any outlier pattern, at the cost of storing more scales. At 8 bits every scheme is fine; at 4 bits and below the choice matters.

One row of a 16 × 128 weight matrix: each original weight and its quantized value, joined by an error line, with the grid of representable levels. Sliders choose the number of bits and the row; buttons choose one scale per tensor, per column or per group of 32 inputs, and add two outlier columns 25 times larger than the rest. A table compares the error and the storage per weight of all three schemes. Keyboard: Tab to the sliders and buttons.

Speculative decoding demo

Acceptance rate and speedup

Static view on small screens. Open this page on a laptop to interact.

Run a step: the draft proposes γ tokens, the target checks them all in one pass.

simulated: – tokens per target pass over 0 steps expected (1 − αγ+1)/(1 − α) = 3.36 speedup at γ = 4: 2.80×; best γ for this α and c: 8 (3.09×)
14812160×1×2×3×x: draft length γ · y: speedup over plain decoding

Each row is one step: the small draft model proposes γ tokens (one cheap pass each), then the large target model scores all of them in a single pass, which costs about the same as generating one token because decoding is limited by reading the weights. Drafts are accepted left to right (✓) until the first rejection (✗), where the target samples a replacement from the leftover probability (r); if all are accepted the target adds one more token for free (+). Here each draft is accepted independently with probability α. The rule keeps the output distributed exactly as the target's, so the only question is speed: longer drafts pay off only when α is high and drafting is cheap.

Left: the last few simulated steps, each showing γ drafted tokens as accepted, rejected or never checked, then the token added by the target, with the average tokens per target pass against the formula. Right: speedup over plain decoding against draft length γ for the acceptance rate and draft cost chosen with sliders, the current γ marked. Keyboard: Tab to the sliders and buttons.
KV cache, quantization and speculative decoding stubs/m5_7_inference.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m5_7_inference.py and run mlc check 5.7. The tests are identical; import the results on the progress page.

Hints · attention_step 0/3 revealed
Hints · quantize_absmax 0/3 revealed
Hints · speculative_verify 0/3 revealed

Then speed up your own model. Open notebooks/5.7-inference.ipynb on Kaggle with a GPU and paste in your 4.6 GPT and your 5.7 file. It trains a target GPT and a small draft model on TinyStories, adds a KV cache to your model and checks that greedy decoding is unchanged, measures the validation loss after quantizing every weight with your functions, and runs speculative decoding with your speculative_verify, comparing tokens per pass with your formula.

1. Why is generating one token at a time memory-bound?
2. A model has 32 query heads and 8 key/value heads (GQA). Compared with 32 KV heads, its KV cache is…
3. Why does one large outlier hurt per-tensor absmax quantization?
4. With speculative sampling, how does the output differ from sampling the target model alone?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.