Personalize this lesson
Adapt explanations and teaching visuals to your background and preferred voice.
Consider an on-call alert: inter-token latency has crossed its service-level objective (SLO) while time to first token (TTFT) still looks healthy. Prompt prefill is finished, so the problem sits between streamed tokens. On a low-batch route, the large target rereads weights and KV state for each next-token step. Product wants faster streaming without changing target distribution. Which work can run ahead safely?
The previous chapter treated a small language model as the product: it had to fit the device and do the job itself. Here, a small language model or another cheap proposal path gets a narrower job. It proposes tokens; a larger target model remains the authority.
The draft proposes the next few tokens, then the target scores that known span in one pass. Agreement lets several tokens survive. A disagreement stops the draft at its first mismatch, and the target supplies the correction. That is speculative decoding: fewer target decode calls per emitted token, with the target distribution preserved by modified rejection sampling up to hardware numerical effects.[1][2]
The trade-off is concrete. Speculation targets low-batch LLM inference that is memory-bandwidth bound; draft work and verification overhead still have to fit the route's latency and throughput budget.
What is speculative decoding trying to reduce: model quality, target-model calls, or output length?
Answer
It tries to reduce expensive target-model decode calls per emitted token. A cheap draft proposes several tokens, and the target verifies them in parallel. If the rejection sampler is implemented correctly, quality and the target distribution stay the same in theory.
Why one decode step waits on memory
Start with the dependency. An LLM can't commit token until token exists, so serial decode exposes one target call for every output token. Prefill has many known positions to process together; decode has one new position per step. Speculation attacks that decode loop, not first-token work.
The arithmetic of billions of parameters isn't the first suspect. Modern GPUs are fast at matrix multiplication, but low-batch decode often leaves compute units waiting for weights and cache state to arrive from memory. Transformer sampling is often limited by memory bandwidth, so time to emit one token tracks parameter traffic more than leftover FLOPs.[3][2] Workload and hardware still decide the bottleneck, so profile before choosing an optimization.
Arithmetic intensity
Arithmetic intensity measures work per byte moved from memory. If one weight load lets the GPU verify 100 candidate tokens, intensity is high. If each load verifies one token, compute units spend more time waiting for the next transfer.
In GPU terms, this ratio is the number of FLOPs (floating point operations, a measure of computational performance) performed per byte of data loaded from memory:
Reading the formula
A high ratio says each byte carries more math; a low ratio points back to memory traffic as the likely limiter.
During autoregressive decoding, generating one token with a model of parameters in FP16 or BF16 (2 bytes per parameter) requires, in a weight-only first-order model:
- Compute: FLOPs (a matrix-vector multiply against the active weights)
- Memory: bytes loaded (those same weights)
Divide and you get an arithmetic intensity of ~1 FLOP/byte in that weight-only model. Chen et al. use the same first-order picture: sampling time tracks parameter size divided by memory bandwidth.[2] Real decode also pays for KV-cache traffic, activations, kernels, scheduling, and batching, so profile the engine before declaring a bottleneck.
For an illustrative dense Qwen3.6-27B BF16 target, the round diagnostic is 54 GB of weights.[4] Published checkpoints can be a bit larger because the true parameter count is not a round 27.0B and extra tensors ship with the card. Plug in deployed accelerator bandwidth before comparing serial decode with verification. The example uses 3,350 GB/s, the H100 SXM HBM3 figure, as a labeled hardware input, not a measured request time.[5]
1params_b = 27
2bytes_per_weight = 2
3h100_sxm_hbm3_gbs = 3_350 # NVIDIA H100 SXM spec; replace with the deployed device
4weights_gb = params_b * bytes_per_weight
5weight_stream_ms = weights_gb / h100_sxm_hbm3_gbs * 1_000
6
7print(f"round BF16 weight footprint: {weights_gb} GB")
8print(f"weight-only read time at {h100_sxm_hbm3_gbs} GB/s: {weight_stream_ms:.1f} ms")
9print("This is a diagnostic lower bound, not measured request latency.")1round BF16 weight footprint: 54 GB
2weight-only read time at 3350 GB/s: 16.1 ms
3This is a diagnostic lower bound, not measured request latency.| Phase | Simplified expectation | Bottleneck to measure | Intuition |
|---|---|---|---|
| Prefill (many tokens together) | Higher intensity | Often compute or mixed | Large matrix work amortizes weight loads |
| Low-batch decode (1 token) | ~1 FLOP/byte in FP16 weight-only model | Often memory bandwidth | Move active weights to emit one new token |

