Reducing LLM Inference Costs: Architecture, Caching, and Evaluation in Practice
This article explains how to lower the cost of running large language models in production. It covers why inference cost often matters more than benchmark scores when choosing a model, architecture options for reducing KV cache pressure, trade-offs in mixture-of-experts designs, prompt caching and cost estimation, inference acceleration techniques, and a reproducible method for comparing models on quality, latency, and cost per task.
1. Why Inference Cost Drives Model Selection
After a large model goes into production, training cost is paid once, but inference cost keeps accumulating with every request. For high-traffic applications, the cost per request, the response time, and the cost per task often determine whether a project is viable more than a single benchmark score does.
Evaluating a model therefore requires answering three questions at once. Is its capability sufficient? Is its latency acceptable? Is its cost under control? If any one of these is missing, the user experience or the budget may run into problems after launch.
2. Architecture-Level Approaches to Reducing Cost
2.1 Memory Pressure from Attention
During autoregressive generation, the model must store the key and value vectors of previous tokens. This is known as the KV cache. Its memory footprint is proportional to the context length, the number of layers, the number of attention heads, and the numerical precision. As the context grows, the KV cache often exhausts GPU memory before the model weights do, which limits the number of concurrent requests.
Common mitigation methods include:
- Grouped-query attention: Multiple query heads share the same set of key and value heads, which significantly reduces cache size.
- Sliding-window or local attention: Each token can access only a limited range of history, so the cache does not grow without bound as the context lengthens.
- Linear or state-space structures: These are used alternately with full attention layers to reduce compute and cache overhead on long sequences.
- Sparse attention: Each token attends only to the subset of history positions most relevant to it.
Hybrid attention is a common way to combine these methods. It interleaves a small number of full attention layers with efficient linear layers in a fixed ratio, balancing output quality against resource consumption. The right ratio must be determined through experiments. No single value works for every case.
2.2 Mixture-of-Experts Models
A mixture-of-experts (MoE) model splits the feed-forward network into multiple experts, and each token is routed to only a few of them. The total parameter count can be very large, but each forward pass activates only part of the parameters, so the compute cost is close to that of a smaller model.
Three points need attention in production:
- Routing balance: If many tokens concentrate on a few experts, those experts become overloaded while the others sit idle. Training usually adds load-balancing constraints to prevent this.
- Communication overhead: When experts are distributed across multiple GPUs, tokens must be dispatched and gathered across devices. Communication can become a bottleneck.
- Small-batch efficiency: With small batches, each expert receives only a few tokens, so compute utilization is low.
The following simplified top-k routing sketch shows the basic routing flow:
def route(token_hidden, gate_weights, k=2):# Compute the score for each expertscores = softmax(token_hidden @ gate_weights)# Select the k experts with the highest scorestopk_scores, topk_ids = top_k(scores, k)# Renormalize the scores of the selected expertstopk_scores = topk_scores / topk_scores.sum()return topk_ids, topk_scores
2.3 External Memory and Conditional Computation
Some designs place part of the parameters into lookup-style memory structures, such as n-gram embedding tables. These parameters increase model capacity, but only a limited portion of them takes part in computation for each token.
When evaluating such structures, distinguish between two kinds of cost. Storage can be very large and mainly affects memory capacity. Compute cost depends on how many parameters each token actually accesses and on the memory bandwidth used during that access. The two should not be treated as the same thing, or the cost estimate will be wrong.
3. Context Caching and Billing
3.1 How Cache Hits Work
When multiple requests share the same prefix, such as an identical system prompt or the same reference document, the server can reuse the previously computed KV cache instead of recomputing that part of the input. The cached portion requires less computation, has lower latency, and is usually billed at a lower unit price.
3.2 Cost Estimation
The cost of a request can be split into three parts: uncached input, cached input, and output.
Total cost = uncached input tokens × uncached input price + cache-hit input tokens × cache-hit price + output tokens × output price
The following function implements this formula as a reusable estimation tool:
def estimate_cost(input_tokens, hit_ratio, out_tokens, price):"""price is a dictionary of prices per million tokens"""hit_tokens = input_tokens * hit_ratiomiss_tokens = input_tokens - hit_tokenscost = (miss_tokens * price["input"]+ hit_tokens * price["cache_hit"]+ out_tokens * price["output"]) / 1_000_000return cost
Get prices from the provider’s latest pricing documentation, and update them promptly when they change.
3.3 Improving Cache Hit Rates
- Fixed prefixes: Place system instructions, role settings, and static documents at the beginning of the prompt, and dynamic content at the end.
- Avoid prefix changes: Do not include timestamps, random IDs, or other values that change on every request in the prefix.
- Consolidate sessions: For multi-turn conversations from the same user, reuse the same prefix instead of reassembling the full background on every turn.
4. Inference Acceleration Techniques
- Quantization: Reducing weights from 16-bit to 8-bit or 4-bit lowers memory usage and memory bandwidth pressure. Quantization causes some loss of accuracy. Math reasoning and code generation tasks are more sensitive to this loss, so validate them separately before launch.
- Continuous batching: Requests of different lengths are batched dynamically. When a request finishes, a new one is added immediately, which improves GPU utilization.
- Operator fusion and custom kernels: Merging several small operators into one kernel reduces the number of kernel launches and the reads and writes of intermediate results to GPU memory.
- Speculative decoding: A small model drafts several tokens, and the large model verifies them in parallel. When the large model accepts most of the drafted tokens, output generation becomes noticeably faster. This suits scenarios with long outputs.
When comparing decoding speed, make sure the numbers are comparable. Tokens per second can vary widely with concurrency, context length, hardware model, and batch size. Report these conditions alongside any speed figure.
5. Building a Reproducible Evaluation Method
5.1 Building a Task Set
Sample by business category in layers, covering common tasks, edge cases, and tasks known to cause errors. Each category needs enough samples. Otherwise, conclusions about a single category may be unstable.
5.2 Blind Testing and Scoring
Evaluators should not know which model produced each output, and they should score against a shared rubric. A four-level satisfaction scale is a common choice. Define the criteria for each level in advance to prevent the scoring standard from drifting.
5.3 Core Metrics
| Metric | Description | Notes |
|---|---|---|
| Quality score | Blind satisfaction rating or task pass rate | Record agreement between evaluators |
| Latency | Median and P90 | The median reflects typical experience. P90 reflects tail latency. |
| Cost per task | Unit price multiplied by actual token consumption | Measure per task. Do not rely on unit price alone. |
The following script summarizes a set of evaluation records:
import statisticsdef summarize(records):scores = [r["score"] for r in records]latency = [r["latency_s"] for r in records]cost = [r["cost"] for r in records]return {"mean_score": round(statistics.mean(scores), 2),"median_latency_s": statistics.median(latency),"mean_cost": round(statistics.mean(cost), 4),"n": len(records),}
5.4 Interpreting Results
With small sample sizes, the difference between two models may be random variation. Before comparing them, report confidence intervals or run a simple significance test. If the difference is not significant, do not draw a conclusion from it.
6. Model Selection Advice and Caveats
- Do not look at unit price alone. Cost per task depends on both the unit price and the number of tokens each task consumes. A model that takes longer or produces more redundant output may cost more in practice.
- Route tasks by difficulty. Simple tasks such as classification, extraction, and format conversion can go to a smaller model. Complex reasoning and code generation can go to a more capable model. Overall cost can often drop significantly this way.
- Use your own data as the reference. Public benchmark scores and technical descriptions are useful for reference. Real production inputs, however, often differ from public evaluation sets.
- Monitor production metrics continuously. After launch, record quality spot-check results, latency percentiles, and daily cost. This helps you detect changes caused by model version updates or shifts in traffic patterns early.
- Keep a fallback plan. When a service hits rate limits, changes prices, or shows quality fluctuations, you should be able to switch to an alternative quickly. This prevents service interruptions.
In summary, reducing LLM costs requires coordinating architecture, caching, inference, and evaluation. Breaking costs down to the level of individual tasks and comparing models with a consistent, reproducible method is what makes selection decisions reliable.
