Speculative decoding
The Sequential Generation Bottleneck
WHAT is the problem?
Standard autoregressive generation produces one token at a time:
For a sequence of length , this requires sequential forward passes. Each pass:
- Loads model weights from memory (billions of parameters)
- Has latency dominated by memory bandwidth, not FLOPs
- Cannot be parallelized across the sequence dimension
The inefficiency: Modern GPUs have teraflops of compute but spend most time waiting for memory I/O. The model is "idling" between tokens.
How Speculative Decoding Works
The Two-Model Setup
- Draft model : Small, fast model (e.g., 1B parameters, distilled from target)
- Target model : Large, slow model (e.g., 70B parameters, the one we actually want)
Key property: is 5-10× faster per token but slightly less accurate.
The Algorithm (Step-by-Step)
WHY this works:
- Lossless: The acceptance sampling ensures output distribution exactly matches alone
- Fast: When draft is correct (often 60-80% of tokens), we accept tokens in one pass
- Bounded: Worst case is rejecting everything = same as standard decoding (no slowdown)
Derivation of Acceptance Criterion
Goal: Match target distribution using proposals from draft .
Start with rejection sampling:
- Sample
- Accept with probability
WHY this gives :
When , we reject with probability and resample from:
Combined distribution:
The math guarantees output matches the target model exactly.
Worked Example: 4-Token Speculation
| Position | Draft Token | (draft) | (target) | Accept? | |----------|-------------|------------|------| | t | "Par" | 0.7 | 0.8 | ✓ (min(1, 0.8/0.7) = 1) | | t+1 | "is" | 0.5 | 0.6 | ✓ (min(1, 0.6/0.5) = 1) | | t+2 | "," | 0.4 | 0.2 | ✗ (min(1, 0.2/0.4) = 0.5, coin flip fails) |
Outcome:
- Accept "Par" and "is" (2 tokens in one target pass!)
- Reject "," and resample from distribution at position t+2
- Likely samples "." (which had )
- Final: Generated 3 tokens with 1 draft pass + 1 target pass (vs. 3 passes normally)
WHY this step: Position t+2 fails because target model strongly prefers "." over ",", so draft's confidence in "," is misleading. The adjusted distribution removes draft's bias.
Speedup Analysis
Expected Acceptance Rate
Let = probability a draft token is accepted (empirically 0.6-0.8 for good draft models).
Tokens accepted per speculation:
Derivation (careful with indices):
- Accept exactly tokens then reject (for ): the first candidates are accepted (probability ) and the -th is rejected (probability ). We then resample one token from the adjusted distribution, giving output tokens. So the term is .
- Accept all candidates (probability ): we additionally sample a bonus token, giving output tokens. So the term is .
- Summing and simplifying the geometric series gives the closed form .
WHY speedup is less than : Rejections waste the target pass. The maximum speedup (as , so output rate ) is
which equals only in the idealized limit (a free draft model). With a nonzero draft cost the draft phase itself takes time, so the true ceiling is below . As , speedup (no gain, possibly slight overhead from the draft passes).
Optimizing the Draft Model
WHAT makes a good draft model?
- High agreement (): Minimize distribution mismatch with target
- Low latency: Must be much faster than target (typically >5× speedup)
- Same vocabulary: Token spaces must align exactly
HOW to create one:
WHY distillation works best: Explicitly optimizes for distribution match, not just task accuracy. A model with 95% task accuracy might have only 60% token-level agreement, while a distilled model can achieve 75%+ agreement at lower task accuracy.
Common Mistakes
Practical Implementation Details
Batching Speculation
Challenge: Different sequences in a batch may accept different numbers of tokens.
Solution: Process in "sync points":
- Draft all sequences with tokens
- Target verifies all
- Each sequence accepts 0 to tokens independently
- Pad shorter sequences, continue from their current position
WHY this works: Target verification is still a single batched forward pass. The asynchrony is handled in post-processing.
Temperature and Sampling
With temperature :
- Draft samples from
- Target uses
- Acceptance criterion unchanged:
Top-k, nucleus sampling: Apply after acceptance sampling on the adjusted distribution.
Extensions and Variants
Medusa decoding
Uses multiple "draft heads" on the target model itself (adds small prediction heads at intermediate layers). Trades some memory for not needing a separate draft model.
Speculative RAG
For retrieval-augmented generation, draft model proposes both tokens and retrieval queries. Target verifies both.
Multi-candidate speculation
Draft model proposes a tree of candidates with multiple branches. Target verifies all paths. Handles uncertainty better when is low.
Recall Feynman Explanation (ELI12)
Imagine you're writing an essay and you have a younger sibling who writes really fast but makes some mistakes. Here's the trick:
- Your sibling writes the next 4 sentences quickly (the "draft")
- You read all 4 sentences at once and check each one
- If a sentence is good, you keep it. If it's wrong, you stop there, fix it, and have your sibling start again from that point Why is this faster than you writing alone? Because reading and checking 4 sentences takes almost the same time as writing 1 sentence yourself. If your sibling gets even 2 out of 4 right, you're saving time!
In AI, the "you" is a giant smart model (slow), the "sibling" is a small quick model (fast but less accurate), and "sentences" are tokens. The small model guesses ahead, the big model checks everything in one shot. Most guesses are right, so we skip most of the slow generation steps.
Connections
- Model Quantization — Complementary: quantize both draft and target for further speedup
- Flash Attention — Orthogonal memory optimization; both can be combined
- Beam Search — Alternative decoding strategy; speculative decoding compatible with beam search
- Knowledge Distillation — Used to train the draft model
- Transformer Architecture — Understanding self-attention explains why memory-bound
- Distributed Training — Speculative decoding reduces inference latency; distributed training reduces time
#flashcards/ai-ml
What is speculative decoding? :: A lossless inference acceleration technique where a fast draft model generates candidate tokens in parallel, and a slow target model verifies all candidates in a single forward pass using rejection sampling to maintain exact target distribution.
Why is autoregressive decoding slow?
What is the acceptance criterion in speculative decoding?
What is the expected number of output tokens per speculation?
What makes a good draft model for speculative decoding?
Why doesn't speculative decoding change the output distribution?
What is the maximum theoretical speedup, accounting for draft cost?
What is the optimal lookahead in speculative decoding?
How does speculative decoding handle different temperatures?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Chalo isko simple tarike se samajhte hain. Socho aapke paas ek bahut bada aur intelligent model hai (target model, jaise 70B parameters), jo har token generate karne mein slow hai kyunki har baar poore model ke weights ko memory se load karna padta hai. Isko autoregressive generation kehte hain—ek time pe ek hi token, aur ye memory-bound hota hai, matlab GPU ka compute idle rehta hai bas memory I/O ka wait karta rehta hai. Yehi asli bottleneck hai—hamare paas teraflops ka compute hai par hum uska sirf ~2% use kar paate hain.
Ab speculative decoding ka jugaad ye hai: ek chhota, fast draft model (jaise 1B parameters) use karo jo jaldi-jaldi kuch tokens guess kar deta hai—jaise ek intern jaldi se sentence sketch kar deta hai. Fir bada target model in saare guessed tokens ko ek hi parallel forward pass mein check kar leta hai—jaise expert editor ek nazar mein poora draft approve kar deta hai. Kyunki draft model aksar 60-80% tokens sahi guess kar leta hai, hum ek hi mehnge pass mein kai tokens accept kar lete hain, aur bahut saare slow sequential steps skip ho jaate hain. Isliye speed bahut badh jaati hai.
Sabse important baat—ye technique lossless hai. Acceptance sampling ka jo maths hai (min(1, p/q) probability se accept karna, warna adjusted distribution se resample karna) wo mathematically guarantee karta hai ki final output bilkul wahi distribution follow karega jo akela target model deta. Matlab quality mein zero compromise, sirf speed ka fayda. Aur worst case bhi safe hai—agar saare guesses galat ho jaayein, tab bhi ye normal decoding jitna hi time lega, usse slow nahi. Isliye ye real-world mein LLM inference fast karne ke liye ek bahut powerful aur practical trick hai.