AI engineering · A guided exploration

Speculative Decoding

Guess ahead. Check together. Commit only what the target allows.

Follow the original method through one complete round. Then explore how Medusa, EAGLE, and LayerSkip change the drafter without making verification disappear.

Before reading
Know that a language model processes tokens and produces next-token scores. Basic causal attention is helpful.
You will learn
Why verification can be parallel, how rejection works, where drafts come from, and when speculation is worth its cost.
Scope
Original chain speculation, exact sampling, and three representative variants. Not an implementation runbook or exhaustive survey.
How to read
Read the original flow first. Use the labs to inspect mechanisms; open the optional details when you want more depth.

Chapter 1

Why guess ahead?

You ask a language model to continue a sentence. It chooses one token, feeds that token back, and chooses another. That serial dependency is real: a different first token can change everything that follows.

Speculative decoding does not remove the dependency. It uses a cheaper mechanism to propose a continuation, then asks the target model to check several positions together. If the guesses are good, one expensive evaluation can advance the answer by several tokens.

The original method can use an existing smaller model as the drafter, without retraining or changing the target model. The early papers by Leviathan, Kalman, and Matias and by Chen and colleagues explain how verification and corrected sampling preserve the target distribution. [1] [2]

Four terms, four responsibilities

Target model
The model whose decoding behavior we want to preserve.
Drafter
A cheaper proposal mechanism. It can be a separate model, trained heads, or an early-exit path.
Drafting
The proposal stage only. A small autoregressive drafter may still generate its candidates sequentially.
Verification
Target evaluation of the proposed continuation, followed by an acceptance rule.

We will first use greedy decoding, where the highest-scoring target token is chosen. Sampling comes later. All sentence examples treat each displayed word as one token for clarity; real tokenization may split words differently.

Chapter 2

Original method: a small model drafts, the target checks

Start with the committed context “The cat sat”. A smaller model proposes “on the mat”. It is allowed to be wrong. The target model is still responsible for the final continuation.

What happens in one round?

  1. Draft. The small model proposes a short chain and, for exact sampling, supplies its proposal distributions.
  2. Verify. The target evaluates the relevant positions together under causal visibility.
  3. Accept or correct. For greedy decoding, keep the longest prefix that matches the target's choices. At the first mismatch, emit the target's choice and discard the draft tail.
  4. Continue. Retain or reconstruct state consistent with the committed sequence, then start the next round.

Try the middle mismatch first. Then switch to all-match and first-failure. The target predictions in the lab are scripted examples, not outputs of an actual LLM.

Lab 1 / Run a complete greedy round

Interactive lesson · illustrative, not a running model

Scenario:

Committed context: The cat sat

  1. Draft
  2. Verify together
  3. Commit
  4. Continue
on
the
mat

Draft: the smaller model proposes on / the / mat. Nothing has been committed yet.

How to read this lab. The draft is “on the mat.” In the middle-mismatch case, the target agrees with “on” but predicts “a” instead of “the.” Commit “on a” and discard “the mat.” Later checks used the rejected prefix and cannot be rescued. If all candidates match, a bonus target token can also be emitted.

Why the matching prefix matters

Suppose the target chooses “on,” then “a.” A later prediction after “on the” is no longer a prediction under the actual context “on a.” Even if that later token happens to look useful, it cannot be kept on the basis of that check.

If K candidates all match, the target's logits after the last candidate can provide one additional bonus token. The classic round can therefore commit up to K + 1 tokens. Output limits and stopping conditions can end the round earlier. [1] [2]

What does the drafter cost?

A separate draft model needs its own weights, execution, and state. A tiny drafter may be cheap but inaccurate; a larger one may be accurate but too expensive. A suitable existing model can be used, or a specialized drafter can be trained. The target need not be retrained in the original approach.

Compatible token handling is essential. The classic explanation assumes a shared token vocabulary. Cross-tokenizer methods require additional machinery and are outside this lesson.

Chapter 3

How can verification be parallel?

The candidates are available before verification begins. The target can evaluate several sequence positions in one multi-position pass, rather than waiting for each next input to be discovered.

Candidate being checkedTarget prediction conditioned on
onThe cat sat
theThe cat sat on
matThe cat sat on the
Bonus tokenThe cat sat on the mat

The causal mask prevents a position from seeing future candidates. Processing “on” produces logits for what comes after “on”; it does not prove that “on” itself was correct. The preceding position's logits perform that check.

If logits after the last committed token are already available, they can check the first candidate. Otherwise the engine evaluates the appropriate preceding position as part of the pass. Exact input-buffer layout depends on the driver and cache. The conditional predictions above are the invariant. [1] [2]

