← Blogs

Speculative Decoding

Autoregressive decoding runs the full target model once per generated token, and at small batch sizes each of those passes is limited by memory bandwidth, not compute. Speculative decoding lets a cheap draft model guess several tokens ahead and has the target check all of them in a single pass. A rejection step on each guess, proposed concurrently by Leviathan et al. and Chen et al., keeps the output distributed exactly as if the target had sampled it alone.

Memory-Bound Decoding

A forward pass of an $N$-parameter model costs about $2N$ FLOPs per token, and at 16-bit precision it reads $2N$ bytes of weights, however many tokens it processes. Pushing $T$ tokens through one pass therefore has an arithmetic intensity of about

\[\frac{2NT \ \text{FLOPs}}{2N \ \text{bytes}} = T \ \text{FLOPs per byte}\]

An H100 SXM provides about 990 TFLOPS of dense BF16 against 3.35 TB/s of memory bandwidth, roughly 300 FLOPs per byte. Decoding one token per pass leaves almost all of that compute idle, and a pass over a handful of tokens takes about as long as a pass over one. The KV cache behaves the same way, since a sequence’s cache is read once per pass however many of its tokens attend to it. So the cost of a decoding step is set by the pass itself, not by the number of tokens in it.

Parallel Verification

Given a prefix $h$, the draft model samples $K$ tokens one at a time,

\[x _i \sim q _i = q(\cdot \mid h, x _1, \dots, x _{i-1}), \quad i = 1, \dots, K\]

and keeps every $q _i$. The target then runs once on $h, x _1, \dots, x _K$. Under the causal mask the output at each position depends only on the tokens before it, so this one pass returns

\[p _i = p(\cdot \mid h, x _1, \dots, x _{i-1}), \quad i = 1, \dots, K + 1\]

which are exactly the distributions the target would have produced had it generated $x _1, \dots, x _K$ itself, one pass per token. Generation is sequential because each token has to be sampled before the next can condition on it, but scoring a sequence that is already written down is not.

Speculative Sampling

Take a single position with target distribution $p$ and draft distribution $q$. The draft samples $x \sim q$, and the target accepts it with probability

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

On rejection, it samples a replacement from the residual distribution

\[r(x) = \frac{\max(0, p(x) - q(x))}{\sum _y \max(0, p(y) - q(y))}\]

Then the output $Y$ is distributed exactly as $p$. Drafting $x$ and then accepting it happens with probability

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

so the probability of accepting at all is

\[\alpha = \sum _x \min(p(x), q(x))\]

and, since $p$ sums to one, the probability of rejecting is

\[1 - \alpha = \sum _x \left( p(x) - \min(p(x), q(x)) \right) = \sum _x \max(0, p(x) - q(x))\]

which is exactly the normalizer of $r$. The output is either an accepted draft or a replacement, so

\[\begin{array}{rcl} P(Y = x) & = & \min(p(x), q(x)) + (1 - \alpha) \, r(x) \\ & = & \min(p(x), q(x)) + \max(0, p(x) - q(x)) \\ & = & p(x) \quad \blacksquare \end{array}\]

The proof places no condition on $q$, so a bad draft costs speed but never correctness. What it does need is for $p$ to be the distribution the target would actually sample from, after temperature and truncation such as top-p, and for $q$ to be the distribution the draft token was actually drawn from. The two need not share sampling settings; the settings only change how much they overlap.

Resampling from $p$ itself after a rejection would be wrong. Accepted drafts have already supplied $\min(p(x), q(x))$ to every token, so a fresh draw from $p$ would count that mass twice. The residual is exactly the part of $p$ that accepted drafts do not supply.

A token can only be rejected when $q(x) > p(x)$, which is exactly where $r(x) = 0$. So the replacement is never the token that was just rejected.

For example, with a vocabulary of four tokens,

  A B C D
$p$ 0.5 0.1 0.3 0.1
$q$ 0.2 0.4 0.2 0.2
$\min(1, p / q)$ 1 0.25 1 0.5
$\min(p, q)$ 0.2 0.1 0.2 0.1
$\max(0, p - q)$ 0.3 0 0.1 0
$r$ 0.75 0 0.25 0

