Speculative Decoding for Online LLM Inference: A Full-Stack Acceleration Practice

    This article explains why online LLM inference is often limited by memory bandwidth during decoding rather than peak compute, how speculative decoding uses one parallel verification pass to accept multiple tokens, and what full-stack engineering issues must be solved before it works reliably in production. It also covers measurement metrics, rollout steps, and common pitfalls for teams deploying speculative decoding under real online traffic.

    1. The Starting Point: Online Inference Is Not Limited by Peak Compute

    In online large language model (LLM) serving, a request is split into two stages. The prefill stage processes input tokens in parallel and is compute-intensive. The decode stage generates tokens autoregressively one by one and is memory-bandwidth-intensive. User experience is often determined by the decode stage: for every token generated, all model weights must be moved from GPU memory into the compute units once, while only one or two tokens actually participate in matrix operations. As a result, compute capacity is largely idle, and single-user TPS (tokens per second) is limited by memory bandwidth rather than peak compute.

    This is also why simply switching to a faster GPU often yields limited improvement: the bottleneck is memory access and scheduling, not floating-point capability. Speculative decoding is proposed specifically to address this structural waste.

    2. Core Idea of Speculative Decoding: Verify Once, Accept Multiple Tokens

    The basic workflow can be summarized as “guess first, verify later”:

    1. A lightweight speculation source—a small draft model, a model’s built-in multi-token prediction head, or a heuristic method based on historical context—proposes K candidate tokens at once.
    2. The target large model performs one parallel forward pass over these K positions and obtains the true distribution for each position.
    3. Verification proceeds from left to right. At the first mismatch, the sequence is truncated, and a token is resampled from the target model’s distribution at that position to fill the gap.
    4. The accepted prefix and the filled token are written into the KV cache, and the next round begins.

    The key is step 2: one forward pass verifies K positions. As long as the candidates have a sufficiently high probability of being accepted, a single round can produce multiple tokens at a cost almost equal to generating one token. With rejection-sampling-style verification rules, the output distribution remains strictly consistent with token-by-token sampling from the target model. This is therefore “lossless acceleration”—it does not change generation quality, only the generation path.

    Let the average acceptance length be L. The theoretical speedup is close to L, while the actual gain is reduced by draft overhead, batching interference, and KV management costs.

    3. From “Speculative” to “Production-Ready”: Four Issues a Full-Stack Framework Must Solve

    Early approaches mostly remained at the demo level of a single machine and a single request. To work reliably under real online traffic, a complete speculative decoding framework must handle at least the following engineering problems.

    3.1 Coupling Between the Speculation Source and the Model

    A model’s built-in multi-token prediction (MTP) head does not require an additional draft model and is simple to deploy, but its acceptance length is constrained by the training objective. An independent small draft model is more flexible but introduces extra GPU memory and an additional forward pass. In engineering practice, teams usually need to tune this empirically between “acceptance rate” and “extra overhead” rather than copying paper configurations directly.

    3.2 Dynamic Speculation Length

    A fixed K value performs poorly in long-tail scenarios. At high-entropy positions—such as code indentation, list markers, or open-domain transitions—candidates are almost all rejected, and the draft cost is wasted. Mature implementations adjust K online based on recent acceptance rates and the distribution entropy at the current position, and may even fall back directly to token-by-token decoding at high-entropy positions.

    3.3 Coexistence with Continuous Batching

    Online services commonly use continuous batching to improve overall throughput. Speculative decoding causes different requests in the same batch to produce different numbers of tokens per round, leading to alignment difficulties, memory fragmentation, and scheduling jitter. The framework needs to support variable-length outputs, per-request KV rollback, and padding or grouping within the batch so that individual requests do not slow down the whole batch.

    3.4 Correctness of KV Cache and Rollback

    Rejected candidates must be rolled back precisely, including cache length, position encoding, and sampler state. This is where hidden defects most easily appear: the system looks faster, but the output silently changes. Distribution-consistency regression tests are therefore essential.

    Illustrative pseudocode (tensor details omitted):

    1. def speculative_step(model, kv, draft, K):
    2. draft_tokens = draft.propose(kv, K) # 1. Propose candidates
    3. logits = model.forward(kv, draft_tokens) # 2. Parallel verification in one forward pass
    4. accepted = 0
    5. for i, tok in enumerate(draft_tokens):
    6. p, q = logits[i], draft.prob(tok)
    7. if random() < min(1.0, p[tok] / q[tok]): # 3. Rejection-sampling check
    8. accepted += 1
    9. else:
    10. kv.rollback(accepted) # 4. Precise rollback
    11. return draft_tokens[:accepted] + [sample(p)]
    12. kv.commit(accepted)
    13. return draft_tokens + [sample(logits[-1])]

    4. How to Measure the Gain: Do Not Look at a Single TPS Number

    In public technical disclosures, such full-stack speculative approaches commonly deliver single-user TPS improvements in the tens of percentage points over traditional multi-token prediction baselines, and under high concurrency they still show further gains relative to stronger verification-based schemes. When applying this to your own business, however, it is better to establish multidimensional metrics:

    • Single-user TPS / TPOT: directly reflects interaction fluency and is the primary benefit metric for speculative decoding.
    • TTFT: prefill is unaffected; if the draft model competes for resources, TTFT may actually become worse, so monitor it separately.
    • Acceptance length L and acceptance rate: the most effective diagnostic metrics. If L stays below 1.5 for a long time, the speculation source does not match the business corpus.
    • System total throughput and GPU utilization: gains are largest at low concurrency; at high concurrency the system is already compute-saturated, so gains are compressed.
    • Cost per token: converting acceleration into cost is the basis for decisions.

    It should be clear that speculative decoding is not worthwhile under all workloads. At extremely low concurrency, with very short sequences, or with highly uncertain outputs, the gain may be close to zero or even negative. Before launch, A/B testing with real traffic replay is more reliable than any offline benchmark.

    5. Suggested Deployment Path

    1. Build a baseline profile: collect the TPS, TTFT, and L-value distributions of the existing service, and determine whether the bottleneck is memory access or scheduling.
    2. Validate at a single point: enable speculative decoding in a single-GPU, single-request environment, and run output-consistency regression tests with fixed random seeds.
    3. Roll out gradually: proceed from 1% to 10% to full traffic, focusing on P99 latency and error rate rather than averages.
    4. Elasticity and observability: use a container platform to host inference instances, monitoring and alerting to track acceptance rate and latency percentiles, and a logging service to retain per-round acceptance length for offline analysis; store model and configuration artifacts in object storage for version management. If you use a cloud platform such as Baidu AI Cloud, these general capabilities can be combined directly rather than building a full infrastructure stack in-house.
    5. Re-evaluate capacity: after acceleration, the load per instance increases, so rate limiting, queuing, and autoscaling thresholds must be reviewed at the same time to avoid shifting the bottleneck to the gateway layer.

    6. Common Misunderstandings

    • Treating “lossless” as “risk-free”: numerical consistency depends on correct verification implementation and must be tested.
    • Tuning only K without looking at the corpus: acceptance rate depends heavily on business distribution, and the optimal configuration differs greatly across code, customer service, and summarization scenarios.
    • Ignoring high-concurrency degradation: low-concurrency gains cannot be linearly extrapolated to production peaks.
    • Introducing too many optimizations at once: when speculative decoding is combined with quantization and cache reuse, attribute gains item by item; otherwise failures become difficult to locate.

    7. Conclusion

    The value of speculative decoding is not in proposing a new model, but in running an already trained model more economically. It is a typical engineering win: no weight changes, no quality changes, just scheduling and verification restructuring to recover wasted compute. For developers, the real barrier is not understanding the algorithm, but polishing details such as dynamic speculation length, coexistence with batching, and KV rollback, along with a metric system that honestly reflects the gains. Do these three things well, and inference acceleration becomes a reliably reproducible engineering result rather than a best case from a paper.