Speculative Decoding: Lossless Multi-Token Generation

Draft several tokens with a fast model, score all the draft prefixes with the target model in one parallel pass, then use modified rejection sampling so the output distribution matches the target model's.

Advanced · Undergraduate mathematics · about 18 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

Speculative decoding has a large model accept several tokens per forward pass while still sampling from its own distribution. We compare draft length, acceptance rate, and the mismatch between draft and target distributions, and work one example of the predicted speedup. Ordinary decoding needs one pass of the large model per token, and each pass must wait for the previous token. For a large model at small batch sizes, each pass is limited by reading the weights from memory, not by arithmetic, so scoring several positions in one pass costs about as much time as scoring one (see the LLM serving page).

Speculative decoding uses that spare capacity by splitting the work into two roles (Leviathan et al., 2023; Chen et al., 2023):

  • a fast draft model proposes a chunk of kk next tokens,
  • the expensive target model scores the prompt plus each draft prefix in parallel.

In the full algorithm, the target produces k+1k+1 next-token distributions: one for the current prefix, one after each draft prefix, and an extra distribution that can supply a new target token if every draft token is accepted. If draft tokens pass the target/draft probability-ratio checks, you accept a prefix of the draft and "skip ahead" in the sequence. If one fails, you reject at the first failed token and replace it with a sample from a residual distribution, so the target distribution is preserved. The method is lossless in this sense: the generated text has exactly the distribution you would get by sampling from the target model alone, up to floating-point rounding.

The gain is in the system, not the model: fewer sequential passes of the large model, with the same output distribution.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Let qiq_i be the draft distribution at position ii and pip_i be the target distribution. This page follows Leviathan et al.'s notation, where pp is the target and qq is the draft; Chen et al. use the opposite symbols. If the draft proposes token xix_i, it is accepted with probability:

Pr⁡(accept xi)=min⁡ ⁣(1,pi[xi]qi[xi]).\Pr(\text{accept } x_i) = \min\!\left(1, \frac{p_i[x_i]}{q_i[x_i]}\right).

If a proposed token is rejected, you sample from a residual distribution that corrects for what the draft already "used up":

xi∼Normalize ⁣(max⁡(0,pi−qi)).x_i \sim \mathrm{Normalize}\!\left(\max(0, p_i - q_i)\right).

This rejection-and-residual mechanism is what makes the method lossless: accepted tokens come from qq but are filtered to match pp, and the residual sample at a rejected position supplies exactly the probability the filter removed.

How much faster?

Averaged over the draft's proposals, a position is accepted with probability β=∑xmin⁡(p(x),q(x))\beta = \sum_x \min\big(p(x), q(x)\big), which is 1 when the two distributions agree and 0 when they do not overlap (Leviathan et al., 2023, Theorem 3.5). Let α\alpha be the average of β\beta over positions. Leviathan et al. make the simplifying assumption that acceptances are independent, each with probability α\alpha. Then one target pass with kk draft tokens produces on average E[tokens per target pass]=1−αk+11−α\mathbb E[\text{tokens per target pass}] = \dfrac{1-\alpha^{k+1}}{1-\alpha} tokens.

This counts the accepted prefix plus one token from the target: either the residual sample at the first rejection or a new token when all kk are accepted. The count ranges from 1 (the first draft token is rejected) to k+1k+1.

Each round also runs the draft model kk times. If one draft pass takes cc times as long as one target pass, the expected wall-clock speedup is 1−αk+1(1−α)(kc+1)\dfrac{1-\alpha^{k+1}}{(1-\alpha)(kc+1)} (Leviathan et al., 2023, Theorem 3.8). For example, with α=0.8\alpha = 0.8, k=4k = 4 and c=0.05c = 0.05, a target pass yields about 3.36 tokens and the speedup is about 2.8×. A longer draft helps only while α\alpha is high; when the draft is often wrong, the extra draft passes cost more than the extra accepted tokens save. The formula also assumes the target can score k+1k+1 positions in about the time of one, which holds when decoding is limited by memory bandwidth, not when the hardware is already busy with large batches.

Worked example: where the rejected probability goes

