Speculative Decoding (also called assisted or parallel decoding) is an optimization technique to speed up autoregressive generation in large language models (LLMs) without sacrificing output quality. The key idea is to use a smaller, faster "draft model" to guess future tokens, and then have the larger "target model" verify and correct those guesses in parallel, reducing the number of sequential steps needed.
How It Works
Draft Phase (Speculation):
A small, fast model (the draft model) generates a sequence of candidate tokens (e.g., 3-5 tokens) autoregressively, just like normal decoding but much faster.
Verification Phase (Parallel Execution):
The larger, slower target model (the main LLM) processes the entire candidate sequence in parallel (instead of step-by-step) and either:
Accepts a candidate token if it matches the target model’s prediction.
Rejects a candidate and samples a correction from the target model’s distribution.
Rollback & Resampling:
If a candidate is rejected, the target model discards all subsequent candidates and continues generation from the corrected token.
If all candidates are accepted, the process repeats with a new draft.
Why It’s Faster
Parallelism: The target model verifies multiple tokens in one forward pass (instead of running sequentially).
Fewer Steps: On average, speculative decoding reduces the number of slow target model calls, especially when the draft model is accurate.
Example
Suppose the draft model guesses: ["The", "quick", "brown"]
The target model verifies in parallel:
Accepts "The" and "quick" but rejects "brown" → samples "red" instead.
The final output becomes "The quick red", and generation continues from "red".
Key Requirements
Draft Model: Must be small and fast (e.g., a distilled version of the target model or an n-gram model).
Correctness Guarantee: The target model’s output distribution must match what it would have produced autoregressively (achieved via careful sampling).
Efficient Verification: The target model uses a modified forward pass to score multiple tokens at once.
Performance Gains
In practice, speculative decoding can 2x-3x speed up generation for models like GPT-3 or LLaMA, with identical outputs to standard decoding.
Works best when the draft model is well-aligned with the target model (e.g., same training data).
Variants & Improvements
Lookahead Decoding: Extends the idea by using multiple draft models or heuristic methods.
Medusa: Uses multiple candidate branches for higher acceptance rates.
Blockwise Parallel Decoding: Generates and verifies chunks of tokens in blocks.
Would you like a deeper dive into any part (e.g., sampling methods, tradeoffs)?
User
So does it only help with throughput, or also with latency?
Assistant
Great question! Speculative decoding improves both throughput and latency, but the extent depends on the implementation and hardware. Here’s how:
1. Latency Reduction
Parallel Verification: The target model verifies multiple draft tokens in a single forward pass, reducing the number of sequential steps (the primary bottleneck in autoregressive decoding).
Example: If the draft model proposes 5 tokens and the target model accepts 3, you’ve effectively "skipped" 3 slow autoregressive steps.
Hardware Utilization: Modern GPUs/TPUs are underutilized in autoregressive decoding (since they process one token at a time). Speculative decoding fills this gap by batching the verification step.
Best-Case Scenario: If the draft model is highly accurate, latency can approach the draft model’s speed (e.g., 2–3x faster for a small draft model).
But:
Latency gains depend on the draft model’s accuracy. If guesses are often wrong, rollbacks add overhead.
The first token’s latency (time-to-first-token) is usually unchanged since drafting still requires an initial autoregressive step.
2. Throughput Improvement
Batching: Speculative decoding allows the target model to process multiple candidate sequences in parallel (e.g., for different requests in a batch), increasing tokens/sec.
Fewer Target Model Calls: By amortizing the cost of the slow target model over multiple tokens, throughput scales almost linearly with the acceptance rate.
Tradeoffs
Metric
Impact of Speculative Decoding
Latency
↓ (Reduced for later tokens, but first-token latency may remain similar)
Throughput
↑↑ (Higher tokens/sec due to parallel verification)
Memory
↑ (Draft model + caching adds overhead)
Output Quality
Identical to standard decoding (no degradation)
When Latency Gains Are Maximized
Long Sequences: More opportunities to skip steps (e.g., document generation).
User
Ah, so basically everything that's been speculatively decoded can be grouped together into one Q?
Assistant
Not quite! While speculative decoding and KV caching both optimize autoregressive generation, they operate at different levels—speculative decoding doesn’t directly affect how queries (Q) are computed or grouped in attention. Here’s the key distinction:
1. Speculative Decoding ≠ Query Grouping
Speculative decoding is about parallelizing token generation (using a draft model to propose multiple future tokens, then verifying them in bulk with the target model).
Q (queries) in attention are still computed per-token during verification, even when processing multiple speculated tokens.
The target model evaluates each speculated token’s Q against the full cached KV history to decide acceptance/rejection.
No "grouping" of Q happens—each token’s Q is computed independently, just verified in parallel.
2. Why Q Isn’t Grouped
Attention Mechanics: Each token’s Q is a function of its current hidden state. Since speculated tokens are generated sequentially by the draft model, their hidden states (and thus Q vectors) are distinct.
Verification Requires Precision: The target model must compute exact attention scores for each speculated token against the KV cache to ensure correctness (no approximation or grouping allowed).
3. How Parallel Verification Works
When verifying k speculated tokens:
The target model runs one forward pass but computes:
k separate Q vectors (one per speculated token).
Each Q attends to the entire KV cache (past tokens + previous correct speculated tokens).
The model checks if the speculated tokens match its own predictions (token-by-token).
Example:
Draft model outputs: ["fox", "jumps"]
Target model computes:
Q_fox → checks if "fox" is correct.
Q_jumps (conditioned on "fox") → checks if "jumps" is correct.
If "fox" is accepted but "jumps" is rejected, the target model samples a replacement for "jumps" (e.g., "runs") and continues.
4. What Is Parallelized?
User
Yes, I meant that they can be sent in as one batch of Q
Assistant
Ah, you're absolutely right! Yes, during the verification phase of speculative decoding, the target model can process the batch of speculated tokens' Q vectors in parallel as a single forward pass—this is the key to its speedup. Let me clarify how this works and why it’s valid:
1. Batching Q Vectors for Parallel Verification
Draft Model Output: Proposes a sequence of k tokens (e.g., ["fox", "jumps", "over"]).
Target Model Input: Computes the Q vectors for all k tokens in parallel (as a batch) and evaluates them against the same KV cache.
Each Q vector (Q_fox, Q_jumps, Q_over) is computed from its respective token’s hidden state (conditioned on previous accepted tokens).
The attention mechanism processes all Q vectors simultaneously in a single forward pass, scoring each against the full KV history.
Why this is valid:
The autoregressive property is preserved because each Q vector is computed as if it were generated step-by-step:
Q_fox depends only on the pre-speculation context.
Q_jumps depends on ["fox"] (if "fox" is accepted).
Q_over depends on ["fox", "jumps"] (if both are accepted).
The target model’s forward pass implicitly handles this dependency chain via masked attention (like standard decoding).
2. Hardware-Level Parallelism
Efficient Attention: Modern accelerators (GPUs/TPUs) compute attention for all Q vectors in the batch simultaneously, leveraging tensor operations.
For k speculated tokens, the attention scores form a matrix of shape [k, seq_len].
This is mathematically identical to running k separate autoregressive steps but fused into one operation.
Memory Savings: The KV cache is shared across all Q vectors in the batch, avoiding redundant memory reads.
3. Practical Example
Suppose the draft model proposes ["fox", "jumps"]:
Target model forward pass:
Input: Q_fox (conditioned on pre-speculation context) and (conditioned on ).
Dataset releases
Not yet included in a published release.
Accurate Draft Model: A well-aligned draft model (e.g., distilled from the target model) reduces rollbacks.
Hardware with Parallel Capacity: GPUs/TPUs with spare compute for batched verification.
Practical Considerations
First-Token Latency: Unaffected unless paired with other optimizations (e.g., prompt caching).
Draft Model Cost: The draft model must be significantly faster than the target model to offset its overhead.
Dynamic Adaptation: Some systems adjust the draft length based on confidence (e.g., shorter drafts for uncertain contexts).
Speculative decoding is a hybrid optimization—it primarily targets throughput but also reduces per-token latency (after the first token). For real-time applications (e.g., chatbots), the perceived latency improves noticeably for long responses. For batched inference, throughput gains dominate.
Would you like details on how to implement this (e.g., draft model selection, verification tricks)?
Compute, Not Q: The target model’s forward pass processes all k speculated tokens in parallel (e.g., as a mini-batch), but each token’s Q/K/V computations remain independent.
Hardware Efficiency: Modern GPUs accelerate this by parallelizing the attention scores for all k Q vectors against the same KV cache.
Key Takeaway
Speculative decoding speeds up generation by amortizing the cost of the target model’s forward pass over multiple tokens, but it doesn’t merge or approximate Q. The attention mechanism stays mathematically identical to standard decoding—just applied more efficiently.
Why Not Group Q?
Hypothetically, if you tried to "group" Q vectors for speculated tokens:
You’d break the autoregressive property (each token depends on the exact previous ones).
The target model could no longer guarantee correct sampling.
The KV cache would become misaligned with the generated sequence.
Advanced Note: Tree-Based Speculation
Some variants (e.g., Medusa, SpecTr) explore branching speculation—proposing multiple candidate continuations in a tree structure. Even then:
Each branch has its own Q vectors.
The target model verifies all branches in parallel but still computes attention per-token.
Would you like a deeper dive into these variants?
Q_jumps
["fox"]
Both Q vectors attend to the same KV cache (past tokens + ["fox"] for Q_jumps).
Verification:
If Q_fox’s predicted token matches "fox", and Q_jumps’s prediction matches "jumps", both are accepted.
If Q_jumps is rejected, the target model samples a correction (e.g., "leaps") and discards subsequent tokens.
4. Why This Doesn’t Break Autoregression
Dependency Masking: The attention mechanism ensures Q_jumps only attends to positions up to and including "fox" (just like standard decoding).
Rollback on Rejection: If any token is rejected, the model discards all subsequent tokens in the batch and continues autoregressively from the corrected token.
Key Insight
Batching Q vectors is not an approximation—it’s a hardware optimization that preserves the exact mathematical behavior of step-by-step decoding while exploiting parallelism. The "trick" is that the target model’s forward pass can compute what would have happened autoregressively in bulk.
When Batching Q Works Best
High Draft Accuracy: Fewer rollbacks mean more tokens are verified per batch.
Large k: Longer speculation sequences amortize the cost of the target model’s forward pass (but trade off higher rejection risk).
Hardware Support: GPUs/TPUs with sufficient memory bandwidth to handle the batched attention computation.
Limitations
First Token Latency: Unaffected (still requires an initial autoregressive step).
Memory Overhead: Storing multiple Q vectors and their attention matrices temporarily increases memory usage.
Advanced: Tree Attention
Some methods (e.g., Medusa) extend this idea by batching Q vectors from multiple candidate branches, further increasing parallelism. The target model verifies all branches simultaneously, but the core principle remains the same.
Would you like details on implementing this (e.g., PyTorch snippets for batched Q attention)?