KV Cache Compression and Sharing for Long-Input Workloads
This article explains why reading is more expensive than writing in long-input LLM workloads, how the KV cache forms from the K and V matrices in attention, and four orthogonal optimization approaches: sequence-direction compression, cross-layer sharing, low-precision storage, and stage separation. It walks through a layered encoder-decoder execution design, shows how sharing and precision reduction can shrink the cache to roughly one quarter of the previous size, and provides a capacity estimation formula along with practical deployment recommendations.
1. Background: Why Reading Costs More Than Writing
In applications such as AI coding assistants, document Q&A, and log analysis, a single interaction is often highly asymmetric: the model reads back tens of thousands of words of source code, test logs, and tool-call outputs, then produces only a few hundred words describing the next action. If resource consumption is split between the input and output sides, the input side easily becomes the dominant cost.
These workloads share three characteristics:
- Inputs are long and highly repetitive, with the same context carried repeatedly;
- Sessions span many turns and must continually extend prior history rather than being processed in one pass;
- Outputs are short, so the compute used during generation is far smaller than that used during encoding.
Traditional inference implementations treat every turn as a full forward pass, causing substantial redundant computation and memory usage. To understand where the optimization headroom lies, it helps to first see where the cache comes from.
2. Where the Cache Comes From: K and V in Attention
A language model splits text into tokens. Each token passes through multiple Transformer layers, forming hidden vectors layer by layer. Attention retrieves information from historical positions, while the feed-forward network continues the processing. The notation Q, K, and V describes this process: Q is the query at the current position, K is used to judge the relevance of historical positions, and V carries the content actually read back.
Single-query, single-head attention can be written as:
o = softmax( q * K^T / sqrt(c) ) * V
Here q is a 1×c query vector, K and V are t×c historical matrices, t is the visible history length, and c is the number of channels. The softmax normalizes relevance scores into weights.
The key point is that when generating a new token, the K and V values at historical positions do not change and can be reused directly. Systems therefore retain them, and this is the KV cache. If one copy is stored per layer, the cache size is roughly proportional to “layers × sequence length × channels × bytes per value of precision.” With sequences in the tens of thousands and dozens of layers, the cache quickly squeezes available GPU memory and limits the concurrent batch size.
3. The General Optimization Landscape: Four Approaches, Each Addressing One Part
Common cache management techniques in the industry fall into four categories. They are orthogonal to one another and can be stacked:
- Sequence-direction compression: reduce the number of channels stored per position or the granularity of history, shrinking the product of t and c.
- Cross-layer sharing: let multiple layers reference the same global cache, removing the “layers” factor from the multiplication.
- Low-precision storage: carry keys and values in fewer bytes, directly compressing the precision factor.
- Stage separation: split long-input encoding from token-by-token generation into different execution paths to avoid redundant computation.
It is worth emphasizing that these four approaches do not yield equal benefits. The more aggressively the sequence direction is compressed, the more the global cache reduction may fall short of expectations, because total cache size is also governed by the number of layers and the precision.
4. Layered Execution: A Causal Encoder and a Decoder
A typical approach splits the network by depth into two segments: the front segment acts as a causal encoder and is the main part that runs when processing long inputs; the back segment acts as a decoder and, during generation of new tokens, forms the complete network together with the encoder segment.
The logic looks roughly like this:
def forward(input_ids, past_cache, mode):if mode == "prefill": # Long-input encodingh = encoder_layers(input_ids, past_cache)return h, build_cache(h)else: # Incremental generationh = encoder_layers(last_token, past_cache)return decoder_layers(h), past_cache
This split brings two benefits: the encoding stage only handles computation for part of the layers, and the generation stage reuses the already-built cache without recomputing history. For workloads with long inputs and short outputs, the benefit is especially pronounced.
5. Sharing and Reuse: Why the Cache Can Drop to One Quarter
Building on the layered design, if multiple layers share the same global KV cache and some layers even directly reuse retrieval results, the “layer factor” of the cache is greatly weakened. Combined with lower storage precision, a total drop to about one quarter of the previous generation follows the multiplicative relationship: the layer contribution is diluted by sharing, the byte count is compressed by precision, and only light compression in the sequence direction is needed to hit the target.
This explains a counterintuitive phenomenon: lighter sequence-direction compression can still yield a smaller global cache. The savings come mainly from cross-layer sharing and storage precision, not from cutting each position more aggressively.
6. Capacity Estimation and Deployment Recommendations
In engineering practice, the following formula gives a rough capacity estimate:
cache_bytes ≈ layers_effective × seq_len × channels × bytes_per_value × batch
Here layers_effective is the number of layers actually stored independently after sharing, typically far smaller than the physical layer count. For deployment, the recommendations are:
- First quantify workload characteristics by measuring the input length distribution and the number of turns;
- Enable cross-layer sharing and low-precision storage first, then consider sequence-direction compression;
- Set an upper bound and eviction policy for the cache to prevent unbounded growth in long sessions;
- Track cache hit rate and memory usage with monitoring and alerts, and build capacity planning on data accumulated through general capabilities such as object storage and logging services.
7. Conclusion
The core tension in long-input workloads is the conflict between repeated reads and limited GPU memory. Layered execution, cross-layer sharing, and low-precision storage working together are more effective than compressing at a single point. Understanding how each factor enters the multiplicative relationship is what makes it possible to make explainable, reproducible trade-offs between capacity and quality.
