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.
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.
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.
The prompt and all tokens already generated form the current context.
The model calculates which vocabulary tokens fit after that context.
Greedy decoding picks the highest-scoring token, while sampling makes a probability-weighted choice.
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.
The GPU performs many calculations at the same time to produce the next-token scores.
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.
Prefill: read once
The model processes all prompt tokens together and builds an internal record of their attention information.
Decode: repeat
The model uses that stored context and the newest output token to choose one more token, then repeats.
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.
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.
The small helper model proposes a short continuation quickly.
The original large model evaluates all proposed positions together.
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 for draft probabilities and 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, means the draft model's probability and 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.
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.
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 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:
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.
| Mode | Acceptance | First mismatch or rejection | Guarantee |
|---|---|---|---|
| Greedy | Keep the longest prefix matching the target argmax at every position | Emit the target argmax and discard later proposals | Same deterministic sequence as target-only greedy decoding |
| Sampling | Apply the probability-ratio acceptance test in prefix order | Sample from the corrected residual distribution | Same distribution as target-only sampling |
Temperature, top-k filtering, nucleus sampling, and other logit processors must be incorporated consistently before computing the effective and used by the acceptance test.
7. The Exact Acceptance Rule
Suppose the draft samples token . Draw uniformly from zero to one and accept the proposal when:
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 of those samples survive.
At the first rejection, later draft tokens are discarded and the replacement token is sampled from:
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.
Reject “fast”. Sample a correction from the residual distribution below.
| Token | Draft q | Target p | Accepted overlap min(p, q) | Correction norm(max(0, p − q)) |
|---|---|---|---|---|
| fast | 0.45 | 0.20 | 0.20 | 0.00 |
| small | 0.30 | 0.25 | 0.25 | 0.00 |
| exact | 0.15 | 0.40 | 0.15 | 0.83 |
| other | 0.10 | 0.15 | 0.10 | 0.17 |
8. Why the Final Distribution Is Exactly the Target Distribution
For any token , the probability that the draft samples it and the verifier accepts it is:
The probability of entering the correction branch is the remaining mass . Sampling from the normalized positive difference contributes to token . Adding the accepted and corrected contributions gives:
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 and the draft length is , the expected number of emitted tokens, including the correction or bonus token, is:
The first term is guaranteed because the round always emits a correction or bonus token. The term is the simplified probability that at least 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 , every proposal is accepted and the series equals . 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 , and let one draft step cost . Under the paper's simplifying assumption that verifying positions takes about one target-step latency, a speculative round costs . The expected wall-time improvement is:
The idealized latency model
Explore the paper's analytical model for acceptance, draft cost, and speculation length.
Increasing 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.
Longer candidate chunks increase attention work, activation traffic, and output-logit computation.
The drafter has its own weights, KV cache, sampling kernels, and launch overhead.
Accepted states must be committed while rejected suffix states are discarded or overwritten safely.
A busy target model may already use the accelerator efficiently, leaving less spare capacity for multi-position verification.
A drafter on another device can overlap work, while communication and synchronization can consume the gain.
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.
| Moment | Draft cache | Target cache |
|---|---|---|
| Before drafting | Synchronized to the committed output before new proposals begin | Represents the committed output, with the latest emitted token possibly still pending |
| After γ proposals | Has advanced speculatively; the final sampled proposal may still be pending input | Has not yet verified the proposal chunk |
| After target verification | Still holds draft-side speculative work | Holds tentative states produced while scoring the proposal chunk |
| After a rejection | Truncate or rebuild state to match the accepted prefix and correction | Keep valid verified states and discard the invalid suffix |
| Next round | Process any pending emitted token before making new proposals | Process 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.
- 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
- 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 and 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.
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.
| Approach | Proposal source | Main tradeoff |
|---|---|---|
| Classic speculative decoding | A separate smaller autoregressive model | Simple and exact, with an additional model and cache to serve |
| Prompt or n-gram proposals | Matching token sequences from the context or a lookup table | Negligible proposal cost, strongest on repetitive text and code |
| Medusa | Multiple decoding heads attached to the target backbone | Avoids a separate drafter but requires training extra heads |
| EAGLE | Predicted second-to-top-layer features plus shifted tokens | Higher proposal accuracy with a target-specific trained module |
| SpecInfer | A tree of candidate continuations from speculative models | More 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]- 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.
- 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.
Primary Sources and Further Reading
The algorithm, exactness argument, analytical speedup model, and architectural variants in this guide are grounded in the original papers below.
- Fast Inference from Transformers via Speculative Decoding, Leviathan, Kalman, and Matias (2023)
- Accelerating Large Language Model Decoding with Speculative Sampling, Chen et al. (2023)
- SpecInfer: Accelerating Generative Large Language Model Serving with Tree-based Speculative Inference and Verification, Miao et al. (2024)
- Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads, Cai et al. (2024)
- EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty, Li et al. (2024)
- Dynamic Speculation Lookahead Accelerates Speculative Decoding of Large Language Models, Mamou et al. (2024)