KV Cache Memory Optimization: Cross-Layer KV Reuse and MoE vs. Dense Trade-offs
This article explains why the KV cache often becomes the memory bottleneck before model weights in long-context, agentic, and high-concurrency LLM serving. It walks through the KV cache memory formula, compares mainstream reduction techniques (MQA/GQA, MLA, cross-layer KV sharing, sliding window, KV quantization, and importance-based eviction), and provides runnable-style pseudocode for group-based cross-layer KV reuse across prefill and decode phases. It also clarifies when to choose MoE versus Dense architectures and how to make KV cache optimizations actually hold up in production through quantization calibration, context-loss safeguards, load testing, and a measurable memory-latency-quality evaluation loop.
1. Why the KV Cache Becomes the Memory Bottleneck in Long Contexts
In LLM inference, KV cache memory usage can be roughly estimated as:
KV Cache memory ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × batch × bytes
The factor of 2 accounts for the two caches, Key and Value. The formula shows that as context length grows, the KV cache grows roughly linearly. In long-context scenarios, the KV cache can even exceed the memory footprint of the model weights themselves.
During autoregressive generation, the model must attend to all previously generated tokens at every step. Recomputing the Key and Value of all historical tokens each time would be prohibitively expensive, so in practice the already-computed K/V tensors of each layer are cached and reused during decoding. In essence, the KV cache trades memory for compute.
But this comes at the cost of memory pressure. KV cache size scales directly with the number of layers, KV heads, head_dim, sequence length, and batch size. Note that in MHA the number of KV heads typically equals the number of attention heads, whereas in GQA or MQA the number of KV heads is reduced significantly, which lowers memory usage. In real deployments, beyond theoretical memory, you also need to account for alignment overhead from paging mechanisms such as PagedAttention.
This is why, in long-document understanding, codebase comprehension, multi-turn agent interactions, and high-concurrency inference serving, the KV cache often becomes a bottleneck even before the model weights do.
2. How to Choose Among Mainstream KV Cache Reduction Techniques
Common techniques include MQA/GQA, MLA, cross-layer KV sharing, sliding window, KV quantization, and importance-based eviction. They are not mutually exclusive, and real systems often combine several of them.
| Technique | Core Idea | Memory Reduction | Compute Overhead | Requires Training Adaptation | Main Quality Risk |
|---|---|---|---|---|---|
| MQA/GQA | Multiple query heads share one set of K/V | High | Usually low | Usually requires training or continued pretraining | Medium; depends on head count and task |
| MLA | Low-rank compressed K/V representation | High | May add compress/decompress compute | Usually requires training | Medium; depends on training adequacy |
| Cross-layer / shared KV | Later layers reuse K/V from earlier layers or a subset of layers | Medium-high | Can reduce compute for some layers | Usually requires structural adaptation or continued training | Medium; sensitive to sharing granularity |
| Sliding window | Keep K/V only for the most recent window of context | High | Low | Usually no training needed | High risk: old context is lost |
| KV quantization | Compress fp16/bf16 cache to int8/int4 | Medium | Low to medium | Usually requires calibration | Medium-high risk: low bit-widths may drop accuracy |
| Importance-based eviction | Keep high-attention-score, important tokens | Medium-high | Requires computing attention or heuristic scores | May need no training but requires tuning | High risk: may evict critical information |
When choosing, do not look at memory savings alone. Consider three things: whether long-context information must be preserved, whether continued training is possible, and whether inference latency is acceptable.
3. How Cross-Layer KV Reuse Saves Memory
In a traditional Transformer, every layer independently computes and caches its own K/V. The idea behind cross-layer reuse is to let certain later layers directly reuse the Key-Value states already computed by earlier layers, instead of recomputing and storing K/V at every layer.
The benefits are twofold:
- Memory benefit: reused layers no longer store their own KV cache, so overall cache size drops.
- Compute benefit: reused layers do not need to recompute the K/V projections, which can also improve inference throughput.
However, cross-layer reuse should not be implemented as simply “all layers share one global KV.” A more sensible approach is group-based sharing, for example sharing one KV across every two adjacent layers, or sharing one KV every few layers. The pseudocode below shows the design with incremental decoding branches included.
# TransformerLayer input/output contract:# forward(hidden_states, shared_kv=None, use_cache=False)# returns: hidden_states, k, v# where k, v are the Key / Value the current layer needs to write to the cache.class CrossLayerReuseAttention(nn.Module):def __init__(self, num_layers, group_size=2):super().__init__()self.num_layers = num_layersself.group_size = group_size # adjacent group_size layers share one KVself.layers = nn.ModuleList([TransformerLayer() for _ in range(num_layers)])def forward(self, hidden_states, past_kv_cache=None):# past_kv_cache: List[(k, v)], each element corresponds to one shared group# each k/v typically has shape [batch, kv_heads, seq_len, head_dim]if past_kv_cache is None:# 1. Prefill phase: share KV within each groupout_cache = []group_kv = Nonefor idx, layer in enumerate(self.layers):if idx % self.group_size == 0:# Group-head layer: compute and cache KV normallyhidden_states, k, v = layer(hidden_states, use_cache=True)group_kv = (k, v)out_cache.append(group_kv)else:# Subsequent layers in the group: reuse the group-head KV, no separate cachinghidden_states = layer(hidden_states,shared_kv=group_kv,use_cache=False)return hidden_states, out_cacheelse:# 2. Decode phase: each layer group computes the current token's K/V# and appends it to the corresponding group cacheout_cache = []for idx, layer in enumerate(self.layers):group_idx = idx // self.group_sizeif idx % self.group_size == 0:# Group-head layer: compute the current token's K/Vhidden_states, k, v = layer(hidden_states, use_cache=True)past_k, past_v = past_kv_cache[group_idx]# Concatenate the current token's K/V into the history cachek_all = torch.cat([past_k, k], dim=2)v_all = torch.cat([past_v, v], dim=2)out_cache.append((k_all, v_all))# Compute attention for the current token using the concatenated full cachehidden_states = layer.forward_with_kv(hidden_states, k_all, v_all)else:# Subsequent layers in the group: reuse this group's full KV cachek_all, v_all = out_cache[group_idx]hidden_states = layer(hidden_states,shared_kv=(k_all, v_all),use_cache=False)return hidden_states, out_cache
This pseudocode highlights a key point: cross-layer reuse is not simply sharing one global KV across all layers, but managing caches by group. In the prefill phase, group sharing reduces the number of caches; in the decode phase, each group must append the current token’s K/V so that context is not lost as the sequence continues to generate.
Note that cross-layer reuse introduces some accuracy risk. Whether accuracy drops depends on sharing granularity, compression ratio, model scale, evaluation set, and whether continued training is performed. It is not accurate to claim generally that it “loses almost no model quality.” For engineering adoption, be sure to validate tasks such as long-context retrieval, multi-turn consistency, and code understanding.
4. MoE vs. Dense: How to Choose
When discussing KV cache, it also helps to understand the differences between MoE and Dense architectures.
MoE uses a routing mechanism so that each token activates only a subset of expert parameters, giving it a degree of computational sparsity. However, it must be emphasized that MoE inference typically requires loading all expert weights, so activation sparsity does not mean memory sparsity. In other words, MoE can increase model capacity per unit of compute, but it does not inherently reduce deployment memory.
In addition, MoE’s sparse routing mainly affects the per-token parameter compute and does not directly reduce the KV cache of each layer. Its impact on KV cache is more indirect: if a MoE model reaches the target quality with fewer total layers, the reduced layer count indirectly lowers KV cache usage.
A Dense architecture, by contrast, has all parameters participate in computation for every token, giving it a more regular structure. Its strengths are post-training friendliness and a clear tuning path, making it well suited to scenarios that need deep fine-tuning, domain alignment, and quality control.
| Scenario Characteristics | Recommended Direction | Core Consideration |
|---|---|---|
| On-device / embedded, memory- or VRAM-constrained | Dense small model + KV optimization | Quantization, sliding window, shared KV |
| Compute-constrained but memory-rich, e.g. datacenter GPUs | MoE | Activation sparsity, large total parameter capacity |
| Deep fine-tuning / domain alignment needed | Dense | Stable post-training, tuning-friendly |
| Long context, high-concurrency serving | Combined with KV optimization | Memory usage and TTFT are the primary bottlenecks |
Therefore, on-device scenarios should not simply assume “MoE is always more memory-efficient.” If memory or VRAM is constrained, a dense small model combined with KV cache optimization is often more reliable. Only when compute is constrained but memory is abundant might MoE show its advantages.
5. How to Make KV Cache Optimization Actually Work
5.1 Start with Quantization, but Calibrate and Run Regression
KV cache quantization is the most direct memory optimization, for example compressing an fp16 cache to int8. But quantization cannot be judged by memory reduction alone; you must also evaluate accuracy loss.
At minimum, this should include:
- Use a representative calibration set to profile K/V distributions;
- Keep higher precision for sensitive layers;
- Compare logits or output distributions before and after quantization;
- Run regression tests for long-context retrieval, multi-turn dialogue, and code understanding.
5.2 Be Cautious About Context Loss with Sliding Windows and Eviction
Sliding windows keep only the most recent context, which suits streaming interactions and low-latency scenarios. But they explicitly discard history that falls outside the window, so in long-document summarization, codebase understanding, and multi-turn agent tasks, you must verify that critical information remains available.
Importance-based eviction keeps important tokens based on attention scores and can reduce the cache, but you also need to watch the threshold. If the threshold is too aggressive, it may wrongly evict information that is critical for later inference.
5.3 Rely on Load Testing and Monitoring in Production
Production deployment cannot rely on theoretical formulas alone. Recommended practices:
- Use load testing to determine the maximum context length and batch size a single instance can handle;
- Monitor peak memory, TTFT, TPS, and OOM counts;
- Scale elastically based on load;
- Set different routing or rate-limiting policies for different context lengths;
- Retain logs of failed requests to help pinpoint memory spikes.
5.4 Build a Measurable Evaluation Loop
It is recommended to establish the following baseline template:
| Item | Example |
|---|---|
| Hardware and model | GPU model, model name, parameter scale |
| Structural parameters | num_layers, num_kv_heads, head_dim |
| Context length gradient | 4k / 16k / 32k / 64k |
| Quantization bit-width | fp16 / int8 / int4 |
| Batch size | 1 / 8 / 16 |
| Measurement tools | nvidia-smi, profiler, inference framework metrics |
| Quality tasks | Long-context retrieval, multi-turn consistency, code understanding |
When evaluating, do not look only at peak memory; also look at TTFT, throughput, failure rate, and task quality. Only by forming a “memory, latency, quality” triangular evaluation can optimization be sustained.
6. FAQ: Quick Answers to Common Questions
What is the difference between KV cache and GQA/MLA?
KV cache is the mechanism that caches historical Key/Value during inference; GQA/MLA are methods that reduce KV cache size at the model structure or representation level. The former addresses “whether to cache,” while the latter addresses “how much to cache and how to compress it.”
Does cross-layer reuse hurt accuracy?
It may. Whether accuracy drops depends on sharing granularity, compression ratio, whether the model is further trained, and the evaluation tasks. When adopting it, you must compare before and after on the target business dataset rather than relying only on conclusions from a paper.
Should on-device choose MoE or Dense?
If device memory or VRAM is constrained, prefer a dense small model, combined with optimizations such as quantization, sliding windows, and shared KV. If compute is constrained but memory is abundant, for example on datacenter GPUs, evaluate whether MoE delivers throughput and capacity benefits.
7. Summary
KV cache slimming is a key engineering challenge in the era of long context, agents, and high-concurrency inference. Its core is not a single trick but a closed loop built around memory estimation, structural selection, compression strategy, and quality regression. Cross-layer KV sharing offers an important path to reducing the cache, but it must be paired with sensible group design, training adaptation, and evaluation validation. MoE and Dense are not a simple either/or choice either; the decision should combine on-device resources, compute conditions, and post-training needs.
