Simple Algorithm
Deep Learning · Emergence · 26 min

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 γ\gamma drafted tokens costs about one decoding step of the large model when decoding is memory-bound, and how one pass yields γ+1\gamma+1 next-token distributions.
  • State the speculative sampling rule and prove that every emitted token follows the target distribution exactly; show that its acceptance probability ∑xmin⁡(p,q)=1−TV⁡(p,q)\sum_x\min(p,q)=1-\operatorname{TV}(p,q) is the best any exact rule with one draft can reach.
  • Derive the expected number of tokens per target pass, (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha), and the walltime speedup (1−αγ+1)/((1−α)(1+γc))(1-\alpha^{\gamma+1})/\big((1-\alpha)(1+\gamma c)\big), 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 γ+1\gamma+1 tokens instead of one multiplies the arithmetic by γ+1\gamma+1 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 γ\gamma guessed tokens returns γ+1\gamma+1 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 MpM_p, a draft model MqM_q and a draft length γ\gamma, one step of speculative decoding reads:

text
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 γ+1\gamma+1 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.

Check your understanding

Why does a single forward pass of the target over prefix+x1…xγ\text{prefix}+x_1\dots x_\gamma yield all of p1,…,pγ+1p_1,\dots,p_{\gamma+1}?

  1. The target runs γ+1\gamma+1 copies of itself in parallel
  2. Under the causal mask, the output at the position of xi−1x_{i-1} depends only on the prefix and x1,…,xi−1x_1,\dots,x_{i-1}, so it is exactly the next-token distribution given them
  3. The draft's distributions are reused as the target's
  4. The target predicts γ+1\gamma+1 tokens from its last position
Show the answer

B. Under the causal mask, the output at the position of xi−1x_{i-1} depends only on the prefix and x1,…,xi−1x_1,\dots,x_{i-1}, 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 i−1i-1 is p(⋅∣prefix,x<i)p\big(\cdot\mid\text{prefix},x_{<i}\big) whatever tokens follow it, so all γ+1\gamma+1 conditionals come out of one pass, at the price of processing γ+1\gamma+1 tokens instead of one.

Exactness, and why it cannot be beaten

DerivationProof
  1. P(draft x, accept)=min⁡(q(x),p(x)),P(accept)=∑xmin⁡(p(x),q(x))=βP(\text{draft }x,\ \text{accept})=\min\big(q(x),p(x)\big),\qquad P(\text{accept})=\sum_x\min\big(p(x),q(x)\big)=\beta

    Token xx is drafted and accepted with probability q(x)min⁡(1,p(x)/q(x))q(x)\min\big(1,p(x)/q(x)\big):

  2. ∑x(p(x)−q(x))+=∑x(p(x)−min⁡(p(x),q(x)))=1−β\sum_x\big(p(x)-q(x)\big)_+=\sum_x\Big(p(x)-\min\big(p(x),q(x)\big)\Big)=1-\beta

    The positive part satisfies (p−q)+=p−min⁡(p,q)(p-q)_+=p-\min(p,q), so its total mass is 1−β1-\beta, exactly the probability of a rejection, and rr is well defined whenever a rejection can happen:

  3. P(emit x)=min⁡(p(x),q(x))+(1−β) p(x)−min⁡(p(x),q(x))1−β=p(x)P(\text{emit }x)=\min\big(p(x),q(x)\big)+(1-\beta)\,\frac{p(x)-\min\big(p(x),q(x)\big)}{1-\beta}=p(x)

    Add the two ways of emitting xx:

  4. For a whole step apply this position by position. Given the prefix and the drafts accepted so far, position ii uses exactly the conditionals pip_i and qiq_i, so each emitted token follows the target's conditional given the tokens before it, and the bonus token is drawn from pγ+1p_{\gamma+1} 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 p=(0.6,0.3,0.1)p=(0.6,0.3,0.1) and q=(0.3,0.3,0.4)q=(0.3,0.3,0.4), β=0.7\beta=0.7 and the residual is (0.3,0,0)/0.3(0.3,0,0)/0.3: a rejection always emits the first token, the one the draft under-proposes. Resampling from pp after a rejection would give min⁡(p,q)+0.3 p=(0.48,0.39,0.13)\min(p,q)+0.3\,p=(0.48,0.39,0.13) instead. Temperature, top-kk and top-pp change nothing in the argument: apply the same transformation to both models' outputs, and pp and qq become the adjusted distributions. In floating point the guarantee holds up to rounding, which Chen et al. call exactness "within hardware numerics".

python
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 q

A Monte Carlo check of the theorem on the example above: although the draft proposes from qq, the emitted token's frequencies match pp to within sampling error.

Tokens per pass, and the speedup

