KV Cache Compression and Sharing in Long-Context Inference: A Practical Breakdown
This article explains why reading context costs more than writing it in long-context LLM inference, and how KV cache compression and sharing reduce memory usage. It covers the KV cache memory formula, the prefill and decode stages, three orthogonal optimization paths (sequence compression, cross-layer sharing, and lower precision), encoder-decoder style layer partitioning with a shared global cache, precision and engineering checklists, and common pitfalls to avoid.
1. The Problem: Why Reading Costs More Than Writing
In applications like AI coding assistants, document Q&A, and log analysis, a typical request looks like this: the model reads back tens of thousands of words of source code, test logs, and tool-call output, then produces only a few hundred words describing the next action. Input length far exceeds output length, and the same session repeatedly extends its context. This workload shifts the pressure on the inference system from “generation speed” to “context capacity and reuse.”
To understand why, recall the basics of autoregressive generation. Each time the model generates a new token, it theoretically needs to run attention over all historical positions. Recomputing history at every step makes the computation grow quadratically with sequence length. The standard engineering fix is the KV cache: store the already-computed keys (K) and values (V) for historical positions and reuse them in later steps, reducing per-step computation to linear.
The cost is GPU memory. Cache size can be approximated as:
cache_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × bytes_per_value
Here, 2 accounts for the two copies (K and V), layers is the number of layers, kv_heads is the number of key-value heads being cached, head_dim is the number of channels per head, seq_len is the context length, and bytes_per_value is the storage size of a single value in bytes. The formula shows that cache usage is proportional to the number of layers, sequence length, and storage precision. In long-context scenarios, seq_len often reaches tens of thousands, so any reduction in a single factor is amplified into meaningful memory savings.
2. The Intuition Behind Attention and the Origin of the Cache
Think of Q, K, and V as “the query, the basis for judging relevance, and the content being read back.” Single-head attention can be written schematically as:
o = softmax(q · Kᵀ / sqrt(c)) · V
q is the query vector at the current position, K and V hold information from t visible historical positions, c is the number of channels, and softmax normalizes relevance scores into weighting coefficients. The key point: K and V depend only on historical tokens and model parameters, not on the current query. That is why they can be cached, reused, and even shared across layers—the foundation for the optimizations discussed later.
A request naturally splits into two stages:
- Prefill: process all input tokens at once, writing to the cache layer by layer. This stage is compute-intensive and the main source of cache growth.
- Decode: process one new token at a time, reading the entire historical cache. This stage is memory-access intensive, with the bottleneck often in memory bandwidth rather than compute.
A long-input, short-output workload means the cache produced during prefill is read repeatedly during decode, further amplifying the “resident cost” of the cache.
3. Three Orthogonal Optimization Paths
Approaches to reducing cache usage fall into three broad categories that are orthogonal and stackable:
- Compress along the sequence dimension: reduce the information stored per position, for example by sharing keys and values across adjacent positions or applying low-rank/sparse approximations to the cache. The gains are direct, but over-compression loses precision on long-range dependencies.
- Share across layers: let multiple layers reuse the same global cache, turning layers from a multiplicative factor into a shared one. The gains are significant, but require different layers to have sufficiently similar key-value needs.
- Lower storage precision: switch the cache from high-precision floating point to a lower-bit representation, directly reducing bytes_per_value. Simple to implement, but requires quantization error control.
One counterintuitive point deserves emphasis: when sequence-dimension compression is done more “lightly” (each position retains more information), total global cache size can actually be lower. The reason is that total usage is a product of factors, and the gains from cross-layer sharing and lower precision can more than offset the overhead of retaining more information per position. When evaluating optimizations, look at the product, not any single factor.
4. Layered Architecture: An Encoder-Decoder Style Split
An effective structural design splits the network vertically into two segments: the first several layers form a “causal encoder” that compresses long input into a compact representation, and the last several layers form a “decoder” that generates new tokens from that compressed representation.
The operating logic is:
- When processing long input, mainly run the first half, encoding the raw context into the global cache chunk by chunk.
- When generating new tokens, run the full network, but the first half only reads the cache without recomputing history.
The engineering value is that it decouples “expensive context absorption” from “frequent small-step generation”: the former runs once, the latter runs repeatedly at low memory-access cost—a good match for long-input, short-output workloads.
A schematic scheduling logic:
if stage == "prefill":for chunk in input_chunks:h = encoder_forward(chunk) # first half onlyglobal_cache.update(h) # write to shared cacheelse:h = encoder_read(global_cache) # read, no recomputeout = decoder_forward(h, new_token) # full network
5. Shared Global Cache and Reuse Across Selected Layers
On top of the layered architecture, multiple layers can share the same global KV cache instead of each storing its own. Going further, some layers can also reuse intermediate retrieval or encoding results, avoiding repeated computation and storage.
The prerequisite is sufficient homogeneity across layer representations: if key-value distributions differ greatly between layers, sharing hurts quality. In practice, sharing is usually limited to groups of adjacent or functionally similar layers, while keeping a small number of “independent layers” for critical feature transformations. Cache lifecycle management also matters: release promptly when a session ends, and evict the least-recently-used chunks by block during long sessions so the shared cache does not become a new source of memory leaks.
6. Precision and an Engineering Checklist
Low-precision storage is the most direct win, but it needs supporting measures:
- Apply low precision only to the cache, keeping weights and activations at higher precision to control error propagation;
- Retain higher precision for channels with many outliers, or use group-wise quantization;
- Complete quantization during prefill to avoid the extra overhead of repeated conversion during decode.
To reproduce similar results in your own system, use this checklist:
- Measure first: profile the input/output length distribution of real requests to confirm whether the workload is long-input, short-output.
- Then locate: use monitoring alerts and log services to observe whether the memory peak occurs during prefill or decode.
- Optimize after: validate one variable at a time in the order precision → sequence compression → cross-layer sharing.
- Look at the product: evaluate with end-to-end total cache size, time-to-first-token, and throughput as unified metrics.
- Have a fallback: set chunking and summarization strategies for extremely long contexts, and if necessary offload historical chunks to object storage and fetch them on demand.
7. Common Pitfalls
- Looking at single-point gains: lighter sequence compression does not mean a larger cache; look at the product of cross-layer sharing and precision.
- Ignoring the bandwidth bottleneck: decode is often limited by memory bandwidth, so simply increasing compute yields limited gains.
- Over-sharing: too wide a cross-layer sharing scope loses precision; keep a small number of independent layers.
- No eviction strategy: without lifecycle management, a shared cache keeps growing in long sessions.
8. Summary
The core tension in long-context inference is between input scale and the resident cost of the cache. Vertical layering decouples context absorption from token generation, cross-layer sharing eliminates redundant storage, and low-precision compression reduces per-value overhead; stacking the three can substantially cut cache usage without significantly sacrificing quality. For developers, the real key is to first quantify workload characteristics, then validate optimizations one by one from a product perspective, backed by solid chunking, eviction, and monitoring mechanisms.
