Phase 04/Algorithmic speedups/Speculative decoding
PHASE 04 · Algorithmic speedups

Speculative decoding

0%
8 h5 subtopics2 lessons · 1 required
In plain English

A big model produces one word per step and spends most of each step just loading its own weights from memory, so checking several words at once costs about the same as producing one. Speculative decoding takes advantage of that. A small, fast assistant model drafts the next few words in a row, and the big model then checks all of them in a single pass, keeping the ones it agrees with and correcting the first one it does not. It is like a senior editor who lets a junior writer draft a paragraph and then reads it in one go, accepting the good sentences and rewriting from the first bad one. A clever acceptance rule makes the final text have exactly the same statistics as if the big model had written every word itself, so quality is unchanged and only speed improves.

Why it matters

Speculative decoding gives 2-3x lower inter-token latency for small batch serving without touching model quality, and it is built into vLLM, SGLang and TensorRT-LLM. Understanding the acceptance rule and the trade-off with batch size tells you when to turn it on and which draft strategy to pick.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Baseten, Cerebras, CoreWeave, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Together AI, xAI.See all skills →

Learning objectives

  • Implement the rejection-sampling acceptance rule and prove empirically that output tokens follow the target distribution.
  • Measure acceptance rate and tokens-per-step as a function of draft length and draft model quality.
  • Explain why speculative decoding helps at low batch size but can hurt at high batch size.
  • Compare draft-model, Medusa, EAGLE and n-gram (prompt lookup) approaches.

Key concepts

Draft model
A small model (or heuristic) that proposes gamma tokens autoregressively.
Verification pass
A single target-model forward over the draft tokens that yields target probabilities for all gamma positions at once.
Acceptance rule
Accept draft token x with probability min(1, p(x)/q(x)); on rejection, sample from the normalized max(0, p - q).
Acceptance rate
Fraction of draft tokens accepted; sets the expected tokens per verification step.
Gamma (draft length)
Number of tokens drafted per step; too large wastes draft work, too small limits the speedup.
Lossless
The output distribution is provably identical to sampling from the target model alone.
Medusa / EAGLE
Extra heads or a small transformer on the target model's hidden state that draft tokens without a separate model.
Prompt lookup / n-gram speculation
Drafting by copying continuations of n-grams that already appeared in the prompt; free for summarization and code editing.

Subtopics

  1. 1. Why verification is almost free

    Decode is memory-bound; a forward over gamma+1 tokens reads the same weights as over 1 token, so time per step barely grows.

  2. 2. Rejection sampling for exactness

    Derive why accepting with min(1, p/q) and resampling from (p - q)+ yields exactly p; handle the bonus token when all drafts are accepted.

  3. 3. Expected speedup

    Expected tokens per step is (1 - alpha^(gamma+1)) / (1 - alpha) for acceptance alpha; plug in draft cost to find the optimal gamma.

  4. 4. Draft strategies

    Separate small model, Medusa heads, EAGLE feature-level drafting, n-gram lookup, and tree-structured drafts.

  5. 5. Interaction with batching and engines

    Verification adds compute; at high batch size the GPU is already compute-bound, so gains vanish; how vLLM and SGLang schedule drafts.

Resources

Hands-on lessons

L1

Implement speculative decoding with two GPT-2 models on CPU

CPU · your Macnotebook150 minrequired

Goal · Build draft-verify-accept decoding with gpt2 as draft and gpt2-medium as target, measure acceptance rate, and verify losslessness statistically.

  1. 1Load gpt2 (draft) and gpt2-medium (target) in float32 on CPU; write a plain autoregressive sampler for the target as the baseline with a fixed seed.
  2. 2Write draft(prompt_ids, gamma) that samples gamma tokens from the draft model and returns the tokens and their probabilities q.
  3. 3Run the target once over prompt + draft tokens and gather target probabilities p at each draft position.
  4. 4Implement the acceptance loop; accept with probability min(1, p/q); on first rejection sample from normalize(max(0, p - q)); if all accepted sample the bonus token from the last target distribution.
  5. 5Generate 200 tokens for five prompts with gamma in [2, 4, 8]; record acceptance rate and mean accepted tokens per verification step.
  6. 6Losslessness check; for one fixed short prompt, sample the next token 5,000 times with plain target sampling and 5,000 times with speculative sampling and compare the two empirical distributions with a chi-square test or total-variation distance.
  7. 7Time the baseline and speculative runs on CPU and compute tokens per second for each gamma.
Deliverable
A notebook with the implementation, an acceptance-rate table per gamma and the distribution comparison.
Check
Total-variation distance between the two empirical next-token distributions is under 0.05; acceptance rate is between 0.5 and 0.9 and mean accepted tokens per step rises with gamma but with diminishing returns.
L2

Prompt-lookup decoding and the batch size trade-off

CPU · your Macexperiment60 minoptional

