Speculative Decoding for LLM Inference Acceleration: How It Works and Performance Analysis
This article explains how speculative decoding accelerates large language model inference and why decoding speed is often the bottleneck in serving. It covers the two inference phases (prefill and decode), the draft-then-verify workflow, the rejection sampling math that keeps the output distribution unchanged, and the key variables that determine real-world gains, including average acceptance length, draft length k, draft model size, batching, and KV cache management. It also outlines a reproducible evaluation methodology based on service-level metrics rather than single-stream speed, and lists common misconceptions to avoid.
1. Background: Why Generation Speed Is a Core Inference Metric
When deploying large language models locally or in the cloud, one of the metrics developers discuss most is decode throughput, usually measured in tokens generated per second. Many teams find that the same model can run several times faster or slower depending on the hardware, context length, and concurrency level. A scenario mentioned in the original discussion—a model of roughly 27 billion parameters generating only tens of tokens per second locally, and approaching over a hundred tokens per second after optimization—is a typical illustration of the decode-stage optimization problem.
Understanding this phenomenon requires distinguishing the two phases of inference:
- Prefill: All input tokens are processed in parallel in a single pass. Computational complexity is high but parallelism is good, so compute resources are usually well utilized.
- Decode: Tokens are generated autoregressively one at a time, and each step depends on the previous one, making it inherently serial. For every token generated, all weights must be moved from memory to the compute units once.
The bottleneck in the decode phase is often not compute but memory bandwidth. This means that simply adding compute power has limited effect on generation speed. What is needed is to reduce the number of weight transfers required per output token, or to verify multiple tokens with a single transfer. Speculative decoding is a representative approach to the latter idea.
2. Core Idea of Speculative Decoding: Guess First, Verify Multiple Tokens in One Forward Pass
The intuition behind speculative decoding is similar to candidate retrieval in a search engine: a cheap “draft” step proposes several candidate tokens, and the expensive target model verifies them all at once.
The standard workflow can be summarized as follows:
- Draft generation: A much smaller draft model autoregressively generates k candidate tokens (k is typically 2–8).
- Parallel verification: The k candidates are appended to the confirmed sequence, and the target model performs one forward pass, producing output distributions at k+1 positions simultaneously.
- Acceptance decision: Draft tokens are compared one by one against the target model’s distribution, from front to back. If the i-th token is accepted, the first i draft tokens are all correct and the sequence advances i+1 positions this round. If a token is rejected at some position, a token is resampled from the target distribution at that position, and the round advances by less than k+1.
- Iterate: Repeat the process until a stopping condition is met.
Illustrative pseudocode:
# Simplified logic of a single speculative decoding rounddraft_tokens = draft_model.generate(target_prefix, k) # cheap draftlogits = target_model.forward(target_prefix + draft_tokens) # one forward pass, k+1 distributionsaccepted = 0for i in range(k):if accept(draft_tokens[i], logits[i]):accepted += 1else:breakif accepted < k:next_token = sample_from(logits[accepted]) # resample at rejection pointelse:next_token = sample_from(logits[k]) # all accepted, one extra for free
The key point is that the cost of one target model forward pass is almost the same as generating a single token. Therefore, as long as the average acceptance length is greater than 1, overall throughput increases. The theoretical speedup is roughly equal to the average acceptance length, with an upper bound of k+1.
3. Why the Output Distribution Is Unchanged: The Math Behind Rejection Sampling
Many people worry that “guessing wrong will degrade generation quality.” A properly implemented speculative decoding uses a specific acceptance probability and residual distribution correction during verification, and it can be proven that the final sampling result is strictly identical to the distribution of the original target model. In other words, speculative decoding is lossless acceleration: it changes the computation path, not the output distribution. This is fundamentally different from “replacing a large model with a small one,” which is a lossy approximation.
A common acceptance criterion in engineering implementations is to accept a draft token with probability min(1, p_target / p_draft); when rejected, sample from the normalized residual distribution max(0, p_target - p_draft). Sampling parameters such as temperature and top-p must be applied to both the draft and verification sides, otherwise consistency is broken.
4. Key Variables Behind Going from Tens to Over a Hundred Tokens/s
The draft model is only half of the solution. What really determines the gains are the following parameters and engineering details:
- Average acceptance length: The higher the draft quality and the better the match with the target task, the longer the acceptance length. Structured content such as domain text and code typically has higher acceptance rates.
- Draft length k: Too small a k yields insufficient gains; too large a k increases draft overhead and memory usage, and the tail is likely to be rejected. There is a clear optimum that needs to be found by empirical scanning.
- Draft model size: A draft that is too small has poor quality; one that is too large loses the “cheap” advantage. In practice, the draft model is commonly one-tenth to one-twentieth the size of the target model.
- Batching and concurrency: Speedup is most obvious in single-request scenarios. Under high concurrency, the target model already utilizes bandwidth well, so gains are diluted. Evaluation should be based on service-level throughput rather than single-stream speed.
- KV cache management: Whether draft and verification share or maintain separate caches, and the copy and rollback strategy for caches, directly affect the extra overhead per round.
- Sampling parameter consistency: Temperature, top-p, repetition penalties, and similar parameters must stay synchronized on both sides.
There is also a class of variants that do not require a separate draft model, such as constructing candidates from the model’s own shallow representations or an additional lightweight prediction head, and n-gram-style candidate retrieval based on historical prefixes. Their common goal is to reduce draft cost and improve candidate hit rate.
5. Evaluation Methodology: Don’t Look Only at Single-Stream Speed
It is recommended to build a minimal reproducible evaluation process in your own environment:
- Fix the baseline: Record time to first token, single-stream generation speed, and memory usage with speculative decoding disabled.
- Scan k and draft size: Run a grid test at levels such as 2, 4, 6, and 8, recording the average acceptance length.
- Break down by scenario: Measure general conversation, long-document summarization, and code completion separately, avoiding conclusions drawn from a single dataset.
- Look at service-level metrics: Total throughput, P99 latency, and cost per thousand tokens at concurrency levels of 1/4/8/16.
- Close the monitoring loop: Feed generation speed, acceptance length, and cache hit rate into logging and monitoring/alerting systems to create an observability surface for continuous tuning.
In terms of deployment, this kind of inference service typically runs on a container platform, with object storage distributing model weights, a message queue for request peak shaving, and logging and monitoring/alerting for observability—a fairly common engineering combination. General capabilities such as the container platform, object storage, logging service, and monitoring/alerting offered by Baidu AI Cloud can serve as the runtime and observability foundation for hosting such inference services.
6. Common Misconceptions
- Thinking speculative decoding can break the memory bandwidth limit: It reduces the effective number of transfers but cannot change the physical bandwidth of the hardware.
- Ignoring sampling consistency: If verification-side sampling parameters are inconsistent with the draft side, the “lossless” assumption no longer holds.
- Blindly increasing k under high concurrency: In concurrent scenarios, the extra draft computation may actually lower total throughput.
- Looking only at averages: Acceptance length has high variance, so tail latency for long-tail requests needs attention.
7. Summary
Through the paradigm of “cheap draft retrieval + one target model forward pass for verification,” speculative decoding turns serial decoding into a parallel candidate-verification process. While keeping the output distribution unchanged, raising generation speed from tens of tokens per second to nearly over a hundred tokens per second is an achievable engineering goal. The actual gains depend on the average acceptance length, the match between draft size and length, caching strategy, and concurrency pattern, and must be validated with multi-scenario benchmarks in your own environment and iterated on continuously with the help of logging and monitoring systems.