Accepted drafts supply $\alpha = 0.6$ of the mass, and B and D already have all of theirs. Only A and C are still short, so a rejection resamples between those two, and A ends up with $0.2 + 0.4 \times 0.75 = 0.5$ and C with $0.2 + 0.4 \times 0.25 = 0.3$. Resampling from $p$ instead would give A only $0.2 + 0.4 \times 0.5 = 0.4$, and B $0.1 + 0.4 \times 0.1 = 0.14$.

Acceptance Rate

Since $\min(a, b) = (a + b - \lvert a - b \rvert) / 2$,

\[\alpha = \sum _x \min(p(x), q(x)) = 1 - \frac{1}{2} \sum _x |p(x) - q(x)| = 1 - \mathrm{TV}(p, q)\]

so the acceptance rate is one minus the total variation distance between target and draft.

No lossless scheme that proposes a single token can keep it more often. If the draft is $X \sim q$ and the output is $Y \sim p$, however the two are coupled,

\[P(X = Y) = \sum _x P(X = Y = x) \le \sum _x \min(p(x), q(x)) = \alpha\]

Speculative sampling attains this bound. A replacement never equals the rejected token, so $Y = X$ exactly when the draft is accepted. In the language of couplings, it is a maximal coupling of $q$ and $p$.

What matters is the overlap of the full distributions, not whether their top tokens agree. A draft that always proposes the target’s argmax $\hat x$ agrees with it on top-1 every time, yet under sampling it is accepted with probability only $\alpha = p(\hat x)$. At temperature zero both distributions are one-hot, and the rule reduces to accepting exactly when the draft token is the target’s argmax, with the target’s argmax as the replacement. The output then matches greedy decoding in exact arithmetic, though the verification pass runs different kernel shapes than single-token decoding, so in floating point the logits can differ in the last bits and near-ties can flip. Acceptance is usually higher at temperature zero than under sampling. With T5-small drafting for T5-XXL on translation, Leviathan et al. measured 0.75 greedy and 0.62 at temperature one.

Drafts are usually trained to match the target with a cross-entropy or KL loss, and by Pinsker’s inequality that bounds acceptance too,

\[\alpha \ge 1 - \sqrt{\frac{1}{2} \mathrm{KL}(p \,\|\, q)}\]

but the bound can be loose, and the quantity that actually sets the acceptance rate is TV. DistillSpec found two choices to matter when distilling a draft: training on the draft’s own samples, and picking the divergence to suit the task and the decoding strategy.

Draft Chains

With $K$ drafted tokens, walk along the chain and apply the single-token rule at each position with $p _i$ and $q _i$. Accept $x _i$ with probability $\min(1, p _i(x _i) / q _i(x _i))$ and move on. At the first rejection, emit a replacement from the residual of $p _i$ and $q _i$ and stop. If all $K$ are accepted, emit one more token from $p _{K+1}$, which the same pass already computed.

Everything after a rejection is thrown away, along with its KV cache entries in both models. Both $x _{i+1}$ and $p _{i+1}$ were computed after $x _i$, so neither applies once $x _i$ is replaced. Each accepted token, on the other hand, was drafted and scored after exactly the prefix that was emitted, so the single-token argument holds at every position, and by induction the output is distributed exactly as if the target had sampled it one token at a time. A round emits between $1$ and $K + 1$ tokens for a single target pass.

Following Leviathan et al., treat the acceptances as independent, each with probability $\alpha$. The number of accepted drafts $n$ then has $P(n \ge i) = \alpha ^i$ for $i \le K$, and a round emits $n + 1$ tokens, so

\[\mathbb{E}[n + 1] = 1 + \sum _{i=1} ^K P(n \ge i) = \sum _{i=0} ^K \alpha ^i = \frac{1 - \alpha ^{K+1}}{1 - \alpha}\]

If a draft step costs $c$ target steps and a verification pass costs about one, a round takes $Kc + 1$ target steps, and the speedup over plain decoding is

\[S = \frac{1 - \alpha ^{K+1}}{(1 - \alpha)(Kc + 1)}\]

With $\alpha = 0.8$ and $c = 0.05$, $K = 4$ gives $S = 2.8$, and the best choice, $K = 8$, gives $3.1$. A free draft and an unbounded chain would reach $1 / (1 - \alpha) = 5$.

