KV Cache Compression to One-Quarter: Layer Sharing for Long-Context Inference
Long-input, short-output workloads make KV cache memory a major constraint on LLM inference. This article explains how a layered encoder–decoder architecture, cross-layer cache sharing, and lower-precision storage can reduce cache requirements to roughly one-quarter of a comparable conventional design. It also examines the quality trade-offs and deployment practices relevant to coding assistants, retrieval applications, and automated agents.
1. The Problem: Read-Heavy, Write-Light Workloads
A common workload in modern LLM applications involves reading far more text than generating it. A coding assistant or automated agent may receive tens of thousands of words of source code, test logs, and tool output in each interaction, yet produce only a few hundred words of decisions or instructions for the next step.
As the agent loop continues, the compute and GPU memory spent processing input can substantially exceed the resources used for output generation.
These workloads combine long inputs, frequent context extensions, and short outputs. They create two challenges for inference systems:
- Long contexts require large amounts of historical key and value data to remain available.
- Conventional decoder architectures run tokens through the full network depth during both input processing and generation, creating opportunities to reduce redundant computation.
Understanding these costs is essential to making long-context inference more economical.
2. How the KV Cache Works
2.1 The Basics of Attention
Language models split text into tokens. As each token passes through Transformer layers, it produces hidden representations. Attention uses three core tensors:
- Q (Query): The query from the current position, representing the information it needs.
- K (Key): The representation used to assess how relevant a historical position is to the current query.
- V (Value): The vector containing the information retrieved from that position.
For a single query and a single attention head, attention can be expressed as:
o = softmax(q · K^T / sqrt(c)) · V
Here, q ∈ R^(1×c) is the current query, while K, V ∈ R^(t×c) contain the keys and values for t historical positions. The output o is the retrieved information vector. Softmax converts relevance scores into normalized weights.
2.2 Why the Cache Keeps Growing
In autoregressive generation, the keys and values for previous tokens do not change when a new token is generated. They can therefore be stored and reused. This persistent storage is the KV cache.
Its approximate size is:
Cache size ≈ Number of layers × 2 (K and V) × Sequence length× Number of attention heads × Head dimension× Bytes per stored element
Three factors drive cache growth: longer sequences, more layers, and higher storage precision.
For contexts containing hundreds of thousands of tokens, the KV cache can become a more pressing GPU memory constraint than model weights. Even when a request adds just one token at a time, the system still needs access to the historical cache.
3. An Architectural Approach: Layered Encoder–Decoder Processing
3.1 Half-Depth Input Processing, Full-Depth Generation
One approach is to split the network at a layer boundary. In an illustrative 40-layer model, the first 20 layers form a causal encoder, and the remaining 20 form a decoder.
The execution strategy is:
- For long inputs: Tokens primarily pass through the encoder half, producing compressed intermediate representations.
- For new output tokens: Generation still uses the full 40-layer network to preserve output quality.
This design targets read-heavy workloads. Most input tokens need to be understood rather than processed through every decoding layer, so the architecture avoids maintaining full per-layer key and value states for those tokens throughout the network.
3.2 Sharing a Global KV Cache Across Layers
The second optimization is cross-layer sharing of a global KV cache.
Instead of maintaining a separate cache for each decoder layer, multiple layers reference the same global representation. Some layers can also include representations of external documents introduced through retrieval-augmented generation (RAG) in the shared storage, avoiding multiple copies of the same knowledge.
3.3 Lower-Precision Storage
The third optimization reduces storage precision. Storing cached keys and values at a lower quantized bit width reduces their memory footprint in proportion to the storage width. Calibration is needed to control the associated accuracy loss.
Together, these three optimizations can reduce the global KV cache to roughly one-quarter of that required by a comparable conventional architecture, even when compression along the sequence dimension remains conservative.
The engineering distinction matters: most of the memory savings come from layer sharing and reduced precision, rather than aggressive information removal. Heavy sequence compression can damage retrieval quality, while sharing and quantization offer more controllable trade-offs.
4. Engineering Benefits and Trade-Offs
4.1 GPU Memory and Throughput
Reducing the KV cache to one-quarter of its previous size can provide several benefits:
- More concurrent long-context requests per GPU: Smaller caches can support several times as many requests when cache memory is the limiting factor.
- Larger batches: Freed memory allows larger batches, which can improve inference throughput.
- Less cache swapping: Reduced movement of cached data lowers scheduling overhead during long-running agent tasks.
4.2 Quality Risks to Evaluate
Memory savings need to be assessed alongside model quality.
- Representational capacity of the shared cache: A cache used by multiple layers must support sufficiently general representations. Otherwise, it may constrain the more refined attention patterns needed by deeper layers.
- Quantization error: Lower-precision storage requires appropriate dequantization and error-compensation strategies. Retrieval quality should be tested particularly carefully for rare tokens in long sequences.
- Encoder–decoder responsibilities: The split point affects the balance between input understanding and output generation. Its placement requires thorough experimental validation.
4.3 Practical Guidance for Cloud Deployment
Teams deploying long-context inference on cloud infrastructure—including container platforms, GPU clusters, model-serving systems, and monitoring and alerting services—should consider the following practices.
Profile the workload before optimizing.
Measure the actual input-to-output token ratio. If it consistently exceeds 10:1, a layered architecture can offer substantial benefits. Workloads dominated by short conversations are likely to benefit less.Monitor cache-related metrics.
Track KV cache hit rate, GPU memory usage, and batch fill rate alongside latency and throughput.Validate compression through staged rollouts.
A/B test the number of layers sharing a cache and the quantization bit width. Use downstream task accuracy—not perplexity alone—as the acceptance criterion.Coordinate cache placement with agent scheduling.
For multi-turn agent tasks, use session-affinity scheduling to keep requests close to their cached context. This reduces the cost of rebuilding caches after cross-node migration.
5. Conclusion
A central cost of long-context inference comes from the conventional practice of storing separate keys and values for every token at every layer.
A layered encoder–decoder architecture reduces the depth used to process long inputs. Cross-layer sharing reduces duplicate storage, and lower-precision representations further shrink the cache. Together, these techniques can bring the global KV cache down to roughly one-quarter of a comparable conventional design, while concentrating the quality trade-offs on representation sharing and quantization rather than aggressive information removal.
For teams building coding assistants, retrieval-based question answering, and automated agents, this approach offers a practical path to lower long-context inference costs. Realizing those benefits requires workload profiling, task-level quality validation, and cache-aware monitoring and scheduling.
