Training and Evaluating Draft Models for Speculative Decoding: A Practical Pipeline
This article provides a practical guide to building, training, and evaluating draft models for speculative decoding. It covers the core principles of this inference acceleration technique, details a three-stage pipeline spanning data preparation, model training, and performance evaluation, and discusses key metrics, engineering considerations, and common pitfalls for production deployment.
Why Speculative Decoding Matters
Large language models (LLMs) generate tokens autoregressively, requiring a full forward pass for each token produced. In high-concurrency scenarios, this sequential process consumes significant computational resources, and per-request latency grows linearly with output length. Speculative decoding offers a common solution: a smaller, faster draft model proposes a sequence of candidate tokens, which the target model then verifies in parallel.
The efficiency gain stems from the fact that the target model can validate multiple positions simultaneously, at a fraction of the cost of generating tokens one by one. As long as a reasonable proportion of the draft model’s tokens are accepted by the target model, overall throughput improves. Consequently, the engineering quality of speculative decoding hinges on the draft model’s quality, which in turn depends on its training data and methodology.
How a Draft Model Works
A single round of speculative decoding involves three steps:
- Propose: The draft model generates k candidate tokens based on the current context.
- Verify: The target model processes the original context concatenated with the k candidate tokens in parallel, computing its output distribution for each position.
- Accept/Reject: The system compares tokens sequentially. A candidate token is accepted if it matches the target model’s choice (or meets the acceptance criterion) at that position. The process stops at the first mismatch, and the token proposed by the target model at that position is used instead.
This mechanism guarantees at least 1 token is produced per round and at most k + 1. The closer the draft model’s distribution is to the target model’s, the higher the average number of accepted tokens per round (acceptance length), leading to greater speedup.
The Three-Stage Training Pipeline
A reproducible toolchain for developing draft models typically breaks the workflow into three sequential stages: data preparation, training, and evaluation. The output of each stage serves as the input for the next, making it critical to design and validate each step carefully to avoid cascading errors.
Stage 1: Data Preparation - Building a Target Output Cache
The draft model learns to mimic the target model’s behavior, not just generic text. Therefore, the core of this stage is to have the target model generate responses to a diverse set of prompts and save the results. This involves:
- Gathering Diverse Prompts: Collect prompts across various domains like mathematical reasoning, code generation, multi-turn dialogue, and general question answering to prevent the draft model from becoming overly specialized.
- Generating Batched Responses: Use an efficient inference engine to have the target model generate answers in bulk, recording intermediate hidden states or output distributions during the generation process.
- Structuring the Cache: Format the prompts, responses, and target outputs into a unified data structure to create the target cache.
The target cache can be enormous. A rough estimate for its size is:
Cache Size ≈ Number of Samples × Average Sequence Length × Hidden Dimension × Bytes per Element × Stored Layers/Distributions
With millions of samples and full hidden states, the cache can easily reach tens of terabytes. When planning storage, it’s crucial to reserve ample space and use sharding and on-demand loading to prevent I/O from becoming a bottleneck during training.
Stage 2: Training - Fitting the Target Model’s Output Behavior
This stage uses the cached target outputs as supervision for the draft model. Standard practices include:
- Soft Label Distillation: Using the target model’s output distribution as a soft label and training the draft model with KL divergence or cross-entropy loss.
- Hidden State Alignment: For draft models based on hidden states, simultaneously aligning intermediate representations so the draft model can capture the target model’s semantic information earlier.
- Positional Loss Weighting: Weighting the loss based on token position. Earlier draft tokens are more likely to be accepted, so their fit should be prioritized.
The default configuration is designed for a single node with 8 GPUs. When extending to multiple nodes, keep these factors in mind:
- Scaling the Learning Rate: The global batch size changes with the number of GPUs, so the learning rate needs adjustment, typically via linear scaling with a warm-up phase.
- Regular Checkpointing: Regularly save checkpoints and log training loss and acceptance length on a validation set to allow rollback before overfitting occurs.
- Reproducibility: Fix the random seed and data ordering to ensure experiments are reproducible.
Stage 3: Evaluation - Measuring Real-World Gains
This stage aims to answer one question: does the draft model actually make inference faster on real tasks? Training loss alone is insufficient. Evaluation should cover several task categories using public benchmark datasets:
| Task Category | Typical Use Case | Key Metrics |
|---|---|---|
| Mathematical Reasoning | Multi-step calculations and symbolic derivation | Acceptance Length |
| Code Generation | Function implementation and algorithm problems | Acceptance Length, First-Token Latency |
| Conversation | Multi-turn interaction and instruction following | Acceptance Rate Stability |
| General QA | Open-domain knowledge and complex instructions | End-to-End Throughput |
Acceptance rates vary significantly across tasks. Code and formatted text are often easier to predict, while open-ended creative writing is harder. Therefore, evaluation results should be reported per task, not as a single average.
Key Metrics and Estimating the Speedup
Evaluation results need to be quantified using a few clear metrics.
- Average Acceptance Length (τ): The average number of draft tokens accepted per verification round. This directly reflects the draft model’s quality.
- Draft Overhead Ratio (c): The ratio of the draft model’s single forward pass time to the target model’s. A smaller draft model results in a lower
c.
Under ideal assumptions (ignoring scheduling and communication overhead), each round produces approximately τ + 1 tokens (including the correction from the target model) and takes about 1 + k · c target-model forward units. This leads to the theoretical speedup formula:
Theoretical Speedup ≈ (τ + 1) / (1 + k · c)
This formula highlights two key points. First, improving the acceptance length is more effective than simply shrinking the draft model, unless the model is already extremely small. Second, a larger k is not always better: with more candidate tokens, the probability of rejection at later positions increases, and the overhead of the draft model also grows. The optimal value for k must be determined experimentally on the target workload.
The illustrative code below shows how to calculate the average acceptance length from per-round verification results:
def average_accepted_tokens(round_results):"""Calculate the average number of accepted draft tokens per round.Each element in round_results is a dictionary with an "accepted"key, indicating how many draft tokens were accepted by the target model."""if not round_results:return 0.0total_accepted = sum(r["accepted"] for r in round_results)return total_accepted / len(round_results)
In the evaluation report, it’s recommended to record acceptance length, end-to-end throughput, and tail latency simultaneously. Relying only on throughput can mask a degradation in performance for long-tail requests.
Engineering Considerations for Deployment
Impact at High Concurrency
The benefits of speculative decoding are most pronounced at low concurrency, where computing resources per request are relatively idle. As concurrency increases, batch processing already improves hardware utilization, and the draft model’s extra computation consumes some of those resources. The benefits of the same draft model can vary greatly depending on the concurrency level. Testing should be done under realistic production traffic during early development, not just with single-request benchmarks.
Rolling Out a New Draft Model
When replacing an existing production draft model, a phased rollout is recommended:
- Shadow Testing: Compare the output quality and latency on shadow traffic to confirm the inference results show no statistically significant regression.
- Incremental Rollout: Gradually shift traffic in stages while monitoring error rates, GPU memory usage, and tail latency.
- Rollback Plan: Maintain a quick rollback path to the previous solution until the new model has been stable for a full business cycle.
Data and Model Version Management
Whenever the target model is upgraded, the target cache and the draft model must be regenerated or retrained. It is essential to record the target model version, prompt source, and generation parameters for each cache to prevent version mismatches that could cause an unexpected drop in acceptance rate.
Common Pitfalls
- Low Acceptance Rate: First, verify that the data distribution matches the real-world prompt distribution for your service. Next, ensure the generation parameters used for creating the target cache are consistent with your production inference settings (e.g., sampling temperature).
- Training Loss Decreases but Acceptance Length Doesn’t Improve: Loss and acceptance behavior are not perfectly correlated. Add evaluation metrics based on acceptance length and validate the model on this metric during training.
- High Storage and I/O Costs: Consider storing outputs only at required positions or using quantized storage. Be aware that quantization can introduce errors, so its impact on the acceptance rate should be tested.
Conclusion
Speculative decoding offers a path to faster inference at a relatively low extra cost. To use it reliably in a production environment, three things are crucial: a high-quality target cache that matches the production data distribution, a reproducible training process, and an evaluation framework centered on acceptance length and end-to-end metrics. Standardizing these components enables teams to continuously iterate on draft models and quickly adapt when the target model is upgraded.
