Reducing Computation and Cache Costs in Long-Context Inference
As AI agents handle growing interaction histories, long-context inference introduces significant structural costs in prefill computation and key-value (KV) cache storage. This article explores practical strategies to mitigate these challenges, including asymmetric computation, KV cache compression via low precision and sparse attention, cross-layer sharing, and decoupling external knowledge memory. It also provides a system design checklist and guidance on evaluating the ROI of these optimizations for long-context LLM applications.
As coding assistants, deep retrieval, and GUI-operating agents enter production environments, models no longer face short prompts but continuously growing interaction histories: multiple tool calls, large terminal outputs, entire repository codes, and multi-round revision logs. As context lengthens, latency, VRAM, and cross-machine transmission rise simultaneously. Blaming this solely on “bigger models being more expensive” is inaccurate. More critically, there are two types of structural costs: repeated computation over the entire history during the prefill phase, and retaining a copy of the key-value (KV) cache for every layer.
1. The Real Cost Structure of Long-Context Scenarios
Traditional decoder-only Transformers, with a prompt length of N and network depth of L, must process all tokens at each layer during prefill, leading to a dominant complexity of O(NL). As N grows from thousands to hundreds of thousands or millions, this computation becomes a bottleneck before decoding even begins. The “slow first token” experienced by users is often due to prefill queuing, not the word-by-word generation itself.
KV cache pressure also grows linearly. If every layer and every historical position stores independent keys and values, the cache size is proportional to the number of layers, heads, head dimensions, and context length. It not only occupies accelerator high-bandwidth memory (HBM) but also incurs CPU memory, disk, and network copies during multi-turn sessions, request migration, and prefix reuse. Agent tasks are particularly disadvantaged: tool returns are often long, yet only a few positions will be repeatedly attended to in subsequent inference.
Therefore, compression targets must fall simultaneously on four quantities: the bytes per cache entry, the number of historical positions actually participating in attention, the duplicated state saved across layers, and the network depth that must be fully executed during prefill. Optimizing only one of these typically cannot simultaneously improve latency and VRAM usage.
2. Reducing Prefill with Asymmetric Computation
An actionable approach is to apply different computation depths to the prompt side and the generation side. Most prompt tokens primarily serve the role of “being read by subsequent queries” and do not need to be fully activated through the entire backbone at every layer. The network can be viewed as two segments: the front segment encodes all prompts into a retrievable state, while the back segment performs full computation only on tokens currently being generated or requiring fine-grained reasoning. Thus, the activation parameters and matrix multiplication scale for prompt tokens can be significantly lower than for decoding tokens.
This asymmetry is not simply about skipping a few layers. Three things must be ensured. First, the representations output by the front segment must be stable enough for the back segment’s attention to locate key evidence. Second, causal boundaries must not be broken; subsequent text cannot see future tokens prematurely. Third, new context appended after tool calls should be incrementally encoded rather than re-computing the entire segment each time. In practice, this is often paired with prefix caching: unchanged history retains only its encoded state, while newly grown terminal outputs or patches enter the prefill phase.
The trade-offs must also be clear. If shallow encoding is over-compressed, complex code dependencies, long-chain mathematical derivations, and cross-file symbol references will degrade. A more reasonable approach is to route tokens by role: system instructions, the current question, and recent rounds maintain deeper computation; earlier logs, repeated stack traces, and low-information-density outputs take the shallow path. Routing strategies should be observable and replayable to avoid inexplicable online behavior.
3. Compressing KV Cache: Precision, Selection, and Cross-Layer Reuse
Cache volume can be reduced from three orthogonal directions.
Low-Precision Storage: Key-value pairs do not necessarily need to reside in VRAM at the high precision used during training. A common industry practice is to apply group-wise quantization before writing to the cache, and then de-quantize during attention read or compute directly on low precision using specialized kernels. Dropping from half-precision to 4-bit reduces the volume to roughly a quarter, but outlier channels, rotary position embeddings, and attention scaling must be handled separately, otherwise numerical drift is more likely in the latter half of long sequences. A small set of high-precision anchor points or periodic recalibration should be retained rather than unprotected quantization throughout.
Sparse Attention: Not every historical position is worth entering subsequent attention. A lightweight index can be used to estimate relevance first, retaining only high-scoring positions per layer or segment, and then applying main attention to this batch. This reduces the “historical length participating in computation,” not just the bytes per entry. Indexing itself has a cost; if re-selected at every layer, indexing computation under long context will eat into the gains. A safer approach is to reuse selection results across adjacent layers, re-filtering only at layers where semantics change significantly.
Cross-Layer Reuse: Deep representations are often highly correlated with shallow ones, making it unnecessary to store a complete set of main keys, index keys, and filter subscripts for every layer. Several layers can share a main cache, or only store deltas and low-rank corrections. Reuse granularity should be block-based rather than a one-size-fits-all approach across the entire network: layers closer to the input change rapidly, while layers closer to the output are more suitable for sharing. After reuse, the global resident cache no longer scales linearly with the number of layers, giving long contexts a chance to fit into the HBM of a single or a few GPUs.
4. Decoupling Knowledge Memory from Backbone Computation
Agents need to remember two types of things. One is episodic memory for the current task, such as this terminal output, this patch, or this error, which must reside in the context or cache. The other is relatively stable facts and code conventions, which are uneconomical to repeatedly “compute” using dense parameters.
Stable knowledge can be placed into a retrievable memory module: the backbone retrieves only a few entries when needed, rather than proportionally increasing per-step activation parameters to expand knowledge capacity. The benefit of this is decoupling knowledge updates from backbone inference, keeping the growth of activation overhead slow. The limitations are equally clear: retrieval errors directly pollute reasoning; the version, timeliness, and permissions of memory entries must be auditable; and private repositories or user data cannot be boundlessly written into shared memory. For enterprise scenarios, episodic cache is isolated by session, while stable memory is managed by knowledge base version. The two should not mix their eviction strategies.
5. Checklist for System Design Implementation
- Estimate capacity planning by bytes, not by “million token” slogans. First determine the resident bytes per token, batch concurrency, and prefix hit rate, then reverse-calculate the VRAM budget. The prefill peak on a prefix miss is often more dangerous than steady-state decoding.
- Scheduling must distinguish between prefill and decoding. Prefill is compute-bound, while decoding is bandwidth- and cache-bound. In mixed deployments, separate queues can be set for long prompts to prevent short requests from being blocked by ultra-long agent tasks. Once the context exceeds a threshold, prioritize evicting low-information logs, duplicate file headers, and expired tool results, retaining traceable summaries instead of silently truncating.
- Correctness validation cannot just look at average scores. Cover at least four types of regressions: whether cross-file references still point to the correct symbols; whether critical errors in the latter half of ultra-long logs are still read; whether numbers and paths drift after multiple rounds of tool calls; and whether there is a systematic shift in attention hit positions for the same prompt before and after quantization. Latency metrics should simultaneously report time to first token (TTFT), time per token, and incremental prefill time on cache hits.
- Security boundaries are also part of cost design. Caches and external memory may retain keys, tokens, and internal hostnames. Eviction, quantization, and cross-node migration must all be handled according to data classification to avoid leaving sensitive fragments in shared prefixes for long periods just for the sake of compression.
6. How to Judge if Optimization is Worthwhile
If the business is primarily short Q&A, the benefits of cross-layer reuse and sparse indexing are limited, yet the engineering complexity is not low. If tasks frequently exceed tens of thousands of tokens, involve many tool turns, and repeatedly append to the same prefix, prefill layer reduction, low-precision caching, and selection result reuse typically reduce both latency and VRAM simultaneously. The evaluation criteria should be the cost per unit of effective context and the task completion rate, rather than a single parameter scale or a single benchmark score.
The architectural combination can be summarized as follows: asymmetric depth reduces prompt-side computation; low precision and sparse attention shrink cache entries and effective history; cross-layer sharing removes duplicated states; and external memory expands stable knowledge with lower activation. Using all four together allows long-horizon agents to maintain full repository-level context within an acceptable hardware budget, rather than trading speed for continuous history truncation.