Take four tokens A, B, C, D with the target and draft from the code below, p=(0.45, 0.30, 0.15, 0.10)p=(0.45,\,0.30,\,0.15,\,0.10) and q=(0.30, 0.45, 0.20, 0.05)q=(0.30,\,0.45,\,0.20,\,0.05). A proposed token is kept with probability min⁡(1,p/q)\min(1,p/q), which is (1, 2/3, 3/4, 1)(1,\,2/3,\,3/4,\,1). The probability that each token is proposed and kept is q⋅min⁡(1,p/q)=min⁡(p,q)q\cdot\min(1,p/q)=\min(p,q):

min⁡(p,q)=(0.30, 0.30, 0.15, 0.05),β=∑xmin⁡(p(x),q(x))=0.80.\min(p,q)=(0.30,\,0.30,\,0.15,\,0.05),\qquad \beta=\sum_x\min\big(p(x),q(x)\big)=0.80.

A rejection therefore happens with probability 1−β=0.201-\beta=0.20, and the residual it samples from is

max⁡(0, p−q)0.20=(0.15, 0, 0, 0.05)0.20=(0.75, 0, 0, 0.25).\frac{\max(0,\,p-q)}{0.20}=\frac{(0.15,\,0,\,0,\,0.05)}{0.20}=(0.75,\,0,\,0,\,0.25).

Rejections add 0.20⋅(0.75,0,0,0.25)=(0.15,0,0,0.05)0.20\cdot(0.75,0,0,0.25)=(0.15,0,0,0.05), and kept plus repaired is (0.45,0.30,0.15,0.10)=p(0.45,0.30,0.15,0.10)=p. The residual is a distribution over the tokens the draft under-proposed, A and D, in proportion to their shortfalls, 0.150.15 and 0.050.05; scaled by the rejection probability 0.200.20, it adds back exactly each shortfall. When p=qp=q every proposal is kept and the residual is never sampled; when pp and qq differ, however slightly, it must be normalized and used, or the output loses that probability.

When acceptance changes along the draft

The token count above assumes every position is accepted independently with the same α\alpha. Without that assumption, let aia_i be the probability that draft position ii is accepted given that positions 1,…,i−11,\ldots,i-1 were, and let LL be the number of draft tokens accepted. By the chain rule,

Pr⁡(L≥i)=a1a2⋯ai,E[L]=∑i=1kPr⁡(L≥i).\Pr(L\ge i)=a_1a_2\cdots a_i,\qquad \mathbb E[L]=\sum_{i=1}^{k}\Pr(L\ge i).

With k=4k=4 and a=(0.80, 0.75, 0.50, 0.25)a=(0.80,\,0.75,\,0.50,\,0.25), the survival probabilities are (0.80, 0.60, 0.30, 0.075)(0.80,\,0.60,\,0.30,\,0.075), so E[L]=1.775\mathbb E[L]=1.775 and one target pass yields 2.7752.775 tokens on average. Reverse the order to a=(0.25, 0.50, 0.75, 0.80)a=(0.25,\,0.50,\,0.75,\,0.80): the mean acceptance is the same 0.5750.575, but the survival probabilities are (0.25, 0.125, 0.09375, 0.075)(0.25,\,0.125,\,0.09375,\,0.075) and E[L]=0.54375\mathbb E[L]=0.54375. A rejection ends the draft, so the early positions count most, and the mean acceptance alone does not determine the expected length; independent acceptance at α=0.575\alpha=0.575 gives a third value, E[L]=1.205\mathbb E[L]=1.205.

These are tokens per target pass, not speedups. The speedup also depends on the draft's cost and on how long the target takes to score the draft, as above.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

First check the one-token correction. Even though some samples come from the draft model, the accepted-or-resampled output should match the target distribution. Then simulate the length of the accepted prefix, which is where the speedup comes from, and compare it with the formula α(1−αk)/(1−α)\alpha(1-\alpha^k)/(1-\alpha), the expected number of accepted draft tokens (one fewer than the tokens per target pass).

import numpy as np

target_p = np.array([0.45, 0.30, 0.15, 0.10])
draft_q = np.array([0.30, 0.45, 0.20, 0.05])
rng = np.random.default_rng(0)

