Long Context and Agent Inference Cost Optimization: Prefill, KV Cache, and Memory Decoupling
This article breaks down the two structural costs that emerge when models move from single-turn Q&A to long-horizon agent tasks: prefill computation and the key-value cache. It then walks through three optimization lines—an asymmetric causal encoder-decoder design that roughly halves prefill work, cross-layer cache reuse combined with low-bit quantization, and decoupling factual memory from the backbone network—and closes with a reusable capacity estimation framework, deployment recommendations, and observability practices for validating the gains in your own environment.
## 1. Background: Two Hard Costs in the Agent Era
As models move from single-turn question answering to long-horizon task execution, context length stops being an optional feature and becomes an infrastructure requirement. A real software engineering task may involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, and the contents of an entire repository. Deep research tasks, GUI-operating agents, and enterprise automation workflows have the same need: the model must retain and reuse historical information across many turns of interaction.
A conventional decoder-only Transformer runs into two structural costs in these scenarios.
The first is prefill computation. For a model with L layers and a prompt of length N, every layer must traverse all N positions, so the dominant complexity is roughly O(N·L). The longer the context, the higher the time to first token—and unlike decoding, this cost cannot be amortized per token.
The second is the key-value (KV) cache. In a typical implementation, each layer stores its own key and value tensors. As the context grows, the cache keeps consuming GPU memory and triggers a chain of secondary costs in multi-turn sessions: host memory, local disk, and network transfer. When the cache no longer fits, the system is forced into swapping, and latency jitter amplifies sharply.
Optimizing architectures for long context therefore means compressing four dimensions at once: the byte size of a single cache entry, the number of historical positions that actually participate in attention, the cache duplicated across layers, and the number of layers that must run in full during prefill.
2. Optimization Line 1: Asymmetric Encoder-Decoder Structure to Cut Prefill Compute
A simple but effective observation: most prompt tokens only need to be “understood once” and do not need to participate in token-by-token autoregressive generation. Building on this, the industry has begun adopting a Causal Encoder-Decoder approach that makes the compute path asymmetric.
The idea is that most prompt tokens pass through only the first half of the network during prefill, while a few critical positions—or the parts that need fine-grained modeling—continue through the full depth. As a result, the number of activated parameters per token drops from roughly 16B at decode time to roughly 8B, cutting prefill computation close to half.
Three engineering constraints matter:
- Causality preservation: the encoding in the first half must be strictly causal to avoid leaking future information, which would otherwise hurt reproducibility and cache consistency.
- Semantic bottleneck design: information passing between the two halves acts as an information bottleneck, so projection dimensions and normalization strategies must control information loss.
- Train-inference consistency: the asymmetric path must exist during training, or inference will show clear distribution shift.
Illustrative pseudocode (structure only, not tied to any specific implementation):
# Asymmetric forward: the first half processes the full prompt,# the second half only processes the necessary positionsdef asymmetric_forward(prompt_hidden, keep_mask):h = encoder_half(prompt_hidden) # causal encoding over all prompt positionsbottleneck = compress(h) # information bottleneck compressionselected = select_positions(h, keep_mask)return decoder_half(bottleneck, selected) # full depth only for necessary positions
3. Optimization Line 2: Cross-Layer Reuse and Low-Bit Quantization of the Cache
Even with faster prefill, the cache remains the main source of memory pressure in long context. Two directions are usually pursued together.
Cross-layer reuse. If adjacent layers attend to history in highly similar ways, there is no need to store a separate copy per layer. Common approaches include keeping a single main cache shared across layers, reusing the indexer key (Indexer K) across layers, and sharing Top-K position selection results across layers to avoid repeated index computation. This reduces both duplicated cache and duplicated addressing overhead.
Low-bit quantization. Storing the main cache at a lower bit width (for example, in the FP4 range) can compress the global per-token cache from thousands of bytes to about a quarter of that—for instance, from roughly 3514 bytes down to roughly 890 bytes. Supporting measures are needed: reserve a few high-precision channels for outliers, calibrate quantization error layer by layer, and monitor shifts in the attention distribution under long context.
Combined, the resident global cache can stay in the range of a few hundred bytes per token, which makes million-token contexts a discussable proposition under limited GPU memory.
4. Optimization Line 3: Decoupling Knowledge Memory from the Backbone
Long context does not mean a large amount of knowledge. Forcing factual knowledge into backbone parameters raises activation overhead at the same time. A better solution is to externalize knowledge memory into a separate structure (often described in the industry as a memoized embedding table–style design), expanding knowledge capacity at a lower activation cost while the backbone handles only reasoning and scheduling.
The direct benefit of this decoupling: expanding knowledge no longer pushes up the activated parameters of a single forward pass linearly, and it becomes easier to add, remove, and gradually roll out memory per business domain. The cost is a longer retrieval path, which needs cache hit-rate monitoring and fallback strategies.
5. Capacity Estimation: Doing the Math Yourself
A reusable estimation framework for quantitative decisions during selection:
GPU memory ≈ global cache bytes/token × context length × concurrency + resident weights + peak activationsTime to first token ≈ prefill compute / effective throughput + scheduling and queueing overhead
“Global cache bytes per token” is the most sensitive variable: dropping it from thousands of bytes to hundreds is equivalent to serving several times more concurrency with the same GPU memory.
6. Deployment Recommendations
- Tiered caching: keep hot data in GPU memory, warm data in host memory, and cold data in object storage or on local disk, with monitoring and alerts on the swap-in/swap-out ratio.
- Context governance: apply structured trimming and summarization to terminal output and log-like content to cut useless tokens.
- Unified benchmarking methodology: fix the input length distribution and concurrency gradient, and record prefill and decode latency separately rather than reporting only averages.
- Capability observability: bring cache hit rate, quantization error metrics, and retrieval fallback counts into the standard dashboard.
7. Conclusion
For long-context and agent inference optimization, the core is not any single trick but the coordination of three lines: compute less in prefill, store less cache, and externalize knowledge. If an organization wants to validate similar gains in its own environment, it can build a benchmarking and tuning loop on top of general-purpose capabilities such as the container platform, object storage, and monitoring and alerting offered by Baidu AI Cloud—making architecture decisions with data rather than with spec sheets.
