Modules
06/30
Speculative Decoding

Contents

Speculative Decoding in LLMs

How a fast helper model lets a larger LLM check several possible next tokens at once.

Why LLM Responses Can Feel Slow

An LLM does not write an entire answer in one operation. It produces the answer in small pieces called tokens. A token may be a word, part of a word, punctuation mark, or space. After producing one token, the model adds it to the text and uses the updated text to choose the next token.

A two-token answer needs two model rounds
Round 1The answer ispredict “42”
Round 2The answer is 42predict “.”

The second round cannot begin until the first round has selected “42,” because that token becomes part of the second round's input. This dependency continues for the full answer. An eighty-token response therefore needs roughly eighty model rounds after the prompt has been read.

This repeated use of a large model creates the delay that speculative decoding tries to reduce. A smaller, faster helper suggests a few upcoming tokens. The large model checks those suggestions together and keeps the ones it agrees with.

Normal generation
large modelone token
Speculative generation
small helper suggestslarge model checksseveral tokens

Speculative decoding in one sentence

Use a cheap model to propose future tokens, then let the original large model verify several proposals in one round. Every output token still needs approval from the large model.

1. How Normal LLM Generation Works

At any moment, the model receives the text written so far and assigns a score to every token in its vocabulary. Those scores become probabilities, and the decoding settings choose one next token. The chosen token is appended to the text, and the same process starts again.

1
Read the current text

The prompt and all tokens already generated form the current context.

2
Score possible next tokens

The model calculates which vocabulary tokens fit after that context.

3
Choose one token

Greedy decoding picks the highest-scoring token, while sampling makes a probability-weighted choice.

4
Append and repeat

The chosen token joins the context before the model runs again.

This process is called autoregressive decoding. “Auto” refers to the sequence using its own earlier output, and “regressive” means the next prediction depends on what has already been produced. The important point is simpler than the name: each selected token changes the input for the next step.

Inside one model round

The GPU performs many calculations at the same time to produce the next-token scores.

Between output tokens

The model must wait for the current token before it knows the exact text needed for the next round.

2. Reading the Prompt vs Writing the Answer

An LLM request has two phases. First, the model reads the prompt. Then it writes the answer token by token. Engineers call these phases prefill and decode.

PHASE 1

Prefill: read once

The model processes all prompt tokens together and builds an internal record of their attention information.

prompt → reusable context
PHASE 2

Decode: repeat

The model uses that stored context and the newest output token to choose one more token, then repeats.

one round → one new token

The stored attention information is called the KV cache. It prevents the model from recalculating the entire prompt during every decode round. The cache saves a large amount of repeated work, but the large model must still run again for each ordinary output token.

Speculative decoding focuses on the decode phase. It tries to turn one large-model round into several approved output tokens instead of only one. It does not make the initial prompt-reading phase disappear.

3. Speculative Decoding in Plain English

Suppose the large model has generated “The fastest route is.” Instead of asking it for exactly one more token, a smaller model quickly suggests the continuation “through the cache today.” The large model then checks the proposed tokens in one pass.

Thefastestrouteis
Small model suggests
throughthecachetoday
Large model checks
✓ through✓ the✕ cachetoday
Final output
throughthenetwork

The first two suggestions are accepted. The third is rejected and replaced with a token sampled from a correction distribution built from the difference between the large and small models' probabilities. Everything after the first rejected token is discarded because it was written using a continuation that is no longer valid. The round still produces three approved tokens after one large-model check.

1. Draft

The small helper model proposes a short continuation quickly.

2. Verify

The original large model evaluates all proposed positions together.

3. Keep or fix

Accepted tokens stay; the first rejection is replaced using the exact correction distribution.

Names used in the rest of this guide

The small helper is the draft model. The original large model is the target model. Later equations use qq for draft probabilities and pp for target probabilities.

4. One Speculative Decoding Round, End to End

Now follow the same idea through a complete round. Start with the Draft tab and move from left to right. On the Verify tab, qq means the draft model's probability and pp means the target model's probability. The exact acceptance formula is explained later in Section 7.

Inside one speculative decoding round

Follow four draft tokens through target verification, prefix acceptance, correction, and cache commitment.

Showing the rejection example at stage 1, Draft.

Stage 1 · draft autoregressively

The small model proposes a continuation

