Optimizing Long-Context and Agent Inference Costs
This article breaks down the dual cost pressures introduced by AI agents—Prefill computation and KV Cache overhead—and outlines three general optimization paths: asymmetric encoder-decoder computation, cache compression with cross-layer reuse, and decoupling knowledge capacity from backbone computation. It also covers layered evaluation metrics, capacity estimation, scenario validation, and cloud-side practices for serving long-context workloads.
1. Background: The Dual Cost Pressure of Agentic Workloads
As agent capabilities grow, the context length a model must process continuously expands rapidly. A single end-to-end software engineering task may involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, and codebases approaching full repository scale. Deep research, GUI operation agents, and enterprise workflow automation similarly require models to retain and reuse historical information across many interaction turns.
A traditional decoder-only Transformer architecture exposes two primary costs under these workloads.
The first is Prefill computation. With L network layers and a prompt length of N, every layer must traverse the full prompt, giving a primary computational complexity of roughly O(N·L). As N grows from a few thousand to hundreds of thousands, time-to-first-token degrades almost linearly.
The second is the KV Cache. Conventional implementations store separate key-value caches for each layer, continuously consuming device memory as context grows and causing additional transfer overhead across host memory, local storage, and network links during multi-turn sessions.
Given this, long-context optimization can be broken into four directions that can be addressed independently: shrinking the size of each cache entry, reducing the number of historical positions that actually participate in attention computation, eliminating redundant per-layer cache storage, and lowering the number of layers that must run in full during Prefill.
2. General Optimization Path 1: Asymmetric Encoder-Decoder Computation
One mainstream approach adds a shallower encoding segment in front of the backbone, so most prompt tokens pass through only the first half of the network during Prefill while a small number of key positions continue through the full depth. The effect is roughly equivalent to halving the average number of activated parameters per token during Prefill relative to decoding, bringing first-request computation close to a 50% reduction.
The illustrative pseudocode below focuses on the idea of routing by position rather than any specific API:
# Pseudocode: illustrates position-based routing for asymmetric computationdef prefill(states, depth_split):for layer in encoder_layers: # Shallow layers: process all prompt positionsstates = layer(states)keep = select_key_positions(states) # Select by attention or index-based scoringdeep = states[keep]for layer in decoder_layers: # Deep layers: process only selected key positionsdeep = layer(deep)return merge(deep, keep)
Three engineering points matter here. First, the selection strategy must align with the training objective; otherwise, missing deep-layer information degrades quality. Second, the split boundary (the shallow-to-deep layer ratio) needs tuning against the task distribution. Third, time-to-first-token and throughput should be evaluated separately, since the mechanisms affecting each are different.
3. General Optimization Path 2: Cache Compression and Cross-Layer Reuse
Cache-side optimization typically compresses along three dimensions at once.
- Entry compression: Store the main cache at a lower bit width (around 4 bits), combined with group-wise quantization and outlier protection, cutting resident memory per token to roughly one quarter of the original.
- Structural simplification: Use sparse or block attention to limit the number of historical positions that actually participate in computation, and maintain lightweight keys and scoring results separately for the index structure.
- Cross-layer reuse: Different layers share the same main cache, index keys, and Top-K selection results, avoiding duplicate caching and duplicate index computation.
Stacked together, these reduce the global cache from thousands of bytes per token to the hundreds of bytes per token range. Estimating at 1M context, resident memory demand drops from multiple GB to around 1GB. This directly determines whether a single card can host a long session, and whether multi-turn sessions can offload history to host memory or object storage without incurring unacceptable retransmission costs.
4. General Optimization Path 3: Decoupling Knowledge Capacity from Backbone Computation
Compression alone cannot extend a model’s knowledge ceiling. One general approach separates knowledge memory from backbone computation, using a sparse, lookup-table-style structure to hold a large volume of low-frequency facts while the backbone handles only reasoning and composition. The advantage is that expanding knowledge capacity adds very little activation overhead; the cost is more complex memory writing, updating, and consistency management, requiring supporting memory lifecycle policies and invalidation mechanisms.
5. Implementation Guidance and Evaluation Criteria
- Layered evaluation: Report time-to-first-token, decode throughput, cache bytes per token, and long-context task accuracy separately, avoiding a single metric masking regressions.
- Capacity accounting: Estimate memory as “cache bytes per token × context length × concurrency,” then add weight and temporary activation overhead.
- Scenario validation: Prioritize regression testing on long-horizon agents, repository-level code understanding, and deep research tasks.
- Cloud-side support: Using a container platform to host inference services, object storage to persist session history, and logging and monitoring with alerting to track latency and memory watermarks can significantly reduce the operational complexity of long-context services. The general capabilities of Baidu AI Cloud can serve as a reference selection direction.
