Technical Paths and Engineering Practices for Reducing LLM Inference Costs
This article explains why inference cost has become the key constraint in deploying large language models, and reviews the main technical paths for reducing it: sparse activation with Mixture of Experts, attention computation optimization, KV Cache compression, inference engine and scheduling techniques, heterogeneous hardware adaptation, and a practical evaluation framework. Readers will learn how to measure latency, throughput, and per-task cost with a consistent methodology, and how to make rational model selection and deployment decisions.
1. Why Inference Cost Has Become the Core Metric
As model capabilities improve, inference cost is gradually replacing training cost as the main constraint on deploying large language models. The cost of serving a single request consists of three parts: computation, i.e., the floating-point operations required per token; memory usage, including model weights and the KV Cache that grows with context length; and communication and scheduling overhead, including data exchange across GPUs and request queuing.
When evaluating a solution, engineering teams typically focus on three numbers: time to first token, tokens generated per second (throughput), and the total cost of completing a task. These three constrain each other. For example, increasing batch size can improve throughput but may lengthen the waiting time for individual requests. Cost optimization therefore needs to consider all three metrics rather than focusing on unit price alone.
2. Sparse Activation: Decoupling Capacity from Computation
A dense model invokes all of its parameters at every inference step. The Mixture of Experts (MoE) architecture instead splits the feed-forward network into multiple experts, with a router selecting only a few experts to compute each token. In this way, the total parameter count determines model capacity, while the activated parameters determine per-step computation.
The following pseudocode illustrates the top-k routing logic:
function moe_forward(token_hidden, experts, router, k):scores = router.linear(token_hidden) # score each experttop_idx = select_top_k(scores, k) # pick the k highest-scoring expertsweights = softmax(scores[top_idx]) # normalize into weightsoutput = 0for i in top_idx:output += weights[i] * experts[i](token_hidden)return output
The benefit of this structure is straightforward. Suppose a model has 300B total parameters and 20B activated parameters; the forward computation per token is then roughly equivalent to that of a 20B dense model. Estimating about 2 FLOPs per parameter, this is around 40 GFLOPs per token (ignoring routing and communication overhead). However, all parameters still need to fit into memory or be distributed across multiple GPUs, so memory usage and inter-GPU communication remain high.
Sparse activation also introduces two problems. First, routing can be imbalanced: a few experts get overloaded while others sit idle, which requires load-balancing losses or capacity limits. Second, when experts are distributed across devices, tokens must be forwarded between devices, and interconnect bandwidth becomes a bottleneck.
3. Optimizing Attention Computation
Standard attention scales quadratically with sequence length, and this cost grows rapidly in long-context scenarios. The industry mainly pursues three approaches.
| Type | Computational Complexity (approx.) | Main Characteristics | Main Trade-off |
|---|---|---|---|
| Full attention | O(n²·d) | Full expressive power | High cost on long sequences |
| Linear attention | O(n·d²) | Complexity grows linearly with length | Degradation on exact retrieval tasks |
| Sparse attention | O(n·k·d) | Computes only selected positions, e.g., sliding window or block selection | Poor selection strategies may miss key information |
Here, n is the sequence length, d is the hidden dimension, and k is the number of positions actually involved in the computation for each position.
The hybrid architecture approach combines different mechanisms across layers. For example, some layers use linear attention to compress the computation of long-range dependencies, while others use sparse attention to preserve sensitivity to exact retrieval. Designs should be validated with long-context evaluations (such as key information retrieval and multi-hop reasoning) rather than judged only by the percentage reduction in computation.
4. KV Cache: The Memory Bottleneck of Long Contexts
During autoregressive generation, the model caches the keys and values of every layer to avoid recomputing historical tokens. KV Cache usage can be estimated as follows:
KV_bytes = 2 × num_layers × num_KV_heads × head_dim × sequence_length × batch_size × bytes_per_element
With a million-token context, even a model with only a few dozen layers can require tens of GB of memory for the KV Cache. Compressing the KV Cache is therefore often more effective than compressing the weights. Common techniques include:
- Reducing KV heads: Grouped-Query Attention (GQA) or Multi-Query Attention (MQA) lets multiple query heads share the same set of key-value heads, reducing cache size proportionally.
- Low-precision storage: Quantizing the KV Cache to FP8 or INT8, usually at the cost of slight accuracy loss that must be confirmed on evaluation sets.
- Index and cache sharing: When sparse attention needs to maintain multiple index structures for the same sequence, these structures can be merged into a single shared store. If index caches account for a fraction p of the total cache and there were originally m copies, merging them into one reduces total cache by roughly p×(1−1/m). For example, with p = 50% and m = 4, the total cache drops by about 37.5%.
- Eviction and compression: Summarizing or discarding early or low-importance tokens works well for dialogue and document QA scenarios, but care is needed to avoid losing critical information.
5. Inference Engine and Scheduling Optimization
The same model can behave very differently across inference engines. The following techniques are the most common in engineering practice.
- Continuous batching: New requests dynamically join the running batch without waiting for the entire batch to finish, significantly improving GPU utilization.
- Paged memory management: The KV Cache is split into fixed-size blocks allocated on demand, reducing memory fragmentation and supporting higher concurrency.
- Quantization: Weight quantization reduces memory footprint and bandwidth pressure. Activation quantization requires more careful calibration; otherwise, numerical overflow is likely.
- Parallelism strategies: Tensor parallelism suits multi-GPU setups on a single machine, pipeline parallelism suits cross-node deployment, and expert parallelism suits MoE models. Interconnect bandwidth must be considered when choosing.
- Trading computation for communication: When bandwidth is limited, recomputing some intermediate results can replace cross-device transfers, at the cost of extra computation.
- Speculative decoding: A small model quickly generates candidate tokens and the large model verifies them in one pass. This suits scenarios with long, predictable outputs.
Optimization results should be measured with a consistent methodology. It is advisable to fix the input/output length distribution, concurrency level, and hardware configuration, then compare end-to-end throughput, P95 latency, and cost per million tokens. Comparing only the theoretical speed of a single request can easily lead to misleading conclusions.
6. Adapting to Heterogeneous Accelerators
Different accelerator chips differ significantly in memory capacity, memory bandwidth, and inter-chip interconnect. A deployment plan that works well on one chip may need to be redesigned when migrated to another. Adaptation work typically includes the following aspects.
- Memory planning: First compute the total requirement of weights, KV Cache, and temporary buffers, then decide on quantization precision and the parallelism partitioning scheme.
- Operator adaptation: Provide custom implementations or replacements for critical operators (attention, normalization, routing), and run numerical alignment tests against the standard implementations.
- Topology awareness: Arrange parallel groups according to the connection topology between devices, placing communication-heavy modules on high-bandwidth links.
- Tiered deployment: Keep frequently accessed hot data in fast memory and cold data in slower storage tiers, scheduled by access frequency.
After adaptation, cost per token should be the core metric, computed as:
cost_per_token = (hardware_cost_per_hour / 3600) / effective_tokens_per_second_per_device
Here, “effective tokens” should exclude the portion consumed by failed requests and retries; otherwise, cost will be underestimated.
7. How to Think Rationally About Low Prices
A low per-token price does not mean a low total cost per task. A task may require multiple rounds of calls, tool invocations, and retries. The cost per task can be approximated as:
cost_per_task = unit_price × average_tokens_per_task × number_of_call_roundscost_per_success = cost_per_task / task_success_rate
Differences in success rate are often overlooked. If two models differ by a factor of two in unit price but differ by a larger factor in success rate, the more expensive model may actually cost less overall.
Limited-time discounts also need separate treatment. Promotional pricing is suitable for short-term experiments and stress testing, but should not be used directly as the basis for long-term budgets. Calculations should be performed at both the regular and discounted prices, and the cost change after the promotion ends should be evaluated.
8. A Model Selection Evaluation Framework
No single leaderboard can reflect real business performance. It is advisable to build an evaluation system along the following dimensions.
- Capability: Build evaluation sets from your own business data, covering typical inputs, edge cases, and failure cases.
- Latency and throughput: Measure time to first token and generation throughput under target concurrency and input lengths.
- Long-context performance: Test information retention with long-document tasks that match your business, rather than only looking at the maximum supported length.
- Cost per task: Compute using the formulas from the previous section, including retries and multi-round calls.
- Stability: Observe error rates, timeout rates, and rate-limiting policies.
- Compliance and data security: Confirm whether data storage location, retention periods, and access permissions meet your requirements.
The evaluation process can be written as a simple loop:
for model in candidates:for case in eval_set:output = model.generate(case.input)record(score(output, case.reference), latency, tokens_used)report = aggregate(records, group_by=model)
9. Deployment Recommendations
First, adopt a tiered invocation strategy. Route simple tasks to low-cost models and escalate complex tasks to more capable models. This cascading structure can significantly reduce average cost while keeping quality acceptable.
Second, enable caching for repeated prefixes. System prompts, fixed templates, and common parts of long documents can reuse computed results, reducing redundant prefill overhead.
Third, roll out gradually with a fallback plan. Run new models on a small fraction of traffic first, monitor quality and cost metrics, and be able to switch back to the original solution quickly when anomalies occur.
Fourth, avoid dependence on a single provider. Model versions and pricing change rapidly, so the application layer should call different models through a unified interface abstraction to reduce migration costs.
In summary, reducing inference cost depends on joint improvements in model architecture, attention mechanisms, memory management, inference engines, and hardware adaptation. Engineering teams should start from business metrics, measure the actual benefit of each optimization with a consistent methodology, and then decide on the deployment plan.
