5.7 Inference
- 1 Learn
- 2 Bridge & derive
- 3 Explore (KV cache animation, Quantization explorer, Speculative decoding demo)
- 4 Do
- 5 Check
1. Learn
Section titled “1. Learn”- Stanford CS336: Language Modeling from Scratchlecture 10 "Inference" (May 1)
- Leviathan et al., Fast Inference from Transformers via Speculative Decodingsections 1–3
2. Bridge
Section titled “2. Bridge”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).
3. Explore
Section titled “3. Explore”stubs/m5_7_inference.pyLoading 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.
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.
5. Check
Section titled “5. Check”- not yet: All tests pass (0/?)
- not yet: Checkpoint quiz ≥ 80%
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.