AI Infra
0%
Part V · Chapter 33

Faster Decoding

AuthorChangkun Ou
Reading time~16 min

The previous two chapters separated request timing from memory allocation. They also established a rule for execution: reserve the state required by a token plan before launching it. Faster decoding changes that plan. Instead of asking the target model for exactly one new token, a proposer supplies several candidates and the target scores them together. A successful cycle can return more than one token, but it also consumes proposal time, verification work, and temporary KV state.

This trade is attractive when target decoding is underutilizing the accelerator, as low-batch dense decoding often does when weight traffic is the main cost. It is not a universal property of decoding. Long contexts add KV traffic; model parallelism adds communication; and larger batches may make verification compute-bound. The proposal must therefore be judged as part of the measured serving regime.

Two 2023 papers established exact versions of this idea: speculative decoding by Leviathan, Kalman, and Matias (Leviathan et al. 2023), and speculative sampling by Chen and colleagues (Chen et al. 2023). Later work changed where candidates come from and how they are arranged. Medusa and Hydra add draft heads (Cai et al. 2024; Ankner et al. 2024), the EAGLE family learns a feature or token drafter (Li et al. 2024; Li et al. 2024; Li et al. 2025), lookahead decoding builds candidates through iteration (Fu et al. 2024), and multi-token prediction trains future-token modules with the model (Gloeckle et al. 2024). These are design choices, not stages in a required lineage.

Verification can be parallel even when generation is sequential

Autoregressive generation still has a sequential dependency: token i+1i+1 depends on token ii. A proposed suffix makes those dependencies available as inputs. Under a causal mask, one target pass can then score every position in that suffix in parallel. The target remains authoritative; the proposal only creates candidate work.

Here γ\gamma is the length of a linear proposal. Define AkA_k as the event that draft position kk is accepted after every earlier position was accepted, and let

sk=Pr(A1Ak),s0=1.s_k=\Pr(A_1\cap\cdots\cap A_k),\qquad s_0=1.

If a cycle emits the accepted prefix plus one corrected or bonus token, and no stop condition truncates that output, its token yield YY satisfies

E[Y]=1+k=1γsk.\mathbb E[Y]=1+\sum_{k=1}^{\gamma}s_k.

This expectation means that an aggregate accepted-token rate does not determine prefix survival. Early positions may be easier than later ones, and acceptance events may be correlated. Only under the additional assumption of a constant conditional acceptance probability α\alpha at every position does sk=αks_k=\alpha^k, giving

E[Y]=k=0γαk=1αγ+11α,α1,\mathbb E[Y] =\sum_{k=0}^{\gamma}\alpha^k =\frac{1-\alpha^{\gamma+1}}{1-\alpha}, \qquad \alpha\ne1,

with E[Y]=γ+1\mathbb E[Y]=\gamma+1 when α=1\alpha=1. This is expected tokens per verification cycle, not a latency speedup. It says nothing yet about the time or memory spent on that cycle.

Here the runnable compares heterogeneous conditional probabilities with an IID estimate formed from their arithmetic mean. The two results differ even in this small deterministic example.

conditional = [0.85, 0.75, 0.60, 0.40]

survival = []
alive = 1.0
for probability in conditional:
    alive *= probability
    survival.append(alive)

expected = 1.0 + sum(survival)
alpha = sum(conditional) / len(conditional)
iid_estimate = sum(alpha**k for k in range(len(conditional) + 1))

print("survival by position:", ", ".join(f"{value:.4f}" for value in survival))
print(f"expected tokens/cycle: {expected:.4f}")
print(f"iid estimate at alpha={alpha:.2f}: {iid_estimate:.4f}")

Modified rejection sampling preserves the target distribution

speculative decoding is proposal-and-verification with a correction rule that leaves the target model's output distribution unchanged. Consider one position after applying the intended decoding policy, including temperature, logit constraints, and any top-kk or top-pp truncation. Here pp denotes the target distribution, qq the proposal distribution, and V\mathcal V their common token space. A candidate XqX\sim q is accepted with probability

a(v)=min ⁣(1,p(v)q(v)).a(v)=\min\!\left(1,\frac{p(v)}{q(v)}\right).

The denominator is defined for a sampled candidate because such a token has q(v)>0q(v)>0. On rejection, sample from the residual distribution

