A small model guesses the next few tokens. The big model checks all of them in one pass. On T5-XXL this ran 3.4× faster, and the output did not change.
Pick a draft model, then move k, the number of guesses per round. Watch both decoders spend the same time and count the tokens each one writes. Then we build, piece by piece, the idle GPU, the keep rule, the speedup formula, and the methods that draft without a second model.
You need what a probability is and the idea that a language model writes one token at a time. We build the rest from zero.
Built on Leviathan, Kalman and Matias, Fast Inference from Transformers via Speculative Decoding (ICML 2023), and Chen et al., Accelerating Large Language Model Decoding with Speculative Sampling (2023). Part of the Inference Engineering family with Serving Engines and Cost Modeling.
The acceptance rates (0.75, 0.62, 0.71) and draft costs (0.02, 0.02, 0.11 of a target pass) are Leviathan et al.'s English to German runs with T5-XXL as the target (Table 4). Which guesses pass in each round is a random draw.
Chapter 0
Find out why one decode step leaves almost all of the chip's arithmetic unused
A chat model streams a reply to one user. You watch the GPU. Its arithmetic units sit almost idle, step after step. Nothing is broken. This is how decoding works.
To write one token, the GPU must read every weight of the model from its memory. Take a 7-billion-parameter model in 16-bit numbers on one A100 GPU. The weights fill 14 GB. The A100 reads about 2 TB per second. So one step costs a fixed time before any multiply starts:
14 GB ÷ 2 TB/s = 7 ms per token, or about 143 tokens per second.
The arithmetic is small. One token needs about 2 operations per weight, so 14 billion operations. The A100 can do 312 trillion per second. That work takes 0.045 ms of the 7 ms. The chip uses about 0.64% of its arithmetic. A step like this is memory-bound: the time to move bytes sets its speed, not the time to compute.
Yellow is the fixed time to read the weights. Blue is the time to compute. Drag the number of token positions one pass must check.
A100 80GB rated figures (about 2 TB/s, 312 dense 16-bit TFLOPS) and the 2-operations-per-weight rule. The model ignores the attention and KV-cache reads, so it is a best case.
One pass reads the weights once, for any number of positions. So how many positions fit before compute becomes the slow part? Call the chip's peak arithmetic rate F, its memory speed BW, and the bytes per weight b. Call the number of positions that fit in the memory time N*.
N-star equals F times b, divided by two times BW.
Divide the arithmetic rate F by the memory speed BW. Multiply by the bytes b each weight costs to read. Divide by the 2 operations each weight costs per position. That is N*.
A100: F = 312 × 1012, b = 2, BW = 2 × 1012. N* = (312 × 1012 × 2) / (2 × 2 × 1012) = 156 positions. One pass can check 156 positions for the price of one.
The idea of this lesson: guess the next few tokens cheaply, then check all the guesses in one pass of the big model. The check costs about one step. Each right guess is a token for free.
Failure. The symptom is a speedup that vanishes under load. Measure the positions per pass across the whole batch. If they near N*, the pass is no longer free. Chapter 9 gives the fix.
Chapter 1
Run one round: a cheap model guesses k tokens, the big model checks them all at once
Two models share the work. The target model is the big model whose output you want. The draft model is a much smaller model that guesses ahead. One round goes like this:
Why can one pass check k guesses? A transformer computes a next-token distribution at every position of its input, in parallel. Feed it the prefix plus k guesses and it returns k + 1 distributions. Each one is what the target would say after that much text.
Purple boxes are the draft's guesses. Teal is a guess the target keeps, red a guess it rejects, warm the target's own token. Press Run a round.
Illustrative: each guess passes with the same chance α, independent of the others. Real acceptance varies token by token.
Worked round, k = 4. The draft guesses "sat by the cold". The target keeps "sat", "by" and "the", and rejects "cold". It writes its own token, "warm", at that place. The round adds 4 tokens for one target pass. If it had kept all 4 guesses, it would add a fifth, the bonus.
Data flow in the target pass: the input is the token ids, shape [k + 1]. The output is logits, shape [k + 1, V], where V is the vocabulary size. Row i is the target's distribution after the prefix plus i guesses.
Failure. Symptom: rounds add one token most of the time. Measure the share of rounds that end on the first guess. If it is high, the draft disagrees with the target too often. Fix it with a better draft (Chapter 6) or a smaller k (Chapter 5).
Chapter 2
Decide when to keep a guess, and what to draw when you reject one
Most servers sample: they draw the next token at random from the model's distribution. So "the token the target would pick" is not one fixed token. We need a rule that keeps the target's odds intact.
Take a vocabulary of three tokens, A, B and C. At this place the target gives each token a probability. Call the target's probability of token x p(x). The draft gives its own probability, q(x). The draft has drawn token x. Call the chance we keep it a(x).
a of x equals the smaller of one and p of x over q of x.
If the target likes x at least as much as the draft (p(x) ≥ q(x)), keep it always. If the draft likes x more, keep it with chance p(x) / q(x).
With made-up numbers: p = (0.5, 0.3, 0.2), q = (0.4, 0.4, 0.2). a(A) = min(1, 0.5 / 0.4) = 1. a(B) = min(1, 0.3 / 0.4) = 0.75. a(C) = min(1, 0.2 / 0.2) = 1. Only B, which the draft likes too much, is ever rejected.
A rejection means the draft gave too few draws to some token. We redraw from the target's leftover: the probability the target has and the draft did not cover. Call the redraw distribution p′(x), and the total leftover Z.
p-prime of x equals the larger of zero and p of x minus q of x, divided by Z.
For each token, subtract q(x) from p(x). Set any negative result to zero. Divide each leftover by their sum Z. Draw from that.
Same numbers: leftovers 0.5 − 0.4 = 0.1, 0.3 − 0.4 → 0, 0.2 − 0.2 = 0. Z = 0.1. So p′ = (1, 0, 0): a rejected B always becomes A.
Left: target p in blue, draft q in purple, with each token's keep chance. Right: what comes out, teal from kept guesses, warm from redraws. Pick a draft, then draw.
The three-token p and q are toy numbers. The rule is the one in Leviathan et al. (Section 2.3) and Chen et al. (Algorithm 2).
Failure. Symptom: outputs from the speculative server read different from the plain server at the same temperature. Measure token frequencies from both on the same prompts. If they differ, the code skips the redraw or redraws from p instead of p′. Fix the rejection branch.
Chapter 3
Prove that the keep rule gives the target's distribution, and see the shortcut that breaks it
The device in Chapter 2 converged to p. Now prove it holds for every p and q. First, one number that matters for the rest of the lesson. For each token, the smaller of p(x) and q(x) is the probability the two models agree on. Call the sum of these overlaps α, the acceptance rate.
alpha equals the sum over x of the smaller of p of x and q of x.
For each token, take the lower of p(x) and q(x). Add them up. The total area the two distributions share is α.
p = (0.5, 0.3, 0.2), q = (0.4, 0.4, 0.2): α = 0.4 + 0.3 + 0.2 = 0.9. The target keeps nine draws in ten. The total leftover Z from Chapter 2 is 1 − α = 0.1.
A token x can come out two ways. The draft drew x and we kept it: chance q(x) × a(x) = min(p(x), q(x)). Or the draft drew something we rejected, chance 1 − α, and the redraw gave x, chance p′(x). Call the chance x comes out P(out = x).
P of out equals x equals the smaller of p of x and q of x, plus one minus alpha times p-prime of x, and that equals p of x.
The 1 − α cancels the Z inside p′(x), leaving max(0, p(x) − q(x)). Add min(p(x), q(x)). If p(x) is larger, you get q(x) + p(x) − q(x). If q(x) is larger, you get p(x) + 0. Both are p(x).
Token A: 0.4 + 0.1 × 1 = 0.5. Token B: 0.3 + 0.1 × 0 = 0.3. Token C: 0.2 + 0 = 0.2. The output is (0.5, 0.3, 0.2), which is p exactly, though q differs at A and B.
A round of k guesses repeats this check at each place, given the tokens kept so far. Each step is an exact draw from the target, so the whole kept sequence is too. Leviathan et al. prove this in their Appendix A.1.
Left: teal is the overlap α, warm the leftover the redraw fills, red the draft's excess, which the rule rejects. Right: what each rule outputs, against p. Pick a rule.
Exact probabilities, not samples. "Greedy match" keeps a guess only if it is the target's top token and otherwise emits the top token.
Failure. The greedy-match shortcut is the common bug. Symptom: answers lose variety, even at temperature 1. Measure the distinct outputs over repeated samples of one prompt. Fix: use the keep rule whenever the server samples.
Chapter 4
Count how many tokens one target pass gives on average, from one acceptance rate
A round with k guesses gives between 1 and k + 1 tokens. How many on average? Assume each guess is kept with the same chance α, independent of the others. This is the simplifying assumption in Leviathan et al.
The round reaches guess number i only if the first i guesses were all kept. That has chance α multiplied by itself i times. Each guess reached and kept adds one token, and the target always adds one more. Call the average tokens per round E and the number of guesses k.
E = 1 + α + α2 + … + αk
Multiply that sum by α and subtract. Every middle term cancels, leaving a short closed form.
E equals one minus alpha to the k plus one, over one minus alpha.
Raise α to the power k + 1. Subtract that from 1. Divide by 1 − α. As k grows, E climbs toward 1 / (1 − α) and stops.
With made-up numbers: α = 0.7, k = 4. α5 = 0.168. E = (1 − 0.168) / 0.3 = 2.77 tokens per round. The ceiling is 1 / 0.3 = 3.33 for any k.
Bars are how many rounds gave 1, 2, …, k + 1 tokens. Dots are what the formula predicts. Set α and k, then run.
Simulated with independent guesses. Real guesses are not independent, which is why the formula is an estimate.
Read the bars at α = 0.7, k = 4. The tallest bar is 1 token: 30% of rounds fail on the first guess. The last bar, 5 tokens, holds 24%: rounds that kept all four guesses and got the bonus. The shape is a capped geometric: each bar is α times the one before, and the last bar collects the rest.
Failure. Symptom: measured tokens per round sit well below the formula. Measure α at each position in the round. If later guesses pass less often, the independence assumption fails. Use the per-position rates in place of one α.
Chapter 5
Divide tokens per round by the cost of a round, and find the best number of guesses
Tokens per round is half of the answer. A round also costs more than a plain step, because the draft runs k times first. Measure every time in units of one target pass. Call the time of one draft step c, the cost ratio. A round costs 1 + k × c target passes. Call the speedup over plain decoding S.
S equals E over one plus k times c.
Work out E from α and k. Work out the round's cost: one target pass plus k draft steps of c each. Divide E by that cost. Above 1 is a win; below 1 is a slowdown.
Leviathan et al., T5-small drafting for T5-XXL: α = 0.75, c = 0.02, k = 7. E = (1 − 0.758) / 0.25 = 3.60. Cost = 1 + 7 × 0.02 = 1.14. S = 3.60 / 1.14 = 3.16. The paper predicted 3.2× and measured 3.4× (Table 4).
The formula is Theorem 3.8 of Leviathan et al. More guesses raise E, but E stops near 1 / (1 − α) while the cost keeps growing by c per guess. So S has a peak.
The curve is the speedup S at each k. The dashed line is 1, plain decoding; red below it is a slowdown. Move α and c.
Theorem 3.8 of Leviathan et al. under the same independence assumption. The default c = 0.10 is a draft about one tenth the target's size.
| α | E at k = 4 | S at k = 4, c = 0.1 | Best k | S at best k |
|---|---|---|---|---|
| 0.3 | 1.43 | 1.02 | 1 | 1.18 |
| 0.5 | 1.94 | 1.38 | 2 | 1.46 |
| 0.7 | 2.77 | 1.98 | 4 | 1.98 |
| 0.9 | 4.10 | 2.93 | 10 or more | 3.43 |
Failure. A weak draft with a large k is slower than no draft. With α = 0.15, k = 8 and c = 0.1: E = 1.18, cost = 1.8, S = 0.65. Measure α on real traffic before you set k. If α drops, lower k or turn speculation off.
Chapter 6
Compare three places to get guesses, and match each one to the traffic it suits
The draft sets two numbers in the speedup formula: α, how often its guesses pass, and c, what each guess costs. You cannot move one without the other. A bigger draft guesses better and costs more.
| Draft source | How it guesses | Cost c | Where it wins |
|---|---|---|---|
| Small model | A model of the same family, 10 to 100 times smaller, runs ahead | 0.02 to 0.1 | Any traffic; needs a second model to host and keep in step |
| Prompt lookup | Find the last few tokens earlier in the prompt and copy what followed | near 0 | Code edits, summaries and RAG answers that quote their input |
| Skip layers | The target itself with some layers skipped drafts for the full target | 0.2 to 0.5 | No second model at all; smaller gains |
Leviathan et al. measured α across T5, LaMDA and a small GPT. Drafts about two orders of magnitude smaller than the target gave α between 0.5 and 0.9 (Section 4.2). Chen et al. reported 2 to 2.5× on Chinchilla 70B with a small draft model. Prompt lookup (Saxena, 2023) uses no model: it matches text. Skipping layers is the idea of Draft & Verify (Zhang et al., 2023), which reports up to 1.99× on LLaMA-2. The cost column gives rough ranges, not measurements.
Each bar is a draft source's speedup at k = 4, from the formula in Chapter 5. Pick the traffic.
Illustrative α and c for each pair, chosen to show the pattern. Measure your own α before you choose.
Worked number, code edits: prompt lookup with α = 0.82 and c = 0.002. E = (1 − 0.825) / 0.18 = 3.50, cost = 1.008, S = 3.47. On fiction the same lookup finds few matches. With α = 0.05, S = 1.04: almost nothing, but almost no loss, because the guesses were free.
Failure. Symptom: latency creeps up over months with no code change. Measure α per traffic type every week. A small draft trained against an old target checkpoint drifts away from the new one. Fix: retrain the draft with each target release.
Chapter 7
Draft from the target's own hidden state, and check a whole tree of guesses in one pass
A second model is a second thing to host, train and keep in step. Medusa and EAGLE remove it. They read the target's last hidden state, the vector it computes just before its output head, and guess from that.
Medusa (Cai et al., 2024) adds K extra heads on that hidden state. Head 1 guesses the token two places ahead, head 2 three places ahead, and so on. Each head is one small block: a d × d layer with a skip connection, then a d × V output layer. That output layer starts as a copy of the target's own head. For a 7B model (d = 4,096, V = 32,000) that is about 148 million weights per head.
Each head offers its top s guesses, so the guesses form a tree. To check every branch in one pass, the target uses tree attention. A mask lets each node see only the nodes on its own path back to the root.
Left: a tree of 2 heads with 2 guesses each. Right: the attention mask, one row per node. Tap a node, or press Next node.
Toy words. The masking rule is the one in the Medusa paper: attention applies only to a token's predecessors.
A full tree grows fast: s + s2 + … + sK nodes. With 4 heads and 4 guesses each, that is 340 positions, over the 156 budget from Chapter 0. Medusa keeps a sparse tree of 64 nodes, depth 4, chosen offline. In the paper it beat a dense tree of 256 nodes.
Medusa reports over 2.2× with a frozen target (Medusa-1) and 2.3 to 3.6× when the target is fine-tuned with the heads (Medusa-2). Its default typical acceptance keeps a guess if the target gives it enough probability. That is faster but not exact. The keep rule of Chapter 2 is the exact option.
| EAGLE version | What it changes | Reported speedup |
|---|---|---|
| EAGLE (Li et al., 2024) | One decoder layer predicts the next hidden state from hidden states plus tokens one step ahead; the target's frozen head turns it into a token. 0.24B weights for a 7B target. | 2.7 to 3.5× on LLaMA2-Chat 70B, output distribution kept |
| EAGLE-2 | Grows the tree per context, using the draft's own confidence as a guide | 3.05 to 4.26×, 20 to 40% over EAGLE |
| EAGLE-3 | Predicts tokens directly and mixes hidden states from several target layers | Up to 6.5×, about 1.4× over EAGLE-2 |
Failure. Symptom: Medusa answers differ in tone from the target's samples. Measure output statistics with typical acceptance on and off. If they differ, switch to the exact keep rule where the output distribution matters.
Chapter 8
Guess a window of future tokens, fix them in parallel, and keep the phrases that appear
What if there is no draft at all? Fill a window of W future places with guesses. Run the target once over all of them. Each place gets a new token, computed from the guesses to its left. Repeat. This is Jacobi iteration, an old way to solve many equations in parallel.
One place is always right after a pass: the first, because the target has confirmed the text before it. A later place becomes right once every place before it is right. So plain Jacobi often fixes one token per pass, no better than normal decoding.
Lookahead decoding (Fu, Bailis, Stoica and Zhang, 2024) adds a pool. As the window changes, short phrases (n-grams) appear in it. The method stores them. Later, when the text reaches a phrase's first token, it offers the phrase as guesses and checks it in the same pass. Correct phrases fix several places at once.
Each box is a place in the window. Teal is fixed for good, purple is still a guess. Press One pass. Turn the pool on and compare the passes needed.
A toy with a greedy target that always continues one fixed sentence. The real method runs a 2-D window and a separate check branch in one pass.
Worked number: a window of 8 places, filled in 3 passes, gives 8 tokens for 3 target passes, so 8 / 3 = 2.67 tokens per pass. Each pass computes more positions than a plain step, so the gain in time is less than 2.67 when the budget is tight.
The paper reports up to 1.8× on MT-bench and up to 4× on code completion when it spreads the work across several GPUs. The output matches the target's greedy decoding.
Failure. Symptom: lookahead gives nothing on short, varied replies. Measure the pool's hit rate. If it is near zero, the text has few repeated phrases. Expect gains on long outputs and code, not on short chat.
Chapter 9
Share the idle budget between real users and guesses, and throttle speculation as the batch fills
A server rarely serves one user. Continuous batching puts many users' tokens into the same pass (see Serving Engines). Each user in the batch spends part of the same idle budget N* from Chapter 0. Speculation spends it too.
Call the number of users in the batch B. If each one checks k guesses, each needs k + 1 positions per pass. The pass stays near its memory time only while the total fits in N*.
B times k plus one is at most N-star.
Multiply the users B by the positions each needs, k + 1. Compare with N*. Below it, guesses are nearly free. Above it, the pass slows down for every user.
B = 20, k = 4: 20 × 5 = 100 ≤ 156, so speculation is nearly free. B = 60, k = 4: 300 positions, almost twice the budget. The largest batch that fits k = 4 is 156 / 5 = 31 users.
The bar is positions per pass: blue for the users' own tokens, purple for guesses. The yellow line is N* = 156. Move B and k.
Illustrative: α = 0.7 and c = 0.1 for every user, the 7 ms A100 step, and no KV-cache reads. Real batches also read each user's cache, so the budget is smaller.
The fix is a rule on the scheduler: read B every step and set k from it. With many free positions, speculate with a large k. Near the line, use a small k or only free drafts such as prompt lookup. Far past the line, turn speculation off. EAGLE-3 reports a 1.38× throughput gain at batch size 64 in SGLang, so the line depends on the method and the cost of its guesses.
Failure. Symptom: p99 latency rises for all users at peak hours after the team turns speculation on. Measure B × (k + 1) against N* over the day. If peaks cross it, throttle k by B.
Chapter 10
Keep the terms, numbers, code and checks in one place
A decode step reads all the weights to make one token, so its arithmetic sits idle. Speculative decoding fills that idle arithmetic with guesses. The keep rule makes the output exact. Two numbers, α and c, decide the speedup, and the batch decides how much budget is left.
| Term | Meaning | Number to remember |
|---|---|---|
| Memory-bound step | Time set by reading weights, not by arithmetic | 7B on an A100: 7 ms, 0.64% of compute used |
| N* | Positions one pass can compute for the price of one | 156 on the A100 in 16-bit |
| Keep rule | Keep x with chance min(1, p(x) / q(x)); else redraw from the leftover | p = (0.5, 0.3, 0.2), q = (0.4, 0.4, 0.2): keep B 75% |
| α | Chance a guess is kept: the overlap Σ min(p, q) | 0.5 to 0.9 for drafts 100× smaller (Leviathan et al.) |
| E | Tokens per round: (1 − αk+1) / (1 − α) | α = 0.7, k = 4: 2.77 |
| S | Speedup: E / (1 + k c) | T5-small for T5-XXL: 3.2× predicted, 3.4× measured |
| Medusa | Extra heads on the target, a 64-node tree, typical acceptance | 2.2× (Medusa-1), 2.3 to 3.6× (Medusa-2) |
| EAGLE family | A one-layer draft on the target's hidden states | 2.7 to 3.5×; EAGLE-2 up to 4.26×; EAGLE-3 up to 6.5× |
| Lookahead | Jacobi window plus an n-gram pool; no draft | Up to 1.8× on MT-bench |
| Batch budget | B × (k + 1) ≤ N* | k = 4 fits up to 31 users |
pythonimport numpy as np def speculative_round(prefix, draft, target, k, rng): # 1. draft k tokens, one at a time; keep each draft distribution q_i (shape [V]) guesses, qs = [], [] for _ in range(k): q = draft(prefix + guesses) guesses.append(rng.choice(len(q), p=q)); qs.append(q) # 2. ONE target pass over prefix + guesses: k + 1 distributions, shape [k + 1, V] ps = target(prefix, guesses) out = [] for i, x in enumerate(guesses): p, q = ps[i], qs[i] if rng.random() < min(1.0, p[x] / q[x]): # the keep rule out.append(x) else: left = np.maximum(p - q, 0) # the leftover out.append(rng.choice(len(p), p=left / left.sum())) return out # correction ends the round out.append(rng.choice(len(ps[k]), p=ps[k])) # all kept: the bonus token return out def speedup(alpha, k, c): E = (1 - alpha ** (k + 1)) / (1 - alpha) return E / (1 + k * c) # speedup(0.75, 7, 0.02) = 3.16
Now press Present or Teach and explain from memory: why the step is memory-bound, the keep rule and its proof, and the speedup formula. Then go back to the race and predict the speedup before you move k.