Reducing Long-Context Inference Costs: Prefill and KV Cache Optimization Strategies
This article explains where inference costs come from in long-context workloads and how recent model architectures reduce them. It covers the compute cost of Prefill, the memory cost of the KV Cache, and the techniques that shrink each one. Readers can use it to judge whether these approaches fit their own services and to identify which metrics to measure before deployment. Full training workflows are out of scope.
1. Two Sources of Long-Context Inference Cost
Context grows quickly in agent workloads. A complex software engineering task can involve hundreds of tool calls, accumulating hundreds of thousands of tokens of terminal output and full code repositories. Deep research, graphical user interface automation, and enterprise workflows also require the model to keep reading its interaction history. As context grows, inference cost comes mainly from two sources.
The first source is Prefill computation. Let the model have L layers, hidden dimension d, and a prompt length of N. The Prefill computation has two parts. The linear layers (the Q, K, and V projections, the output projection, and the feed-forward network) require roughly O(N·L·d²) operations, which scales linearly with prompt length. The self-attention score and weighting computation requires roughly O(N²·L·d) operations, which scales quadratically. For short prompts, the linear layers dominate. Once the prompt length exceeds a certain multiple of the hidden dimension, the attention term gradually becomes the main cost. Long-context optimization therefore needs to reduce the cost of the linear layers and also address the quadratic cost of attention.
The second source is KV Cache storage. Traditional architectures keep separate Key and Value tensors for every layer. As context grows, the KV Cache keeps occupying high-bandwidth GPU memory. Long multi-turn conversations may also move data to host memory, SSDs, or across the network, which adds transfer overhead. For an inference service, GPU memory usage determines how many concurrent sessions a single card can serve, so it directly determines serving cost.
Because of this, new efficient inference architectures typically compress four dimensions at once: the size of each KV entry, the number of historical positions each token actually attends to, the KV data repeatedly stored across adjacent layers, and the number of network layers that must run fully during Prefill.
2. Asymmetric Computation: Running Only Part of the Network During Prefill
The next-generation architecture of an open-source large model uses an asymmetric computation design called Causal Encoder-Decoder. The basic idea is that most prompt tokens pass only through the first half of the network during Prefill and do not need to traverse the full deep structure. According to the public description of this architecture, each token activates about 8 billion parameters during Prefill, compared with about 16 billion during Decode.
Two points deserve attention. First, halving the activated parameters does not halve the Prefill compute. The figures above account only for the linear layers, meaning the number of tokens multiplied by the activated parameters per token. Attention computation and memory access do not drop by the same proportion, so the reduction in total latency is usually smaller than half. The exact gain depends on prompt length, batch size, and hardware. Second, this figure comes from a single vendor’s disclosure. Actual gains need to be measured again on your own model and workload.
The design offers three lessons for engineering practice.
- Prefill and Decode can be optimized separately. Decode is a serial process that generates one token at a time, and its bottleneck is usually memory bandwidth. Prefill can process the entire prompt in parallel, and its bottleneck is usually compute. The two stages suit different deployment specifications or activation strategies.
- Shallow layers already extract most of the context information. Existing analyses suggest that the representations in the first half of a Transformer already contain rich contextual information. This conclusion depends on the specific model and task, so it must be verified through evaluation. It suggests a direction for early-exit designs.
- In self-hosted services, you can evaluate the benefits of layer-wise scheduling and staged parallelism. For example, you could deploy Prefill on nodes with stronger compute and Decode on nodes with higher memory bandwidth, then allocate resources in proportion to load.
3. KV Cache Compression: Cross-Layer Reuse and Low-Precision Quantization
If Prefill optimization reduces compute, KV Cache compression reduces storage. This architecture uses two techniques in this area.
3.1 Cross-Layer Cache Reuse
In a traditional Transformer, each layer maintains its own KV data. Attention patterns in adjacent layers often look similar, so the stored data contains redundancy. The new approach lets several adjacent layers share part of their intermediate results. These results fall into three categories: the main KV data, the Key vectors used by the indexer, and the Top-K selection results, meaning the list of historical positions each token finally selects.
Sharing is organized by layer groups. The following is an illustration, not the architecture’s actual configuration: a group of four consecutive layers can share one Top-K index, while each layer still computes its own Value. This reduces both the number of index computations and the number of index writes.
Combined with sparse attention, this approach compresses two dimensions. First, the total KV data stored per layer goes down. Second, the number of historical positions each token actually attends to in full attention decreases. The model runs attention only over the most relevant part of the history, and the indexing mechanism skips the remaining positions.
3.2 Low-Precision KV Quantization
Beyond reducing the number of cache copies, you can also reduce the number of bytes per cache copy. This architecture stores the main KV Cache in FP4 precision. According to the public material, combined with cross-layer reuse, the global KV Cache drops from about 3,514 bytes per token to about 890 bytes per token, roughly one quarter of the original.
These figures should be used with care. The public material does not disclose the number of layers, the number of heads, the head_dim, the quantization granularity, whether the indexer is included, or how the figures were counted. Readers cannot apply them directly to their own models. To estimate the KV bytes per token, use this formula: number of layers × number of KV heads × head_dim × bytes per element × 2 (for K and V). If cross-layer sharing is used, count the layers as the actual number of cache copies after sharing.
When applying KV quantization, pay attention to the following points.
- Trade-off between precision and quality. Each step down from FP16 to INT8 and then to FP4 carries some risk of accuracy loss. In practice, you can use different quantization granularities for Keys and Values.