def residual_distribution(p, q):
    repair_mass = np.maximum(0.0, p - q)
    return repair_mass / repair_mass.sum()

def speculative_one_token(p, q):
    draft = rng.choice(len(q), p=q)
    accept_prob = min(1.0, p[draft] / q[draft])
    if rng.random() < accept_prob:
        return draft, True
    repair = rng.choice(len(p), p=residual_distribution(p, q))
    return repair, False

samples = np.zeros_like(target_p)
accepted = 0
for _ in range(200_000):
    token, was_accepted = speculative_one_token(target_p, draft_q)
    samples[token] += 1
    accepted += int(was_accepted)

print("target distribution:   ", np.round(target_p, 3))
print("speculative samples:   ", np.round(samples / samples.sum(), 3))
print("draft-token acceptance:", round(accepted / samples.sum(), 3))

def expected_accepted(alpha, k):
    # Expected length of consecutive acceptances (prefix), capped at k.
    if alpha == 1.0:
        return float(k)
    return alpha * (1.0 - alpha**k) / (1.0 - alpha)

def simulate(alpha, k, trials=50000, seed=0):
    rng = np.random.RandomState(seed)
    total = 0
    for _ in range(trials):
        a = 0
        for _ in range(k):
            if rng.rand() < alpha:
                a += 1
            else:
                break
        total += a
    return total / trials

for alpha in [0.3, 0.6, 0.85]:
    for k in [2, 4, 8]:
        theo = expected_accepted(alpha, k)
        mc = simulate(alpha, k)
        print(f"alpha={alpha:.2f} k={k:>2}  E[accepted] theo={theo:.3f}  mc={mc:.3f}")

The same two calculations, exactly

This standard-library Python code does the worked examples above without sampling: the kept and repaired mass for one position, and the survival of a four-token draft.

def repair(p, q):
    kept = [min(pi, qi) for pi, qi in zip(p, q)]
    shortfall = [max(0.0, pi - qi) for pi, qi in zip(p, q)]
    z = sum(shortfall)                       # probability of a rejection
    residual = [s / z for s in shortfall] if z > 0 else [0.0] * len(p)
    return kept, z, residual, [k + z * r for k, r in zip(kept, residual)]

def survival(a):
    s, running = [], 1.0
    for ai in a:
        running *= ai                        # P(L >= i) = a_1 ... a_i
        s.append(running)
    return s, sum(s)                         # E[L] is the sum of the survival probabilities

kept, z, residual, output = repair([0.45, 0.30, 0.15, 0.10], [0.30, 0.45, 0.20, 0.05])
print("kept:", kept, "rejection:", round(z, 12), "residual:", [round(r, 12) for r in residual])
assert all(abs(o - t) < 1e-12 for o, t in zip(output, [0.45, 0.30, 0.15, 0.10]))

# A tiny positive residual is still normalized and used.
output = repair([0.5, 0.5], [0.5000000005, 0.4999999995])[3]
assert abs(sum(output) - 1) < 1e-15

for a in ([0.80, 0.75, 0.50, 0.25], [0.25, 0.50, 0.75, 0.80]):
    s, expected = survival(a)
    print(a, "P(L >= i):", [round(x, 6) for x in s], "E[L]:", round(expected, 6))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Speculative Decoding: Lossless Multi-Token Generation

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Speculative Decoding: Lossless Multi-Token Generation, then open its guide.

Use the demo to see how the acceptance rate, the draft length and the mismatch between the two distributions affect the expected speedup, and why verification is nearly free only if the target model can score the whole draft in about the time of one step. The practice after the demo works the two calculations above by hand: where the rejected probability goes, and how far a draft survives.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Practice

Follow kept and rejected probability until they rebuild the target, then work out how far a four-token draft survives and reverse its order.

Loading the exercise…
In focus

Concept: Speculative Decoding: Lossless Multi-Token Generation

What is the smallest example of Speculative Decoding you can work through by hand, and what does it show?

BeforeMaximum LikelihoodNextStructured Decoding: Token Masks From Schema Automata
DetailsLLM Systems

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

