Reducing MoE Inference Costs: Expert Pruning and Speculative Decoding in Practice
This article explains how to cut inference costs for Mixture-of-Experts (MoE) large language models using expert pruning and speculative decoding. It covers GPU memory budgeting, calibration-based pruning steps, quality gates, draft model options, acceptance rate measurement, and how to compare costs with your own benchmark results.
1. Where Inference Costs Come From
When you deploy a large model, GPU memory is used mainly by three things: model weights, activations and the KV cache, and runtime overhead from the inference framework. Larger models have larger weights. During inference, the KV cache grows linearly with sequence length and the number of concurrent requests. In long-context workloads, it can exceed the memory taken by the weights.
A Mixture-of-Experts (MoE) model has a very large total parameter count, but each token activates only a few experts. As a result, compute does not scale with total weight memory. All expert parameters must still fit in GPU memory, which is why compression and memory planning are worth the effort.
2. Plan the Memory Budget Before Deployment
Before you compress a model, estimate how much GPU memory your target configuration needs. A common formula for the KV cache is:
KV cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × number of concurrent requests × bytes per element
The factor of 2 accounts for the Key and the Value. With bf16, each element takes 2 bytes. When you use grouped-query attention (GQA), the number of KV heads is much smaller than the number of query heads, so the cache is noticeably smaller. Use the number of KV heads in this estimate, not the number of query heads.
| Item | Estimation method | Inputs to confirm |
|---|---|---|
| Model weights | Parameter count × bytes per parameter | Precision (bf16, int8, int4) |
| KV cache | Use the formula above | Maximum context length, number of concurrent requests, number of KV heads |
| Activations and temporary buffers | Measure under real batch size and sequence length | Batch size, inference framework |
| Runtime overhead | Measure | Inference framework, communication library |
Reserve some memory headroom for peak request loads, so you avoid out-of-memory (OOM) errors. No standard headroom ratio exists. Set it based on the peak memory your framework uses under your target workload, as measured in testing.
3. The Basic Expert Pruning Workflow
3.1 Build a Calibration Dataset
A calibration dataset shows how experts are used. It usually contains several thousand to tens of thousands of samples. The samples should reflect the real requests your service receives, and you should sample evenly across task types, languages, and input lengths. For each token, record which experts it is routed to at every layer. Then compute each expert’s hit frequency f_i and the average gate weight g_i.
3.2 Calculate an Expert Importance Score
One workable approach is a weighted sum of three metrics:
S_i = a · f_i + b · g_i + c · Δ_i
Here, Δ_i is the average increase in KL divergence between the output distribution of the pruned model and that of the original model on the calibration set, measured after removing expert i. Normalize all three metrics to the range 0 to 1. Tune the coefficients a, b, and c on a validation set. No universal values exist for these coefficients. Use your business evaluation results to set them.
3.3 Layer-by-Layer Pruning with Minimum Retention
Set a retention ratio for each layer instead of ranking all experts globally. A global ranking can remove every expert from some layers, which breaks that layer’s function. Set a minimum number of experts to keep in each layer. Prune in multiple rounds, and keep each round’s removal ratio small. Evaluate after each round before deciding whether to continue. This makes it possible to roll back to the previous level.
3.4 Adjust the Router
After you remove experts, reduce the router’s output dimension to match and delete the routing weights for those experts. Renormalize the routing weights of the remaining experts. If top-k is larger than the number of experts left in a layer, reduce k to match. Pruning can leave expert load unbalanced. To correct this, iteratively adjust the router’s bias terms on the calibration set so that expert hit rates become more even.
3.5 Recover Quality with Light Fine-Tuning
Pruning changes the model structure, so some capabilities may degrade. A common fix is light fine-tuning on tens of thousands of high-quality instruction samples. Use a learning rate about one order of magnitude lower than the pretraining rate, and train for one to three epochs. During training, monitor validation loss and the coefficient of variation of expert load, so the load does not become unbalanced again.
3.6 Quality Gates
A pruned model must pass both general benchmarks and your own business evaluation set. Define the gate thresholds in advance. For example, you could require that core business metrics drop by no more than 1 percentage point compared with the original model. For long-tail tasks, you could rely on manual spot checks. These thresholds are only examples. Each team should set them based on how much quality loss its business can tolerate.
4. Choosing the Pruning Ratio
Some public materials report figures such as “about 30% reduction” or “about 37% reduction.” These materials do not describe the baseline, hardware setup, or measurement conditions. You cannot use these figures for planning. Measure the results yourself.
4.1 How to Choose Between a 30% and a 37% Reduction
When you choose a pruning level, consider three things in order: your target context length, the headroom your quality gates allow, and what you plan to use the freed memory for. First, use the quality gates to remove levels that fail. Next, compare how much memory each remaining level frees. Finally, decide based on your business needs.
| Pruning ratio | Change in weight memory | Quality change | Suitable scenario |
|---|---|---|---|
| 0% (baseline) | Baseline | Baseline | Quality first, ample memory |
| About 30% (example level) | Fill in measured value | Fill in evaluation result | Moderate concurrency, medium to long context |
| About 37% (example level) | Fill in measured value | Fill in evaluation result | More memory needed for the KV cache |
4.2 Does Freed Memory Always Lengthen the Context?
No. Freed memory only supports a longer context if it becomes KV cache capacity. Other techniques must support this conversion, such as KV cache quantization, paged cache management, and models that use GQA. Longer contexts also increase attention compute, and generation quality on long inputs can drop. Therefore, evaluate separately at your target context length. A common approach is to use retrieval and long-document comprehension benchmarks.
4.3 What to Do If Longer Contexts Reduce Quality
Try three adjustments in this order. First, lower the maximum context length. Second, adjust your retrieval chunking or summarization strategy to remove unnecessary long inputs. Third, roll back to a pruning level with higher quality. After each change, rerun the quality gate evaluation, and record the changes in memory use and quality.
5. Using Freed Memory for a Draft Model
5.1 How Speculative Decoding Works
Traditional autoregressive generation produces one token per step. Each step reads the full main model weights, so memory bandwidth often becomes the bottleneck. Speculative decoding works differently. A small draft model proposes k candidate tokens at once. The main model then verifies all k positions in a single forward pass.
The verification rule works as follows. For each candidate token, let p_main be the main model’s probability and p_draft be the draft model’s probability. Accept the token with probability min(1, p_main / p_draft). When a token is rejected, sample a new token from the corrected distribution norm(max(0, p_main − p_draft)) and end the round. If all k candidates are accepted, draw one extra token from the main model’s distribution at the next position. This rule keeps the final output distribution identical to what sampling from the main model alone would produce.
If the acceptance rate for each token is α, and each round proposes k candidate tokens, the average number of tokens generated per round is:
E = (1 − α^(k+1)) / (1 − α)
For example, if the acceptance rate is always 0.8 and k is 4, each round generates about 3.36 tokens on average. This value comes from the math alone and is only an illustration. The real acceptance rate changes with the input content. The speedup also depends on how much compute the draft model uses. A slower draft model gives smaller gains.
The draft model and the main model must use the same tokenizer and vocabulary. Otherwise, you cannot compare their probabilities token by token.
5.2 Three Sources of Draft Models
| Source | Expected acceptance rate | Extra memory | Extra cost | Notes |
|---|---|---|---|---|
| A substructure pruned from the main model | Usually higher, must be measured | Lower, because it shares part of the main model’s structure | Requires pruning and fine-tuning | The substructure does not match the main model exactly, so validate it on the calibration set |
| A small model from distillation | Depends on distillation data and training quality | Smaller | Requires distillation training | Training data must cover the distribution of real requests |
| An independently trained small model | Usually lower | Smaller | Lower training cost | Must use the same vocabulary as the main model |
A pruned or distilled model does not automatically match the main model’s distribution. Measure the acceptance rate on your own business data. Do not assume anything based on where the model came from.
5.3 Pseudocode
The pseudocode below shows the core loop of speculative decoding. It illustrates the logic only and is not ready for production use.
import numpy as npdef speculative_decode(main_model, draft_model, prompt_ids,max_new_tokens, k=4):tokens = list(prompt_ids)target_len = len(prompt_ids) + max_new_tokenswhile len(tokens) < target_len:# The draft length in this round must not exceed the remaining token budgetn_draft = min(k, target_len - len(tokens))# 1. The draft model proposes n_draft candidate tokens autoregressively and returns the probability distribution at each stepdraft_tokens, draft_probs = draft_model.generate(tokens, n_draft)# 2. The main model runs one forward pass and returns distributions for n_draft + 1 positionsmain_probs = main_model.next_token_probs(tokens, draft_tokens)# 3. Accept tokens one by one. On the first rejection, sample a corrected token and end the roundn_accepted, extra_token = verify_and_correct(draft_tokens, draft_probs, main_probs)tokens.extend(draft_tokens[:n_accepted])tokens.append(extra_token)# 4. Record acceptance statistics for online monitoringstats.record(proposed=n_draft, accepted=n_accepted)# The last round may generate extra tokens, so truncate to the target lengthreturn tokens[:target_len]def verify_and_correct(draft_tokens, draft_probs, main_probs):for i, token in enumerate(draft_tokens):p_main = main_probs[i][token]p_draft = draft_probs[i][token]if np.random.random() < min(1.0, p_main / p_draft):continue# Rejected: sample a corrected token from the distribution max(0, p_main - p_draft), normalizedresidual = np.maximum(main_probs[i] - draft_probs[i], 0.0)total = residual.sum()if total <= 0:# If numerical issues make the residual zero, fall back to sampling from the main model distributionresidual = main_probs[i]total = residual.sum()return i, sample(residual / total)# All candidates accepted: sample an extra token from the main model's distribution at the last positionreturn len(draft_tokens), sample(main_probs[len(draft_tokens)])
Keep the following points in mind. First, verify_and_correct returns the accepted length and the corrected token, and the main loop uses them to update the sequence. Second, sampling a corrected token after a rejection keeps the output distribution consistent with the main model. Third, the loop ends with truncation to handle the max_new_tokens boundary.
Production code needs more than this. It must handle the end-of-sequence (EOS) token and stop early when it appears. It also needs batching and concurrency scheduling, KV cache reuse so that each round does not recompute the full prefix, numerical stability handling, and random seed management. If you only need greedy decoding, you can simplify the acceptance check to comparing whether the argmax tokens of the two models match. The implementation becomes much simpler.
5.4 Draft Length and Monitoring
Tune the draft length k. When the acceptance rate is high, you can increase k. When the draft model is slow, reduce k. In production, monitor these metrics continuously: the ratio of accepted tokens to proposed tokens per round, average latency per token, p50 and p99 latency, and acceptance rate broken down by request type. If the acceptance rate drops noticeably for some workloads, raise an alert and check whether the input distribution has drifted from the calibration set.
6. Cost Comparison: Use Measured Results Instead of Claimed Figures
The original material mentioned claims such as reducing GPUs from 8 to 4, a purchase cost reduction of about 20%, and a rental cost reduction of about 22%. These figures came without sources or test conditions, so this article does not use them. Record your own test results with the template below, then calculate costs from those results.
| Metric | Before optimization | After optimization | Test conditions |
|---|---|---|---|
| GPUs per instance | Measured value | Measured value | Precision, maximum context length |
| GPU model and memory | Fill in | Fill in | From a purchase quote or a cloud provider’s price list |
| Memory used per instance | Measured value | Measured value | Concurrency, sequence length |
| Output tokens per second | Measured value | Measured value | Batch size, acceptance rate |
| Cost per token | Calculated value | Calculated value | Unit price and throughput |
Use this formula to calculate the cost per token:
Cost per token = hourly cost per instance ÷ (output tokens per second × 3600)
Include the extra memory and compute that the draft model uses in your calculation. Purchased hardware also requires depreciation and operating costs. For rented capacity, use the billing rate and the actual running time.
7. Deployment Checklist
- Memory estimate: Estimate weights, KV cache, and runtime overhead separately, and keep headroom
- Calibration dataset: Cover the real request distribution, and record the sample count and stratification method
- Pruning levels: Test at least two ratios, and record quality and memory results
- Quality gates: Use both general benchmarks and business evaluation, and set thresholds in advance
- Long-context evaluation: Validate separately at the target context length
- Draft model: Confirm the vocabulary matches, and measure the acceptance rate offline and online
- Acceptance rate monitoring: Track by time period and request type, and set alert thresholds
- Canary release and rollback: Launch with a small share of traffic, and keep the original model deployment for fast rollback
8. Conclusion
Whether pruning and speculative decoding lower your costs depends on your workload, your quality gates, and your measured throughput. The steps and decision criteria in this article can guide your planning. The actual gains, however, can only be confirmed by testing on your target workload.
