KV Cache Reuse and MoE vs Dense: LLM Architecture Evolution
This article explains why KV Cache becomes a major bottleneck in long-context LLM inference, how cross-layer KV sharing can reduce cache size on small models, and how MoE and Dense architectures differ in compute cost, memory requirements, post-training complexity, and deployment predictability. It also covers practical KV Cache optimization techniques, capacity estimation, and a deployment checklist.
1. Background: The KV Cache Bottleneck in the Long-Context Era
1.1 Repeated computation during autoregressive decoding
Transformer decoding is autoregressive: every newly generated token must attend to all previous tokens. For standard multi-head attention, the attention output for a single token can be simplified as:
Attention(Q_t, K, V) = softmax( Q_t · Kᵀ / √d + mask ) · V
Q_t is a query vector of length d; K and V are the key and value matrices for all previous tokens; mask prevents attending to future tokens.
In a naive implementation, K and V must be recomputed for all historical tokens at every step. This causes two problems:
- Repeated computation: each token’s K and V are recomputed at every decoding step, and computation grows quadratically with context length;
- No batching of historical state: because representations of previous tokens are not retained, each step degenerates into an independent short-sequence computation.
Therefore, KV Cache is commonly used in engineering practice: during the first forward pass, K and V for all historical tokens are computed and cached. Afterwards, each step only computes K and V for the new token and appends them to the cache. The attention operator reads directly from the cache, reducing complexity from “repeated computation” to “incremental computation.”
1.2 Quantifying memory usage
KV Cache turns a computation problem into a memory-access problem. For each token and each layer, two tensors must be cached: K and V. Each tensor has shape [B, H_kv, d_head], where B is batch size, H_kv is the number of KV heads, and d_head is the dimension of each head.
Let:
- L be the number of layers;
- b be bytes per element, which is 2 for half precision and 1 for 8-bit quantization;
- N be context length in tokens.
The KV Cache memory usage for a single request is approximately:
KV_bytes ≈ 2 × L × H_kv × d_head × b × N
It grows linearly with context length and is proportional to batch size. Long-document question answering, code repository understanding, and multi-turn agent tool calling can push contexts to tens of thousands or even hundreds of thousands of tokens. At that point, KV Cache may become the dominant consumer of GPU memory and reduce the headroom available for higher concurrency.
1.3 Impact on serving metrics
KV Cache directly affects four serving metrics:
- Memory capacity: determines how many concurrent requests a machine can hold;
- Memory bandwidth: during decoding, every generated token requires reading all K and V, and longer context increases per-token latency;
- Time to first token: prefill must compute and write all K and V at once, and with long prompts this stage can be significant;
- Cache hit rate: prefix reuse can substantially reduce repeated computation for multi-turn dialogue, fixed system prompts, and shared long documents.
Whether inference serving feels smooth and how much concurrency can be supported per unit of compute largely depends on how KV Cache is designed and reused. This is also a core motivation behind recent architectural changes.
2. KV Cache Optimization for Small On-Device Models: Cross-Layer Sharing
2.1 What is cross-layer KV sharing?
On-device models for phones and embedded devices are usually smaller, have fewer layers, and prefer narrower head dimensions for efficient quantization. A simple and effective change is introduced: later layers within a shared group do not recompute and cache their own K and V; instead, they directly reuse the K and V computed by the first cached layer in that group.
For example, with 24 layers and one group every 6 layers, full caching would store K and V for 24 layers. With cross-layer sharing, only 4 groups need to store 8 tensors in total, reducing KV Cache size to about 1/6 of the original. The amount of K and V that must be read for attention computation also decreases, which is especially beneficial for bandwidth-limited on-device hardware.
It is important to note that the shared state is the entire historical K and V cache, not just the current token representation. For each new token, K and V are computed once by the first layer in the group, appended to that group’s cache, and then used by all layers in the group. Therefore, this approach is different from techniques that pass hidden states across layers. Its goal is to shrink the cache itself, not to change how information flows between layers.
2.2 Difference from GQA and sliding-window attention
Cross-layer sharing is not entirely new. Research has previously proposed compressing caches by reusing key/value states across layers, and the technique has gradually appeared in open-weight models. To understand it, it is useful to distinguish it from two other mainstream KV optimizations:
| Technique | Compression dimension | Compression target | Main benefit |
|---|---|---|---|
| Grouped-query attention (GQA) | Head dimension | Fewer KV heads than Q heads inside each layer | Reduces per-layer K and V tensor size |
| Sliding-window attention | Context dimension | Keep K and V only for the most recent tokens | Limits cache growth for long contexts |
| Cross-layer KV sharing | Layer dimension | Multiple layers share the same K and V group | Substantially reduces layer-level redundancy |
These techniques operate on different dimensions and can theoretically be combined. For example, GQA can reduce the number of heads, some layers can then share KV across layers, and a sliding-window constraint can be added afterward.
2.3 Benefits and costs
Benefits
- Memory: fewer layers need to maintain independent K and V, so cache usage decreases roughly proportionally;
- Bandwidth and compute: because every layer reads K and V for attention, sharing reduces read volume proportionally; non-leading layers in a group also skip repeated K/V projection, saving compute on on-device hardware;
- Fit for small models: feature differences between layers in small models are usually limited, so the capability loss caused by sharing is often controllable, making it attractive for on-device scenarios.
Costs
- Reduced expressiveness: different layers may originally attend to different token patterns, for example local patterns in shallow layers and long-range dependencies in deeper layers; after sharing, they must obtain information from the same K and V;
- Attention-head degradation: if sharing granularity is too coarse, later layers may gradually ignore the attention branch and behave like approximate token-wise feed-forward transformations, making deeper layers less effective;
- Positional-encoding coupling: layers in a shared group must use the same positional encoding scheme, so individual layers can no longer flexibly adjust positional bias;
- Operational complexity: cache management operations such as quantization and memory swapping must be performed at the group level; updating the cache for a single layer independently would break consistency within the group.
Choosing the sharing granularity is the core design parameter:
- Too coarse, for example keeping only one K and V state for the entire model, clearly weakens expressiveness;
- Too fine, and compression gains become limited.
In practice, teams must repeatedly balance perplexity, downstream task accuracy, and memory usage.
2.4 Illustrative implementation
The following pseudo-code shows the read/write logic and cache organization within a shared group. The first layer in a group computes and writes K and V, while the remaining layers read them directly:
# Illustrative code: decoding logic for cross-layer KV sharing (pseudo-code; control flow only)# Example configuration: num_layers total layers, with every group_size layers forming one shared groupclass SharedKVTransformer:def __init__(self, num_layers: int, group_size: int):self.num_layers = num_layersself.group_size = group_size# KV cache is organized by group rather than by layer: groups = ceil(num_layers / group_size)self.num_groups = (num_layers + group_size - 1) // group_sizeself.k_cache = [None] * self.num_groups # one K cache per group: [B, H_kv, S, d_head]self.v_cache = [None] * self.num_groups # one V cache per group: [B, H_kv, S, d_head]def forward(self, x, layer_idx: int):group_idx = layer_idx // self.group_sizeis_group_lead = (layer_idx % self.group_size == 0)if is_group_lead:# Lead layer in the group: compute K/V for the current token and append to the group cachek_new, v_new = self.kv_proj(x) # [B, H_kv, 1, d_head]k = self.append(self.k_cache[group_idx], k_new)v = self.append(self.v_cache[group_idx], v_new)self.k_cache[group_idx], self.v_cache[group_idx] = k, velse:# Other layers: reuse the K/V maintained by the lead layer and skip K/V projectionk, v = self.k_cache[group_idx], self.v_cache[group_idx]# Q is still computed independently from each layer's hidden state: layer differences come from different query viewsq = self.q_proj(x)out = causal_attention(q, k, v) # with causal maskreturn self.ffn(self.norm(out + x))
Three easily overlooked implementation details matter:
- Causality and positional consistency: K and V written by the lead layer already include positional encoding, and all layers in the group share the same positional coordinate system. Therefore, the whole model must use a unified positional encoding scheme before reuse is possible. If different position biases are applied alternately across layers, direct cross-layer sharing is not feasible.
- Cache management must be group-aligned: when using paged GPU memory management, pages should be allocated and reclaimed at the group level. For prefix caching, hit decisions should also be made by group. Any strategy that prunes or evicts old tokens layer by layer independently would break intra-group consistency.
- Training and inference must be structurally aligned: the model’s attention topology must strictly match the cache implementation of the target inference engine. Otherwise, the numerical path in training and inference will diverge, causing noticeable fluctuations in production behavior.
3. MoE vs Dense: Trade-offs Between Two Architecture Routes
3.1 MoE: compute economics of sparse activation
Beyond on-device models, newer mainstream model families often split into Mixture-of-Experts and Dense variants. MoE uses a lightweight router to select a small subset of experts for each token. The model can have a large total parameter count, while the actual computation for a single token corresponds only to part of the model.
Its main advantage is the decoupling of parameter capacity from compute cost. Under the same compute budget, MoE can hold more “knowledge capacity” and often performs better on knowledge-intensive and reasoning tasks.
The costs are also clear:
- Memory: during inference, all expert weights must remain resident, so memory demand approaches the total parameter count;
- Communication: when experts are spread across devices, additional routing communication overhead is required;
- Load balancing: routing collapse can occur during training, where a few experts are overused; load-balancing loss and capacity factors are commonly used as mitigations.
3.2 Why post-training is harder
MoE models are generally harder to post-train and tune. Mechanically, there are four main reasons:
- Sparse gradients: each token activates only a few experts, so many parameters receive no gradient during a single update. With small-batch or low-learning-rate fine-tuning, effective parameter updates are insufficient, and larger batches or more steps are needed to match Dense models.
- Limited parameter-efficient fine-tuning coverage: methods such as low-rank adaptation usually target projection matrices in attention and shared feed-forward layers, while MoE models have many dispersed expert layers. Adapting every expert significantly increases the number of trainable parameters, while partial adaptation leaves many parameters untouched.
- Instability during alignment: reinforcement-learning alignment is sensitive to the initial policy and reward signal. Sparse routing increases variance in policy updates, and once the routing distribution drifts, training can oscillate.
- Complex distillation paths: when a MoE model is the teacher, a Dense student can only observe outputs from activated experts, resulting in incomplete knowledge coverage.
3.3 Dense: predictable engineering certainty
In a Dense variant, all parameters participate in computation for every token. At the same total parameter count, its compute cost is significantly higher than MoE, but its engineering properties are friendlier:
- Memory usage matches the active parameter count, making capacity planning straightforward;
- Post-training pipelines such as fine-tuning, quantization, pruning, and distillation are mature;
- Behavior is predictable, which makes staged rollouts and regression testing easier.
Therefore, teams that prioritize high-quality outputs, frequent domain post-training, or deployment certainty often prefer Dense variants.
3.4 Selection comparison
| Dimension | MoE | Dense |
|---|---|---|
| Compute per token | Low | High |
| Inference memory | Close to total parameter count | Close to parameter count; more controllable |
| Post-training difficulty | Higher | Lower |
| Fine-tuning coverage | Limited by sparse routing | Comprehensive |
| Deployment complexity | Higher | Lower |
4. Inference Engineering Practice: Six Levers for KV Cache Optimization
Cross-layer sharing is only one part of KV Cache optimization. In real deployments, the following techniques are often combined:
- Grouped-query attention: reduce the number of KV heads during training to shrink per-layer cache from the source.
- Window and hybrid attention: use sliding-window attention in some layers and retain global attention in a few layers, balancing local efficiency and long-range modeling.
- Paged memory management: split KV Cache into fixed-size blocks allocated on demand, reducing fragmentation and supporting mixed scheduling of requests with different lengths.
- KV Cache quantization: compress K and V to 8-bit or lower precision, reducing memory usage by roughly half or more, while evaluating accuracy impact.
- Prefix cache reuse: use a hash of input token sequences as the key to reuse common prefixes such as system prompts, long documents, and few-shot examples across requests.
- Prefill/decode separation: schedule compute-intensive prefill and memory-bandwidth-intensive decode onto different resource pools, optimizing time to first token and throughput separately.
# Illustrative code: keys and hit logic for paged KV cache (pseudo-code)PAGE_SIZE = 16 # number of tokens per page; must match the target inference frameworkdef prefix_cache_lookup(cached_pages: dict, tokens, model_tag: str) -> int:"""Returns the number of complete reusable pages; the tail shorter than one page is not cached to avoid partial-hit boundary issues."""full_pages = len(tokens) // PAGE_SIZEmatched = 0for i in range(full_pages):# Cache key includes model version, shared-group configuration, and position informationkey = (model_tag, i, hash(tokens[i * PAGE_SIZE:(i + 1) * PAGE_SIZE]))if key not in cached_pages:breakmatched += 1return matched * PAGE_SIZE # number of matched tokens; always an integer multiple of page size
The cache key must include model version identifier, architecture configuration, and position information. Otherwise, cross-version reuse may return incorrect K and V, which is the most error-prone part of prefix caching.
5. Capacity Estimation: Including KV Cache in Resource Planning
During model selection, it is recommended to treat KV Cache as an explicit variable in the capacity model:
KV memory per request = 2 × effective cached layers × H_kv × d_head × b × context lengthMaximum concurrency ≈ (GPU memory - model weights - runtime overhead) / KV memory per request
Here, effective cached layers is a key parameter. After cross-layer sharing, it is roughly the number of shared groups, each retaining one lead layer’s cache, plus any non-shared layers. This is usually much smaller than the total number of layers, so the number of concurrent requests a single GPU can support increases accordingly.
Two types of memory should also be distinguished: MoE weights that remain resident in GPU memory reduce available headroom, while Dense model KV Cache is more dependent on memory bandwidth. In capacity planning, teams should measure prefill latency, decode latency, and peak memory usage separately rather than looking only at average throughput.
6. Selection Recommendations and Launch Checklist
6.1 Match architecture to scenario
- On-device and embedded systems: prefer small models that support cross-layer KV sharing, combined with 4-bit weight quantization and window attention. Focus on memory peak and thermal control during long conversations.
- Local efficient inference: when memory allows, MoE may offer a better quality-to-compute ratio; when memory is constrained, choose a smaller Dense variant and accept higher compute overhead.
- Cloud high-concurrency serving: choose the route based on whether frequent post-training is required. Use Dense for frequent fine-tuning; choose MoE for maximum quality per unit of compute; use prefill/decode separation and prefix caching to improve utilization.
6.2 Pre-launch checklist
- Numerical consistency: compare shared and full-cache implementations on identical inputs and confirm that output distributions differ within acceptable bounds.
- Accuracy evaluation: go beyond perplexity and add task-based evaluations such as long-context retrieval and multi-hop reasoning.
- Capacity stress testing: run concurrency tests using context lengths close to business limits, recording peak memory usage and time to first token.
- Cache key design: ensure prefix cache keys include version and position information to prevent cross-request contamination.
- Cache management alignment: confirm quantization, swapping, and paging operations are executed at the shared-group granularity.
- Observability: set up monitoring and alerting for KV Cache hit rate, memory usage, and latency percentiles to detect anomalies quickly.
7. Trend Outlook
Recent architecture changes suggest several directions in LLM design:
- Inference efficiency is moved earlier into design: KV Cache compression methods are incorporated during model design rather than optimized only after deployment;
- Route differentiation: on-device models pursue extreme cache efficiency, while cloud models pursue sparsification and maximum quality; the two tracks evolve separately;
- Post-training capability becomes an architecture metric: whether a model can be efficiently fine-tuned, aligned, and distilled is becoming as important as perplexity;
- Cloud-side engineering support: these optimizations ultimately depend on deployment infrastructure. For example, cloud platforms such as Baidu AI Cloud can provide model serving, containerized inference, and monitoring/alerting capabilities, allowing teams to focus on model selection and parameter tuning while platform solutions handle GPU memory management, elasticity, and observability.
For developers, understanding KV Cache reuse mechanisms and the trade-off logic between MoE and Dense models is more valuable than memorizing a specific model name: the former determines how long a context you can push the model to, and the latter determines how well you can achieve quality at a lower cost.
