Reducing LLM Inference Costs: Expert Pruning, Speculative Decoding, and Memory Planning for MoE Models

    This guide walks through a five-step workflow for cutting the serving cost of MoE (Mixture-of-Experts) models: establishing a unified cost baseline, evaluating and executing expert pruning, selecting a draft model and k value for speculative decoding, planning KV cache memory and concurrency, and running retest matrices with rollback procedures. Each section provides executable steps, quantitative decision criteria, and default starting thresholds that teams should calibrate in their own environments. All numbers in this article are hypothetical starting points, not universal recommendations.

    For MoE models, resident GPU memory is usually the first constraint. All expert weights must fit in memory because the router may select any expert at any step, so reducing resident weights and improving per-GPU utilization are the shared goals of most cost-reduction work. This article proceeds in five parts, each with directly executable steps, decision criteria, and default starting points. All numbers are hypothetical values or starting points; teams must calibrate them in their own environment.

    1. Unify the Cost Baseline First

    Fix the measurement criteria before comparing any solutions. Otherwise, two sets of numbers may come from different batch sizes or input lengths, making the conclusions incomparable.

    Break costs into four items, each with required fields and a clear owner:

    Cost item Fields to collect Question it answers Suggested owner
    Resident memory Memory used by expert weights, non-expert weights, and framework overhead Minimum number of GPUs needed Inference platform team
    Concurrency limit KV cache usage, average and peak length per request, available concurrency How many requests can be processed simultaneously Inference platform team
    Latency Time to first token, per-token latency, P95 and P99 Whether pruning and speculative decoding meet the SLA Algorithm team
    Utilization GPU utilization, batch size distribution, idle time Whether the cost per token is too high Operations team

    Unify the cost metric as cost per million output tokens:

    Cost per million tokens = GPU hourly price ÷ (effective output throughput × 3600) × 1,000,000

    The effective output throughput is defined as follows. The numerator counts only output tokens: the total output tokens of requests completed within the measurement window. The denominator is the window duration in seconds. The window includes batching wait, queuing, and prefill time, so it reflects true end-to-end output. GPU price is calculated over the instance’s billed duration across the entire window. Input tokens are not counted separately in the numerator, but their prefill cost is already reflected in throughput, so throughput must be remeasured whenever the input length distribution changes. Network, storage, and operations labor are excluded from this metric and should be accounted for separately and noted in the report.

    Example: assume an instance costs 10 currency units per hour and the effective output throughput is 500 tokens/s; the cost per million output tokens is about 5.56. These numbers only demonstrate the formula.

    When citing external numbers, record the source, model version, framework version, GPU model, batch size, and input/output length distribution. Numbers lacking these conditions are only hypotheses to be verified and must not be used directly for capacity planning or budgeting.

    2. Expert Pruning: Evaluate First, Then Remove

    Pruning identifies experts that contribute little to the target workloads and removes or replaces them, reducing resident weights. The hard part is judging which experts are truly safe to delete. The table below gives quantitative fields, default starting points, and calibration methods for each step. The starting values are only for bootstrapping the evaluation; final thresholds must be determined by business metrics.

    Step Quantitative fields Default starting point Calibration method
    1. Activation frequency statistics Token share of each expert in each layer per scene group Global share below 0.5% and below 1% in every scene group → candidate Sample real production traffic; scene groups divided by language, code, long documents, and business type
    2. Task coverage evaluation Accuracy, refusal rate, and format error rate on core and long-tail tasks Core task drop no more than 1 percentage point; long-tail tasks have their own limits Retest with samples matching the online distribution; at least 1,000 requests per group
    3. Routing load check Token distribution across remaining experts, ratio of max load to mean, P99 latency, peak memory Load ratio no more than 1.5; P99 within SLA target Compare before/after pruning under identical batch and concurrency
    4. Recovery training decision Validation gap before/after pruning; samples and GPU hours needed for recovery training Only do light recovery training if the drop exceeds the threshold Include training cost in total cost before comparing
    5. Rollback preparation Checksum of original weights, pruning config version, switch-back time Able to switch back within an agreed time window Complete a switch-back drill before every release

    The starting values above come from common practice and are not guaranteed to apply to any particular model.

    Statistics must be grouped by scene. Low-frequency experts may serve only specific languages, code, or long documents; looking only at the global average will wrongly delete them. Each scene group’s statistics require at least 100,000 output tokens or 1,000 requests, whichever is larger. With insufficient samples, that group’s conclusion is excluded from the decision.

    Recommended log fields:

    • request_id, timestamp
    • layer_id, expert_id
    • scene_group
    • routed_tokens (number of tokens routed to that expert for this request)

    Example query for candidate experts (adjust table and field names to your own logging system):

    1. SELECT layer_id, expert_id, scene_group, SUM(routed_tokens) AS tokens
    2. FROM expert_routing_log
    3. WHERE log_date >= '2026-11-01'
    4. GROUP BY layer_id, expert_id, scene_group;

    After experts are removed, the remaining experts absorb their traffic. After load redistribution, some experts may exceed the mean in memory and compute pressure, and peak memory and P99 latency may worsen simultaneously. Step 3 therefore cannot be skipped: retest under the same batch and concurrency conditions as production.

    Secondhand sources often claim that “a certain proportion of experts can be removed with almost no score change.” Such claims usually omit the model version, test set, and statistical method, and cannot be used directly as a capacity-planning ratio. Rely on your own step 2 and step 3 results on your own model.

    3. Speculative Decoding: Draft Model and k Selection

    Autoregressive generation produces one token per step, and each step reads a large amount of weights. When memory bandwidth becomes the bottleneck, adding compute yields limited gains. Speculative decoding lets a draft model propose k candidate tokens, which the main model verifies in parallel with a single forward pass. Starting from the first candidate, the continuously verified prefix is accepted at once. At the first disagreement, the main model emits its own token at that position and all subsequent candidates are discarded.

    The draft model must meet these conditions:

    • It shares the same tokenizer and vocabulary as the main model; otherwise token-by-token verification is impossible.
    • Its memory footprint, added to the main model weights and KV cache, still fits within the GPU’s available memory.
    • Its per-step latency is significantly lower than the main model’s; otherwise the draft overhead cancels the gain.

    Template for the draft model parameter table (fill in measured values from the retest matrix):

    Candidate draft model Parameter size Vocabulary matches main model Precision Memory footprint Per-step latency as fraction of main model Acceptance rate α Notes
    Candidate A TBD Yes / No TBD TBD TBD TBD
    Candidate B TBD Yes / No TBD TBD TBD TBD

    The acceptance rate α is measured as: within a unified scene group, the number of candidate tokens accepted by the main model divided by the number of candidate tokens proposed by the draft. Measure it separately by scene group and batch size; do not take a single global average.

    The choice of k is based on the acceptance curve. Under ideal conditions, assuming each token’s acceptance probability is independent and equal to α, the expected number of tokens produced per step is:

    E = (1 − α^(k+1)) ÷ (1 − α)

    The speedup is approximately E ÷ (1 + k × c), where c is the ratio of the draft’s per-step time to the main model’s per-step time.

    Example (α = 0.8, k = 4, c = 0.1, all hypothetical): E = (1 − 0.8^5) ÷ 0.2 ≈ 3.36, speedup ≈ 3.36 ÷ 1.4 ≈ 2.4.

    Steps for selecting k:

    1. Measure α for k = 1 to 6, or directly measure the actual speedup at each k.
    2. Compute how the speedup changes with k and pick the k just before the marginal gain clearly shrinks.
    3. Repeat steps 1 and 2 by batch-size tier. As batch size grows, the main model’s memory-bandwidth bottleneck is amortized, speculative decoding’s gain usually drops, the optimal k may shrink, and speculative decoding may even need to be disabled.

    Speculative decoding interacts with pruning. Pruning changes the main model’s output distribution, reducing alignment between draft and main model, and the acceptance rate may drop noticeably. After pruning goes live, α must be remeasured and the before/after speedups compared; do not reuse the pre-pruning k value.

    Rollback conditions for speculative decoding: speedup below 1.1 (starting point), P99 latency worse than with it disabled, or peak memory exceeding the reserved margin. Meeting any one condition means turning speculative decoding off.

    4. KV Cache Memory Planning

    KV cache determines how many requests can be processed concurrently. Bytes per token:

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

    The factor of 2 accounts for storing both K and V. A single request’s KV usage equals the per-token bytes multiplied by sequence length. The peak KV usage across all concurrent requests equals the per-request usage multiplied by the concurrency level.

    Example (hypothetical: 60 layers, 8 KV heads, head dimension 128, FP16, 2 bytes per element):

    • Per token: 2 × 60 × 8 × 128 × 2 = 245,760 bytes, about 240 KiB.
    • With sequence length 4096 and concurrency 16: 245,760 × 4096 × 16 ≈ 15 GiB.

    For planning, split memory into separate line items, each estimated independently:

    • Resident expert weights: all experts’ weights; usually the largest item for MoE models.
    • Non-expert weights: attention layers, embedding layers, etc.
    • Draft model weights: if speculative decoding is enabled.
    • Peak KV cache: computed with the formula above.
    • Framework overhead and fragmentation margin: start by reserving 10%–15% of total available memory, then adjust after measurement.

    Maximum concurrency is estimated as memory available for KV cache divided by the per-request peak KV usage. Use the P99 input length plus maximum output length from production quantiles as the peak length, not the average; otherwise long requests will trigger OOM.

    OOM troubleshooting checklist:

    1. Determine whether OOM occurs during loading or inference. Loading-stage OOM usually means resident weights exceed the limit; inference-stage OOM usually means KV cache or batch size exceeds the limit.
    2. Record the batch size, concurrency, longest sequence length at the time of OOM, and whether the draft model was enabled.
    3. Compare against the line-item table to identify which item exceeded expectations.
    4. Reduce maximum concurrency or maximum sequence length, or disable speculative decoding, and verify recovery.
    5. If OOM appears after pruning, check the peak memory of individual experts after load redistribution.

    5. Retesting and Rollback

    Numbers from any source cannot be copied directly; every optimization must be validated on a unified retest matrix. The matrix dimensions:

    Dimension Suggested values
    Model version Original, pruned, pruned + speculative decoding
    Inference framework version Same as production, pinned minor version
    GPU model Same as production instances
    Batch size 1, 8, 32, 64; add tiers based on the production distribution
    Input/output length distribution Short, medium, long tiers from production quantiles
    Concurrency 50%, 100%, 120% of the production peak

    For each experiment, record these A/B metrics: accuracy and format error rate; P50, P95, and P99 of time-to-first-token and per-token latency; effective output throughput; cost per million output tokens; peak memory; OOM count; routing load ratio; and speculative decoding acceptance rate.

    Rollback trigger thresholds (starting values; calibrate per business needs):

    Metric Trigger condition (starting point) Action
    Core task accuracy Drops more than 1 percentage point vs. original baseline Switch back to original
    Format error rate Rises more than 0.5 percentage points vs. original baseline Switch back to original
    P99 latency Exceeds SLA target for 10 minutes Disable speculative decoding first; switch back to original if still over
    OOM Reproducible OOM in production Lower concurrency limit; switch back to original if recurring
    Routing load ratio Above 1.5 for 15 minutes Add replicas or switch back to original
    Speculative decoding acceptance rate Below 80% of the retest baseline (relative) Re-select k or disable speculative decoding

    Weight checksums prevent loading the wrong version. Before release, compute SHA-256 of both original and pruned weights and record them in the configuration center. The service verifies each weight at load time; on mismatch it refuses to start and raises an alert.

    Minimum monitoring and alerting configuration:

    • Latency: P50, P95, P99 of time-to-first-token and per-token latency, broken down by scene group.
    • Resources: memory usage, KV cache utilization, GPU utilization, OOM count.
    • Quality: format error rate and refusal rate, by scene group, compared against baseline.
    • Routing: token distribution across experts, load ratio.
    • Speculative decoding: acceptance rate and speedup.

    Alerts have two levels. Level one: metrics approaching thresholds, handled by the algorithm and inference platform teams during working hours. Level two: rollback conditions triggered — execute the switch-back immediately, and preserve logs and configuration snapshots afterward for postmortem.

    The recommended rollout order: first unify the cost baseline and collect baseline data; then complete the per-scene expert pruning evaluation; then select the draft model and k on the retest matrix; then plan memory and concurrency using the line-item table; and finally go live only after completing a switch-back drill.