Z=uV[p(u)q(u)]+,r(v)=[p(v)q(v)]+Z,Z=\sum_{u\in\mathcal V}[p(u)-q(u)]_+, \qquad r(v)=\frac{[p(v)-q(v)]_+}{Z},

where [z]+=max(0,z)[z]_+=\max(0,z). The rejection probability is ZZ. For any token vv, the probability mass contributed by acceptance and correction is

q(v)a(v)+Zr(v)=min(p(v),q(v))+[p(v)q(v)]+=p(v).q(v)a(v)+Zr(v)=\min(p(v),q(v))+[p(v)-q(v)]_+=p(v).

If Z=0Z=0, the rejection probability is zero and the residual is never sampled. This one-position identity is applied left to right: stop at the first rejection, emit a corrected token, and discard the remaining proposal. If all γ\gamma candidates are accepted, sample one bonus token from the target distribution at the next position. The target pass must therefore provide distributions for all candidate positions and for that bonus position (Leviathan et al. 2023; Chen et al. 2023).

Sample candidate tokens from q while retaining the proposal probability at each position.
Run the target once with the proposed suffix, producing p for every candidate and the possible bonus position.
At each position, accept the candidate with probability min(1, p(v)/q(v)).
On the first rejection, sample one token from the normalized positive part of p − q and stop checking.
If the whole suffix survives, sample one extra token from the target's bonus-position distribution.
Keep target KV only for the accepted candidate prefix; reclaim rejected candidate state before the next cycle.
Figure 33.1. The exact linear speculative-sampling cycle. Proposal, target scoring, stochastic correction, and state commit are separate operations.

"Exact" here means equal output distributions, not identical sampled token sequences for the same seed. Floating-point kernels, batching, and random-number consumption can change a particular realization. Exactness also requires the same sampling transformation and stopping policy on the distributions being compared: temperature, truncation, constraints, and token mapping cannot be silently different. EOS, stop sequences, and maximum length may shorten a cycle and suppress the bonus token.

Greedy verification is a separate deterministic contract. It can accept the longest run that matches the target's greedy tokens and then take the target's first mismatch. Relaxed rules, such as a typical-acceptance mode, deliberately trade distribution equality for another quality or speed criterion. A system must label these contracts separately.

Proposal source, candidate topology, and acceptance policy are separate choices

Implementations make three independent choices: who proposes candidates, how candidates are arranged, and which rule authorizes output. A proposal mechanism does not by itself make sampling exact.

Proposal source Added artifact or state Natural candidate shape Important condition
Separate autoregressive model (Leviathan et al. 2023; Chen et al. 2023) Draft weights, draft KV, and draft scheduling Linear suffix Target and draft need compatible token spaces and sampling probabilities.
Attached draft heads (Cai et al. 2024; Ankner et al. 2024) Learned heads; Hydra conditions later heads on earlier candidates Linear or tree The training and acceptance recipe determines whether the result is exact, greedy, or relaxed.
Feature or token drafter (Li et al. 2024; Li et al. 2024; Li et al. 2025) A learned module beside the target Linear or dynamic tree Target verification still determines which proposed tokens may be committed.
Prompt lookup (Saxena 2023) An index or search over repeated prompt and output spans One or more retrieved suffixes It helps only when the workload contains useful repetition; verification supplies the correctness contract.
Lookahead decoding (Fu et al. 2024) A Jacobi window, n-gram pool, and custom masks Multiple n-gram continuations It removes a learned drafter, not proposal compute or temporary state.
Multi-token prediction module (Gloeckle et al. 2024; DeepSeek-AI 2024) Future-token heads trained with the base model Linear or branched proposals The training objective supplies candidates; it is not an acceptance theorem.

This table is not a ranking. A deployer may already have a compatible small model, while another model may ship with useful heads. Proposal quality can also change with domain, context length, sampling settings, and quantization. The cheapest proposal is the one that reduces measured target-cycle cost for the actual workload.

Linear chains and candidate trees spend work differently

Here a linear suffix contains γ\gamma candidate positions. If an early token is rejected, its later positions cannot be emitted in that cycle. A candidate tree hedges by carrying several continuations. A tree attention mask packs branches into one target operation while ensuring that each node attends only to its own ancestry.

flowchart TD
  C[context] --> A1[A1] --> A2[A2]
  C --> B1[B1] --> B2[B2]
  B1 --> B3[B3]