State must follow the accepted answer

Verification can temporarily compute state for rejected positions. That tail must not become remembered context. Standard KV caches can retain the accepted prefix and invalidate the rest. Other architectures may require snapshots or replay. A correction token must be processed before later predictions can depend on it.

Thus selecting, emitting, and processing a token are distinct events. “Parallel verification” refers to evaluation across candidate positions, not parallel execution of every layer or independent generation of the final answer.

Chapter 4

Sampling needs a different acceptance rule

Greedy verification checks whether a candidate equals the target's highest-scoring token. For stochastic sampling, simply comparing independently sampled tokens is not the original exact algorithm.

Let p(x) be the target probability and q(x) the draft probability for the same position and prefix. A candidate drawn from q is accepted with probability:

min(1, p(x) / q(x))

If rejected, draw a correction from the normalized positive residual:

r(x) = max(0, p(x) − q(x)) / Σy max(0, p(y) − q(y))

The correction compensates for probability mass that the draft overproduced. It is not an arbitrary fallback. The original papers prove distribution preservation under the algorithm's assumptions. Define p and q after the intended sampling transformations. [1] [2]

Lab 2 / Keep the target distribution

Interactive lesson · illustrative, not a running model

Target: A 60.0% / B 40.0%
Draft: A 80.0% / B 20.0%
Final output: A 60.0% / B 40.0%

Accept draft A: 75.0%. Accept draft B: 100.0%. Rejection probability: 20.0%.

On rejection, correction goes to B. The corrected final distribution matches the target, not the draft.

How to read this lab. With target A=60% and draft A=80%, accept a draft A with probability 75%. Draft B is always accepted. Rejected A is corrected to B. The final output distribution is A=60%, B=40%. These bars are exact calculations for a hypothetical two-token vocabulary, not a random simulation.
What if p and q are equal?

Every proposal is accepted. The residual has zero mass, but no rejection occurs, so it does not need to be sampled. The lab handles this case explicitly.

Chapter 5

Medusa: predict future positions with extra heads

The original method must find and serve a suitable smaller model. Medusa changes the proposal mechanism: attach additional decoding heads to the target's final hidden representations.

A hidden representation is a numerical vector produced inside the model. A head maps that representation into predictions. The ordinary LM head predicts the next token. Medusa's extra heads predict positions farther ahead from the same representation; one head does not simply consume the previous head's chosen token. [3, section 2.1]

One round

  1. Obtain the target's hidden representation at the current boundary.
  2. The LM head and extra heads produce candidate distributions for their designated future positions.
  3. Take selected top candidates and arrange possible continuations as a tree.
  4. The target evaluates tree positions together using a branch-aware attention mask and matching position indices.
  5. Apply the chosen acceptance policy, commit a continuation, and use accepted target representations for the next round.

A tree shares prefixes across alternatives. A node may attend to its ancestors and the committed context, but not to another branch. More branches offer more chances of a useful continuation and also create more verification work.

Lab 3 / Inspect a candidate tree

Interactive lesson · illustrative, not a running model

Candidate node:

Shared hidden representation: h after “The cat”

LM head: sat
Extra head 1: on / near
Extra head 2: the / a

To predict candidate “the”, the target uses: The cat sat on. When processing the node, it may attend to itself and ancestors, never siblings or descendants.

Select a node to inspect its causal prefix. Extra heads proposed alternatives; target verification has not committed them.

How to read this lab. The LM head supplies “sat.” Additional heads propose future-position candidates from the same hidden representation. Nodes see the committed prefix and their ancestors, not sibling branches. In this scripted greedy case the target path is “sat on a”; “near” and “the” branches are rejected. The widget teaches tree visibility and greedy selection, not Medusa's typical-acceptance policy.

Two training strategies

Medusa-1 freezes the backbone and trains the additional heads. Medusa-2 trains heads and backbone together, with a training recipe intended to preserve the backbone's next-token capability. Training the backbone changes which target is being accelerated; do not compare it as if the original weights were untouched. [3, section 2.2]

Acceptance is a separate choice

The paper discusses rejection sampling and typical acceptance. Typical acceptance keeps candidates whose target probability exceeds a threshold related to probability and entropy, rather than requiring the exact original sampling distribution. It seeks similar quality with more acceptance; it is not the same guarantee as exact speculative sampling. The widget deliberately uses a simple greedy rule so the tree mechanics stay clear. [3, section 2.3]

Use this approach when trained heads and tree-verification support are available. Its advantages are shared target representations and no standalone small-model backbone. Its costs include head training, additional parameters, and potentially large candidate trees.

Chapter 6

EAGLE: predict features with the selected token in view

