Sparse Architectures and Inference Cost Reduction: A Technical Guide to Unit Cost

    This article examines inference cost reduction through sparse architectures and unit-cost accounting. It covers MoE routing, capacity factors, attention-efficiency trade-offs, prefix caching, tiered routing, benchmark alignment, and a step-by-step method for calculating cost per successful task, with troubleshooting guidance for production deployments.

    1. Background: Competition Shifts from Parameter Scale to Unit Cost

    For the past few years, large-model competition has largely centered on parameter scale. As training and inference costs continue to rise, the industry has begun to focus on another set of metrics: computation consumed per task, price per token, and whether a model can reliably complete multi-step work. The efficiency-first approach has therefore become an important direction, but whether it delivers returns depends on task type and deployment conditions.

    This shift appears in three areas. First, model architecture design places more emphasis on making every computation count. Second, application-side attention has expanded from single-turn question answering to long-horizon tasks such as multi-step retrieval, code editing, and tool calling. Third, when teams evaluate models, they need to compare quality, latency, and cost in the same table.

    Vendor-published benchmark numbers are usually based on specific settings, including prompt templates, sampling parameters, context length, and whether tool calls are allowed. Independent reruns may differ. This article discusses general technical methods, does not evaluate any specific product, and does not promise that a particular change will reduce costs by a specific percentage.

    2. Sparse Activation Architectures: MoE Principles and Boundaries

    2.1 Dense Models and Mixture-of-Experts Models

    A dense model uses all parameters in every forward computation. The larger the model, the more computation each token requires. A Mixture-of-Experts (MoE) model splits the feed-forward network into multiple expert subnetworks, and a router selects a small number of experts for each token to participate in computation.

    This approach separates model capacity from per-token computation. The total number of model parameters can be large, while only a small fraction of parameters are actually activated for each token. Therefore, total parameter count and active parameter count are two metrics that must be distinguished. Looking only at total parameters can easily overestimate inference computation cost. Looking only at active parameters can easily miss the following overheads:

    • Expert weights still occupy GPU memory. The larger the total parameter count, the higher the memory requirement.
    • Expert scheduling requires additional data movement and synchronization.
    • In multi-GPU deployments, cross-device communication may become a bottleneck.

    Another term that needs to be understood is the capacity factor. The number of tokens each expert can process usually has an upper limit, generally calculated as capacity_factor × (token count × k ÷ E), where E is the number of experts. Tokens exceeding the limit are dropped (drop token) or bypass the layer, with the residual connection preserving the original value. The smaller the capacity factor, the more controllable memory and communication become, but the higher the drop rate.

    2.2 Top-k Routing: Code Example and Production Considerations

    The most common approach is Top-k routing. The system first computes scores for all experts for each token, selects the k experts with the highest scores, and then performs a weighted sum of their outputs.

    The following illustrative code shows the computation path for a single token:

    1. import numpy as np
    2. def top_k_route(x, gate_weights, experts, k=2):
    3. """
    4. x: (d,) hidden vector for a single token
    5. gate_weights: (d, E) routing matrix, where E is the number of experts
    6. experts: callable list of length E; each function receives a (d,) vector and returns a (d,) vector
    7. """
    8. logits = x @ gate_weights # (E,) raw score for each expert
    9. top_idx = np.argsort(logits)[-k:] # ascending sort, take the last k entries, i.e. highest-scoring experts
    10. top_idx = top_idx[::-1] # order from highest to lowest score for easier log reading
    11. selected = logits[top_idx]
    12. selected = selected - selected.max() # subtract the max value to avoid exp overflow
    13. weights = np.exp(selected)
    14. weights /= weights.sum() # softmax normalization over selected experts
    15. return sum(w * experts[i](x) for w, i in zip(weights, top_idx))

    In the code, np.argsort sorts in ascending order, so [-k:] takes the indices of the k highest-scoring experts. Subtracting the maximum value before softmax prevents np.exp from overflowing when scores are large. This code covers only a single token and still differs from a production environment in the following ways:

    1. Batching: a real system processes a batch of tokens at once, computes routing results in matrix form, and performs grouped batch forward passes by expert.
    2. Capacity limits: the number of tokens received by each expert must be counted, and portions exceeding the capacity factor are handled according to the rules above.
    3. Load balancing: routing can easily concentrate on a few experts, leaving other compute units idle. During training, an auxiliary loss is often added as a constraint; after deployment, the token share of each expert must be monitored.
    4. Expert-parallel communication: when experts are distributed across different devices, tokens need to be sent to target experts through all-to-all communication and then collected after computation. Communication time is directly related to k, batch size, and network bandwidth.
    5. Shape assumptions: experts[i](x) must return a vector with the same shape as x; otherwise the weighted sum will raise an error or produce hard-to-detect incorrect results.

    2.3 Efficiency Improvements in the Attention Layer

    In addition to the feed-forward layer, the attention layer is also an important source of computation. Standard attention computes relevance for all token pairs, and computation grows quadratically with sequence length n, i.e., O(n²). During inference, KV-cache memory usage grows linearly with sequence length.

    Common improvement directions and their trade-offs are as follows:

    Method Computational complexity (approximate) Memory characteristics Suitable sequence length Main cost
    Standard full attention O(n²) KV cache grows linearly with n Most stable for medium and short sequences High cost for long sequences
    Sliding-window attention O(n·w), where w is the window size Cache length can be limited Long text with strong local dependencies Long-range information must be propagated through multiple layers
    Sparse attention Depends on the sparsity pattern Depends on implementation Structured long text Poor pattern design can miss critical dependencies
    Linear attention Approximately O(n·d²) Fixed state size Ultra-long sequences May be weaker than full attention on exact retrieval tasks

    The choice should be based on evaluation results for the target task. The attention structure of released models is usually fixed, and deployment teams need to confirm whether the model supports that structure and whether the inference framework provides a corresponding implementation.

    3. Long-Horizon Tasks, Caching, and Tiered Routing

    3.1 Cost Sources in Long-Horizon Tasks

    The cost of single-turn question answering mainly depends on one input and one output. Long-horizon tasks have more cost sources:

    • Context accumulation: each step sends historical dialogue and tool results into the model again, so input tokens gradually increase.
    • Retries and fallbacks: when a tool reports an error or output format does not match, the system reruns a step, increasing cost.
    • Failed tasks: unfinished tasks also consume tokens but do not produce usable results.

    Therefore, the first step in cost reduction is to record the token count, number of calls, and failure reason for each step. Without these records, any subsequent optimization is difficult to verify.

    3.2 Caching: Prefix Cache and Hit Rate

    Prefix cache refers to retaining the computation results for identical request prefixes, such as system prompts, fixed tool descriptions, and long documents, and reusing them directly when subsequent requests hit the cache, thereby reducing repeated computation.

    The cache hit rate is calculated as follows:

    Hit rate = number of input tokens hitting the cache ÷ total number of input tokens

    Hit rate is only an intermediate metric; the ultimate question is whether cost and latency decrease. When using caching, note the following:

    1. Place stable content at the front of the prompt and changing content at the end; otherwise the prefix cannot match.
    2. Caches usually have a time-to-live (TTL). If the request interval exceeds that duration, the cache expires.
    3. Different vendors have different cache billing rules, such as whether hit portions receive a discount and whether writes are billed separately. Use the vendor’s current documentation and validate with real traffic.

    3.3 Tiered Routing

    Tiered routing means first using a smaller, cheaper model to handle a request, and escalating to a larger model only when confidence is insufficient or validation fails.

    The expected cost of a single request can be estimated as follows:

    Expected cost = c_small + escalation_rate × c_large

    Here, c_small is the cost of one small-model call (including the portion still paid after failure), c_large is the cost of one large-model call, and escalation_rate is the proportion of requests that need escalation.

    Consider an example calculation. If the small model costs CNY 0.2 per call, the large model costs CNY 2 per call, and the escalation rate is 30%, the expected cost is 0.2 + 0.3 × 2 = CNY 0.8, lower than CNY 2 for using the large model for everything. If the escalation rate rises to 80%, the expected cost becomes 0.2 + 0.8 × 2 = CNY 1.8, leaving little savings and adding latency. The escalation rate is a key metric in routing design and must be monitored together with quality metrics.

    When implementing tiered routing, first determine the escalation threshold on an evaluation set, then observe the online escalation rate and success rate. If escalation is judged only by question length, misjudgments are often frequent; it is better to combine task type and model confidence.

    4. Unit Task Cost Accounting and Benchmark Interpretation

    4.1 Aligning Benchmark Definitions

    Before comparing two models or two approaches, first confirm whether the following definitions are consistent:

    • Whether prompt templates and system prompts are the same.
    • Whether sampling parameters (temperature, top-p) and random seeds are the same.
    • Whether tool calls are allowed and whether retrieval augmentation is used.
    • Whether the metric is single-attempt pass rate (pass@1) or at least one success across multiple samples (pass@k).
    • Sample size, and whether the sample source is close to your own business.

    When definitions are inconsistent, the numbers cannot be compared directly.

    When the sample size is small, success-rate fluctuations are also large. For example, with 200 samples and an 80% success rate, the standard error is approximately √(0.8 × 0.2 ÷ 200) ≈ 2.8 percentage points, and the 95% confidence interval is approximately ±5.5 percentage points. A success rate between 74.5% and 85.5% is within normal fluctuation. A 3-percentage-point difference between two results is usually insufficient to show that one approach is better.

    4.2 Steps for Measuring Unit Task Cost

    Unit task cost refers to the average cost of completing one task, calculated with the number of successfully completed tasks as the denominator:

    Unit task cost = total cost of all tasks ÷ number of successfully completed tasks

    Here, total cost includes the cost of failed tasks, retries, and tool calls. Counting only the cost of successful tasks underestimates the real cost.

    The measurement steps are as follows:

    1. Define the task set, clarify what counts as success, and write it as automatically determinable rules.
    2. For each task, record input tokens, output tokens, number of calls, number of tool calls, and final result.
    3. Calculate the cost of each task according to the vendor’s current public unit prices: input tokens × input unit price + output tokens × output unit price + tool costs + allocated cost of self-owned infrastructure.
    4. Sum the total cost and divide by the number of successful tasks to obtain unit task cost.
    5. Record P50 and P95 latency at the same time. Averages mask a small number of very slow requests, while P95 better reflects long-tail problems.
    6. Repeat the measurement across different time periods and input distributions to check whether results are stable.

    4.3 Comparison Table Fields

    When comparing approaches, use a unified table. The following fields can be reused directly:

    Field Description Example
    Task category Task classification in the business Code editing
    Sample count Number of tasks included in the measurement 200
    Success rate Successful tasks ÷ sample count 80%
    Latency P50 / P95 Median and 95th percentile of end-to-end time 4.2 s / 11.8 s
    Median input tokens Input volume per task 6,000
    Median output tokens Output volume per task 900
    Unit price Vendor’s current public price, with currency and unit noted CNY / million tokens
    Retry rate Proportion of tasks with retries 6%
    Unit task cost Total cost ÷ successful tasks CNY / task
    Rerun conditions Date, model version, parameters, prompt version 2026-11, temperature=0

    5. Troubleshooting Checklist

    When measurement results or online behavior are abnormal, use the following table to investigate:

    Symptom Possible cause Check method
    Unit task cost suddenly rises Retry loops, continuously accumulating context Count calls per task and input-token growth curves
    Low cache hit rate Stable content is placed too late, or request intervals exceed TTL Compare whether prefixes of adjacent requests are identical
    Escalation rate too high Threshold is too strict, or task distribution has changed Calculate escalation rate by task category
    Success rate drops but cost decreases Routing sends difficult tasks to the small model Evaluate samples before and after escalation separately
    P95 latency becomes noticeably longer Long-tail requests, overly long escalation paths, expert communication bottlenecks Group latency by request length and routing path
    Rerun results differ greatly from vendor numbers Inconsistent definitions or too few samples Check item by item against Section 4.1