Lesson 11: Speculative decoding · Workbook
Speculative decoding: the workbook
The full working behind lesson 11. Why checking several guesses costs one pass, the acceptance rule and its proof, the expected tokens per pass and the speedup formula, why the gain fades at large batch, Medusa and EAGLE, and seven exercises to check yourself.
In the roofline lesson, one decode step for one user read every weight of the model from memory to do a sliver of arithmetic. The tensor cores sat idle almost all of the time. Batching more users fills that idle compute, but it does nothing for the user who is waiting on a single long answer.
Speculative decoding fills the idle compute for that one user. A small, cheap draft model guesses the next few tokens. The large target model, the one whose output you actually want, then checks all those guesses in a single forward pass. When the guesses are right, one pass of the big model produces several tokens instead of one. A special acceptance rule guarantees that the text comes out with exactly the same probability distribution as if the target model had generated it alone.
This lesson builds the method from three pieces: why checking several tokens is nearly free, the acceptance rule that keeps the output exact, and the formula that says how much faster it gets.
Checking is nearly free
Recall from the prefill and decode lesson that a transformer can process many tokens in one forward pass when they are all known up front. That is how prefill reads a whole prompt at once. Speculative decoding exploits the same fact during generation.
Suppose a draft model has proposed tokens (gamma, the number of guesses per round). The target model runs one forward pass over the last token of the text plus those guesses. Because of the causal mask, the pass yields the target’s own next-token distribution at each of the positions: after the existing text, after the first guess, after the first two, and so on up to after all guesses. Every guess can now be checked, and there is one extra distribution left over for a bonus token.
What does that pass cost? Take Llama 3.1 70B as the target and Llama 3.1 8B as the draft, both with weights in FP8, on one H200, with 1,024 tokens of context already in the KV cache. The two models’ weights take 81.7 GB, which fits in the H200’s 141 GB. With draft tokens, the roofline floors are:
| Target forward pass | Matmul arithmetic at peak | Step time floor | Bound by |
|---|---|---|---|
| 1 token (ordinary decode) | 70 µs | 14.77 ms | memory |
| 5 tokens (verify 4 guesses) | 351 µs | 14.77 ms | memory |
The arithmetic grows 5×, but it was tiny to begin with: both passes are dominated by reading 70.6 GB of weights, which happens once whether the pass carries one token or five. The verification pass costs 0.004% more than an ordinary decode step. Leviathan et al. state the premise directly: inference from large models is often bottlenecked on memory bandwidth, not arithmetic, so additional compute is available.
The draft model is not free. In the same setup, one 8B decode step has a floor of 1.70 ms, so the cost ratio , the time of one draft step divided by the time of one target step, is 0.12. When both models are memory-bound, is roughly the ratio of their weight bytes: 8.03 GB against 70.6 GB.
The acceptance rule
The draft and the target will not always agree, so we need a rule for which guesses to keep. The obvious rule, keep a guess if the target would also have picked it, works for greedy decoding (always take the most likely token): a guess is kept when it matches the target’s top token. But most serving uses sampling with a temperature, and then “would have picked” has no single answer.
Write for the target’s probability of token at some position and for the draft’s. Leviathan et al. and Chen et al. independently arrived at the same rule, which Leviathan et al. call speculative sampling:
- Draw the guess from the draft, .
- Keep it with probability . If the target likes at least as much as the draft did, it is always kept. If the draft was overconfident about , it is kept only part of the time.
- If it is rejected, draw a replacement from the residual distribution
which puts weight only on tokens the draft under-proposed, in proportion to how much it under-proposed them.
A round runs this down the guesses in order. It stops at the first rejection: that position gets a replacement from , and every guess after it is thrown away (along with the KV-cache entries both the target and the draft wrote for them), because they were conditioned on a token that is no longer in the text. If all guesses are kept, the target’s extra distribution at position supplies one bonus token for free. So every round produces at least one token and at most .
Greedy decoding is the special case where and put all their probability on one token each. Then the ratio is 1 or 0, and the rule reduces to “keep the guess if it matches the target’s top token”.
Why the output is exactly the target’s distribution
Theorem (Leviathan et al., Section 2.3 and Appendix A.1). For any draft , a token produced by this procedure has distribution exactly .
The proof fits in two lines. The chance that is proposed and kept is . Summing over all tokens, a guess is kept with probability
so a rejection happens with probability . The normalizing sum in is as well, because , so the sum is . So the total probability of producing is
The intuition: draw and as two bar charts on top of each other. Where they overlap, the draft’s proposal can be kept as is. The acceptance step keeps exactly that overlap, . What is left of after removing the overlap is the part the draft under-supplies, and the residual distribution supplies exactly that part on a rejection. Every token ends up with its full , split between “proposed and kept” and “filled in after a rejection”.
Two consequences matter in practice. First, a bad draft cannot change what the user sees; it can only make the method slower. Second, , called the acceptance rate, measures how well the draft matches the target: it is 1 minus the total variation distance between and , which is half the sum of over all tokens: 0 when the distributions are identical, 1 when they share no tokens.
The simulator below makes the theorem concrete on a six-token vocabulary. The outlined bars are a fixed target ; the short horizontal marks are the draft . Each round drafts tokens, applies the rule, and adds every produced token to the green histogram. Step one round at a time to see the rule act, then run thousands of rounds. Switch the draft: the histogram converges to every time, and only the tokens per target call change.
Whatever the draft, the same odds come out
Plays by itself; press a button or pick a draft to take over.
✓ kept, ✗ rejected: a guess is kept when the uniform draw u is below its keep probability min(1, p/q). After a rejection the round ends with a token resampled from the residual; if every guess is kept, a bonus token comes from p.
target pdraft qproduced
How many tokens per pass
Leviathan et al. make one simplifying assumption to get a closed form: each guess is accepted independently with the same probability (in reality varies with the text, and here is its average). A round then keeps the first guesses with probability and keeps all with probability . The shortest route to the average: token number of the round is produced exactly when the first guesses all survive, which has probability for . So the expected number of tokens per target call, counting the replacement or bonus token, is the geometric series , which is their Equation 1:
Check the ends. At the draft is never right and every call produces exactly one token, the replacement: no gain, but no loss in tokens either. As the sum approaches . In between, longer drafts help less and less, because the chance that the whole chain survives decays like . Even with infinitely many guesses the expectation is capped at .
With = 0.8 and = 4, the expectation is 3.36 tokens per target call.
From tokens to wall-clock time
A round costs draft steps plus one target pass. Measuring time in units of one ordinary target decode step, that is , using the fact from the first section that the verification pass costs about one decode step. Dividing tokens by cost gives Leviathan et al.’s Theorem 3.8, the expected improvement in wall-clock time over ordinary decoding:
For the 70B target and 8B draft, with = 0.12 and an acceptance rate of 0.8, 4 guesses give an expected 2.30× speedup. Here is an assumed value, not a measurement for this pair: the acceptance rate depends on the models, the task and the sampling temperature, and you measure it on your own traffic. For reference, Leviathan et al. report that drafts a couple of orders of magnitude smaller than the target gave between 0.5 and 0.9 in their experiments.
The draft length is the one knob you set. Too small, and you leave tokens on the table. Too large, and you pay for draft steps whose output will usually be thrown away. Since is an integer, the best value is easy to find by trying each one. For our pair at = 0.8, the best is = 5, for 2.34×.
Speedup against the number of guesses
Plays by itself; move a slider to take over.
speeduptokens per big-model pass
Leviathan et al. tested this on T5-XXL (11B parameters) at batch size 1 on a TPU v4. With T5-small (77M) as the draft on English-to-German translation with greedy decoding, they measured = 0.75 at = 7 and a 3.4× wall-clock speedup over the standard T5X implementation. Chen et al., developing the same method independently, report 2–2.5× on Chinchilla 70B in a distributed setup. Neither result changes the model’s outputs.
Why it helps less at large batch
Everything above rested on one fact: verifying tokens costs about the same as decoding one. That is true only while decode is memory-bound. A batch of users verifying tokens each pushes tokens through every weight matrix, and the roofline lesson showed that the matmuls turn compute-bound once their intensity passes the ridge point. In BF16, intensity is about the token count, but with 1-byte FP8 weights each byte does 2 FLOPs per token. With FP8 math the H200’s ridge is 412 FLOPs per byte, so the crossover comes at about 206 tokens per pass. Past it, verification costs extra time in proportion to the extra tokens.
Keeping the same accounting but using the roofline floor for every term (one round costs draft steps plus one verification pass, each at its real cost at that batch size), and keeping = 0.8 and = 4:
| Batch | Decode step | Verify 5 tokens | Verify ÷ decode | Draft cost c | Estimated speedup | Weights + KV (fits in 127 GB?) |
|---|---|---|---|---|---|---|
| 1 | 14.77 ms | 14.77 ms | 1.00 | 0.12 | 2.30× | 82.2 GB (yes) |
| 16 | 15.82 ms | 15.83 ms | 1.00 | 0.13 | 2.19× | 89.3 GB (yes) |
| 32 | 16.94 ms | 16.96 ms | 1.00 | 0.15 | 2.09× | 96.8 GB (yes) |
| 64 | 19.18 ms | 27.00 ms | 1.41 | 0.18 | 1.58× | 112 GB (yes) |
| 128 | 23.66 ms | 53.99 ms | 2.28 | 0.22 | 1.06× | 142 GB (no) |
| 256 | 35.91 ms | 107.98 ms | 3.01 | 0.25 | 0.84× | 203 GB (no) |
At batch 32 the verification pass still costs almost nothing extra, yet the speedup has already slipped to 2.09×. That is because also grows with batch: each sequence’s KV-cache read is a larger share of the 8B’s step than of the 70B’s (its KV is 40% of the 70B’s per token while its weights are 11%), and past about 206 sequences the draft’s own matmuls turn compute-bound too. At batch 64 the verify pass carries 320 tokens per matrix multiply, the matmuls become compute-bound, and verification costs 1.41× a decode step. The last column is the reality check. Both models’ weights plus both KV caches must fit on the GPU, and the draft’s KV cache takes memory the target could otherwise give to more users. A server holds back 10% of the H200’s 141 GB, as in lesson 4, which leaves 127 GB. Batch 64 needs 112 GB and fits, with the speedup down to 1.58×. Batch 128 would need 142 GB: more than the whole H200, so it does not fit, and even if it did the speedup would be only 1.06×. Batch 256 would need 203 GB; if it fit, the same accounting says speculation would make things slower, 0.84×. Rejected guesses are not just unhelpful at large batch; they are arithmetic the GPU had to pay for.
Leviathan et al. name this limit themselves: the method trades more arithmetic for lower latency, so it does not help when spare compute is not available. In a serving system the batch size changes with load, so the table suggests using speculation when load is light or latency matters most, and shortening as the batch grows. The continuous batching lesson covers how that batch forms in the first place.
Variants: drafting without a separate model
A separate draft model has costs beyond : it needs the same tokenizer as the target, its own weights and KV cache in memory, and its own forward passes. Two well-known variants drop it.
Medusa (Cai et al., 2024) adds extra decoding heads to the target model itself. Each head is a single feed-forward layer with a residual connection that reads the target’s last hidden state and predicts a token further ahead: the first extra head guesses two positions ahead, the second three, and so on. Because each head offers its top few candidates, the guesses form a tree rather than a single chain. Medusa checks the whole tree in one forward pass with tree attention: the candidate tokens are laid out in one sequence, and an attention mask lets each token see only its own ancestors in the tree, so every branch is scored as if it were alone. In Medusa-1 only the heads are trained, on top of a frozen target, which the authors describe as lossless; they report over 2.2× speedup. Medusa-2 also fine-tunes the target model together with the heads, which changes the target itself, and reaches 2.3–2.8×. The paper also proposes a “typical acceptance” rule that accepts more guesses but, as the authors say, does not insist on matching the original distribution exactly; use it only if that trade is acceptable to you.
EAGLE (Li et al., 2024) keeps a separate draft, but makes it tiny and feeds it the target’s own internal state. Its draft reuses the target’s embedding table and output head, and adds a fully connected layer plus one transformer decoder layer. Instead of predicting tokens from tokens, it predicts the target’s next feature vector (the hidden state at the second-to-top layer) from previous feature vectors, together with the token sequence shifted one step ahead so it knows which token was actually sampled. It drafts a tree, verified with tree attention like Medusa. For sampling it uses a multi-round version of the acceptance rule: candidates at the same position are tried in turn, with the residual recomputed after each rejection. That keeps the output distribution exact for both greedy and sampled decoding, with no fine-tuning of the target. The authors report 2.7–3.5× latency speedup on LLaMA2-Chat 70B, and 1.5–1.6× over Medusa on MT-bench.
Both still obey this lesson’s accounting. Trees raise the number of tokens per call by giving several chances per position, at the cost of more tokens in the verification pass, which is nearly free at small batch and not free at large batch.
Check yourself
Work each one out on paper before opening the answer. Every answer comes from the same formulas as the figures above.
Exercise 1. A draft has acceptance rate α = 0.7. With γ = 3 guesses per round, how many tokens does each target call produce on average? What is the most any call can produce? Enter the average.
Show the worked answer
On average 2.53 tokens: . At most = 4, when all three guesses are kept and the bonus token is added. This matches the 2.53× in Leviathan et al.’s Table 1, which assumes drafting is free.
Exercise 2. Leviathan et al. measured α ≈ 0.2 for a bigram model drafting for T5-XXL on English-to-German translation. A bigram lookup costs almost nothing, so take c = 0. What speedup should γ = 3 give?
Show the worked answer
About 1.25×: , divided by . The paper reports the same 1.25× for this case. Even a trivial draft helps a little, because its cost is negligible and a rejection still yields one token.
Exercise 3. Two tokens, A and B. The target has p = (0.5, 0.5); the draft has q = (0.9, 0.1). What is the acceptance rate, what is the residual distribution, and what is the final probability of producing A?
Show the answer
The acceptance rate is = 0.6. The residual is normalized: (0, 1), all on B, the token the draft under-proposed. A is produced only by being proposed and kept: . B is produced by being proposed and kept () or as the replacement after a rejection (), also 0.5. The output matches even though the draft was badly skewed.
Exercise 4. With the 70B target and 8B draft (c ≈ 0.115), what is the best γ and the expected speedup if α = 0.9? If α = 0.6? Use the speedup chart above, or evaluate the formula for each γ.
Show the answer
At = 0.9: γ = 9, 3.20×. At = 0.6: γ = 3, 1.62×. A better draft both raises the speedup and makes longer drafts worthwhile, because long chains survive more often.
Exercise 5. Your server runs the 70B model on one H200 at an average batch of 128. Should you turn on speculative decoding with the 8B draft, γ = 4, α = 0.8?
Show the answer
Probably not. At batch 128 each verification pass carries 640 tokens per matrix multiply, well past the ridge, so it costs 2.28× an ordinary decode step and the estimated speedup falls to 1.06×, almost nothing. Memory is a problem too: at batch 128 the draft’s weights and KV cache take 26.3 GB, and with the 70B’s the total is 142 GB, more than the H200's whole 141 GB, so with the draft added it does not fit at all. Turn it on, or keep γ short, when load is light; that is where single-user latency is set by memory bandwidth and the tensor cores have room to spare.
Exercise 6. From lesson 1: a GPU's ridge point is its peak arithmetic rate divided by its memory bandwidth. The H200 does 1.98 PFLOP/s of FP8 arithmetic and reads 4.80 TB/s from memory. What is its FP8 ridge point?
Show the worked answer
About 412 FLOPs per byte: 1.98 PFLOP/s ÷ 4.80 TB/s. A matrix multiply below that intensity waits on memory, and that idle arithmetic is what speculative decoding spends. With 1-byte FP8 weights each weight byte does 2 FLOPs per token, so a verification pass stays memory-bound up to about 206 tokens through each weight matrix. At batch 64 with γ = 4, it carries 320, which is why the verify pass stops being free there.
Exercise 7. From lesson 4: Llama 3.1 8B has 32 layers, 8 KV heads and a head dimension of 128. How many bytes of KV cache does it store per token in BF16?
Show the worked answer
131,072 bytes per token: 2 × 32 × 8 × 128 × 2. Used as a draft, the 8B keeps its own KV cache for every sequence alongside the 70B’s 327,680 bytes per token, which is part of why the draft costs memory that more users could have had.
Sources
- Leviathan, Kalman, Matias (2023). Fast Inference from Transformers via Speculative Decoding. ICML 2023. arXiv:2211.17192. Algorithm 1, Equation 1, Theorem 3.8 (walltime improvement), Table 1 (speed for c = 0), Table 2 (T5-XXL results)
- Chen, Borgeaud, Irving, Lespiau, Sifre, Jumper (2023). Accelerating Large Language Model Decoding with Speculative Sampling. arXiv:2302.01318. Independent development of the same method; 2–2.5× on Chinchilla 70B in a distributed setup
- Cai, Li, Geng, Peng, Lee, Chen, Dao (2024). Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads. ICML 2024. arXiv:2401.10774. Medusa-2 speedup is 2.3–2.8× in the v3/ICML paper; the arXiv listing abstract still says 2.3–3.6×
- Li, Wei, Zhang, Zhang (2024). EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty. ICML 2024. arXiv:2401.15077. Appendix A.2 and Algorithm 1 (multi-round speculative sampling for tree drafts)
- Llama 3.1 70B and 8B configs (Meta, Hugging Face). The target and draft in this lesson's worked example. Both configs have the same 128,256-token vocabulary
- NVIDIA H200 product page, specifications table