EAGLE changes what the drafter predicts. Instead of reproducing a complete small language model, it learns to predict target features: hidden representations before the LM head. The original EAGLE paper combines a feature sequence with a token sequence shifted one step ahead. This section covers that original design, not every later EAGLE version. [4]

Why feature-only prediction is ambiguous

After “I,” the target may select “am” or “always.” Those choices create different next representations. The feature after “I” alone does not specify which branch was selected. EAGLE gives the draft component the selected next token, so it predicts the feature for that particular continuation.

For example: the target feature after “I” plus the selected token “am” helps predict a feature after “I am.” Passing that predicted feature through the target LM head proposes the following token, such as “ready.” The drafter can then use its predicted feature and proposed token to continue.

Lab 4 / Follow a feature-based draft

Interactive lesson · illustrative, not a running model

Next token selected by target:

Committed context: I

  1. Target feature
  2. Shifted token
  3. Predict feature
  4. Draft token
  5. Verify
Target feature f(I)

The target has produced a feature after I. This vector is not a token and is not a future feature.

How to read this lab. The feature after “I” alone does not identify the next feature: choosing “am” and choosing “always” lead to different contexts. EAGLE conditions feature prediction on the selected next token as well. Its predicted feature is passed through the target LM head to propose a later token. The symbolic features are explanatory labels, not real model vectors. This widget follows one branch; the original method can draft a tree.

One round in the original method

  1. Collect target features for the current accepted sequence.
  2. Embed the one-step-ahead tokens and combine them with the feature sequence.
  3. A trained autoregression component predicts the next feature.
  4. The target's LM head maps that predicted feature into a token distribution.
  5. Repeat cheap drafting, potentially expanding a candidate tree.
  6. The target verifies the tree and applies the speculative sampling rule. Accepted tokens and actual target features seed the next round.

The original draft component uses a projection and a decoder layer. The target embedding and LM head are reused rather than newly trained; the target backbone remains fixed. Training uses feature regression and a token-distribution objective, with noise augmentation to reduce sensitivity to accumulated feature errors. [4, section 3]

Guarantee and trade-off

Feature predictions may be inaccurate. Exactness comes from target verification and the acceptance/correction algorithm, not from perfect feature prediction. The original method uses tree verification with speculative sampling to preserve the target distribution. [4, section 3.3]

This requires a trained component matched to the target and an engine able to expose and reuse the relevant representations. It is not a generic plugin for any checkpoint without preparation. Feature error can accumulate across draft steps, so cheapness and acceptance still need measurement.

Chapter 7

LayerSkip: use early layers as the drafter

LayerSkip uses one model at two depths. The early layers propose tokens, and the remaining layers verify those proposals. It avoids a separate draft model and can reuse early-layer computation.

An early exit reads a prediction before the final layer. Ordinary models are not necessarily trained to make useful predictions at every early layer. LayerSkip addresses this with layer dropout and an early-exit loss using a shared LM head. Later layers are dropped more often during training, encouraging earlier layers to become useful predictors. [5, section 4.1]

One round

  1. Choose an exit layer in a suitably trained model.
  2. Run the early layers autoregressively to propose several tokens.
  3. Retain their boundary activations and early-layer cache.
  4. Run the remaining layers on those positions together to obtain full-depth target predictions.
  5. Accept or correct, then repair the cache to match the committed continuation.

Lab 5 / Choose an early exit

Interactive lesson · illustrative, not a running model

Draft path: layers 1–4. Verification continuation: layers 5–12. One shared LM head reads predictions.

Choose the split. Shaded layers are the early draft path. No accuracy or speed is inferred from the slider.

How to read this lab. This conceptual model has 12 layers. Exiting after layer 4 uses layers 1–4 for cheap drafting. Verification continues stored boundary activations through layers 5–12 for multiple candidate positions. Moving the split changes the division of work; it does not supply a measured speedup or acceptance rate. A LayerSkip-trained checkpoint is required for the intended early-exit behavior.

Why computation can be shared

The verification path uses the same early layers in the same order as the draft path. Their results need not be discarded and recomputed from scratch. The paper's self-verification stage continues from retained activations through the later layers. Its cache handling keeps the accepted prefix and rolls back rejected work. [5, sections 4.3.1–4.3.3]

Early exit alone is not self-speculative decoding

If you simply stop at an early layer and output its token, you can change the model's behavior. Self-speculation adds full-depth verification and correction. The relevant target is the full-depth version of the trained checkpoint, not an unrelated pre-training checkpoint.