The draft model still generates sequentially, but each of its four decoding steps is much cheaper than one target-model step.

Thefastestrouteisthroughthecachetoday
The runtime stores each proposal together with the draft distribution qᵢ that produced it. Those probabilities are required by exact speculative sampling.

The rejected example emits two accepted draft tokens and one correction token. The all-accepted example emits four draft tokens and one bonus token from the target's extra distribution. In both cases, one target verification round makes forward progress.

5. Why the Target Can Verify Several Positions Together

Future output tokens are unknown during ordinary decoding. Drafting makes a candidate continuation y1,,yγy_1,\ldots,y_\gamma available before the target runs. With the usual causal mask, each candidate position can attend to the prompt and the candidate tokens before it. The target pass returns:

p1=p(c)p_1=p(\cdot\mid c)
p2=p(c,y1),pγ+1=p(c,y1:γ)p_2=p(\cdot\mid c,y_1),\quad \ldots \quad p_{\gamma+1}=p(\cdot\mid c,y_{1:\gamma})

These distributions correspond to different sequence positions within one teacher-forced target pass. Accelerator kernels process their matrix operations concurrently. Acceptance remains ordered afterward because a later candidate can be committed only when all earlier candidates remain in the output prefix.

Parallel verification does not make drafting parallel

A classic autoregressive draft model still needs γ small-model steps. Methods such as multiple prediction heads and token trees change the proposal mechanism, which is why they are separate variants.

6. Greedy Verification and Speculative Sampling

The verification rule depends on how the target would normally choose tokens. Deterministic greedy decoding and probabilistic sampling need different logic.

ModeAcceptanceFirst mismatch or rejectionGuarantee
GreedyKeep the longest prefix matching the target argmax at every positionEmit the target argmax and discard later proposalsSame deterministic sequence as target-only greedy decoding
SamplingApply the probability-ratio acceptance test in prefix orderSample from the corrected residual distributionSame distribution as target-only sampling

Temperature, top-k filtering, nucleus sampling, and other logit processors must be incorporated consistently before computing the effective pip_i and qiq_i used by the acceptance test.

7. The Exact Acceptance Rule

Suppose the draft samples token yiqiy_i\sim q_i. Draw uiu_i uniformly from zero to one and accept the proposal when:

uimin(1,pi(yi)qi(yi))u_i\leq \min\left(1,\frac{p_i(y_i)}{q_i(y_i)}\right)

When the target assigns at least as much probability to the proposed token as the draft does, the ratio reaches one and the token is always accepted. When the draft overestimates that token, only a fraction pi(yi)/qi(yi)p_i(y_i)/q_i(y_i) of those samples survive.

At the first rejection, later draft tokens are discarded and the replacement token is sampled from:

pi(x)=norm(max(0,pi(x)qi(x)))p'_i(x)=\operatorname{norm}\left(\max(0,p_i(x)-q_i(x))\right)

Interactive: Accept or Correct One Draft Token

The example uses two complete distributions over a four-token vocabulary. Select a token sampled by the draft and adjust the uniform random value. The final column shows where correction probability goes if rejection occurs.

Exact acceptance, one token at a time

Choose a draft sample and move the random draw to see when it is kept or replaced.

Draft sample x ∼ q
u = 0.62
0.00threshold 0.441.00
0.62 > min(1, 0.20 / 0.45) = 0.44

Reject “fast”. Sample a correction from the residual distribution below.

Draft, target, accepted-overlap, and correction probabilities for the example vocabulary.
TokenDraft qTarget pAccepted overlap min(p, q)Correction norm(max(0, p − q))
fast0.450.200.200.00
small0.300.250.250.00
exact0.150.400.150.83
other0.100.150.100.17
Accepted draft mass contributes min(p, q). Rejected mass is restored by norm(max(0, p − q)). Together they reproduce the target distribution p exactly, subject to ordinary numerical precision.

8. Why the Final Distribution Is Exactly the Target Distribution

For any token xx, the probability that the draft samples it and the verifier accepts it is:

q(x)min(1,p(x)q(x))=min(p(x),q(x))q(x)\min\left(1,\frac{p(x)}{q(x)}\right)=\min(p(x),q(x))

The probability of entering the correction branch is the remaining mass Z=xmax(0,p(x)q(x))Z=\sum_x\max(0,p(x)-q(x)). Sampling from the normalized positive difference contributes max(0,p(x)q(x))\max(0,p(x)-q(x)) to token xx. Adding the accepted and corrected contributions gives:

