KV Cache Compression for Long-Input, High-Concurrency LLM Inference

    This article explains why reading the KV cache costs more than writing it in long-context, high-concurrency LLM serving. It covers the attention mechanism, the prefill and decode execution stages, and a capacity estimation formula, then walks through three general optimization paths: encoder-decoder layered execution, cross-layer sharing of a global cache, and low-precision storage combined with sequence-direction compression. It also offers practical guidance for coding assistant workloads, including capacity baselines, per-factor attribution, and quality guardrails.

    KV Cache Compression for Long-Input, High-Concurrency Inference

    1. Background: Why Reading Costs More Than Writing

    In applications such as AI coding assistants, long-document question answering, and log analysis, a typical request is highly asymmetric. The input can contain tens of thousands of words of source code, test logs, and tool-call results, while the output is only a few hundred words describing the next decision or a short code snippet. This workload—very long input, very short output, and multiple turns that continue against the same context—is fundamentally different from a traditional short-question, short-answer workload.

    Multi-turn continuation means the same long context is processed repeatedly. Recomputing the entire history on every turn wastes a large amount of compute. The common engineering practice is to cache the intermediate states of historical tokens, which is where the KV cache comes from. The problem is that the cache grows linearly with sequence length and with the number of layers. Under long inputs it quickly becomes the dominant consumer of GPU memory, which in turn limits both the number of concurrent requests and the supported context length.

    Compressing the KV cache without noticeably degrading generation quality has therefore become a core engineering topic for long-context inference serving.

    2. Core Mechanics: Attention, the KV Cache, and Two-Stage Execution

    2.1 Starting from Q, K, and V

    A language model splits text into tokens. Each token passes through multiple Transformer layers and forms hidden vectors layer by layer. In the attention mechanism, Q is the query issued from the current position, K measures the relevance of historical positions, and V carries the information that is actually read back. The computation for a single query and a single attention head can be abstracted as:

    1. o = softmax(q · Kᵀ / sqrt(c)) · V

    Here q is the current query vector, K and V are the key and value matrices for t visible historical positions, c is the number of channels, and o is the result read back. Dividing by sqrt(c) is a common numerical stability measure. This formula is only meant to build intuition; real systems also introduce designs such as grouped-query attention and compression projections that change the storage layout.

    2.2 The Two-Stage Execution Model

    An inference request is usually split into two stages:

    • Prefill: all input tokens are processed in parallel to build the state needed for subsequent generation. This stage is compute-intensive and is the main source of cache writes.
    • Decode: new tokens are generated one at a time, and every step reads the historical cache. This stage is memory-access intensive; the compute per step is small but dominated by cache-read overhead.

    Key takeaway: even when the decode stage produces only one token, it depends on the complete historical cache. The larger the cache, the higher the per-step latency and the lower the achievable concurrency.

    2.3 A Rough Estimate of Cache Capacity

    Without compression, the cache size for a single layer and a single request can be approximated as:

    1. bytes ≈ 2(K and V) × layers × seq_len × kv_channels × dtype_bytes × batch

    This expression points to three cost-reduction paths: reduce the contribution of layers (cross-layer sharing), reduce storage along the sequence dimension (compression or sparsification), and lower dtype_bytes (lower-precision storage). The techniques discussed below map directly onto these three paths.

    3. General Optimization Path 1: Layered Encoder-Decoder Execution

    One architectural idea that pays off clearly under long-input workloads is to split the network by function into two segments: a front segment responsible for encoding the long input into a compact representation, and a back segment responsible for autoregressive generation from that representation.

    • When processing long inputs, mainly the front encoder runs, avoiding repeated computation across the full network over an extremely long sequence.
    • When generating new tokens, the full network runs, preserving the expressive power of the generation stage.
    • The compact state produced by the front segment can be reused by the back segment, reducing repeated encoding.

    The benefits of layered execution have two sides: it lowers the compute peak during prefill, and it confines the “long sequence” to the front segment, so the context size the back segment faces is compressed and cache pressure is indirectly reduced. Note that a layered design affects model expressiveness and training complexity; it is an architecture-level trade-off, and evaluation sets should be used to verify whether any quality regression stays within an acceptable range.

    4. General Optimization Path 2: Cross-Layer Sharing of a Global Cache

    If every layer keeps its own copy of K and V, the cache inflates linearly with the number of layers. The idea behind cross-layer sharing is to let multiple layers read the same global cache, with some layers even reusing retrieval or encoding results directly instead of maintaining separate copies.

    The gains come from:

    1. Eliminating redundant copies: layers have highly overlapping information needs for similar contexts, so sharing can substantially reduce duplicate storage.
    2. Lowering write amplification: during prefill, the global state only needs to be written once, reducing pressure on memory bandwidth.
    3. Improving cache hit rate: with multi-turn continuation, a global cache is reused more fully.

    Engineering-wise, consistency has to be handled: which layers can share and which must keep independent state is usually determined through offline ablation experiments. Sharing too much loses the ability to model layer-level differences; sharing too little yields limited cost savings.

    5. General Optimization Path 3: Low-Precision Storage and Sequence-Direction Compression

    The third path acts on how many bytes each element occupies and how many positions are retained along the sequence.

    • Low-precision storage: store the cache in a format lower than the training precision, with scaling factors to control the numerical range. The benefit is direct and the implementation cost is relatively low, but accumulated error over long sequences needs attention.
    • Sequence-direction compression: reduce the number of cached positions through pooling, windowing, sparse retention, and similar methods. The more aggressive the compression, the greater the loss of distant information.
    • Combining the two: first compress the number of positions, then lower the precision per element; capacity drops roughly by the product.

    A common misconception is that making sequence-direction compression lighter will reduce total cache size proportionally. If cross-layer sharing and low-precision storage contribute most of the reduction, you can end up with more conservative sequence compression yet a smaller total cache. This shows that cache optimization is a multiplicative effect of several techniques, and evaluation must attribute results per factor rather than looking at a single metric.

    6. Practical Recommendations for Coding Assistants

    1. Choose by workload: for long-input, short-output, multi-turn continuation scenarios, evaluate layered execution and cross-layer sharing first; the gains are limited for short-question, short-answer scenarios.
    2. Establish a capacity baseline: use the estimation formula to compute the unoptimized cache size, then enable optimizations one by one and measure the actual reduction.
    3. Attribute per factor: record the contributions of layer count, sequence length, and precision separately to avoid confusing conclusions.
    4. Guard quality: use business metrics such as code completion accuracy, unit test pass rate, and instruction-following rate as red lines for regression.
    5. Coordinate on the serving side: combine request scheduling, context reuse, and general cloud capabilities such as logging services and monitoring alerts to observe cache hit rate and per-step latency, forming a closed tuning loop.

    7. Conclusion

    The cost center of long-context inference lies in reading rather than writing. Given the resource differences between the prefill and decode stages, starting from layered encoder-decoder execution, cross-layer sharing of a global cache, and low-precision storage with sequence compression can significantly reduce cache usage while keeping quality regression under control. The key is to build an interpretable capacity model and a per-factor attribution method, so optimization decisions rest on data rather than intuition.