Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

Speculative Decoding: Lossless Multi-Token Generation

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

published · difficulty 4/5 · 18 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

Autoregressive decoding is painfully sequential: one forward pass per token.

Speculative decoding gets around this by splitting work into two roles:

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

In the full algorithm, the target produces k+1k+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 repair that position with a residual sample so the target distribution is preserved. The key promise is that this is lossless: the final distribution of generated text is exactly what you would have sampled from the target model alone.

So the win is systems-level: fewer expensive sequential target steps, same output distribution.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let qiq_iqi be the draft distribution at position iii and pip_ipi be the target distribution. This page follows Leviathan et al.'s notation where ppp is the target and qqq is the draft; Chen et al. use the opposite symbols. If the draft proposes token xix_ixi, the acceptance probability is:

αi=min ⁣(1,pi[xi]qi[xi]).\alpha_i = \min\!\left(1, \frac{p_i[x_i]}{q_i[x_i]}\right).αi=min(1,qi[xi]pi[xi]).

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

xiNormalize ⁣(max(0,piqi)).x_i \sim \mathrm{Normalize}\!\left(\max(0, p_i - q_i)\right).xiNormalize(max(0,piqi)).

This rejection/residual mechanism is what makes the method lossless: accepted tokens come from qqq but are filtered to match ppp, and rejected positions are repaired to restore the exact ppp distribution.

A rough intuition for speedup: if the draft is often right, you accept a long prefix of the kkk proposed tokens, and the target model advances several tokens per verification step.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.

First check the one-token correction mechanism. Even though some samples come from the draft model, the accepted-or-repaired output should match the target distribution. Then simulate the accepted-prefix length that creates the latency upside.

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}")
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Speculative Decoding: Lossless Multi-Token Generation

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

Choose what to inspect in Speculative Decoding: Lossless Multi-Token Generation. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo to see how acceptance probability, draft length, and distribution mismatch affect expected speedup, and why verification is "free" only if your target model can score the chunk efficiently.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Speculative Decoding: Lossless Multi-Token Generation

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextLong Context Engineering: RoPE Scaling, KV Compression & Memory Optimization
Object contextLLM Systems
ConceptLearner lens

Speculative Decoding: Lossless Multi-Token Generation

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inMaximum Likelihood

Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.

Work hereSpeculative Decoding: Lossless Multi-Token Generation

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

Carry outLong Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

The next edge should feel earned: use the demo prediction here before following Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptSpeculative Decoding: Lossless Multi-Token GenerationLLM Systems

Mechanism Storyboard

See the idea move before the page explains it

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

Demo notes open01 / Intuition
Editorial systems illustration of draft tokens passing through verifier gates with accepted and rejected branches.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Speculative Decoding: Lossless Multi-Token Generation should make visible.

Visual Inquiry

Make the image answer a mathematical question

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Speculative Decoding: Lossless Multi-Token Generation easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptSpeculative Decoding: Lossless Multi-Token GenerationQuestion

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

concept:llm-systems/speculative-decoding
Boundary

sources: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling

Check

Open the closest source note before trusting the local explanation.

Evidence

2 selected-object sources shown first; 2 references total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2022Fast Inference from Transformers via Speculative DecodingLeviathan, Kalman, and Matias
Located CF editorial boundary

Introduces speculative decoding as parallel draft-prefix scoring with modified rejection/residual sampling that preserves the target distribution.

Used here as

Leviathan defines gamma draft tokens from a faster approximation model, parallel target scoring of draft prefixes, accept/reject filtering, residual sampling from norm(max(0, p - q)), and...

Caveat

Checks lossless sampling under standardized sampling distributions; Chen qualifies the guarantee as within hardware numerics. Not a universal latency guarantee. Code is a toy finite-distr...

Open source
selected object source · paper · 2023Accelerating Large Language Model Decoding with Speculative SamplingChen et al.
Located CF editorial boundary

Independently grounds K-token drafts, parallel target scoring, modified rejection sampling, residual repair, and measured large-model decoding speedups.

Used here as

Leviathan defines gamma draft tokens from a faster approximation model, parallel target scoring of draft prefixes, accept/reject filtering, residual sampling from norm(max(0, p - q)), and...

Caveat

Checks lossless sampling under standardized sampling distributions; Chen qualifies the guarantee as within hardware numerics. Not a universal latency guarantee. Code is a toy finite-distr...

