Lightweight LLM Selection: Real Cost Calculation and A/B Evaluation
This article explains how to evaluate lightweight large language models using real business data rather than list prices alone. It covers how to calculate expected cost per task, including token usage, cache hit rates, and retries; how to design A/B tests with appropriate traffic splitting, sample size, duration, metrics, statistical judgment, rollback rules, and data masking; how to interpret capability benchmarks and build targeted test sets for code generation, tool calling, and vision; what to verify in frontend and multimodal outputs; and how to compare self-built, open-source, and cloud provider gateways for enterprise deployment.
Model list prices are only one part of the bill. To determine whether a lightweight model truly saves money, calculate the actual cost per task first, then compare the results across models.
1. Calculate Total Cost Before Unit Price
First, calculate the cost of a single attempt:
Single-attempt cost = input tokens × average input price per token + output tokens × output price per token
Second, calculate the expected cost per task:
Expected cost per task = expected number of attempts × single-attempt cost
Expected number of attempts = 1 + average number of retries. The average number of retries should be calculated from historical logs or canary tests. For example, if 100 tasks produce 18 retries in total, the average number of retries is 0.18. The cost of retries is already included in the expected number of attempts; do not add retries again as a separate fixed amount.
The variables in the formula should use real business data:
- Input tokens and output tokens: use the averages from real business requests, not estimates based on sample text.
- Average input price: cache hit rate × cache-hit price + (1 − cache hit rate) × standard input price. The longer the system prompt and the lower the reuse rate, the closer the actual input price is to the standard price.
- Output tokens: reasoning models may count intermediate reasoning content as output tokens. If billing includes this content, use the actual billed output tokens.
The following is a hypothetical example; the numbers are only for demonstrating the calculation method. Assume each task uses an average of 2,000 input tokens and 500 output tokens, the input price is CNY 1 per 1K tokens, the output price is CNY 2 per 1K tokens, and the cache hit rate is 0. The single-attempt cost is 2 × 1 + 0.5 × 2 = CNY 3. If the average number of retries is 0.2, the expected number of attempts is 1.2, and the expected cost per task is 1.2 × 3 = CNY 3.6.
Prices change over time. When calculating costs, record the following information and use the official billing page as the source of truth:
| Record item | Purpose |
|---|---|
| Model name and version number | Avoid mixing data from different versions |
| Billing region and billing date | Prices may change over time |
| Cache conditions | Determine the average input price |
| Retry rate and timeout rate | Determine the expected number of attempts |
When citing specific prices in reports or articles, include this information as well.
2. Use A/B Testing to Verify Real Performance
Benchmarks and leaderboards only show model performance on specific test questions. A/B testing is usually a more reliable way to judge performance in your own business.
Traffic splitting: use hash-based splitting by user ID or request ID so that the same user always accesses the same model during the test. Do not switch models by time period; otherwise, differences between daytime and nighttime traffic will contaminate the results.
Sample size: when task success rate is the primary metric, assume the baseline success rate is 80% and you want to detect a 5 percentage point improvement (to 85%). Using a two-sided two-proportion test with significance level α = 0.05 and power of 80%, each group needs at least about 906 independent tasks; in practice, use 910 or more. The smaller the difference you want to detect, the more samples are needed. Before launch, verify the sample size with a sample size calculation tool.
Test duration: cover at least one complete business cycle, such as 7 consecutive days, to ensure weekdays, weekends, peak hours, and off-peak hours are included. Overnight batch tasks should be counted separately and compared with a concurrent control group.
Core metrics: include task success rate (determined by rules or manual review), cost per task, P50 and P95 response latency, retry rate, and manual review pass rate. Define the definition and calculation method of each metric in advance.
Statistical judgment: calculate the 95% confidence interval for the difference in success rate. If the interval includes zero, the current sample cannot determine which model is better; do not draw a conclusion based only on the mean.
Rollback strategy: define circuit-breaker conditions in advance, such as a success rate drop below a set threshold compared with the baseline, or P95 latency exceeding the budget. When triggered, automatically switch back to the original model and notify the owner.
Data masking: phone numbers, ID numbers, bank card numbers, and customer names in test logs should be masked before being written. Restrict access to the test team and set a log retention period.
3. How to Read Capability Evaluations
Before reading scores in leaderboards or promotional materials, confirm the following: leaderboard name, evaluation date, model version, test set scope, scoring rubric, and maximum score.
If the score difference between two models is smaller than the fluctuation range of the evaluation itself, do not judge which one is stronger. For example, if two models score 72 and 73 on the same test set, and repeated evaluations of the same model fluctuate by about ±2 points, the 1-point difference cannot show a meaningful difference. Repeat the evaluation multiple times and estimate the fluctuation range before judging.
Composite scores also cannot replace component analysis. It is recommended to break capabilities into three categories and build a small test set for each, with 100 to 300 real samples per category.
- Code generation: provide a requirement description, check whether the generated code passes unit tests, and record the proportion that requires manual modification.
- Agents and tool calling: check whether the model selects the right tools, fills in parameters correctly, and completes multi-step tasks. Record the tool-call parameter accuracy rate and end-to-end completion rate.
- Vision understanding: given an image and a question, check the accuracy of key information extraction. Receipts, tables, screenshots, and other document types should be counted separately.
Test sets should come from real business data as much as possible, be desensitized, and be saved for reuse during model upgrades.
4. Validation Points for Frontend and Multimodal Scenarios
Models can generate pages, components, and scripts from natural language, which provides a new source of efficiency for frontend development. However, generated results must be validated before use.
Generated page code should be checked across multiple screen sizes and mainstream browsers to confirm that the layout is not misaligned, interactions work properly, and accessibility attributes are complete. Maintainability should also be evaluated, including whether components are split reasonably, whether styles are duplicated, and whether naming follows team conventions.
Security also requires attention. Generated code may contain unsafe DOM writes, unescaped user input, or third-party scripts of unknown origin. Before release, perform manual code review and run static analysis tools.
Multimodal scenarios, such as generating an editing script or timeline from video content, require manual sampling and verification. Randomly sample outputs, compare them item by item with the original material, and record error types and error rates. It is recommended to sample 5% to 10% of outputs first. After the error rate stabilizes, reduce sampling to 1% to 3%, but continue periodic spot checks. Only when the error rate is stable within an acceptable range should the process be suitable for automation.
5. Selection Dimensions for Enterprise Architecture
When an enterprise integrates large models, architecture choices affect cost, stability, and future migration difficulty. There are three common options, each with trade-offs:
| Option | Control | Ops cost | Vendor lock-in risk | Time to launch |
|---|---|---|---|---|
| Self-built gateway | Strongest; supports deep customization of routing and audit rules | High; high availability and security patches must be handled in-house | Low | Slow |
| Open-source gateway | Relatively strong; rich plugin ecosystem | Medium; evaluate community activity and release frequency | Low | Medium |
| Cloud provider gateway service | Limited by platform capabilities | Low; highly integrated | Relatively high; cross-cloud migration requires re-adaptation | Fast |
A self-built gateway is suitable for teams with strong operations capabilities that need deep customization of routing and audit rules. An open-source gateway is suitable for teams that want to remain technology-neutral without building from scratch; before choosing one, evaluate community activity, release frequency, and commercial support. A cloud provider gateway service is suitable for teams that want to launch quickly and already run their business on that cloud platform.
Regardless of the option, keep a unified adapter interface between business code and model providers. When switching models, only the adapter layer needs to be changed; business logic does not.
If private deployment or fine-tuning is required, use a container platform to orchestrate inference services and configure elastic scaling for GPU nodes. Elastic scaling has cold-start latency. Overnight batch tasks can combine queue-based peak shaving with autoscaling, and the impact of cold-start latency on service-level objectives should be accounted for separately.
