Cross-Layer KV Cache Reuse: A Guide to MoE and Dense Architecture Selection
This article explores optimizing large language model (LLM) inference by evaluating cross-layer KV cache reuse, architectural selection, and cloud deployment metrics. It breaks down the memory dynamics of KV cache, the practical implementation and trade-offs of cross-layer tensor sharing, and provides a comparative guide for choosing between edge, MoE, and dense models. Additionally, it outlines post-training challenges and key performance indicators for enterprise cloud deployments.
Introduction
This article answers three primary questions. First, can cross-layer KV tensor reuse be directly applied to existing models, and how significant are the memory benefits? Second, how should developers choose between edge small models, local Mixture of Experts (MoE) models, and dense models? Third, what metrics should enterprises monitor when deploying these models in the cloud?
We will first explain why the KV cache consumes so much memory, then discuss the principles and trade-offs of cross-layer reuse, and finally outline selection strategies for different architectures.
1. Why KV Cache Consumes Significant Memory
In autoregressive generation with Transformers, every time the model generates a new token, it must read the Key and Value of all previously generated tokens. To avoid redundant computation, inference frameworks save these K and V tensors, creating the KV Cache.
The memory footprint of the KV Cache can be estimated using the following formula:
Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
For example, consider a model with 32 layers, 8 KV heads, a head dimension of 128, and FP16 precision (2 bytes per element). Each token consumes approximately 128 KiB. At a context length of 32K, a single sequence’s KV Cache is roughly 4 GiB. This footprint grows almost linearly with sequence length and must be multiplied by the number of concurrent requests during batch inference.
It is important to distinguish that during the Prefill phase, the size of the attention score matrix is proportional to the square of the sequence length. If the inference implementation does not utilize techniques like block-wise computation, the compute and temporary memory for this part will scale rapidly. Therefore, the memory pressure from long contexts stems from two sources: the long-term stored KV Cache, and the intermediate attention results from temporary computation. Cross-layer reuse primarily targets the former.
2. Principles and Trade-offs of Cross-Layer KV Tensor Reuse
In traditional multi-layer attention, each layer independently computes and stores its own K and V. Cross-layer reuse allows several adjacent layers to share the same set of K and V. Within a sharing group, only one layer is responsible for computing and writing, while the remaining layers simply read this cache.
Continuing the previous example, if every two layers share a group of KV, the KV Cache theoretically reduces by about half, resulting in roughly 2 GiB for a 32K context. This is an idealized estimate. Actual gains depend on the group size, which layers participate in sharing, the number of KV heads, and the quantization precision of the KV Cache.
The following pseudocode demonstrates the read/write logic for sharing caches by layer group:
import torch.nn as nnclass GroupSharedKVCache:"""Saves a group of K and V by layer group; only the writer layer computes."""def __init__(self, group_size):self.group_size = group_sizeself.store = {} # group_id -> (k, v)def group_id(self, layer_idx):return layer_idx // self.group_sizedef is_writer(self, layer_idx):# The first layer of each group computes and writes KVreturn layer_idx % self.group_size == 0def write(self, layer_idx, k, v):self.store[self.group_id(layer_idx)] = (k, v)def read(self, layer_idx):return self.store[self.group_id(layer_idx)]class SharedKVAttention(nn.Module):def __init__(self, config, layer_idx, shared_cache):super().__init__()self.layer_idx = layer_idxself.shared_cache = shared_cacheself.q_proj = nn.Linear(config.hidden_size, config.hidden_size)self.k_proj = nn.Linear(config.hidden_size, config.kv_dim)self.v_proj = nn.Linear(config.hidden_size, config.kv_dim)def forward(self, hidden_states, attn_mask=None):q = self.q_proj(hidden_states)if self.shared_cache.is_writer(self.layer_idx):k = self.k_proj(hidden_states)v = self.v_proj(hidden_states)self.shared_cache.write(self.layer_idx, k, v)k, v = self.shared_cache.read(self.layer_idx)return self.attend(q, k, v, attn_mask)def attend(self, q, k, v, attn_mask):# Multi-head splitting, scaled dot-product attention, and output projection are implemented here, omittedraise NotImplementedError
This code illustrates only the read/write logic and cannot run directly. It omits the appending of new KVs token-by-token, multi-head splitting, Rotary Position Embedding (RoPE) handling, and incremental decoding during inference. A real implementation requires attention to two points: first, the writer layer must complete its computation before the reader layers. Second, the position encodings and attention masks corresponding to the shared K and V must remain consistent; otherwise, the results obtained by the reader layers will deviate from expectations.
Cross-layer reuse also involves three trade-offs that need evaluation:
- Requires model structure support: This optimization typically requires the model to adopt a shared structure during its design or training phase. It cannot be arbitrarily enabled on existing models at the inference side.
- Potential quality degradation: Sharing reduces the independent representational space of each layer. It is necessary to compare against a baseline model on an evaluation set to ensure the quality regression is within an acceptable range.
- Benefits affected by other factors: Methods like quantizing the KV Cache or reducing the number of KV heads also lower memory usage. Their combined effect with cross-layer reuse requires empirical testing.
Therefore, the correct approach is to first confirm if the model supports this structure, then empirically test memory and latency using target context lengths and concurrency, and finally verify quality on an evaluation set.
2 (Cont.): Edge, Local, and Cloud Model Selection
Different deployment environments have vastly different requirements for models. The table below provides a rough comparison; specific values should be tested based on actual hardware and quantization schemes.
| Model Category | Parameter Scale | Typical Scenarios | Resource Characteristics | Post-Training Difficulty |
|---|---|---|---|---|
| Edge ultra-small models | 2B to 4B | Smartphones, embedded devices, edge boxes | Low memory footprint after distillation and quantization, suitable for low-latency simple tasks | Low; single GPU is sufficient for small-scale fine-tuning |
| Local MoE models | Tens of B total params, few active params | Local workstations, enterprise internal data processing | High total parameter footprint; requires enough VRAM or RAM to host all experts | High; routing and hyperparameters require specialized tuning |
| Dense models | ~30B | Vertical domains requiring high quality and frequent fine-tuning | All parameters active per inference; compute scales linearly with parameters | Medium; mature workflow, but requires preventing catastrophic forgetting |
Edge ultra-small models are suited for latency-sensitive scenarios with low problem complexity. Developers need to focus on operator fusion and memory allocation to prevent prolonged memory jittering on low-compute devices.
MoE models have a large total parameter count, but since each token only activates a subset of experts, the single-pass compute is relatively small. However, all expert weights must reside in accessible memory. If VRAM is insufficient, loading expert weights becomes a bottleneck, and inference speed may not be faster than a dense model with equivalent active compute.
Dense models use all parameters in every forward pass, making their inference and training behavior more straightforward. When a team needs to frequently fine-tune, compare the effects of different data ratios, or perform deep customization in a specific domain, dense models are generally easier to maintain.
3. Post-Training Issues and Checklist for MoE Models
The gating network of an MoE model determines which experts each token is routed to. This dynamic routing mechanism is prone to three types of issues during post-training:
- Load imbalance: Some experts receive too many tokens, while others are rarely activated.
- Routing oscillation: During fine-tuning, the same type of input is repeatedly assigned to different experts, leading to training instability.
- Hyperparameter sensitivity: Minor changes in learning rate or batch size can cause noticeable performance fluctuations.
To address these issues, check the following list:
- Enable load balancing auxiliary loss during training and log its coefficient. Too high a coefficient may suppress the model’s primary learning objective, while too low makes it hard to correct load imbalance.
- Track each expert’s activation frequency on the validation set and calculate the ratio of maximum load to average load. If this ratio remains persistently high, adjust routing settings or data distribution.
- Monitor the entropy of the routing distribution. A rapid drop in entropy usually indicates premature routing convergence to a few experts.
- Search for learning rate and batch size within a small range, and compare against pre-training settings.
- If the data volume is small, freeze the router and fine-tune only a subset of experts or adapter layers to reduce routing oscillation risks.
- Retain the pre-trained baseline checkpoint for every fine-tuning run and compare on the same evaluation set.
4. Advantages and Risks of Dense Model Post-Training
When fine-tuning dense models, gradients cover all parameters, eliminating allocation problems caused by routing. This makes the training process easier to reproduce and tuning results easier to interpret. In vertical domains like healthcare or law, teams can more directly assess the model’s knowledge forgetting and capability alignment.
However, dense model post-training still carries several common risks:
- Catastrophic forgetting: With an excess of domain-specific data, general capabilities may drop significantly. The solution is to mix general data with domain data at a fixed ratio and continuously monitor scores on general evaluation sets.
- Evaluation set leakage: Overlap between training and evaluation data will inflate results. It is recommended to deduplicate during data construction and maintain strict isolation between evaluation and training sets.
- Overfitting on small data: With small sample sizes, models easily memorize training sample phrasing. Use early stopping, reduce training epochs, and observe result stability across multiple random seeds.
A sound practice is to save baseline checkpoints, training configurations, and evaluation results for every version. If a new version degrades in quality, the team can quickly roll back and pinpoint whether the issue stems from data, hyperparameters, or the training pipeline.
5. Metrics to Monitor for Cloud Deployment
In enterprise environments, model serving is often deployed on cloud-native platforms, supported collectively by container orchestration, elastic GPU instances, distributed storage, and monitoring systems. Pay attention to the following metrics during deployment:
- Prefix cache hit rate: The ratio of hit prefix tokens to the total input tokens in a request. This metric reflects the effectiveness of cache reuse and is easier to define and compare than a simple “KV Cache hit rate.”
- KV cache pool usage: The proportion of occupied KV Cache capacity to total capacity. When consistently near the limit, inference services are prone to queuing or eviction.
- Time To First Token (TTFT) and Time Per Output Token (TPOT): These measure the user’s wait time for the first token and the speed of subsequent generation, respectively.
- MoE expert load ratio: The ratio of maximum to average load across experts. A persistently high value indicates that certain experts have become bottlenecks.
- Elastic scaling cold start time: The time required from triggering a scale-out event to a new instance being ready to receive requests. For large models, this time can be significantly longer than standard services.
For MoE models, large expert weights mean that the bandwidth of distributed storage and high-speed networks will affect loading speeds. For dense model fine-tuning, multi-node multi-GPU training requires attention to communication overhead and inter-node synchronization efficiency.
Conclusion
Cross-layer KV tensor reuse can reduce the memory footprint of the KV Cache, but it requires structural support from the model and quality validation on an evaluation set. Edge small models, local MoE models, and dense models each have their applicable scenarios; selection should weigh VRAM, post-training difficulty, and deployment environment. Before going live, teams are best served by conducting a round of empirical testing using their own hardware, context lengths, and evaluation data to determine the optimal approach.