An earlier exit can make drafting cheaper but less accurate; a later exit can improve proposals but spend more work before verification. The optimum depends on the trained model, workload, hardware, and draft length. The widget shows the split only, not a fabricated accuracy curve.

Chapter 8

Choose a method by cost, not by its name

Speculation may do more arithmetic yet finish sooner by reducing expensive serial target calls. This is especially plausible when short-batch target decode is constrained by data movement and a short multi-position verification pass can reuse weights effectively. It is not a universal property of every workload. [1] [2]

Acceptance rate alone is not enough. You need draft cost, verification cost, state handling, and useful committed tokens. Tree methods also propose alternatives that cannot all be accepted, so their raw accepted/drafted ratio is not directly comparable with a chain ratio.

Lab 6 / Does the extra work pay off?

Interactive lesson · illustrative, not a running model

Ordinary: 10.00 ms/token

Speculative round: 18.00 ms for 4 committed tokens = 4.50 ms/token

Illustrative speed ratio: 2.22×

The assumed saved target steps outweigh the assumed extra work. This is a hypothetical calculation, not a measured speedup.

How to read this lab. All timings are hypothetical inputs. A round costing 18 ms that commits four tokens averages 4.5 ms per token, compared with 10 ms ordinary decode. If it commits only one, it loses. This simplified calculation excludes prefill, queueing, and variable round costs; it is not a hardware forecast.
MethodProposal sourcePreparationMain practical cost
OriginalSeparate small modelCompatible existing or trained drafterExtra model weights, state, and draft execution
MedusaFuture-position headsHead training; optionally joint backbone trainingHeads and candidate-tree verification
Original EAGLEFeature predictor plus shifted tokensTarget-specific draft trainingFeature integration and tree/state management
LayerSkipEarly layers of the same modelEarly-exit training recipeSplit-depth execution and cache repair

Longer drafts can increase useful accepted tokens and wasted tail work. More concurrency can reduce the spare compute that made speculation attractive. Streaming may become burstier because several tokens are committed after one check. Decode speedup does not automatically improve end-to-end first-token time.

A fair inference-engine experiment

Hold target checkpoint, backend, precision, prompts, output limits, sampling, cache conditions, and concurrency comparable. Record actual output length, client latency, failures, memory, draft/verify costs, and committed tokens per round. For a changed backbone, say explicitly that the target changed. Check output consistency under the promised acceptance policy.

Do not assume all four methods are supported by a given engine. A checkpoint needs the appropriate trained components and the engine needs the matching execution path. MTP is a training or prediction capability, not a synonym for one universal speculative algorithm.

Chapter 9

Teach back the whole mechanism

A good drafter is cheap and often useful, not authoritative. Verification evaluates conditional predictions under candidate prefixes. Acceptance selects a valid continuation, and state repair ensures the next round starts from that continuation.

  1. Why can candidate positions be checked together?
  2. Why can a matching token after the first rejection not be kept?
  3. What changes between Medusa heads and original EAGLE's draft component?
  4. Why does LayerSkip need special training?
  5. What does exact sampling guarantee, and what does it not guarantee?
Read the answer key
  1. The candidate inputs are already known. Causal evaluation can score their conditional predictions together without choosing unknown inputs first.
  2. Its check used a rejected prefix. The corrected prefix may give a different prediction.
  3. Medusa heads predict future-position tokens from shared target representations. Original EAGLE predicts features conditioned on shifted token information, then uses the LM head to propose tokens.
  4. Early layers and the shared head need to make useful early predictions. Ordinary final-layer training does not ensure that.
  5. It preserves the target distribution under the algorithm's assumptions. It does not imply identical text for the same seed, universal speedup, or exactness for relaxed acceptance policies.

Read the original algorithm first, then the method whose proposal mechanism interests you. This guide describes the cited versions, not a complete or current survey of every speculative-decoding variant. All token examples, target choices, feature symbols, layer counts in widgets, and timing inputs are illustrative. The widgets do not execute an LLM, reproduce training, or report benchmark results. Their static captions preserve the lesson without JavaScript.

Sources and reading paths

  1. 1.
    Fast Inference from Transformers via Speculative Decoding by Leviathan, Kalman, and Matias

    First submitted 30 November 2022; ICML 2023. Original chain algorithm and exact sampling.

  2. 2.
    Accelerating Large Language Model Decoding with Speculative Sampling by Chen and colleagues

    First submitted 2 February 2023. Parallel scoring and modified rejection sampling.

  3. 3.
    Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads

    Heads, tree attention, training strategies, and acceptance choices.

  4. 4.
    EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty

    Original feature-based drafting with shifted tokens and tree verification.

  5. 5.
    LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding

    Training, shared early-layer work, verification, and cache reuse.