So choosing a draft trades $\alpha$ against $c$. A bigger draft is accepted more often but costs more per step, and since the expected tokens per round can never exceed $1 / (1 - \alpha)$ while the cost grows linearly in $K$, the draft with the highest acceptance is rarely the fastest.

Verification is only free while the pass stays memory-bound. A batch of $B$ sequences puts $B(K + 1)$ tokens through each pass, so at large batch sizes the pass becomes compute-bound, rejected drafts become wasted FLOPs, and the speedup shrinks or turns into a slowdown. Long contexts push the other way, since each sequence’s KV cache is read once per pass, which keeps attention memory-bound even at large batch sizes. MagicDec builds on this, with a draft that keeps a sparse KV cache, to speed up long-context decoding at large batch sizes.

Implementation

Given the target’s distributions p of shape [K+1, V], the draft’s distributions q of shape [K, V], and the drafted token ids draft,

import torch

def verify(p, q, draft):
    K = len(draft)
    i = torch.arange(K)
    accept = torch.rand(K) < p[i, draft] / q[i, draft]
    n = int(accept.int().cumprod(0).sum())
    if n == K:
        last = torch.multinomial(p[K], 1)
    else:
        residual = (p[n] - q[n]).clamp(min=0)
        last = torch.multinomial(residual / residual.sum(), 1)
    return torch.cat([draft[:n], last])

Comparing a uniform draw with the ratio accepts with probability $\min(1, p / q)$ without an explicit min, and the cumulative product keeps only the leading run of acceptances. The residual is taken over the whole vocabulary, on probabilities after temperature and truncation, not on logits.

Draft Trees

A chain has a single candidate per position, so one early rejection discards everything after it. A draft tree keeps several candidates per position and extends each of them. The target scores the whole tree in one pass by flattening it into a sequence, with an attention mask under which every node sees the prefix and its own ancestors and nothing else, and with each node’s position index set by its depth. Once a sibling is accepted, verification moves on to its children, using the target distribution the same pass computed at that node.

Testing each sibling independently against $p$ and keeping the first acceptance supplies $\min(p, q)$ once per sibling, so the output is no longer distributed as $p$. SpecInfer instead applies the single-token rule recursively, with each rejection replacing the target by its residual before the next sibling is tried. For siblings $x ^{(1)}, \dots, x ^{(k)}$, with $x ^{(j)}$ drawn from $q ^{(j)}$,

\[p ^{(1)} = p, \quad p ^{(j+1)} = \frac{\max(0, p ^{(j)} - q ^{(j)})}{\sum _y \max(0, p ^{(j)}(y) - q ^{(j)}(y))}\]

accept $x ^{(j)}$ with probability $\min(1, p ^{(j)}(x ^{(j)}) / q ^{(j)}(x ^{(j)}))$, and if all $k$ are rejected, sample from $p ^{(k+1)}$. The single-token proof only needs the replacement to be an exact sample of the residual. By induction from the last sibling, the procedure that follows each rejection is such a sample, so each level samples exactly from its $p ^{(j)}$, and the first level from $p$.

Each $q ^{(j)}$ has to be the distribution its sibling was actually drawn from. Independent siblings all use $q ^{(j)} = q$. Siblings drawn without replacement, as in recursive speculative decoding, use $q$ with the earlier siblings removed and renormalized, which the Gumbel-top-$k$ extension of the Gumbel-max trick samples in one shot. Deterministic top-$k$ siblings are point masses, for which the rule accepts the $j$-th sibling with probability exactly $p(x ^{(j)})$, so a node accepts with probability $\sum _j p(x ^{(j)})$, the target’s mass on its candidates.

With a single draft, speculative sampling is a maximal coupling, but the recursive rule for several drafts is not optimal. SpecTr casts multi-draft verification as optimal transport, whose exact solution is a linear program exponential in $k$, and gives an approximation within a factor $1 - 1/e$ of the optimal acceptance. Hu et al. compute the optimum through the dual and find existing verifiers below it, with drafts sampled without replacement ahead of drafts sampled with replacement.

Drafters

