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

    Long-context inference becomes expensive because prefill must process large prompts while decoding repeatedly reads the entire KV cache. This article presents practical optimization strategies, including KV cache sizing, prefix reuse, lower-precision storage, sparse attention, cross-layer sharing, external memory, and agent-oriented context management. It also explains the trade-offs and evaluation requirements behind each approach.

    1. Why Long-Context Inference Gets More Expensive

    Context grows quickly in agentic tasks. A single code-fixing workflow may invoke dozens of tools, with logs, directory structures, and test outputs appended to the context after every call. Each time the model generates a token, it must read the key-value (KV) states for all preceding tokens. Inference costs are concentrated in two stages:

    1. Prefill: The model processes the complete input prompt in one pass. The cost of the linear layers is approximately proportional to the input length (N) and the number of layers (L). The attention component also includes terms related to (N^2), which become increasingly significant as the input grows.
    2. Decode: The model generates tokens one at a time. At every step, it must read the entire historical KV cache, making GPU memory capacity and memory bandwidth major bottlenecks.

    These challenges can be addressed in four largely independent ways:

    • Reduce the amount of computation that must be fully performed during prefill.
    • Reduce the number of bytes used by each KV entry.
    • Reduce the number of historical positions that actually participate in attention.
    • Reduce redundant cache storage across layers.

    In practice, these approaches are usually combined.

    2. Estimate KV Cache Size First

    Before selecting an optimization strategy, calculate how much GPU memory the cache requires. A general estimate is:

    1. KV cache bytes =
    2. 2 × number of layers × number of KV heads × head dimension
    3. × bytes per element × number of tokens

    The factor of 2 accounts for storing both K and V. The following example uses hypothetical configuration values that do not correspond to any particular model:

    1. def kv_cache_bytes(layers, kv_heads, head_dim, bytes_per_elem, tokens):
    2. per_token = 2 * layers * kv_heads * head_dim * bytes_per_elem
    3. return per_token, per_token * tokens
    4. # Example configuration: 60 layers, 8 KV heads, head dimension 128,
    5. # BF16 (2 bytes), and a 128K-token context
    6. per_tok, total = kv_cache_bytes(60, 8, 128, 2, 128 * 1024)
    7. print(f"Per token: {per_tok / 1024:.0f} KiB") # 240 KiB
    8. print(f"128K tokens: {total / 2**30:.1f} GiB") # 30.0 GiB

    If the storage precision is reduced from 2 bytes per element to 1 byte, the same 128K-token context requires approximately 15 GiB. This shows that bytes per element have a linear impact on memory usage. Reducing the number of KV heads or sharing caches across adjacent layers can also reduce the footprint proportionally.

    The estimate must include the number of concurrent requests, because each request has its own KV cache.

    3. Reduce Prefill Computation

    Prefill computation comes from sending every input token through all network layers. One possible approach is to distinguish tokens by role. Input prompt tokens primarily establish the context representation, while generated tokens require the full depth of computation. If the architecture allows some prompt tokens to pass through only the earlier layers, the effective computation can be reduced.

    This type of design has three prerequisites:

    • The architecture must be determined during training. Dynamically skipping layers at inference time usually causes a significant quality loss.
    • Shallow representations must be validated. Tests should determine whether the information in the prompt is sufficiently captured by shallow representations for later generation. Relevant evaluations include long-context question answering, retrieval, and code understanding.
    • The benefit increases with input length. Savings are limited for short prompts and are most significant for workloads dominated by long documents or extensive logs.

    For multi-turn conversations and repeated system prompts, a more direct approach is to reuse the already computed prefix KV cache instead of changing the model architecture. The key requirement is a stable cache key. The following example generates chained hashes over fixed-size blocks. Identical prefixes produce identical keys for the corresponding blocks:

    1. import hashlib
    2. def block_keys(token_ids, block_size=256):
    3. """Generate chained hash keys for fixed-size blocks.
    4. Matching prefixes produce matching keys for corresponding blocks.
    5. """
    6. keys, prev = [], b""
    7. for start in range(0, len(token_ids), block_size):
    8. block = token_ids[start:start + block_size]
    9. digest = hashlib.sha256(prev + repr(block).encode()).digest()
    10. keys.append(digest.hex())
    11. prev = digest
    12. return keys

    With chained hashing, changing one block changes the keys for every subsequent block. This prevents an incorrect cache from being reused. Production systems must also handle fields such as template variables and timestamps that can break prefix equality. These fields should be placed after the reusable prefix whenever possible.

    4. Three Ways to Compress the KV Cache

    4.1 Reduce the Precision of Individual KV Entries

    Quantizing the cache from 16-bit floating point to 8-bit or 4-bit values directly reduces memory consumption. Scaling factors should be calculated per channel or per group; otherwise, errors may become concentrated around a small number of outliers.

    The risk is reduced long-range retrieval quality. Every precision change should therefore be reevaluated on long-context retrieval tasks.

    4.2 Reduce the Number of Historical Positions Used in Attention

    Sliding-window attention and sparse selection both target the number of historical positions involved in attention. With sparse selection, a lightweight indexer first identifies a small number of important historical positions for each query. Attention is then computed only over those positions.

    One easily overlooked cost is the indexer itself. If adjacent layers produce sufficiently similar selections, the selection results can be reused to reduce repeated indexing overhead. This is appropriate only when the attention patterns of adjacent layers are genuinely similar; otherwise, reuse can introduce accuracy drift.

    4.3 Share the Cache Across Layers

    Several adjacent layers can share the same KV cache. The cache footprint then decreases roughly in proportion to the size of each sharing group. The trade-off is reduced representational flexibility in the shared layers, so the grouping strategy is best designed during training.

    The three approaches are summarized below:

    Method What it reduces Primary trade-off
    Low-precision quantization Bytes per KV entry Quantization error; long-context retrieval must be reevaluated
    Sparse selection and index reuse Number of positions participating in attention Indexing overhead; adjacent layers must have similar patterns
    Cross-layer sharing Number of redundant KV copies Limited layer-wise representation capacity; depends on training design

    These methods can be combined. For example, cross-layer sharing together with low-precision storage can reduce memory by approximately the product of their individual reduction factors. However, every additional optimization requires a separate evaluation of its impact on output quality.

    5. Decouple Knowledge Capacity from Backbone Computation

    Model capabilities come from both parameters and retrievable knowledge. If some knowledge is placed in an externally queryable memory or parameter table, the backbone network can focus on reasoning. This makes it possible to expand capacity without significantly increasing per-step activation computation.

    The main engineering challenges are lookup latency, storage layout, and deployment complexity. In practice, measure the memory-access cost of lookups first, then decide whether frequently accessed knowledge should remain resident in GPU memory.

    6. Engineering Practices for Agentic Workloads

    Agent contexts have a clear temporal structure: recent tool outputs are usually more important, while large outputs from earlier steps often provide less value. The following practices can be applied directly:

    • Layer the context: Keep the most recent turns in their original form. Compress older tool outputs into structured summaries while recording their original positions for later reference.
    • Trim outputs: For terminal logs, it is often sufficient to retain error sections and tail output. Trimming rules should be configured by tool type rather than applying one universal truncation policy.
    • Use tiered KV storage: Keep hot data in GPU memory, warm data in host memory, and cold data on local storage. Swapping data in and out introduces transfer latency, so thresholds should be based on the probability of session reuse.
    • Use chunked prefill: Split an extremely long input into smaller chunks and interleave them with decode operations from other requests. This prevents one long request from monopolizing compute resources for an extended period and degrading the responsiveness of other requests.