Reducing Long-Context Inference Costs: Practical Prefill and KV Cache Optimization

    Long-context inference becomes increasingly expensive as prompt length, KV cache size, and model depth grow. This article explains how asymmetric prefill computation, low-precision and cross-layer KV cache sharing, sparse attention, and decoupled memory can reduce latency, memory usage, and serving costs for long-context models and AI agents. It also provides an engineering checklist for evaluating these techniques in production workloads.

    1. Why Long-Context Inference Costs Are Difficult to Reduce

    When a model processes hundreds of thousands or even millions of tokens, inference costs are mainly driven by two factors.

    1. Prefill computation

    For a decoder-only model with (L) layers and a prompt length of (N), each layer performs attention and feed-forward computation over the full prompt. The total computation is approximately:

    1. Prefill FLOPs ≈ O(N × L)

    As a result, doubling the context length almost doubles prefill computation. In software engineering workloads, a single task may include hundreds of tool calls, hundreds of thousands of tokens of terminal output, and an entire code repository. Prefill quickly becomes the primary source of latency and cost.

    2. KV cache memory and transfer costs

    Traditional Transformers store separate Key and Value caches for every historical token at every layer. As the context grows, the KV cache continuously consumes GPU HBM. In multi-turn conversations, multi-instance deployments, and long-running agent workloads, it can also create additional host memory, SSD, and network transfer overhead.

    Even with a batch size of one, an extremely long context can exhaust GPU memory and make a workload impossible to serve.

    Reducing long-context costs therefore requires progress in four areas:

    • Reduce the number of bytes used by each KV entry.
    • Reduce the number of historical positions that actually participate in attention.
    • Avoid storing duplicate KV data across Transformer layers.
    • Reduce the number of network layers that must be fully executed during prefill.

    2. Prefill Optimization: Using Asymmetric Computation to Assign Different Costs to Tokens

    One effective approach is to introduce an asymmetric causal encoder-decoder-style architecture. Its central assumption is that not every token needs to pass through the entire network.

    During prefill, most prompt tokens may obtain sufficiently useful representations after passing through only the earlier layers. Only a smaller subset of tokens—for example, positions that require a more precise connection to generation—needs to traverse the full network.

    According to publicly available data from an open-source MoE model, the backbone contains 552B parameters, while the original decode phase activates approximately 16B parameters per token. By allowing most prefill tokens to pass through only the first half of the network, the number of activated parameters can be reduced to approximately 8B, bringing prefill computation close to half of the original level.

    This design provides three major benefits:

    • Significantly lower time to first token (TTFT): This is particularly valuable for interactive agents and long-document question answering.
    • Less dependence between cost and context length: Long prompts no longer increase computation in direct proportion to their length.
    • Strong compatibility with MoE architectures: MoE models already provide sparse computation by activating only a subset of experts for each token. Asymmetric depth extends this sparsity beyond model width to model depth.

    There is an important engineering trade-off. A token truncated at shallow layers may lose detail if it is later referenced by deeper attention layers. Architectures of this type therefore commonly use globally shared Main KV data and an indexing mechanism, ensuring that the KV representations of truncated tokens remain accessible to later layers.

    3. KV Cache Compression: Three Complementary Paths

    The core of KV cache optimization is to reduce three factors at the same time:

    Cost per token × number of cached positions × number of cached layers

    Publicly described approaches generally combine the following three techniques.

    1. Reduce the size of each KV entry with low-precision quantization

    Quantizing the Main KV Cache from BF16 or FP16 to a low-precision format such as FP4 can reduce the storage required for each entry to roughly one-quarter of its original size.

    According to the report for the public model referenced above, its global KV cache is reduced from 3,514 bytes per token to approximately 890 bytes per token. Low-precision quantization is one of the primary contributors to this reduction.

    The main risk is a decline in long-context retrieval accuracy. Low-precision KV therefore requires careful quantization-error control and tests for numerical stability in attention.

    2. Share KV data across layers

    In a traditional architecture, all (L) layers maintain their own complete KV cache. Cross-layer sharing allows adjacent layers to reuse the same Main KV, Indexer KV, and Top-K selection results:

    • Main KV data is stored centrally, while deeper layers use lightweight projections for adaptation.
    • Indexer Keys are computed and stored only once.
    • Top-K historical-position selections are reused across layers, avoiding repeated retrieval.

    This substantially amortizes the cost of maintaining layer-specific KV data and also reduces index computation.

    3. Use sparse attention to reduce the number of active historical positions

    With Top-K selection, each query performs full attention only over a small number of the most relevant historical KV entries. Other positions are excluded from the computation path.

    This is especially important for long contexts. The amount of attention access can move from an (O(N^2))-scale pattern toward one that is approximately linear with respect to context length.

    When combined, these three techniques can reduce cache usage to roughly one-quarter of a traditional implementation while preserving long-range retrieval capabilities. Together with paged management, such as Paged Attention-style mechanisms, and tiered storage across HBM, host memory, and SSD, they can support practical serving costs at context lengths of up to approximately 1M tokens.

    4. Decoupling Knowledge Capacity from Compute Cost: The Value of External Memory

    Long-context models also face a less obvious problem: the knowledge capacity stored in model parameters is limited, while expanding the parameter count can increase activation costs for every inference request.

    A more economical approach is to decouple knowledge memory from backbone computation. A separate memory module with low activation overhead can expand the model’s knowledge capacity, while the backbone focuses on reasoning and generation.

    This design allows a model to access a broader range of knowledge at a similar activation cost. It also avoids forcing all knowledge into dense parameters, which would require computation for that knowledge during every forward pass.

    For agents, external memory can additionally store task state, tool-call history, and domain documents. This creates a division of responsibility among context memory, parameter memory, and retrieved memory.

    5. Engineering Implications for Agents and Long-Running Tasks

    Taken together, these optimizations change what is feasible for long-context agents:

    • Multi-turn tool use: Hundreds of thousands of tokens of interaction history can remain in resident memory, avoiding a full prefill recomputation on every turn.
    • Repository-scale understanding: Both TTFT and memory consumption can be reduced when processing the context of an entire codebase.
    • Enterprise workflows and automation: Long-running tasks are less likely to require frequent restarts or degradation because of KV cache growth.

    Using the public figures described above as a reference, reducing the KV cache to approximately one-quarter of its original size and cutting prefill computation nearly in half can substantially improve throughput and reduce per-request costs in long-context workloads. A 1M-token context window also creates room for genuine repository-scale and end-to-end tasks.

    6. Implementation Recommendations and Validation Checklist

    If you are evaluating or building a similar inference optimization system, consider the following sequence:

    1. Profile the actual cost structure first: Measure prompt-length distributions, multi-turn session lengths, and HBM usage under real workloads. Confirm that the bottleneck is prefill or KV cache rather than decoding.
    2. Prioritize KV quantization: Low-precision KV is often the highest-return single optimization. Start by using offline evaluation sets to measure accuracy degradation in long-document retrieval and multi-hop question answering.
    3. Add cross-layer sharing and sparse attention: Build on quantization and focus on long-range retrieval quality, including “needle in a haystack” tests and dependency tracking across tool calls.
    4. Match asymmetric computation to workload characteristics: The greatest benefits appear in workloads with a high prefill ratio. Test how different truncation depths affect the information retained by shallow-layer tokens.
    5. Establish regression benchmarks: Evaluate long-context retrieval, code-change localization, multi-turn agent task success rate, TTFT, and throughput. Do not rely on perplexity alone.
    6. Build the supporting infrastructure: Paged KV management, tiered storage across GPU memory and host memory, cache lifecycle management for multi-turn sessions, monitoring, and alerting determine whether the optimization will deliver its expected value in production.

    7. Conclusion

    There is no single solution for reducing long-context inference costs. It is a multi-factor optimization problem:

    • Use asymmetric computation to reduce prefill cost.
    • Use cross-layer reuse and low-precision quantization to reduce KV cache cost.
    • Use decoupled memory to expand knowledge capacity without proportionally increasing backbone computation.

    Public MoE architecture practices indicate that, when combined, these techniques can support million-token contexts while reducing global KV cache usage to approximately one-quarter and lowering prefill computation by nearly half.

    For developers building long-running agents, understanding the principles and limitations of these optimizations is an important step toward designing inference services with better cost efficiency.