min(p(x),q(x))+max(0,p(x)q(x))=p(x)\min(p(x),q(x))+\max(0,p(x)-q(x))=p(x)

Applying this argument at each accepted prefix position preserves the target model's autoregressive distribution. The proof concerns the exact algorithm; approximate acceptance heuristics and relaxed verification schemes can make different quality tradeoffs.

9. Expected Tokens From One Target Round

A round accepts a prefix, so later proposals count only when every earlier proposal survives. If each proposal has independent mean acceptance probability α\alpha and the draft length is γ\gamma, the expected number of emitted tokens, including the correction or bonus token, is:

E[N]=1+α+α2++αγ=1αγ+11α\mathbb{E}[N]=1+\alpha+\alpha^2+\cdots+\alpha^\gamma=\frac{1-\alpha^{\gamma+1}}{1-\alpha}

The first term is guaranteed because the round always emits a correction or bonus token. The term αj\alpha^j is the simplified probability that at least jj proposals survive. Real acceptance probabilities vary with the prompt, position, sampling settings, and draft confidence, so serving systems often adjust the speculation length dynamically.

When α=1\alpha=1, every proposal is accepted and the series equals γ+1\gamma+1. The fraction above is interpreted by that limit because direct substitution would divide by zero.

Average token agreement is insufficient

Early errors are especially costly because every proposal after the first rejection is discarded. Accepted-prefix length is a more operationally useful metric than treating positions as independent completed work.

10. The Idealized Speedup Model

Let one ordinary target step cost TT, and let one draft step cost cTcT. Under the paper's simplifying assumption that verifying γ+1\gamma+1 positions takes about one target-step latency, a speculative round costs T(1+γc)T(1+\gamma c). The expected wall-time improvement is:

speedup1αγ+1(1α)(1+γc)\text{speedup}\approx\frac{1-\alpha^{\gamma+1}}{(1-\alpha)(1+\gamma c)}

The idealized latency model

Explore the paper's analytical model for acceptance, draft cost, and speculation length.

Expected tokens per round
3.05
Relative round time
1.16
Estimated speedup
2.63×
Speedup by draft length
Best γ in this model: 7
α=0.75 · c=0.04
12345678910
This model assumes the target can score γ + 1 positions in approximately one ordinary target-step latency and that enough parallel compute is available. Kernel shapes, context length, batching, cache operations, and device placement change the measured result.

Increasing γ\gamma creates more opportunities to emit tokens, but it also adds draft steps and makes the target verification chunk longer. The best lookahead depends on acceptance and measured runtime costs rather than a universal constant.

11. Why Theoretical Speedup and Real Latency Differ

The analytical equation isolates the central tradeoff, but real target verification does not have perfectly constant latency as the candidate length grows. A deployment must account for several interacting costs.

Target verification

Longer candidate chunks increase attention work, activation traffic, and output-logit computation.

Draft execution

The drafter has its own weights, KV cache, sampling kernels, and launch overhead.

Cache operations

Accepted states must be committed while rejected suffix states are discarded or overwritten safely.

Batch shape

A busy target model may already use the accelerator efficiently, leaving less spare capacity for multi-position verification.

Device placement

A drafter on another device can overlap work, while communication and synchronization can consume the gain.

Sampling pipeline

Vocabulary projection, logit processing, probability transfer, and random sampling contribute measurable overhead.

12. The KV-Cache Lifecycle

Classic two-model speculation maintains separate caches because the target and draft have different weights and hidden states. Both represent the same committed output sequence, but the exact last token already stored in each cache depends on when the runtime processes newly sampled tokens.

MomentDraft cacheTarget cache
Before draftingSynchronized to the committed output before new proposals beginRepresents the committed output, with the latest emitted token possibly still pending
After γ proposalsHas advanced speculatively; the final sampled proposal may still be pending inputHas not yet verified the proposal chunk
After target verificationStill holds draft-side speculative workHolds tentative states produced while scoring the proposal chunk
After a rejectionTruncate or rebuild state to match the accepted prefix and correctionKeep valid verified states and discard the invalid suffix
Next roundProcess any pending emitted token before making new proposalsProcess any pending emitted token as the next verification begins

