LLM Inference Cost Reduction in Practice: Combining Expert Pruning and Speculative Decoding
This article explains how inference cost depends on model size, KV cache, and hardware choice, and how to measure it as cost per million output tokens. It then compares three approaches: pruning mixture-of-experts modules, speculative decoding, and accelerator selection. It also covers quality evaluation, a phased rollout plan, and how to troubleshoot common problems.
1. Background: What Determines Inference Cost
Inference cost does not depend on a single factor. Larger models need more memory for their weights. During inference, the KV cache (Key-Value Cache) also grows with context length and the number of concurrent requests. Memory requirements determine how many accelerator cards a model needs and what specification each card must have. The card count and specification then directly set the cost of purchasing hardware or renting it from a cloud provider.
Cost reduction therefore has two directions. One is to reduce the hardware resources needed for each inference. The other is to increase the useful output of each unit of hardware.
1.1 Measuring Efficiency with Cost per Million Tokens
Before discussing optimization options, a team should agree on a single cost metric. A commonly used metric is the cost per million output tokens, calculated as follows:
Cost per million tokens = GPU hourly price × number of GPUs ÷ output tokens per hour × 1,000,000
The code below shows an example calculation. The price and throughput values are hypothetical. They only illustrate the method and do not represent any real environment.
def cost_per_million_tokens(gpu_hour_price: float,num_gpus: int,tokens_per_second: float) -> float:"""Calculate the inference cost per million output tokens (hypothetical example)."""if tokens_per_second <= 0:raise ValueError("tokens_per_second must be greater than 0")hourly_tokens = tokens_per_second * 3600hourly_cost = gpu_hour_price * num_gpusreturn hourly_cost / hourly_tokens * 1_000_000# Assumption: each GPU costs 10 currency units per hour, 8 GPUs, 500 output tokens per secondprint(round(cost_per_million_tokens(10, 8, 500), 2))
This formula points to three optimization directions. First, lower the unit price by using cheaper hardware. Second, reduce the number of GPUs by fitting the model onto fewer cards. Third, raise throughput by generating more tokens on the same hardware. These three paths can be used alone or combined.
1.2 Relationship Between Memory and Accelerator Selection
Memory capacity determines which accelerator cards are possible options. If the model weights plus the KV cache exceed the memory of one card, the model must run on multiple cards in parallel. If compressing the model or managing the cache reduces the total footprint below a certain threshold, the team can switch to a cheaper card with slightly less memory or reduce the number of parallel cards.
The key point is that the goal is to meet a memory threshold, not simply to make the model smaller. Once quality targets are met, the freed memory can support higher concurrency, longer context, or auxiliary inference components.
2. Path 1: Expert Module Pruning
A mixture-of-experts (MoE) model contains multiple expert sub-networks in each layer. A router selects a few experts to process each token. These models have a large total parameter count, but a single inference activates only part of the parameters.
However, the weights of all experts must stay in memory, so the total parameter count still determines memory usage. Expert pruning identifies experts that contribute little to the target task and removes them to reduce the size of the weights.
2.1 Evaluating Expert Contribution
Before pruning, the team needs to assess the value of each expert. Common methods include measuring activation frequency and measuring the loss in quality after removal.
- Activation frequency: On a representative dataset, measure how often the router selects each expert. Experts that are rarely selected over time carry a lower risk when removed.
- Quality impact: Remove experts one at a time or in groups, then compare output quality on an evaluation set.
- Task coverage: Check whether a removed expert handles a specific type of task. Some experts may only work in niche domains, specific languages, or long-tail scenarios. Looking only at the overall average score can miss this kind of degradation.
The following example shows how to measure the expert activation distribution.
import numpy as npdef expert_usage_ratio(router_logits: np.ndarray, top_k: int = 2) -> np.ndarray:"""Calculate the proportion of tokens routed to each expert.router_logits: routing score matrix with shape [number of tokens, number of experts]"""topk_idx = np.argsort(-router_logits, axis=1)[:, :top_k]counts = np.bincount(topk_idx.flatten(), minlength=router_logits.shape[1])return counts / counts.sum()# Example: randomly generated routing scores, for demonstration onlyrng = np.random.default_rng(0)logits = rng.normal(size=(10000, 16))ratio = expert_usage_ratio(logits, top_k=2)candidates = np.argsort(ratio)[:4] # Use the 4 experts with the lowest activation ratios as candidatesprint("Candidate experts for pruning:", candidates.tolist())
2.2 Pruning Implementation Steps
Pruning should be iterative, not a single deletion. The recommended process is as follows:
- Prepare an evaluation set that covers the business scenarios, including core tasks, edge tasks, and difficult samples.
- Measure the expert activation distribution and list the candidate experts.
- Remove only a small batch of experts at a time, then rerun the evaluation.
- If a core metric drops beyond the preset threshold, roll back that batch and remove other candidates instead.
- Repeat these steps until the target size is reached or the quality loss becomes unacceptable.
- Run regression tests on the final model, then perform a canary validation before release.
2.3 Main Risks of Pruning
Pruning changes the routing decisions of the router. Tokens that were sent to a removed expert are reassigned to other experts. This can increase the load on those experts and disrupt the original division of labor. After pruning, the team should usually check load balancing and, if needed, make small calibration adjustments to the router.
Another risk is long-tail degradation. Overall metrics may remain stable while performance drops noticeably for specific languages, code formats, or technical terms. The team should break down evaluation results by task type instead of relying only on the composite score.
3. Path 2: Speculative Decoding
Autoregressive generation outputs one token at a time, and each step requires a full forward pass of the large model. Speculative decoding (Speculative Decoding) adds a smaller draft model that proposes several candidate tokens in advance. The large target model then verifies all candidates in parallel. Accepted tokens are output directly. For rejected positions, the target model generates replacement tokens.
3.1 How It Works
The process can be summarized in the following steps:
- Based on the current context, the draft model proposes k candidate tokens in sequence.
- The target model computes the probability distributions for those k positions in parallel.
- The candidates are checked one by one against the verification rule. Tokens that match the target model’s output, or that meet the acceptance condition, are accepted.
- At the first rejected position, the target model samples a replacement token from its distribution. The next round then starts from that position.
This method does not change the probability distribution of the final output. In theory, its output is equivalent to generating directly with the target model. The speedup comes from replacing several sequential target-model computations with fewer verification computations.
3.2 Factors That Determine the Speedup
The acceleration from speculative decoding depends mainly on three factors.
- Acceptance rate: The closer the draft model’s proposals are to the target model’s outputs, the more tokens are accepted in each round.
- Draft overhead: The shorter the draft model’s computation time, the greater the benefit. An oversized draft model can cancel out the speedup.
- Task characteristics: Code, templated text, and structured output are usually easier to predict and have higher acceptance rates. Open-ended creative writing and high-temperature sampling often lower the acceptance rate.
The following pseudocode illustrates the core loop.
def speculative_decode(draft_model, target_model, prompt, k=4, max_new_tokens=256):"""Simplified illustration of speculative decoding. Probability comparison details are omitted."""tokens = list(prompt)generated = 0while generated < max_new_tokens:# 1. The draft model proposes k candidate tokenscandidates = draft_model.propose(tokens, k)# 2. The target model verifies all candidate positions at onceverified = target_model.verify(tokens, candidates)# verified is the accepted prefix. If every candidate is rejected, it includes one replacement token.tokens.extend(verified)generated += len(verified)return tokens
3.3 Relationship with Memory
Speculative decoding requires loading an additional draft model, which uses some memory. If earlier pruning or quantization frees enough space, that extra usage can be offset. This is the basis for the combined strategy of reducing memory first and then using the saved space to accelerate inference.
The KV cache also uses memory, and its size grows as the context gets longer. The longer the context, the more likely the memory saved by pruning will be consumed by the cache. When planning for long-context scenarios, the team should calculate both the weight footprint and the cache footprint.
4. Path 3: Accelerator Specification Selection
Specification selection has the most direct effect on cost. The team should first calculate the memory required by the model at the target context length and concurrency level. Then it should choose the lowest-cost option among the candidate specifications that meet this requirement.
4.1 Estimating the Memory Budget
A rough memory estimate can be divided into three parts:
- Model weights: The parameter count multiplied by the bytes stored per parameter. For example, a 16-bit floating-point number takes 2 bytes.
- KV cache: Depends on the number of layers, the attention head configuration, the context length, and the number of concurrent requests.
- Runtime overhead: Includes activation values, communication buffers, and the memory used by the framework itself.
In production, it is advisable to reserve some headroom to avoid running out of memory during traffic peaks.
def estimate_weight_memory_gb(num_params_billion: float, bytes_per_param: float) -> float:"""Estimate the memory required for model weights in GB. Excludes the KV cache and runtime overhead."""return num_params_billion * 1e9 * bytes_per_param / (1024 ** 3)# Example: a model with 100 billion parameters, stored with 2 bytes and 1 byte per parameterprint(round(estimate_weight_memory_gb(100, 2), 1))print(round(estimate_weight_memory_gb(100, 1), 1))
4.2 Decision Logic for Selection
Use the following order when choosing a specification:
- Determine the target context length and maximum concurrency, then calculate the total memory requirement.
- List the available accelerator specifications, and record each card’s memory, unit price, interconnect bandwidth, and available quantity.
- Remove options with insufficient memory.
- Among the remaining options, compare cost per token and latency.
- Decide on the final option based on supply stability and the difficulty of scaling out.
Newer specifications are not always better. When memory is the constraint, a lower-tier card with enough memory can be more economical than a higher-tier card. Conversely, if compute throughput rather than memory is the bottleneck, simply switching to a lower-tier card can push latency beyond acceptable limits.
5. Quality Evaluation Framework
Any cost reduction plan must keep quality above a minimum level. The evaluation framework should cover three types of metrics.
| Category | Example Metrics | Description |
|---|---|---|
| Quality | Core task accuracy, scores by task type, manual review pass rate | Checks whether the optimized model keeps its business capabilities |
| Performance | Time to first token, average generation speed, P99 latency | Measures user experience and service capacity |
| Cost | Cost per million tokens, cost per request, GPU utilization | Shows whether the optimization actually lowers spending |
5.1 Setting Acceptance Thresholds
Business stakeholders and the technical team should set thresholds together. For example, the team could require the core task score to stay above a set percentage of the baseline, while also requiring the cost per token to fall by the expected amount. Once set, thresholds should be hard conditions for release. Changing the standard after seeing the results should be avoided.
5.2 Regression Testing and Canary Release
Before an optimized model goes live, it should pass a full regression test. The test set should include samples from past production issues to prevent old problems from returning. For release, use a canary deployment. Send a small share of traffic to the new model first, then compare error rates, user feedback, and cost data. Increase the share gradually after the model proves stable.
6. Phased Implementation Roadmap
Combining the three paths above, a team can proceed through the following phases.
- Establish a baseline: Record the current model’s quality, performance, and cost data. Build a unified evaluation set and monitoring dashboard.
- Analyze memory: Determine whether memory, compute, or communication is the bottleneck. Estimate resource needs at different context lengths.
- Validate individually: Test quantization, expert pruning, and speculative decoding separately. Record the quality loss and benefit of each.
- Optimize in combination: Based on the individual results, choose the combination that offers the greatest benefit with manageable risk.
- Switch specifications: Run load tests of the optimized model on candidate accelerator specifications to find the lowest-cost configuration.
- Roll out and monitor: Increase traffic gradually, keep tracking quality and cost metrics, and maintain a fast rollback plan.
Each phase should have clear deliverables. For example, the baseline phase should produce a performance report, the memory analysis phase should produce a resource requirements table, and the rollout phase should produce a comparison report. These deliverables support decisions and make later reviews easier.
7. Common Problems and Solutions
Problem 1: Users report lower quality after cost reduction. First, check whether the evaluation set covers the scenarios that users actually encounter. If the evaluation set has gaps, add more samples. Next, break down the comparison results by task type to locate the categories where quality drops. Then decide whether to adjust the pruning scope or keep more experts.
Problem 2: Speculative decoding does not deliver the expected speedup. First, measure the acceptance rate. If the rate is low, try a draft model that is closer to the target model, or adjust the proposal length k. If the draft model itself takes too long, the team should choose
