Cross-Layer KV Sharing: Reducing KV Cache Memory for Long-Context LLM Inference
This article explains why the KV cache has become a memory bottleneck in LLM inference and how standard techniques such as GQA, quantization, sliding-window attention, and paged memory management reduce it. It then focuses on cross-layer KV sharing, which compresses the layer dimension of the cache, and covers the main engineering considerations for implementing it, including sharing-group design, RoPE compatibility, cache management in inference frameworks, and evaluation.
Introduction: Why the KV Cache Has Become the Core Constraint in the Inference Era
Large language models keep getting more capable, but the focus of model architecture design is shifting. The question is no longer only “how to train a stronger model” but also “how to run models more efficiently.” As reasoning models and AI agents see wide deployment, a single request often carries thousands or even tens of thousands of tokens of context. At inference time, GPU memory usage quickly becomes a system bottleneck.
The KV cache is central to this problem. Whether it is the cross-layer KV tensor reuse adopted by recent mainstream open-source models or the grouped-query attention (GQA) that is already widespread, both approaches answer the same question: how to shrink the KV cache as much as possible with little or no loss in model quality.
This article takes a neutral technical view. It explains the memory cost of the KV cache, the principles and trade-offs of the main compression techniques, and the implementation approach and engineering recommendations for cross-layer sharing.
1. How Large the KV Cache Memory Cost Really Is
In standard autoregressive inference, each time the model generates a new token, it computes attention over the keys and values of all previous tokens. Without caching, these intermediate results would be recomputed at every step, and the computation would grow quadratically with sequence length. The KV cache trades space for time by keeping the historical key and value tensors in GPU memory.
The memory footprint can be estimated with a simple formula:
KV cache size ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element
The factor of 2 accounts for the key and value tensors. Take a medium-sized model with 48 layers, 8 KV heads, a head dimension of 128, and FP16 precision (2 bytes per element). With a batch size of 1 and a context length of 128K:
2 × 48 × 8 × 128 × 131072 × 2 ≈ 25.8 GB
The KV cache for a single request can consume the entire memory of a mid-range GPU. Multiple concurrent requests multiply this pressure. This is why reducing the KV cache has become a main goal of architecture design. It directly determines how much context a single GPU can handle, how many requests it can serve at once, and the cost of inference.
2. Established Approaches to KV Cache Compression
Before discussing cross-layer sharing, it helps to review the mature techniques and identify which factor in the formula each one reduces.
2.1 Grouped-Query Attention (GQA): Reducing the Number of KV Heads
In standard multi-head attention (MHA), each query head has its own key and value head. GQA lets multiple query heads share one set of KV heads, which directly reduces the num_kv_heads term. For example, if 32 query heads share 8 KV heads, the KV cache shrinks to one quarter of its original size, usually with only a small loss in quality. In the extreme case, a single KV head is kept, which is called multi-query attention (MQA). This gives a higher compression ratio but has a more noticeable effect on expressive capacity.
GQA is now standard in mainstream open-source models. However, it compresses the “horizontal” dimension (heads) and does nothing for the “vertical” dimension (layers).
2.2 Quantization and Low-Precision Storage: Reducing Bytes per Element
Storing the KV cache in INT8 or even INT4 instead of FP16 can save another 2× to 4× in memory. Combined with techniques such as group-wise quantization and per-channel scaling, the accuracy loss can be kept within an acceptable range. The cost is the extra computation for quantization and dequantization, which places demands on kernel implementation.
2.3 Sparse Attention and Sliding Windows: Reducing Sequence Length
Sliding-window attention lets some layers attend only to a fixed window of the most recent tokens. A small number of global layers maintain long-range dependencies. This reduces the KV cache for these layers from O(n) to O(w), where w is the window size. Other methods use token eviction strategies based on importance scores to decide dynamically which historical tokens to keep.
2.4 Paged Memory Management: Eliminating Fragmentation
These methods do not change the model architecture. Instead, they borrow the idea of virtual memory from operating systems. The KV cache is split into fixed-size blocks that are allocated on demand. This addresses the internal fragmentation caused by reserving memory in advance, improves memory utilization significantly, and supports continuous batching.
3. Cross-Layer KV Tensor Sharing: A New Way to Reduce the Layer Dimension
With the techniques above in view, the motivation for cross-layer sharing is clear. GQA compresses heads, quantization compresses bytes, and sliding windows compress length, but the number of layers has never been addressed.
The core observation behind cross-layer sharing is that adjacent Transformer layers often extract key and value representations that are strongly correlated for the same span of text. Therefore, each layer does not need to compute and store its own KV. Subsequent layers can directly reuse the KV states already computed by an earlier layer.
3.1 Basic Structure
A typical implementation divides the layers into groups. All layers in a group share one set of KV tensors:
Layer 0 → compute and store KV_0Layer 1 → reuse KV_0 (computes only its own query)Layer 2 → reuse KV_0Layer 3 → compute and store KV_1Layer 4 → reuse KV_1...
If every three layers of a 48-layer model share one set of KV tensors, the number of stored KV sets drops from 48 to 16. The KV cache shrinks directly to one third of its original size. This gain is orthogonal to GQA and quantization, so the techniques can be combined.
3.2 Why This Approach Deserves Attention
Research around 2024 systematically validated the feasibility of cross-layer attention. With carefully chosen sharing strategies, such as sharing every other layer or sharing only even-numbered layers, the performance loss on downstream tasks typically stays small, while the memory savings are substantial. Recently, several mainstream open-source model families have begun applying this mechanism at scale in released architectures. This marks a shift of the technique from research papers to production practice. It matters most for models designed for edge and small devices, where every gigabyte saved lowers the deployment barrier.
3.3 Value for On-Device Deployment
On mobile and embedded devices, memory is often only 4 to 8 GB and must be shared with the operating system and other applications. Combining cross-layer sharing with GQA and quantization can reduce the KV cache to one tenth of its original size or less. This allows small-parameter models to support tens of thousands of tokens of context locally, which opens up use cases such as on-device document Q&A and long-conversation assistants.
4. Key Engineering Considerations
Cross-layer sharing looks simple, but several engineering issues must be handled in practice.
First, designing the sharing groups. Not every layer is a good candidate for sharing. The lower layers near the input and the upper layers near the output usually differ more in semantics, while the middle layers tend to be more correlated. In practice, it is advisable to determine the group size through small-scale ablation experiments. For example, compare the effects of “sharing every 2 layers” and “sharing every 4 layers” on perplexity and downstream task metrics, then find the balance between compression ratio and quality.
Second, compatibility with RoPE position encoding. If all layers use the same rotary position embedding (RoPE) parameters, sharing KV is naturally compatible. If the architecture applies different position encoding transformations to different layers, these must be handled consistently during sharing. Otherwise, subtle accuracy problems can occur.
Third, support in inference frameworks. Cross-layer sharing changes the assumption that each layer has its own KV cache. The cache management module of an inference framework must support the semantics of one KV block being referenced by multiple layers. It must also correctly track reference counts and determine when memory can be released. A sample implementation is shown below:
class SharedKVCache:def __init__(self, num_groups, max_len, head_dim, num_kv_heads):# Allocate only one KV buffer for each sharing groupself.buffers = [torch.zeros(2, num_kv_heads, max_len, head_dim)for _ in range(num_groups)]def get_kv(self, layer_id, sharing_map):group_id = sharing_map[layer_id] # layer -> sharing group mappingreturn self.buffers[group_id]
Fourth, combining with other compression techniques. Cross-layer sharing does not replace GQA or quantization. It stacks on top of them. First reduce the number of KV heads with GQA, then reduce the layer factor with cross-layer sharing, and finally quantize the stored KV tensors to INT8. Together, these three techniques can achieve a total compression of more than an order of magnitude.
Fifth, quality evaluation. Before any compression technique goes live, run regression evaluations. Long-context retrieval benchmarks such as “needle in a haystack” tests, long-document summarization, and multi-turn dialogue consistency are the most sensitive to KV compression, so they must be included in the evaluation set.
5. Implications for Cloud Deployment
For teams that offer large model inference services in the cloud, KV cache compression translates directly into cost savings. When a single GPU can serve more concurrent requests, the compute needed for the same traffic goes down. Combining the elastic scaling of container platforms, object storage for model weights, and monitoring that tracks memory usage and time to first token can produce an inference infrastructure that balances cost and service quality. Some cloud providers also offer ready-to-use large model inference services. Developers can weigh self-hosting against managed services based on their requirements for latency, concurrency, and customization.
Conclusion
The path from GQA to cross-layer sharing shows a clear logic in KV cache optimization. Break down the memory formula factor by factor, and use structural priors to gain memory savings. Cross-layer KV tensor reuse targets the layer dimension, which no earlier technique had addressed, and offers a new lever for long-context inference, especially on-device deployment. As inference workloads keep growing, architecture innovation and system optimization around the KV cache will likely remain one of the most active areas in large model engineering for some time.
