Speculative decoding: reject a guess without changing the distribution
推测解码
Derive the acceptance correction, verify an actual block sampler and separate expected savings from measured speed.
speculative-decodingA wrong guess can still save a correct computation
A small draft model predicts a few tokens cheaply. A larger target model checks those known tokens together. Some guesses are accepted; at the first rejection, the rest of that draft is discarded. The useful trick is the replacement distribution: choosing it correctly preserves the target’s sampling distribution, even when the draft is poor.
Take three tokens with target probabilities 0.5, 0.3 and 0.2, and draft probabilities 0.2, 0.5 and 0.3. The draft proposes the first token too rarely and the other two too often. Accepting every guess would reproduce the wrong distribution. The correction below accepts probability mass 0.2, 0.3 and 0.2, then supplies the missing 0.3 entirely to the first token.
Leviathan, Kalman and Matias call the target distribution and draft . Chen and colleagues describe a closely related speculative sampling procedure but use the opposite symbols. This article consistently uses for the target. Confusing the two conventions reverses the crucial rejection correction.
Preserve probability mass at each prefix
An autoregressive target defines a sequence distribution through its prefix-conditioned probabilities:
At a fixed prefix, draw a proposal from . Accept it with probability:
A token with zero draft probability cannot be proposed, so the sampler never needs to divide by that zero. Such a token can still appear through the correction. The total acceptance probability is:
Thus acceptance depends on overlap of the distributions, not merely whether their most likely tokens match. After a rejection, sample from:
This formula is used only when rejection has positive probability. If , acceptance is certain and the residual is unnecessary. If the supports are disjoint, every guess is rejected and the residual equals the target.
The preservation proof is a probability-mass accounting identity. A token can arrive through acceptance or through rejection followed by correction:
For the opening vectors, and . Resampling directly from after rejection would be wrong: the accepted mass plus would be , not the target. The residual corrects exactly the part that acceptance has not already supplied.
For a draft of length , generate proposals autoregressively and keep the draft distributions used for each one. The target scores all draft-conditioned prefixes, plus the position after the complete draft:
Verify in order. At the first rejection, emit a corrected token and discard later proposals and their target scores because they were conditioned on the rejected history. If all proposals pass, emit one extra token from . A Transformer can score this known continuation in a causal forward pass; the small Python model below performs those calculations serially.
Under an explicit simplifying assumption of independent, identically distributed acceptance events with probability , the expected emitted block length is:
For , use . Suppose one draft step costs a fraction of one target step, and scoring the whole known draft has the latency of one target step. The idealized long-run speed ratio is:
These are assumptions, not timing measurements. Real acceptance depends on prefixes; target latency can grow with draft length; memory, batching and draft cost matter. At , the modeled ratio peaks near 1.980786 at among the tested integers 1–8, then falls. Longer speculation is not automatically better.
An actual block sampler with an exact small oracle
The complete NumPy program uses two three-token Markov models. It drafts a block, calculates the corresponding target distributions, verifies sequentially and uses the corrected residual on rejection. Output length is fixed; there is no end-of-sequence token in this example.
"""Finite Markov speculative sampler; target scoring is serial Python, not a speed benchmark."""
import json
import numpy as np
def distribution(p):
p=np.asarray(p,dtype=float)
if p.ndim!=1 or not len(p) or not np.isfinite(p).all() or (p<0).any() or not np.isclose(p.sum(),1,rtol=0,atol=1e-12):
raise ValueError('A finite normalized probability vector is required')
return p/p.sum()
def correction(target,draft):
p,q=distribution(target),distribution(draft)
if p.shape!=q.shape:raise ValueError('Common vocabulary required')
accepted=np.minimum(p,q);residual=np.maximum(p-q,0)
reject=float(residual.sum())
return accepted, None if reject==0 else residual/reject
def models():
p0=np.array([.5,.3,.2]);q0=np.array([.2,.5,.3])
p=np.array([[.55,.25,.2],[.2,.6,.2],[.3,.2,.5]])
q=np.array([[.4,.35,.25],[.25,.4,.35],[.4,.25,.35]])
return (p0,p),(q0,q)
def probabilities(model,prefix):
return model[0] if not prefix else model[1][prefix[-1]]
def step(prefix,target,draft,gamma,rng):
if type(gamma) is not int or gamma<1:raise ValueError('Positive integer lookahead required')
guesses=[];qs=[]
for _ in range(gamma):
q=distribution(probabilities(draft,prefix+guesses));qs.append(q)
guesses.append(int(rng.choice(len(q),p=q)))
# A real Transformer can score these known prefixes in one causal forward pass.
ps=[distribution(probabilities(target,prefix+guesses[:i])) for i in range(gamma+1)]
accepted=[]
for i,x in enumerate(guesses):
if rng.random()<min(1.,ps[i][x]/qs[i][x]):
accepted.append(x)
else:
_,r=correction(ps[i],qs[i])
if r is None:raise ArithmeticError('Rejected equal distributions')
return accepted+[int(rng.choice(len(r),p=r))],len(accepted)
p=ps[-1]
return accepted+[int(rng.choice(len(p),p=p))],len(accepted)
def generate(target,draft,length,gamma,rng):
if type(length) is not int or length<1:raise ValueError('Positive integer output length required')
prefix=[];iterations=0;accepted=0
while len(prefix)<length:
emitted,n=step(prefix,target,draft,gamma,rng)
prefix+=emitted;iterations+=1;accepted+=n
return prefix[:length],dict(iterations=iterations,accepted=accepted)
def ideal_gain(alpha,gamma,draft_cost):
if not 0<=alpha<=1 or type(gamma) is not int or gamma<1 or not np.isfinite(draft_cost) or draft_cost<0:
raise ValueError('Invalid acceptance/cost assumptions')
return sum(alpha**i for i in range(gamma+1))/(1+gamma*draft_cost)
def demo():
target,draft=models();a,r=correction(target[0],draft[0]);rng=np.random.default_rng(43)
samples=4000;counts=np.zeros(3);iterations=0
for _ in range(samples):
sequence,stats=generate(target,draft,4,2,rng);counts[sequence[-1]]+=1;iterations+=stats['iterations']
return dict(target=target[0].tolist(),draft=draft[0].tolist(),accepted_mass=a.tolist(),
acceptance=float(a.sum()),residual=r.tolist(),exact_one_step=(a+(1-a.sum())*r).tolist(),
last_target=(target[0]@np.linalg.matrix_power(target[1],3)).tolist(),
last_empirical=(counts/samples).tolist(),samples=samples,
iterations_per_four_tokens=iterations/samples,
gain=[dict(gamma=g,value=ideal_gain(.7,g,.1)) for g in range(1,9)],
scope='Fixed length, no EOS; cost curve assumes iid acceptance and constant batched target latency')
if __name__=='__main__':print(json.dumps(demo()))
The opening correction reconstructs exactly 0.5, 0.3 and 0.2 within float arithmetic. For 4,000 sampled length-four sequences with seed 43, the last-token frequencies are 0.36075, 0.37000 and 0.26925. The target’s exact last-position marginal is approximately 0.355288, 0.361313 and 0.283400. Sampling noise explains the difference; the empirical check alone is not a proof.
The independent test additionally enumerates every draft and acceptance/rejection branch for length-three output. It drives the actual step function with prescribed random choices, multiplies each branch probability and compares all 27 output-sequence probabilities with the target. It also checks all pairs of three-token distributions whose probabilities are multiples of one quarter, including zeros.
The observed mean is 2.112 speculative iterations per four-token sample. This is a count of iterations, not GPU latency. The separate cost curve uses constant acceptance 0.7; our Markov model’s acceptance changes with its prefix, so that curve is not fitted to these samples. A final emitted block may exceed the requested length and is truncated; unused generated tokens still consumed computation.
Distribution equality has conditions
The draft and target must refer to the same token space for this algorithm. If temperature, top-k, top-p or constraints alter either sampling distribution, verify using those actual adjusted distributions. Correcting raw model probabilities while sampling from a truncated proposal generally invalidates the proof.
Equality in distribution does not imply identical text under the same pseudorandom seed. The two samplers consume random numbers differently. Numerical discrepancies between sequential and batched target scoring can also affect exact agreement; test the intended precision and kernels. The papers discuss hardware and scoring conditions rather than promising a universal speed multiplier.
This example omits KV-cache rollback, tokenizer reconciliation, concurrent requests and EOS handling. Those are required engineering decisions for a real service. When a proposal is rejected, the associated cache must follow the accepted prefix, not retain states from the abandoned branch. The finite Markov oracle verifies probability logic without claiming to implement that serving machinery.
Follow the mass after a rejection
- For the opening target and draft, what is the probability of rejecting a proposed second token? Answer: Its acceptance probability is , so conditional rejection is 0.4. Multiplying by its proposal probability gives rejected mass 0.2 from that token.
- Why is drawing directly from the target after rejection incorrect? Answer: Some target mass was already delivered by acceptance. Direct resampling adds it again in the wrong proportions; the opening example becomes . Use the normalized positive difference instead.
- With , and , calculate the ideal ratio. Answer: Expected block length is and modeled cost is 1.2 target-step units, giving 1.825. This depends on the stated latency and acceptance assumptions.
- All two draft tokens pass. Why generate one more target token? Answer: Scoring the entire known draft already provides the next-position target distribution. Sampling it yields a third correct token and accounts for the extra one in the block-length formula.
Speculation trades extra work for fewer serial waits
Leviathan and colleagues separate probability preservation, acceptance and wall-time analysis. Chen and colleagues emphasize conditional scoring and modified rejection sampling, including numerical and hardware qualifications. Both motivate doing extra predictable work when it can reduce sequential latency; neither makes this Python implementation a speed benchmark.
Continue with temperature and top-k/top-p to see how the distributions being preserved are constructed. The correct target is the requested sampling policy’s distribution, not automatically the unmodified softmax.
Make a prediction, then check
After a rejection, which distribution corrects a draft q toward a target p?
Learning objectives
- Prove one-step distribution preservation and its prefix-conditioned extension.
- Handle zero support and the all-accepted extra token correctly.
- State the iid acceptance and target-latency assumptions behind a cost estimate.
Prerequisites & connections
Explore related knowledge →References
- Fast Inference from Transformers via Speculative Decoding
Yaniv Leviathan; Matan Kalman; Yossi Matias · 2023 - Accelerating Large Language Model Decoding with Speculative Sampling — v1
Charlie Chen; Sebastian Borgeaud; Geoffrey Irving; Jean-Baptiste Lespiau; Laurent Sifre; John Jumper · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Leviathan section2.2 text and PDF3/4 Algorithm1/cost assumptions; Chen v1 PDF3/4 Algorithm2 and scoring qualifications. Eight paired equations and four explained exercises. Original actual block sampler checked by exact enumeration of all27 length-three output probabilities, quarter-grid distributions including zero support and seeded4000 samples. Opposite paper notation reconciled; iid cost curve separate from prefix-varying Markov experiment. No GPU speed or KV rollback implementation.
- Single AI author read Leviathan section2.2 text and PDF3/4 Algorithm1/cost assumptions; Chen v1 PDF3/4 Algorithm2 and scoring qualifications. Eight paired equations and four explained exercises. Original actual block sampler checked by exact enumeration of all27 length-three output probabilities, quarter-grid distributions including zero support and seeded4000 samples. Opposite paper notation reconciled; iid cost curve separate from prefix-varying Markov experiment. No GPU speed or KV rollback implementation.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.
Source locations checked:
- Fast Inference from Transformers via Speculative Decoding · Read section2.2 text and visually inspected PDF3–4: section2.3/Algorithm1, acceptance, iid expected block length and cost assumptions. Uses p for target and q for draft. No T5 or GPU timing reproduction.
- Accelerating Large Language Model Decoding with Speculative Sampling — v1 · Visually read PDF3–4: Algorithm2, conditional scoring, rejection correction and hardware qualifications. The paper calls the target q and draft p, opposite to this chapter. No Chinchilla benchmark reproduced.
Related topics