Speculative Decoding for LLM Inference: A Practical Guide to Faster Token Generation
This article explains how speculative decoding accelerates large language model inference by replacing serial token verification with parallel verification, without changing output quality. It covers the core draft-and-verify workflow, semi-autoregressive drafting to reduce draft cost, confidence-scheduled verification for dynamic draft length, and the right way to evaluate gains using equal-throughput A/B tests. A deployment checklist and notes on running the setup on container platforms are included.
1. Background: Why Serial Single-Token Generation Is the Bottleneck
Autoregressive decoding in large language models is inherently serial: every generated token requires a full forward pass, and the entire context plus the KV cache is read again. Under high concurrency, compute utilization is acceptable. But in low-concurrency, long-context online chat scenarios, the dominant cost of the decode phase is not matrix multiplication — it is memory bandwidth and kernel launch overhead. The result: GPU utilization looks low, the user-facing “word-by-word” experience is poor, and single-user generation speed (typically understood as output tokens per second) becomes the main source of complaints.
Common industry optimizations include quantization, operator fusion, continuous batching, and KV cache reuse. Most of them improve overall throughput or memory footprint, with limited effect on the output speed of an individual request. Speculative decoding targets exactly this gap: it does not reduce total computation, but converts serial verification into parallel verification, using a single target-model forward pass to validate multiple candidate tokens.
2. How Speculative Decoding Works
Speculative decoding has two stages:
- Draft stage: a lightweight model (or shallow layers / extra prediction heads of the model itself) quickly proposes K candidate tokens at a cost far below the target model.
- Verification stage: the target model performs one parallel forward pass over the K positions, obtains a probability distribution at each position, applies an acceptance criterion position by position, accepts the longest valid prefix, and discards and resamples the rest.
Correctness hinges on the verification criterion guaranteeing that the output distribution matches the target model’s token-by-token sampling. This makes it lossless acceleration: model quality is unchanged. The speedup depends on two quantities: the accepted length of candidates, and the cost ratio between drafting and verification.
Illustrative pseudocode:
def speculative_decode(ctx, draft, target, K=5):tokens = draft.propose(ctx, K) # lightweight draft, cost c_dlogits = target.forward(ctx, tokens) # one parallel verification, cost c_vaccepted = 0for i, t in enumerate(tokens):p = softmax(logits[i])q = draft.dist_at(ctx, i)if random() < min(1.0, p[t] / q[t]):accepted += 1else:breakbonus = sample(softmax(logits[accepted])) # correction term, keeps the distribution consistentreturn accepted + 1, ctx.extend(tokens[:accepted] + [bonus])
The average accepted length (tokens produced per verification round) is the core metric. Raising it from 1 to 3–4 opens up several times of headroom in end-to-end output speed; conversely, if draft quality is poor and accepted length stays near 1, the speedup degrades into a net loss.
3. Semi-Autoregressive Generation: Multiple Draft Tokens in One Pass
A conventional draft model is still token-by-token autoregressive: K candidates require K small forward passes, so draft cost grows linearly with K and eats into the gains. Semi-autoregressive generation lets the draft head predict multiple future positions in parallel within a single forward pass: target positions are organized into blocks, parallel within a block and autoregressive across blocks, reducing the serial depth of the draft stage from K to the number of blocks.
Three engineering concerns:
- Matching block size to accepted length: too large a block degrades candidate quality in its later positions; too small reverts to serial behavior. A range of 3–8 is a common empirical band to load-test.
- Training objective: the draft head must align with the target model’s distribution, typically via distillation (minimizing divergence between draft and target distributions) rather than fitting hard labels alone.
- Position encoding and mask consistency: when predicting multiple positions in parallel, attention masks and position indices must correspond exactly, otherwise a hidden defect appears that “looks converged but does not accelerate in production.”
4. Hardware-Aware Confidence-Scheduled Verification
A fixed K is the simplest and most wasteful policy: K is too small for easy continuations and wastes compute, while at high-entropy positions a large K gets most candidates rejected. Confidence-scheduled verification makes K dynamic: the draft head outputs a confidence per position (such as max probability or entropy), and a scheduler uses it to decide the verification length for the round, adapting to hardware state such as current batch size, sequence length, and memory bandwidth pressure.
A workable scheduling logic:
def schedule_K(conf, batch, seq_len, budget):# conf: draft confidence sequence across positionsk = 1for c in conf:if c < tau_low: # low confidence, little gain from verifying furtherbreakk += 1if c > tau_high: # high confidence, safe to extendk += 1k = min(k, budget(batch, seq_len)) # hardware budget constraintreturn max(1, k)
Here budget is set based on whether the marginal cost of one verification is lower than the marginal benefit of producing one more token. The empirical rule: with a large batch, compute is already saturated and parallel headroom for verification is small, so be conservative; with a small batch, long context, and bandwidth constraints, aggressive scheduling pays off most.
5. Evaluating Results the Right Way
Evaluation must separate two classes of metrics, or the conclusions will be wrong:
- Offline quality metrics: average accepted length, candidate hit rate, draft cost share. These can be compared across several general-purpose target models to see whether relative improvement reaches the double-digit percentage range.
- Online serving metrics: single-user generation speed, overall throughput, time to first token, cost per request.
The most critical constraint is equal-throughput comparison. If output speed is bought by lowering concurrency or oversubscribing resources, the numbers look good but carry no engineering meaning. The proper approach is to fix total cluster throughput (or fix QPS and the batch upper bound), change only the decoding strategy, and compare the distribution of user-side speed (P50/P90 rather than the mean is recommended).
Note that any specific percentage from a vendor blog is tightly bound to that vendor’s model architecture, cluster configuration, and traffic profile, and cannot be extrapolated directly to your own system. The right path is to build a reproducible A/B load test and derive your own speedup range from your own traffic profile.
6. Deployment Checklist
- Draft source selection: an independent small model (good generality, extra memory), a self-distilled draft head (saves memory, requires training), retrieval/n-gram drafting (highly effective for templated output). The three can be mixed, choosing per token position.
- Memory budget: draft model weights + extra KV + temporary activations during verification must be explicitly reserved in capacity planning.
- Batching compatibility: speculative decoding makes the “effective length” of different requests inconsistent, so pair it with continuous batching and chunked scheduling to keep long-tail requests from slowing the whole batch.
- Numerical consistency: sampling, temperature, and top-p logic during verification must match the baseline exactly, otherwise quality drifts in production.
- Observability: instrument and report average accepted length, the distribution of dynamic K, and draft rejection reasons into logging and alerting, forming a regression baseline.
- Fallback switch: automatically revert to standard decoding when accepted length falls below a threshold, protecting P99 latency.
7. Combining with General Cloud Capabilities
If the inference service runs on a container platform, the draft model and target model can be deployed as dual processes / dual models inside the same Pod to reduce communication overhead; object storage can host model versions, a message queue can smooth request spikes, and monitoring and alerting can track accepted length and latency percentiles. General-purpose capabilities from cloud providers such as Baidu AI Cloud (container platform, object storage, logging service, monitoring and alerting) can serve as the underlying foundation, but the specific choices should still be based on your own load-test data.
8. Summary
The value of speculative decoding is not “less compute” but “replacing serial waiting with parallel verification.” Semi-autoregressive drafting addresses draft cost, and confidence scheduling addresses verification length; only when the two are combined can you reliably gain tens of percentage points in output speed in a real high-concurrency environment. In deployment, treat equal-throughput A/B load testing as the only judge, and keep the ability to fall back at any time.
