Cross-Layer KV Cache Sharing: A Memory Optimization Path for Long-Context LLM Inference
This article explains why the KV cache becomes the dominant cost center in long-context inference and introduces cross-layer KV tensor sharing as a vertical optimization path distinct from traditional horizontal compression. It breaks down how KV cache memory is calculated, the assumption that makes sharing across layers viable, the mechanics of grouped KV sharing with illustrative code, and a realistic assessment of the benefits, trade-offs, and boundaries of the approach. Readers will also find practical engineering guidance for deciding when to adopt this technique, how to stack it with MQA/GQA and KV quantization, and how to tune grouping granularity against a quality threshold. It is aimed at engineers deploying long-context LLM services who need to reduce GPU memory, relieve bandwidth pressure, and improve throughput without sacrificing generation quality blindly.
1. Starting from the Decoding Bottleneck: Why KV Cache Becomes the Cost Center of Long Context
In autoregressive generation, a model predicts one token at a time, appends it to the end of the input sequence, and runs the forward pass again to predict the next token. If the model recomputed the entire sequence from scratch for every generated token, the compute cost would grow quadratically with sequence length—completely unacceptable.
To avoid this redundant computation, mainstream implementations introduce a classic optimization: cache the Key and Value tensors that each attention layer computes over historical tokens, and reuse them directly during later decoding. This cache is the so-called KV Cache. Its essence is trading “extra memory” for “avoiding redundant computation”—during inference, the model no longer needs to recompute the key-value pairs for the historical portion; it only computes new Keys/Values for the newly added tokens, concatenates them with the cached history, and completes the attention.
The problem is that this cache grows linearly with context length. As the context expands from a few thousand tokens to tens of thousands or even hundreds of thousands, the KV Cache swells rapidly and can often occupy more space than the model weights themselves. In scenarios such as long-document summarization, multi-turn dialogue, codebase understanding, and long video/audio modeling, the KV Cache frequently becomes the hard bottleneck that determines how large a batch a single GPU can hold and how long a context it can support.
2. How KV Cache Memory Is Actually Calculated
To understand where the optimization room lies, we first need to account for the memory clearly. The size of the KV Cache can be approximated as:
KV_cache ≈ 2 × num_layers(L) × num_kv_heads(H_kv) × head_dim(d) × seq_len(S) × batch × bytes
Here the factor of 2 accounts for the two tensors, Key and Value. This formula reveals a key fact: the KV Cache is strictly linear in the number of layers. In other words, every layer in a Transformer independently maintains its own key-value cache.
This leaves two orthogonal directions for optimization:
- Horizontal compression: reduce the key-value width per token. Representative approaches include Multi-Query Attention (MQA), where multiple Query heads share one set of KV, and Grouped-Query Attention (GQA), which shares KV in proportional groups; there is also KV quantization, which compresses the cache from 16-bit down to 8-bit or even lower.
- Vertical reuse: reduce the number of cache copies—that is, stop having every layer hold its own KV, and instead let several layers share the same key-value state. This is the core idea of “cross-layer KV tensor sharing” (Cross-Layer KV Sharing / Cross-Layer Attention).
These two directions are not mutually exclusive and can be stacked together.
3. The Intuition Behind Cross-Layer Reuse: Why Layers Can “Share”
A natural question arises: since different layers learn different features, on what basis can they share the same Key/Value?
Empirically, the attention patterns of adjacent Transformer layers tend to be highly correlated—in particular, the “positional relationships” and “content aggregation weights” carried by the Key and Value are strongly similar across adjacent layers. On this basis, the fundamental assumption of cross-layer reuse is that introducing a degree of parameter and state sharing along the network’s vertical dimension has a relatively controllable impact on final generation quality, while the memory savings it yields are substantial.
So “cross-layer reuse” is not simply deleting some layers’ caches, but redesigning how KV is produced and consumed: a subset of layers is responsible for computing and caching the Key/Value, while the remaining layers directly reference these shared key-value tensors when computing attention. Note that this is an architectural, structural change. It usually requires training from scratch, or at least substantial continued training (uptraining) and fine-tuning on an existing model, so that the sharing mechanism coordinates with the rest of the parameters. Simply “grafting” cross-layer sharing onto an already fully trained standalone model often fails to produce the desired results.
4. How Cross-Layer KV Reuse Works, with Illustrative Code
The most common implementation strategy is grouped sharing: divide all layers into several groups, where the layers within each group share one KV. The larger the group, the more layers share, and the more pronounced the memory savings—but the stronger the constraint on the model’s expressiveness.
First, here is the conventional structure where each layer caches independently:
# Conventional structure: each layer computes and caches its own Key/Valuefor layer in layers:q, k, v = layer.qkv_proj(hidden) # every layer produces its own k, vk_cache[layer.idx].append(k) # each layer caches independentlyv_cache[layer.idx].append(v)hidden = layer.attend(q, k_cache[layer.idx], v_cache[layer.idx])
Now the cross-layer reuse version:
# Cross-layer reuse: every group_size layers share one Key/Valuefor group_id, group in enumerate(layer_groups): # divided into several groupsshared_k, shared_v = group.compute_shared_kv(hidden) # computed by a representative layer in the groupfor layer in group:q = layer.q_proj(hidden) # each layer still computes its own Query# attention uniformly references this group's shared K/Vhidden = attend(q, shared_k, shared_v)# note: only the shared source layer produces new K/V written to the cache# the cache only needs to store one K/V per group
The key differences are:
- The Query is still computed per layer, preserving each layer’s ability to express a distinct output direction for attention;
- The Key/Value is produced only once per group, and is reused by all layers in the group;
- The memory only needs to store
num_groups × 2 × num_heads × head_dim × seq_len, rather thannum_layers × ....
If all layers are compressed into a single shared KV, that is the most aggressive scheme (the number of cache copies drops to 1); if each group holds only 2 layers, memory is roughly halved. In engineering practice, teams typically tune the group size to strike a balance between “memory savings” and “quality loss.”
5. Benefits, Costs, and Applicability Boundaries
The benefits are cumulative, not just memory savings:
- Lower memory footprint: the most direct benefit, which directly determines the batch size and maximum sequence length supportable under long context.
- Reduced memory bandwidth pressure: autoregressive decoding is a memory-bandwidth-intensive task; a smaller KV Cache means less data to move at each decoding step, often yielding improvements in both throughput and latency.
- Stackable with horizontal optimizations: cross-layer reuse can be combined with MQA/GQA and KV quantization to further shrink the cache.
The costs and constraints must also be faced squarely:
- It requires training-side support: as noted, cross-layer sharing is a structural change that needs training from scratch or substantial continued training, and cannot simply be “grafted” onto any off-the-shelf model.
- There is a quality tradeoff: the larger the group, the more you save, but the stronger the constraint on the model’s expressiveness, which may cause quality regression on some challenging tasks and requires evaluation tailored to the target scenario.
- It couples with some inference optimizations: cross-layer sharing changes how KV is organized, so optimizations that rely on per-layer independent caching need to be adapted accordingly.
Applicability boundaries:
- Highly recommended: deployment scenarios with extremely long context, tight memory, and throughput and long-sequence support as the core metrics.
- Evaluate carefully: scenarios that are extremely sensitive to generation quality, or where the context is short (in which case the KV Cache is not the primary bottleneck)—the benefits may not justify the modification cost.
6. Engineering Recommendations
- Locate the bottleneck first, then decide the optimization direction. Use inference-side memory profiling tools to confirm the KV Cache’s share of total memory. If the weights dominate and the context is short, the marginal benefit of cross-layer reuse is limited; otherwise, it should be a priority.
- Try stackable, mature combinations first. A common practice is to apply horizontal compression with GQA/MQA, pair it with KV quantization to reduce the per-token width, and then evaluate whether to introduce cross-layer reuse for vertical compression.
- Run a sensitivity analysis via grouping granularity. It is advisable to do continued training and evaluation across different group sizes, plot a “memory savings vs. task quality” curve, and find the maximum compression point that stays above the business quality threshold.
- Build a per-scenario evaluation loop. Cover typical tasks such as long-document understanding, multi-turn dialogue, and structured extraction, and compare different configurations horizontally using unified metrics, avoiding a view based on a single metric alone.
- Deploy elastically on demand in the cloud. The optimizations above ultimately manifest in the deployment posture. With foundational capabilities such as general-purpose container platforms, model-serving, and monitoring and alerting, long-context services can scale elastically, quantify inference resource utilization, and continuously observe memory, latency, and throughput metrics—so the benefits of architectural optimization actually translate into cost savings.
7. Summary
The KV Cache is an unavoidable cost in long-context inference, and “cross-layer KV tensor sharing” offers a vertical optimization path distinct from traditional horizontal compression: by sharing Key/Value state across layers, it reduces the number of cache copies from “growing with the number of layers” to “growing with the number of groups.” Understanding the full chain of “sharing assumption → grouping strategy → training support → quality tradeoff” helps make more precise engineering trade-offs among memory, bandwidth, throughput, and generation quality. It is worth stressing that any architecture-level optimization should be grounded in real evaluation, avoiding empty claims of benefit detached from the actual scenario.
