Long Context and Agent Inference Cost Optimization Explained
This article breaks down why inference costs change structurally in the Agent era and examines three engineering approaches to long-context optimization: an asymmetric encoder-decoder design that reduces prefill computation, cross-layer reuse combined with low-precision quantization to compress the KV cache, and decoupling knowledge memory from the backbone network. It includes capacity estimation examples, pseudocode, and a practical optimization sequence for long-context and Agent workloads.
1. Background: How Inference Costs Change Structurally in the Agent Era
As agents move from single-turn question answering to long-horizon task execution, the context size a model must carry changes by orders of magnitude. A complete software engineering task may involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, and key fragments of an entire code repository. Deep research agents, GUI-operating agents, and enterprise automation workflows face the same pressure: the model must retain and reuse historical information across many interaction turns.
Under this load, a traditional decoder-only Transformer exposes two main costs.
The first is prefill computation cost. With L network layers and a prompt length of N, every layer performs a forward pass over the full prompt, so overall complexity grows roughly as O(N·L). The longer the context, the harder it becomes to control time to first token (TTFT).
The second is the storage and data movement cost of the KV cache. In a conventional implementation, key-value caches are stored separately for each layer. As the context grows, the cache continuously occupies GPU high-bandwidth memory (HBM), and in multi-turn sessions it further triggers transfer overhead across host memory, SSDs, and network links. The larger the cache, the fewer concurrent sessions are possible, and the higher the cost per request.
Given this, long-context optimization can be broken into four directions that can be addressed independently:
- Reduce the number of bytes in a single KV entry;
- Reduce the number of historical positions that actually participate in attention computation;
- Eliminate KV data that is redundantly stored across different layers;
- Reduce the number of layers that must be fully executed during prefill.
A recently released 552B-parameter mixture-of-experts (MoE) backbone model was designed along these lines. According to its official description, it can compress the global KV cache resident in HBM to roughly 890 bytes/token and supports a context length of up to 1M tokens. The sections below abstract its architectural highlights into a general engineering pattern.
2. Path 1: An Asymmetric Encoder-Decoder Structure to Reduce Prefill Computation
The core idea is to introduce the asymmetric computation of a causal encoder-decoder (CED): during prefill, most prompt tokens pass mainly through the first half of the network, and only a smaller set of tokens needs to traverse all layers.
As a result, the number of activated parameters per token drops from about 16B during decoding to about 8B, and prefill computation is nearly halved. For engineering practice, this means:
- TTFT drops significantly, with clear perceived improvements in scenarios such as long-document summarization and repository-level code understanding;
- The compute ratio between prefill and decode shifts, so batching strategies need to be re-evaluated at deployment time;
- Because the second half of the network applies to only a small subset of tokens, operator implementations must support variable lengths and masking to avoid wasting compute on alignment.
Illustrative logic (not a specific API):
# Pseudocode: skeleton of asymmetric prefilldef prefill(tokens, layers, boundary):front = layers[:boundary]back = layers[boundary:]h = front.run_all(tokens) # all tokens pass through the front halfkeep = select_tokens(h, ratio=0.1) # only a small subset continuesh2 = back.run(keep, h[keep]) # the back half processes the subset onlyreturn merge(h, h2, keep)
3. Path 2: Cross-Layer Reuse and Low-Precision Quantization to Compress the KV Cache
The second optimization is completed by two parts working together.
The first is a cross-layer reuse mechanism (referred to as CSA2 in the source material): the main KV, the indexer keys (Indexer K), and the Top-K selection results are shared across layers, avoiding repeated caching and repeated index computation at every layer. Sparse attention already reduces the number of historical positions involved in computation, and cross-layer reuse goes further by turning the “selection results” into a shared asset as well.
The second is a low-precision main cache (FP4 Main KV Cache). Combined, the two bring the global KV cache down from about 3514 bytes/token to about 890 bytes/token, roughly a quarter of the original.
This makes capacity estimation straightforward:
total cache ≈ number of tokens × bytes per token × concurrent sessions1M tokens × 890 B ≈ 890 MB / session (single replica)
This means that with the same memory budget, the number of concurrent long sessions that can be supported increases severalfold, and more multi-turn history can be kept at the memory tier, reducing swap-in and swap-out to host memory and external storage. The tradeoff to note is that a low-precision cache may introduce slight accuracy loss, so before launch, regression evaluation should be run on sensitive tasks such as long-document retrieval and numerical reasoning.
4. Path 3: Decoupling Knowledge Memory from Backbone Computation
The third design (Engram) separates knowledge memory from backbone computation and expands knowledge capacity at a lower activation cost. Its approach differs from the traditional assumption that “parameters are memory”: high-frequency factual knowledge is placed in an independently addressable memory structure, while the backbone network is responsible only for reasoning and composition.
The benefits include: total model capacity grows while per-token activation overhead stays largely controllable; knowledge updates do not require retraining the backbone; and in vertical domains, adaptation can be achieved by expanding memory rather than enlarging the network. In terms of implementation, this type of capability can naturally combine with common industry offerings such as retrieval augmentation, vector retrieval, object storage, cache services, and logging and monitoring alerts, forming an operable knowledge update pipeline.
5. Practical Recommendations and Summary
For long-context and Agent workloads, the recommended optimization order is:
- Establish a baseline first: measure P50/P95 TTFT, peak tokens per session, cache usage, and concurrency;
- Then compress the cache: prioritize cross-layer reuse and low-precision KV, which offer the most direct gains;
- Next, cut prefill: evaluate whether an asymmetric structure or layered execution fits your prompt distribution;
- Finally, decouple knowledge: move stable facts out of the backbone to reduce the dependence of long context on parameters.
In summary, the asymmetric structure reduces prefill computation, cross-layer reuse and low-precision quantization compress the KV cache, and memory decoupling expands knowledge capacity efficiently. Together, the three let complex reasoning, software engineering, and long-horizon agent tasks achieve a better balance between cost and capability. On platforms such as Baidu AI Cloud, however, this type of optimization typically needs to be implemented alongside monitoring and alerting, logging services, and elastic container resources in order to turn architectural gains into stable business gains.
