Chapter 35 of 40 · ~22 min read & lab+85 XP
Chapter 35 · Generative AI

Speculative Decoding: Lossless 2–3× Faster LLM Inference via Draft & Verify

How Speculative Decoding breaks the single-token autoregressive memory-bandwidth barrier for 2×–3× faster generation with 100% mathematically IDENTICAL outputs: Draft-K → Parallel Verify, Modified Rejection Sampling, and Medusa / EAGLE.

What Is It?

Speculative Decoding uses a tiny fast Draft model to propose K tokens ahead, then lets the large Target model verify all K tokens in ONE parallel forward pass with lossless rejection sampling.

Why Is It Required?

Autoregressive decoding underutilizes GPU compute on 1 token at a time; verifying 5 draft tokens in parallel delivers 2×–3× faster latency with mathematically identical output quality.

Everyday Analogy: A junior assistant drafting a 5-word phrase quickly while the senior editor approves all 5 words in a single glance.
Why ML Engineers & Data Scientists Actually Need This

Speculative Decoding is the closest thing to a free lunch in LLM systems — cutting single-user latency by 2×–3× while guaranteeing the exact same probability distribution as the full 70B+ model!

ML / AI Engineer

In coding assistants (Cursor, Copilot) and RAG summarization where acceptance rate α reaches 0.85–0.95, Speculative Decoding (especially EAGLE-2/3 and N-gram Prompt Lookup) delivers dramatic real-world speedups!

Data Scientist

Understanding why Speculative Decoding shines at small batch sizes (memory-bound regime) and shrinks at huge batch sizes (when the GPU is already compute-bound) prevents misconfigured deployments.

Interview & Debug Edge

Gold-standard LLM inference question: 'Prove why Speculative Decoding is 100% mathematically lossless — even at Temperature > 0 — and explain why verifying 5 tokens costs ~1 token of time!'

Step 0 · Test Your Gut Before Any Math!

Why does running a 70B target LLM on K = 5 draft tokens in parallel take almost the exact same wall-clock time as running it on 1 single token?

What You Will Master in This Chapter
  • Explain why verifying K = 5 draft tokens in parallel through a 70B target model takes almost the EXACT same latency as generating 1 token!
  • Derive Modified Rejection Sampling: accept with min(1, p(x)/q(x)) and resample from norm(max(0, p − q)) on rejection to prove 100% lossless distribution equivalence
  • Compute expected accepted tokens per target pass E[tokens] = (1 − α^(K+1)) / (1 − α) from acceptance rate α
  • Compare classic Draft-Model speculation (1B → 70B) with Draft-Free Speculation (Medusa, EAGLE, and Prompt-Lookup N-gram drafting)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
q(x),  p(x)q(x), \; p(x)Say aloud:“draft & target distributions”
Plain-English Meaning
Next-token probabilities from the tiny fast Draft model q vs. giant Target model p
Everyday Example
1B Draft q vs. 70B Target p
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of a senior architect (70B Target) and a fast junior intern (1B Draft) writing boilerplate Python. Instead of the senior architect typing 1 word at a time, the intern quickly drafts the next 5 words (def fib(n): return). The senior architect glances at all 5 words in one blink: 'Yes, yes, yes, wait — change return to if!' You just got 4 exact senior-architect words in the time of 1 blink!

1. Draft-K → Parallel Target Verify

Everyday Story First (Zero Math Yet!)

Because causal self-attention computes logits for ALL K+1K+1 positions simultaneously in 1 forward pass, the 70B target verifies all KK draft tokens — AND gives you a free bonus (K+1)(K+1)-th token if all KK pass!

Speculative Decoding: Cheap 1B Draft (K=4) → 1 Parallel 70B Verify Pass!1. Tiny 1B Draft Model (Fast)[the] → [cat] → [sat] → [on]4 cheap sequential steps (~4 ms total)2. Giant 70B Target (1 Parallel Pass!)[the ✓] [cat ✓] [sat ✓] [near ↺]Outputs 4 exact tokens for the HBM cost of 1!
Speculative Decoding drafts K=5 tokens cheaply with a tiny 1B model, then verifies ALL 5 tokens in ONE single parallel forward pass of the 70B target model — turning 5 memory-bound steps into 1!

Why Even a Rejection Still Produces Progress

In the worst case where the very first draft token is rejected, the target pass STILL produces 1 exact token from p(x)p(x) — so every target pass ALWAYS advances by between 11 and K+1K+1 exact tokens!

2. Modified Rejection Sampling: Proof of 100% Lossless Equivalence

Everyday Story First (Zero Math Yet!)

Even at T=0.8T = 0.8 stochastic sampling, Speculative Decoding guarantees the EXACT target probability p(x)p(x) for every token in the vocabulary!

Modified Rejection Sampling: 100% Mathematically Lossless Distribution!Accept Ruleaccept prob = min(1, p(x) / q(x))If target likes x at least as much as draft → 100% accept!On First Rejectionx' ~ norm( max(0, p − q) )Resamples exact residual → P(output) ≡ p_target!
Modified Rejection Sampling accepts token x_i with probability min(1, p_target/p_draft) and resamples from norm(max(0, p_target − p_draft)) on rejection — mathematically 100% IDENTICAL to sampling from the 70B model!

The 2-Line Lossless Math (Leviathan et al. / Chen et al., 2023)