The correction or bonus token is sampled from a target-derived distribution, but its target KV state has not necessarily been computed when it is emitted. Implementations commonly treat it as pending input to the next round. The same pending-input convention can apply to the draft model's final proposal. Cache layouts, paged allocation, and fused verification kernels determine how expensive rollback and commitment become.

13. What Makes a Good Draft Model?

The draft mechanism must balance two competing quantities: closeness to the target raises acceptance, while low execution cost keeps drafting cheap. The strongest draft in isolation may produce less speedup than a weaker model that runs much faster.

Useful properties
  • High distribution overlap with the target on the actual workload
  • Much lower latency per draft step than the target
  • Compatible token space and sampling transformations
  • Efficient cache memory use and device placement
  • Stable acceptance across prompt types and output positions
Common failure modes
  • A drafter that is too large relative to the target
  • Distribution drift from unrelated training or tokenization
  • Low agreement on code, rare languages, or specialized domains
  • CPU or network placement that adds synchronization delay
  • A fixed lookahead that ignores changing confidence

Classic two-model speculative sampling needs pip_i and qiq_i over the same token support at each position, so deployments commonly pair models using the same tokenizer and vocabulary. Alternative proposal methods use extra heads, feature prediction, prompt matches, or token trees.

14. Speculative Decoding in a Batched Serving System

Single-request latency and multi-request throughput are different objectives. In a batch, every request can accept a different number of tokens. The scheduler must handle ragged progress while deciding whether accelerator time should serve more requests, longer speculative chunks, or a mixture of both.

Request
Verified proposal
Progress this round
A
✓ ✓ ✓ ✓ + bonus
5 tokens
B
✓ ✓ ✗ ·
3 tokens
C
✗ · · ·
1 token

Under light load, spare compute can make speculation attractive for reducing time per output token. Under heavy load, ordinary continuous batching may use the target hardware efficiently enough that extra verification work lowers aggregate throughput. A serving policy should select speculation per workload and load level.

15. Important Speculative Decoding Variants

Speculative decoding describes a family of systems that propose inexpensive future work and verify it with the target. Their proposal structures and training requirements differ.

ApproachProposal sourceMain tradeoff
Classic speculative decodingA separate smaller autoregressive modelSimple and exact, with an additional model and cache to serve
Prompt or n-gram proposalsMatching token sequences from the context or a lookup tableNegligible proposal cost, strongest on repetitive text and code
MedusaMultiple decoding heads attached to the target backboneAvoids a separate drafter but requires training extra heads
EAGLEPredicted second-to-top-layer features plus shifted tokensHigher proposal accuracy with a target-specific trained module
SpecInferA tree of candidate continuations from speculative modelsMore candidates per verification pass with tree attention and scheduling complexity

16. Minimal Speculative Sampling Pseudocode

The following pseudocode shows one sampling round. It emphasizes the probability logic and omits batching, cache allocation, end-of-sequence handling, numerical safeguards, and device communication.

def speculative_step(prefix, gamma, draft, target):
    proposals = []
    draft_distributions = []

    for _ in range(gamma):
        q = draft.next_distribution(prefix + proposals)
        token = sample(q)
        draft_distributions.append(q)
        proposals.append(token)

    target_distributions = target.score_continuation(
        prefix,
        proposals,
        include_next=True,
    )

    accepted = []
    for i, token in enumerate(proposals):
        p = target_distributions[i]
        q = draft_distributions[i]
        keep_probability = min(1.0, p[token] / q[token])

        if uniform_0_1() <= keep_probability:
            accepted.append(token)
            continue

        residual = normalize(maximum(p - q, 0.0))
        correction = sample(residual)
        return accepted + [correction]

    bonus = sample(target_distributions[gamma])
    return proposals + [bonus]
Correctness checks
  • Apply identical target-side sampling transforms used by the baseline.
  • Evaluate acceptance strictly from left to right.
  • Discard every proposal after the first rejection.
  • Normalize the positive residual with stable finite precision.
  • Handle zero draft probability and end-of-sequence tokens explicitly.
Systems checks
  • Keep draft and target cache positions synchronized after rollback.
  • Measure verification time across candidate lengths and contexts.
  • Avoid transferring complete vocabulary distributions unnecessarily.
  • Test mixed batches with different accepted prefix lengths.
  • Compare identical random-number streams where exact regression is required.