Analyzing Cross-Layer Shared KV Cache: A New Trend in LLM Architecture
Recent open-source large language models (LLMs) are increasingly focusing on balancing inference efficiency, training complexity, and output quality. A major bottleneck in LLM inference is the memory footprint of the KV Cache, especially for long-context processing. This article explores the mechanism of cross-layer shared KV states, a new architectural trend adopted by recent lightweight models. We analyze how sharing Key and Value projections across adjacent layers reduces memory and computational overhead, how it compares to existing compression techniques like GQA and MQA, and the trade-offs in model expressiveness. Finally, we provide practical guidelines for evaluating, deploying, and operating models utilizing this architecture in production environments.
I. Background: Architectural Trends in Open-Source Models
This spring, a major vendor released a new set of open-source model weights comprising three categories: small-scale models for mobile and embedded devices, Mixture-of-Experts (MoE) models for efficient inference, and larger models utilizing a dense architecture. Although these three model types serve different purposes, they all address the same challenge: how to enable models to process long texts faster and more efficiently under limited GPU memory and computational power.
MoE models activate only a fraction of their parameters during each forward pass, resulting in lower inference costs. However, their training and post-training pipelines are more complex, making hyperparameter tuning and routing strategies harder to optimize. Dense models have a straightforward structure and more mature post-training workflows, making them suitable as base models when output quality is the priority. The coexistence of both types indicates that current architectural designs require trade-offs among inference efficiency, training difficulty, and model quality.
In this set of models, the first structural change introduced in the small models is cross-layer shared KV states. This modification directly targets the primary memory overhead during inference, making it worth a separate, detailed analysis.
II. Why KV Cache Becomes an Inference Bottleneck
During autoregressive generation, every time the model generates a new token, it requires the Key and Value vectors from all previous tokens at every layer. To avoid redundant calculations, inference frameworks cache these vectors, which is known as the KV Cache.
The memory footprint of the KV Cache can be estimated using the following approximate formula:
Memory ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × batch_size × bytes_per_element
The coefficient of 2 accounts for storing both Key and Value. Below is an example calculation using hypothetical parameters, rather than any specific model configuration:
num_layers = 32, num_kv_heads = 8, head_dim = 128seq_len = 8192, batch_size = 1, data_type = FP16 (2 bytes)Memory = 2 × 32 × 8 × 128 × 8192 × 1 × 2 bytes = 1 GiB
A single 8K-length sequence consumes approximately 1 GiB of memory. If the batch size increases to 16, the same configuration requires about 16 GiB. When sequence length and concurrency grow simultaneously, the KV Cache often exhausts GPU memory before the model weights do. Therefore, reducing the amount of cached KV data is a direct way to lower inference costs.
III. The Mechanism of Cross-Layer Shared KV States
3.1 Basic Concept
In a conventional Transformer, each layer has independent Key and Value projection matrices, generating and caching its own set of KV states. The cross-layer sharing approach allows several adjacent layers to share the same set of KV states. Only the “source layer” computes and writes to the cache, while subsequent layers directly read the results from the preceding layers. Each layer still retains its own Query projection, so the attention computation remains unchanged; only the source of the KV states differs.
3.2 Comparison with Other KV Compression Methods
Common KV compression methods in the industry differ primarily in their sharing dimensions:
| Method | Sharing Dimension | Primary Function |
|---|---|---|
| Multi-Head Attention (MHA) | No sharing, each head is independent | Strongest expressiveness, largest cache |
| Grouped-Query Attention (GQA) | Multiple Query heads share KV heads within the same layer | Reduces the number of KV heads per layer |
| Multi-Query Attention (MQA) | All Query heads in a layer share one set of KV | Smallest cache, noticeable quality loss |
| Cross-Layer Sharing | Different layers share KV states | Reduces the number of layers that need caching |
Cross-layer sharing can be combined with GQA and MQA. The former reduces the number of “layers” cached, while the latter reduces the number of “heads” cached. The savings from both methods are multiplicative.
3.3 Illustrative Implementation
The following pseudocode illustrates the organization of the cache and the mapping between layers and cache slots:
# The first layer of each shared group acts as the source layer, responsible for computing and writing to the KV cache# Other layers read from the source layer's cache and only retain their own Query projectionLAYER_TO_CACHE_SLOT = {0: 0, 1: 0, # Layers 0 and 1 share cache slot 02: 1, 3: 1, # Layers 2 and 3 share cache slot 14: 2, 5: 2,# ...}def attention_layer(layer_idx, hidden, kv_cache, weights):q = hidden @ weights[layer_idx].wqslot = LAYER_TO_CACHE_SLOT[layer_idx]if is_source_layer(layer_idx):k = hidden @ weights[layer_idx].wkv = hidden @ weights[layer_idx].wvkv_cache.write(slot, k, v)k, v = kv_cache.read(slot)return scaled_dot_product_attention(q, k, v)
This code only demonstrates the core concept and omits positional encoding, masking, and multi-head splitting. A real-world implementation must handle the weight loading sequence between source and shared layers, as well as cache alignment during batch processing.
IV. Benefits and Trade-offs
4.1 Benefits
Assuming every two layers share a single set of KV states, the number of KV layers requiring storage is roughly halved, and the KV Cache memory footprint decreases accordingly. After sharing, layers other than the source layer no longer need to compute K and V projections, reducing the computational load for each generation step. For long-context scenarios, memory savings are particularly significant, as they directly determine the maximum sequence length and concurrency a single GPU can handle.
4.2 Trade-offs
Cross-layer sharing limits the model’s expressiveness. Subsequent layers can only utilize the KV computed by previous layers. Since the semantics carried in shallow and deep layers may differ, a higher degree of sharing increases the risk of quality degradation. Consequently, how to partition shared layer groups and where to place source layers must be determined experimentally; it cannot be applied as a simple one-size-fits-all rule.
Additionally, this type of architecture usually needs to be defined during the training phase; existing pre-trained dense models cannot be easily retrofitted. The inference framework must also support layer-to-cache mapping to realize the theoretical memory savings.
4.3 Research Background
The concept of cross-layer attention was proposed in academic research in 2024 and validated in small-scale experiments regarding KV cache compression. The novelty of this recent architectural shift is its application in the official release of a mainstream open-source model. Moving from research to large-scale engineering practice indicates that this method has passed preliminary tests for both training stability and inference efficiency.
V. Key Evaluation Points Before Deployment
Before deploying cross-layer shared architectures in production, it is recommended to conduct comparative testing across the following dimensions:
- Memory Peak: Under a fixed sequence length and batch size, compare the memory usage against a baseline model and record the growth curve for long sequences.
- Throughput and Latency: Measure Time-To-First-Token (TTFT) and tokens generated per second, distinguishing between the prefill and decoding phases.
- Long-Context Quality: Use tasks like long-document QA and multi-hop reasoning to check if the shared structure causes loss of distant information.
- General Capability Regression: Compare output quality on code, math, and commonsense benchmarks to avoid focusing solely on a single metric.
- Stability: Check across different input distributions for output repetition, truncation, or formatting errors.
During evaluation, fix the random seed and inference parameters to ensure reproducible comparisons between different versions.
VI. Deployment and Operations Recommendations
When deploying such models in the cloud, they can be managed as standard inference services. Recommended practices include:
- Reserve sufficient memory margins for each instance based on the KV Cache estimation formula to prevent Out-Of-Memory (OOM) errors caused by long requests.
- Set memory quotas and concurrency limits in container platforms to prevent a single tenant from exhausting resources.
- Track memory utilization, queue wait times, and request failure rates through monitoring and alerts, setting thresholds for timely scaling.
- Analyze the request length distribution in logs to dynamically adjust maximum context length and batch processing strategies.
While these measures are architecture-agnostic, they determine whether memory savings can actually translate into service capacity.
VII. Conclusion
Cross-layer shared KV states is a structural improvement directly targeting inference memory overhead. By reducing the amount of cached KV data, it lowers the cost of long-context inference, at the expense of limited expressiveness, and must be integrated during the initial training design. When evaluating this solution, decisions should be based on empirical measurements of memory, latency, and quality, rather than solely on theoretical compression ratios.
