Cutting Long-Context Inference Costs with Cross-Layer KV Cache Reuse
As context windows grow into the hundreds of thousands of tokens, the KV Cache quickly becomes the dominant memory bottleneck in LLM inference. This article explains why the KV Cache scales linearly with sequence length and layer count, the key observation that K and V tensors are highly redundant across Transformer layers, and how cross-layer KV cache reuse lets groups of consecutive layers share a single set of keys and values to cut both memory footprint and compute. It also covers the tradeoffs between MoE and Dense architectures and the practical considerations for adopting this optimization.
1. Why the KV Cache Is the Top Bottleneck for Long Contexts
During autoregressive decoding, the model attends the current token over all historical tokens every time it generates a new one. To avoid recomputing the keys and values of tokens that have already been processed, inference frameworks cache the computed K and V tensors. This is the KV Cache.
Its cost can be understood intuitively through an approximate memory formula:
# Approximate KV Cache memory (bytes)kv_cache_bytes = 2 # one copy each for K and V* num_layers # number of layers* num_kv_heads # number of KV attention heads* head_dim # dimension per head* seq_len # sequence length (context)* batch_size # batch size* bytes_per_elem # bytes per element (FP16=2)
The key point: seq_len grows the memory footprint linearly, while num_layers acts as a constant multiplicative factor. When the context expands from a few thousand tokens to hundreds of thousands, the KV Cache quickly consumes most of the available memory, which directly shrinks the batch size you can serve concurrently and pushes up the inference cost per token. For on-device and embedded deployment, this memory footprint is often the deciding factor in whether the model can run at all.
2. The Core Observation: K and V Are Highly Redundant Across Layers
Each layer of a Transformer computes and caches its own set of K and V. However, extensive empirical observations show that the attention patterns learned at different layers are often highly similar, and the K and V tensors exhibit clear correlation and redundancy across layers. This means that storing a full, independent KV set for every layer is a waste of resources.
The core idea of cross-layer KV cache reuse is straightforward: instead of maintaining separate K and V for each layer, let a group of consecutive layers share the same KV state. Later layers directly reuse the keys and values already computed by earlier layers (or by a representative layer in the group) rather than re-projecting and re-caching them.
3. How Cross-Layer Reuse Saves Both Memory and Compute
Take the case of sharing one KV set per group of g layers. The gains show up in two dimensions:
- Memory: The effective number of layers holding a KV cache drops from
num_layersto roughlynum_layers / g, cutting memory usage to about1/gof the original. The largerg, the more you save. - Compute and memory bandwidth: The merged layers no longer need to run their own K and V linear projections, and fewer cache reads and writes happen at each decoding step, which lowers memory-bandwidth pressure.
Here is illustrative, framework-agnostic pseudocode:
def forward_with_shared_kv(layers, hidden, share_group=2):kv_cache = {} # store shared K/V keyed by the group's representative layeroutput = hiddenfor idx, layer in enumerate(layers):group_id = idx // share_groupif group_id not in kv_cache:# First layer of the group: compute K/V and write to the shared cacheq, k, v = layer.proj_qkv(output)kv_cache[group_id] = (k, v)else:# Subsequent layers: compute only their own Q and reuse the group's K/Vq = layer.proj_q(output)k, v = kv_cache[group_id]attn = scaled_dot_product_attention(q, k, v)output = layer.ffn(attn)return output
What this logic shows is that the real savings come not from the computation of any single layer, but from the overall scale of duplicated storage and duplicated projection. With the model structure largely unchanged, it trades a very small amount of engineering effort for a significant memory gain.
4. Two Mainstream Architectures: The MoE vs. Dense Tradeoff
When discussing this kind of lightweight design, you often see two parallel technical routes. They are not mutually exclusive but target different goals:
- Mixture of Experts (MoE): Each token activates only a subset of expert networks, so the actual per-token activation compute stays relatively controlled even as parameter count grows. This suits high-performance on-device inference scenarios that aim for large parameter counts with manageable compute.
- Dense: All parameters are activated for every token, making inference behavior more predictable. Dense models are also friendlier to post-training and fine-tuning—because MoE’s routing mechanism makes training and fine-tuning less stable and harder to tune, whereas Dense models more easily achieve stable quality in instruction tuning, alignment, and similar workflows.
A common productization approach follows from this: choose MoE for scenarios that demand extreme efficiency, and choose Dense for scenarios that require frequent post-training and fine-grained tuning. A general inference-side optimization like cross-layer KV reuse can be stacked on top of either architecture as an orthogonal capability.
5. Key Tradeoffs in Practice
Cross-layer reuse is not a free lunch. Real deployment needs to account for the following:
- Accuracy evaluation: While K and V are redundant across layers, they are not identical. Sharing them may cause slight degradation in perplexity or downstream task metrics, so always run A/B evaluation on your target business data.
- Choosing the sharing granularity: A larger
share_groupsaves more memory but carries more risk, while a smaller one yields limited gains. Start with 2 and adjust gradually using both accuracy and memory as metrics. - Coordination with quantization and paging: Cross-layer reuse can be combined with KV quantization and paged cache management (memory scheduling on a page-by-page basis) for often larger gains, but be mindful of implementation-level compatibility.
- Alignment during training: The most reliable approach is to introduce the shared structure during training so the model adapts to it proactively. Force-fitting sharing only at inference time usually works worse.
6. Summary
The inference cost of long contexts comes down to a balancing act between memory and memory bandwidth. By sharing K and V across layers, cross-layer KV cache reuse is a simple yet effective design that directly targets the root cause of the KV Cache scaling linearly with layer count, making it a general optimization with low adaptation cost and clear benefits. In practice, it is worth evaluating alongside your choice of architecture (MoE/Dense), KV quantization, and paged caching: first settle on a sharing granularity that meets accuracy requirements, then do capacity planning based on your workload’s context length, concurrency, and memory budget. When deploying such model services in the cloud, you can combine general capabilities such as container platforms, monitoring and alerting, and logging to continuously track memory usage, throughput, and latency, and use data to iteratively tune the optimal context length and batching configuration—balancing quality, cost, and user experience.
