Skip to content
LearnAI

4.6Speculative decoding & multi-token prediction

Let a cheap model guess several tokens ahead and have the big model check them all in one pass. With the right acceptance rule, the output distribution doesn't change at all.

⏱ 13 minAdvanced

Decoding leaves the GPU idle

As the KV cache lesson showed, generating one token at a time is memory-boundMemory-bound (vs compute-bound)A workload is memory-bound when its speed is limited by how fast data can be moved from memory, not by arithmetic. The deciding ratio is arithmetic intensity: FLOPs performed per byte moved.: every step streams all the model’s weights from memory to do very little arithmetic per byte. A useful consequence follows. Running the target model on 5 tokens at once costs barely more time than running it on 1, because the weights are read once either way and the extra arithmetic fits into otherwise idle compute.

That would be pointless if we had nothing to feed it: in autoregressiveAutoregressive generationGenerating one token at a time, appending each output to the input before predicting the next. generation, token 5 depends on token 4. But suppose someone guessed tokens 1 to 4 cheaply. The target could then check all the guesses in a single pass, because computing its predictions at every position of a known sequence is exactly what it does during prefill. Correct guesses are free tokens. That is speculative decodingSpeculative decodingA small draft model proposes several tokens and the large model verifies them in one pass. This speeds up generation without changing the output distribution., proposed independently by Leviathan et al. (2022) and Chen et al. (2023).

ANALOGY· A junior writer and a senior editor

A senior editor writes slowly but well; a junior writer is fast but less reliable. To speed things up, the junior drafts the next few sentences, and the editor reads the whole draft in one sitting. The editor keeps everything up to the first sentence they would have written differently, rewrites that one sentence their own way, and throws away the rest of the draft. Then the junior drafts again from there.

The junior is the draft model, the editor the target model, one reading session is one forward pass, and “the first sentence they’d change” is the first rejection. If the junior writes like the editor (high acceptance rate), whole drafts survive and the book gets written several times faster, and every page still reads exactly as if the editor wrote it alone.

The algorithm

Let qq be the draft model’s next-token distribution and pp the target’s. One round goes like this:

  1. Draft. The draft model generates kk tokens autoregressively, x1,…,xkx_1, \dots, x_k, remembering its probabilities q(xi)q(x_i). It’s small, so these kk steps are cheap.
  2. Verify. The target runs one forward pass over the context plus all kk drafts, producing its own distributions p1,…,pk+1p_1, \dots, p_{k+1} at every position at once.
  3. Accept or reject, left to right. Accept xix_i with probability min⁡ ⁣(1,pi(xi)/qi(xi))\min\!\big(1, p_i(x_i)/q_i(x_i)\big). If the target likes the token at least as much as the draft did, it is always accepted; if less, it’s accepted only sometimes.
  4. At the first rejection, discard xix_i and everything after it, and sample a replacement from the residual distribution norm(max⁡(0, pi−qi))\text{norm}\big(\max(0,\ p_i - q_i)\big): the probability mass the target wanted but the draft under-proposed.
  5. If all kk are accepted, sample one bonus token from pk+1p_{k+1}, which the verification pass computed for free.

Every round therefore yields between 1 and k+1k+1 tokens for one target pass. Even in the worst case, when the first draft is rejected, you still get one correct token, so you never do worse than ordinary decoding by more than the draft’s cost.

With greedy decoding (temperature 0), the rule simplifies: accept a draft token if and only if it equals the target’s top choice.

INTERACTIVEDraft and verify
Output so far (0 tokens in 0 target passes)
Press Play or Next round.
Round 1: the draft proposes 4 tokens, the target checks them in one pass
✓ accepted draft✕ first rejection (rest discarded)· resampled by target· bonus token (all accepted)
Target passes
0
plain decoding would need 0
Tokens per pass (observed)
–
Expected tokens per pass
2.77
(1 − α^(k+1)) / (1 − α)
Speedup at draft cost 0.05
2.31×
best k for this α: 6
0123412345678910k →expected tokens per target passspeedup after paying for k draft steps
The draft proposes k tokens (dashed); the target checks them all in one pass. Accepted tokens turn green, the first rejection is struck out and replaced by a token resampled from the target, and if everything is accepted the target adds a bonus token. Move α and k and compare observed tokens per pass with the formula and the speedup curve.

Things to try:

  1. α = 0.7, k = 4, press Play. Most rounds produce 2 to 4 tokens per target pass, and the observed average approaches the expected 2.77. (The demo uses a fixed acceptance probability α per token, the standard simplifying assumption in the analysis.)
  2. Drop α to 0.2. Most rounds now end at the first draft, yielding just the corrected token. With a nonzero draft cost the speedup falls below 1: speculation is slower than plain decoding.
  3. Raise α to 0.9 and sweep k. Longer drafts pay off when the draft is usually right. Notice the speedup curve peaks and then falls: past some point, extra draft steps cost more than the rare extra acceptances bring.
  4. Increase the draft cost. The best k shrinks. A draft model that is too big wastes the time it is supposed to save.

