Speculative Decoding: Accelerating LLM Inference with Small Draft Models

    Speculative decoding is an effective technique for overcoming the memory-bandwidth bottlenecks of autoregressive large language model (LLM) inference. By utilizing a small, fast draft model to generate candidate tokens that are verified in a single forward pass by a larger target model, it reduces serial waiting time without compromising output quality. This article explores the fundamental workflow, mathematical speedup estimation, key influencing factors, engineering implementation details, and practical recommendations for adopting speculative decoding in real-world applications.

    1. Background: Performance Bottlenecks in Autoregressive Decoding

    Inference in large language models is typically autoregressive. The model generates one token at a time, appends it back to the context, and proceeds to the next computation step. Each step requires reading all model weights and the cached KV cache, while the actual computation volume is relatively small. Consequently, in single-request, small-batch scenarios, the compute units often wait for data, making memory bandwidth the primary bottleneck.

    This characteristic leads to a key observation: under memory-bound conditions, a single forward pass processing multiple tokens takes nearly the same time as processing just one. If a large model could verify multiple candidate tokens in a single forward pass, several originally serial steps could be merged into one. This is the core motivation behind speculative decoding.

    2. Basic Workflow

    Speculative decoding involves two models:

    • Draft model: A small, fast model responsible for predicting $k$ candidate tokens sequentially.
    • Target model: A large, high-quality model that makes the final decision on the output.

    Each decoding round consists of three steps:

    1. Draft Generation: The draft model autoregressively generates $k$ candidate tokens starting from the current context. This step is fast because the model is small.
    2. Parallel Verification: The original context plus the $k$ candidates are concatenated as input, and the target model performs a single forward pass. Because the Transformer attention mechanism can process the entire input in parallel, the target model simultaneously outputs the probability distribution for each position.
    3. Position-by-Position Accept/Reject: Comparison starts from the first candidate. If the target model agrees with the candidate at that position, it is kept, and the next is checked. Upon encountering the first position where the candidate is rejected, that candidate and all subsequent ones are discarded, and a replacement token is sampled from the target model’s distribution at that position.

    This yields two outcomes. First, if all $k$ candidates are accepted, the target model’s output at position $k$ is also valid, resulting in $k+1$ tokens for that round. Second, even if all are rejected, the target model will still produce at least one correct token, meaning the output per round is never less than that of standard decoding.

    In short: the draft model “guesses,” the target model “verifies,” and correctly guessed tokens effectively parallelize the computation time for free.

    3. Why Output Quality Does Not Degrade

    Speculative decoding is often misunderstood as an approximation technique. In reality, when using acceptance rules based on rejection sampling, the final output distribution is theoretically identical to sampling directly from the target model token-by-token. Several research papers around 2023 provided proofs for this.

    For sampling, suppose the draft model gives a probability of $p(t)$ for token $t$ at a certain position, and the target model gives $q(t)$. If $t$ is accepted with probability $\min(1, q(t)/p(t))$, and otherwise resampled from the corrected distribution $\text{norm}(\max(0, q - p))$, the final distribution is guaranteed to be exactly $q$. This means the acceleration is achieved without altering the output distribution.

    Greedy decoding (taking the token with the highest probability at each step) is even simpler: a draft token is accepted if it matches the target model’s argmax, otherwise it is rejected. The output is perfectly consistent with standard decoding, making it easy to perform regression testing.

    4. Mathematical Estimation of Speedup

    Assume the probability of each candidate token being accepted is $\alpha$ (acceptance rate, assuming independence across positions) and the candidate length is $k$. The expected number of tokens the target model can produce per round is:

    E=1−αk+11−αE = \frac{1 - \alpha^{k+1}}{1 - \alpha}

    For example, when $\alpha = 0.8$ and $k = 4$, $E = (1 - 0.8^5) / 0.2 \approx 3.36$. This means the target model outputs about 3.4 tokens per forward pass on average.

    This number is only a theoretical upper bound; actual gains must subtract the following overheads:

    • Computation time of the draft model itself (increases with $k$).
    • Extra computation for the target model to process longer inputs.
    • Scheduling, synchronization, and cache rollback costs between the two models.

    Therefore, the actual speedup ratio is typically lower than $E$. In publicly available industry reports, speedups in single-request scenarios are mostly around 2x. The exact value depends on the task, model combination, and hardware, so one should not directly apply others’ data as expectations.

    5. Key Factors Influencing ROI

    5.1 Acceptance Rate

    The acceptance rate is the primary factor determining the return. The closer the draft model’s distribution is to the target model’s, the higher the acceptance rate. Generally:

    • Tasks with deterministic outputs like code completion, formatted text, and templated replies tend to have high acceptance rates.
    • Open-ended creative tasks and high-temperature sampling tasks tend to have lower acceptance rates.

    5.2 Draft Model Size and Speed

    A smaller draft model generates faster, but the gap with the target model widens, reducing the acceptance rate. A trade-off is necessary. A common practice is to select a smaller version from the same model family with similar training data as the draft.

    5.3 Candidate Length $k$

    As $k$ increases, the potential gain per round grows, but the exponential decay of the acceptance rate makes it increasingly difficult for later candidates to be adopted, leading to more wasted computation on failures. A reasonable $k$ usually falls between a few to a dozen and should be determined through empirical testing.

    5.4 Batch Size and Hardware

    As batch size increases, the compute units gradually become saturated, raising the relative cost of parallel verifying multiple candidates, which diminishes the relative gains of speculative decoding. Thus, it is better suited for low-concurrency, low-latency interactive scenarios rather than high-throughput offline batch processing.

    6. Engineering Implementation Details

    6.1 Tokenizer Consistency

    The draft model and target model must use the exact same tokenizer. Otherwise, the token IDs generated by the draft model are meaningless to the target model. This is the most easily overlooked check before deployment.

    6.2 KV Cache Rollback

    Rejected candidates leave traces in the target model’s cache. The implementation must truncate the cache length to the last accepted position and ensure the draft model’s cache rolls back synchronously. Improper cache management is a common source of correctness issues.

    6.3 Adaptive Candidate Length

    The acceptance rate fluctuates with input content. You can maintain a sliding average of the acceptance rate over recent rounds and dynamically adjust $k$ accordingly: increase $k$ when the acceptance rate is high, decrease it when low, or even fall back to standard decoding.

    6.4 Memory Budget

    Speculative decoding requires loading two models simultaneously, increasing memory usage. In memory-constrained environments, the size of the draft model must be strictly limited, or the overhead may outweigh the benefits.

    Below is illustrative pseudocode showing the main logic of a single speculative decoding round (omitting batching and cache details):

    1. def speculative_step(target, draft, prefix, k):
    2. # 1. Draft model autoregressively generates k candidates
    3. candidates, draft_probs = [], []
    4. ctx = list(prefix)
    5. for _ in range(k):
    6. p = draft.next_token_probs(ctx)
    7. t = sample(p)
    8. candidates.append(t)
    9. draft_probs.append(p)
    10. ctx.append(t)
    11. # 2. Target model single forward pass, getting distributions for k+1 positions
    12. target_probs = target.forward_all_positions(list(prefix) + candidates)
    13. # 3. Verify position by position
    14. accepted = []
    15. for i, t in enumerate(candidates):
    16. q, p = target_probs[i], draft_probs[i]
    17. if random() < min(1.0, q[t] / p[t]):
    18. accepted.append(t)
    19. else:
    20. accepted.append(sample_residual(q, p)) # Sample from norm(max(0, q-p))
    21. return accepted
    22. # All accepted, append a bonus token
    23. accepted.append(sample(target_probs[k]))
    24. return accepted

    This example assumes the distributions for the same batch of positions are available for both models. In actual engineering, boundary cases with zero probability and numerical stability issues must also be handled.

    7. Applicable Scenarios and Boundaries

    Scenarios suitable for speculative decoding include:

    • Latency-sensitive online conversations and interactive programming assistants.
    • Generation tasks with long outputs and relatively predictable content.
    • Deployment environments with low concurrency and surplus computing resources.

    Unsuitable scenarios include:

    • High-throughput services where compute is already saturated by large batch requests.
    • Cases where the draft and target models differ significantly on the target task.
    • Environments with tight memory that cannot accommodate a second model.

    8. How to Evaluate ROI Scientifically

    When evaluating speculative decoding, avoid looking only at single demonstrations or peak data. Pay attention to the following metrics:

    • End-to-end latency: Time from request to complete output; this is the most direct user experience metric.
    • Sustained generation speed: Measured in tokens generated per second, excluding the latency of the first token.
    • Acceptance rate and average accepted length: Helps determine if the source of gains aligns with expectations.
    • Quality consistency: Compare outputs under greedy decoding to see if they perfectly match the baseline.

    When testing, fix the prompt set, perform sufficient warm-up, and conduct an apples-to-apples comparison against a baseline with speculative decoding disabled. Results can vary greatly across different tasks and prompt lengths, so conclusions should cover typical business workloads.

    9. Practical Recommendations

    1. Clarify whether the business bottleneck is latency or throughput before deciding to introduce speculative decoding.
    2. Choose a draft model with a matching tokenizer and similar distribution to the target model, and measure the acceptance rate on a small dataset first.
    3. Start with a small candidate length, tune empirically, and introduce adaptive mechanisms.
    4. Complete correctness regression tests before going live to confirm the output distribution or greedy results meet expectations.
    5. Continuously monitor acceptance rate and latency metrics, and promptly re-evaluate parameters when task distributions change.

    The essence of speculative decoding is trading parallel computation for serial waiting time. By understanding its acceptance rules, speedup formulas, and engineering constraints, you can determine whether it is worth introducing in specific scenarios and translate theoretical speedups into stable, reproducible practical gains.