Cross-Layer KV Tensor Reuse: A Practical Guide to KV Cache Compression for LLMs
KV Cache is a major memory bottleneck in long-context LLM inference. This article explains how cross-layer KV reuse—letting multiple Transformer layers share the same Key-Value tensors—compresses the cache along the layer dimension. It covers the core idea, a simplified implementation, how to combine it with GQA, quantization, and sliding-window attention, and how to evaluate accuracy and deploy the optimization in production.
1. The Memory Bottleneck of Long-Context Inference: Why KV Cache Matters
During autoregressive inference in large language models, generating each new token requires attention between that token and all previous tokens. To avoid recomputing the Key and Value projections of historical tokens at every step, inference systems universally adopt KV Cache: the K and V tensors computed by each attention layer are cached in GPU memory and read directly by subsequent decoding steps.
The memory footprint of KV Cache can be estimated with the following formula:
Memory ≈ 2 × number of layers × sequence length × hidden dimension × batch size × bytes per element
The factor of 2 comes from storing both K and V. Memory usage scales linearly with the number of layers and sequence length. When a model has dozens of layers, the context extends to tens of thousands of tokens, and concurrent batch sizes grow, KV Cache can easily consume tens of gigabytes of memory—sometimes more than the model weights themselves. This leads to three engineering consequences: limited context length per GPU, reduced inference concurrency, and significantly higher deployment costs for long-text scenarios.
As a result, KV Cache compression has become a core topic in inference systems. Common industry approaches include multi-query attention and grouped-query attention (reducing KV heads per layer), KV quantization (reducing bytes per element), sliding-window attention (truncating the sequence dimension), and the focus of this article: cross-layer KV reuse (shrinking the layer dimension).
2. The Core Idea of Cross-Layer KV Reuse
The key observation behind cross-layer reuse is that attention patterns in adjacent Transformer layers are strongly correlated—not every layer needs its own independent Key-Value state. Therefore, several subsequent layers can directly share the K and V tensors already computed by an earlier layer, compressing cache size along the “layer” dimension by a constant factor.
A typical grouped-sharing design works as follows:
- Divide all L layers into groups of G layers each;
- The first layer of each group computes and caches K, V normally;
- The remaining layers in the group do not maintain their own KV cache. Instead, they reuse the K and V of the group’s first layer, keeping only their own attention output projections and feed-forward network parameters.
In this way, the layer factor in total KV Cache size drops from L to L/G. With G=2, cache size is cut in half, with almost no additional computation—reuse is a read operation, not a recomputation.
It is worth noting that this idea has a published research foundation. Related papers presented at major academic conferences have proposed the Cross-Layer Attention framework and verified that, across various model scales, halving or further reducing the number of KV layers keeps downstream accuracy loss within a small range. Recently, some new model architectures targeting edge and local inference have natively incorporated shared KV Cache mechanisms, indicating that this direction is moving from research into engineering practice.
3. A Simplified Implementation
The following simplified code illustrates the logic of cross-layer KV sharing (tensor shape details omitted):
class SharedKVDecoderLayer(nn.Module):def forward(self, hidden, kv_cache, layer_id, group_size=2):if layer_id % group_size == 0:# First layer of the group: compute and write to the KV cachek = self.k_proj(hidden)v = self.v_proj(hidden)kv_cache.write(group_id=layer_id // group_size, k=k, v=v)else:# Other layers in the group: read the group leader's KV directlyk, v = kv_cache.read(group_id=layer_id // group_size)attn_out = self.attend(hidden, k, v)return self.ffn(attn_out)
Several details matter in production. First, cache indexing should be organized by “group” rather than by “layer” to avoid pointer mismatches. Second, adopting the shared structure during training yields the best results; if retrofitting a trained model, a small amount of continued training is needed so the model adapts to the distribution shift introduced by shared KV. Third, the arrangement of shared and non-shared layers (interleaved or segmented) affects accuracy and should be determined empirically.
4. Combining with Other Compression Techniques
Cross-layer reuse does not conflict with other KV Cache optimizations; orthogonal combinations often yield greater benefits:
- Combined with grouped-query attention: the former compresses the layer dimension, the latter the head dimension. Multiplied together, they can shrink the cache to a fraction of the original;
- Combined with KV quantization: storing the shared cache in low-bit formats further reduces bytes per element;
- Combined with sliding-window attention: retaining only the shared KV within a window for very long sequences keeps the sequence dimension under control.
In practice, it is recommended to stack techniques in a “structure first, numerics second” order: fix the layer-sharing and head-grouping structure first, then decide the quantization precision, to avoid cascading error amplification.
5. Accuracy Evaluation and Rollout Recommendations
Any compression method must answer the question: “How much accuracy is lost?” A layered evaluation system is recommended: first run perplexity and standard benchmarks, then conduct targeted evaluations for the long-context capabilities your business cares about (such as long-document retrieval, multi-turn dialogue consistency, and repository-level code understanding). Empirically, with group size G=2 the accuracy loss is usually negligible; larger G requires caution, and hybrid strategies should be considered—independent shallow layers with shared deep layers—since shallow-layer attention patterns are more sensitive to downstream impact.
At the deployment level, KV Cache compression directly improves memory utilization, which can be converted into longer context windows or higher request concurrency. When rolling out in cloud environments, you can use general-purpose container platforms to elastically scale inference services, rely on monitoring and alerting systems to track memory watermarks, time-to-first-token latency, and throughput, and use object storage to manage model weights and evaluation datasets—forming a complete go-live loop.
6. Conclusion
Cross-layer KV tensor reuse reduces KV Cache by a constant factor along the layer dimension by letting multiple layers share the same Key-Value state, making it an effective technique for long-context, low-cost inference. It is orthogonal to and stackable with head grouping, quantization, and sliding-window techniques, and accuracy loss remains controllable at moderate sharing ratios. For teams that need to deploy LLM inference services on limited hardware resources, mastering this technique and its evaluation methodology is an important part of building an efficient inference system.
