Cross-Layer KV Tensor Reuse: KV Cache Compression for Long-Context LLM Inference

    This article explains why KV Cache becomes a bottleneck for long-context inference in Transformer-based large language models and how cross-layer KV reuse can reduce memory use, computation, and memory bandwidth pressure. It reviews mainstream KV Cache compression approaches, describes the core principle of sharing Key and Value tensors across layer groups, and shows how cross-layer reuse complements GQA and quantization. It also covers engineering considerations such as training-time alignment, grouping strategy, positional encoding consistency, inference framework adaptation, and long-context validation, followed by guidance on when cross-layer KV reuse is a good fit.

    Cross-Layer KV Tensor Reuse: KV Cache Compression for Long-Context LLM Inference

    1. Background: Why KV Cache Becomes a Bottleneck in Long-Context Inference

    In autoregressive large language models based on the Transformer architecture, inference generates tokens one by one. To avoid recomputing attention intermediates for historical tokens at every step, the industry commonly uses a KV Cache mechanism: the Key and Value tensors computed by each attention module in each layer are cached, and subsequent generation steps read them directly.

    This mechanism trades space for time, but its cost grows linearly with context length. The memory footprint of KV Cache can be approximated as:

    1. memory footprint ≈ 2 × number of layers × sequence length × hidden dimension × bytes per element × batch size

    The coefficient 2 corresponds to the two tensors, Key and Value. As shown above, both the number of layers and the sequence length are multiplicative factors. When a model has dozens of layers and the context window expands to tens of thousands of tokens, KV Cache can consume even more memory than the model weights themselves, becoming a major bottleneck for local deployment and high-concurrency serving. This is especially true for mobile devices, embedded devices, and other scenarios with extremely limited memory, where KV Cache compression is almost an unavoidable engineering problem.

    2. Overview of Mainstream KV Cache Compression Approaches

    Before discussing cross-layer reuse in detail, it is useful to review common compression routes in the industry so that the differentiated position of cross-layer approaches is clear:

    1. Structural variants of multi-head attention: Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) reduce the head dimension of each layer’s KV tensors by allowing multiple query heads to share the same set of KV heads. This is “intra-layer” compression. It is stable and has been adopted by many mainstream models.
    2. Quantization: KV Cache is stored at INT8 or even INT4 instead of FP16/BF16 and dequantized when read. This is simple to implement, but extremely low bit widths can introduce accuracy loss.
    3. Eviction and sparsification: Important historical tokens are identified based on attention scores, and their KV states are removed from the cache. This is suitable for very long contexts, but policy tuning is complex.
    4. Cross-layer reuse: Several subsequent layers no longer compute KV independently and instead directly reuse KV tensors already generated by earlier layers. This is “inter-layer” compression and is the focus of this article.

    3. Core Principle of Cross-Layer KV Reuse

    The basic observation behind cross-layer reuse is that attention patterns between adjacent Transformer layers are often highly similar, especially in the middle and later layers of a model, where different layers attend to highly overlapping historical positions. This means that the KV states independently computed by some layers contain a high degree of redundant information and can be shared safely.

    A typical approach is to divide all model layers into several groups. The first layer in each group (or a designated layer) performs KV projection normally and writes to the cache, while the remaining layers in the group skip their own Key/Value projection computations and directly reference the shared KV tensor during attention computation. An illustrative pseudocode example is shown below:

    1. class CrossLayerAttention(nn.Module):
    2. def forward(self, x, shared_kv=None):
    3. q = self.w_q(x)
    4. if shared_kv is None:
    5. # This layer produces the shared KV
    6. k = self.w_k(x)
    7. v = self.w_v(x)
    8. cache.write(self.layer_id, k, v)
    9. else:
    10. # Reuse KV from an earlier layer; do not write to cache
    11. k, v = shared_kv
    12. return self.attend(q, k, v)

    This design brings three benefits:

    • Memory benefit: If a proportion p of layers switch to reuse, the total KV Cache size is approximately reduced to (1−p) of the original. For example, if every two layers share once, cache usage is nearly halved.
    • Computation benefit: Reused layers skip the two linear projections for Key and Value, so inference FLOPs decrease accordingly. The benefit is more noticeable for long sequences.
    • Bandwidth benefit: The decoding stage is a memory-bandwidth-bound workload, so halving KV reads directly improves throughput.

    It is worth emphasizing that this idea is not entirely new. Public academic research has systematically validated its feasibility, and related results have been published at top academic conferences. What is more noteworthy is that recent mainstream open-weight model families have introduced this mechanism at scale for the first time in their small-parameter versions aimed at mobile and small devices, marking a transition of cross-layer KV reuse from papers to production-grade architectures. The same families also offer efficient inference versions with Mixture-of-Experts architectures, as well as dense architecture versions designed for higher quality and a smoother post-training experience. This shows that cache compression strategies can be flexibly combined with different architecture forms.

    4. Relationship with GQA and Other Approaches

    Cross-layer reuse does not conflict with GQA; the two are orthogonal and complementary. GQA compresses the number of KV heads “within a layer,” while cross-layer reuse compresses the number of layers “across layers.” They can be used together, and the final cache size is:

    1. final cache ≈ original × (number of KV heads / number of query heads) × (number of independent KV layers / total layers)

    A common combination in practice is to first use GQA to reduce each layer’s KV heads to a small number, and then apply cross-layer sharing at a ratio of 2:1 or 3:1, thereby achieving a combined compression rate of several times. Note that the more aggressive the compression, the greater the potential impact on model quality, so it must be calibrated through experiments.

    5. Key Engineering Considerations for Deployment

    1. Training-time alignment: If a model is trained from scratch, cross-layer sharing should be enabled directly during training so that model weights adapt to the shared KV distribution; quality loss is usually small. If modifying an already trained model after the fact, additional continued training or distillation is needed to recover performance. Direct hard modification often causes obvious quality degradation.
    2. Grouping strategy: The choice of sharing granularity is a core hyperparameter. Adjacent layers tend to have higher similarity, so contiguous groups of layers are commonly used. It is also possible to make non-uniform partitions based on layer importance, keeping independent KV for layers that contribute more to representation capacity.
    3. Positional encoding consistency: When reusing KV, the shared layers and the layer being reused must use consistent positional encoding treatment; otherwise, attention distributions will be misaligned. For schemes using rotary positional encoding, confirm whether rotation is applied before KV is written or at read time, and design the cache layout accordingly.
    4. Inference framework adaptation: KV Cache management in mainstream inference frameworks is usually designed around “independent tensors per layer.” Introducing cross-layer sharing requires modifying cache allocation and addressing logic so that multiple layers map to the same cache region. It is also necessary to correctly handle the timing of incremental writes during streaming generation: shared KV is written only once by the layer that produces it.
    5. Long-context validation: The benefits of cross-layer sharing scale with sequence length, but potential errors may also accumulate over long sequences. Be sure to evaluate both perplexity and downstream tasks at the target context length, rather than looking only at short-text metrics.

    6. Suitable Scenarios and Selection Guidance

    Cross-layer KV reuse is particularly suitable for the following scenarios:

    • Mobile and embedded devices: Memory is a hard constraint. Although small models have fewer layers, the cache accounts for a high proportion of memory, and sharing can significantly extend the usable context length.
    • High-concurrency online serving: The smaller the KV Cache for a single request, the more concurrent sessions a single GPU can support, directly reducing inference cost. When deploying inference services on cloud platforms such as Baidu AI Cloud, you can combine the elastic scheduling and monitoring/alerting capabilities of container platforms to continuously observe cache usage and throughput metrics and dynamically adjust batching strategies.
    • Long-document processing: Scenarios such as retrieval-augmented generation and document question answering often involve contexts of tens of thousands of tokens, and cache compression directly determines whether a solution is feasible.

    Conversely, if model quality is the top priority and hardware resources are abundant—such as in dense large-model post-training scenarios pursuing maximum quality—you may choose not to enable cross-layer sharing or to enable it only lightly, leaving the compression budget for methods with more controllable impact, such as quantization.

    7. Conclusion

    Cross-layer KV Cache reuse compresses inference cache from the inter-layer dimension by letting adjacent layers share Key-Value tensors. It is orthogonal and complementary to intra-layer methods such as GQA and quantization. Its transition from academic research to mainstream open-source architectures shows that its quality-efficiency trade-off has been validated in practice. For developers, understanding its principles, training-time alignment requirements, and inference framework modification points is a key part of deploying long-context LLM applications on devices and in the cloud. In the future, as cache compression and sparse attention technologies become more integrated, the resource barrier for LLM inference will continue to decrease.