Draft several tokens with a fast model, score all the draft prefixes with the target model in one parallel pass, then use modified rejection sampling so the output distribution matches the target model's.

Choose what to look for (no demo yet)01 / Intuition
Illustration of draft tokens passing through verifier gates with accepted and rejected branches.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Speculative Decoding: Lossless Multi-Token Generation.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

Draft several tokens with a fast model, score all the draft prefixes with the target model in one parallel pass, then use modified rejection sampling so the output distribution matches the target model's.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Speculative Decoding: Lossless Multi-Token Generation.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2023Fast Inference from Transformers via Speculative DecodingLeviathan, Kalman, and Matias
Why it is cited

A fast model drafts γ tokens, the target scores every draft prefix in one pass, and accept/reject sampling with a residual keeps the target's distribution; §3 gives tokens per pass, (1 − α^(γ+1))/(1 − α), and the speedup (ICML 2023).

Open source
paper · 2023Accelerating Large Language Model Decoding with Speculative SamplingChen et al.
Why it is cited

Independently proposes the same draft-then-verify scheme with modified rejection sampling, and reports a 2–2.5× decoding speedup for the 70-billion-parameter Chinchilla model in a distributed setup (arXiv preprint).

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

Draft several tokens with a fast model, score all the draft prefixes with the target model in one parallel pass, then use modified rejection sampling so the output distribution matches the target model's.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Speculative decoding uses a fast draft model to propose several tokens and the target model to verify them in parallel, using rejection and residual sampling so that the output distribution matches sampling from the target model alone.
What the sources support

Leviathan et al. define γ draft tokens from a faster approximation model, parallel target scoring of the draft prefixes, accept/reject filtering and residual sampling from norm(max(0, p − q)), and prove that...

Where to see it on this page
Equation 1
Pr⁡(accept xi)=min⁡ ⁣(1,pi[xi]qi[xi]).\Pr(\text{accept } x_i) = \min\!\left(1, \frac{p_i[x_i]}{q_i[x_i]}\right).
Equation 2
xi∼Normalize ⁣(max⁡(0,pi−qi)).x_i \sim \mathrm{Normalize}\!\left(\max(0, p_i - q_i)\right).
Caveat

The guarantee is about the output distribution, exact up to floating-point arithmetic, as Chen et al. note. It is not a latency guarantee: the speedup depends on the acceptance rate and the draft's cost. The...

StatusChecked against the cited passages.

Leviathan et al. (2023) support drafting γ tokens, parallel target scoring of the draft prefixes, accept/reject filtering, residual sampling from norm(max(0, p − q)), and a proof that the output follows the target distribution. Chen et al. (2023) independently support K-token drafts, parallel scoring and modified rejection sampling, with the guarantee qualified by hardware numerics and with p and q swapped. The page's math follows Leviathan et al.'s notation.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Speculative Decoding: Lossless Multi-Token Generation

Try the idea in your own words

Draft several tokens with a fast model, score all the draft prefixes with the target model in one parallel pass, then use modified rejection sampling so the output distribution matches the target model's.

Concept · Selected for practice

Speculative Decoding: Lossless Multi-Token Generation

What it rests on: Sources: Fast Inference from Transformers via Speculative Decoding; Accelerating Large Language Model Decoding with Speculative Sampling

Context and links
Choose a task

Explain the mechanism

For Speculative Decoding: Lossless Multi-Token Generation: What is the smallest example of Speculative Decoding you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptSpeculative Decoding: Lossless Multi-Token GenerationSources: Fast Inference from Transformers via Speculative Decoding; Accelerating Large Language Model Decoding with Speculative Samplingassert all(abs(o - t) < 1e-12 for o, t in zip(output, [0.45, 0.30, 0.15, 0.10]))

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptLLM Systems

    Speculative Decoding: Lossless Multi-Token Generation

    Starting question

    What is the smallest example of Speculative Decoding you can work through by hand, and what does it show?

    SourcesCheck the 2 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Speculative Decoding: Lossless Multi-Token Generation" feel predictable rather than familiar.
    Assumption

    The 2 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 2 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 2 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/llm-systems/speculative-decoding concept:llm-systems/speculative-decoding