Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Speculative decoding,
explained.
Generating text from a large model is slow for a frustrating reason: it makes one token at a time, and each token forces the whole model to be read from memory. Speculative decoding turns that waste into speed with a simple bet — let a tiny, cheap model guess a few tokens ahead, then have the big model check them all at once. When the guesses are good you get several tokens for the price of one, and the output is provably identical. Here's the trick, and the math that says how much it saves.
What changes against better memory use: the idle arithmetic gets used
Rungs 2 and 3 make memory work harder. This rung attacks a waste that is visible only once you look at what generating one token costs. To emit a single token, the accelerator must read every weight in the model from memory and do very little arithmetic with each one. Decode is therefore memory-bandwidth-bound, and the chip's arithmetic units sit largely idle. Meanwhile, scoring several tokens at once costs almost exactly the same as scoring one, because the weight read is what you were paying for.
That asymmetry is an opportunity: the expensive model can check several candidate tokens in a single pass for nearly the price of producing one. So have a small, cheap model draft the next few tokens, then verify them all in one pass of the large model. Every draft token that survives is a token generated without its own weight read.
What makes this remarkable rather than merely clever is the acceptance rule. Tokens are accepted or rejected — and on rejection a replacement is sampled from a carefully-constructed residual distribution — such that the sequence emitted is distributed exactly as if the large model had generated it alone. Not approximately: provably identically. So the speed-up, reported in the region of two to three times, costs nothing in quality, which is close to unique among the optimisations on this site. How much you gain depends on how often the draft is right, and drafting further ahead helps until the compounding chance of an early rejection wastes the rest — so there is an optimal draft length.
Why decoding is slow
A language model generates autoregressively: each token depends on all the ones before it, so they come out strictly one at a time. And here is the painful part — producing that single token requires reading the model's entire set of weights from memory. For a large model that is tens or hundreds of gigabytes moved per token. Decoding is memory-bandwidth-bound: the GPU's arithmetic units sit mostly idle, starved while weights stream in.
That idle compute is the opportunity. Checking whether a proposed token is correct costs one forward pass — and a forward pass can check many token positions at once for barely more than the cost of one, because it is bandwidth-bound, not compute-bound. So if something could guess the next few tokens, the big model could verify the whole batch of guesses in a single pass, spending its wasted compute to produce several tokens at once.
Decoding wastes compute waiting on memory; speculative decoding fills that idle compute by verifying several cheaply-guessed tokens in the one pass it takes to make one.
Draft, then verify
The scheme uses two models: a small fast draft model and the large target model whose output you actually want. Each round:
If the draft is good, most of its k guesses survive and you advance many tokens per expensive target pass. If it is bad, you reject early — but you have still produced at least one correct token (the target's own), so per target call you never do worse than ordinary decoding. (In wall-clock time a poor draft can still be a net loss, since you pay for the draft passes too.)
Why the output is identical
The subtle, beautiful part is that this is lossless. You might expect a shortcut to change what the model says — but speculative decoding is arranged so the tokens it emits are distributed exactly as if you had sampled from the target model normally. It uses a modified rejection sampling rule: accept the draft's token with probability min(1, ptarget/pdraft), and on rejection sample the correction from an adjusted distribution. The algebra works out so the combined process's distribution equals the target's, token for token.
That guarantee is what makes it deployable. It is not an approximation with a quality knob — it produces the same samples as the model it accelerates, so a serving system can switch it on transparently and users see identical outputs, just faster. Speed for free, in the truest sense the field offers.
The expected-tokens math
How much faster? Model each drafted token as accepted independently with probability α, the acceptance rate (how often the little model agrees with the big one). Accept a leading run until the first rejection, then add the target's one guaranteed token. The expected number of tokens produced per target pass is a geometric sum:
Standard decoding produces exactly 1 token per target pass, so this ratio is the speedup in target passes. With α = 0.8 and k = 4 it is ~3.4 tokens per pass. But drafting isn't free: each of the k draft tokens costs the draft model's (smaller) compute, wasted whenever the token is rejected. Dividing the expected tokens by that draft overhead gives a real-time speedup that peaks at a modest k and then falls — guessing too far ahead spends draft compute on tokens that rarely survive. The runnable model below computes both the token count and that peak.
How one speculative decoding step works
Leviathan, Kalman and Matias use two models over the same vocabulary: the target Mp, whose output distribution p you want to sample from, and a cheaper draft Mq with distribution q. Their draft length is γ (the page's k). One call of the procedure, which the paper names SpeculativeDecodingStep, emits between 1 and γ + 1 tokens:
- Draft γ tokens. Run the draft autoregressively from the current prefix: for i = 1…γ, compute qi(x) = Mq(prefix + x1…xi−1) and sample xi from it. Keep each full distribution qi, not just the sampled token.
- Score every position in one target call. Run Mp once, in parallel, on the prefix extended by all γ guesses. This yields γ + 1 distributions: p1 for the first guess's position through pγ+1 for the position after the last guess.
- Accept or reject left to right. For each guess draw ri uniformly from [0, 1] and accept xi if ri ≤ pi(xi)/qi(xi). A guess the target likes at least as much as the draft (p ≥ q) is always kept. Stop at the first rejection; call the number accepted n.
- Correct, or take a bonus. If guess n + 1 was rejected, sample one replacement from the residual distribution norm(max(0, pn+1 − qn+1)). If all γ guesses survived, sample one extra token from pγ+1, which the target call computed anyway.
- Emit and repeat. Append x1…xn plus that one token to the prefix. Every call therefore yields at least one token drawn from the target's own distribution.
Why the result is exactly the target's distribution
Take one position, and let β = Σx min(p(x), q(x)) be the probability that the draft's token is accepted. The chance of emitting x through acceptance is q(x) · min(1, p(x)/q(x)) = min(p(x), q(x)). Rejection happens with probability 1 − β = Σx max(0, p(x) − q(x)), which is exactly the residual's total mass, and the residual then picks x with probability (p(x) − min(p(x), q(x)))/(1 − β). Adding the two routes gives min(p, q) + p − min(p, q) = p(x). Each later position repeats the argument conditioned on the accepted prefix, so the whole emitted sequence has the target's distribution.
The rule covers the usual decoding settings because temperature, top-k and nucleus sampling only reshape p and q, and the same reshaping can be applied to both before the test. Greedy decoding is the special case where both distributions are one-hot: a guess is kept exactly when it equals the target's argmax, and the correction is that argmax.
What it needs, and what came alongside
Nothing is retrained and the target's architecture is untouched; the draft only has to share the vocabulary. The paper tried drafts ranging from trivial unigram and bigram models to smaller Transformers. Chen and colleagues at DeepMind published the same accept-and-resample rule independently soon after as speculative sampling, speeding up Chinchilla 70B with a 4B draft by 2–2.5× in a distributed setup. Blockwise parallel decoding by Stern, Shazeer and Uszkoreit (2018) had verified several guessed tokens in one pass earlier, but only for greedy decoding.
The acceptance rate and the walltime improvement formula
p, q— target and draft distributions at one position;DTV= ½ Σ|p − q|, the total variation distance between them.β, α— the acceptance probability at one position and its average over positions, which the analysis treats as independent.γ— draft length;c— the time of one draft step divided by the time of one target call.p′— the residual distribution the correction is drawn from.
At the extremes: α → 1 gives γ + 1 tokens per call and an improvement of (γ + 1)/(γc + 1); α = 0 gives one token per call and an improvement of 1/(γc + 1), which is a slowdown. With a free draft (c → 0) the ceiling as γ grows is 1/(1 − α). The paper also shows that whenever α > c some γ helps, by at least (1 + α)/(1 + c) at γ = 1, and that total arithmetic rises: the method spends extra FLOPs, including on rejected guesses, to cut latency.
What the speculative decoding paper measured
The main experiments sped up T5-XXL (11B parameters) in the T5X codebase, fine-tuned for English-to-German translation (WMT EnDe) and for CNN/DailyMail summarization, with T5-small (77M), T5-base (250M) and T5-large (800M) as drafts. Decoding ran on a single TPU-v4 at batch size 1, both greedily and by sampling at temperature 1, and the outputs matched standard decoding: exactly under greedy decoding, in distribution under sampling.
| Task | Draft | Decoding | Walltime speedup |
|---|---|---|---|
| EnDe translation | T5-small | greedy | 3.4× |
| EnDe translation | T5-small | sampling, T = 1 | 2.6× |
| CNN/DM summarization | T5-small | greedy | 3.1× |
| CNN/DM summarization | T5-small | sampling, T = 1 | 2.3× |
The draft-size ablation is the instructive part. Larger drafts agreed with T5-XXL more often, so α rose from T5-small to T5-large, but each draft step also cost more, and T5-large, the most accurate draft, gave the smallest speedups. The smallest draft won because its cost ratio c fell faster than its acceptance rate. Sampling at temperature 1 lowered α compared with greedy decoding, which is why the sampled rows are slower.
The paper also estimated α for pairs it did not time, including a small GPT-like decoder and LaMDA 137B with smaller LaMDA drafts, and found that even unigram and bigram drafts reach nonzero acceptance. Such a draft costs essentially nothing, so any acceptance rate α is worth up to 1/(1 − α), about 1.25× at α = 0.2. What the paper did not test is serving at large batch sizes, where the idle arithmetic the method spends is no longer idle.
What the authors admit, and what happened next
The method needs a draft model that is well aligned with the target — a draft that rarely agrees gets rejected constantly and you have paid for it for nothing — so in practice it requires a small model from the same family, which is not always available and is extra memory when it is.
The limitation that matters most in production is one the framing makes easy to predict and easy to forget: the whole argument rests on decode being bandwidth-bound, and at large batch sizes it is not. Batching many sequences already amortises the weight read across all of them, so the arithmetic units are no longer idle and the free capacity speculation exploits has been spent. This helps most for low-concurrency, latency-sensitive serving — a single user waiting on a response — and least for a saturated throughput-oriented server.
How it held up: it is standard in every serious serving stack, and the exactness guarantee is why it was adopted without argument — there is no quality regression to weigh. The draft model's awkwardness is the one loose end, and rung 5 removes it.
How many tokens per pass, and the best k
The speedup is a geometric sum you can hold in your hand. This computes the expected tokens per target pass, (1 − αᵏ⁺¹)/(1 − α), and checks its limits: a useless draft (α=0) yields exactly 1 token per pass, a perfect draft (α=1) yields k+1. Then it factors in draft cost and sweeps the draft length k — and you'll see the speedup rise, peak around k=2–4, and fall as over-long drafts waste compute on tokens that get rejected. Change the acceptance rate α or the draft cost and watch the sweet spot move.
Write the body of accepted_prefix. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- The closed form equals the geometric sum
- A perfect draft yields k+1 tokens per pass
- A useless draft yields exactly 1 token per pass
- The accepted prefix stops at the first rejection
- Draft cost makes an over-long k worse
What came after
Speculative decoding kicked off a wave of "guess-and-verify" inference methods, most aimed at removing the need for a separate draft model. Medusa bolts extra prediction heads onto the target model itself so it can propose its own future tokens. EAGLE drafts in the model's feature space for higher acceptance. Lookahead decoding generates and verifies n-grams without any draft model at all. All share the same skeleton: propose cheaply, verify in parallel, keep what's correct.
The lasting idea is a reframing of what a forward pass is for. A big model's pass has spare compute; instead of spending it on one token, spend it checking many. That principle — verification is parallel and cheap, generation is serial and expensive, so trade the former for the latter — now underlies a whole branch of efficient-inference research.
The same verify-in-parallel trick appears elsewhere: it's why prefilling a long prompt is fast (all positions at once) but generating is slow (one at a time). Speculative decoding basically makes generation borrow prefill's parallelism.
Why it still matters
Speculative decoding is the key idea behind making LLM generation faster without changing what it produces. Normal decoding is one token per forward pass, and each pass is memory-bound, so the big model's compute sits mostly idle. Speculative decoding uses a small, cheap draft model to guess several tokens ahead, then has the large target model verify all those guesses in a single pass.
The guarantee is what makes it beautiful: the target model accepts the longest prefix of the draft that matches its own distribution and rejects the rest, and the acceptance/rejection sampling is designed so the final output is statistically identical to what the target model would have produced alone. You get a speedup for free — no quality loss, no different outputs.
How much you gain depends on how often the draft guesses right: a well-matched, fast draft model that agrees with the target most of the time yields several tokens per verification pass. The technique turns an underused, memory-bound big model into one that commits multiple tokens per step by spending a little cheap draft compute.
It matters because inference cost and latency dominate the economics of running LLMs, and lossless acceleration is rare and valuable. Speculative decoding — and its self-drafting variants like Medusa, plus draft-model and n-gram flavors — is now a standard feature of production serving stacks. It reframed the latency problem: don't shrink the model, predict its output cheaply and verify.
Questions people ask about Speculative Decoding
Why does speculative sampling resample from max(0, p − q)?
Because that is exactly the probability mass acceptance under-delivers. If the draft proposes x with probability q(x) and keeps it with probability min(1, p(x)/q(x)), token x comes out through acceptance with probability min(p(x), q(x)). Tokens where the target wants more than the draft offers, p(x) above q(x), are short by p(x) minus q(x). Rejection happens with probability equal to the sum of those shortfalls, so drawing the correction from the normalized shortfall, max(0, p − q) divided by its total, adds exactly the missing amount to every token. The two routes sum to p(x), which is why the emitted tokens follow the target model's distribution exactly, not approximately.
What is the speculative decoding speedup formula?
Leviathan, Kalman and Matias give the expected walltime improvement as (1 − α^(γ+1)) divided by (1 − α)(γc + 1), where α is the average acceptance rate, γ the number of drafted tokens per round and c the cost of one draft step relative to one target call. The first part, (1 − α^(γ+1)) over (1 − α), is the expected number of tokens per target call; γc + 1 is the time one round takes, in target calls. With α = 0.8, γ = 4 and c = 0.05 the formula gives about 2.8 times. It assumes acceptances are independent across positions and that a target call checking γ + 1 positions costs about the same as one that checks a single position.
Does speculative decoding work with temperature sampling or only greedy decoding?
Both. The accept-and-resample rule is stated for arbitrary distributions, and temperature, top-k and nucleus sampling are transformations of the target's and the draft's distributions that can be applied to both before the acceptance test, so the output still follows the target's adjusted distribution. Greedy decoding is the special case where both distributions put all their mass on one token, so a guess is kept exactly when it matches the target's argmax. In the paper's T5 experiments, sampling at temperature 1 was slower than greedy decoding, 2.6 against 3.4 times on translation with a T5-small draft, because random samples are harder for a draft to anticipate.
How is the acceptance rate α related to total variation distance?
At a single position, the probability that a drafted token is accepted is the sum over the vocabulary of min(p, q), and that sum equals one minus the total variation distance between the target distribution p and the draft distribution q. The paper defines α as the expected value of this quantity over positions. The practical consequence is that a draft is judged on its whole distribution, not just its top choice: a draft whose top token often matches but which spreads probability very differently will still be rejected often under sampling. It also means α can be estimated offline, from both models' distributions on sample text, before anything is timed.
Who invented speculative decoding, Leviathan et al. or Chen et al.?
The two papers are generally treated as concurrent. Leviathan, Kalman and Matias at Google posted theirs in November 2022 and published it at ICML 2023, naming the method speculative decoding and testing it on T5-XXL. Chen and colleagues at DeepMind posted the same accept-and-resample scheme in early 2023 as speculative sampling, applied to Chinchilla 70B with a 4B draft model and reporting a 2 to 2.5 times speedup. Earlier still, blockwise parallel decoding by Stern, Shazeer and Uszkoreit in 2018 verified several guessed tokens in one pass, but only for greedy decoding and with prediction heads trained into the model rather than a separate draft.
What is the best draft length γ for speculative decoding?
The one that maximizes the walltime formula for your measured acceptance rate α and cost ratio c, which is easy to find numerically. Longer drafts raise the ceiling of γ + 1 tokens per call, but each extra guess only counts if every earlier one survived, so its expected value shrinks like α raised to its position while its cost c stays fixed. With α = 0.8 and c = 0.05, the formula rises from about 1.7 times at γ = 1 to about 2.8 at γ = 4 and peaks near 3.1 around γ = 7 or 8 before falling. In practice the optimum is a handful of tokens, and it moves with the task and the draft.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
Draft q = [0.50, 0.30, 0.15, 0.05] and target p = [0.35, 0.40, 0.10, 0.15] over four tokens. What is the chance the drafted token is accepted, and what distribution is the correction drawn from?
Show answer
β = Σ min(p, q) = 0.35 + 0.30 + 0.10 + 0.05 = 0.80. The residual max(0, p − q) is [0, 0.10, 0, 0.10] with mass 0.20, so the correction is drawn from [0, 0.5, 0, 0.5]: only tokens the draft under-proposes can be chosen.
In that same example, can you show that the second token comes out with probability exactly p = 0.40?
Show answer
Through acceptance: min(0.40, 0.30) = 0.30. Through rejection: 0.20 × 0.5 = 0.10. Total 0.40. The first token gives 0.35 + 0.20 × 0 = 0.35, also equal to its p. Every token checks out, which is the exactness proof in miniature.
With α = 0.8, γ = 4 and a draft costing c = 0.05 of a target call, what walltime improvement does the formula predict, and what if the draft cost c = 0.5?
Show answer
Tokens per call: (1 − 0.8^5)/0.2 ≈ 3.36. At c = 0.05 a round costs 1.2 target calls, so ≈ 2.8×. At c = 0.5 it costs 3 target calls, so ≈ 1.12×: the same acceptance rate is nearly worthless with an expensive draft.
Predict: a bigram draft costs essentially nothing (c ≈ 0) but is accepted only about 20% of the time. What is the best speedup it can give, however long the draft?
Show answer
With c = 0 the formula becomes (1 − α^γ+1)/(1 − α), which tends to 1/(1 − α) as γ grows: 1.25× at α = 0.2. A cheap draft cannot beat its own acceptance rate; only a more accurate one can.
Serving it cheaply
Five papers about the bill. Each one buys throughput back from a different part of the stack: the weights, the memory hierarchy, the KV cache, the decode loop.
- 1Knowledge Distillation2014
- 2FlashAttention2022
- 3PagedAttention2023
- 4Speculative Decoding2023
- 5Medusa2024
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →