Understanding KV Cache Compression in Long-Context Inference

    This article explains how KV cache compression works in long-context inference, where reading large inputs costs far more than generating short outputs. It covers the capacity model behind the KV cache, four optimization paths including layer-wise heterogeneity, cross-layer sharing, partial retrieval reuse, and lightweight sequence compression with low-precision storage, plus practical guidance on capacity planning, prefix reuse, precision strategy, and observability.

    1. Background: Why Reading Costs More Than Writing

    In applications such as AI coding assistants, document question answering, and log analysis, a typical turn looks like this: the model first reads back tens of thousands of words of source code, test logs, and tool-call outputs, and in the end produces only a few hundred words describing the next action. Input and output are severely asymmetric in length, which inverts the structure of inference resource consumption. The bottleneck is not the generation stage but the repeated reading and state maintenance of long contexts.

    Two characteristics of this workload deserve special emphasis:

    • Long inputs: the visible history of a single request can easily reach tens of thousands of tokens.
    • Frequent continuation: across multi-turn tool calls, the history context keeps growing and the prefix is highly repetitive.

    A class of model designs optimized for this kind of workload is built around “long input plus frequent continuation” in its technical report. The core approach is to split the network into a causal encoder in the first half and a decoder in the second half, and to let multiple layers share a single global KV cache. This article breaks down its principles and costs from a general technical perspective.

    2. Where the KV Cache Comes From and Its Capacity Model

    A language model splits text into tokens. Each token is processed by multiple Transformer layers, where attention retrieves information from historical positions and the feed-forward network continues the transformation. In attention, Q is the query of the current position, K determines the relevance of historical positions, and V carries the content being read back. The intuitive form for a single head and single query is:

    1. o = softmax(q * K^T / sqrt(c)) * V
    2. q ∈ R^(1×c), K,V ∈ R^(t×c), o ∈ R^(1×c)

    Here t is the visible history length and c is the number of channels. When generating a new token, the historical K and V can be reused, so they are cached, which is the KV cache. Its capacity is approximately:

    1. bytes ≈ 2 × layers × t × c × dtype_bytes × batch

    Three multipliers determine the direction of optimization: the number of layers, the precision, and the compression ratio along the sequence dimension. A single request is therefore divided into two phases: the Prefill phase processes the existing input and builds the state, while the Decode phase generates tokens one by one and keeps reading the cache. For long-input workloads, the Prefill compute and cache writes account for the overwhelming majority.

    3. Four Optimization Paths

    1. Layer-wise heterogeneity: split the network into a causal encoder in the first half and a decoder in the second half. Long inputs mainly go through the first half, and only the generation stage runs the full network, which lowers the marginal cost of “reading.”
    2. Cross-layer sharing of a global cache: instead of storing a separate copy per layer, multiple layers share the same global KV, which significantly dilutes the layer-count multiplier.
    3. Partial reuse of retrieval results across layers: for retrieval-style contexts, some layers directly reuse existing representations, reducing duplicate writes.
    4. Lightweight sequence-dimension compression plus low-precision storage: compression along the sequence dimension is lighter, but storage precision is lower, and the combination brings the global cache down to roughly one quarter of the previous generation.

    Key takeaway: the reduction in total cache size comes mainly from cross-layer sharing and lower storage precision, not from sequence compression itself. This explains the apparent contradiction of “lighter sequence compression yet a smaller total cache.”

    4. Engineering Recommendations

    • Capacity estimation: use the formula above to reserve GPU memory for the worst-case context length and concurrency, avoiding swap-out triggered by long-tail requests.
    • Prefix reuse: place stable prefixes (system prompts, repository skeleton) at the front to maximize cache hits.
    • Precision strategy: keep higher precision for precision-sensitive layers and lower precision for the rest, and run end-to-end quality regression.
    • Observability: track cache hit rate, Prefill latency, and swap-out counts through logging services and monitoring alerts.

    In summary, optimizing long-context inference essentially means pushing down all three multipliers—layers × sequence × precision—at the same time. Layer-wise heterogeneity and cross-layer sharing change the structure, while low-precision storage changes the unit cost, and together they determine the final cache size. In a general cloud environment such as Baidu AI Cloud, a complete inference pipeline can be built by combining container platforms, object storage, and monitoring alerts.