Speculative Decoding for LLMs: Acceleration Practice and Performance Analysis

    This article explains how speculative decoding accelerates large language model inference, from its core mechanism and average acceptance length to cost structure and engineering configuration. It focuses on long-context code generation scenarios, showing how to measure baselines, tune draft length, and evaluate throughput across different workload types for reliable performance gains.

    1. Background: Why Long-Context Inference Needs More Efficient Decoding

    As intelligent coding tools, code assistants, and long-document understanding applications become more common, the input length of large language models keeps growing. Outputs are also shifting from short text to multi-turn code completion, cross-file understanding, and complex task execution.

    In this context, traditional autoregressive decoding is hitting efficiency bottlenecks: it generates only one token per step. For small-batch requests, the GPU repeatedly reads a large number of model weights while the matrix computation scale remains limited, so compute utilization is often low.

    To address this, the industry has widely adopted speculative decoding as an inference acceleration technique. The core idea is to use a smaller draft model to propose multiple candidate tokens at once, then have the target model verify them in a single parallel pass, advancing multiple positions in one forward computation. While preserving the output distribution, this approach can significantly reduce the time cost of the decoding stage.

    This article analyzes this technical approach across several dimensions: principles, cost structure, acceptance length, engineering configuration, and measured performance. It also provides a practical evaluation methodology for long-context code generation scenarios.

    2. How Speculative Decoding Works

    2.1 From Token-by-Token Generation to Parallel Verification

    Standard autoregressive (AR) decoding produces only one token per step. It is logically simple, but every step requires a full forward pass through the target model. For small-batch requests, memory access overhead far exceeds computation overhead, leading to low hardware utilization.

    Speculative decoding splits generation into two stages:

    1. Draft stage: a lightweight drafter consecutively generates a sequence of candidate tokens.
    2. Verification stage: the target model performs a single parallel forward pass over the candidates and determines which positions can be accepted.

    During verification, all drafts after the first rejected position are discarded. Only the consecutively accepted prefix is kept, and the target model generates one additional token. As a result, the number of tokens advanced per step is usually greater than one.

    2.2 Why It Does Not Change the Output Distribution

    As long as the verification rule is designed correctly, speculative decoding is mathematically equivalent to sampling from the original target distribution. The draft model only proposes; the target model makes the final decision on acceptance. It is essentially a computation reordering, not a rewrite of model output quality.

    2.3 Key Metric: Average Acceptance Length

    One of the core metrics for measuring speculative decoding effectiveness is the average acceptance length τ, the average number of tokens advanced per step, including the one generated by the target model. A higher τ indicates better draft quality and more obvious per-step gains.

    However, τ is not the only determining factor. The per-step time can be approximated as:

    1. Per-step time ≈ draft generation time + target verification time + other overhead

    Other overhead includes scheduling, sampling, and state maintenance. This shows that even if acceptance length improves, if drafting or verification is too expensive, the overall speedup may still be limited.

    3. What Parallel Drafting Actually Saves

    3.1 It Eliminates Repeated Target Model Forward Passes

    In traditional AR, generating each additional token requires another target model run. Speculative decoding combines the verification of multiple positions into a single forward pass, saving the number of times the target model is repeatedly invoked.

    This is also why it delivers more obvious gains in small-batch, low-concurrency scenarios: the GPU is more likely to be slowed by memory access and scheduling overhead rather than being fully compute-bound.

    3.2 Verification Cost Can Be Significant

    In some public experimental setups, the verification stage accounts for a large proportion of total per-step time, commonly around 70%. This means the draft model must be lightweight enough, and the draft length cannot be extended indefinitely; otherwise, verification cost will consume most of the gains.

    3.3 Draft Quality Matters More Than Draft Length

    A common misconception is that longer drafts are always better. In fact, if many candidates in the latter part are rejected, it not only wastes draft computation but also increases the verification burden. A more reasonable goal is to improve the prefix acceptance rate, concentrating effective drafts in the earlier portion.

    4. Special Challenges in Long-Context Code Scenarios

    4.1 Inputs Are Getting Longer, and Outputs Are Not Always Regular Code

    Code agents often handle extremely long contexts, such as cross-file dependencies, historical conversations, tool call records, and partial runtime logs. As input length increases, both attention computation and cache management pressure grow, and the relative gains in the decoding stage change accordingly.

    At the same time, code output is not always highly templated. For tasks involving complex refactoring, cross-module changes, and mixed natural language explanations, the draft hit rate drops and acceptance length fluctuates.

    4.2 Measured Throughput Must Be Evaluated by Scenario

    For short code requests, the context is shorter and the output is more regular, so the speculative decoding speedup is usually higher. In multi-turn completion tasks with contexts approaching the hundred-thousand-token level, both acceptance length and throughput decline. Therefore, evaluation should not rely on a single peak number, but should distinguish:

    • Short input, short output;
    • Long input, short output;
    • Long input, long output;
    • Multi-turn continuous completion.

    Only by recording results per scenario can you determine the real retained gains of an optimization in production.

    5. Configuration Recommendations for Engineering Deployment

    5.1 Measure the Baseline First, Then Discuss Speedup

    It is recommended to first record the AR baseline throughput without speculative decoding, then gradually enable the drafting mechanism and observe three curves: τ, per-step time, and end-to-end throughput. Without a baseline, any speedup ratio lacks a reference.

    5.2 Control Draft Length and Verification Batch Size

    Draft length is not always better when larger. Start with a smaller draft length to observe the acceptance rate, then gradually increase it until verification cost begins to noticeably erode the gains. For long-context tasks, avoid blindly extending the draft.

    5.3 Pay Attention to Numerical Precision and Runtime Environment

    Different precision modes affect memory usage, bandwidth pressure, and verification stability. In constrained environments, mixed precision or quantization schemes may deliver higher throughput, but output consistency and long-context performance must be observed at the same time.

    5.4 Make Monitoring Metrics a Standard Capability

    In real services, it is recommended to include average acceptance length, draft hit rate, verification time proportion, end-to-end latency, and throughput in logging services and monitoring/alerting systems. Only by forming a closed loop can parameter configurations be continuously optimized.

    6. A Simplified Pseudocode Example

    1. def speculative_decode(target, drafter, prompt, max_new_tokens, draft_len):
    2. state = target.init_state(prompt)
    3. output = []
    4. while len(output) < max_new_tokens:
    5. draft = drafter.propose(state, draft_len)
    6. accepted, bonus = target.verify(state, draft)
    7. output.extend(accepted)
    8. if bonus is not None:
    9. output.append(bonus)
    10. state = target.advance(state, len(accepted) + (bonus is not None))
    11. return output

    This pseudocode highlights three points: drafts are proposed by the small model, verification is completed by the target model, and state advancement depends only on the length of the accepted prefix.

    7. Conclusion: Speedup Is Only a Result; System Fit Is What Matters

    The value of speculative decoding lies not in a single-point number, but in whether it can reliably deliver gains in a specific service form. For tasks like long-context code generation, what truly matters is the matching relationship among acceptance length, verification cost, runtime precision, and scenario distribution.

    From an engineering perspective, it is recommended that developers break evaluation into four steps: baseline measurement, parameter scanning, scenario stratification, and online monitoring. This avoids being misled by a single peak and enables more reliable performance tuning and capacity planning in general-purpose compute and inference environments such as Baidu AI Cloud.