All courses

Speculative decoding

Let a cheap draft model propose several tokens and have the big model verify them in one pass. Explain the accept/reject rule that keeps the output distribution exactly the big model's.

Builds on: Prefill vs decode: compute- vs memory-bound

▶ Watch this lesson Start the whole course

What the animation says

Why guess ahead?

When a big model writes, every new token means streaming all its weights in from memory. The maths per token is tiny by comparison: about two operations per parameter. The chip mostly waits on memory. So scoring five tokens in one pass reads the weights once, just like scoring one. The catch: each token needs the one before it. Generation is a chain. Suppose five guessed tokens were already lying around. Checking all five in one pass costs how much, compared to one?

Draft guesses, big model checks

About the same. So who makes the guesses? A draft model: same tokenizer, maybe fifty times smaller. It writes four tokens, one at a time. That's cheap. Then the big model runs one pass on the last token plus all four drafts, giving its own prediction at five positions. Left to right, it keeps or rejects each draft. At the first rejection, it puts in a corrected token and throws away the rest. Now suppose all four drafts survive. How many tokens does this pass commit?

The keep-or-reject rule

Five, thanks to a free bonus token. Now the keep-or-reject rule at one position, with three tokens: A, B, C. The big model gives A point six, B point three, C point one. The draft swaps A and B. The draft proposes B. Keep it with chance big over draft: point three over point six, one half. Proposed A or C? Always kept: the ratio is at least one. If B is rejected, the replacement comes only from where the big model wants more than the draft. Tap it.

Why the output is exact

Only A has a gap: point six minus point three. So a rejected B always becomes A. Now total it up. A: proposed directly, point three, always kept. Plus B proposed, point six, rejected half the time, turning into A: another point three. That makes point six. B: point six times one half, point three. C: point one. Exactly the big model's numbers, though every guess came from the draft. Here the draft is kept seventy percent of the time. Now swap in a worse draft. What changes?

Run it, and remember

Only speed. Here's the rule in code. The draft proposes; this line keeps it with chance big over draft. Otherwise, these two lines take the gap, clip it at zero, normalise, and sample the fix. Run it a hundred thousand times: point six, point three, point one. The big model's distribution. With greedy decoding it's simpler: keep a draft only if it matches the big model's top choice. At acceptance point eight with four drafts, a pass yields about three point three tokens, if acceptances are independent.

Can the big model emit several tokens per pass?

Decode is memory-bound: each step streams every weight (and the KV cache) from memory to do only about $2N$ FLOPs per token. Scoring 5 tokens in one pass reads those weights once, so it costs barely more than scoring 1. But generation is sequential, because token $t+1$ needs token $t$. Can we guess ahead cheaply and let the big model check all the guesses in one pass, without changing a single probability of its output?

Draft guesses, big model checks

A **draft model** is a small model with the same tokenizer, for example 50× fewer parameters. It generates $\gamma$ tokens one by one, which is cheap. The big model then runs **one** pass on the last committed token plus the $\gamma$ drafts, reusing its KV cache. This gives its own next-token distribution at $\gamma+1$ positions. Going left to right, it keeps or rejects each draft. At the first rejection it substitutes a corrected token and discards the rest, including their KV entries. If every draft survives, the last distribution yields a free **bonus token**. So each big pass commits 1 to $\gamma+1$ tokens.

The accept/reject rule

At one position, let $p(x)=p_\theta(x\mid x_{\le t})$ (big model) and $q(x)$ (draft, same prefix). The draft sampled $x\sim q$. - Accept with probability $\min(1,\,p(x)/q(x))$. - If rejected, sample from the **residual distribution** $\text{res}(x)=\frac{\max(0,p(x)-q(x))}{\sum_y\max(0,p(y)-q(y))}$. Why this is exact: - Proposing and accepting $x$ has probability $q(x)\min(1,p(x)/q(x))=\min(p(x),q(x))$. - The total rejection probability is $1-\sum_y\min(p,q)$, which equals the normaliser. So the rejection branch adds exactly $\max(0,p(x)-q(x))$. Together, $P(\text{out}=x)=\min(p,q)+\max(0,p-q)=p(x)$. The acceptance rate is $\alpha=\sum_y\min(p(y),q(y))$.

Three tokens, checked by hand

Tokens A, B, C have $p=(0.6,0.3,0.1)$ and $q=(0.3,0.6,0.1)$. The draft proposes B, which is accepted with probability $0.3/0.6=0.5$. The residual is $\max(0,p-q)=(0.3,0,0)$, so a rejection always yields A. Check over all draft outcomes: - $P(A)=0.3\cdot1+0.6\cdot0.5=0.6$ ✓ - $P(B)=0.6\cdot0.5=0.3$ ✓ - $P(C)=0.1\cdot1=0.1$ ✓ The acceptance rate is $\alpha=0.3+0.3+0.1=0.7$.

Simulate one verify step

This runs the rule 100,000 times on the example. The output frequencies match the big model's $p$, even though every proposal came from the draft's $q$.
import numpy as np
rng = np.random.default_rng(0)
p = np.array([0.6, 0.3, 0.1])   # big model
q = np.array([0.3, 0.6, 0.1])   # draft model
def step():
    x = rng.choice(3, p=q)                    # draft proposes
    if rng.random() < min(1, p[x] / q[x]):
        return x                              # accept
    res = np.maximum(p - q, 0)
    return rng.choice(3, p=res / res.sum())   # corrected token
out = [step() for _ in range(100_000)]
print(np.bincount(out) / len(out))  # ~ [0.6 0.3 0.1]

Remember

The draft guesses; the big model checks all guesses in one memory-bound pass. Accept each with probability $\min(1,p/q)$, otherwise resample from normalised $\max(0,p-q)$. The output is exactly the big model's distribution, and only the speed depends on draft quality. If you always pick the most likely token, this becomes: keep a draft only if it matches the big model's top token. If acceptances were independent, expected tokens per pass $\approx\frac{1-\alpha^{\gamma+1}}{1-\alpha}$ (for $\alpha=0.8$, $\gamma=4$, that is 3.36).

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.