Long Context and Agent Inference Cost Optimization: Prefill, KV Cache, and Capacity
This article breaks down why agentic workflows shift LLM inference costs away from token generation and toward prefill compute and KV cache storage. It explains three independent architectural optimization paths—asymmetric causal encoder-decoder prefill, cross-layer KV reuse with low-bit quantization and sparse selection, and decoupling knowledge capacity from the backbone—along with the engineering tradeoffs, validation methods, and deployment practices needed to make million-token contexts plannable.
1. Background: Agents Reshape the Cost Structure
When models move from single-turn question answering to long-horizon agentic workflows, the cost center shifts. A real software engineering task can involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, and nearly an entire code repository. Deep research, GUI operation agents, and enterprise process automation similarly require the model to retain and reuse history across many turns. The dominant expense is no longer only the generation stage; it concentrates in two places.
The first is prefill compute. For a model with L layers and a prompt of length N, every layer traverses the full prompt, giving a primary complexity of roughly O(N·L). As the context grows from a few thousand tokens to the million-token range, time-to-first-token degrades almost linearly.
The second is the KV cache. A conventional decoder-only structure stores Key/Value tensors independently for each layer, so the cache grows linearly with context, occupies GPU HBM for long periods, and creates host memory, SSD, and network transfer overhead across multi-turn sessions. The common engineering practice of swapping out to host memory and swapping back in only moves the problem from VRAM to I/O; it does not remove it.
A model built for long context therefore needs to compress four dimensions at once:
- The number of bytes per KV entry;
- The number of historical positions that actually participate in attention;
- The KV duplicated across different layers;
- The number of network layers that must run in full during prefill.
2. Three Optimization Tracks
A certain class of new-generation lightweight flagship models (a mixture-of-experts backbone on the order of 550B total parameters) offers an approach that abstracts into three points: asymmetric compute to reduce prefill work, cross-layer reuse plus low-bit quantization to shrink the cache, and knowledge decoupling to expand capacity. The three are independent and can be borrowed separately.
2.1 Asymmetric Encoder-Decoder Structure: Halving Prefill Work
The core insight is that prefill and decode have different compute demands. Decode processes one token per step and is bottlenecked by memory bandwidth; prefill is throughput-bound and bottlenecked by compute. Running both stages through the same full network means paying a high cost for low-value computation.
An asymmetric causal encoder-decoder lets most prompt tokens pass mainly through the front half of the network during prefill, while only a small number of key positions continue through the full depth. The result is that activated parameters per token drop from roughly 16B in decode to 8B, prefill compute is cut close to half, and generation quality is carried primarily by the full-depth path.
Illustrative pseudocode (expressing scheduling intent only, not any specific API):
# Asymmetric forward pass: prompt segments go shallow, key positions go full depthdef forward(prompt, decoder):shallow = encoder_front(prompt) # most tokens pass only the front halfkeep = select_pivots(prompt, ratio=0.1) # a few key positionsdeep = decoder(shallow, positions=keep) # full depthreturn deep
Engineering benefits: lower time-to-first-token and higher concurrency per unit of compute. The cost is that the model must be trained to adapt to this asymmetric path, or inference will suffer distribution shift.
2.2 Cache Compression: From 3514 to 890 Bytes per Token
Cache compression typically proceeds along three paths at the same time.
Cross-layer reuse: different layers share the same Main KV, shared index keys (Indexer K), and Top-K selection results, avoiding repeated caching and repeated index computation per layer. This removes the “inter-layer redundancy” dimension outright.
Low-bit quantization: the Main KV is stored in FP4, with dequantization completed before attention computation. Global cache per token drops from about 3514 bytes to about 890 bytes, roughly one quarter of the original.
Sparse selection: fine-grained attention is applied only to the Top-K historical positions, while the rest participate as low-precision summaries, reducing the number of positions that truly take part in computation.
Combined, the resident VRAM for a million-scale context can be estimated as:
890 Bytes/token × 1,000,000 token ≈ 890 MB (globally resident portion)
Compared with the multi-kilobyte-per-token range common in unoptimized structures, this difference directly determines whether a single machine can host an extremely long session and whether swap-out and swap-in across turns are still necessary.
2.3 Decoupling Knowledge Capacity: Moving Memory Out of the Backbone
Only a modest share of the parameters is actually used for inference computation; a large portion is static knowledge storage. Decoupling knowledge memory from the backbone in the form of embeddings (Engram) expands knowledge capacity at low activation cost: the backbone keeps a small activation footprint to preserve speed, while the knowledge side is accessed like a lookup table on demand. This shares the same lineage as retrieval augmentation, except that knowledge exists in parameterized form rather than as external documents.
3. Capability Boundaries and Validation
Architectural optimization does not imply a free capability upgrade. Three kinds of validation should be done before production:
- Long-context effectiveness: use needle-in-a-haystack, multi-hop QA, and cross-file dependency analysis to test recall of mid-context information;
- Agent stability: track tool call success rate, repeated call rate, and final completion rate on long-horizon tasks;
- Cost observability: measure prefill duration, decode throughput, cache hit rate, and swap volume separately.
4. Engineering Deployment Recommendations
- Layer the context: put stable information such as repository structure and interface definitions at the front and reuse the cache, and put volatile logs at the end, to improve prefix cache hit rate.
- Govern the output side: structure and trim terminal and build logs before they enter the context; raw output of hundreds of thousands of tokens is often 90% information-free.
- Plan capacity: use “cache bytes per token × context length × concurrency” as the capacity baseline, combined with elastic scaling on a container platform and object storage for session archiving.
- Observability: connect logging services and monitoring alerts, and set thresholds for time-to-first-token, cache hits, and failed retries.
- Migrate incrementally: start with a canary on read-only analysis tasks, then extend to write-operation long-horizon tasks.
5. Conclusion
The essence of long-context cost is “repeated computation plus repeated storage.” Asymmetric structures cut repeated computation, cross-layer reuse and low-bit quantization cut repeated storage, and knowledge decoupling relieves backbone pressure; together they move million-token contexts from “unaffordable” toward “plannable.” For developers, the real payoff is not just a smaller bill, but the ability to hand longer stretches of real working state to the model, reducing the information loss caused by manually splitting context. If managed inference and elastic resources are needed, general container and monitoring capabilities on platforms such as Baidu AI Cloud can be evaluated, but optimization at the model-structure level still needs to be driven by your own business scenario.