How much does one step produce? Leviathan et al. define the acceptance rate α=E[β]\alpha=\E[\beta], the average of ∑xmin⁡(p,q)\sum_x\min(p,q) over contexts, and assume, as a simplification, that successive drafted tokens are accepted independently, each with probability α\alpha.

DerivationTokens per target pass, and walltime
  1. P(N≥i)=αi(0≤i≤γ)P(N\ge i)=\alpha^{i}\qquad(0\le i\le\gamma)

    The number NN of accepted drafts is a geometric count capped at γ\gamma: draft ii counts only if drafts 1,…,i1,\dots,i are all accepted.

  2. E[N+1]=1+∑i=1γP(N≥i)=∑i=0γαi=1−αγ+11−α\E[N+1]=1+\sum_{i=1}^{\gamma}P(N\ge i)=\sum_{i=0}^{\gamma}\alpha^{i}=\frac{1-\alpha^{\gamma+1}}{1-\alpha}

    Every step emits N+1N+1 tokens: the accepted drafts plus the resampled or bonus token. The mean of a nonnegative integer variable is the sum of its tail probabilities:

  3. S(γ)=1−αγ+1(1−α)(1+γc)S(\gamma)=\frac{1-\alpha^{\gamma+1}}{(1-\alpha)(1+\gamma c)}

    As γ→∞\gamma\to\infty this approaches 1/(1−α)1/(1-\alpha): an acceptance rate of 0.8 can at best quintuple the tokens per pass. Let cc be the time of one draft step relative to one target step, and assume that the target scores γ+1\gamma+1 tokens in the time of one. A speculative step then costs 1+γc1+\gamma c target steps, and the expected speedup in walltime is (Leviathan et al., 2023):

  4. FLOPs with speculationFLOPs without=(1−α)(γc^+γ+1)1−αγ+1\frac{\text{FLOPs with speculation}}{\text{FLOPs without}}=\frac{(1-\alpha)(\gamma\hat c+\gamma+1)}{1-\alpha^{\gamma+1}}

    At γ=1\gamma=1 this is (1+α)/(1+c)(1+\alpha)/(1+c), so speculation helps whenever α>c\alpha>c; the best γ\gamma balances more accepted tokens against more draft passes. Speculation does cost arithmetic, because rejected drafts were scored for nothing: with c^\hat c the draft's FLOPs per token relative to the target's, total FLOPs grow by

Predict before you look

With acceptance rate α=0.8\alpha=0.8 and draft length γ=4\gamma=4, how many tokens does one target pass produce on average?

Show the answer

3.36 tokens

(1−0.85)/(1−0.8)=(1−0.32768)/0.2=3.3616(1-0.8^5)/(1-0.8)=(1-0.32768)/0.2=3.3616. With a draft step costing c=0.05c=0.05 of a target step the speedup is 3.36/(1+4×0.05)=2.803.36/(1+4\times0.05)=2.80; drafting 8 tokens would raise it to about 3.09 before the draft's own cost wins. The arithmetic, with c^=0.05\hat c=0.05, grows by a factor of about 1.55.

Acceptance rate α\alphac=0.01c=0.01c=0.05c=0.05c=0.1c=0.1
0.6γ=7\gamma=7: 2.30×γ=4\gamma=4: 1.92×γ=3\gamma=3: 1.67×
0.8γ=14\gamma=14: 4.23×γ=8\gamma=8: 3.09×γ=6\gamma=6: 2.47×
0.9γ=24\gamma=24: 7.49×γ=13\gamma=13: 4.67×γ=10\gamma=10: 3.43×
The best draft length and its speedup from S(γ)S(\gamma), under its assumptions: independent acceptances, and γ+1\gamma+1 tokens verified in the time of one. The second assumption fails for long drafts, which is one reason practical drafts propose only a handful of tokens.

Measurements match the model. With T5-XXL (11 billion parameters) as target and T5-small (77 million) as draft, Leviathan et al. measured α=0.75\alpha=0.75 and a 3.4-fold speedup for greedy translation at γ=7\gamma=7, and α=0.62\alpha=0.62 with a 2.6-fold speedup when sampling at temperature 1; the formula with c→0c\to0 gives 3.6 and 2.6. Drafts a couple of orders of magnitude smaller than their targets gave α\alpha 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, α\alpha and cc, 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 KK small heads on the target's last hidden state, head kk predicting the token k+1k+1 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.

