LLM Inference Cost Reduction: Combining Expert Pruning and Speculative Decoding
As large language models (LLMs), particularly Mixture of Experts (MoE) architectures, scale to trillions of parameters, inference costs remain a major hurdle for enterprise deployment. This article explores a two-step approach to reducing these costs: compressing model memory footprint via expert pruning and leveraging the freed VRAM to accelerate generation using speculative decoding. It covers practical implementation details, code logic, an acceptance rate troubleshooting checklist, and standardized metrics for evaluating cost comparisons to help teams optimize LLM deployment efficiently.
1. Why Inference Costs Remain High
Open-weight large language models are growing increasingly large, with some Mixture of Experts (MoE) models reaching the trillion-parameter level. More parameters mean more VRAM is required during inference, which in turn demands more high-end accelerators. Consequently, hardware procurement and cloud rental fees have become primary expenses for enterprises deploying large models.
The core question enterprises care about is: Can we switch to a lower tier of hardware while keeping accuracy loss within an acceptable range for the business? To address this, the industry has explored several cost-reduction practices. Some cases claim that hardware procurement and cloud rental costs can each be reduced by about 20%. However, such figures often lack public testing environments, GPU types, batch sizes, and billing durations. Without these specific metrics, they can only serve as directional references, not direct expectations for your own project.
Cost reduction typically follows two steps. The first step is to compress the VRAM occupied by the model, and the second is to use the freed VRAM to increase speed. The following two sections detail these steps.
2. Step 1: Expert Pruning for MoE Models
In MoE models, each forward pass activates only a subset of expert subnetworks, but all expert weights must remain resident in VRAM. Different experts vary significantly in their importance to a given task, which creates room for pruning.
Pruning can be carried out in three steps:
- Importance Evaluation: Using the expert subnetwork as the minimum unit, collect statistics on activation frequency, output contribution, and gradient sensitivity on a representative corpus. The corpus should cover the main task types of the target business, and its size should be determined through experimentation.
- Selective Removal: Remove experts in batches from lowest to highest importance. After each batch, check the load distribution of the routing (gating) network to ensure the remaining experts share a roughly balanced load, preventing a few experts from handling too many requests.
- Precision Recovery: If necessary, perform lightweight fine-tuning with a small amount of calibration data to fix distribution shifts caused by pruning.
Some reports have highlighted a relatively large pruning ratio, claiming the compressed model retained most of its original score on a highly complex scientific reasoning benchmark. However, these reports often omit the benchmark name and evaluation settings. Therefore, this result merely proves redundancy exists in certain experts; it does not mean all tasks can be compressed losslessly. The exact pruning ratio and accuracy loss must be tested empirically on your own business data.
Pruning ratios should be tiered. It is common practice to prepare multiple compressed versions corresponding to different requirements for accuracy, cost, and context length. The freed VRAM can be used to expand the KV cache, thereby supporting longer inputs. However, the usable context length is still limited by two conditions: the model’s training context length and its positional encoding scheme. Ultra-long windows mentioned in some reports must be tested on the target model before confirmation; they cannot be assumed usable simply because pruning was applied.
3. Step 2: Using Speculative Decoding to Convert VRAM to Speed
The VRAM saved by pruning should not sit idle. One approach is to load a small draft model to work alongside the main model using Speculative Decoding.
The basic process of speculative decoding is as follows:
- The draft model quickly proposes the next k candidate tokens.
- The main model performs one forward pass, simultaneously providing the probability distribution for these k positions.
- Each candidate token is accepted or rejected based on the ratio of the main model’s probability to the draft model’s probability. If rejected, a token is resampled from the corrected distribution, and the current round ends.
In sampling mode, this rule guarantees that the output distribution matches that of the main model generating alone. The pseudocode below illustrates the accept/reject logic. Compared to the standard version, it includes safeguards for when q is 0, probability handling after temperature scaling, a greedy decoding branch, end-of-sequence conditions, and random source management.
import randomdef speculative_generate(draft_model, target_model, prompt, k=4,temperature=1.0, max_new_tokens=256,eos_id=None, seed=None):rng = random.Random(seed) # Independent random source for issue reproductiontokens = tokenize(prompt) # Draft and target models must use the same vocabularystart = len(tokens)# Stop condition: reached max generation length or generated EOSwhile len(tokens) - start < max_new_tokens:# 1. Draft model autoregressively proposes k candidates and records each candidate's probability q under the draft distribution# Probabilities are scaled by temperature and normalizedcandidates, q_probs = draft_model.propose(tokens, k, temperature)# 2. Target model does one forward pass, gets probabilities p for k candidate positions and the final position# Also scaled by temperature and normalizedp_probs = target_model.score(tokens, candidates, temperature)accepted = []for i, x in enumerate(candidates):p, q = p_probs[i][x], q_probs[i][x]if temperature == 0:# Greedy decoding: accept only if candidate matches target model argmax, no random branchok = (x == argmax(p_probs[i]))else:# 3. Accept with probability min(1, p/q). Reject directly if q is 0 to avoid division by zerook = q > 0 and rng.random() < min(1.0, p / q)if ok:accepted.append(x)else:# 4. On rejection: greedy takes target argmax; sampling resamples from normalized max(0, p - q)if temperature == 0:accepted.append(argmax(p_probs[i]))else:residual = clip_nonnegative(p_probs[i] - q_probs[i])# Theoretically, rejection probability is 0 when p and q are identical; the sum here will not be 0accepted.append(sample(normalize(residual), rng))break # Current round endselse:# 5. If all accepted: sample an extra token from the target model's final position distributionif temperature == 0:accepted.append(argmax(p_probs[k]))else:accepted.append(sample(p_probs[k], rng))tokens.extend(accepted)if eos_id is not None and eos_id in accepted:tokens = truncate_at_eos(tokens, eos_id)breakreturn detokenize(tokens)
When implementing this, pay attention to the following points:
- The vocabularies of the draft model and the main model must be perfectly identical; otherwise, probabilities cannot be aligned position by position.
- In greedy decoding (temperature = 0), the rule simplifies to an argmax comparison. This branch should not call the random number generator.
- The random seed for sampling must be managed separately to facilitate issue reproduction.
- The probabilities p and q must be the results of temperature scaling and normalization, and must be non-negative. Otherwise, their ratio loses meaning.
- Some sources claim that 8 mid-range accelerators can achieve generation speeds close to a high-end GPU configuration. This conclusion only holds under specific conditions. GPU type, batch size, input/output length, draft model size, and acceptance rate all influence the result. Without this context, readers cannot judge whether it applies to their own scenarios.
4. Acceptance Rate Troubleshooting Checklist
If the acceptance rate is too low, speculative decoding will actually slow down inference because the overhead of the draft model yields no returns. When troubleshooting, check the following items in order:
- Vocabulary & Tokenizer: Ensure the draft and main models use the same tokenizer and vocabulary. Action: Compare the vocab sizes and encoding results of several sample texts from both.
- Temperature & Sampling Params: Ensure both models use the same temperature, top-p, and top-k. Action: Print the sampling configs for both sides and compare them on the same set of prompts.
- Candidate Length k: A larger k increases the probability that later candidates will be rejected, lowering the average accepted length. Action: Test acceptance rates and end-to-end speeds for k = 2, 4, and 8, and select the value with the highest throughput.
- Target Model Score Position Alignment: A common error is a one-position offset. Action: Generate a short text step-by-step directly with the main model and compare it with the score output probabilities to confirm that the i-th position corresponds to the conditional distribution of the i-th candidate.
- Draft Model Capability & Distribution Difference: If the gap between the draft and main models is too large, the distribution deviation will lower the acceptance rate. Action: Choose a draft model from the same series or distilled from the same training data, and compare draft models of different sizes.
- Batch Size & Padding: Batch size changes alter the computation path and padding method, which can skew acceptance rate statistics. Action: Fix the batch size before comparing, and ensure padding positions are excluded from probability calculations.
- Context Length & KV Cache: As context lengthens, the main model’s forward pass overhead increases, diluting the benefits of the draft model. Action: Group statistics for acceptance rate and speed by input length.
- Random Seed: In sampling mode, unfixed seeds lead to varying results, making it difficult to determine if an optimization is effective. Action: Fix the seed and run three or more times to observe statistical fluctuation.
- Stress Testing Criteria: The acceptance rate should be uniformly defined as “number of accepted candidate tokens / number of proposed candidate tokens.” Action: Use the same batch of prompts, warm up first, and then calculate the mean and percentiles.
5. How to Evaluate Cost Comparisons
The most error-prone aspect of cost comparisons is inconsistent metrics. Two sets of numbers are only comparable if the following conditions are identical: same GPU type, same batch size, same input/output length, same acceptance rate, and same precision regression standard. Missing any of these means the comparison cannot be directly used for decision-making.
It is recommended to record your own test results using the template below. The data in the table must come from your own stress tests; do not directly apply numbers published by others.
| Solution | GPU Spec | Num of GPUs | Batch Size | I/O Length | Acceptance Rate | Precision Regression | Relative Procurement Cost | Relative Rental Cost | Measurement Criteria |
|---|---|---|---|---|---|---|---|---|---|
| Baseline: Original Model | TBD | TBD | TBD | TBD | N/A | TBD | 1.00 (Base) | 1.00 (Base) | TBD |
| Plan A: Pruned Version | TBD | TBD | TBD | TBD | N/A | TBD | TBD | TBD | TBD |
| Plan B: Pruned + Speculative Decoding | TBD | TBD | TBD | TBD | TBD | TBD | TBD | TBD | TBD |
When reading the table, keep three things in mind. First, relative costs should be calculated based on the actual cost per 1,000 tokens or the cost per unit of throughput, not just the number of GPUs. Second, precision regression results should be evaluated alongside business metrics; a score on a single benchmark cannot represent all tasks. Third, rental costs should be calculated based on actual billing duration, including warm-up, queuing, and idle time.
6. Pre-Deployment Checklist
Before pushing the solution to production, it is recommended to complete three tasks:
First, perform a precision regression test using samples of real business requests, covering main task types and long-input scenarios.
Second, conduct a stress test on the target hardware for at least one complete business cycle, recording acceptance rates, latency percentiles, and throughput.
Third, retain the original model as a fallback path. If the pruned or speculative decoding version exhibits anomalies, you can quickly switch back.
Ultimately, the benefits of cost reduction depend on the numbers from your own business. The processes and checklists provided in this article aim to help readers establish a reproducible measurement methodology, rather than offering a universally applicable conclusion.