That arithmetic gives a hypothesis, not a verdict. Measure target decode across served batch sizes, concurrency, precisions, and context lengths; weight traffic is often dominant when the target emits one token at a time.[2]
Why does speculative decoding help more in low-batch decode than in a large prefill?
Answer
Low-batch decode has poor arithmetic intensity because it rereads weights to produce one token. Prefill already processes many known tokens together, so it naturally amortizes weight movement through larger matrix work.
Why verification can win
Take a five-token draft. Serial decode asks target to move its weights five times. Verification feeds those five known positions to target together, so one target pass can replace several serial calls when its extra query and KV work stays small. The target still scores every proposed position, even if the sampler later keeps only a prefix.
That use of known proposed tokens is teacher forcing: target scores a candidate sequence in parallel rather than choosing each token one by one. The draft pays cheap sequential work up front. The exchange is favorable only when target weight movement saved by verification exceeds draft, sampler, and cache costs.
What does teacher forcing mean in the verification step?
Answer
The target model is given the proposed draft tokens as known inputs and scores all draft positions in one forward pass. It isn't autoregressively choosing each of those tokens one at a time during verification.
The algorithm

Read the figure as one round you can check by hand. Prefix is "The model"; draft is serves with cache. The target accepts first two tokens, rejects cache, and samples latency as correction. If every draft token survives, the same target pass has logits for the next position, so sampler can emit one extra bonus token. A rejection samples from residual and rewinds KV cache.

Drafting is sequential on the cheap path. Verification is one target forward pass over the prefix plus proposed tokens. The first rejection stops the round because later draft tokens were generated on a prefix that no longer exists.
Accept/reject criterion
At each proposed position, the target and draft must score the same token under the same prefix: committed history plus any earlier accepted draft tokens. That shared condition makes their probabilities comparable.
If the target assigns at least as much probability as the draft, the verifier always accepts. If the target assigns less, verifier accepts with the ratio of target probability to draft probability; otherwise it rejects and samples a correction.
The running round uses these probabilities:
| Position | Draft token | Draft | Target | Verdict |
|---|---|---|---|---|
| 1 | serves | 0.40 | 0.60 | Accept (target likes it more) |
| 2 | with | 0.35 | 0.40 | Accept (target likes it more) |
| 3 | cache | 0.60 | 0.40 | Accept with probability |
serves and with are guaranteed accepts because target probability is higher. cache is accepted with probability because target probability is lower. This illustrated draw rejects it, so verifier stops and samples a correction from residual. There is no later draft token after cache in this example; with one, the same stop rule would discard it.
1draft_probability = 0.60
2target_probability = 0.40
3accept_probability = min(1.0, target_probability / draft_probability)
4
5print(f"accept probability for 'cache': {accept_probability:.2f}")
6print("Later drafted positions are discarded after a rejection.")1accept probability for 'cache': 0.67
2Later drafted positions are discarded after a rejection.The construction preserves the target distribution exactly in the mathematical sampler. The accepted branch contributes overlap between distributions; the residual sampler contributes missing mass. Together they reconstruct target probability for every token.[1]
Why does the verifier stop at the first rejected draft token instead of checking later draft tokens?
Answer
Later draft tokens were generated conditioned on the rejected token. Once that token is replaced, the prefix changes, so later draft probabilities are no longer conditioned on the sequence that will actually continue.
Mathematically, for each draft token , both models assign a probability to that token conditioned on the same prefix. We compare the target model's probability with the draft model's probability :
Reading the formula
Compute the ratio of the big model's probability to the draft model's probability for this token. If the big model likes it more (ratio >= 1), always accept. If the big model likes it less, accept randomly with probability equal to the ratio. The bigger the disagreement, the more likely rejection.
When a token is rejected at position , we sample a correction token from the residual distribution:
where is the normalizing constant.
In plain terms
The correction picks from tokens that the target wanted more than the draft predicted. At the rejected cache position, the draft put 60% on cache and 30% on latency. The target wanted 40% and 50%. That extra 20% on latency is the residual pool. Tokens where the draft was already too generous (cache) get zero residual probability.