Why the output is exactly the target’s

The acceptance rule is a form of rejection sampling. For any token xx, the chance that it’s proposed and accepted is q(x)⋅min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x) \cdot \min(1, p(x)/q(x)) = \min(p(x), q(x)). The chance of a rejection at this position is 1−∑xmin⁡(p(x),q(x))1 - \sum_x \min(p(x), q(x)), and the residual distribution adds back exactly p(x)−min⁡(p(x),q(x))p(x) - \min(p(x), q(x)) to each token in that case. Sum the two routes and you get p(x)p(x). The Math Corner checks this with numbers.

So speculative decoding is lossless: it is not “a bit worse but faster”. The sampled text has the same distribution as the target sampling alone, regardless of how good or bad the draft is. The draft’s quality only affects speed.

How much faster?

If each draft token is accepted independently with probability α\alpha, a round with draft length kk produces on average

E[tokens per target pass]=1−αk+11−α.\mathbb{E}[\text{tokens per target pass}] = \frac{1 - \alpha^{k+1}}{1 - \alpha}.

With α=0.8\alpha = 0.8 and k=4k = 4 that’s about 3.4 tokens per pass. Accounting for the draft’s own cost, cc (the time of one draft step relative to one target pass), the speedup is roughly 1−αk+1(1−α)(1+kc)\frac{1-\alpha^{k+1}}{(1-\alpha)(1 + kc)}. The papers report real-world gains of about 2–3×: Leviathan et al. measured 2×–3× on T5-XXL, and Chen et al. 2–2.5× with Chinchilla 70B as the target.

The acceptance rate depends on how well the draft imitates the target and on the text. Boilerplate, code and repetitive structure are easy to guess; creative writing at high temperature is not. Speculation also helps most at small batch sizes: when a server already batches many requests, the GPU is busier, there is less idle compute to fill, and the gains shrink.

Choosing the draft is an engineering trade-off. It should share the target’s tokenizer (otherwise its tokens can’t be checked directly), be much cheaper per step, and imitate the target as closely as possible. A small model from the same family, often distilled from the target, is the classic choice. Many systems also verify a small tree of alternative drafts at once instead of a single chain, so that if the draft’s first guess is wrong its second guess might still be accepted, all within the same target pass.

Drafting without a separate model

Running and maintaining a second model is awkward, so several methods make the target draft for itself:

  • Medusa (Cai et al., 2024) adds a few extra output heads to the target, each predicting a token further ahead, and verifies several candidate continuations at once with a tree-shaped attention mask. The paper reports speedups of roughly 2.2× to 3.6×. Its optional “typical acceptance” scheme trades strict exactness for more accepted tokens.
  • EAGLE (Li et al., 2024) drafts at the level of the target’s internal features rather than tokens, using a small autoregressive head on top of the target’s second-to-last layer, and reports speedups around 3× on Llama-2-Chat models. Later versions refine the idea.
  • Simple n-gram or prompt-lookup drafts copy candidate continuations from the prompt itself, which works surprisingly well for editing and retrieval-heavy tasks.

Multi-token prediction

Multi-token predictionMulti-token prediction (MTP)Training a model to predict several future tokens at each position, which densifies the training signal and enables speculative decoding. (MTP) bakes drafting into training. Gloeckle et al. (2024) attach nn output heads to a shared trunk and train each to predict a different future token: the next one, the one after, and so on. Beyond the speed benefit, they found it a better training objective at scale for code: their 13B models solved 12% more HumanEval and 17% more MBPP problems than comparable next-token models. And the extra heads give free drafts: with 4-token prediction, the paper reports inference up to 3× faster via self-speculative decoding.

DeepSeek-V3 uses a sequential variant. Its MTP module is a small extra Transformer block that takes the main model’s representation at position tt together with the embedding of token t+1t+1, and predicts token t+2t+2, keeping the full causal chain rather than predicting from position tt alone. During training it densifies the learning signal. At inference it can be dropped, or used as a built-in draft model: the report gives an acceptance rate of about 85–90% for the second token and about 1.8× higher tokens per second.

MATH CORNER · optionalThe acceptance rule preserves p, and the expected tokens per pass

A three-token vocabulary. Let the target be p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2) over {A,B,C}\{A, B, C\} and the draft q=(0.7,0.2,0.1)q = (0.7, 0.2, 0.1). The draft over-proposes A.

