KV Cache Compression and Sharing for Long-Context LLM Inference
This article explains why read-heavy, write-light workloads put the most pressure on the KV cache during long-context inference, and how a layered causal encoder plus decoder design, cross-layer cache sharing, and lower-precision storage reduce memory usage and redundant computation. It covers what the cache stores, how workload characteristics shape optimization priorities, practical implementation steps, evaluation guidance, and common pitfalls to avoid.
1. Background: Why Read-Heavy, Write-Light Workloads Strain the Cache
In applications such as AI coding assistants, document Q&A, and log analysis, a typical interaction looks like this: after a tool modifies files, the model must read back tens of thousands of words of source code, test output, and stack traces, yet it produces only a few hundred words describing the next action. Input and output lengths are severely asymmetric, and context continues to accumulate across turns.
This type of workload puts pressure on the inference system in two places: the attention computation over long sequences, and the GPU memory occupied by the historical key-value cache (KV cache). Even when generating a single new token, the system must read from the historical cache, and the cache does not shrink just because the output is short.
2. The Basics: What the Cache Actually Stores
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, and the feed-forward network continues to process it. In attention, Q, K, and V can be understood as follows: Q is the query at the current position, K is used to determine the relevance of historical positions, and V carries the content that gets read back. The computation for a single query and single head can be written as:
o = softmax( q * K^T / sqrt(c) ) * Vq ∈ 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. During generation, the K and V of historical positions can be reused, so they are cached. If one copy is stored per layer, the cache size grows roughly linearly with “number of layers × sequence length × number of channels × precision,” which is the root cause of tight GPU memory in long-context scenarios.
3. Let Workload Characteristics Drive the Optimization Direction
Stating the optimization goals clearly keeps the approach from drifting:
- Prefill phase: processes the long input all at once, is compute-intensive, and determines time to first token.
- Decode phase: generates tokens one by one, is memory-access-intensive, and cache read bandwidth determines throughput.
- Continuation scenarios: multiple turns share a prefix, so redundant computation and redundant storage both occur.
The conclusion is straightforward: for long-input workloads, prioritize reducing “storage volume” and “redundant computation” rather than aggressively compressing the information in the sequence direction.
4. Layered Design: Causal Encoder Plus Decoder
One viable structure splits the network by depth into two segments: the front segment acts as a causal encoder and runs mainly when processing long inputs; the back segment acts as a decoder and runs the full network when generating new tokens. This brings three benefits:
- Lower computation in the prefill phase, improving time to first token;
- Representations of the long input are processed centrally, making unified caching easier;
- The generation phase retains full expressive power, keeping quality degradation controllable.
Illustration (pseudocode):
# Prefill: run only the front encoder segmenthidden = encoder_layers(tokens)cache = hidden.kv # handed to the cache layer for unified management# Decode: encoder output + new token go through the full networkfor step in range(max_new_tokens):hidden = decoder_layers(embed(next_token), cache)cache = cache.append(hidden.kv)
5. Cache Sharing and Low-Precision Storage
Building on the layered design, two further steps help:
- Share a global cache across layers: multiple layers reuse the same global key-values, and some layers even reuse the retrieval results, avoiding repeated per-layer writes;
- Reduce storage precision: store historical key-values at a lower bit width, trading acceptable precision loss for gains in memory and bandwidth.
These two are a different dimension from sequence-direction compression: the former reduces “how many copies are stored and how wide each one is,” while the latter reduces “how long each one is.” As a result, it is entirely possible to see lighter sequence compression while the global cache still drops to roughly one quarter of the previous generation—the savings come mainly from sharing and precision, not from more aggressive sequence pruning.
6. Implementation and Evaluation
Recommended order of work:
- Measure the input/output length distribution and continuation turns of real workloads to set optimization priorities;
- Build a memory budget table showing how much each of layers, sequence length, channels, and bit width contributes;
- Compare time to first token, decode throughput, and output quality on a unified evaluation set, avoiding single-metric optimization;
- Combine container platforms, logging services, and monitoring alerts to continuously observe cache hit rate and memory levels.
7. Common Pitfalls
- Focusing only on sequence compression ratio while ignoring the larger gains from cross-layer sharing;
- Evaluating a long-context approach with short-input benchmarks, leading to distorted conclusions;
- Skipping quality regression after lowering precision, so problems surface only after release.
Overall, the focus of long-context inference optimization has shifted from “single-point compression” to the systems engineering of “layered structure + cache sharing + precision coordination.” Understanding the independent role of each dimension is what enables explainable, reproducible performance decisions.
