KV Cache Compression and Sharing for Long-Input Workloads
This article explains why long-input LLM workloads are dominated by reading rather than writing, and walks through three cost-reduction approaches: splitting a network into a causal encoder and decoder, sharing a global KV cache across layers, and combining lower-precision storage with mild sequence-direction compression. It also includes a cache capacity formula and a practical tuning checklist for production deployment.
1. The Problem: Why Reading Costs More Than Writing
In applications such as AI coding assistants, document Q&A, and log analysis, a typical turn looks like this: the tool ingests tens of thousands of words of source code, test output, and call results, and the model eventually emits only a few hundred words describing the next action. Input and output are severely asymmetric in length, so inference resources are dominated by the “read” side.
To see why, go back to the basic Transformer structure. Text is split into tokens, and each token passes through multiple layers to form a hidden vector. Attention layers pull information from the historical context, while feed-forward layers continue the nonlinear processing. Attention commonly uses three symbols: Q, K, and V. Q is the query issued at the current position, K is used to judge the relevance of historical positions, and V carries the content that is actually read back. The computation for a single query and single head 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, c is the number of channels, and o is the result read back. The softmax normalizes relevance scores into weighting coefficients.
When a new token is generated, the K and V of historical positions do not change, so they are cached and reused. 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.” Even to generate a single token, the historical cache must be read into the compute units, so in long-input scenarios both memory footprint and memory-access bandwidth are amplified at the same time.
2. Workload Characteristics: Long Inputs, Frequent Continuations
This kind of workload shares three characteristics:
- Input is far larger than output; the prefill stage is compute-intensive while the decode stage is memory-access-intensive.
- Context must be carried across turns, so the cache has to stay resident over the long term rather than being discarded right after use.
- Intermediate artifacts (source code, logs, tool returns) are highly repetitive, with obvious information redundancy.
The traditional approach of “storing a full-precision cache independently at every layer” is very cost-ineffective under this workload: the vast majority of the cache is moved back and forth repeatedly, yet it serves only a small amount of newly added computation.
3. Approach One: Layering a Causal Encoder and a Decoder
A common approach is to split a deep network into two segments: the front segment acts as a causal encoder that compresses long input into a compact representation, and the back segment acts as a decoder that performs autoregressive generation. Long input mainly runs the front segment; generating new tokens then runs the full network.
The benefit is that the expensive computation over long input is confined to a shallower segment of the network, while each generation step only has to pass through the full network facing an already-compressed context. A sketch:
input tokens -> [causal encoder, several layers] -> compact context representation|new token -> [decoder, several layers] <--------------+
Note that this layering is not free: an interface for the representation must be agreed upon between the encoder and the decoder, and the generation stage still has to read the cache. It must therefore be combined with cache sharing and precision optimization to bring end-to-end cost down.
4. Approach Two: Cross-Layer Global KV Cache Sharing
If every layer keeps an unrelated copy of the cache, the redundancy is severe. A more aggressive approach is to set up a single global cache shared by multiple layers; some layers even reuse retrieval results or intermediate results as well, leaving only a few layers to maintain independent state.
This has two direct effects: first, the number of cache copies drops from “proportional to the number of layers” to a constant; second, the number of memory accesses falls, since the decode stage no longer has to read in multiple near-duplicate caches repeatedly. The cost is that the model must learn during training to work on the shared representation, which places higher demands on the training strategy and data mix.
5. Approach Three: Lower Storage Precision and Mild Sequence-Direction Compression
There are two more sources of savings:
- Storage precision: the cache is stored at lower numerical precision, combined with the necessary scaling and outlier handling, which substantially shrinks its size at an acceptable quality loss.
- Sequence-direction compression: compress moderately along the sequence dimension rather than pruning aggressively, avoiding the excessive loss of critical information in long inputs.
Stacking the three together produces a phenomenon worth explaining: even with lighter sequence-direction compression, the total global cache can still drop to roughly a quarter of the previous generation. The reason is not contradictory — the total is determined jointly by “number of copies × size per copy × precision,” and the reduction from cross-layer sharing and low precision far outweighs the rebound from relaxing sequence compression.
6. Engineering Practice: Capacity Estimation and a Tuning Checklist
Before going live, it is advisable to do a capacity calculation first and then decide on the parameter combination:
cache bytes ≈ layers (or shared copies) × sequence length × channels × bytes per element × 2 (K and V)
Tuning can proceed in the following order:
- Measure the input/output length distribution of the real workload and confirm whether long inputs dominate.
- Enable cross-layer sharing first and observe whether quality metrics stay stable.
- Then introduce low-precision storage and perform a layer-by-layer sensitivity analysis.
- Finally adjust the sequence compression strength, preserving critical segments.
- Use monitoring alerts and logging services to continuously track hit rate, cache residency time, and tail latency.
For cloud deployment, you can combine a container platform to host inference instances, object storage to hold session intermediate artifacts, and a message queue to decouple tool calls, forming a complete long-context inference pipeline.
7. Conclusion
The core tension in long-input workloads is “read a lot, write a little.” Splitting the network into a causal encoder and a decoder, letting multiple layers share a global cache, and storing state at lower precision with mild sequence compression are three widely accepted cost-reduction paths in the industry. Understanding the formula that governs cache size is what makes it possible to make explainable, reproducible trade-offs among quality, latency, and cost.
