Lab 02 — Speculative Decoding
Phase: 08 — Inference Optimization at Depth | Difficulty: ⭐⭐⭐⭐⭐ | Time: 4–5 hours
Speculative decoding (Chen et al., 2023) uses a small draft model to generate K tokens, then verifies them all in one target model pass — achieving near-lossless 2–4× throughput gains.
What you build
TinyLM— small draft language modelspeculative_step— draft K tokens, target verifies in one forward pass, accept/reject withmin(1, p_t/p_d), sample corrected distribution on rejection, add bonus tokenspeculative_generate— full generation loopcompare_distributions— total variation distance between distributions
Key concepts
| Concept | What to understand |
|---|---|
| Accept/reject | Token t accepted with prob min(1, p_target(t) / p_draft(t)) |
| Corrected distribution | On rejection: sample from max(0, p_t - p_d) / Z |
| Bonus token | When all K accepted, target generates one extra token "for free" |
| Throughput gain | With high acceptance rate α, gain ≈ K·α + 1 tokens per target call |
| Draft-target alignment | More similar models → higher α → more speedup |
Files
| File | Purpose |
|---|---|
lab.py | Stubs with TODO markers |
solution.py | Complete working implementation |
test_lab.py | pytest suite |
requirements.txt | Dependencies |
Run
pip install -r requirements.txt
python lab.py
pytest test_lab.py -v