Figure 33.2. A candidate tree carries alternatives where a linear suffix carries one node per depth. Every scored node consumes verification work and temporary state; the verification policy, not the mask, decides which path can be committed.

The mask makes joint scoring possible; it does not make a verifier exact. Greedy tree search, distribution-preserving tree sampling, and relaxed tree acceptance are different algorithms. Tree width can improve the chance of finding a useful path, but verification time and temporary KV grow with the number of scored nodes. Rejected branches are real work, not free alternatives.

Speedup is a wall-clock measurement

Here t1t_1 denotes the measured time for one baseline target decode step, tpropose(γ)t_{\mathrm{propose}}(\gamma) the proposal time, tverify(γ,m)t_{\mathrm{verify}}(\gamma,m) the target time for a proposal containing mm scored candidate nodes, and treconcilet_{\mathrm{reconcile}} the acceptance, synchronization, and state-management time. For a chain, m=γm=\gamma. A useful first-order latency ratio is

SlatencyE[Y]t1tpropose(γ)+tverify(γ,m)+treconcile.S_{\mathrm{latency}} \approx \frac{\mathbb E[Y]t_1} {t_{\mathrm{propose}}(\gamma) +t_{\mathrm{verify}}(\gamma,m) +t_{\mathrm{reconcile}}}.

The denominator represents tcyclet_{\mathrm{cycle}}. In words, speculation improves average token time only when

tcycleE[Y]<t1.\frac{t_{\mathrm{cycle}}}{\mathbb E[Y]}<t_1.

Verification time grows with candidate positions, tree nodes, context length, KV traffic, batch composition, kernels, and communication. In a low-batch, weight-bandwidth-bound regime, that growth may be small enough that fewer target synchronizations win. At higher utilization, rejected candidate work can compete with other requests. Compute-bound operation can reduce the advantage, but it does not prove that every proposal must lose; proposal placement, overlap, kernels, and synchronization still matter.

Paper results demonstrate feasibility in their evaluated settings, not portable multipliers. Leviathan and colleagues reported twofold to threefold improvement on their T5 experiments (Leviathan et al. 2023), while EAGLE reported 2.7 to 3.5 times lower latency on its evaluated LLaMA2-Chat configurations (Li et al. 2024). Those numbers used different models, hardware, software, sampling settings, and baselines. Reproduce the configuration before comparing them.

The scheduler must plan speculative work

Chapter 32's reserve, execute, and commit protocol applies directly. Before a cycle begins, the scheduler should reserve candidate positions and workspace. A linear proposal needs room for its candidate suffix; a tree needs room for all scored nodes. Admission must use that planned maximum, not the expected accepted length.

After verification, commit target KV only for the accepted draft prefix and release every rejected tail or branch. Draft and target caches are separate namespaces: their tensors come from different models or modules and are not interchangeable. The corrected or bonus token becomes input to the next target cycle, where its own target KV is materialized. The scheduler must roll reservations back on cancellation or failure before the same blocks are offered elsewhere.

Different requests accept different prefix lengths, so the next batch is ragged. The scheduler must preserve each request's positions, masks, stop state, and cache ownership while repacking work. Under memory pressure or rising concurrency, it may shorten γ\gamma, narrow a tree, select a cheaper proposal, or fall back to ordinary one-token decoding. No universal batch cutoff chooses among those policies.

Choose from workload evidence

A deployment decision starts with a contract and ends with a load test.

  1. Fix the output contract. Decide whether the service promises exact sampling, greedy sequence equality, or a documented relaxed rule. Confirm the target, tokenizer, vocabulary mapping, model revision, adapters, sampling transforms, constraints, and stopping behavior. Here the named transforms include top-kk and top-pp.
  2. Profile proposal budgets. Sweep chain length or tree-node budget across representative context lengths, output types, batch shapes, and sampling settings. Include low-acceptance workloads rather than tuning only on the easiest prompts.
  3. Measure the whole cycle. Record the accepted-prefix length distribution, proposed, verified, accepted, corrected, and bonus tokens; target cycles per output token; proposal, verification, and reconciliation time; and temporary KV and workspace high-water marks.
  4. Evaluate as a service. Compare at matched admitted load and report TTFT, TPOT, inter-token latency, end-to-end latency, output throughput, goodput, rejection rate, cost, and energy. Inspect both medians and tails.
  5. Keep a fallback. Disable speculation when its predicted cost exceeds baseline decoding, when capacity cannot be reserved, or when compatibility checks fail. Record when and why fallback occurs.

