Long-Context Inference Too Expensive? Strategies for Prefill and KV Cache Cost Reduction
As agent tasks demand increasingly long contexts, inference costs surge primarily due to Prefill computation and KV Cache memory consumption. This article analyzes the root causes of these costs, detailing the quadratic growth of self-attention and the memory footprint of caching. It explores four optimization directions: asymmetric computation for shallow token routing, cross-layer KV sharing, low-precision storage, and decoupling knowledge from computation. Additionally, it provides key metrics and validation methods for engineering teams evaluating long-context inference solutions.
1. Where Do Long-Context Inference Costs Come From?
The context length in AI agent tasks is growing rapidly. A complex software engineering task might involve hundreds of tool calls, hundreds of thousands of tokens in terminal output, and the content of an entire code repository. Deep research, GUI interactions, and enterprise-level workflow orchestration also require models to retain interaction history over extended periods. The longer the context, the higher the inference cost, which primarily stems from two areas: Prefill computation and KV Cache memory usage.
Let’s look at Prefill computation first. Assume the model has L layers, a hidden dimension of d, and a prompt length of N (number of tokens). Each layer consists of two parts of computation.
The first part is linear computation, including the Q, K, V, and output projections in the attention mechanism, as well as the Feed-Forward Network (FFN). The computation volume for each token in each layer is proportional to d², and the total volume for N tokens across L layers is approximately O(L·N·d²).
The second part is self-attention computation. Each layer needs to compute an N×N attention score matrix, where each score is the inner product of two d-dimensional vectors. Thus, the total volume is approximately O(L·N²·d).
The ratio of these two parts is roughly N/d. Here, constant terms are ignored, and the actual ratio is also affected by the FFN width and the number of attention heads. When N is significantly larger than d, the quadratic term of attention dominates. The hidden dimension is typically in the thousands, so for contexts with hundreds of thousands of tokens, self-attention is usually the primary bottleneck in Prefill. Implementations like FlashAttention reduce memory read/write operations but do not change the quadratic growth in computation.
Next, consider the KV Cache. During autoregressive generation, every historical token must store its Key and Value in every layer. The number of bytes occupied by a single token’s cache can be estimated using the following formula:
Bytes per Token Cache ≈ 2 × L × h_kv × d_head × b
Where h_kv is the number of KV heads, d_head is the dimension per head, and b is the number of bytes per element (2 for BF16, 1 for FP8). The coefficient 2 corresponds to the two separate caches for Key and Value.
Consider a hypothetical configuration: L is 60, h_kv is 8, d_head is 128, using BF16. The cache per token is approximately 245,760 bytes, or about 240 KB. A 128K token session would require about 32 GB of GPU memory. This figure illustrates that the KV Cache often exhausts memory before the model weights do, and it dictates how many concurrent sessions a single GPU can serve.
Industry optimization directions can be categorized into four classes: compressing the size of each KV entry, reducing the number of participating historical positions in attention computation, eliminating duplicate caches across different layers, and reducing the number of network layers that each token actually traverses during Prefill. Let’s examine each of these.
2. Asymmetric Computation: Routing Some Tokens Through Shallower Networks
The computational characteristics of Prefill and Decode differ. Decode processes only one new token per step, and generation quality heavily relies on the representational capacity of the full network. Prefill, however, processes a large amount of known context, where the representations of many tokens do not require deep computation. Some studies have proposed asymmetric encoding and decoding structures based on this observation. This design stems from analyzing the differences between Prefill and Decode and is not exclusive to any specific model architecture, such as Mixture of Experts (MoE) models.
The specific approach is to let the majority of prompt tokens pass through only the first half of the network during Prefill, while a small number of critical tokens still traverse the full network. There are two issues that must be addressed with this method.
First, the model must still satisfy causality—each position can only attend to previous positions. Second, tokens taking the shallow path skip the deep layers, resulting in missing Keys and Values in those deep layers. The system must explicitly define how to fill or reuse these missing caches; otherwise, the subsequent attention results during Decode will be incorrect. When evaluating such solutions, you should verify whether this aspect has a clear implementation.
The estimation of savings also needs to be viewed separately. Let f be the fraction of tokens taking the shallow path, and s be the fraction of layers skipped for each such token. The computation savings in the linear part are approximately f·s. The quadratic term of attention does not automatically decrease due to this change and still grows with N². Therefore, when evaluating, the time spent on linear computation and attention computation should be measured separately, rather than being lumped into a single total.
For engineering teams, the takeaway from this concept is that the computation budget for Prefill can be allocated differently based on token importance. Uniformly routing every token through the full network is not the only option. Whether to adopt this approach depends on the task’s requirement for long-range precision and whether the team can afford the additional routing and cache-filling overhead.
3. KV Cache Optimization: Cross-Layer Sharing and Low-Precision Storage
KV Cache compression can be approached from two independent directions.
Direction 1: Cross-Layer Sharing to Reduce Duplicate Caches. In traditional architectures, each layer independently saves its own KV. However, the attention patterns of adjacent layers are often highly correlated. Some sparse attention schemes allow multiple layers to reuse the same core KV set and share the indexer’s Key and Top-K selection results, thereby avoiding duplicate caching and computation. If k layers share the same cache, the memory footprint for that portion is reduced to about 1/k of the original. The actual savings must also subtract the small amount of layer-specific incremental cache.
Direction 2: Low-Precision Storage. The KV Cache generally has a higher tolerance for quantization than model weights. Switching from BF16 to FP8 halves the number of cache bytes. Switching to FP4 reduces it to about a quarter. The actual footprint will be slightly higher than the theoretical value due to the inclusion of quantization scale factors and other metadata.
Precision loss must be empirically tested and not judged solely by experience. It is recommended to compare against a BF16 baseline using the same test batch, including at least three types of metrics:
- Changes in Perplexity on long texts;
- Long-text retrieval accuracy, such as finding inserted key information at various positions and lengths;
- Pass rate or accuracy of the target business task.
Teams should establish acceptable regression thresholds in advance. For example, if the accuracy of a core task drops by more than 1 percentage point, roll back to higher precision. The threshold should be determined by business risk and not blindly copied from others’ data.
It is also important to note a common comparison error here. Public technical reports often provide the number of cache bytes per token, but the meaning of these numbers can vary: whether all layers are counted, whether local attention and indexer caches are included, what data types are used, and how the sequence length and model configuration are set. When the measurement criteria are inconsistent, two numbers cannot be directly compared. When citing such data, you should return to the original report to verify the measurement conditions; if verification is impossible, treat it only as a qualitative reference.
For practitioners, you can use the following checklist to evaluate your own solution:
- Have you adopted a cross-layer or group-shared KV structure, and how many layers are shared?
- Have you enabled FP8 or FP4 caching and validated the regression margin using the three metrics mentioned above?
- Have you implemented sparse selection for historical positions, allowing only relevant positions to participate in attention, and has the selection strategy been validated in long-text tests?
- Have you established a cache tiering strategy across GPU memory, host memory, and SSD, and is the swap-in/swap-out latency acceptable?
4. Decoupling Knowledge and Computation: Expanding Knowledge Without Enlarging the Backbone
Long-context models also face an easily overlooked cost: knowledge capacity. If all knowledge is stored in the backbone parameters, expanding knowledge means scaling up the model size, which increases the activated computation per inference. Memory decoupling is an alternative approach. It stores knowledge in an independent memory module, retrieves it on-demand during inference, and the backbone network only processes the small amount of retrieved content.
Implementing such a solution typically involves three steps.
The first step is knowledge organization. Documents, codebases, or business rules are segmented into chunks, encoded as vectors or key-value entries, and indexed. The granularity of segmentation directly impacts retrieval recall.
The second step is retrieval and injection. During inference, relevant entries are queried based on the current context, the Top-k results are extracted, and then fed into the backbone via attention or concatenation. A larger k value means more injected tokens, which increases computation costs.
The third step is evaluation. You need to measure retrieval recall, the impact of retrieval latency on Time to First Token (TTFT), and the final task performance separately.
The applicability boundaries of this approach include three points.
First, knowledge update frequency. The more frequently knowledge is updated, the higher the cost of index rebuilding or incremental updating. Internal codebases and product documentation usually have fixed update cycles, making them more suitable for this approach.
Second, latency. Retrieval occurs before generation, directly increasing TTFT. Online services need to undergo stress testing to confirm this is acceptable.
Third, consistency. The version of the memory module and the backbone need to be managed in correspondence. If the knowledge base is updated but the model still reads the old index, inconsistencies will arise between the answer and the latest data. For enterprise internal knowledge, retrieval results also need to be filtered by user permissions to prevent unauthorized access.
5. Selection Metrics and Validation Methods
For teams currently evaluating long-context inference solutions, it is recommended to focus on the following four metrics rather than just looking at benchmark scores.
1. Global KV Cache size per token. This determines memory usage and the concurrency limit. First, calculate the theoretical value using the formula in Section 1, then record the actual memory usage during stress testing. The deviation between the two can reflect framework overhead, memory fragmentation, and the impact of batch padding. Global cache, local cache, and indexer cache should be tracked separately; otherwise, the two sets of numbers are not comparable.
2. Prefill and Decode computation ratio and TTFT curve. Use profiling tools to measure the time spent in the Prefill and Decode phases separately. Then plot the curve of TTFT against prompt length. If the curve rises sharply as length increases, it usually indicates that the quadratic term of attention has become the primary overhead, and attention optimization should be prioritized.
3. Effective utilization rate under ultra-long contexts. The length a model can read is not equal to the length it can utilize. You can use a long-text retrieval task with inserted test information to test accuracy at various lengths and positions, and plot an accuracy curve. The inflection point where the curve drops indicates the model’s effective length, which needs to be compared with the claimed window length.
