LLM Inference Cost Reduction: Asymmetric Architecture and KV Cache Optimization
The unit cost of serving large language models depends on several interrelated factors: compute per request, GPU memory and storage consumed during inference, throughput, and how resources are allocated over time. This article breaks down the cost structure of prefill and decode phases, explains how asymmetric compute designs such as Mixture of Experts reduce activated parameters, and provides practical methods for KV cache sizing and compression, prefix caching in agent workloads, multimodal input handling, peak/off-peak scheduling, smooth version migration, and cost-quality evaluation, with code examples and a deployment checklist.
The unit cost of serving large language models is determined by several interrelated factors: the amount of compute per request, the GPU memory and storage consumed during inference, the number of requests the system can handle per unit of time, and how resources are allocated over time. As model capabilities improve, if these cost items are not controlled in parallel, scaling the service becomes constrained. This article reviews general technical approaches for each cost factor and provides methods you can apply directly to evaluation and deployment.
1. The Anatomy of Inference Cost
A typical LLM call has two phases. The first phase processes the input and is called prefill. The model reads all input tokens in parallel, which involves heavy computation but high parallelism. The second phase generates output tokens one by one and is called decode. Generating each token requires reading the model weights and the historical cache, so it is more constrained by memory bandwidth. Because the two phases have different bottlenecks, both “cheap input, expensive output” and the reverse are common. Cost optimization therefore needs to be done per phase.
Costs can be broken down into three categories:
- Compute cost: proportional to the number of activated parameters and tokens.
- Storage cost: mainly the GPU memory or external storage occupied by the KV cache.
- Time cost: queuing, waiting, and concurrent resource occupancy.
Only after breaking costs down can you decide where optimization should start.
2. Asymmetric Compute and Activated Parameters
In a Mixture of Experts (MoE) architecture, only a subset of expert networks is activated during each forward pass. The total parameter count can be very large while per-request compute stays low—this is a general cost-reduction strategy. Building on this, different phases can use different compute paths. For example, input encoding and output generation can use different sizes or routing strategies so that each phase matches its own bottleneck.
Asymmetric design has its costs. The parameter allocation between encoding and decoding must be validated through training and evaluation. Over-compressing one side may harm long-context comprehension or generation coherence. In engineering practice, judge effectiveness by task metrics rather than theoretical FLOPs alone.
3. KV Cache: The Main Memory Cost of Long Context
During generation, a Transformer must store the Key and Value vectors of every layer—the KV cache. Its size grows linearly with context length, batch size, and the number of layers. The estimation formula is:
KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element
The following code gives an estimation example. The parameters are illustrative only and do not represent any specific model.
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, dtype_bytes=2):# The factor of 2 accounts for storing both Key and Valuereturn 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes# Illustrative parameters: 32 layers, 8 KV heads, head dim 128,# context 32768, batch size 8, FP16size = kv_cache_bytes(32, 8, 128, 32768, 8)print(f"{size / 1024**3:.2f} GiB") # outputs 32.00 GiB
Common cache compression techniques include:
- Grouped-Query Attention (GQA) and Multi-Query Attention (MQA): reduce the number of KV heads, directly shrinking the cache.
- Quantization: reduce the cache from FP16 to INT8 or lower precision. Use an evaluation set to verify that the accuracy loss is acceptable.
- Sliding window and chunking: keep only recent or critical segments and discard parts that are no longer needed.
- Tiered storage: hot data in GPU memory, warm data in host memory, cold data on SSD, migrating by access frequency.
- Cache reuse: requests sharing the same prefix reuse the already-computed KV results.
4. Agent Workloads and Prefix Caching
Agent tasks typically involve multi-turn calls. Each turn carries the system instructions, tool definitions, and conversation history, much of which repeats across turns. If the serving side supports prefix caching, the repeated portion only needs to be computed once. Three practical points to keep in mind:
- Place stable content (system instructions, tool descriptions) at the front of the prompt and dynamic content at the end to improve the hit rate.
- Avoid inserting timestamps, random IDs, or other varying fields into each request, or the prefix will be invalidated.
- Summarize or trim the conversation history to control its growth.
Billing discounts for cache hits vary by provider policy. Verify savings against actual bills rather than estimating from experience.
SYSTEM_PROMPT = "You are a code review assistant..." # stable prefix, always firstTOOLS = [...] # keep tool definitions in fixed order and formatdef build_messages(history_summary, user_input):return [{"role": "system", "content": SYSTEM_PROMPT},*history_summary, # history summary, length controlled{"role": "user", "content": user_input},]
5. Engineering Practices for Multimodal Input
Before entering a language model, images are typically split into patches and encoded as visual tokens. Higher resolution means more tokens and higher cost. Common practices include:
- Choose a resolution tier based on task requirements instead of always using the highest resolution.
- For large images, crop the region of interest first, then send it to the model.
- Deduplicate images in batch workloads to avoid repeated billing.
Input normalization—such as format validation and limits on dimensions and file size—should be done at the gateway layer. This intercepts invalid input before it reaches the model and avoids wasting compute.
6. Peak/Off-Peak Pricing and Task Scheduling
Resource utilization is usually uneven throughout the day. Deferrable tasks—such as offline batch processing, data labeling, and report generation—can be scheduled during low-load periods, while interactive requests keep the peak-period resources. Peak/off-peak price differences can guide this scheduling, but organizations should estimate the benefit before adjusting.
Below is an illustrative calculation. The numbers are hypothetical and only demonstrate the method. If a batch of tasks totals T units, the peak unit price is p, and the off-peak price is half of p, then migrating a fraction r of the tasks to off-peak hours saves:
Savings = T × r × p × 0.5
The fraction r depends on what share of the tasks can be deferred—it is the key variable determining the benefit.
7. Integration and Smooth Migration
Model identifiers, version numbers, and routing rules should live in configuration, not scattered across business code. The recommended migration process is:
- In a test environment, run regression comparisons between old and new versions on a fixed evaluation set.
- Roll out gradually: switch a small portion of traffic first and observe error rate, latency, and quality metrics.
- Keep a rollback switch so you can quickly revert to the old version if anomalies appear.
- When setting up compatibility routing for legacy identifiers, record the mapping and set a deprecation timeline.
models:default: "model-current"aliases:"model-legacy": "model-current" # compatibility route; record deprecation daterollout:canary_percent: 5 # gradual rollout percentagerollback_to: "model-previous" # rollback target on anomalies
8. How to Evaluate “Better” and “Cheaper”
Claims like “overall superiority” need to be verified dimension by dimension. It is recommended to fix the following metrics under identical conditions:
- Task quality: use evaluation sets relevant to your business rather than relying only on public leaderboards.
- Time to first token and generation speed: record values separately under different input lengths and concurrency levels.
- Unit cost: measure the total cost per completed task rather than only the per-token price.
- Stability: timeout rate, error rate, and retry counts.
Public benchmarks only reflect model performance on specific test items. Business scenarios still require your own validation.
9. Deployment Checklist
- Clarify the cost structure: the share of input, output, cache, and concurrency
- Keep prompt prefixes stable and minimize dynamic fields
- Set KV cache capacity limits and eviction policies
- Select model sizes and image resolutions by task tier
- Build your own evaluation set and regression process