For each draft token xi∼qix_i \sim q_i:

  1. Accept xix_i with probability min⁡ ⁣(1,pi(xi)qi(xi))\min\!\big(1, \frac{p_i(x_i)}{q_i(x_i)}\big).
  2. On the first rejection, discard remaining drafts xi+1..Kx_{i+1..K} and sample a replacement xi′x'_i from the normalized positive residual: pi′(x)=norm ⁣(max⁡(0, pi(x)−qi(x)))p'_i(x) = \text{norm}\!\Big(\max\big(0, \, p_i(x) - q_i(x)\big)\Big) Summing the probability of emitting any token xx (via acceptance OR via residual resampling) equals pi(x)p_i(x) identically!

3. Speedup Math & Modern Draft-Free Speculation (EAGLE / Prompt Lookup)

Everyday Story First (Zero Math Yet!)

Slide the acceptance rate α in the mini-lab below to see how high agreement (like code & RAG!) multiplies effective tokens/pass!

Expected Accepted Tokens per Target Pass (K = 5 Draft Tokens)α = 0.501.97 tokens / passα = 0.753.29 tokens / passα = 0.904.69 tokens / pass
Expected accepted tokens per step grows as (1 − α^(K+1)) / (1 − α): at acceptance rate α = 0.80 and K = 5, Speculative Decoding delivers ~2.5×–3.0× lossless speedup!

Beyond Separate Draft Models

  • EAGLE-2/3 & Medusa: Attach tiny lightweight prediction heads directly onto the target LLM's own last hidden states — zero separate draft model to manage, higher acceptance rate α\alpha!
  • Prompt Lookup (N-gram) Drafting: For RAG, code editing, and summarization, simply copy matching n-grams straight from the user's input prompt as draft tokens — zero draft compute and up to 3×–4× speedup on editing tasks!
Walk Through With Me · Interactive Worked Example

Worked Example: Checking Modified Rejection Sampling

Target p('cat') = 0.40, Draft q('cat') = 0.50. Draft sampled 'cat'.

11. Compute acceptance probabilityStep 1 / 2

min⁡(1,p/q)=min⁡(1,0.40/0.50)=0.80\min(1, p/q) = \min(1, 0.40/0.50) = \mathbf{0.80} (80% chance to accept!).

Teacher's Note: Notice q('cat') × accept = 0.50 × 0.80 = 0.40 = p('cat') — exact!
Animated Mini-Lab • 6.3

Speculative Decoding Expected Tokens / Pass (K = 5)

Expected exact tokens per 70B target pass: 3.69× tokens
Pause & Check · Quick Intuition Pulse

In Speculative Decoding, if the 1B Draft model and 70B Target model have identical tokenizers, does Speculative Decoding change the output quality of the 70B model?

Try It YourselfStandard

Why does Speculative Decoding's speedup shrink (and can even slow down!) at very large serving batch sizes like B = 128?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Yes for standard token-level Speculative Decoding (e.g., LLaMA-3.2-1B drafting for LLaMA-3.3-70B, or Qwen-0.5B drafting for Qwen-72B), so token probabilities p(x)p(x) and q(x)q(x) align 1-to-1!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Speculative Decoding Studio draft 4 code tokens and verify all 4 in ONE single 70B pass.
Interactive Animation • 6.3 Deep Lab

Speculative Decoding: Draft-4 → Single-Pass Target Verification

Watch a tiny 1B draft model propose 4 code tokens, then watch the 70B target verify all 4 in ONE parallel pass (3 accepted + 1 exact correction = 4 tokens!).

Phase 1: 1B Drafting
def
Draft #1
fib(
Draft #2
n):
Draft #3
return
Draft #4
0%
Drafting 4 tokens...
Intuition Takeaway: Speculative Decoding drafts KK tokens cheaply and verifies them in 1 parallel target pass via Modified Rejection Sampling — delivering 2×–3× lower latency with 100% mathematically identical outputs.
Where This Powers Real ML, Deep Learning & Generative AI

Ultra-Fast Code Editing (Fast Apply / Prompt Lookup)

Drafts unchanged lines directly from the existing source file to rewrite 500-line files at 500–1,000+ tok/s!

Production NumPy & PyTorch Code Patterns
import torch

# Lossless Speculative Decoding Rejection Sampling Step (preserves exact target distribution)
def speculative_accept(p_target: torch.Tensor, q_draft: torch.Tensor, draft_tokens: list[int]) -> tuple[list[int], int]:
    accepted = []
    for i, tok in enumerate(draft_tokens):
        ratio = (p_target[i, tok] / max(q_draft[i, tok].item(), 1e-9)).clamp(max=1.0).item()
        if torch.rand(1).item() < ratio:
            accepted.append(tok)
        else:
            # Sample corrected token from residual distribution max(0, p - q)
            residual = (p_target[i] - q_draft[i]).clamp(min=0.0)
            residual /= residual.sum()
            return accepted, int(torch.multinomial(residual, 1).item())
    return accepted, -1  # all draft tokens accepted!

torch.manual_seed(3)
p = torch.softmax(torch.tensor([[3.0, 1.0, 0.2], [0.5, 2.8, 0.1]]), dim=-1)
q = torch.softmax(torch.tensor([[2.9, 1.1, 0.2], [0.4, 2.7, 0.2]]), dim=-1)
acc, corr = speculative_accept(p, q, draft_tokens=[0, 1])
print(f"Accepted draft tokens: {acc} | Correction token: {corr}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Saying Speculative Decoding only works for greedy (T = 0) decoding.
Best Practice: Modified Rejection Sampling makes it 100% lossless for arbitrary stochastic sampling (T > 0, Top-P) too!
Chapter Mastery Check (+85 XP)
Score: 0 / 1
1In Speculative Decoding with K = 5 draft tokens, what is the MAXIMUM number of exact target tokens a single target verification pass can emit?

Apply What You Learned — Solve Matching Coding Problems