Speculative Decoding for LLM Inference: How It Delivers Up to 3x Speedup, Principles and Practice
This article explains why autoregressive token-by-token decoding is the main bottleneck in large language model inference, then breaks down how speculative decoding works: a lightweight draft stage proposes k candidate tokens, the target model verifies them in a single forward pass, and a modified sampling rule keeps the output distribution strictly equivalent to the original model. You will find the speedup formula and what it implies about acceptance rate, draft length and cost ratio, the key engineering decisions around draft sources, batching, sampling consistency, KV cache and observability, plus evaluation methods and common pitfalls.
1. The Problem: Why Token-by-Token Decoding Is the Bottleneck
Autoregressive decoding in large models advances only one token at a time. Every new token requires feeding the entire history back into the model for another forward pass. This has two consequences:
- Very low compute-to-memory-access ratio. Each step in the generation phase processes a single token, yet the weights must be read into GPU memory in full. Compute capacity sits largely idle, so the bottleneck is memory bandwidth rather than floating-point throughput.
- Serial length cannot be compressed. Generating 500 tokens means 500 sequential forward passes, and latency grows linearly with output length. Adding more parallelism cannot remove it.
Optimization efforts in the industry therefore fall into two categories: reducing the cost of a single forward pass (quantization, sparsification, KV cache compression, operator fusion, more efficient attention implementations), and reducing the number of forward passes. Speculative decoding belongs to the second category and is one of the most broadly applicable ideas of the past two years.
2. How Speculative Decoding Works
The original framing compares it to a search engine, and the analogy captures the essence: first “guess” a batch of candidates with a cheap method, then confirm them in bulk with one expensive check.
The standard flow is:
- Draft stage. A lightweight model (or shallow layers / extra prediction heads of the model itself) autoregressively generates k candidate tokens. The cost is far lower than running the target model.
- Verification stage. The k candidates are appended to the confirmed sequence, and a single forward pass of the target model yields distributions at all k+1 positions at once.
- Acceptance decision. Draft tokens are compared left to right against what the target distribution would sample at each position. At the first mismatch, the sequence is truncated and one token is resampled from the target distribution at that position as a correction.
- Loop. The accepted prefix plus the corrected token becomes the new confirmed sequence for the next round.
The key is step 2: verification of all k positions shares one forward pass, so the more guesses that land, the more tokens a single round produces. If every draft token is accepted, a round advances k+1 tokens; if the very first one misses, it degrades to ordinary decoding plus the extra draft overhead.
Illustrative pseudocode (sampling details omitted):
def speculative_step(ctx, draft, target, k):draft_tokens, draft_probs = draft.generate(ctx, k)logits = target.forward(ctx + draft_tokens) # one forward pass, k+1 positionsaccepted = 0for i in range(k):if accept(draft_tokens[i], draft_probs[i], logits[i]):accepted += 1else:breaknext_token = sample(logits[accepted]) # correction or bonus tokenreturn ctx + draft_tokens[:accepted] + [next_token], accepted
For the output to be exactly identical to the original model, acceptance must use a modified sampling rule: accept a draft token with probability min(1, p_target/p_draft), and on rejection sample from the normalized residual distribution max(0, p_target − p_draft). This rule can be proven strictly equivalent to token-by-token sampling from the target model, which is the precondition for using speculative decoding in production with confidence.
3. The Math Behind the Speedup
Let α be the average acceptance rate of draft tokens, k the draft length, and c the cost ratio of a draft step to a verification step (typically well below 1). The expected output per round is roughly (1 − α^(k+1)) / (1 − α), giving an ideal speedup of approximately:
speedup ≈ (1 − α^(k+1)) / ((1 − α) · (k·c + 1))
Three practical conclusions follow:
- α is the decisive variable. Raising α from 0.5 to 0.8 does not increase gains linearly; the benefit multiplies.
- There is an optimal k. When k is too large, the tail candidates are almost certainly rejected and only add draft and verification cost. Higher α supports a larger optimal k.
- c must be small enough. If the draft model is too large or the implementation is inefficient, the time saved in verification gets eaten by drafting, producing a net regression.
The original text mentions improving “from 40 tokens/s to nearly 120.” By the formula, that implies both α and implementation efficiency sit in a favorable range. Numbers like this depend heavily on model architecture, batch size, sequence length and hardware; they are observations from a specific setting and should not be treated as a general baseline.
4. Key Engineering Decisions
4.1 Choosing the draft source
- Independent small model: good generality, but requires extra GPU memory and an alignment training or distillation pass.
- Self-drafting (shallow prediction heads, Medusa-style multiple heads, EAGLE-style feature-level prediction): no second model needed and acceptance rates are usually higher, but it depends on modifying and training against the target model’s architecture.
- Retrieval or template drafting: extremely high acceptance in highly repetitive scenarios such as code completion, fixed templates and RAG, at almost zero training cost.
4.2 Batching and scheduling
Speculative decoding pays off most in interactive, batch-size-1 settings. With large batches the GPU is already compute-saturated, and extra candidates compete for throughput. A workable approach is to toggle dynamically based on load: use a larger k at low concurrency, shrink k or turn the feature off at high concurrency, switching the optimization goal from single-request latency to overall throughput.
4.3 Sampling consistency
Equivalence is easy to verify under greedy decoding. Random sampling with temperature, top-p or repetition penalties must go through residual distribution correction, otherwise output quality drifts. Run a distribution-equivalence regression before rollout, not just a speed check.
4.4 Memory and KV cache
Drafting and verification add extra KV writes and require reclaiming cache for rejected tokens. Pair this with paged cache management and prefix reuse to avoid fragmentation slowing everything down.
4.5 Observability
Collect at minimum: average acceptance rate, average accepted length, share of cost spent on drafting, per-round latency distribution, and toggle state. Without an acceptance-rate metric, no speedup or regression can be explained.
5. How to Evaluate, and Common Pitfalls
Fix the model version, the input/output length distribution, concurrency and hardware. Report three sets of numbers: time to first token, per-user tokens/s, and total system throughput, and keep a control group with the optimization disabled.
Four common mistakes: treating a speedup from one scenario as a general result; checking speed but not whether the output distribution is equivalent; forcing the feature on under high concurrency and losing throughput; hard-coding the draft length instead of making it adaptive.
6. Relationship to Baidu AI Cloud Practices
When deploying in a general cloud environment such as Baidu AI Cloud, you can combine a container platform to host the inference service, object storage for model and draft weights, and logging plus monitoring and alerting to track acceptance rate and latency percentiles. These are general product categories; check the official documentation for actual parameters and quotas. The overall approach: first determine whether the bottleneck is the number of forward passes or the cost of each one, then choose among speculative decoding, quantization or cache optimization, and iterate on data rather than chasing a single metric.
