Speculative Decoding
Drafting tokens cheaply and verifying them exactly.
A large model generating text one token at a time spends most of each step reading its weights, and having read them, it could score five tokens about as fast as one. Speculative decoding turns that slack into speed: guess several tokens with something cheap, check them all in one pass of the large model, and keep the longest acceptable prefix. A carefully chosen acceptance rule makes the output distribution exactly the large model's, so the speedup costs nothing in quality.
What you’ll learn
- Explain why verifying drafted tokens costs about one decoding step of the large model when decoding is memory-bound, and how one pass yields next-token distributions.
- State the speculative sampling rule and prove that every emitted token follows the target distribution exactly; show that its acceptance probability is the best any exact rule with one draft can reach.
- Derive the expected number of tokens per target pass, , and the walltime speedup , and choose the draft length.
- Compare drafting strategies (small models, distillation, extra heads, feature-level drafts, early exits, trees) and explain when speculation stops paying, and why long contexts change that.
One pass, many tokens
A decoding step of a large model is memory-bound: the weights and the cache are read once per step at about one FLOP per byte (Efficient Transformers). Feeding tokens instead of one multiplies the arithmetic by but reads the same weights, so as long as the step stays well below the ridge it takes about the same time. And one causal forward pass over a prefix extended by guessed tokens returns next-token distributions, one at every new position, exactly as in training.
So if something cheap could guess the next few tokens, the large model could check them all in one pass. Stern, Shazeer and Uszkoreit (2018) did this for greedy decoding with blockwise parallel decoding: extra heads propose several tokens, and the model keeps the longest prefix that agrees with its own greedy choices. Leviathan, Kalman and Matias (2023) and, independently, Chen et al. (2023) extended the idea to sampling, with a rejection rule that keeps the output distribution exact. With a target model , a draft model and a draft length , one step of speculative decoding reads:
SPECULATIVE-STEP(prefix) // target M_p, draft M_q, draft length γ
for i = 1 … γ: // draft autoregressively: γ cheap passes
q_i ← M_q(prefix + x_1 … x_{i−1}); x_i ~ q_i
p_1 … p_{γ+1} ← M_p(prefix + x_1 … x_γ) // ONE target pass gives γ+1 distributions
for i = 1 … γ:
with probability min(1, p_i(x_i) / q_i(x_i)): accept x_i
otherwise: emit y ~ normalize(max(0, p_i − q_i)) and stop
if all γ were accepted: emit a bonus token y ~ p_{γ+1}Each step emits between 1 and tokens, and the target's cache is cut back to what was emitted. At temperature 0 both distributions are one-hot, and the rule reduces to keeping drafted tokens while they equal the target's greedy choices.
Why does a single forward pass of the target over yield all of ?
- The target runs copies of itself in parallel
- Under the causal mask, the output at the position of depends only on the prefix and , so it is exactly the next-token distribution given them
- The draft's distributions are reused as the target's
- The target predicts tokens from its last position
Show the answer
B. Under the causal mask, the output at the position of depends only on the prefix and , so it is exactly the next-token distribution given them
This is the property that lets a decoder train on every position of a sequence at once. The output at position is whatever tokens follow it, so all conditionals come out of one pass, at the price of processing tokens instead of one.
Exactness, and why it cannot be beaten
Token is drafted and accepted with probability :
The positive part satisfies , so its total mass is , exactly the probability of a rejection, and is well defined whenever a rejection can happen:
Add the two ways of emitting :
For a whole step apply this position by position. Given the prefix and the drafts accepted so far, position uses exactly the conditionals and , so each emitted token follows the target's conditional given the tokens before it, and the bonus token is drawn from directly. By the chain rule, the emitted sequence has the target's distribution, whatever the draft.
The residual is what makes the rule exact. For and , and the residual is : a rejection always emits the first token, the one the draft under-proposes. Resampling from after a rejection would give instead. Temperature, top- and top- change nothing in the argument: apply the same transformation to both models' outputs, and and become the adjusted distributions. In floating point the guarantee holds up to rounding, which Chen et al. call exactness "within hardware numerics".
import torch
def verify(p, q, draft):
"""One speculative step. p: (g+1, V) target distributions at the g+1 positions, from one parallel pass;
q: (g, V) draft distributions; draft: (g,) drafted tokens. Returns the tokens to append."""
out = []
for i, x in enumerate(draft.tolist()):
if torch.rand(()) < p[i, x] / q[i, x]: # accept with probability min(1, p/q)
out.append(x)
else: # reject: resample from (p - q)+, normalized
r = torch.clamp(p[i] - q[i], min=0)
out.append(torch.multinomial(r / r.sum(), 1).item())
return out
out.append(torch.multinomial(p[-1], 1).item()) # every draft accepted: one bonus token from p
return out
p1, q1 = torch.tensor([0.6, 0.3, 0.1]), torch.tensor([0.3, 0.3, 0.4])
first = torch.zeros(3)
for _ in range(100_000):
x = torch.multinomial(q1, 1) # the draft proposes one token
first[verify(torch.stack([p1, p1]), q1[None], x)[0]] += 1
assert torch.allclose(first / first.sum(), p1, atol=0.01) # the emitted token follows p, not qA Monte Carlo check of the theorem on the example above: although the draft proposes from , the emitted token's frequencies match to within sampling error.
Tokens per pass, and the speedup
How much does one step produce? Leviathan et al. define the acceptance rate , the average of over contexts, and assume, as a simplification, that successive drafted tokens are accepted independently, each with probability .
The number of accepted drafts is a geometric count capped at : draft counts only if drafts are all accepted.
Every step emits tokens: the accepted drafts plus the resampled or bonus token. The mean of a nonnegative integer variable is the sum of its tail probabilities:
As this approaches : an acceptance rate of 0.8 can at best quintuple the tokens per pass. Let be the time of one draft step relative to one target step, and assume that the target scores tokens in the time of one. A speculative step then costs target steps, and the expected speedup in walltime is (Leviathan et al., 2023):
At this is , so speculation helps whenever ; the best balances more accepted tokens against more draft passes. Speculation does cost arithmetic, because rejected drafts were scored for nothing: with the draft's FLOPs per token relative to the target's, total FLOPs grow by
With acceptance rate and draft length , how many tokens does one target pass produce on average?
Show the answer
3.36 tokens
. With a draft step costing of a target step the speedup is ; drafting 8 tokens would raise it to about 3.09 before the draft's own cost wins. The arithmetic, with , grows by a factor of about 1.55.
| Acceptance rate | |||
|---|---|---|---|
| 0.6 | : 2.30× | : 1.92× | : 1.67× |
| 0.8 | : 4.23× | : 3.09× | : 2.47× |
| 0.9 | : 7.49× | : 4.67× | : 3.43× |
Measurements match the model. With T5-XXL (11 billion parameters) as target and T5-small (77 million) as draft, Leviathan et al. measured and a 3.4-fold speedup for greedy translation at , and with a 2.6-fold speedup when sampling at temperature 1; the formula with gives 3.6 and 2.6. Drafts a couple of orders of magnitude smaller than their targets gave between 0.5 and 0.9 across their tasks, higher for sharper distributions. Chen et al. sped up sampling from the 70-billion-parameter Chinchilla 2–2.5-fold with a 4-billion-parameter draft trained for the purpose.
Better drafts: heads, features, early exits and trees
The speedup depends on two numbers, and , and every refinement moves one of them.
- Align the draft. A draft distilled from the target matches it better. DistillSpec (Zhou et al., 2024) trains the draft on text the draft itself generates and chooses the divergence to suit the task and the decoding strategy, for speedups 10–45% above standard speculative decoding (Knowledge Distillation).
- Heads instead of a model. Medusa (Cai et al., 2024) adds small heads on the target's last hidden state, head predicting the token positions ahead, so drafting costs almost nothing and needs no separate model. With the backbone frozen (Medusa-1) it exceeded a 2.2-fold speedup; training heads and backbone together (Medusa-2) gave 2.3–2.8-fold. Medusa also offers a "typical acceptance" rule that keeps any candidate the target finds plausible enough, which helps at higher temperatures but is no longer exact.
- Draft in feature space. EAGLE (Li, Wei, Zhang & Zhang, 2024) drafts at the level of the target's second-to-top-layer features: a small network predicts the next feature vector from the current ones together with the token sequence advanced by one step, which resolves the uncertainty about which token was sampled. That network is one transformer decoder layer, after a linear layer that fuses each feature with the embedding of the next token, and it reuses the target's embedding and output layers; for LLaMA2-Chat 70B it has under a billion parameters. EAGLE keeps the output distribution exact and reported 2.7–3.5-fold latency speedups for LLaMA2-Chat 70B. EAGLE-2 (Li et al., 2024) found that acceptance depends on the context, not only on the position in the draft, and shapes its draft tree on the fly from the draft's confidence, which tracks acceptance well.
- Draft with the target itself. Skipping some intermediate layers gives a cheap draft with no extra parameters and no training (Draft & Verify: Zhang et al., 2024, up to 1.99-fold on LLaMA-2 models). LayerSkip (Elhoushi et al., 2024) trains with layer dropout and an early-exit loss, so that the early layers draft and the remaining layers verify, reusing the computation they share, for up to 2.16-fold on summarization. Heads trained during pretraining to predict several future tokens serve the same purpose (Beyond Left-to-Right: Multi-Token & Diffusion LMs).
- No separate draft at all. Lookahead decoding (Fu, Bailis, Stoica & Zhang, 2024) needs neither a draft model nor a data store. It spends extra FLOPs in every step: Jacobi (fixed-point) iterations over a window of future positions produce candidate n-grams, which are kept in a pool, and candidates from the pool are verified in the same forward pass. It reported up to 1.8-fold speedups on MT-bench and 4-fold with several GPUs on code completion.
Trees. Instead of one chain of drafts, propose a tree: several candidates for the next token, each with its own continuations. The target verifies every branch in one pass by placing the tree's tokens after the prefix with a tree attention mask, in which each node attends to the prefix and to its own ancestors only, with positions set by depth. SpecInfer (Miao et al., 2024) merges trees from several small draft models and verifies them with a multi-step speculative sampling rule that preserves the target's distribution and rejects no more often than drawing from the target and checking whether the draw is in the tree; it reported 1.5–2.8-fold speedups for distributed serving and 2.6–3.5-fold for offloading-based inference.
import torch
def tree_mask(parents):
"""parents[i]: the draft-tree node that node i continues, or -1 if it directly follows the prefix.
Returns which tree nodes each node may attend to; every node also sees the whole prefix."""
n = len(parents)
mask = torch.zeros(n, n, dtype=torch.bool)
for i in range(n):
j = i
while j != -1: # a node sees itself and its ancestors, nothing else
mask[i, j] = True
j = parents[j]
return mask
# two candidates for the next token (nodes 0, 1), each followed by two candidates (nodes 2-5)
mask = tree_mask([-1, -1, 0, 0, 1, 1])
depth = mask.sum(dim=1) - 1 # position offset of each node after the prefix
assert depth.tolist() == [0, 0, 1, 1, 1, 1]
assert mask[4].tolist() == [False, True, False, False, True, False]Six tree tokens verified in one pass cover four candidate continuations of length two. Node 4 sees only node 1 and itself (plus the prefix), so its output is exactly the target's distribution after "prefix, node 1, node 4"; the depths give the positions its position encoding uses.
When speculation stops paying
Every speedup above assumes that the target's step is memory-bound, so that scoring tokens costs about as much as scoring one. Batching erodes the assumption. With sequences per step the weight matrices already run at an intensity of about , and speculation multiplies the tokens per step by up to ; once approaches the ridge, verification costs real time, and the FLOPs spent on rejected drafts are paid in full. In the limit of a compute-bound target a speculative step costs about ordinary ones, and the speedup becomes : 0.67 for and . Speculation therefore pays most at low load and can hurt at high load.
Long contexts change the picture again. At large batches with long contexts, each sequence's cache reads dominate the step (Serving Language Models), and they are the same whether the sequence brings one query or . MagicDec (Sadhukhan et al., 2025) identified a critical sequence length beyond which speculative decoding speeds up even large batches, with gains that grow with the batch size, and drafted with a sparse cache rather than with smaller weights, keeping only part of the context in the style of StreamingLLM. For moderate to long sequences they reported speedups of up to 2.51-fold for LLaMA-3.1-8B at batch sizes from 32 to 256.
Key takeaways
- Memory-bound decoding makes scoring tokens about as costly as scoring one, and one causal pass over the prefix plus drafts returns all next-token distributions.
- Accepting each draft with probability and resampling the first rejection from makes every emitted token follow exactly; the acceptance probability is the best any exact single-draft rule can reach, a maximal coupling.
- With independent acceptances at rate , a pass yields tokens (3.36 for , , never more than ), and walltime improves by that factor over ; measured gains were 3.4-fold for T5-XXL and 2–2.5-fold for Chinchilla.
- Better drafts raise or cut : distilled draft models, Medusa heads, EAGLE's feature-level drafts, layer skipping and early exits, and trees of candidates verified in one pass with a tree attention mask.
- Speculation pays while the target is memory-bound. At large batches with short contexts it can slow decoding down; at long contexts, where cache reads dominate, its gains return.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A drafted token is rejected. Why must the replacement be drawn from renormalized rather than from itself?
- Drawing from would be slower
- Drawing from could return the rejected token
- Accepted drafts already supply of each token's probability; only the residual is missing, and drawing from would over-represent tokens the draft already proposes
- The residual has lower entropy, which improves quality
Show the answer
C. Accepted drafts already supply of each token's probability; only the residual is missing, and drawing from would over-represent tokens the draft already proposes
The emitted token has probability . With the normalized residual this is exactly ; with it is , which for and gives .
A draft has acceptance rate and proposes tokens per step. Under the independence assumption, how many tokens does each target pass produce on average?
- About 2.18
- 1.8
- 2.8
- 4
Show the answer
A. About 2.18
: one token always, plus expected accepted drafts. Even infinitely long drafts would give at most .
For a single drafted token, what is the highest acceptance probability that any verification rule can reach while keeping the output distributed exactly as ?
- , with a clever enough rule
Show the answer
B.
For any coupling of the draft and the output , , and speculative sampling attains it. Higher acceptance needs several drafts per position, trees, or giving up exactness.
A server decodes 256 short-context sequences per step, and its target model is close to compute-bound. What does speculative decoding with and do?
- It speeds up generation about 3.4-fold, as at batch 1
- It speeds up generation, because verification is always free
- Nothing at all: the batch hides the draft's cost
- It can slow generation down: each step now costs up to 5 times more compute while yielding about 3.4 tokens per sequence
Show the answer
D. It can slow generation down: each step now costs up to 5 times more compute while yielding about 3.4 tokens per sequence
The speedup formula assumes that tokens cost one target step. When the step is compute-bound they cost about steps, so the ratio falls to about . At long contexts cache reads dominate again, and speculation can pay even at large batches (Sadhukhan et al., 2025).
Further reading
- Y. Leviathan, M. Kalman & Y. Matias, "Fast inference from transformers via speculative decoding," ICML (2023).
- C. Chen, S. Borgeaud, G. Irving, J.-B. Lespiau, L. Sifre & J. Jumper, "Accelerating large language model decoding with speculative sampling," arXiv:2302.01318 (2023).
- Z. Sun, A. T. Suresh, J. H. Ro, A. Beirami, H. Jain & F. Yu, "SpecTr: Fast speculative decoding via optimal transport," NeurIPS (2023).
- T. Cai, Y. Li, Z. Geng, H. Peng, J. D. Lee, D. Chen & T. Dao, "Medusa: Simple LLM inference acceleration framework with multiple decoding heads," ICML (2024).
- Y. Li, F. Wei, C. Zhang & H. Zhang, "EAGLE: Speculative sampling requires rethinking feature uncertainty," ICML (2024).
- H. Xia et al., "Unlocking efficiency in large language model inference: A comprehensive survey of speculative decoding," Findings of ACL (2024).