python
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 γ+1\gamma+1 tokens costs about as much as scoring one. Batching erodes the assumption. With BB sequences per step the weight matrices already run at an intensity of about BB, and speculation multiplies the tokens per step by up to γ+1\gamma+1; once B(γ+1)B(\gamma+1) 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 γ+1\gamma+1 ordinary ones, and the speedup becomes E[N+1]/(γ+1)<1\E[N+1]/(\gamma+1)<1: 0.67 for α=0.8\alpha=0.8 and γ=4\gamma=4. 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 γ+1\gamma+1. 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 γ+1\gamma+1 tokens about as costly as scoring one, and one causal pass over the prefix plus γ\gamma drafts returns all γ+1\gamma+1 next-token distributions.
  • Accepting each draft xx with probability min⁡(1,p(x)/q(x))\min\big(1,p(x)/q(x)\big) and resampling the first rejection from (p−q)+(p-q)_+ makes every emitted token follow pp exactly; the acceptance probability ∑xmin⁡(p,q)=1−TV⁡(p,q)\sum_x\min(p,q)=1-\operatorname{TV}(p,q) is the best any exact single-draft rule can reach, a maximal coupling.
  • With independent acceptances at rate α\alpha, a pass yields (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha) tokens (3.36 for α=0.8\alpha=0.8, γ=4\gamma=4, never more than 1/(1−α)1/(1-\alpha)), and walltime improves by that factor over 1+γc1+\gamma c; measured gains were 3.4-fold for T5-XXL and 2–2.5-fold for Chinchilla.
  • Better drafts raise α\alpha or cut cc: 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.

Question 1

A drafted token is rejected. Why must the replacement be drawn from (p−q)+(p-q)_+ renormalized rather than from pp itself?

  1. Drawing from pp would be slower
  2. Drawing from pp could return the rejected token
  3. Accepted drafts already supply min⁡(p,q)\min(p,q) of each token's probability; only the residual p−min⁡(p,q)p-\min(p,q) is missing, and drawing from pp would over-represent tokens the draft already proposes
  4. The residual has lower entropy, which improves quality
Show the answer

C. Accepted drafts already supply min⁡(p,q)\min(p,q) of each token's probability; only the residual p−min⁡(p,q)p-\min(p,q) is missing, and drawing from pp would over-represent tokens the draft already proposes

The emitted token has probability min⁡(p,q)+(1−β) r\min(p,q)+(1-\beta)\,r. With rr the normalized residual this is exactly pp; with r=pr=p it is min⁡(p,q)+(1−β)p\min(p,q)+(1-\beta)p, which for p=(0.6,0.3,0.1)p=(0.6,0.3,0.1) and q=(0.3,0.3,0.4)q=(0.3,0.3,0.4) gives (0.48,0.39,0.13)(0.48,0.39,0.13).

Question 2

A draft has acceptance rate α=0.6\alpha=0.6 and proposes γ=3\gamma=3 tokens per step. Under the independence assumption, how many tokens does each target pass produce on average?

  1. About 2.18
  2. 1.8
  3. 2.8
  4. 4
Show the answer

A. About 2.18

(1−0.64)/(1−0.6)=(1−0.1296)/0.4=2.176(1-0.6^4)/(1-0.6)=(1-0.1296)/0.4=2.176: one token always, plus 0.6+0.36+0.2160.6+0.36+0.216 expected accepted drafts. Even infinitely long drafts would give at most 1/(1−0.6)=2.51/(1-0.6)=2.5.

Question 3

For a single drafted token, what is the highest acceptance probability that any verification rule can reach while keeping the output distributed exactly as pp?

  1. 11, with a clever enough rule
  2. ∑xmin⁡(p(x),q(x))=1−TV⁡(p,q)\sum_x\min\big(p(x),q(x)\big)=1-\operatorname{TV}(p,q)
  3. ∑xp(x) q(x)\sum_xp(x)\,q(x)
  4. max⁡xmin⁡(p(x),q(x))\max_x\min\big(p(x),q(x)\big)
Show the answer

B. ∑xmin⁡(p(x),q(x))=1−TV⁡(p,q)\sum_x\min\big(p(x),q(x)\big)=1-\operatorname{TV}(p,q)

For any coupling of the draft X∼qX\sim q and the output Y∼pY\sim p, P(X=Y)=∑xP(X=x,Y=x)≤∑xmin⁡(q(x),p(x))P(X=Y)=\sum_xP(X=x,Y=x)\le\sum_x\min\big(q(x),p(x)\big), and speculative sampling attains it. Higher acceptance needs several drafts per position, trees, or giving up exactness.

Question 4

A server decodes 256 short-context sequences per step, and its target model is close to compute-bound. What does speculative decoding with γ=4\gamma=4 and α=0.8\alpha=0.8 do?

  1. It speeds up generation about 3.4-fold, as at batch 1
  2. It speeds up generation, because verification is always free
  3. Nothing at all: the batch hides the draft's cost
  4. 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 γ+1\gamma+1 tokens cost one target step. When the step is compute-bound they cost about γ+1\gamma+1 steps, so the ratio falls to about 3.36/5≈0.673.36/5\approx0.67. 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).