Cutting Inference Costs with Open-Source LLMs: From Model Evaluation to Inference Optimization
This article explains why open-source large language models can lower inference costs, how to compare models by cost per successful task, and how to set up an evaluation process for model selection. It also covers practical optimizations, including prompt caching, task routing, output length control, batch processing, and cost monitoring.
Open-source large language models (LLMs) with large parameter counts and open weights have recently drawn attention from developers outside China. For companies expanding overseas, the key question is how model capability, license terms, and price fit together. This article first explains the technical reasons open-source models can lower inference costs. It then shows how to evaluate models and calculate costs, and finally introduces several inference optimization methods that can be put into practice. All prices and percentages in this article are illustrative. Actual decisions should be based on measured data from your own workloads.
1. Why MoE Architecture Reduces Compute
A mixture-of-experts (MoE) model splits the network into many expert sub-networks. For each token, a router selects only a few experts to process it. As a result, the total parameter count can be very large, while only a fraction of the parameters, the active parameters, are used in each forward pass.
This design reduces the compute per token, but it does not reduce all costs in the same proportion. There are three reasons. First, the weights of all experts must stay resident in GPU memory, so memory requirements depend on the total parameter count. Second, experts are usually spread across multiple accelerator cards, and cross-card communication during routing adds latency. Third, when expert load is unbalanced, some cards wait in queues, which lowers batching efficiency. For this reason, the actual unit price and latency of an MoE model should be confirmed through load testing. They cannot be inferred from parameter count alone.
2. How to Calculate the Price Advantage of Open-Source Models
Model pricing is usually charged per million tokens and separates input from output. Output prices are often higher than input prices. Some services also offer different prices for cache hits and batch calls. When comparing models, use the same currency, billing items, and date, and record whether cache and batch discounts are included.
The example below uses hypothetical numbers to illustrate the calculation method only. Assume a daily total of 100 million tokens, with 80 million input tokens and 20 million output tokens. Assume 30 days per month and no cache discount. Both models process the same workload with the same token usage.
- Model A (proprietary flagship, illustrative price): input CNY 10 per million tokens, output CNY 40 per million tokens. Daily cost: 80 × 10 + 20 × 40 = CNY 1,600. Monthly cost: about CNY 48,000.
- Model B (open-source model, illustrative price): input CNY 2 per million tokens, output CNY 8 per million tokens. Daily cost: 80 × 2 + 20 × 8 = CNY 320. Monthly cost: about CNY 9,600.
Based on the bills alone, Model B costs about one-fifth of Model A. But the bill is not the final cost. Task success rate also matters. Assume 1 million tasks per month. Model A has a 90% success rate, so 900,000 tasks succeed. Model B has an 80% success rate, so 800,000 tasks succeed. The cost per successful task is about CNY 0.053 for Model A and about CNY 0.012 for Model B. The gap is still large, but it is smaller than the bill ratio suggests, and it changes with success rates.
3. An Evaluation Process for Enterprise Model Selection
When weighing performance against price, set up a quantitative process first. Do not rely only on leaderboards or quoted prices.
1. Build a business evaluation set
Benchmark scores do not reflect business performance. Sample several hundred to several thousand cases from real traffic, covering typical tasks, edge-case inputs, and long-tail questions. Combine automated scoring (rule checks, reference answer comparison, and model-based peer review) with manual spot checks. Record the agreement rate between manual checks and automated scoring separately.
2. Calculate cost per effective task
Do not compare token prices alone. Compare the cost of completing one successful task. Use the following formula:
Cost per effective task = (monthly inference bill + manual review cost + fallback cost for failed tasks) / number of successfully completed tasks
The inference bill is calculated from input tokens, output tokens, and unit prices, after deducting cache hits. The higher the retry rate, the higher the cost of failed tasks. A model with a low unit price that often needs retries can end up costing more than a model with a higher unit price.
3. Measure non-functional metrics
Key metrics include time to first token (TTFT), output tokens per second (TPS), P95 latency under high concurrency, maximum context window, and the pass rate for function calling and structured output. Business stakeholders should set acceptance thresholds in advance. For example, a model with a structured output pass rate below 98% may be excluded from canary release. The 98% figure is only an example threshold.
4. Assess migration cost and compliance prerequisites
Estimate the effort needed to migrate prompts, tool-calling chains, and the evaluation set to a new model. During architecture design, add a model abstraction layer so the underlying model can be replaced. Businesses expanding overseas also need to confirm data export rules, regulatory requirements in target markets, and whether private deployment is supported. Open-source license terms differ. Some restrict commercial scale or distribution methods, so legal teams should review each term.
4. Engineering Practices for Reducing Inference Costs
After selecting a model, several engineering methods can still reduce costs.
1. Prompt trimming and prefix caching
System prompts often make up most of the input tokens. Compress system prompts, and place the stable long prefix at the start of each request so it can hit the server-side prefix cache. In multi-turn conversations, trim the history to keep only content relevant to the current request. Track cache hit rate as a monitoring metric.
2. Tiered task routing
Not every request needs a flagship model. Add a lightweight routing layer that sends simple tasks, such as classification, information extraction, and rewriting, to a small model, and sends complex reasoning to a large model. The code below is illustrative and should not be used directly in production:
COMPLEXITY_THRESHOLD = 0.4 # Calibrate offline with the evaluation setdef route(query: str, complexity: float) -> str:# complexity is produced by rules (e.g., input length, keywords) or a lightweight classifier, in the range 0 to 1try:if complexity < COMPLEXITY_THRESHOLD:return small_model.invoke(query) # Low-cost pathreturn large_model.invoke(query) # High-performance pathexcept Exception as exc:logger.warning("Routing failed, falling back to the large model: %s", exc)return large_model.invoke(query) # Fallback path
Whether routing saves money depends on the share of simple requests. In traffic with many simple requests, savings may be considerable, but measure them against the actual traffic distribution. After launch, periodically sample requests sent to the small model to confirm that quality has not dropped.
3. Output length control
Output tokens usually cost more than input tokens. Give explicit length requirements in instructions, use structured output templates, and set a maximum token limit. Also monitor the truncation rate. Retries triggered by truncation can cancel out the savings.
4. Batch processing and asynchronous execution
For offline tasks with low latency requirements, such as data cleaning, bulk translation, and report generation, use batch inference interfaces. Some providers offer discounts for batch calls. Check the provider’s documentation for specific rates. Asynchronous tasks should also use rate limits and exponential backoff retries to avoid amplifying failure costs during peak hours.
5. Observability
Build a monitoring system for cost and quality, and allocate costs by business line. Track at least the following metrics for each business line: input and output token counts, cache hit rate, TTFT, TPS, error and timeout rates, retry rate, routing split ratio, and cost per effective task. Cost management must continue as the business evolves. It cannot be done once and then left alone.
5. Conclusion
Open-source LLMs give enterprises more options, but cost savings depend on three things: business-specific evaluation, accurate calculation of cost per effective task, and ongoing inference optimization. Start with a small-traffic pilot on one business line, use measured data to judge the results, and then decide whether to expand. Do not proceed with a full migration until data compliance and license terms are confirmed.
