Reducing Long-Context Inference Costs: Optimizing Prefill and KV Cache
Long-context agent workloads drive up inference costs mainly in two areas: Prefill compute and KV Cache memory. This article explains why quadratic attention dominates Prefill at long sequence lengths, how much memory KV Cache actually consumes, and three optimization directions—causal asymmetric compute that lets most prompt tokens skip deep layers, cross-layer KV reuse, and low-bit quantization—along with their constraints and trade-offs.
Why Long Context Makes Inference Expensive
Context in agent tasks grows quickly. A single automated coding task may involve hundreds of tool calls, hundreds of thousands of tokens of terminal logs, and an entire code repository. All of this content must enter the model, and the cost concentrates in two areas.
The first is compute during the Prefill stage. Suppose a model has L layers, a prompt length of N, and a hidden dimension of d. The attention computation per layer is roughly O(N²d), the feed-forward network (FFN) is roughly O(Nd²), and the total is approximately O(L(N²d + Nd²)). When N is small, the linear FFN term dominates; as N grows into the hundreds of thousands, the quadratic attention term quickly takes over. This means you cannot estimate Prefill cost from parameter count alone in long-context scenarios.
Whether Prefill becomes the bottleneck depends on the size of N, cache hit rates, batching strategy, and hardware. Prefill is compute-heavy and, unlike the Decode stage, cannot easily be amortized through batching. For long-prompt requests, it often directly determines time to first token (TTFT).
The second cost area is the KV Cache. Every layer must store keys and values, and the bytes consumed per token can be estimated with the following formula:
KV bytes per token ≈ 2 × number of layers × number of KV heads × head dimension × bytes per element
For example, assume a model with 60 layers, 8 KV heads, a head dimension of 128, and 16-bit storage (2 bytes per element). Each token then occupies about 245,760 bytes, or roughly 240 KB. With a one-million-token context, the KV Cache alone reaches the 240 GB range—and that excludes model weights, activations, and framework overhead. These numbers are estimates under a hypothetical configuration, meant only to illustrate orders of magnitude, not to describe any specific model.
KV Cache size directly constrains two things: the context length a single GPU can hold, and the number of concurrent requests that can be served within the same memory budget.
New long-context architectures aim to compress four dimensions at once: the size of each KV entry, the number of historical positions involved in attention, KV duplicated across layers, and the number of network layers that Prefill must execute in full.
Can Asymmetric Compute Let Prefill Skip Layers?
In a traditional decoder-only model, every token passes through all layers during both Prefill and Decode. But much of the prompt content—repetitive logs, large code blocks, conversation history—does not require every token to traverse the full network depth to be understood.
A hybrid encoder-decoder architecture (referred to below as CED) uses causal asymmetric compute. Most prompt tokens pass mainly through the first half of the network, while a small number of key tokens and all generation-stage tokens execute the full depth. The pseudocode below illustrates the idea:
# Simplified illustration: asymmetric depth allocationdef prefill(prompt_tokens):shallow_repr = model.front_half(prompt_tokens) # most tokens only go through the front halfkey_tokens = selector.pick(prompt_tokens) # select key tokensdeep_repr = model.full_stack(key_tokens) # key tokens go through full depthreturn merge(shallow_repr, deep_repr)
This pruning has a hard constraint: no token’s representation may depend on future information. Otherwise, generation would violate causality and output quality would degrade. This is why the architecture is called a causal encoder-decoder.
Published material offers one configuration estimate: in a MoE model with a backbone of roughly 552B parameters, the activated parameters per token during Prefill drop from about 16B in the Decode stage to about 8B, suggesting Prefill compute is nearly halved. This figure is calculated on an activated-parameter basis, does not include the full attention overhead, and comes without end-to-end benchmark results. Readers should refer to the model’s official technical report and measure on their own workloads. Actual gains also depend on sequence length, batch size, and the accuracy of key-token selection. If the selector misses important information, answer quality will suffer.
Cross-Layer KV Reuse and Low-Bit Quantization: Reducing Redundant Caching
Modern efficient attention typically works in two steps. First, a lightweight Indexer K selects the Top-K most relevant historical positions; then, fine-grained attention is computed only over those positions. This reduces attention computation, but the Indexer K, the Top-K selection results, and the main KV are still stored redundantly across layers.
Cross-layer reuse generally falls into three categories:
- Multiple layers share a single copy of the main KV, reducing per-layer independent caching;
- The Indexer K and Top-K selection results are reused across layers, avoiding repeated sparse indexing in every layer;
- The shared KV is stored with low-bit quantization.
The scope of sharing must be clearly defined. If all layers share the same KV, information that different layers attend to may be compressed into a single representation, and recall and accuracy on some tasks may degrade. Whether to share, and across how many layers, should be validated on long-context benchmarks—losslessness should not be assumed by default.
Low-bit quantization follows the same logic. Reducing the cache from 16-bit to 4-bit theoretically cuts storage per element to one quarter. However, quantization scale factors, metadata, and unquantized portions offset part of the gain. FP4 may also introduce precision loss, requiring calibration data, error evaluation, and a fallback plan—for example, keeping higher precision for precision-sensitive layers, or rolling back based on evaluation metrics.
