KV Cache Compression for Long-Context Inference: Mechanisms, Capacity Math, and Trade-offs

    This article explains why KV cache becomes the dominant cost in long-context LLM inference, how the cache is created during prefill and decode, and four general optimization routes: layer-wise heterogeneous execution, cross-layer cache sharing, lower storage precision, and sequence-dimension compression. It also provides a reusable capacity estimation formula and practical guidance on cache hit rate, precision tiers, observability, and how to evaluate quality, latency, and throughput cost.

    1. The Starting Point: Why Reading Costs More Than Writing

    In applications like AI coding assistants, document question answering, and log analysis, a typical turn looks like this: a tool modifies several files, then source snippets, test output, and stack traces are read back into the model, and the model finally produces only a few hundred words describing the next action. Input and output lengths are severely asymmetric, and the context has to be carried forward turn after turn.

    This kind of workload has two characteristics: the input sequence is extremely long, and the same context is reused repeatedly. Together, they make the attention cache one of the main consumers of GPU memory and memory bandwidth. The industry summarizes this as the cost structure problem of long-context inference. It is not a defect unique to one model, but an inherent property of standard Transformer inference.

    2. Where the Cache Comes From: Attention and the Two-Phase Execution Model

    A language model first splits text into tokens. Each token enters the network and forms hidden vectors layer by layer: attention pulls information from historical positions, and the feed-forward network continues to process it. Attention commonly uses three symbols: Q, K, and V. Q is the query at the current position, K is used to decide which historical positions are relevant, and V carries the content that is actually read back. The intuition for single-head attention can be written as:

    1. o = softmax(q · Kᵀ / 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 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 layers × sequence length × channels.

    A request therefore splits into two phases:

    • Prefill: process the existing input in parallel and build the state needed for subsequent generation. Compute-intensive with high parallelism.
    • Decode: generate new tokens one by one, reading the entire history cache at every step. Bandwidth-intensive with low parallelism.

    Key takeaway: the bottleneck in the decode phase is usually not compute, but the bandwidth required to move the cache into the compute units. Compressing the cache and reducing the number of reads is often more effective than accelerating matrix multiplication.

    3. Four General Optimization Routes

    3.1 Layer-Wise Heterogeneity: Encoding in the Front, Generation in the Back

    Split a deep network into two parts, a causal encoder and a decoder (for example, each taking half the layers). Long inputs mainly run the front part, and the full network is only traversed when generating new tokens. There are two benefits: the effective compute in the prefill phase drops, and a long input only needs to pass through the front part to form a reusable state. The cost is that expressive capacity is split, so the two parts must be trained to cooperate; otherwise generation quality degrades.

    3.2 Cross-Layer Sharing of a Global Cache

    Instead of storing a separate K and V per layer, multiple layers share one global cache; some layers even reuse retrieval or encoding results directly. With L layers and G sharing groups, the cache is reduced to roughly G/L of the original. This is the main source of “same layer count, lower storage,” and it also explains why compression along the sequence dimension is light while total cache size can still drop significantly.

    3.3 Lower Storage Precision

    Store the cache in a lower-bit representation instead of high-precision floating point, or use per-block scaling to control error. Storage drops roughly in proportion to bit width, but outlier channels are sensitive to precision, so a small number of high-precision channels are usually kept for compensation.

    3.4 Sequence-Dimension Compression

    Pool, window, or sparsely select historical positions, keeping only representative K and V. This route directly reduces t, but it is more sensitive for tasks that require precise recall of distant details, so compression ratio and recall must be balanced.

    4. Capacity Estimation: A Reusable Formula

    1. cache_bytes ≈ 2 × L_eff × t × c × bytes_per_elem × batch

    The 2 accounts for the two copies, K and V; L_eff is the number of layers that actually store a cache (much smaller than L after sharing). Example: with t=100k, c=4096, batch=1, 2 bytes per element, and 32 layers, the cache is about 52GB; with sharing into 8 groups and 1 byte per element, it is about 6.5GB. This formula quickly shows whether the bottleneck is layer count, sequence length, or precision.

    5. Engineering Practices

    • Prioritize hit rate: put stable prefixes (system prompts, tool definitions, fixed documents) first to guarantee cache reuse.
    • Continue in segments: split long context into semantically complete blocks and avoid rewriting the prefix frequently, which invalidates the cache.
    • Tier precision: keep higher precision for retrieval and localization content, and compress log noise more aggressively.
    • Observability: monitor prefill duration, decode throughput, cache hit rate, and peak GPU memory, and tune with data rather than intuition.
    • Cloud deployment: inference services can run on container platforms, long documents can be stored in object storage, and log services plus monitoring and alerting can close the observability loop, all using general-purpose capability categories.

    6. A Framework for Judging Benefits and Costs

    When evaluating such approaches, fix three variables: task quality (long-range recall accuracy), time to first token (affected by prefill), and cost per unit of throughput (affected by decode bandwidth). If the workload is mainly long input, short output, and frequent continuation, layer-wise heterogeneity plus cross-layer sharing gives the most obvious gains. If it is mainly short input and long output, sequence-dimension compression and precision optimization are more worthwhile.

    7. Conclusion

    The cost of long-context inference is essentially the cost of repeatedly moving historical state. Layer-wise execution reduces compute, cross-layer sharing reduces storage, and low precision plus sequence compression reduce bandwidth. Only when the four are combined can the cache be pushed into an acceptable range while preserving quality. Understanding this general mechanism has more long-term value than memorizing the parameters of any single model.