Cross-Layer KV Reuse: A New Approach to Memory Optimization for Long-Context LLM Inference
This article explains cross-layer KV reuse, an architecture-level method in which deeper Transformer layers reuse the Key and Value states computed by earlier layers. It covers why the KV cache grows with sequence length, how this method compares with quantization, sliding-window attention, and sparse attention, how to choose which layers share a cache, what changes the inference system needs, and where the trade-offs fall for online and offline workloads.
From the Memory Wall to Long Context: The Challenges of KV Cache Optimization
As large language models grow in both parameter count and context window length, memory bottlenecks during inference have become increasingly prominent. The memory that model parameters occupy is predictable and fixed. In tasks that require continuous generation, such as multi-turn dialogue or long-document analysis, however, the KV cache (Key-Value cache) grows linearly with sequence length and can become the largest consumer of inference memory. Take a common 7B-scale dense model with 32 layers, 32 attention heads, and a head dimension of 128. At a sequence length of 32K tokens, the KV cache alone may exceed the memory needed for the model parameters. This poses a serious challenge for deployment cost-effectiveness and hardware compatibility.
The KV cache is necessary. It stores the Key and Value matrices already computed, so the model does not recompute them when generating each new token. In autoregressive decoding, this is the natural choice for balancing speed and cost. However, every caching strategy must answer one fundamental question: how can cached content deliver greater reuse value at a lower storage cost?
Existing Approaches: Quantization, Windowing, and Sparsification
Before discussing cross-layer reuse, it helps to review the existing KV cache compression techniques, so that the new approach’s place among them is clear.
- KV quantization: Compresses FP16 Key and Value tensors into INT8 or even INT4 storage. This is intuitive and effective, but aggressive quantization introduces accuracy loss, and results can be unstable on long-tail tasks or fine-tuned models.
- Sliding window attention: Caches only the states of the most recent tokens and discards older information. This greatly reduces cache size but sacrifices the modeling of long-range dependencies, so it is unsuitable for scenarios that require complex reasoning over the full text.
- Sparse attention: Applies structured sparsity to attention patterns, keeping only representative token interactions. These methods add indexing overhead and can cause unstable quality fluctuations on some tasks.
These approaches all work on the cached content itself. Cross-layer KV reuse takes a different path: can the total number of KV tensors that must be computed and stored be reduced directly?
Cross-Layer KV Reuse: Principles and Architectural Advantages
The core idea of cross-layer KV reuse is simple. Transformer layers with higher indices reuse the Key and Value states already computed by lower-indexed layers, instead of each layer computing and storing its own. This breaks the traditional design in which every layer has independent KV, and it changes the KV cache structure from per-layer ownership to hierarchical sharing.
The approach works because Transformer layers contain substantial information redundancy. In deep networks, the representations learned at different layers may overlap heavily in high-dimensional space. In particular, the semantic roles carried by Key and Value matrices, such as coreference, key entities, and topic words extracted from text, tend to stay consistent across abstraction levels. Enforcing reuse explicitly at the architecture level turns this implicit representation similarity into direct memory savings.
As a rough estimate, suppose a model has 48 layers and every two adjacent layers share one KV set. The overall KV cache memory could theoretically drop by nearly 50%. With a 4:1 reuse ratio, the cache cost would be one quarter of the original design. This is not a simple algorithmic optimization. It is a structural cost reduction at the architecture level.
Which Layers Should Share? An Engineering Decision
Cross-layer reuse should not be applied uniformly across all layers. In shallow layers near the input, attention tends to focus on local lexical patterns and short-range dependencies, so their KV states may not be very valuable for reuse in deeper layers. Deeper layers near the output tend to capture long-range semantic relations and global logical structure.
A typical practice is to form sharing groups based on similarity measurement. Run a calibration pass on the model, measure the cosine similarity between the Key matrices of adjacent layers, place high-similarity layer pairs into a shared group, and keep independent KV computation paths for low-similarity layers. This dynamic allocation saves memory without significantly disturbing the specificity of attention distributions.
Cross-layer KV reuse can also be combined with other optimizations. For example, INT8 quantization can be applied on top of shared KV tensors, or sparse windows can be added to the sharing strategy. Each combination yields further savings.
Deployment: Adapting the Inference System
Moving cross-layer KV reuse from a paper or model architecture into production requires adjusting several parts of the inference system.
1. Changes to cache management
Traditional inference frameworks typically allocate memory pools per layer. Cross-layer reuse means multiple decoder layers must read the same memory region at the same time. The memory manager must therefore change its scheduling granularity from individual layers to shared layer groups, which prevents incorrect repeated allocation or release.
2. Changes to the computation flow
During prefill, layers that reuse KV no longer compute their own KV, so their compute units can be rescheduled for other workloads. During decoding, the batch scheduler must also account for these dependencies. When a sequence’s KV is shared by several layers, its lifecycle management must wait until all dependent layers no longer need that cache before releasing it.
3. Compatibility with continuous batching
In a dynamic inference cluster, requests vary in length and progress, and continuous batching schedulers often insert or remove requests at each iteration. Cross-layer KV reuse adds a constraint to batching decisions. The scheduler must keep the shared cache consistent while still meeting service quality targets efficiently. In practice, a layered KV pooling strategy is recommended. It manages shared and exclusive caches separately, which reduces system coupling.
Quick Validation: A Simulated Code Sketch
Before engineering rollout, validate the cache reuse logic with simplified function simulations. The following pseudocode shows how to modify a traditional attention computation:
# Traditional structure: each layer computes its own KVdef traditional_forward(layer_input, layer_idx):k = k_proj[layer_idx](layer_input)v = v_proj[layer_idx](layer_input)return k, v# Cross-layer reuse structure: every N layers share one KV groupshared_kv_store = {}def shared_forward(layer_input, layer_idx, group_size=2):group_id = layer_idx // group_sizeif group_id not in shared_kv_store:# Only the first layer in the group computes KVshared_kv_store[group_id] = {"k": k_proj[layer_idx](layer_input),"v": v_proj[layer_idx](layer_input)}else:# Subsequent layers directly reuse the KV already computed in the grouppassreturn shared_kv_store[group_id]["k"], shared_kv_store[group_id]["v"]
In a real implementation, the Query projections of the layers in a reuse group must stay independent. Attention scores are still computed as the dot product of each layer’s own Query matrix and the shared Key matrix.
Evaluating Cross-Layer Reuse: Benefits, Costs, and Limits
Benefits. The most visible gain is higher throughput in long-context scenarios. Because the KV cache shrinks significantly, the same memory can hold a larger batch size, which raises GPU utilization and overall generation throughput.
Costs. Potential accuracy loss must be evaluated carefully. If sharing groups are poorly chosen and deep layers are forced to use the local semantic KV of shallow layers, attention distributions may become smoother, and attention entropy rises. This can cause a slight drop in accuracy on long-text understanding tasks.
Applicability. For scenarios that prioritize maximum offline quality, such as academic benchmark leaderboards, the reuse ratio can be set conservatively. For high-concurrency, high-throughput online services, such as intelligent customer service or knowledge base Q&A, cross-layer reuse can deliver significant cost advantages at a very small accuracy cost.
Summary and Outlook
Cross-layer KV reuse points to a clear direction. As scaling model parameters becomes harder to sustain, restructuring the inference process at the architecture level becomes a promising area for further gains. The technique does not require overturning the Transformer framework. It rethinks the data flow during inference with a more efficient way of organizing it.
For deployers, choosing an inference platform that supports these architectural optimizations matters. Cloud providers, including Baidu AI Cloud, continue to invest in LLM inference acceleration, with a focus on cache compression, operator fusion, and scheduling optimization. As cross-layer reuse is combined with generation acceleration methods such as speculative decoding and speculative sampling, the memory wall in long-context inference may be pushed further. This could enable more complex Agent-based applications and full-scale knowledge base understanding. The broader l
