12.4 Speculative Decoding
Imagine a model completing the same prefix over and over. Its next token must be A three times as often as B. A smaller model can draft the next tokens, but it has the odds backwards. Can the server use those drafts and still deliver the original 75/25 split? This is the question behind speculative sampling, the randomized form of speculative decoding. [1] [2]
What one target pass buys
At small decode batches, reading the target model’s weights can take much of the time needed to produce a single token. A cheaper draft model proposes a chain of tokens. Given the prefix and the chain, the target can score the proposed continuation in parallel. Its causal mask still ensures that the score at each position depends only on the preceding tokens. The verifier needs the next-token distribution at the original prefix, after each accepted proposal and, for a bonus token, after the entire chain. The first of these distributions can already be available from the preceding target computation. [1]
Walk along the chain in order. Keep a proposal if it passes the acceptance test below. At the first rejection, draw a replacement from the residual distribution, discard the remaining proposals, and begin the next cycle from the committed prefix. If all proposals pass, sample one bonus token from the target, subject to the output limit and end-of-sequence rule. A rejection at the first position produces one output token. A fully accepted chain can produce .
Why redrawing from the target gives the wrong answer
Return to A and B. At this prefix the draft probabilities are 25% A and 75% B. The target probabilities are 75% A and 25% B. Keep all the A proposals and one third of the B proposals. Measured across all draws, that commits 25% A and 25% B. The remaining 50% of draws must produce A to meet the target.
If you redraw those rejections from the original target, only three quarters of them become A. The final probability of A is . Now move the draft probability past the target probability. Which token must supply the missing mass?
| Calculation | A | B |
|---|---|---|
| Kept from the draft | 25% | 25% |
| Added after rejection | 50% | 0% |
| Final distribution | 75% | 25% |
| If redrawn from the target | 62.5% | 37.5% |
Rejection probability is 50%. Every replacement drawn from the residual is A.
Generally, when proposes a token with , accept it with probability . The probability of both proposing and accepting is . The missing mass for each possible token is . Summing over the vocabulary gives the rejection probability . On rejection, draw with probability . Adding the accepted and replacement contributions gives . If , every proposal passes and the replacement step is skipped. [1] [2]
This calculation applies at each committed prefix using the probabilities after serving-time filters such as temperature and top-p. The guarantee concerns the distribution. Two samplers with the same seed can consume different random draws and produce different text.
When does another draft token pay for itself?
Suppose and, for this cost example only, each draft passes independently with probability . The cycle emits one token for certain, a second with probability , and a third with probability . That is 1.75 output tokens per cycle on average, assuming no early stop. If ordinary decoding takes 10 ms per token, the work replaced averages 17.5 ms. An illustrative draft-and-verify cycle taking 14 ms delivers a gain. A 20 ms cycle loses time at the same acceptance rate. Measure these costs on the workload you serve. [1]
Record accepted draft tokens by depth, discarded proposals, verification time and state restoration time. On rejection, resume both models from a state consistent with the committed prefix. Entries computed for the discarded suffix must never affect later predictions. Measure end-to-end latency percentiles and delivered tokens per second with matching prompts, sampling settings and batch scheduling. A longer accepted chain can still lose to ordinary decoding if it takes longer to produce.
Educational Verification Reference
The Python code checks one chain of proposals against target distributions for the same prefixes. The final line reports the tokens committed in one seeded cycle and how many came from the draft.
This standard-library example takes normalized probabilities over one shared vocabulary. Model execution, logits filters, batched tensors, EOS and length limits, KV caches and distributed scheduling are outside the example.
import math
import random
def validate_distribution(probabilities):
if not probabilities or any(not math.isfinite(p) or p < 0 for p in probabilities):
raise ValueError("require finite nonnegative probabilities")
if not math.isclose(sum(probabilities), 1.0, abs_tol=1e-8):
raise ValueError("probabilities must sum to one")
def draw(probabilities, rng):
threshold = rng.random() * math.fsum(probabilities)
cumulative = 0.0
for token, probability in enumerate(probabilities):
cumulative += probability
if threshold < cumulative:
return token
# Rounding can leave the running sum just below the threshold.
return max(token for token, probability in enumerate(probabilities) if probability > 0)
def verify_draft_tokens(draft_probs, target_probs, draft_tokens, rng):
# One sequence: q has K rows; p has K+1 rows, including the bonus.
# Each p row is target-verified under the corresponding draft prefix.
k = len(draft_tokens)
if k < 1 or len(draft_probs) != k or len(target_probs) != k + 1:
raise ValueError("require K draft rows and K+1 target rows")
vocab = len(target_probs[0])
for row in [*draft_probs, *target_probs]:
validate_distribution(row)
if len(row) != vocab:
raise ValueError("draft and target must share a token space")
output = []
for i, token in enumerate(draft_tokens):
if not 0 <= token < vocab or draft_probs[i][token] <= 0:
raise ValueError("proposal must have positive draft probability")
q = draft_probs[i][token]
p = target_probs[i][token]
if rng.random() < min(1.0, p / q):
output.append(token)
else:
residual = [max(pj - qj, 0.0)
for pj, qj in zip(target_probs[i], draft_probs[i])]
mass = sum(residual)
if mass <= 0:
raise ArithmeticError("rejection with no residual mass")
output.append(draw([value / mass for value in residual], rng))
return output, i # accepted draft count; no bonus after rejection
output.append(draw(target_probs[k], rng))
return output, k # bonus only when all K draft tokens were accepted
rng = random.Random(7)
q = [[0.25, 0.75]]
p = [[0.75, 0.25], [0.5, 0.5]]
proposal = [draw(q[0], rng)] # sample from q, not argmax(q)
output, accepted_drafts = verify_draft_tokens(q, p, proposal, rng)
print(output, accepted_drafts)
Tree Speculation Needs Branch-Safe State
Research snapshot as of 2026-11-25. A September DeepSeek-V4-Flash study integrates tree speculation with compressed attention using branch-aware verification, isolated temporary state, and refresh of the accepted path [3]. As branches diverge, their compressed states can differ. Verification must preserve each branch’s state until it is known which path will be kept. The study reports throughput saturation even as accepted draft length keeps growing.
For engineering validation, compare with non-speculative sampling under the same effective temperature and top-k/top-p filters, not just the same raw logits. Test rejection at every depth, all-accepted bonus handling, EOS, cancellation, mixed batch lengths, and restoration of compressed/recurrent state. Measure accepted draft tokens separately from replacement and bonus tokens, and report total time including drafting, verification, state refresh, and scheduling. A longer accepted draft is not automatically a faster service.
Quizzes
Quiz 1: Is parallel draft verification always faster?
No. Reusing weight reads helps when bandwidth dominates, but acceptance, drafting, verification work, KV/recurrent-state restoration and batch size determine the gain. Compare latency and throughput at matched output distributions and load.
Quiz 2: The draft proposes A 25% of the time and the target needs A 75% of the time. What goes wrong if you redraw every rejected proposal from the target?
Accepted proposals already contribute 25% A and 25% B. Redrawing the rejected half adds 37.5% A and 12.5% B. You end with 62.5% A. All replacements must be A in this example.
Quiz 3: What happens when the draft and target have exactly the same distribution at a position?
Every token that can be proposed has acceptance probability 1. There is no rejection, so the sampler never divides by the zero residual mass.
Quiz 4: With no early stopping, how many tokens does one cycle emit on average if it proposes tokens whose acceptance events are independent with constant probability ?
One token is certain. A second requires one acceptance, a third requires two, and an output of length requires all . The expectation is . This equals for and for . In production, estimate how often each depth is reached under the actual stopping policy.
References
- Leviathan, Y., et al. (2023). Fast Inference from Transformers via Speculative Decoding. ICML 2023.
- Chen, C., et al. (2023). Accelerating Large Language Model Decoding with Speculative Sampling. arXiv:2302.01318.
- Liu, C., & Li, Z. (2026). Adapting Tree-Structured Speculative Decoding to DeepSeek-V4 for Efficient Inference. Source.