Reducing LLM Inference Costs: Expert Pruning and Speculative Decoding

    This article explores two practical techniques for lowering the inference cost of large language models, particularly Mixture-of-Experts (MoE) architectures. It begins by breaking down GPU memory usage into model weights, KV cache, and activations, then provides a step-by-step guide to expert pruning, including importance evaluation, selective removal, accuracy regression, and tiered pruning. It also explains the mechanism of speculative decoding, acceptance rates, and common reasons for low acceptance. Additional topics include KV cache management for long contexts, common pitfalls, and a pre-deployment checklist. The goal is to help practitioners balance model capability, memory footprint, and generation speed in real-world deployments.

    1. First, Understand Where GPU Memory Goes

    Before deploying a large MoE model, teams need a clear picture of what consumes GPU memory. It typically falls into three categories.

    Model weights. Weight size is roughly equal to the number of parameters multiplied by bytes per parameter. With FP16 or BF16, each parameter takes 2 bytes, so a trillion-parameter model needs about 2 TB just for weights. Even with INT8 or INT4 quantization, weights still far exceed a single GPU’s capacity, making multi-GPU parallelism the norm.

    KV cache. During autoregressive generation, the model must retain the key-value vectors for every layer up to the current token. The per-token KV cache size can be estimated as:

    Per-token KV cache bytes = 2 × number of layers × number of KV heads × head dimension × bytes per element

    Total cache for a single request is then multiplied by context length. More concurrent requests multiply the total further, so long contexts and high concurrency both compress available memory.

    Activations and temporary buffers. These include intermediate computation results, communication buffers, and verification intermediates from speculative decoding. This category is often underestimated and should be planned with headroom.

    The proportion of these three components depends on model architecture, precision, batch size, and context length. Numbers quoted in articles or promotional material without specifying these conditions cannot be directly applied to your own environment.

    2. How to Prune MoE Experts

    Mixture-of-Experts architectures split the feed-forward network into many experts, with each token activating only a few. Usage frequency can vary widely across experts; some are only called on for specific domains. Pruning aims to identify low-contribution experts and remove them.

    A common workflow has four steps.

    Step 1: Importance Evaluation. On a representative calibration dataset, count how often each expert is selected by the router and record how its output contributes to the final result. Common metrics include routing probability statistics, output norms, and the change in loss after removing an expert. The calibration set should cover the main task types in your business. Using only general-purpose corpora can misjudge expert importance.

    Step 2: Selective Removal. Remove experts in order of increasing importance. After each batch of removals, adjust the routing layer—for example, re-normalize the routing weights of the remaining experts. If conditions allow, perform light fine-tuning to restore the output distribution.

    Step 3: Accuracy Regression. Use your own business evaluation set to compare results before and after pruning. General benchmarks can serve as reference but cannot replace business-specific metrics. Recording should include baseline scores, pruned scores, evaluation set name, and sample count for later review.

    Step 4: Tiered Pruning. In practice, it is common to prepare multiple pruning strengths: a conservative version that removes fewer experts and an aggressive version that removes more. The conservative version carries lower accuracy risk; the aggressive version frees more memory. Choose the tier based on the minimum acceptable business accuracy.

    Pruning benefits go beyond memory reduction. During inference, fewer expert weights need to be loaded each forward pass, reducing memory bandwidth pressure and potentially improving end-to-end latency—but this improvement must also be verified through actual measurement.

    What If Accuracy Drops After Expert Pruning?

    First, determine which tasks suffered the most. If only certain domains degrade, the removed experts likely served those domains. Roll back those experts or switch to a more conservative tier. If all tasks degrade together, the routing layer was probably not adjusted correctly—check normalization and routing thresholds.

    3. Speculative Decoding: Principles and Acceptance Rate

    Large models generate tokens autoregressively, each requiring a full forward pass. Speculative decoding uses a small draft model to propose several candidate tokens, which the main model then verifies in a single parallel forward pass.

    The verification rule is as follows. For each candidate token, the main model outputs probability p and the draft model outputs q. If p ≥ q, accept the candidate; otherwise, accept with probability p/q. If a candidate is rejected, resample a token from the corrected distribution proportional to max(0, p − q) and discard all subsequent candidates. Under this rule, the output distribution is mathematically identical to sampling directly from the main model token by token. Under greedy decoding, results also match greedy decoding.

    Speedup depends on two factors: the acceptance rate of the draft model and the draft model’s own overhead. Higher acceptance means more tokens produced per main-model forward pass. A slower draft model adds more overhead.

    What If the Acceptance Rate Is Low?

    Four common causes:

    1. Distribution mismatch between draft and main model. Choose a smaller version from the same model family, or distill from the main model’s outputs to bring the draft model closer.
    2. The business text itself is hard to predict. Code completion and structured output are typically easier for a draft model to guess than open-ended dialogue. Test on real business traffic.
    3. Sampling temperature too high. Higher temperature makes both output distributions more spread out, lowering acceptance.
    4. Candidate length not set properly. If the candidate sequence is too long, later candidates are almost always rejected, wasting verification compute. Adjust candidate length dynamically based on a rolling window of acceptance rates.

    If acceptance remains low and draft model overhead is still non-trivial, overall throughput may fall below the baseline without speculative decoding—a situation called negative speedup. Measure both throughput and latency with and without speculative decoding before deployment.

    On the memory side, the draft model’s weights, its own KV cache, and extra verification activations all consume memory. Freed memory from pruning can accommodate these overheads.

    4. Long Contexts: Managing the KV Cache

    The longer the context, the larger the KV cache. As shown earlier, cache usage scales with context length, concurrency, and bytes per token. Thus, the maximum supported context depends on the combination of memory budget, precision, and concurrency strategy.

    Common optimization techniques include:

    • Paged KV cache. Inspired by OS virtual memory, the cache is divided into fixed-size blocks allocated on demand. This reduces memory fragmentation when mixing short and long requests.
    • Attention optimization. Use block-sparse attention or sliding window approaches to reduce compute for long sequences. Sliding windows discard distant information, so evaluate whether tasks rely on long-range dependencies.
    • KV cache quantization. Compress the cache from FP16 to INT8 or lower. This significantly reduces memory but incurs accuracy loss that must be validated on long-context evaluation sets.
    • Continuous batching. Dynamically merge computation at the request level, preventing short requests from waiting too long behind long requests, thereby improving GPU utilization.

    How Many Tokens Can a Long Context Support?

    There is no universal answer. It should be measured on your target hardware, model precision, and concurrency. Fix a configuration, gradually increase context length, and record peak memory and time-to-first-token until memory or latency exceeds limits. If an article or promotion claims a context limit without specifying memory capacity, batch size, and KV cache precision, do not adopt it directly.

    5. Common Mistakes

    The following errors frequently appear in practice:

    • Using general benchmarks instead of business-specific evaluation, leading to noticeable online degradation after pruning.
    • Calibration data not matching online traffic distribution, causing distorted expert importance rankings.
    • Testing only single-request latency instead of throughput and tail latency under concurrency.
    • Only considering model weight memory while ignoring activations and speculative decoding overhead, causing out-of-memory at deployment.
    • Treating others’ cost reductions as your expected savings without factoring in your own GPU pricing and deployment scale.

    6. Pre-Deployment Checklist

    • Model weight license permits pruning, distillation, and commercial deployment.
    • A regression evaluation set covering core business scenarios is established, with baseline scores recorded.
    • The lower bound for each post-pruning metric is defined; fall back to the previous tier if exceeded.
    • A threshold for speculative decoding acceptance rate is set; disable the feature automatically when below the threshold.
    • Measure throughput and tail latency with and without speculative decoding to confirm real benefit.
    • Long-context configurations are tested on the target GPU, with headroom for activations and concurrency fluctuations.
    • A rollback plan is ready: keep old model instances for a period, switch via configuration without rebuilding.
    • Monitoring covers memory usage, acceptance rate, time-to-first-token, and error rate.

    7. Conclusion

    Reducing inference cost for large language models requires trade-offs among model capability, memory footprint, and generation speed. Expert pruning reduces weight footprint, and speculative decoding trades extra compute for speed. Long-context management, careful evaluation, and a robust deployment checklist help ensure that cost savings do not come at the expense of business quality.