KV Cache Compression in Long-Context Inference: How It Works

    This article explains why KV cache becomes the main bottleneck in long-context LLM inference, where the cache comes from, and how a layered encode-decode design with cross-layer sharing reduces memory usage. It includes a simplified capacity estimation formula, practical engineering tips for prefix reuse, quantization and eviction, and common pitfalls to avoid.

    1. Background: Why Reading Costs More Than Writing

    In scenarios such as AI coding assistants, document Q&A, and long-log analysis, a single interaction often looks like this: the tool reads back tens of thousands of words of source code, test output, and call results, while the model produces only a few hundred words describing the next action. The context keeps being extended, and historical tokens are recomputed over and over, shifting inference cost from the generation side to the input side.

    This kind of workload has two characteristics: the input is far longer than the output, and sessions have many turns with a highly repetitive prefix. Together, these make the KV cache the primary bottleneck: it consumes GPU memory and also consumes memory bandwidth at every decoding step.

    2. Where the Cache Comes From: Attention and State Reuse

    A language model splits text into tokens, and each token is processed repeatedly across multiple layers. In the attention mechanism, Q is the query issued from the current position, K determines the relevance of historical positions, and V carries the information read back. Single-head attention read-back can be abstracted as:

    1. o = softmax(q * K^T) * V
    2. q: 1×c # current query
    3. K,V: t×c # keys and values of t visible historical positions
    4. o: 1×c # read-back result

    When generating a new token, the K and V of historical positions do not change, so they can be cached and reused. This is the KV cache. If each layer stores its own copy, the cache size grows roughly linearly with “number of layers × sequence length × number of channels.”

    A request therefore splits into two phases: Prefill, which processes the existing input and builds the state, and is compute-intensive; and Decode, which generates tokens one by one and is memory-access-intensive. The pain points of long-context workloads concentrate on repeated Prefill execution and cache reads during Decode.

    3. A General Design: Layered Encode-Decode Plus Cross-Layer Sharing

    The industry’s general optimization approaches for long-context workloads fall into two orthogonal paths.

    The first compresses along the sequence dimension, for example sparse attention, windowing, and low-rank projection, aiming to reduce the amount of information each position must store or read. The second reuses along the layer dimension, letting multiple layers share the same global cache, or directly reusing retrieval results in some layers, aiming to reduce the number of cache copies.

    Combining the two yields a layered encode-decode structure: split the network into a causal encoder segment and a decoder segment. Processing long input mainly runs the first half to build a compact global state; generating new tokens runs the full network to refine that shared state.

    This structure explains a seemingly contradictory phenomenon: sequence-dimension compression is not aggressive, yet the global cache may drop to about a quarter of the previous generation. Because the total equals “size per copy × number of copies,” the gain from fewer copies is multiplicative, while the gain from a smaller single copy is additive. In addition, lowering the cache storage precision (for example, storing keys and values at a lower bit width) directly reduces usage proportionally.

    4. Capacity Estimation: Doing the Math on the Gains

    For engineering purposes, a simplified formula can be used to forecast capacity:

    1. cache ≈ layers_effective × t × c × bytes_per_value × 2(K and V) × batch

    Here layers_effective is the number of layers that actually store the cache independently. Changing from per-layer storage to multi-layer sharing can reduce this term by an order of magnitude; halving the bytes per value multiplies total usage by roughly 0.5 as well. Combined, a reduction on the order of a quarter is not exaggerated.

    It is worth emphasizing that the exact numbers depend on model configuration and implementation. Evaluations should follow the figures disclosed in public technical reports, and the estimation formula should not replace real measurements.

    5. Engineering Implementation Notes

    • Prefix reuse: put stable system prompts and repository context at the very front of the session to maximize cache hits; place frequently changing content later.
    • Segmentation and summarization: structurally trim long logs and tool output first, keeping only the fragments relevant to the current task.
    • Precision and quantization: use a lower bit width for the cache, evaluate the impact on long-range recall, and build a regression evaluation set.
    • Eviction policy: combine “recently used + attention contribution” for eviction, avoiding FIFO-only eviction that can drop critical information.
    • Observability: bring cache hit rate, Prefill duration, and peak GPU memory into monitoring, alerting, and logging services to form a capacity baseline.

    6. Common Misconceptions

    The first is equating cache compression with model compression: their goals differ, since the former does not change parameters while the latter changes precision. The second is looking only at GPU memory and not bandwidth, since the Decode phase is often bandwidth-bound. The third is ignoring correctness regression, because both compression and sharing can affect long-range consistency and must be accepted against task-level metrics.

    7. Conclusion

    The focus of long-context inference optimization is shifting from “making the model write better” to “making the model read more cheaply.” Layered encode-decode and cross-layer cache sharing offer a reusable approach: trading a structural reduction in the number of copies for a larger gain than sequence compression. The practical advice for developers is to first quantify the input-to-output ratio of the workload, then choose a compression path, and finally keep calibrating with observability metrics. If running in the cloud, you can combine general capabilities such as container platforms, object storage, and monitoring and alerting to bring cache hit rate and capacity levels into routine governance.