tokenqqppaccept prob min⁡(1,p/q)\min(1, p/q)proposed and accepted min⁡(p,q)\min(p, q)residual max⁡(0,p−q)\max(0, p-q)
A0.70.50.7140.50
B0.20.310.20.1
C0.10.210.10.1

The acceptance probability at this position is ∑min⁡(p,q)=0.8\sum \min(p, q) = 0.8, so rejection happens with probability 0.2. The normalized residual is (0,0.5,0.5)(0, 0.5, 0.5). Final output probabilities:

P(A)=0.5+0.2⋅0=0.5,P(B)=0.2+0.2⋅0.5=0.3,P(C)=0.1+0.2⋅0.5=0.2,P(A) = 0.5 + 0.2 \cdot 0 = 0.5, \quad P(B) = 0.2 + 0.2 \cdot 0.5 = 0.3, \quad P(C) = 0.1 + 0.2 \cdot 0.5 = 0.2,

exactly pp. In general, min⁡(p,q)+(1−∑min⁡(p,q))⋅max⁡(0,p−q)∑max⁡(0,p−q)=p\min(p, q) + \big(1 - \sum \min(p,q)\big) \cdot \frac{\max(0, p-q)}{\sum \max(0, p-q)} = p, because ∑xmax⁡(0,p−q)=1−∑xmin⁡(p,q)\sum_x \max(0, p-q) = 1 - \sum_x \min(p,q).

Expected tokens per round. With per-token acceptance probability α\alpha, the round accepts exactly jj drafts and then rejects with probability αj(1−α)\alpha^j(1-\alpha) for j<kj < k, yielding j+1j + 1 tokens; it accepts all kk with probability αk\alpha^k, yielding k+1k + 1. Summing,

E=∑j=0k−1(j+1) αj(1−α)+(k+1) αk=1+α+α2+⋯+αk=1−αk+11−α.\mathbb{E} = \sum_{j=0}^{k-1} (j+1)\,\alpha^j (1-\alpha) + (k+1)\,\alpha^k = 1 + \alpha + \alpha^2 + \dots + \alpha^k = \frac{1-\alpha^{k+1}}{1-\alpha}.
α\alphak=2k=2k=4k=4k=8k=8limit k→∞k \to \infty
0.51.751.942.002
0.72.192.773.203.33
0.92.714.106.1310

The limit is 1/(1−α)1/(1-\alpha): even an infinitely long draft can’t beat it, which is why gains saturate.

In code

One round of speculative sampling. draft and target return next-token probability vectors; target.forward_all returns the target’s distributions at every drafted position in a single pass.

import torch

def speculative_round(prefix, draft, target, k=4):
    xs, qs, ctx = [], [], list(prefix)
    for _ in range(k):                              # 1. draft k tokens cheaply
        q = draft(ctx)
        x = torch.multinomial(q, 1).item()
        xs.append(x); qs.append(q); ctx.append(x)

    ps = target.forward_all(prefix, xs)             # 2. one pass: k+1 distributions

    out = []
    for i, x in enumerate(xs):                      # 3. accept left to right
        if torch.rand(()) < min(1.0, (ps[i][x] / qs[i][x]).item()):
            out.append(x)
        else:                                       # 4. resample from the residual
            resid = torch.clamp(ps[i] - qs[i], min=0)
            out.append(torch.multinomial(resid / resid.sum(), 1).item())
            return out
    out.append(torch.multinomial(ps[k], 1).item())  # 5. bonus token
    return out
COMMON MISCONCEPTIONS
  • “Speculative decoding trades quality for speed.” With the min(1, p/q) rule and residual resampling, the output distribution is exactly the target’s. Only the speed depends on the draft.
  • “It always makes generation faster.” With a low acceptance rate, an expensive draft or large batches that already keep the GPU busy, it can be neutral or even slower.
  • “You need a separate draft model.” Medusa heads, EAGLE, multi-token prediction modules and even n-gram lookup from the prompt can all serve as drafts.
  • “Verifying k tokens costs k target passes.” All k positions are scored in one forward pass, just like processing a prompt. That parallelism is the whole trick.

Check your understanding

0/5 answered
  1. Q1.Why does verifying k drafted tokens cost about the same wall-clock time as generating one token?

  2. Q2.The target assigns p(x) = 0.2 to a drafted token and the draft assigned q(x) = 0.5. What is the probability of accepting it?

  3. Q3.With acceptance rate α = 0.6 and draft length k = 3, what is the expected number of tokens per target pass?

  4. Q4.All k drafted tokens are accepted. What happens next in the round?

  5. Q5.How does DeepSeek-V3's multi-token prediction module differ from simply adding parallel heads that each predict a token further ahead?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.