Why Full KV Cache Slows Down Long-Context Inference: A Deep Dive into Cross-Layer KV Reuse
As LLM context windows stretch to tens or even hundreds of thousands of tokens, the KV Cache often becomes the single largest consumer of GPU memory—sometimes exceeding the model weights themselves—and the first bottleneck to surface during long-context inference. This article frames cross-layer KV reuse as a general engineering problem: how to safely share key/value tensors across Transformer layers. It covers where the KV Cache overhead originates, how to quantify it, the spectrum of sharing strategies from full sharing to grouped sharing, the architectural constraints that sharing cannot cross, training and distillation-based adaptation, inference-engine implementation with paged caches, evaluation metrics, and practical guidance for taking such a design from experiment to production. Readers will gain a clear model of why cross-layer reuse saves memory on the layer dimension rather than per token, and what it takes to turn that saving into stable results.
Introduction: Context Windows Keep Growing, and the Bottleneck Is Shifting
Since the start of 2025, open-weight model releases have accelerated noticeably, and model shapes have begun to diverge. Small models aimed at mobile and embedded devices, mid-size mixture-of-experts (MoE) models, and larger, denser (Dense) models built for stronger general capability are now making differentiated trade-offs among performance, cost, and ease of use.
A note on terminology: The defining feature of an open-weight model is that the weights are open, which makes local deployment and customization convenient. This does not require the data, code, and training methodology to all be open—the exact degree of openness depends on each model’s own license and terms of use.
Alongside this, the industry keeps pushing for long-context capability: code-repository understanding, long-document question answering, and multi-turn agent tasks all demand that a model reliably handle tens of thousands to hundreds of thousands of tokens. Parameter count sets the ceiling on model capability, but on the inference side, what usually runs out first is not compute—it is memory. The largest and most rapidly growing part of that memory, scaling linearly with context length, is the KV Cache inside the attention mechanism.
One small architectural change in recent open-weight models is worth attention: adjacent sublayers share a single Key/Value state—it is computed and cached only once, and the remaining layers simply reuse it. This is called cross-layer KV reuse, and it can substantially reduce memory usage and inference overhead under long context.
This article evaluates no specific model. Instead, it abstracts the problem into a general technical question: in long-context inference, how can we safely share KV tensors across different layers? It covers the underlying principles, the available strategies, compatibility with mainstream architectural designs, training and post-training adaptation, key points for inference-engine implementation, and recommendations for evaluation and deployment.
1. Problem Background: Why the KV Cache Is the First Constraint of Long Context
1.1 Where It Comes From: The “Historical Memory” of Autoregressive Decoding
When a large model generates autoregressively, each new token requires the attention layer to use the current token’s query (Query) plus the keys (Key) and values (Value) of all previous tokens. If the K/V of historical tokens were recomputed at every step, the compute cost would balloon with generation length. Inference engines therefore cache the K/V, compute only the new token at each step, and append it incrementally to the cache. This design eliminates repeated computation; the cost is that memory usage grows continuously with layers × sequence length × concurrent requests.
1.2 How Big: A Quantifiable Estimate
The size of a single request’s KV Cache can be approximated as:
KV_bytes ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element
Here the coefficient 2 accounts for the two tensors, K and V. Take a 32-layer model with 8 KV heads, head dimension 128, and FP16 storage as an example:
- Each token occupies roughly 2 × 32 × 8 × 128 × 2 ≈ 128 KB;
- A single request with a 32K context needs about 4 GB;
- 8 concurrent requests swell to about 32 GB.
These numbers vary by model, but they reveal a key pattern: in the long-context era, the KV Cache easily becomes the largest single memory expense, sometimes even exceeding the weights themselves.
1.3 How It Slows Down the System: It Is Not Just About “Fitting”
The impact of the KV Cache runs across the entire pipeline:
- Capacity: The cache squeezes out memory available for concurrency, pushing down batch size and, with it, GPU utilization and overall throughput.
- Bandwidth: During decoding, every generated token requires reading all historical K/V from memory into the on-chip compute units. The longer the context, the more decoding is bound by memory bandwidth, and per-token latency (TPOT) keeps climbing.
- Latency: A long request’s time to first token (TTFT) comes mainly from the prefill stage. That stage must compute the K/V projections for all historical tokens and write them to the cache, and the memory read/write bandwidth involved is equally significant.
- Cost: Insufficient memory often means adding GPU instances or splitting the model, which raises the per-token serving cost.
In some lightweight solutions aimed at mobile and embedded devices, memory and bandwidth are even tighter, so the resource squeeze from long context is especially acute.
1.4 Existing Methods and Their Limitations
The industry already has a series of methods for reducing KV Cache overhead, each with a different focus:
- Grouped-query attention (GQA) / multi-query attention (MQA): Multiple query heads share one set of K/V heads, reducing the head-count dimension.
- Low-rank compression: Project K/V into a lower-dimensional latent space for caching, then reconstruct it during decoding to reduce the cached bytes per token.
- Quantization compression: Store the cache in lower-precision formats such as INT8 or FP8 to directly shrink the byte count.
- Cache eviction and sparse attention: Keep or compute attention over only part of the historical tokens, suitable for scenarios that can tolerate some information loss.
Most of these optimize along the lines of “cheaper per token” or “keep only a subset,” and they all assume that every layer has its own independent and complete K/V state. But there is redundancy between layers too—and that is precisely the entry point for cross-layer KV reuse.
2. Core Principle: Why Different Layers Can Share KV
2.1 Observation: Adjacent Layers Show Strong Representational Similarity
Adjacent Transformer layers are highly continuous in their representations: each layer builds on the output of the previous one, and many layers respond similarly to similar information patterns. Several studies have observed that some attention layers contribute little to the final output and can even be merged or removed. Since there is functional redundancy across layers, maintaining a separate K/V for each layer is not necessarily required.
The logic of cross-layer KV reuse is this: if several consecutive layers sharing the same K/V still produce acceptable results, then that K/V only needs to be computed once and cached once. It requires no new training data and no change to the inference flow, making it a typical case of “architecture–system co-design.”
2.2 Comparison: This Is a “Cross-Layer,” Not “Intra-Layer,” Optimization
Cross-layer reuse is easily confused with the following two ideas, which optimize along entirely different dimensions:
| Optimization idea | Optimization dimension | Typical approach |
|---|---|---|
| Grouped-query attention (GQA) | The head dimension within a layer | Multiple query heads share one set of K/V heads |
| Low-rank compression, low-precision quantization | The bytes per token | Compress the latent vector dimension, or reduce storage precision |
| Cross-layer KV reuse | The layer dimension | Adjacent layers share the same K/V |
The three are independent and can, in principle, be stacked. For example: first use GQA to reduce the number of KV heads, then let every 2 layers share one cache. The final memory overhead is roughly the product of the three coefficients.
2.3 The Computational-Graph View: Compute Once, Reference Across Layers
In a standard decoder layer, the attention block typically consists of: K/V linear projection → attention computation (dot product of the Query with each layer’s Key, then a weighted sum over the Value) → output projection. After introducing cross-layer reuse, the structure becomes:
Standard: each layer's K/V projection → each layer's own cache → each layer's attentionReuse: shared group's first layer K/V projection → shared cache ─┐├─→ attention of every layer in the groupOther layers in the group (reuse, no projection) ────────────────────┘
In the prefill stage, only the first layer of a shared group performs the K/V projection and writes to the cache; every layer in the group then reads that same K/V using its own Query. In the decoding stage, each new token appends only one copy to the cache.
This lets us divide the benefits more precisely:
- Significant benefit: Memory capacity drops in proportion to the sharing ratio, and the K/V projection computation and cache write-back volume drop in step.
- Limited benefit: During decoding, each layer still needs to read the historical K/V. After sharing, the layers read the same cache; per-layer read volume is unchanged, and total read volume stays roughly the same. The improvement comes mainly through the indirect path of “freed memory buys larger concurrency.”
3. Sharing Strategies: A Spectrum from Aggressive to Conservative
Cross-layer reuse is not a binary choice between “share everything” and “share nothing,” but a spectrum of strategies from aggressive to conservative.
3.1 Full Sharing: One KV Across All Layers
All layers share the first layer’s K/V, compressing the cache to 1/L on the layer dimension—an extreme memory reduction. But each layer’s Query space shifts considerably as depth increases; matching increasingly divergent Queries with the same Key noticeably damages attention quality in deeper layers. This strategy is therefore usually applied only to ultra-lightweight models, or used as a control group.
3.2 Grouped Sharing: Share Once Every Fixed Number of Layers
Partition the model by a fixed sharing interval s: layer 1 is independent, layers 2 and 3 share, layers 4 and 5 share, and so on. Each group has only its first layer compute and write the K/V; the rest reuse it directly.
This is a relatively balanced approach between memory savings and model quality, and the key is choosing the value of s:
- The larger s is, the more memory is saved—but the more the Queries of layers within that span diverge, and the higher the quality risk.
- In public research on cross-layer sharing and cross-layer parameter sharing, an interval of 2 (adjacent layers sharing) generally strikes a good balance between quality and efficiency. But this is only an empirical starting point; the final choice still has to be pinned down through task evaluation in the context of the specific model architecture.
3.3 Keeping a Few Layers Independent: A Small Number of Exceptions for Quality
Another line of thinking introduces “exceptions” to sharing:
- A few key layers (for instance, some layers near the input or output) keep their own independent K/V;
- The remaining layers uniformly reuse a shared state, forming a hybrid structure of “one global cache plus a few local caches.”
This design follows the same line of thought as research on cross-layer parameter sharing. Because the key layers carry more of the representation-transformation workload, keeping their independent state often buys a fairly clear quality improvement at a small memory cost.
3.4 Retrofitting an Existing Model: Dynamic Sharing and Weight Binding
For a model that has already been trained, “post-hoc” modification is also possible:
- Dynamic sharing: After deployment, continuously measure the similarity of attention states across layers and merge the highly similar ones into shared groups, achieving fine-grained “on-demand sharing.”
- Weight binding: Let adjacent layers’ K/V projections share the same parameters. At inference, the projection is computed only once, and the resulting K/V can be reused across layers.
These approaches do not change the model’s external input/output interface, but they do require corresponding fine-tuning to make up for the loss of capability.
A note: If a single layer contains multiple Transformer sublayers (for example, an alternating “attention + MLP” arrangement), a shared group can also be divided at the sublayer granularity. For instance, with two sublayers per group, the attention of the first sublayer and the attention of the second sublayer in the group share the same K/V. Such a division is finer-grained and leaves more room to tune the trade-off between memory benefit and quality.
4. Sample Code: How to Organize a Shared KV Cache
The following simplified example helps illustrate the implementation idea for organizing memory and mapping layers to groups (it serves only to explain the principle and does not represent any specific framework’s API):
import torchdef build_layer_to_group(num_layers: int, share_interval: int) -> list[int]:"""Map layer index -> shared-group index; layer 1 is always independent and serves as the group's shared baseline."""mapping = [0] * num_layersfor i in range(1, num_layers):mapping[i] = (i - 1) // share_interval + 1return mapping # with s=2: [0, 1, 1, 2, 2, 3, 3, ...]def prefill_layer(hidden, layer, layer_to_group, k_cache, v_cache, pos_offset,pre_norm, qk_norm, rope,):"""Single-head simplified example: layer 1 computes and writes K/V, the other layers reuse it directly."""if layer == 0:h = pre_norm(hidden)k = rope(qk_norm(layer.k_proj(h)), pos_offset)v = layer.v_proj(h)k_cache[:, pos_offset] = k # [num_kv_heads, max_seq_len]v_cache[:, pos_offset] = v# Each layer computes its own Query; Key/Value both come from the shared group the layer belongs tog = layer_to_group[layer]h = pre_norm(hidden)q = rope(qk_norm(layer.q_proj(h)), pos_offset)attn = torch.softmax(q @ k_cache[:, g] / q.shape[-1] ** 0.5, dim=-1)return attn @ v_cache[:, g]
This code reflects three points:
- The layer-to-group mapping is static: It is fixed at model initialization and does not change during inference.
- Memory is allocated per shared group: The layer dimension of the KV cache shrinks from
num_layersto the number of shared groups. - Writes happen only once: Only layer 1 performs the K/V projection and cache write; the other layers only read.
In a real inference engine, additional engineering concerns must be handled, such as paged caching, continuous batching, and tensor-parallel sharding—topics discussed later in this article.
5. Architectural Constraints: What Cross-Layer Reuse Cannot “Cross”
The prerequisite for cross-layer reuse is that the layers being shared have consistent “K/V semantics.” The following architectural features break that consistency, and the corresponding boundaries must be avoided when grouping.
5.1 Mixing Local and Global Attention Layers
Many long-context models adopt an alternating layered design of “local attention + global attention”:
- Local attention layers use a sliding window, so each position can attend only to a recent span of tokens;
- Global attention layers compute attention over all historical tokens.
The two have different visibility ranges. If K/V is shared across the boundary, a local layer would “see” tokens outside its window, and the attention mask would break down accordingly. Therefore:
- A shared group cannot cross the local/global boundary;
- Same-type layers can only be shared within their own type;
- A local attention layer’s cache is inherently short, so sharing brings limited benefit—prioritize sharing between global attention layers.
5.2 Differences in Positional Encoding
Rotary position embeddings (RoPE) usually apply a rotational transformation to the Query and Key according to each token’s absolute position before the attention computation. If layers within a group use different positional-encoding base frequencies, or apply differentiated interpolation for long context, the transformed Keys will not live in the same “coordinate system,” and cross-layer reuse would scramble positional information. A shared group must fall entirely within the set of layers that share the same positional-encoding configuration.
5.3 Normalization Method and the Sharing Point
QK normalization (normalizing the Query and Key) and attention-logit scaling determine whether the shared Key should be the “pre-normalization” or “post-normalization” version. If the layers in a group use the same configuration, the two are equivalent; if they differ, they must first be unified.
The more general principle is: the K/V entering the shared cache at any given moment must come from the same computation stage. Otherwise the layers would be reusing Keys of different semantics, and the attention distribution would develop a systematic bias.
5.4 Summary: The Boundary of Sharing
The constraints above can be summed up in one sentence: cross-layer reuse can only happen between layers of the same attention paradigm. Before putting a scheme into practice, first draw a layered-attribute map of the model—including attention type, positional-encoding configuration, and normalization method—and only then decide the sharing plan.
6. Training and Post-Training Adaptation: How the Shared Structure “Grows”
Cross-layer KV reuse raises an unavoidable question: the model must “adapt” to this shared structure during training or post-training; otherwise, forcing the sharing at inference time will cost quality.
6.1 Training from Scratch: Build Sharing into the Architecture
The most direct approach is to adopt the cross-layer sharing structure during pretraining, letting the model gradually adapt to “sharing one K/V within each group.” This yields the most thorough adaptation, but it requires a complete pretraining compute budget and dataset, which is unrealistic for most teams.
6.2 Converting from an Existing Model: Knowledge Distillation Is Key
A more pragmatic path is “retrofit + distill”:
- Retrofit: Map the original model’s layers onto shared groups, and at initialization have the layers in each group reuse the K/V projection parameters of one layer (usually the group’s first layer).
- Distill: Use the original model as the teacher and, under the same inputs, align the output distribution of the retrofitted student model. The loss typically includes cross-entropy distillation on the final output as well as intermediate-layer alignment of each layer’s hidden state, so that the remaining layers learn to “align” their own Queries against the shared Key.
In addition, parameter-efficient fine-tuning methods such as low-rank adaptation (LoRA) can complete the adaptation under the premise of “freezing the backbone and training only a small number of parameters,” at a cost far lower than full-parameter fine-tuning.
6.3 How the Architectural Shape Affects Adaptation Difficulty
It is worth stressing that the model’s architectural shape significantly affects post-training and adaptation difficulty. A mixture-of-experts (MoE) architecture relies on a router to dynamically select a few experts to participate in the computation for each token. It can scale up parameters while keeping inference cost relatively controllable, but it poses the following challenges:
- Routing decisions make the gradient signal sparse, so fine-tuning stability is poorer;
- Adapting to a shared structure requires the various experts to stay coordinated under the same shared Key, which makes the adjustment space more complex.
A dense (Dense) architecture has every parameter participate in each forward pass; its structure is simple and its behavior predictable, and it is usually easier to fine-tune and to adapt to sharing. As a result, models that pursue convenient post-training tend to choose the Dense route, while those that pursue inference-cost efficiency lean toward MoE. This is a trade-off between “capability ceiling and controllability.”
7. Inference-Engine Implementation: Putting the Shared Structure into Practice
In a real inference system, cross-layer KV reuse involves a series of engineering details. Take the currently mainstream PagedAttention-style paged-cache mechanism as an example: it divides each request’s KV cache into fixed-size physical blocks and maps logical token positions to physical blocks via a block table. The key modifications for cross-layer reuse are as follows:
- Allocate the cache per shared group: Physical blocks of the KV cache are organized by shared group. A group’s block table is visible to all layers within the group, but there is only one copy in physical memory.
- Deduplicate writes: During both prefill and decoding, only a shared group’s first layer performs the K/V projection and writes the result to the position indicated by the block table. Other layers read through the same block table and need no independent write path.
- Preserve attention-computation correctness: Each layer still runs attention with its own Query against the shared Key. At the operator level, one only needs to ensure that the layers in a group read the same block table; the rest of the flow (such as softmax and masking) stays unchanged.
- Stay compatible with continuous batching: The shared structure does not change the request-level scheduling logic, but it reduces each request’s block usage—effectively increasing the number of concurrent requests a single card can hold.
- Stay compatible with prefix caching and speculative decoding: A cross-request shared prefix cache can still be matched by token sequence; in speculative decoding, the small draft model and the large verify model can each adopt an independent sharing strategy without conflict.
- Mind the tensor-parallel sharding: Under tensor parallelism, ensure that the shared K/V is read as the same complete cache by every shard, avoiding sharding errors that could cause dirty-data reads.
8. Evaluating the Benefits: How to Quantify the Gains from Cross-Layer Reuse
Deciding whether a sharing scheme is “worth it” requires metrics along multiple dimensions.
8.1 Resource-Side Metrics
- Memory usage: With context length and concurrency held fixed, compare the KV Cache memory before and after sharing, and the maximum concurrency that can be supported.
- Throughput and latency: On the same hardware and at the same context length, compare output tokens per second (throughput), TTFT, and TPOT.
- Long-context behavior: Observe the degradation curves of the metrics above as the context extends from 8K to 32K and 128K.
8.2 Quality-Side Metrics
- Benchmark tests: On task suites such as general knowledge, mathematical reasoning, code generation, and long-document understanding, compare scores before and after sharing.
- Long-context tasks: For “needle in a haystack” (retrieving a specific piece of information within a long text) and multi-document question answering, focus on the recall of information in middle positions.
- Inter-layer behavior diagnosis: Measure the KL divergence of the attention distributions after each group shares, and pinpoint which layers change behavior the most when “forced to share”—providing a basis for later adjusting the sharing granularity.
8.3 Engineering-Side Metrics
- Deployment density: The number of instances a single card can host, and the trigger thresholds for elastic scale-up/down.
- Long-tail stability: Whether P99 latency converges under high concurrency.
Overall, the essence of cross-layer KV reuse is “trading a structural prior for memory”: when inter-layer redundancy is large enough, the benefit is significant; when the layers’ responsibilities differ greatly, the cost amplifies quickly. The purpose of evaluation is to find the right point on this trade-off curve.
9. Deployment Practice: From Experiment to Production
- Verify first, then roll out: Retrofit a few layers in a test environment, validate the inference flow and operator compatibility, and then gradually expand the sharing scope.
- Tiered sharing strategy: Use a more aggressive sharing ratio for latency-sensitive workloads; use a conservative ratio for quality-critical workloads, or keep some layers’ caches independent.
- Monitor and roll back: In production, set monitoring and alerts for key metrics such as KV Cache hit rate, memory utilization, and TPOT. If quality degrades or performance regresses, roll back to the original structure quickly.
- Leverage general cloud capabilities: In actual deployment, container platforms can handle elastic scaling and canary releases for the inference service, while log services and monitoring alerts can track metrics continuously. On cloud platforms such as Baidu AI Cloud, these general-purpose product categories can be combined to provide operational and maintenance support for a cross-layer reuse scheme.
- Small-model scenarios: For memory-constrained lightweight solutions on mobile and embedded devices, cross-layer reuse can significantly ease the memory pressure of long context. Combined with techniques such as INT8 quantization and KV Cache compression, it can support longer interactive contexts under limited memory.
10. Common Misconceptions and Outlook
Misconception 1: The higher the sharing ratio, the better. Sharing weakens each layer’s ability to represent things independently. When the layers within a span differ too much in responsibility, the quality drop offsets the memory benefit. It is advisable to start with an interval of 2 and then experiment with larger spans step by step.
Misconception 2: Cross-layer reuse can completely replace other KV-compression methods. The two optimize along different dimensions, and cross-layer reuse cannot reduce the cached bytes per token within a single layer. In memory-constrained deployments, the usual combination is “cross-layer reuse + GQA + low-precision storage.”
Misconception 3: All layers can share. Sets of layers with mixed local/global attention or inconsistent positional encoding cannot be forced to share. Architectural analysis should be a mandatory step before deployment.
Misconception 4: No fine-tuning is needed after sharing. Unless the model already used a shared structure during pretraining, it must be distilled or fine-tuned to restore quality.
Outlook
As context lengths continue to grow, structural optimization of the KV Cache will remain one of the core topics in inference-system design. Cross-layer reuse is orthogonal to directions such as low-rank compression, quantization, and sparse attention, and can be combined into a “multi-level cache compression” scheme. Lightweight inference for on-device and edge deployment will also continue to rely on this kind of structure–system co-design.
For developers, understanding cross-layer reuse comes down to three points: it saves redundancy along the layer dimension, not the bytes of each token; it depends on architectural analysis and cannot be applied blindly; and it requires training adaptation before the memory savings can be turned into stable business value.