Goal · Use transformers assisted generation with n-gram lookup on a summarization prompt and model the speedup as batch size grows.

  1. 1Use model.generate(..., prompt_lookup_num_tokens=10) with gpt2-medium on a prompt that contains a 300-word passage to summarize; compare wall time with plain generate.
  2. 2Repeat on a creative-writing prompt with no repeated text and note the difference in acceptance.
  3. 3Write a small cost model; step_time(batch) = max(weight_bytes / bandwidth, flops(batch, tokens) / peak_flops) and compute speculative speedup for batch in [1, 4, 16, 64] with alpha=0.7, gamma=4.
  4. 4Plot speedup versus batch size and identify where it crosses 1.0.
Deliverable
Timing results for both prompts and the speedup-versus-batch plot.
Check
The summarization prompt shows a higher acceptance rate than the creative prompt; the cost model shows speedup falling toward or below 1 as batch grows.

Build your own

Build your own speculative decoder

PythonCPU · your Mac~8 h

Draft-verify-accept decoding with gpt2 drafting for gpt2-medium on CPU, exact in the greedy case, provably lossless in the sampled case, with KV rollback, an n-gram drafter and a measured speedup-versus-acceptance curve.

The real thing: github.com/vllm-project/vllm/tree/main/vllm/v1/spec_decode ↗

How you know a stage passes

Write tests/test_spec.py first. Every stage adds a test against the plain autoregressive target model (gpt2-medium, fp32, CPU, fixed seed): greedy stages must match token-for-token, sampled stages must match in distribution (total-variation distance under 0.05 between 5,000-sample empirical next-token distributions on a fixed prompt), and every stage records acceptance rate, accepted tokens per step and tokens per second into results.csv via bench.py. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01the baseline you will beat
    A plain sampler with a KV cache for the target model, greedy and temperature modes, with a seeded RNG and a tokens-per-second timer.
    test · 64 greedy tokens equal transformers' generate(do_sample=False) for 5 prompts; the baseline tokens-per-second number is written to results.csv.
  2. 02greedy speculation
    Draft gamma tokens with gpt2, verify them in one target forward, accept the longest matching prefix and append the target's bonus token.
    test · 128 greedy tokens equal the stage-1 baseline exactly for 5 prompts with gamma 4; the test prints mean accepted tokens per verification step and asserts it is above 1.0.
  3. 03lossless sampling via rejection
    Accept each draft token with probability min(1, p/q); on the first rejection sample from normalize(max(0, p - q)); if all are accepted sample the bonus token from the target's last distribution.
    test · Total-variation distance between 5,000 speculative samples and 5,000 plain target samples of the next token is below 0.05 at temperature 1.0; acceptance rate on 5 prompts is between 0.5 and 0.9.
  4. 04KV rollback instead of recompute
    Both draft and target caches are truncated to the accepted length after each round rather than rebuilt, and the number of target forwards is counted.
    test · Output equals a recompute-from-scratch implementation token-for-token in greedy mode; target forward calls equal the number of verification rounds; tokens per second improves over stage 2 and both numbers are in results.csv.
  5. 05a pluggable Drafter and an n-gram drafter
    A Drafter interface with propose(context) and accept_feedback(n_accepted) has two implementations, the small-model drafter and a prompt-lookup drafter that proposes the continuation of the last n-gram match in the context.
    test · With the n-gram drafter greedy output still equals the baseline; acceptance rate on a prompt containing a 300-word passage to summarise is higher than on a creative-writing prompt, both printed; draft cost per round is below 1 ms.
  6. 06speedup versus acceptance and gamma
    bench.py sweeps gamma 1 to 8 for both drafters, measures acceptance alpha, and overlays the cost model (1 - alpha^(gamma+1)) / ((1 - alpha) * (gamma * c + 1)) where c is the measured draft-to-target cost ratio.
    test · The plot speedup_vs_gamma.png exists; predicted speedup is within 25 percent of measured for gamma 2 to 4; the README states the best gamma and the measured end-to-end speedup at batch 1.
  7. 07Stage 7 (optional), tree drafting
    The draft proposes a top-2 branching tree of depth 3 and the target verifies all 14 nodes in one forward using a tree attention mask and per-node position ids.
    test · Greedy output still equals the baseline; accepted tokens per round is higher than the linear drafter at the same depth on the 5 prompts, and the test prints both means.

Knowledge check

QWhy does verifying gamma draft tokens cost about the same as generating one token?

Decode is memory-bound on reading weights; a forward over gamma+1 tokens reuses the same weight reads and only adds a small amount of compute.

QWhat happens when a draft token is rejected?

A replacement token is sampled from the normalized positive part of (p - q), all later draft tokens are discarded, and decoding resumes from there.

QWhy can speculative decoding slow down a server at high batch size?

With many requests the GPU is compute-bound, so the extra verification and draft compute is no longer free and lowers total throughput.

QWhat does Medusa change compared to a separate draft model?

It adds small prediction heads on the target model's last hidden state, so drafting needs no second model and no second KV cache.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 notebook saved with the losslessness check passing.
  • Can write the acceptance rule and the expected-tokens-per-step formula from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →