Reducing Long-Context LLM Inference Costs: Core Technical Approaches
This article explains where the cost of long-context and multi-turn agent inference comes from. It then covers three technical directions: reducing prefill computation, compressing KV cache memory, and separating knowledge storage from core computation. For each direction, it describes the underlying principle, a method for estimating its impact, and the engineering trade-offs, and it closes with guidance on evaluation and selection.
Introduction
Long-context inputs and multi-turn agent tasks cause inference costs to rise quickly. The longer the input, the more historical information the model must process, and both memory usage and computation grow accordingly. When selecting and optimizing a system, teams should first identify where the cost comes from, then choose techniques that address that specific source.
This article starts from the basic structure of the inference process and discusses three directions in turn: reducing computation in the prefill stage, compressing the memory used by the Key-Value (KV) cache, and separating knowledge storage from the main computation. Each direction includes an explanation of the principle, a method for estimation, and the engineering trade-offs.
1. Two Sources of Inference Cost
Large model inference typically runs in two stages.
Prefill stage: The model reads all input tokens at once and computes an intermediate representation for each token at every layer. This stage is highly parallel and is mainly limited by compute power.
Decode stage: The model generates output tokens one at a time. To generate each token, it reads the KV cache accumulated so far, so this stage is limited mainly by memory bandwidth.
The two stages have different bottlenecks, so their optimizations should be considered separately. If most requests in a system consist of long prompts and short replies, the prefill cost usually accounts for the largest share. If replies are long, the memory and bandwidth pressure of the decode stage becomes more prominent.
For dense models, the prefill computation can be roughly estimated as:
Prefill compute ≈ 2 × active parameters × input tokens
For Mixture of Experts (MoE) models, only part of the total parameters are active, so the compute cost per token is lower than for a dense model of the same total size. Reducing the number of active parameters per token is therefore one direct way to lower prefill cost.
2. Asymmetric Computation: Letting Input Tokens Pass Through Part of the Network
The traditional approach passes every token through all layers of the network. This design is not always necessary for prompt tokens, because prompts mainly provide context and do not need to produce a complete output distribution.
The idea behind asymmetric computation is to split the network into a front part and a back part, and to treat the two types of tokens differently:
- During prefill, most input tokens pass only through the front part of the network, which produces the intermediate representations needed.
- Tokens that must produce an output distribution, along with the generation process in the decode stage, pass through the full network or the back part of the network.
This split provides two benefits. First, the compute per prefill token drops, which reduces the total compute. Second, the front part of the network can handle much of the general context encoding, while the back part focuses on the reasoning related to generation.
When adopting this design, pay attention to the following points.
- Match the training method: If the model was trained with every token passing through the full network, forcibly truncating the computation at inference will degrade quality. The front and back division must be applied during training.
- Define the routing logic clearly: The inference engine must determine which tokens take the short path and which take the full path, and it must ensure that the state passed between the two paths stays correct.
- Evaluate on long contexts: Focus testing on scenarios such as long-document question answering and cross-paragraph reasoning, to confirm that truncation does not impair the use of key information.
The routing logic can be represented with the following pseudocode:
function forward(tokens, phase):hidden = embed(tokens)for layer in front_layers:hidden = layer(hidden)if phase == PREFILL and not needs_logits(tokens):store_context_state(hidden)returnfor layer in back_layers:hidden = layer(hidden)return output_head(hidden)
This code only illustrates the control flow. The actual implementation depends on the model architecture and the inference framework.
3. KV Cache: The Memory Bottleneck and Compression Methods
3.1 Estimating Memory Usage
The attention mechanism stores two sets of vectors, Key and Value, for each token at each layer. The KV cache size per token can be estimated with the following formula:
Bytes per token = 2 × layers × KV heads × head dimension × bytes per element
As an example, consider a hypothetical configuration with 60 layers, 8 KV heads, a head dimension of 128, and 16-bit floating-point storage (2 bytes per element). Each token then occupies approximately:
2 × 60 × 8 × 128 × 2 = 245760 bytes ≈ 240 KB
For a context length of 128K tokens, the total usage is about 30 GiB. This figure shows that adding more GPUs alone cannot indefinitely support long contexts. The cache itself must be addressed.
3.2 Cross-Layer Reuse
In the attention computation of adjacent layers, some intermediate results are similar. For example, different layers can share the same set of KV representations, or reuse the results of the same sparse attention indexing. Reuse can reduce two kinds of overhead:
- The amount of KV data written and stored repeatedly;
- The number of times Top-K selection or indexing must be recomputed at each layer.
The cost of reuse is a constraint on model expressiveness. When layers share information, each layer can no longer learn its own independent attention patterns. For this reason, the reuse strategy is usually determined during training and verified with long-context benchmarks.
3.3 Low-Precision Compression
Compressing the KV cache from 16 bits to 8 bits or 4 bits can reduce storage to one half or one quarter of the original size. Common methods include:
- Grouped quantization: Vectors are split into fixed-length groups, and each group uses its own scaling factor, which reduces quantization error.
- Mixed precision: Precision-sensitive layers or heads keep a higher bit width, while the rest use lower precision.
- Dequantization timing: Values are restored when attention is computed, or the computation is performed directly with low-precision kernels.
Low-precision compression introduces error, and the error accumulates with the number of layers and the context length. During validation, compare the output differences between the original and compressed precision, paying attention to numerical stability and the preservation of long-range dependencies.
The following function estimates the benefit of compression:
function cache_bytes(tokens, layers, kv_heads, head_dim, bits, shared_layers):effective_layers = layers / shared_layersbytes_per_elem = bits / 8return tokens * 2 * effective_layers * kv_heads * head_dim * bytes_per_elem
Changing bits from 16 to 4 and setting shared_layers to 2 theoretically reduces the cache to one eighth of its original size. The actual savings must account for quantization parameters, index structures, and runtime overhead, so measured data should be the final reference.
4. Knowledge Decoupling: Separating Memory from Core Computation
Model capability has two components: reasoning performed by the core network, and factual knowledge stored in the parameters. In the traditional approach, both rely on the same set of parameters. Increasing knowledge capacity therefore means increasing the size of the core network and the compute per token.
Knowledge decoupling designs a separate storage structure for knowledge. The core network then reads a small number of relevant entries on demand. This approach can expand knowledge capacity without significantly increasing the number of active parameters per token.
The key issues for these methods include:
- Retrieval quality: Whether the selected entries are accurate directly determines how well the knowledge is used.
- Read latency: Additional storage access can increase tail latency, so it must be designed together with inference scheduling.
- Update method: Once knowledge storage is independent, incremental updates and version management need separate design.
These approaches are especially valuable for scenarios that require large amounts of domain knowledge but have limited inference budgets. When evaluating them, measure both the accuracy of factual question answering and the change in latency per request.
5. Engineering Deployment: Selection and Evaluation
The three technical directions target different bottlenecks. The following table can guide selection.
| Technique | Main Benefit | Main Cost | Typical Risk |
|---|---|---|---|
| Asymmetric computation | Lower prefill compute | Requires training alignment and complex routing | Degraded long-text understanding |
| Cross-layer cache reuse | Fewer cache writes and index computations | Limited expressiveness across layers | Lower accuracy on specific tasks |
| Low-precision cache | Lower memory usage | Accumulated numerical error | Distorted long-range dependencies |
| Knowledge decoupling | Larger knowledge capacity | More storage and retrieval systems | Retrieval errors and higher tail latency |
When evaluating, it is recommended to track the following metrics:
- Time to First Token (TTFT): Reflects prefill efficiency, and is most sensitive in long-prompt scenarios.
- Time Per Output Token (TPOT): Reflects decode-stage efficiency.
- Throughput: The number of requests or tokens completed per unit of time.
- Unit cost: Compute and memory cost converted to a per-million-token basis.
- Quality metrics: Accuracy on tasks such as long-document question answering, code repair, and multi-step tool calling.
Tests should use a request distribution close to live traffic and cover short inputs, long inputs, and mixed workloads. Looking only at a single benchmark score can hide degradation that appears in real scenarios.
6. Special Considerations for Agent Scenarios
Agent tasks usually involve multiple rounds of calls, and each round carries a large amount of historical context. This workload has two characteristics: high prompt repetition and a large share of prefill cost.
For this reason, the following strategies can be used together:
- Prefix caching: Build a cache for system prompts and fixed tool descriptions, so that later requests that hit the cache skip repeated computation.
- Context compression: Periodically summarize the conversation history, keeping key conclusions and open tasks while removing unnecessary tokens.
- Tiered storage: Keep recent context in high-speed GPU memory, and move older content to larger-capacity storage tiers.
These strategies must work together with the capabilities of the underlying inference system. Before choosing them, measure the prefix reuse rate of live requests, then estimate the caching benefit.
7. Practical Recommendations
- Use monitoring data to determine whether the bottleneck is in the prefill or decode stage, to avoid optimizing blindly.
- Use the memory estimation formula to calculate the cache footprint at the target context length, and confirm that the hardware meets the requirement.
- Introduce one technique at a time, and compare quality and performance against a baseline each time, so that multiple changes do not mask each other’s effects.
- Build a long-context regression test set for compression and reuse methods, covering key business scenarios.
- Include cost metrics in the daily dashboard, and track optimization results continuously.
Inference optimization for long-context and agent scenarios is fundamentally a trade-off among compute, memory, and quality. Identifying where the bottleneck lies, choosing matching techniques, and verifying results with a reliable evaluation system are the basic steps for controlling cost.
