In short
Speculative decoding speeds up LLM generation by letting a cheap drafter guess the next few tokens and having the large target model check all of them in one forward pass, which costs about as much as generating a single token because decoding is limited by memory bandwidth, not arithmetic. A modified rejection sampling rule accepts each draft token with probability min(1, p/q) and otherwise resamples from the leftover probability mass, so the output follows the target model's distribution exactly. The gain depends on how often drafts are accepted and on how busy the server is: it is largest for single streams and light load, and it can vanish at large batch sizes.
Key points
- Decoding one token reads every weight of the model from memory, so checking several proposed tokens in one forward pass costs about the same wall time as generating one.
- A cheap drafter proposes a few tokens, the target verifies them in a single pass, keeps the prefix it accepts and adds one token of its own, so each step yields between one token and all the drafts plus one.
- The acceptance rule, keep a draft token with probability min(1, p/q) and otherwise resample from the normalized leftover max(0, p - q), makes the output follow the target distribution exactly. A poor drafter costs speed, never correctness.
- With acceptance rate α and γ draft tokens, the expected tokens per target pass is (1 - α^(γ+1)) / (1 - α); the drafter's relative cost decides how long a draft is worth proposing.
- Medusa heads, EAGLE, n-gram prompt lookup and self-speculative decoding replace or shrink the separate draft model.
- Gains are largest for single streams and light load. At large batch sizes the server is compute-bound, rejected drafts are wasted work, and speculation can slow it down, so measure at your real load.
Why autoregressive decoding is memory-bandwidth bound
A decoder-only language model writes one token at a time. Every token depends on all the tokens before it, so a 500-token answer takes 500 forward passes in sequence. In each pass, for a single sequence, the accelerator has to read every weight of the model from high-bandwidth memory, plus the KV cache of the tokens so far, and it does very little arithmetic with each byte it reads: about one multiply and one add per weight for the one new token. Modern accelerators can do far more arithmetic per second than that ratio uses, so during decoding the compute units mostly wait on memory. The Medusa authors put the bottleneck plainly: every decoding step has to move the full set of model parameters out of high-bandwidth memory.
That waiting is the opening speculative decoding uses. Running the model over five positions in one pass costs about the same wall time as running it over one, because the weights are read once either way and the extra arithmetic fits into compute that was idle. Prefill already works like this: the whole prompt goes through in one parallel pass. Decoding cannot, because the next tokens are not known yet. If they could be guessed cheaply, the large model could check several guesses in the time it normally spends producing one token.
Leviathan, Kalman and Matias make the memory argument explicit: with speculative decoding, the target model's weights and KV cache are read once per verification pass instead of once per token, so the number of memory reads falls by the same factor as the number of target passes. How prefill and decode behave on a real server, and why batching is the other way to fill idle compute, is covered in LLM inference serving and batching.
The idea: draft cheaply, verify in one pass
Two groups published the method independently. Leviathan, Kalman and Matias at Google called it speculative decoding (ICML 2023), and Chen and colleagues at DeepMind called it speculative sampling (2023). The papers use the same structure. Call the large model whose outputs you want the target, with next-token distribution p, and the cheap model the drafter, with distribution q. One step of the algorithm:
- Draft: the drafter generates γ tokens autoregressively from the current prefix, and records q for each position.
- Verify: the target runs one forward pass over the prefix plus all γ draft tokens. Because a transformer predicts the next token at every position, that single pass yields γ + 1 distributions: one for each draft position and one after the last draft token.
- Accept: walk the draft tokens left to right and accept or reject each with the rule in the next section. Stop at the first rejection.
- Correct or extend: at a rejection, sample one replacement token from a corrected distribution. If every draft token was accepted, sample one bonus token from the last of the γ + 1 distributions.
- Roll back: drop the KV cache entries for rejected positions in both models, and start the next step from the new prefix.
Every step produces at least one token, the correction or the bonus, and at most γ + 1. Leviathan and colleagues point out that this means the number of serial target passes can never exceed plain decoding, even in the worst case. A bad step still costs something: the γ drafter passes, and a verification pass over γ + 1 positions instead of one.
With greedy decoding, temperature zero, the rule collapses to a simple check: accept a draft token if it equals the target's most likely token at that position, and otherwise emit the target's token and stop. The output is identical to greedy decoding with the target alone. Sampling at a temperature above zero needs more care, because two models can agree on the distribution without drawing the same token.
The acceptance rule that keeps the output exact
Both papers use a modified form of rejection sampling. For a draft token x drawn from q, compare the two models' probabilities for that token:
- If q(x) is at most p(x), the target likes the token at least as much as the drafter did: keep it.
- If q(x) is larger than p(x), the drafter overproposes this token: keep it with probability p(x) / q(x).
- If the token is rejected, sample a replacement from the residual distribution norm(max(0, p - q)): the probability mass where the target wants more than the drafter supplied, rescaled to sum to one.
Why the result is distributed exactly as p takes four lines. The probability of emitting x through acceptance is q(x) times min(1, p(x)/q(x)), which is min(p(x), q(x)). The probability of a rejection is whatever mass is left, and the residual hands that mass out in proportion to max(0, p - q):
P(accept x) = q(x) * min(1, p(x) / q(x)) = min(p(x), q(x))
P(reject) = 1 - sum_y min(p(y), q(y)) = sum_y max(0, p(y) - q(y))
P(output is x) = min(p(x), q(x)) + P(reject) * max(0, p(x) - q(x)) / sum_y max(0, p(y) - q(y))
= min(p(x), q(x)) + max(0, p(x) - q(x))
= p(x)The drafter only changes how often a token is accepted, never the distribution of what comes out. A poor drafter makes generation slower, not wrong. Sampling settings such as temperature, top-k and top-p are applied to both distributions before the rule runs; Leviathan and colleagues note that each of them can be written as plain sampling from an adjusted distribution, so the rule covers them all. Chen and colleagues state the guarantee with a qualifier that matters in practice: the target distribution is preserved within hardware numerics.
The simulation below checks the rule on a toy six-word vocabulary. The drafter is deliberately poor: it gives "a" three times the probability the target does. It then simulates full verification steps to compare tokens per step with the formula in the next section. It uses only the standard library:
import random
from collections import Counter
VOCAB = ['the', 'a', 'cat', 'dog', 'sat', 'ran']
p = [0.30, 0.10, 0.25, 0.15, 0.15, 0.05] # target model: next-token distribution
q = [0.20, 0.30, 0.10, 0.20, 0.10, 0.10] # draft model: a worse guess at the same thing
def verify(p, q, rng):
"""One draft token checked by the target. Returns (token, accepted)."""
x = rng.choices(range(len(q)), weights=q)[0] # draft proposes x ~ q
if rng.random() < min(1.0, p[x] / q[x]): # keep it with probability min(1, p/q)
return x, True
residual = [max(0.0, pi - qi) for pi, qi in zip(p, q)]
return rng.choices(range(len(p)), weights=residual)[0], False # resample from norm(max(0, p - q))
rng = random.Random(7)
N = 200_000
counts, accepted = Counter(), 0
for _ in range(N):
x, ok = verify(p, q, rng)
counts[x] += 1
accepted += ok
print('token target p draft q output freq')
for i, w in enumerate(VOCAB):
print(f'{w:5} {p[i]:8.3f} {q[i]:7.3f} {counts[i] / N:11.3f}')
alpha = sum(min(pi, qi) for pi, qi in zip(p, q)) # acceptance rate = sum of min(p, q)
print(f'acceptance: measured {accepted / N:.3f}, predicted {alpha:.3f}')
def tokens_per_step(alpha, gamma, rng, steps=100_000):
"""Simulate verification of gamma drafts, each accepted with probability alpha."""
total = 0
for _ in range(steps):
n = 0
while n < gamma and rng.random() < alpha:
n += 1
total += n + 1 # accepted drafts plus one target token
return total / steps
print('\nalpha gamma tokens/step (sim) formula speedup at c=0.05')
for a in (0.5, 0.7, 0.9):
for g in (2, 4, 8):
expected = (1 - a ** (g + 1)) / (1 - a)
speedup = expected / (g * 0.05 + 1) # c: draft step time / target step time
print(f'{a:5.1f} {g:5d} {tokens_per_step(a, g, rng):17.2f} {expected:7.2f} {speedup:17.2f}')Running it with Python 3 prints:
token target p draft q output freq
the 0.300 0.200 0.301
a 0.100 0.300 0.100
cat 0.250 0.100 0.249
dog 0.150 0.200 0.149
sat 0.150 0.100 0.151
ran 0.050 0.100 0.050
acceptance: measured 0.702, predicted 0.700
alpha gamma tokens/step (sim) formula speedup at c=0.05
0.5 2 1.75 1.75 1.59
0.5 4 1.93 1.94 1.61
0.5 8 2.00 2.00 1.43
0.7 2 2.19 2.19 1.99
0.7 4 2.78 2.77 2.31
0.7 8 3.20 3.20 2.28
0.9 2 2.71 2.71 2.46
0.9 4 4.09 4.10 3.41
0.9 8 6.12 6.13 4.38The output frequencies match the target column, not the drafter column, to within sampling noise, and the measured acceptance rate matches the sum of min(p, q) over the vocabulary.
Acceptance rate and expected tokens per step
For a given prefix, the chance that a draft token is accepted is the sum of min(p, q) over the vocabulary, which is one minus the total variation distance between the two distributions. Leviathan and colleagues call its expected value α and use it as the measure of how well the drafter approximates the target. If acceptances at different positions are assumed independent, the number of tokens one step produces is a capped geometric variable, and its expectation is:
expected tokens per target pass = (1 - α^(γ + 1)) / (1 - α)
wall-time improvement = (1 - α^(γ + 1)) / ((1 - α) * (γ * c + 1))
α: expected acceptance rate γ: draft tokens per step
c: time of one drafter pass divided by time of one target passTokens per pass is not the speedup, because the drafter costs time too. The second formula, the paper's wall-time result, divides by the cost of γ drafter passes. The simulation output shows the consequences. At α = 0.5, drafts past four tokens add almost nothing, and with c = 0.05 an eight-token draft is slower than a four-token one, 1.43 against 1.61. At α = 0.9 long drafts keep paying. When the drafter costs almost nothing, the improvement is bounded above by 1 / (1 - α): an acceptance rate of 0.8 can never give more than five tokens per target pass, however long the draft.
The values seen in practice are encouraging. In their experiments, the authors report that drafters a couple of orders of magnitude smaller than the target tended to reach α between 0.5 and 0.9, that α was higher with greedy decoding than with sampling at temperature one, and that c stayed below 0.05. With T5-XXL (11B) as the target, the 77M T5-small was the best drafter, giving the best balance of α and c, and the measured speedups were 3.4 times with greedy decoding and 2.6 times at temperature one on translation, and slightly lower on summarization. Even a bigram table, with α around 0.2 and a cost close to zero, gave a 1.25 times speedup at γ = 3 on translation.
Two assumptions behind the formulas break in real systems. Acceptance is not constant: boilerplate and quoted text are easy to guess and the content words of an answer are not, so a fixed γ is too long in some stretches and too short in others. The authors estimate that an oracle choosing γ per step could raise the improvement by up to about 60 percent, which is why engines experiment with adaptive draft lengths. And the formula assumes that verifying γ + 1 positions costs the same wall time as one, which only holds while the target is memory-bound. That assumption is the one batching breaks, covered below.
Choosing a draft model
The drafter is the main design decision, and it is a trade between acceptance rate and cost. A larger drafter guesses better and costs more per token; the T5 results show the smallest candidate winning because its low cost outweighed its lower α. Points to check:
- The same tokenizer and vocabulary. The rule compares p and q token by token, so both models have to assign probabilities over the same set of tokens. A smaller model from the same family is the easiest way to get that.
- Size relative to the target. A drafter one to two orders of magnitude smaller is the range the papers report working well; measure c on your hardware, because small models often run below the speed their size suggests, limited by kernel launches and other fixed overheads rather than memory.
- The same behavior as the target. A drafter trained on similar data, or distilled from the target's own outputs, accepts more. A chat-tuned or domain-tuned target with a base-model drafter accepts less, because the drafter does not know the target's formatting and phrasing habits.
- Memory. The drafter's weights and its own KV cache occupy accelerator memory that would otherwise hold more sequences of the batch.
- Acceptance on your traffic. Log proposed and accepted tokens per request and compute α per task. A drafter that does well on chat can do poorly on code, or on languages it saw little of in training. vLLM, for example, lists per-request acceptance metrics among its speculative decoding features.
When no suitable small model exists, for example for a custom fine-tune with no smaller sibling, the variants in the next section get a drafter from the target itself or from the text.
Variants: Medusa heads, EAGLE, n-gram lookup and self-speculation
| Method | Where the draft comes from | Extra training | Output distribution | What the authors report |
|---|---|---|---|---|
| Draft model (Leviathan et al.; Chen et al.) | A separate smaller model with the same vocabulary | None if a suitable model exists | Exact, by the rejection rule | 2 to 3 times on T5-XXL with identical outputs; 2 to 2.5 times on the 70B Chinchilla |
| Medusa | Extra decoding heads on the target that predict several later tokens at once; tree attention verifies several candidate continuations in one pass | The heads (Medusa-1, frozen backbone) or heads and backbone together (Medusa-2) | Lossless for Medusa-1 by the authors' account; Medusa-2 fine-tunes the backbone, and an optional typical acceptance scheme relaxes the check | Over 2.2 times (Medusa-1), 2.3 to 3.6 times (Medusa-2) |
| EAGLE | A light head that autoregresses on the target's second-to-top-layer features, fed the token sequence one step ahead | The draft head | Preserved, per the authors | 2.7 to 3.5 times lower latency and doubled throughput on LLaMA2-Chat 70B |
| N-gram or prompt lookup (LLMA) | Spans copied from the prompt or retrieved documents that match the latest output | None | Identical to greedy decoding in LLMA; exact with the rejection rule | Over 2 times where output and reference overlap heavily |
| Self-speculative (Draft & Verify) | The target itself with some intermediate layers skipped | None, and no extra memory | Lossless: the full model verifies | Up to 1.99 times on LLaMA-2 models |
Medusa, from Cai and colleagues (2024), adds extra heads to the target, each predicting a token further ahead. Each head proposes several likely tokens, so the candidates form a tree, and a tree-shaped attention mask lets the target verify many candidate continuations in one pass: a longer expected accepted length for more computation per step. Medusa-2 trains the backbone along with the heads, and needs a special recipe to keep its capabilities, so the model being sampled is a fine-tuned model, not the original. The paper's typical acceptance scheme accepts more drafts while aiming to maintain quality, rather than matching the target distribution exactly.
EAGLE, from Li and colleagues (2024), drafts in feature space instead of token space: a small head predicts the target's second-to-top-layer features, and it is given the sampled token from one step ahead to resolve the uncertainty about which token the features should lead to. The authors report that this keeps the distribution of the generated text while reaching the highest speedups in the table, across dialogue, code, math and instruction following, including on the mixture-of-experts Mixtral 8x7B Instruct.
Prompt lookup needs no model at all. Yang and colleagues observe in their LLMA paper that outputs often contain long spans identical to text already available, such as retrieved documents or earlier turns of a conversation. When the last few generated tokens match a span in the reference, the rest of that span becomes the draft. This works well for editing, extraction and code changes, and hardly at all for open-ended writing.
Self-speculative decoding, in the Draft & Verify paper by Zhang and colleagues, drafts with the target model itself by skipping some intermediate layers, then verifies with the full model. There is nothing to train and no second set of weights, which makes it attractive when memory is tight. Serving engines keep adding methods: vLLM's documentation lists draft models, n-gram and suffix decoding, EAGLE and multi-token prediction heads among others, and says the model-based methods give the largest latency reductions while n-gram and suffix decoding give modest gains without adding load at peak traffic.
How batching and serving engines change the picture
Speculative decoding and batching compete for the same resource: the compute that sits idle while a memory-bound decode step reads the weights. Continuous batching fills it with other users' sequences; speculation fills it with extra positions of the same sequence. On a quiet server, the compute is free and speculation is close to a pure gain. On a busy one, the batch has already used it, the step is closer to compute-bound, and verifying γ + 1 positions per sequence multiplies the arithmetic, including for draft tokens that get thrown away.
The paper quantifies the extra arithmetic. With a drafter whose cost is negligible, total operations grow by a factor of (1 - α)(γ + 1) / (1 - α^(γ + 1)). At α = 0.7 and γ = 4 that is about 1.8 times the arithmetic of plain decoding for the same tokens. When compute is free, that does not matter; when it is the bottleneck, it is a slowdown.
Liu and colleagues, the TurboSpec authors, describe the benefit of speculation in serving as fragile: it adds overhead, drafts can be rejected, and it can degrade serving performance if added naively without tuning. Their system, implemented in vLLM, profiles the environment and uses runtime feedback to choose how much speculation to run, aiming at the highest goodput, the rate of successfully generated tokens, at the current load. vLLM's own documentation targets speculative decoding at medium-to-low request rates and memory-bound workloads, and lists dynamic speculative decoding for workloads whose load fluctuates.
Inside an engine, several details decide whether the theory survives:
- Ragged acceptance. Sequences in one batch accept different numbers of tokens per step, so the engine has to advance each by its own amount and roll back the KV cache entries of rejected positions.
- Draft memory. A separate drafter needs its own weights and KV cache, which shrink the batch the server can hold. Head-based and self-speculative methods reuse the target's state and avoid most of that.
- Drafter overhead. Drafting is sequential and the drafter is small, so per-step fixed costs such as kernel launches can make c much larger than the ratio of model sizes suggests.
- Numerics. vLLM says its standard sampler is lossless up to hardware numerics, and that outputs with and without speculation can still differ because of floating-point precision and batch size. One of its listed methods relaxes verification on purpose and does not preserve the distribution. If you need bit-identical outputs, check what your engine guarantees.
- Latency type. Speculation reduces inter-token latency. It does not shorten prefill, so it does nothing for time to first token on a long prompt; prompt caching and the KV cache is the tool for that.
When speculative decoding does not help
The method is a bet that spare compute exists and that the drafter guesses well. It loses when either is false:
- Large batches. A server that is already compute-bound has no idle compute to spend on verification, and rejected drafts become pure waste.
- Low acceptance. Creative text at high temperature, a drafter that does not match a fine-tuned target, or a domain or language the drafter handles poorly all push α down, and with it the gain.
- Short outputs. A classifier that answers in three tokens spends its time in prefill, where speculation does nothing.
- An expensive drafter. If c is high, every extra draft token costs more than it is expected to return; the formula shows the optimum γ shrinking toward one.
- Tight memory. A separate drafter that displaces KV cache and so shrinks the batch can cost more throughput than it saves latency.
Measure it on your own traffic before relying on it:
- Take real prompts with their real output lengths and sampling settings, per task: chat, code, extraction and so on.
- Run the baseline and each speculative configuration at several load levels, from a single stream up to your peak concurrency.
- Sweep γ and record the acceptance rate, mean accepted tokens per step, inter-token latency at p50 and p99, and output tokens per second.
- With greedy decoding, check that outputs match the baseline, allowing for the numerics caveat above.
- Keep speculation where it wins, turn it off or shorten γ where it loses, or use an engine feature that adapts it to load.
Speculative decoding sits beside other ways of cutting the work per token, such as quantization, which reduces the bytes read per step, and constrained decoding, which shapes what may be generated; see constrained decoding and structured outputs for the second. For the wider list of levers on latency and spend, see how to reduce LLM costs.
If you are building an AI agent or assistant that has to respond quickly under real load, see our AI agent development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Leviathan, Kalman and Matias, Fast Inference from Transformers via Speculative Decoding (arXiv, ICML 2023)
- Chen et al., Accelerating Large Language Model Decoding with Speculative Sampling (arXiv, 2023)
- Cai et al., Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads (arXiv, 2024)
- Li et al., EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty (arXiv, 2024)
- Yang et al., Inference with Reference: Lossless Acceleration of Large Language Models (arXiv, 2023)
- Zhang et al., Draft & Verify: Lossless Large Language Model Acceleration via Self-Speculative Decoding (arXiv, ACL 2024)
- Liu et al., TurboSpec: Closed-loop Speculation Control System for Optimizing LLM Serving Goodput (arXiv)
- vLLM documentation: Speculative Decoding