The proof holds for any $q$, so the draft can be anything that produces a distribution over the target’s vocabulary.

The original papers drafted with smaller models from the same family. Leviathan et al. drafted for the 11B T5-XXL with the 77M T5-small, reaching 2.6× at temperature one and 3.4× greedy on translation, and Chen et al. trained a 4B draft with only 8 layers, Chinchilla’s tokenizer and data, for 2× to 2.5× on Chinchilla 70B. Leviathan et al. also note that a draft which copies the continuation of a matching span from the context costs nothing to run and can be accepted often when outputs repeat their inputs. A separate model is simple to deploy, but it sees only the tokens, not anything the target computed about them.

Medusa adds extra heads on the target’s last hidden state, which predict the tokens two, three and more positions ahead. All heads run in the same step, so drafting is nearly free, but no head sees the tokens between its position and the current one, so later heads are accepted less often. Medusa assembles their top candidates into a tree, and for sampling it also offers a typical acceptance rule that gives up exactness for more acceptance.

EAGLE keeps drafting autoregressive but moves it to feature space. A single transformer layer takes the target’s last hidden states together with the tokens shifted one step ahead, predicts the next hidden state, and reuses the target’s LM head to turn it into a distribution. The next hidden state depends on which token was sampled, and the shifted tokens remove that uncertainty. EAGLE-2 grows the tree dynamically, using the draft’s own confidence as an estimate of acceptance. EAGLE-3 drops hidden-state prediction and predicts tokens directly from a fusion of low-, mid- and high-level target features, trained with training-time test, which feeds the draft its own predictions during training, and reports speedups of up to 6.5×. EAGLE-3.1 found that as the draft runs along a chain, its attention drifts from the prompt onto its own recent tokens. It adds an RMSNorm to each captured target hidden state and a post-norm on the draft’s own, which lengthens acceptance by up to 2× when the prompt template is perturbed and 1.18× on long contexts.

Multi-token prediction (MTP) makes the draft part of pretraining. Gloeckle et al. train several output heads on a shared trunk to predict several future tokens at once, and models trained with 4-token prediction decode up to 3× faster using the extra heads as drafts. DeepSeek-V3 chains its MTP modules instead, each a transformer block that combines the previous depth’s representation with the embedding of the next token, and shares the embedding and output head with the main model. It trains a single module, and as a draft that module’s prediction of the second token is accepted 85% to 90% of the time, for 1.8× the tokens per second. Structurally the module is an EAGLE draft trained along with the model, and many large open models since ship one, including DeepSeek-V4, Qwen3.5, GLM-5 and Kimi K3, which serving engines run directly as the draft.

Parallel drafting produces all $K$ draft tokens in one pass of the draft instead of $K$. P-EAGLE predicts several positions at once from a learned shared hidden state, DFlash drafts a whole block with a small block diffusion model, and DSpark pairs a parallel backbone with a light sequential module and sets each request’s verification length from the estimated chance that the drafted prefix survives. The drafting cost $Kc$ in the speedup then becomes about $c$, so the draft can afford to be deeper. However, the block size is fixed in advance.

EAGLE-4 keeps the draft autoregressive, since an autoregressive draft can stop at any depth. A cost model profiled on the hardware grows the tree one level at a time while the expected gain in accepted tokens pays for the extra draft step, then verifies only the nodes whose acceptance probability pays for the extra verification cost, which gives deep, wide trees for a single request and short chains under heavy load. It also scores the vocabulary with a low-rank candidate head, and can restrict the draft’s attention to a sliding window. On Qwen3.8-27B with four B300s and a single request, it reports 3.59× over plain decoding at temperature zero and 2.59× at temperature one. At 512 concurrent requests the same comparison gives 1.34× and 1.03×, and DFlash 2 and DSpark, with their fixed blocks, fall below plain decoding. These are results on one setup, not a general guarantee. The drop from temperature zero to one is consistent with lower acceptance under sampling, and the drop at 512 requests with the verification pass turning compute-bound.

Each of these moves a term in the speedup. A better draft raises $\alpha$, a cheaper or parallel one lowers $Kc$, and a tree raises the tokens accepted per pass, while the batch size decides whether the verification pass stays memory-bound.

Reference