Long-Context Inference: Compute and Cache Optimization for LLM Agents
Long contexts have become a primary cost driver for LLM inference, especially in software engineering and research agent workloads that repeatedly append tool outputs, terminal logs, web text, code, and documents. This article presents a model-agnostic framework for reducing long-context cost across four levers: shrinking each cache entry, limiting the historical positions that actually participate in attention, reusing cache across layers, and avoiding full-depth prefill on every layer. It covers the cost model, asymmetric prefill, cross-layer KV reuse, sparse attention, low-precision residency, external memory, system scheduling, and an evaluation plan that combines efficiency, recall, task success, and degradation checks.
Long contexts have moved from a “can it fit in the window” feature to a primary cost center for inference systems. A single software engineering or research agent task often involves multiple rounds of tool calls, large amounts of terminal and web text, and code and documents that must be revisited repeatedly. Context is not a static appendix; it is growing working memory. If we still use a conventional decoder-only Transformer for full prefill and store a complete key-value cache for every layer, accelerator memory, host memory, and cross-node transfer all rise together. Latency and cost grow roughly linearly with length, or even faster.
This article narrows the problem to four levers: shrink each cache entry, reduce the historical positions that actually participate in attention, eliminate duplicate caching across layers, and avoid running every layer to full depth during prefill. The discussion below covers cost, mechanisms, and engineering deployment, and is not tied to a specific model family.
Where the Cost Comes From
Let the network have L layers and the prompt length be N. The dominant complexity of conventional prefill can be written as O(N·L): every token passes through all layers. During decoding, only a small number of new tokens are generated each step, but the keys and values already materialized from history must be read. Therefore, the bill for long context usually splits into two parts.
The first part is prefill compute. As N grows from tens of thousands to hundreds of thousands of tokens, time to first token and batched throughput are consumed first by this stage. Agent scenarios are more difficult: tool results are often inserted later in the conversation, so the system cannot assume that prefill happens only once.
The second part is the KV cache. If every layer stores its own cache, cache capacity is roughly proportional to N·L·d, where d is a width related to the head dimension. This consumes high-bandwidth accelerator memory and reduces the number of concurrent sessions. Across turns, cache must also be paged between host memory, local disk, and the network. If a globally resident cache is accounted for by fixed bytes per token, then as length grows, the concurrency ceiling is limited by cache rather than by parameter count.
The design target can be framed as a rough budget rather than a chase for a single metric:
prefill_cost ≈ c_compute * N * L_fullkv_bytes ≈ N_resident * bytes_per_tokenbytes_per_token ≈ layers_stored * heads * dim * bytes_per_elem* reuse_factor * precision_factor
Only when L_full is less than the total number of layers, the reuse factor is below 1, and elements move from high precision to low precision do the three terms multiply into order-of-magnitude headroom. Compressing only one term is often offset by another.
Prefill: Asymmetric Compute
One effective approach is to split the network into an encoder side and a decoder side and use them asymmetrically. During prefill, most tokens in the historical prompt pass only through the first half or a set of shallower blocks, producing representations that later attention can read. During actual generation, current tokens still follow a deeper path with more active parameters. This reduces the active parameters and matrix multiplications per prompt token, so prefill compute can shrink roughly in proportion to the layer ratio, while decoding quality is still backed by full depth.
This is not the same as simply bolting an encoder and a decoder together. There are three key constraints.
- Causality cannot break. Prompt tokens may only see themselves and earlier positions; otherwise multi-turn dialogue and tool insertion would leak future information.
- Shallow representations must be readable by deep attention. If the first half of the network does not produce stable KV or an equivalent index, the compute saved in the later half will be added back in attention.
- The boundary must be configurable. Code symbols, system prompts, and recent tool results are usually more sensitive than distant background. A tail window can use full layers, while long-tail background can use the shallow path.
In engineering, the full-layer ratio should be an explicit knob rather than a hard-coded value. For short contexts, the compute savings are limited and scheduling overhead may outweigh the benefit. Asymmetric prefill becomes more attractive beyond tens of thousands of tokens. During evaluation, measure time to first token, prefill throughput, and task success rate under the same decode budget separately, rather than reporting only the compute reduction.
Cache: Store Less, Reuse, and Lower Precision
Cache optimization usually combines three techniques.
Cross-layer reuse. Keys in adjacent layers, as well as index vectors used for retrieval, are often highly correlated. If multiple layers share the same primary KV cache and the same Top-K selection results, there is no need to store one copy per layer or compute the index separately for each layer. Reuse causes some loss of expressiveness, so it is better suited to middle layers; layers near the input and output can keep independent caches.
Sparse attention. Not every historical position enters the attention of the current query. A lightweight index first selects Top-K positions, and main attention is then computed only over those positions, reducing the historical length that participates in computation from N to K. K should vary by task: code jumps and long-chain reasoning need larger K, while chat summaries can use a smaller K. If selection results can be reused across layers, the cost of indexing itself also falls.
Low-precision residency. Moving the primary KV cache from half precision to a low precision such as 4-bit can greatly reduce bytes per element and therefore resident accelerator memory. Low precision must use scaling factors or group quantization; otherwise outliers can corrupt attention scores. A common compromise is to keep the index at higher precision for recall, use low precision for the primary KV cache to save capacity, and recompute or correct the few positions hit during decoding at higher precision on demand.
The product of these three techniques determines the global cache bytes per token. Layer reuse reduces layers_stored, sparse indexing determines how many positions must remain on the hot path, and low precision reduces bytes_per_elem. It is important to evaluate compression ratio together with task metrics. If the cache becomes smaller but key evidence is often not recalled, the agent will repeatedly call tools or produce incorrect patches, and total cost may rise rather than fall.
Decoupling Knowledge Capacity from Main-Activation Compute
Long context addresses the working memory for the current task; knowledge in parameters addresses what the model already knows. If all new knowledge is stuffed into the backbone and activated at every step, parameter count and per-token compute rise together. A cleaner approach is to place large-capacity memory in an external table or side module that can be retrieved on demand: the backbone still handles reasoning and tool use, while the memory module provides facts and code conventions at lower activation cost.
Three points matter in deployment. Memory updates must be traceable to avoid silent overwrites that make results non-reproducible. Retrieval keys must be coordinated with cache indexes so that two separate Top-K mechanisms do not conflict. Evaluation should distinguish between “the context clearly contains it but the model did not read it” and “the model does not have this knowledge in its parameters.” The former is a cache and attention problem; the latter is a memory capacity problem.
System Integration
Model architecture determines only bytes and operators; production cost depends on scheduling.
Separate hot data from cold data. The recent window and current tool results can stay in accelerator memory; older global cache can be placed in host memory. In cloud environments such as Baidu AI Cloud, colder session snapshots can go to object storage, a container platform can launch instances per session, and logging and monitoring can track prefill time, cache hits, and swap bandwidth. This uses generic object storage, containers, and observability capabilities, not a proprietary interface.
Budget by session, not by request. An agent appends context multiple times within one round. If cache is reserved for the maximum window every time, concurrency capacity will be filled by holes. Capacity should grow dynamically based on used tokens and compressed bytes per token, with caps and eviction policies: drop tool outputs already replaced by summaries first, and retain user constraints, stack traces, and uncommitted code diffs.
Transfer must be included in the cost model. If cache is moved between nodes across turns, the network bytes are roughly equal to the resident cache size. Compressing bytes per token helps not only accelerator memory but also migration and recovery speed.
How to Evaluate Whether It Actually Improves
Do not look only at compression ratio. At minimum, use four comparison groups, with prompt distributions close to real agent traffic.
- Efficiency: prefill token throughput, time to first token, accelerator memory per concurrent session, and cache swap-in time.
- Recall: insert constraints or defect descriptions that must be cited in ultra-long contexts, and measure the ratio of correct citations.
- Tasks: success rate and average number of tool calls for bug fixing, cross-file modification, and multi-step research question answering.
- Degradation: whether low precision and shallow prefill increase repetition, missed reads, or formatting errors.
Controls should fix decode length and sampling method. If tool calls increase after compression, the model is using external interaction to compensate for failures in reading context, and the bill shifts to tools and the network.
Boundaries and Misuse
Asymmetric prefill is not suitable for very short requests. Sparse attention may miss evidence when a task requires global exact counting or whole-repository symbol consistency checks; for those subtasks, increase K or temporarily disable sparsity. Low-precision caches should be monitored for score overflow and outlier ratio. When cross-layer reuse is too aggressive, deep layers no longer have an independent retrieval space, and complex reasoning degrades before casual chat does.
These techniques are interacting knobs, not a free lunch that can be stacked without limit. A reasonable order is usually: first measure cache bytes per token and the number of prefill layers, then introduce reuse and low precision, and finally tune sparsity and the shallow-layer ratio back using task recall.
Conclusion
Long context and agents shift cost from “how large are the parameters” to “how much compute and storage each historical token requires.” Asymmetric prefill reduces prompt-side layer compute, cross-layer reuse and low-precision compression reduce global cache, and external memory expands knowledge at low activation cost. Together, these approaches can keep both quality and cost under control in complex reasoning, software engineering, and long-horizon tool use. Before launch, validate with accelerator memory, recall, and task success rate jointly; that is closer to real benefit than claiming a compression multiple alone.
