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

    This article explains why long-context inference is bottlenecked by prefill and repeated reads of cached history rather than by token generation. It covers how attention, keys, values, and the KV cache work, why the cache grows with layers, sequence length, and channel width, a layered architecture that splits causal encoding from decoding, and the three multipliers—cross-layer sharing, shared retrieval results, and lower storage precision—that can shrink the cache to roughly one quarter. It closes with engineering practices for scheduling, cache governance, precision tradeoffs, observability, and elastic resources.

    1. The Problem: Why Reading Costs More Than Writing

    In applications such as AI coding assistants, code review tools, and long-document analysis, a typical turn unfolds in a predictable way. The tool first modifies several files, then feeds the updated source code, unit test output, static analysis reports, and dependency logs back to the model. The model reads tens of thousands of characters of context and ultimately produces only a few hundred characters of instructions for the next step. Across multiple continued turns, the cumulative volume read in ends up several times larger than the volume written out.

    This creates a cost structure that is easy to overlook: the bottleneck of an inference system is not the generation stage, but the prefill stage and the repeated reading of historical context. Understanding this is the prerequisite for understanding long-context inference optimization.

    2. The Basics: Attention, KV, and Why the Cache Balloons

    A language model first splits text into tokens, where a token may be a character, part of a word, or a symbol. As each token passes through multiple Transformer layers, it forms different hidden vectors at different layers: attention is responsible for pulling information from the historical context, while the feed-forward network continues to process it.

    The Q, K, and V in attention can be understood this way: Q is the query issued by the current position, K is used to determine which historical positions are relevant, and V carries the content that is actually read back. The computation for a single query and a single attention head can be written as:

    1. o = softmax(q · Kᵀ / √c) · V
    2. where q ∈ R^{1×c}, K, V ∈ R^{t×c}
    3. c is the number of channels, t is the visible history length

    When generating a new token, the K and V of historical positions do not need to be recomputed, so they are cached. 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 single request therefore naturally splits into two phases:

    • Prefill phase: processes the long input all at once, compute-intensive, and parallelizable;
    • Decode phase: generates token by token, memory-access-intensive, and requires repeatedly reading the historical cache.

    3. A Layered Architecture: Causal Encoder Plus Decoder

    For workloads characterized by “long inputs and frequent continuation,” one viable design is to split the network vertically: the total number of layers stays the same, with the first half taking on causal encoding duties and the second half taking on decoding duties.

    • When processing long inputs, mainly the first half runs, compressing the long sequence into a more compact representation;
    • When generating new tokens, the full network runs to ensure representational capacity does not degrade.

    Illustration (pseudocode, expressing scheduling logic only):

    1. def forward(input_ids, past_cache, is_prefill):
    2. if is_prefill:
    3. h = encoder_layers(input_ids) # first half only
    4. cache = build_global_cache(h) # build/update the global cache
    5. return cache
    6. else:
    7. h = decoder_layers(last_token, past_cache) # full network
    8. return h

    The benefit of this split is that the expensive computation for long inputs is confined to the first half, while the second half participates only on demand during generation. This leaves an adjustable knob between “compression strength” and “generation quality.”

    4. Why the Cache Can Drop to About One Quarter

    A common misconception needs clearing up: lighter compression along the sequence dimension does not necessarily make the cache larger. The total cache size depends on three multipliers—number of layers, storage width per token, and storage precision. Cross-layer sharing and reduced precision are precisely the main sources that push the total down to about one quarter.

    1. Cross-layer sharing of a global cache: multiple layers no longer each store a copy but reuse the same global representation, significantly weakening the layer-count multiplier;
    2. Partial layers reuse retrieval results: intermediate results related to retrieval augmentation are shared across layers, reducing redundant writes;
    3. Lower storage precision: the cache is stored at lower numerical precision, reducing the storage width per token.

    A rough model can be used to estimate it:

    1. Cache ≈ L_eff × T × d × p × bytes
    2. L_eff: effective number of independent cache layers (far smaller than total layers after sharing)
    3. T: sequence length, d: number of channels, p: bytes per element

    When both L_eff and p drop, even if T rises due to long inputs, the product can still shrink substantially.

    5. Engineering Implementation Notes

    • Layered scheduling: clearly separate the prefill and decode paths, avoiding useless full recomputation during the generation stage;
    • Cache governance: set a capacity limit and eviction policy for the global cache to prevent unbounded growth from continued multi-turn sessions;
    • Precision tradeoffs: validate the impact of low-precision caches on long-context tasks using an offline evaluation set, especially for highly structured inputs like code and logs;
    • Observability: use monitoring, alerting, and logging services to track cache hit rate, prefill latency, and per-turn input volume;
    • Elastic resources: container platforms scale with load, object storage holds long-context snapshots, and message queues smooth out continuation request spikes.

    6. Conclusion

    The focus of long-context inference optimization is shifting from “compressing the sequence shorter” to “storing the cache fewer times redundantly.” The combination of layered encoding and cross-layer sharing offers a reusable engineering path for read-heavy, write-light scenarios such as AI coding assistants: carrying longer context at a smaller cache cost.