Long Context and Agent Inference Cost Optimization: Prefill, KV Cache, and Memory Design
This article breaks down the structural costs that appear when AI agents move from single-turn question answering to long-horizon execution, and reviews three optimization paths: asymmetric encoder-decoder designs that cut prefill computation, cross-layer reuse and low-bit quantization that shrink the KV cache, and decoupling factual knowledge into an external memory layer. It also outlines a reference deployment on Baidu AI Cloud and a load-testing checklist covering time to first token, cost per thousand tokens, cache residency, and task success rate.
1. Background: Two Structural Costs in the Agent Era
As agents move from single-turn question answering to long-horizon execution, long context stops being optional and becomes a requirement. A single software engineering task can involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, log fragments, and retrieval results from an entire code repository. Deep research, GUI operation agents, and enterprise workflow automation all need the model to retain and reuse long interaction histories as well.
Under these workloads, the conventional decoder-only architecture exposes two costs:
- Prefill computation cost. With L network layers and a prompt length of N, every layer must scan the full prompt, giving a dominant complexity of roughly O(N·L). The longer the prompt and the more frequent the calls, the harder it becomes to keep time to first token (TTFT) under control.
- KV cache memory and transfer cost. In a conventional implementation, KV is stored separately for each layer. As the context grows, the cache keeps consuming GPU memory and, across multi-turn sessions, triggers搬运-style movement across host memory, local SSDs, and even network links.
The goal of long-context optimization can therefore be abstracted into four “compression dimensions”: the size of a single cache entry, the number of historical positions that actually participate in attention, the cache duplicated across different layers, and the number of layers that must run in full during prefill. Recent approaches in the industry have compressed the resident global cache to roughly 890 bytes per token while supporting context lengths in the millions of tokens.
2. Path 1: Asymmetric Encoder-Decoder Design to Reduce Prefill Computation
The core idea is to let “reading the prompt” and “writing the answer” run through networks of different depths. The encoder side handles shallow representations of the massive prompt tokens, while the decoder side keeps full depth for autoregressive generation.
Take a Mixture-of-Experts (MoE) model with a 552B backbone as an example. Its asymmetric design routes most prompt tokens through only the first half of the network during prefill, dropping the activated parameters per token from about 16B at decode time to about 8B and nearly halving prefill computation. The engineering payoff shows up in three places: lower TTFT, steadier compute usage under long prompts, and easier request queuing and priority scheduling under concurrent batches.
Illustrative pseudocode (scheduling semantics only, not a real API):
# Asymmetric forward pass: shallow layers for the prompt, full layers for generationdef forward(prompt_tokens, max_new_tokens):h = encoder_shallow_layers(prompt_tokens) # activation scale is roughly half of the decode sidecache = build_global_kv(h) # global cache after cross-layer reusefor _ in range(max_new_tokens):h = decoder_full_layers(h, cache) # full-depth autoregressionyield sample(h)
3. Path 2: Cross-Layer Reuse and Low-Bit Quantization for Cache Compression
Cache compression has to work on both “what to store” and “how to store it.”
- Cross-layer reuse: attention keys and values, indexer keys, and Top-K selection results are shared between adjacent layers, avoiding duplicate caching and duplicate index computation. This effectively folds L copies of the cache into a few.
- Low-bit quantization: the main cache uses 4-bit representation, with block-wise scaling factors to control error, which sharply reduces the byte count per entry.
- Sparse selection: only a small number of historical positions actually enter attention, pushing complexity from linear growth in N to something close to bounded.
Combined, these three bring the global cache down from about 3514 bytes per token to about 890 bytes per token, roughly a quarter of the original. Capacity planning can be estimated with:
GPU memory ≈ bytes per token × context length × concurrent sessions × safety factor (1.2–1.5)
4. Path 3: Decoupling Knowledge Memory from Backbone Computation
Externalizing factual knowledge into a separate memory structure while the backbone handles only reasoning and scheduling makes it possible to scale knowledge capacity at a lower activation cost. Three things matter in practice: the consistency policy for memory writes, the impact of retrieval recall quality on answer quality, and the rollback mechanism when memory becomes invalid. For long-horizon tasks, it is advisable to store “task state” and “factual knowledge” separately: the former lives for the duration of a session, while the latter is reused across sessions.
5. Deployment and Validation on Baidu AI Cloud
Recommended architecture: a container platform hosts stateless inference services, object storage holds session snapshots and memory data, a message queue absorbs spikes and smooths tool-call callbacks, and logging plus monitoring and alerting track TTFT, cache hit rate, and memory watermark.
Load testing should cover four workload types: very long single-turn prompts, multi-turn tool-call chains, high-concurrency short sessions, and scenarios with frequent cache swap-in and swap-out. Core metrics include time to first token, cost per thousand tokens, cache residency ratio, and task success rate. If GPU memory is tight, reduce concurrency before truncating context; if latency exceeds target, check prefill batch size and chunking strategy first.