This is modified rejection sampling. The accepted branch contributes ; the residual sampler contributes missing mass . Add them and you recover exactly.[1]
1tokens = ["cache", "latency", "batch"]
2draft = [0.60, 0.30, 0.10]
3target = [0.40, 0.50, 0.10]
4overlap = [min(p, q) for p, q in zip(target, draft)]
5residual_mass = [max(0.0, p - q) for p, q in zip(target, draft)]
6normalizer = sum(residual_mass)
7residual = [value / normalizer if normalizer else 0.0 for value in residual_mass]
8reconstructed = [left + right for left, right in zip(overlap, residual_mass)]
9
10print(dict(zip(tokens, residual)))
11print(f"positive correction mass: {normalizer:.2f}")
12print(f"overlap plus residual equals target: {reconstructed == target}")1{'cache': 0.0, 'latency': 1.0, 'batch': 0.0}
2positive correction mass: 0.20
3overlap plus residual equals target: TrueA draft token has draft probability 0.60 and target probability 0.40. What is the acceptance probability?
Answer
It's . The draft over-represented the token, so the verifier keeps it only with probability equal to the ratio. If it's rejected, the residual sampler draws from tokens the target wanted more than the draft did.
Implementation
The loop below mirrors Leviathan's Algorithm 1 with tiny probability tables, so you can run it without a GPU. A production engine still has two model calls per round: the draft proposes tokens autoregressively, then the target scores the prefix plus those tokens in one forward pass. In Hugging Face-style causal LMs, softmax turns each logits vector into probabilities, and position predicts token , so the row at prompt_len - 1 scores the first drafted token.
Before reading code, predict its trace: keep serves and with, reject cache, then draw latency from residual. The sampler must use the same post-processed distributions you serve, not a different temperature or top-p configuration. KV-cache rewind, EOS, batching, and logits processors stay out of this toy.[1][2]
Why must the acceptance test use the same temperature, top-p, top-k, and logits processors as serving?
Answer
The proof is about the final served distribution. If verification compares raw probabilities while serving samples from a post-processed distribution, the accept/reject math reconstructs the wrong target distribution.
1def top_k_normalize(probabilities, k):
2 kept = sorted(range(len(probabilities)), key=probabilities.__getitem__, reverse=True)[:k]
3 total = sum(probabilities[index] for index in kept)
4 return [probabilities[index] / total if index in kept else 0.0 for index in range(len(probabilities))]
5
6raw_target = [0.55, 0.30, 0.15]
7raw_draft = [0.40, 0.35, 0.25]
8served_target = top_k_normalize(raw_target, k=2)
9served_draft = top_k_normalize(raw_draft, k=2)
10token_id = 1
11
12raw_accept = min(1.0, raw_target[token_id] / raw_draft[token_id])
13served_accept = min(1.0, served_target[token_id] / served_draft[token_id])
14print(f"raw acceptance: {raw_accept:.3f}")
15print(f"served top-k acceptance: {served_accept:.3f}")
16print("Verification must use served probabilities.")1raw acceptance: 0.857
2served top-k acceptance: 0.756
3Verification must use served probabilities.1from random import Random
2
3VOCAB = ("cache", "latency", "batch")
4
5def residual_mass(target, draft):
6 return [max(0.0, p - q) for p, q in zip(target, draft)]
7
8def normalize(mass):
9 total = sum(mass)
10 if total == 0.0:
11 raise ValueError("residual has no positive mass")
12 return [value / total for value in mass]
13
14def sample(probs, rng):
15 draw = rng.random()
16 cumulative = 0.0
17 for token, prob in zip(VOCAB, probs):
18 cumulative += prob
19 if draw < cumulative:
20 return token
21 return VOCAB[-1]
22
23def verify_draft(draft_tokens, token_q, token_p, position_q, position_p, rng):
24 accepted = []
25 for index, token in enumerate(draft_tokens):
26 accept_p = min(1.0, token_p[index] / token_q[index])
27 if rng.random() < accept_p:
28 accepted.append(token)
29 continue
30 residual = normalize(residual_mass(position_p, position_q))
31 correction = sample(residual, rng)
32 return accepted + [correction], "reject"
33 bonus = sample(position_p, rng)
34 return accepted + [bonus], "bonus"
35
36draft_tokens = ["serves", "with", "cache"]
37token_q = [0.40, 0.35, 0.60]
38token_p = [0.60, 0.40, 0.40]
39# Full distributions at the rejected cache position.
40position_q = [0.60, 0.30, 0.10]
41position_p = [0.40, 0.50, 0.10]
42overlap = [min(p, q) for p, q in zip(position_p, position_q)]
43reconstructed = [left + right for left, right in zip(overlap, residual_mass(position_p, position_q))]
44
45emitted, outcome = verify_draft(
46 draft_tokens, token_q, token_p, position_q, position_p, Random(1)
47)
48
49print(f"emitted: {' '.join(emitted)}")
50print(f"outcome: {outcome}")
51print(f"reconstructed target: {reconstructed == position_p}")
52assert emitted == ["serves", "with", "latency"]
53assert outcome == "reject"
54assert reconstructed == position_p1emitted: serves with latency
2outcome: reject
3reconstructed target: TrueTracing one step
The prefix is already "The model". The draft proposes serves, with, cache. With seed 1, verifier accepts first two because target assigns each at least as much probability as draft, then rejects cache (). Residual at that position is a point mass on latency, so emitted text is "serves with latency". Any later draft tokens would be discarded; has none.
If every drafted token is accepted, the same target pass has logits for the next position, so sampler emits one bonus token and the round returns tokens. In a real engine, rejection also rewinds target KV cache to accepted prefix before appending correction. Leaving rejected keys in cache would make later attention read tokens that are not in sequence.
Why can a speculative round emit K+1 tokens when all K draft tokens are accepted?
Answer
The target pass over the prefix plus K draft tokens also produces logits for the token after the draft. If every drafted token is accepted, the sampler can use that final target logit to sample one bonus token.
Speedup analysis
Once exactness is clear, ask how much target work one round replaces. The expected tokens per verification step depends on acceptance rate and speculation length . Start with a deliberately simple model: each drafted token is accepted independently with probability . Verification still runs left to right, so each accepted token extends the prefix and first rejection ends the draft run with a target correction.
Under that approximation, the expected tokens per verification round is given by the geometric series (with the convention when ):
Expected tokens per round
is the per-token acceptance probability, and is the number of proposals. The sum counts one token for a first rejection or bonus, then one more token for each accepted position. High moves the result toward tokens per round; low leaves the result near one.
Wall-clock speedup
Tokens per round are not wall-clock speedup. Include draft cost ratio (draft time relative to normal target decode step) and verify cost, which grows as or sequence length grows. The model below is a first prediction, not a production forecast:
The classic Leviathan-style simplification sets (one target pass ≈ one decode step) and as draft cost relative to that step. That's optimistic when:
- Verification attends over query positions on a long prefix, so attention and KV traffic scale with and sequence length . Prefer a profiled , often closer to than to a flat 1.
- Continuous batching shares a token budget across streams. Each accepted draft multiplies tokens scheduled that iteration; high can steal slots from other users and worsen multi-tenant ITL even when single-stream speedup looks good.
- Real systems also pay for cache growth, kernel launches, sampler parity checks, and tree-attention variants (Medusa/EAGLE), which aren't the classic residual chain alone.
For the first table below we still use so the arithmetic stays readable. Treat those numbers as an optimistic upper-bound sketch to compare against a benchmark, not as promised fleet speedup. The second table and lab re-open so you can see how verify cost collapses the win as grows.
Classic serial two-model drafting pays roughly for sequential draft steps (each step ~ target-equivalents). Tree methods such as Medusa and EAGLE replace that chain with parallel heads or a coupled drafter, so proposal cost is not automatically ; profile the method you ship.
Worked example
Use explicit model inputs, not measured results. Suppose a candidate draft path costs 10% of a target pass (), set , and plug in acceptance rate .
Expected tokens per round = tokens.
Optimistic cost denominator () = target-equivalent passes.
Optimistic speedup = x.
The model predicts about 2.5x for those inputs under flat verification. If acceptance changes to 0.6, same model predicts about 1.6x; at 0.9, about 3.1x. These are model outputs to compare against a benchmark, not promised throughput.
| Model input | Assume | Approx. tokens/round | Approx. speedup | |||
|---|---|---|---|---|---|---|
| sweep | 0.6 | 5 | 0.1 | 1 | 2.4 | 1.6x |
| sweep | 0.7 | 5 | 0.1 | 1 | 2.9 | 2.0x |
| sweep | 0.8 | 5 | 0.1 | 1 | 3.7 | 2.5x |
| sweep | 0.9 | 5 | 0.1 | 1 | 4.7 | 3.1x |
| Depth sweep | 0.85 | 8 | 0.1 | 1 | 5.1 | 2.8x |
| Depth sweep | 0.90 | 10 | 0.1 | 1 | 6.9 | 3.4x |
Nothing in this model table is a hardware measurement. A measured speedup needs target and draft checkpoints, engine and kernel versions, accelerator and precision, batch and concurrency, prompt/output-length distribution, decoding settings, warmup policy, and a named non-speculative baseline. Pair p50/p99 TTFT and ITL with throughput, cost, acceptance, and an output-distribution or correctness check.
Now keep and , but set so verification cost grows with draft depth:
| Tokens/round | Speedup vs flat | ||
|---|---|---|---|
| 1 | 1.80 | 1.15 | 1.57x (vs 1.64x) |
| 5 | 3.69 | 1.75 | 2.11x (vs 2.46x) |
| 10 | 4.57 | 2.50 | 1.83x (vs 2.29x) |
Even with strong acceptance, larger can lose after verify cost is counted. Production sweep tools therefore need profiles alongside and .
1def expected_tokens(acceptance: float, depth: int) -> float:
2 return sum(acceptance**step for step in range(depth + 1))
3
4def modeled_speedup(
5 acceptance: float,
6 depth: int,
7 draft_cost: float,
8 verify_cost: float = 1.0,
9) -> float:
10 return expected_tokens(acceptance, depth) / (verify_cost + depth * draft_cost)
11
12for acceptance in (0.6, 0.8, 0.9):
13 estimate = modeled_speedup(acceptance, depth=5, draft_cost=0.1, verify_cost=1.0)
14 print(f"acceptance={acceptance:.1f}: optimistic speedup={estimate:.2f}x")
15
16print("--- growing verify cost, alpha=0.8 ---")
17for depth in (1, 5, 10):
18 verify = 1.0 + 0.05 * depth
19 estimate = modeled_speedup(0.8, depth, draft_cost=0.1, verify_cost=verify)
20 print(f"K={depth}: c_verify={verify:.2f}, modeled speedup={estimate:.2f}x")1acceptance=0.6: optimistic speedup=1.59x
2acceptance=0.8: optimistic speedup=2.46x
3acceptance=0.9: optimistic speedup=3.12x
4--- growing verify cost, alpha=0.8 ---
5K=1: c_verify=1.05, modeled speedup=1.57x
6K=5: c_verify=1.25, modeled speedup=2.11x
7K=10: c_verify=1.50, modeled speedup=1.83x
Pick from measured acceptance, draft cost, and serving behavior. Start a sweep with single-digit depths, then let route-specific benchmarks choose the operating point rather than a universal default.
1def modeled_speedup(acceptance, depth, draft_cost, verify_cost=1.0):
2 expected = sum(acceptance**step for step in range(depth + 1))
3 return expected / (verify_cost + depth * draft_cost)
4
5measurements = {"acceptance": 0.72, "draft_cost": 0.12}
6candidates = {
7 depth: modeled_speedup(
8 measurements["acceptance"],
9 depth,
10 measurements["draft_cost"],
11 verify_cost=1.0 + 0.05 * depth,
12 )
13 for depth in (1, 3, 5, 8)
14}
15best_depth = max(candidates, key=candidates.get)
16print({depth: round(value, 3) for depth, value in candidates.items()})
17print(f"model-selected K to benchmark: {best_depth}")1{1: 1.47, 3: 1.73, 5: 1.662, 8: 1.435}
2model-selected K to benchmark: 3With growing , the same acceptance and draft cost prefer a smaller than the flat- sketch (which selected ). Always re-rank depths under the profiled verify curve.
Continuous batching token budget
Single-stream speedup can still hurt multi-tenant ITL. Continuous batching keeps two ledgers: target positions scored and tokens committed. With target-verification budget and active streams, no speculation schedules about target positions per iteration. At depth , target scores about proposed positions even when rejection happens early.
Committed output and KV growth follow a different ledger, about for accepted fraction . Acceptance reduces committed growth; it doesn't erase verification work. If either target or KV-append capacity fills, streams wait or shrink and multi-tenant inter-token latency rises, even when solo speedup looks good.
1target_token_budget_b = 64
2kv_append_budget_b = 64
3streams = 16
4accepted_fraction = 0.6 # mean fraction of K that survives before reject
5for depth in (0, 2, 4, 8):
6 target_work = streams * depth if depth else streams
7 expected_commits = streams * (1 + accepted_fraction * depth) if depth else streams
8 fit = target_work <= target_token_budget_b and expected_commits <= kv_append_budget_b
9 print(
10 f"K={depth}: target={target_work:.0f}/{target_token_budget_b} "
11 f"commits≈{expected_commits:.0f}/{kv_append_budget_b} "
12 f"({'fits' if fit else 'OVER budget: multi-tenant ITL risk'})"
13 )1K=0: target=16/64 commits≈16/64 (fits)
2K=2: target=32/64 commits≈35/64 (fits)
3K=4: target=64/64 commits≈54/64 (fits)
4K=8: target=128/64 commits≈93/64 (OVER budget: multi-tenant ITL risk)If acceptance drops from 0.8 to 0.5, should you usually increase K first?
Answer
No. Low acceptance means drafts are rejected early, so a larger K mostly adds draft work that never survives. First check tokenizer, sampler, prompt distribution, and draft-model alignment.
Draft model choices
Choose draft source by asking two questions: how much does each proposal cost, and how often does target accept it? A weak drafter rejects early; an expensive drafter consumes the latency budget. Common serving choices are:
| Approach | Draft source | Main advantage | Main trade-off |
|---|---|---|---|
| Smaller same-family model | Separate assistant model with the same tokenizer | Simple exact speculative-decoding setup | Extra model to load and schedule |
| Medusa heads[6] | Extra heads attached to the target model | No separate model at inference time | Needs extra training and tree verification |
| EAGLE / EAGLE-3[7][8] | Target-coupled speculator over hidden states or direct token heads | Strong proposals without a full second model | More integration complexity |
| MTP heads[9] | Checkpoint-native multi-token prediction modules | No separate assistant when supported | Requires checkpoint and engine support |
| Prompt Lookup[9] | Reuse repeated n-grams from context | No extra model or training | Only helps when the context repeats itself |
| Suffix decoding[9] | Reuse matching suffixes from previous outputs | No extra model | Fit depends on reusable prior output patterns |
For classic direct-token probabilistic sampling, draft and target need the exact same tokenizer and token-ID mapping. If IDs map to different subwords, target is verifying a different candidate sequence. Some engines expose limited heterogeneous-vocabulary paths, but those can constrain sampling method; decoded strings alone are not a proof of compatibility.[9]
1draft_vocab = {"return": 14, " label": 88, " expires": 103}
2target_vocab = {"return": 14, " label": 88, " expires": 104}
3required_pieces = ["return", " label", " expires"]
4
5mismatches = [
6 piece for piece in required_pieces
7 if draft_vocab.get(piece) != target_vocab.get(piece)
8]
9print(f"token-id mismatches: {mismatches}")
10print(f"direct draft path allowed: {not mismatches}")1token-id mismatches: [' expires']
2direct draft path allowed: FalseWhat is the core draft-model trade-off?
Answer
The draft must be cheap enough that K draft passes cost far less than one target pass, but accurate enough that many proposed tokens are accepted. Too weak lowers acceptance; too large erases the saved latency.
Medusa: multi-head speculative decoding
Medusa avoids a separate draft model. It adds extra prediction heads to the target itself. Each head predicts a different future position from the same hidden state, so the draft is a tree of continuations rather than one chain. Tree attention then scores those candidate paths in one target pass and keeps the longest accepted prefix.
That removes the job of loading and scheduling a second model, at the cost of training the heads and implementing tree verification.[6]
The lossless path still uses the same residual sampler as the rest of this lesson. Medusa also describes typical acceptance, which keeps drafts that look plausible under an entropy threshold instead of reconstructing exactly. Use typical acceptance only when you're willing to leave the exact target distribution. If you need Leviathan-style matching, keep rejection sampling.[6]
EAGLE drafts from target-model internals instead of a separate full assistant. Earlier variants predict feature states, which can raise acceptance because those states carry more information than a plain token-only head.[7] EAGLE-3 switches to direct token prediction, fuses low, middle, and high target layers, and trains the drafter with a training-time-test loop on its own outputs. Its paper reports up to 6.5x over vanilla autoregressive generation across five tasks, plus roughly 1.4x latency improvement over EAGLE-2 at batch size 1. In an SGLang test on H100 with LLaMA-Instruct 3.1 8B and MT-Bench, using chain length 3 without the tree structure, EAGLE-3 reports 1.38x throughput at batch size 64. Those are study-specific baselines, hardware, workloads, and settings, not portable service guarantees.[8] Current vLLM docs expose EAGLE-family speculation, but flags and caveats move quickly.[9]
Why do Medusa-style heads remove one major deployment burden of classic speculative decoding?
Answer
They avoid loading and scheduling a separate draft model. The target model gains extra heads that propose future tokens from its own hidden state, then tree verification decides which path survives.
Prompt lookup decoding
Prompt Lookup Decoding (PLD) skips the neural draft model. It searches the current context window for matching n-grams and reuses them as draft tokens. That helps on tasks with repeated text or pattern matching.
| Aspect | How it works |
|---|---|
| Draft source | Match n-grams from the prompt/context window |
| Candidate workloads | Code completion, summarization, repetitive text |
| Memory overhead | No extra model weights |
| Main failure mode | Little benefit when the context has little repetition |
The algorithm scans the context window for n-grams (typically 3-5 tokens) that match the end of the currently generated sequence. When it finds a match, it looks at what token followed that n-gram earlier in the context window and uses that as the next draft token. For example, if the model has generated "timeout error" and the context contains "timeout error repeats Friday," PLD proposes "repeats" as the next draft token.
PLD is a candidate for code generation and other repetitive tasks because variable names, function calls, and boilerplate often reappear within the context window.[9]
PLD's appeal is that there's no extra model to load, train, or keep in memory. You can stack it with other speculative methods or use it as a fallback when no neural draft model is available.
1context = "timeout error repeats Friday. auth callback needs review. timeout error"
2tokens = context.split()
3suffix = ["timeout", "error"]
4
5proposal = None
6for index in range(len(tokens) - len(suffix)):
7 if tokens[index:index + len(suffix)] == suffix:
8 proposal = tokens[index + len(suffix)]
9 break
10
11print(f"matched suffix: {' '.join(suffix)}")
12print(f"lookup proposal: {proposal}")1matched suffix: timeout error
2lookup proposal: repeatsWhy is Prompt Lookup Decoding often strong for code completion but weak for open-ended creative writing?
Answer
Code often repeats identifiers, imports, call patterns, and boilerplate already present in context. Creative writing is less likely to contain exact reusable n-gram continuations, so lookup drafts have fewer high-quality proposals.
Production deployment
The production decision starts with a bottleneck, not a flag. Speculation spends extra FLOPs on drafting to save target-model memory bandwidth. Modern serving stacks expose several proposer families, so payoff depends on method, route, and load.[9] On a compute-saturated route, the same trade can lower throughput and raise cost.
When the classic draft-model setup helps (and when it doesn't)
Before rolling out a separate draft model, check whether your workload benefits from the draft-then-verify cycle. The technique is a trade-off: it burns additional compute (FLOPs) to save memory bandwidth. If your system is already compute-bound, this trade-off will usually backfire and reduce overall throughput.
| Scenario | Hypothesis before benchmark | Why test it |
|---|---|---|
| Single-user, low-batch inference | Strong candidate | Target decode may be memory-bandwidth bound |
| Throughput-maximized batching | Measure carefully | Extra draft work can compete with saturated compute |
| Long outputs | Candidate | More decode steps can amortize setup |
| Very short outputs | Weak candidate | Setup and drafting may dominate |
| Repetitive outputs (code, templates) | Candidate | Draft or lookup acceptance may be higher |
| Diverse outputs | Measure carefully | Acceptance may vary with sampling and prompt mix |

Current vLLM docs describe model-based methods (EAGLE, MTP, draft model, and related proposers) as stronger inter-token-latency options, while n-gram and suffix decoding add less workload during peak QPS (queries per second).[9] Speculation targets the gap between emitted tokens, not TTFT; draft setup can add first-token work. Feature incompatibilities and hardware numerics sit outside the paper proof, so validate the method on your stack.
When is classic draft-model speculation most likely to help production serving?
Answer
It's most likely to help medium-to-low QPS, memory-bound, latency-sensitive decode where the target has idle compute between weight reads. It's less reliable in high-QPS, large-batch serving that is already compute-heavy. Light proposers such as n-gram or suffix are the first things to try when traffic is high but you still want some speculation.
Serving-engine reality
Serving-engine support changes quickly. vLLM's current docs list several speculation families, plus known feature incompatibilities, and they separate theoretical losslessness from what you should expect under real hardware numerics.[9] Treat framework support as something you validate in your stack, not as a timeless property of the algorithm.
Make the rollout comparison reproducible before tuning . Freeze target and draft checkpoints, engine and kernel versions, accelerator, precision, decoding settings, warmup policy, concurrency, and a prompt/output-length distribution that represents route traffic. Measure baseline TTFT, p50/p99 inter-token latency, and tokens-per-second throughput separately.
Then sweep proposer and depth on those same requests. Break out acceptance, output length, fallback rate, cost, and p50/p99 latency by workload class. Keep a non-speculative fallback for peak-QPS periods or incompatible features, and promote only after output-distribution parity or task correctness passes alongside latency and throughput gates.
The gate example below uses synthetic values to show decision logic, not a benchmark result.
1baseline = {"p95_itl_ms": 46.0, "throughput_tps": 380, "sampler_parity": True}
2canary = {"p95_itl_ms": 29.0, "throughput_tps": 372, "sampler_parity": True}
3minimum_throughput_ratio = 0.95
4
5promote = (
6 canary["sampler_parity"]
7 and canary["p95_itl_ms"] < baseline["p95_itl_ms"]
8 and canary["throughput_tps"] >= baseline["throughput_tps"] * minimum_throughput_ratio
9)
10print(f"inter-token latency improved: {canary['p95_itl_ms'] < baseline['p95_itl_ms']}")
11print(f"canary promoted: {promote}")1inter-token latency improved: True
2canary promoted: TrueWhich metrics should you split by workload class before deciding speculation is working?
Answer
Track acceptance rate, inter-token latency, TTFT, output length, throughput, cost per output token, and fallback rate by workload class. A global average can hide that code improves while creative chat regresses.
When speculation backfires
Speculation fails in recognizable ways. Diagnose first mismatch before changing .
| Symptom | Likely cause | Fix |
|---|---|---|
| Speedup is near 1x or negative | Draft model is too slow or too inaccurate (low acceptance rate) | Benchmark a smaller or better-aligned draft, or switch to Prompt Lookup for repetitive tasks |
| Correctness checks fail | Acceptance test uses different temperature or top-p than the served model | Ensure the verifier and the sampler share the exact same post-processed distribution |
| Memory usage spikes unexpectedly | KV cache wasn't truncated after a rejected token | Implement cache rewind so rejected draft tokens don't persist in the cache |
What target-model state must be restored after a speculative rejection?
Answer
The target KV cache must be rewound to the accepted prefix before appending the correction token. Keeping KV entries for rejected draft tokens corrupts subsequent attention.
Replay representative prompt and output-length distributions through baseline and speculative paths with identical sampling settings, warmup, hardware, precision, engine, and concurrency. Check output-distribution parity and KV-cache rewind first. Then compare acceptance, TTFT, p50/p99 inter-token latency, throughput, cost per output token, and fallback rate by workload class. Promote routes that beat the latency target without breaking the throughput floor; keep a non-speculative fallback for rejection-heavy or incompatible traffic.