Reducing LLM Inference Costs: Expert Pruning and Speculative Decoding

    Learn how to evaluate and implement expert pruning and speculative decoding to reduce LLM inference costs. This guide covers baseline measurements, expert importance scoring, layer-specific pruning, post-pruning validation, and draft model selection, with practical considerations for memory, output quality, and decoding speed.

    1. Why LLM Inference Costs Remain High

    Large language model inference costs are driven primarily by GPU memory requirements and the number of GPUs needed. Model weights must remain in GPU memory, while each active session also requires a KV cache during generation. These requirements grow with model size and context length.

    For self-hosted infrastructure, this translates into GPU acquisition costs. In the cloud, it appears as time-based GPU rental charges.

    Mixture-of-experts (MoE) models have large total parameter counts, but activate only a small subset of experts for each token. This can lead to an assumption that every expert must remain in GPU memory, even when some experts are rarely used in a particular workload. Expert pruning targets this opportunity.

    There is no universal cost-reduction figure. Savings depend on the model architecture, workload distribution, hardware, and serving concurrency. Any claim about potential savings needs to be verified against your own benchmarks.

    2. Establish a Baseline Before Making Changes

    Record the original model’s performance before modifying it. At a minimum, measure:

    • GPU memory usage: Record model weight memory, KV cache memory, and peak memory usage separately.
    • Generation performance: Measure time to first token (TTFT) and output tokens per second.
    • Task quality: Evaluate benchmarks relevant to your application, not just public leaderboard scores.
    • Serving configuration: Document GPU type and count, parallelization strategy, batch size, and the distributions of input and output lengths.

    Without a baseline, you cannot determine whether an optimization actually works. A lower memory footprint after pruning is not enough: output quality and latency may also have changed.

    3. How to Prune MoE Experts

    3.1 Evaluate Expert Importance

    Run the model on a calibration dataset and collect three types of information for each expert:

    • Activation frequency.
    • The sum of routing weights.
    • Changes in downstream metrics when the expert is removed.

    These signals can be combined into an importance score. One common approach is leave-one-out ablation: remove each expert individually, measure the resulting quality degradation, and rank experts by the size of that degradation.

    The calibration dataset should cover the main task types in your application. Use enough samples to obtain stable activation-frequency estimates. With too few samples, expert rankings may fluctuate randomly, making pruning decisions unreliable.

    3.2 Set Different Pruning Limits for Different Layers

    Experts in earlier layers often support general-purpose feature extraction, so pruning them can introduce broader distribution shifts. Experts in later layers tend to be more task-specific and may be better pruning candidates.

    In practice, set separate pruning limits for different layers. Within each layer, rank experts by importance and remove them gradually.

    3.3 Increase the Pruning Ratio Gradually

    Start with a small pruning ratio and increase it incrementally—for example, by 10 percentage points per round. After each round, plot the relationship between:

    • Pruning ratio.
    • Quality metrics.
    • GPU memory usage.

    A clear inflection point in these curves often indicates the practical pruning limit.

    Avoid pruning directly to the target ratio in a single step. After a large one-time reduction, it is harder to identify which removals caused quality degradation.

    3.4 Fine-Tune and Run Regression Tests

    After pruning, lightweight fine-tuning with a small amount of high-quality instruction data—for example, using LoRA—can help recover from distribution shifts caused by missing experts. The fine-tuning data should match your application’s tasks.

    Regression testing must cover the target workload, including long inputs, multi-turn conversations, and output-format constraints. Strong scores on general-purpose benchmarks alone do not establish that application quality has been preserved.

    4. Speculative Decoding and Draft Model Selection

    4.1 How Speculative Decoding Works

    In conventional autoregressive decoding, generating each token requires a forward pass through the large model.

    Speculative decoding changes this process. A smaller draft model first proposes k candidate tokens. The target model then evaluates those k positions in a single parallel forward pass.

    For sampling-based decoding, acceptance follows these rules:

    1. Let q be the probability assigned to a candidate token by the draft model, and p the probability assigned by the target model.
    2. If p ≥ q, accept the token.
    3. If p < q, accept it with probability p/q.
    4. At the first rejection, sample a correction token from the normalized residual distribution proportional to max(0, p − q), where the subtraction is applied across the token distributions. Then end the current proposal round.
    5. If all k candidates are accepted, sample one additional token from the target model.

    These rules preserve the output distribution of direct sampling from the target model.

    For greedy decoding, verification is simpler: accept a candidate if it matches the target model’s argmax token at that position. Otherwise, reject it and use the target model’s argmax as the correction token.

    4.2 How to Choose a Draft Model

    Two measurements matter most:

    • Acceptance rate: How closely the draft model’s proposals align with the target model.
    • Per-step overhead: How much computation the draft model adds.

    Both must be measured on the intended workload.

    Use the following selection criteria:

    • Prefer a shared vocabulary and similar training distribution. A smaller model with the same vocabulary as the target model and a similar training-data distribution will generally offer better acceptance rates.
    • Include the draft model in the memory budget. Count both its weights and its KV cache, not just the target model’s memory.
    • Measure acceptance on application data. Random text is not a substitute for real workloads. Acceptance rates can differ substantially across code generation, structured output, and long-document tasks.
    • Apply consistent sampling settings. Use the same settings, such as temperature, for both models to avoid unnecessarily reducing acceptance rates.

    For a rough estimate, assume that acceptance events are independent and that every position has approximately the same acceptance probability, α. The expected number of output tokens per round is then:

    1. Expected tokens per round ≈ (1 − α^(k+1)) / (1 − α)

    As α approaches 1, this value approaches k + 1.

    This approximation ignores correlations between positions. It is useful for rough planning, but measured speedup should determine the final decision.

    Draft model overhead also affects the result. If one draft-model step takes c times as long as one target-model step, the approximate speedup is:

    1. Speedup ≈ Expected tokens per round / (k × c + 1)

    A smaller draft model reduces per-step overhead, but it may also lower acceptance rates. Evaluate the two together rather than optimizing either in isolation.

    4.3 Illustrative Implementation Fragment

    The following fragment introduces a simplified speculative decoding function. Its interfaces are hypothetical, and the fragment is incomplete, so it cannot be run as provided. A production implementation also needs to handle batched requests, KV cache reuse, and random-number management.

    1. import random
    2. def speculative_decode(target, draft, prompt_ids, max_new_tokens,
    3. k=4, temperature=1.0):
    4. ids = list(prompt_ids)
    5. limit = len(prompt_ids) + max_new_tokens
    6. while len(