No single acceptance rate or paper speedup answers whether the deployment wins. For example, two systems can accept the same fraction of candidates but place rejections at different positions, producing different E[Y]\mathbb E[Y]. They can also have the same yield but very different target verification times.

Correctness and failure tests

Test the sampler and the memory protocol independently, then together.

  • On a tiny vocabulary, compare empirical output frequencies with the target distribution for p=qp=q, partial overlap, and disjoint support. Here partial overlap means that only part of the proposal's probability mass matches the target. Force first rejection, later rejection, and full acceptance.
  • Compare greedy output token for token with baseline decoding. Exercise EOS, stop sequences, and maximum length, including full acceptance at a boundary.
  • Repeat under temperature, top-kk, top-pp, grammar constraints, and logit processors. Reject a tokenizer, adapter, or constraint mismatch before work begins.
  • Batch requests with mixed accepted-prefix lengths. Verify positions, masks, output order, and per-request random state after repacking.
  • Cross a cache-block boundary, reject a wide tree, cancel during verification, and inject a target failure. Reconcile every reservation, committed block, reference count, and released branch.
  • Compare numerical distributions within a stated tolerance across batch and kernel configurations. Do not require bitwise-identical stochastic samples.
  • Drive acceptance low and memory pressure high. Confirm bounded queueing and a clean return to baseline decoding.
What's contested

There is no universal best proposal source, tree shape, draft length, or batch cutoff. Exact stochastic sampling, exact greedy sequences, and quality-tolerant acceptance are also different product contracts. Cross-paper speedups are not comparable without the target and draft models, hardware, parallelism, batch, context, sampling policy, baseline, and load. The open operational question is not whether speculative methods can work, but where their full cycle wins for a particular service.

Constraint arrow

Faster decoding raises the useful tokens returned by some target cycles, while also widening the scheduler's temporary token plan. It composes with continuous batching, paged KV allocation, prefix reuse, and disaggregated serving only if their reservation and ownership rules include speculative state. A change in batching or memory policy changes the latency inequality, so reprofile the combination rather than multiplying isolated speedup factors.

Payoff and boundary

Proposal-and-verification does not remove autoregression. It supplies candidate dependencies so the target can verify several positions in parallel, then commits only output authorized by an explicit acceptance contract. Its payoff is fewer expensive target cycles per output token; its price is proposal work, wider verification, temporary memory, and more complex reconciliation.

The next chapter changes a complementary quantity. Quantization reduces the bytes used to represent model state, while fused kernels reduce data movement and launch overhead inside a cycle. Those changes can alter both baseline time and proposal acceptance, so faster decoding, quantization, and kernels should be measured together rather than treated as independent multipliers.

Further reading

  • Leviathan et al., “Fast Inference from Transformers via Speculative Decoding,” 2023. proceedings.mlr.press
    Speculative decoding uses a faster draft model plus modified rejection sampling to reduce target-model calls while preserving the target distribution; the reported gains are specific to the paper's T5 experiments.
  • Chen et al., “Accelerating Large Language Model Decoding with Speculative Sampling,” 2023. arXiv:2302.01318
    Speculative sampling verifies a short sequence from a trained draft model with one target-model call and uses a correction distribution to preserve the target distribution.
  • Cai et al., “Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads,” 2024. proceedings.mlr.press
    Medusa adds future-token heads and tree attention to produce and verify multiple candidates; its exact and typical-acceptance configurations have different output contracts.
  • Li et al., “EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test,” 2025. proceedings.neurips.cc
    EAGLE-3 trains a direct token drafter from fused target-model features and evaluates how drafter scale affects speculative-decoding latency and throughput.
  • Fu et al., “Break the Sequential Dependency of LLM Inference Using Lookahead Decoding,” 2024. proceedings.mlr.press
    Lookahead decoding uses Jacobi iteration and an n-gram pool to generate and verify several continuations without a learned draft model.
  • Gloeckle et al., “Better & Faster Large Language Models via Multi-token Prediction,” 2024. proceedings.mlr.press
    Multi-token prediction trains several future-token heads as an auxiliary objective; those heads can also supply candidates for self-speculative decoding.

Comments

Log in to comment