Open source

Claim Review

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

Object - ConceptSpeculative Decoding: Lossless Multi-Token GenerationQuestion

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

concept:llm-systems/speculative-decoding
Boundary

sources: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 2 references and 3 local witnesses are available for inspection.

Speculative decoding uses a fast draft model to propose multiple tokens and a target model to verify them in parallel, using rejection/residual sampling so the final output distribution matches target-model decoding.
Used here as

Leviathan defines gamma draft tokens from a faster approximation model, parallel target scoring of draft prefixes, accept/reject filtering, residual sampling from norm(max(0, p - q)), and proves target-distr...

Local witness
Equation 1
αi=min ⁣(1,pi[xi]qi[xi]).\alpha_i = \min\!\left(1, \frac{p_i[x_i]}{q_i[x_i]}\right).
Equation 2
xiNormalize ⁣(max(0,piqi)).x_i \sim \mathrm{Normalize}\!\left(\max(0, p_i - q_i)\right).
Code witness 1import numpy as np target_p = np.array([0.45, 0.30, 0.15, 0.10]) draft_q = np.array([0.30, 0....
Caveat

Checks lossless sampling under standardized sampling distributions; Chen qualifies the guarantee as within hardware numerics. Not a universal latency guarantee. Code is a toy finite-distribution/residual che...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Leviathan 2022 supports gamma-token drafting, parallel target scoring of draft prefixes, accept/reject filtering, residual sampling from norm(max(0, p - q)), and a proof of target-distribution sampling. Chen 2023 independently supports K-token drafts, parallel scoring, modified rejection/residual sampling, and hardware-numerics-qualified preservation, with reversed p/q notation. Page math follows Leviathan; code is a toy residual/distribution plus prefix check, and demo is toy speedup only.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice notebook

Use the idea, then test it somewhere new

Draft several tokens with a fast model, score draft prefixes with the target model in parallel, then use modified rejection/residual sampling so the sampled distribution matches target-model decoding.

AttemptNo learning claim inferred
Object - ConceptSpeculative Decoding: Lossless Multi-Token GenerationQuestion

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

concept:llm-systems/speculative-decoding
Boundary

sources: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling

Check

Use one state from Speculative Decoding: Lossless Multi-Token Generation to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from Speculative Decoding: Lossless Multi-Token Generation to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling
  1. ObjectConceptSpeculative Decoding: Lossless Multi-Token Generation
  2. PredictBefore revealSpeculative Decoding: Lossless Multi-Token Generation prediction
  3. WitnessCompare codeSpeculative Decoding: Lossless Multi-Token Generation code witness 1
  4. RoomAsk groundedChecking local snapshot
ConceptSpeculative Decoding: Lossless Multi-Token GenerationLLM Systems

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
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

Anchored question

What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math?

Source boundaryInspect source ids: leviathan-2022-speculative-decoding, chen-2023-speculative-samplingStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk what would make "Speculative Decoding: Lossless Multi-Token Generation" feel predictable rather than familiar.
Assumption

Source ids leviathan-2022-speculative-decoding, chen-2023-speculative-sampling must support the exact object, not just the surrounding topic.

Source-checking summary

Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

Proposed experiment

Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:llm-systems/speculative-decoding.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Object-attached AI handoff

I am working in Continuous Function's research reading room. Object: concept - Speculative Decoding: Lossless Multi-Token Generation Object key: concept:llm-systems/speculative-decoding Context: LLM Systems Anchor id: concept/concept-notebook/llm-systems/speculative-decoding Open question: What is the smallest example that makes Speculative Decoding: Lossless Multi-Token Generation click without losing the math? Evidence to inspect: - Source ids to inspect: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids leviathan-2022-speculative-decoding, chen-2023-speculative-sampling must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Speculative Decoding: Lossless Multi-Token Generation" feel predictable rather than familiar." | assumption: Source ids leviathan-2022-speculative-decoding, chen-2023-speculative-sampling must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: leviathan-2022-speculative-decoding, chen-2023-speculative-sampling" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Speculative Decoding: Lossless Multi-Token Generation" feel predictable rather than familiar. - Assumption to keep visible: Source ids leviathan-2022-speculative-decoding, chen-2023-speculative-sampling must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

concept/concept-notebook/llm-systems/speculative-decoding concept:llm-systems/speculative-decoding