ERNIE Model Architecture Evolution: The Engineering Cost of KV Cache Reuse
This article uses KV cache reuse as a lens to examine recent shifts in large language model architecture and the engineering tradeoffs behind long-context inference. It quantifies how KV cache memory scales with layer count, KV heads, sequence length, and batch size, explains why decoding is memory-bandwidth bound while prefilling is compute bound, and walks through five KV cache optimization routes — reducing KV heads (MHA to MQA/GQA), cross-layer KV reuse, low-rank compression, KV quantization, and sparse eviction — plus system-level techniques such as paged KV management and prefix sharing. It then contrasts mixture-of-experts (MoE) and dense architectures across training, inference, and post-training, explains why on-device models are especially sensitive to KV cache cost, and closes with a reproducible evaluation checklist, common misconceptions, and a decision matrix for matching architecture choices to deployment conditions.
1. Introduction: The Center of Architectural Innovation Has Shifted
Over the past two years, competition among large language models centered on parameter count and training data. After 2025, open-weight model series began iterating noticeably faster, and changes at the architecture level shifted from “piling on parameters” to “sweating the details”: how attention heads are organized, where the key-value cache is stored, the ratio of expert layers to dense layers, and the placement of normalization and positional encoding — all of these have been reworked and refined again.
A recent and fairly typical iteration came from one open-weight model series. That series split its product line into three tiers: ultra-small models for edge and embedded devices, mixture-of-experts models for efficient local inference, and dense models for quality-first scenarios. One change in a small-size version drew particular attention: later layers directly reuse the Key-Value tensors already computed by earlier layers, shrinking the KV cache. The idea isn’t new — academia had studied cross-layer attention sharing before — but this was the first time it appeared as a “default architecture” in a widely used open-weight series, so its signal value outweighs its novelty.
This article doesn’t evaluate any specific product. Instead, it abstracts this class of architectural change into a set of reusable engineering questions:
- Why the KV cache becomes the main cost of long-context inference, and how to account for it at the selection stage;
- The applicable boundaries and costs of cross-layer reuse, low-rank compression, KV quantization, and sparse eviction;
- How mixture-of-experts and dense architectures differ across training, inference, and post-training;
- Why on-device models are especially sensitive to the KV cache;
- How to design a reproducible evaluation and avoid being misled by “good-looking” architectures.
2. Do the Math First: How Much Does the KV Cache Actually Cost
Any architectural discussion that doesn’t come down to numbers turns into a pile of jargon. Start with the most commonly used estimate.
2.1 Quantifying Memory Usage
During autoregressive decoding, every layer caches the Key and Value tensors of past tokens. The memory footprint can be approximated as:
KV_bytes ≈ 2 (K and V) × L (layers) × H_kv (KV heads) × d_head × S (sequence length) × B (batch) × bytes_per_element
Writing it as a function makes quick estimates easy under a concrete model configuration:
def kv_cache_bytes(n_layers, n_kv_heads, head_dim,seq_len, batch=1, bytes_per_elem=2):"""bytes_per_elem: 2 for fp16/bf16, 1 for int8, 1 for fp8"""per_token_per_layer = 2 * n_kv_heads * head_dim * bytes_per_elemreturn per_token_per_layer * n_layers * seq_len * batch# Example: 32 layers, 4 KV heads shared per query group, head_dim=128print(kv_cache_bytes(32, 4, 128, seq_len=131072) / 1024**2, "MiB")
This formula explains several recurring phenomena:
- The KV cache and the weights are two separate memory budgets. Weights are static, quantizable, and shareable; the KV cache grows linearly with concurrency and context, and must stay at inference precision. A 30B-class model’s weights might take only a dozen GB or so after 4-bit quantization, but under long-context scenarios the KV cache can easily exceed the weights themselves.
- The number of layers is a multiplier. This is also the mathematical reason cross-layer reuse works: if only one layer out of every k produces KV and the rest borrow it, the total KV cache theoretically drops to roughly 1/k.
- The number of KV heads is another multiplier. Going from multi-head attention (MHA) to multi-query attention (MQA) and then to grouped-query attention (GQA) is essentially compressing H_kv from n_heads down to 1 or some intermediate value.
- Batch and sequence length are multiplicative. In serving scenarios, throughput gains usually come from higher concurrency, and concurrency inflates the KV cache faster than it inflates compute demand — so the system hits the memory wall first.
2.2 The Bandwidth Ledger: Decoding Is Memory-Bound
The prefill stage is compute-bound: it processes the entire prompt at once, the arithmetic intensity of the matrix multiplications is high, and the GPU’s compute can be fully utilized. Decoding is completely different — for each generated token, it must read all historical KV from memory, while the computation is just one vector-matrix multiplication. The bottleneck here is memory bandwidth, not compute.
This leads to two conclusions:
- The direct payoff of a smaller KV cache shows up in TPOT (time per output token), not just in “saving memory.” Read less, wait less.
- Prefill’s TTFT (time to first token) won’t necessarily improve in tandem. Cross-layer reuse cuts KV storage and reads, but the main prefill costs — Q/K/V projections, attention computation — remain. Expecting a single architectural change to compress both TTFT and TPOT at once is usually unrealistic.
2.3 An Easily Overlooked Quantity: Arithmetic Intensity
Divide the bytes read per generated token by the number of floating-point operations, and you get arithmetic intensity. Roughly speaking, weight reads are fixed at “parameter count × bytes,” while KV reads grow linearly with context. The longer the context, the higher the KV share of total reads, the lower the arithmetic intensity, and the worse the hardware utilization. This explains why “long context” and “high inference cost” almost always appear together in practice — not a coincidence, but two expressions of the same physical constraint.
3. Five KV Cache Optimization Routes and Their Costs
The industry’s approaches to the KV cache can be grouped into five categories. They stack with one another, but each has a clear boundary of applicability.
3.1 Reducing KV Heads: MHA → MQA → GQA
The most classic move. In MHA, every query head has its own K/V head; MQA lets all query heads share a single set of K/V; GQA is a compromise that splits query heads into several groups that share within each group.
- Benefits: The KV cache drops proportionally, and decode-phase bandwidth pressure drops in step; simple to implement, broadly supported by inference frameworks.
- Costs: Some loss of expressive power; the group count must be decided at the pretraining stage, and changing it afterward loses quality. Too few groups hurt quality; too many limit the gains.
- Applicability: The default configuration of nearly all modern open-weight models.
3.2 Cross-Layer KV Reuse: A Structural Saving
The approach: within a group of several adjacent layers, only one layer (the producer) computes and writes K/V, while the other layers in the group read this tensor directly for attention.
- Benefits: Compared to GQA, this cuts on “layers” in addition to “head count,” so the two multipliers stack; it doesn’t change the attention operator shape of a single layer, so the changes to the inference framework stay relatively contained; what it saves is memory and bandwidth, without adding decode-phase compute.
- Costs: The representations each layer originally learned differ, so forcing sharing weakens inter-layer expressive power; training needs the corresponding structural prior or alignment, otherwise long-context retrieval tasks easily lose quality; the producer layer’s output becomes a shared bottleneck for all layers in the group — once that layer’s representation quality is poor, the error propagates through the group.
- Key detail: Producer layers are usually selected uniformly, but can also be placed toward the front of the group; if layers within a group have different KV head counts, a linear mapping layer is needed for alignment; the phase of positional encoding (especially rotary positional encoding) must be consistent, otherwise the reused K vectors are geometrically misaligned — this is the most common source of bugs in implementation.
A sketch implementation to help understand what “sharing” actually changes in code:
import torchimport torch.nn as nnclass SharedKVCache:"""Group-level shared KV cache: each group keeps only one copy of K/V."""def __init__(self, n_groups, n_kv_heads, head_dim,max_len, dtype=torch.float16, device="cuda"):self.k = torch.zeros(n_groups, max_len, n_kv_heads, head_dim,dtype=dtype, device=device)self.v = torch.zeros_like(self.k)self.len = 0def append(self, k_new, v_new):t = k_new.size(1)# Write the whole chunk during training/prefill; write one token at a time during decodingself.k[:, self.len:self.len + t] = k_newself.v[:, self.len:self.len + t] = v_newself.len += treturn self.k[:, :self.len], self.v[:, :self.len]class AttentionLayer(nn.Module):"""The first layer in a group is the producer; the rest reuse upstream K/V."""def __init__(self, dim, n_q_heads, n_kv_heads, head_dim,group_idx, is_producer):super().__init__()self.is_producer = is_producerself.group_idx = group_idxself.n_q_heads = n_q_headsself.n_kv_heads = n_kv_headsself.head_dim = head_dimself.q_proj = nn.Linear(dim, n_q_heads * head_dim, bias=False)# Only the producer needs K/V projectionsif is_producer:self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)self.o_proj = nn.Linear(n_q_heads * head_dim, dim, bias=False)def forward(self, x, cache, group_size):b, s, _ = x.shapeq = self.q_proj(x).view(b, s, self.n_q_heads, self.head_dim)if self.is_producer:k = self.k_proj(x).view(b, s, self.n_kv_heads, self.head_dim)v = self.v_proj(x).view(b, s, self.n_kv_heads, self.head_dim)k_all, v_all = cache.append(k, v)else:# Key line: don't compute its own K/V, read the group's cache directlyk_all, v_all = cache.k[self.group_idx], cache.v[self.group_idx]k_all, v_all = k_all[:, :cache.len], v_all[:, :cache.len]out = self._attend(q, k_all, v_all) # GQA head grouping happens internallyreturn self.o_proj(out.reshape(b, s, -1))def _attend(self, q, k, v):# Sketch: a real implementation must handle causal masking, RoPE, and the mapping between KV heads and Q headsscale = self.head_dim ** -0.5scores = torch.einsum("bshd,bthd->bhst", q, k) * scalemask = torch.ones(scores.size(-1), device=q.device).tril()scores = scores.masked_fill(mask == 0, float("-inf"))attn = scores.softmax(dim=-1)return torch.einsum("bhst,bthd->bshd", attn, v)
It’s worth stressing that how the “groups” are divided is itself a design variable: uniform grouping by layer, non-uniform grouping by depth, or even letting only some layers participate in reuse all lead to different quality-cost curves. These choices can’t be judged by intuition; they must be verified by evaluation.
3.3 Low-Rank Compression: Projecting KV into a Low-Dimensional Latent Space
Another approach projects K/V into a low-dimensional latent vector far smaller than n_kv_heads × head_dim, caches the latent vector, and projects it back up to full dimension during attention.
- Benefits: The compression ratio can be aggressive, and the compression is “continuous” — you can pick any latent dimension rather than being limited by integer division of head counts.
- Costs: Each attention requires two extra up-projection matrix multiplications, increasing decode-phase compute; high implementation complexity — a custom kernel is needed to realize the theoretical gains; the choice of latent dimension must be coordinated with training.
- Applicability: Scenarios chasing extreme long context that are willing to invest in kernel engineering.
3.4 KV Quantization: Keeping the Structure, Changing Only Precision
Compressing cached K/V from fp16 to fp8 or int8/int4.
- Benefits: The smallest change, nearly orthogonal to any architecture, usually just a configuration on the inference side.
- Costs: There’s precision loss, and layer sensitivity varies widely — some layers’ K distributions have long-tail outliers, and quantizing them directly loses significant quality, requiring per-layer, per-channel mixed-precision strategies or smoothing.
- Note: What’s quantized is the cache, not the weights. They are two independent precision strategies and can be configured separately.
3.5 Sparsity and Eviction: Keeping Only the “Important” Tokens
This includes sliding-window local attention, hybrids of global tokens plus local windows, KV eviction based on attention scores, and block-sparse attention computation.
- Benefits: Memory usage can be pushed down to constant or sublinear levels, sharply lowering the marginal cost of long context.
- Costs: Information that needs to be precisely remembered may get evicted. In practice, the “normal at short context, suddenly can’t find the key fragment at long context” phenomenon often has its root cause here.
- Compromise: Keep a few global tokens (the first few tokens often serve as “attention sinks,” and evicting them is costly), and cover the rest with a window.
3.6 At the System Level: Paged Management and Prefix Sharing
The previous five all change the model; there’s another class of changes at the inference system level:
- Paged KV management: Split the KV cache into fixed-size blocks, allocated on demand, reducing fragmentation and reserved waste and markedly improving memory utilization.
- Prefix sharing: For multi-turn conversations, few-shot prompts, and shared system prompts, the common prefix’s KV is computed once and reused across requests. This is the most cost-effective optimization in conversational workloads, and it’s fully decoupled from the model architecture.
- Tiered storage: Swap inactive KV blocks out to host memory or even local storage, at the cost of swap-in/swap-out latency.
4. Mixture of Experts vs. Dense: More Than a Parameter-Count Contest
The second dividing line worth expanding on is MoE vs. Dense.
4.1 The Essential Difference
MoE splits the feed-forward layer into multiple “experts,” and each token activates only its top-k. This decouples the model’s total parameter count from the activated parameter count per token: you can have a very large total parameter count while computing only a small fraction per forward pass.
A dense model does a full matrix multiplication for every token in every layer, so parameter count is proportional to compute.
4.2 Differences on the Inference Side
| Dimension | Dense | Mixture of Experts (MoE) |
|---|---|---|
| Compute | Proportional to total parameters | Only the activated part; small per-token compute |
| Memory usage | Proportional to total parameters | Must hold all experts; large memory footprint |
| Bandwidth pressure | Fixed weight reads | Weight reads = total parameters (experts must be read in); few activated parameters ≠ few reads |
| Batch-friendliness | Good, fixed shapes | Routing makes the token count per expert vary, requiring capacity factors and padding; long-tail experts slow down the whole |
| Distributed deployment | Tensor parallelism suffices | Often needs expert parallelism, introducing all-to-all communication, sensitive to the network |
| Quantization | Mature, many granularity choices | Expert-layer quantization is more sensitive; routing logits’ numerical stability needs separate protection |
The most easily misread column in the table above is “bandwidth.” MoE’s compute advantage comes from “computing less,” but all experts still have to reside in memory; during decoding, every token must read the activated experts’ weights, and the total read depends on the activation pattern — you can’t keep the weights resident in a cache-friendly layout the way a dense model can. So on memory-bandwidth-limited edge devices, MoE’s theoretical advantage often fails to materialize.
4.3 Differences on the Training and Post-Training Side
This is often underestimated at the selection stage. A dense model has a deterministic gradient path: every parameter receives a gradient every step, the training curve is smooth, and hyperparameter transfer is good; the post-training toolchain (instruction fine-tuning, preference alignment, distillation, quantization-aware training) is mature, and a small team can produce a usable custom model with just a few dozen examples.
MoE’s difficulties lie in:
- Load balancing. Routing tends to collapse onto a few experts, requiring auxiliary losses or lossless balancing strategies to constrain it; the balancing strength is itself a knob to tune — too tight hurts quality, too loose hurts efficiency.
- Sparse gradients. Experts not activated in a given step receive no gradient, effectively shrinking the batch and increasing training noise.
- Post-training coupling. If fine-tuning shifts the data distribution, the routing distribution shifts too, potentially pushing many tokens toward experts that were under-trained originally, producing the “worse after fine-tuning” phenomenon.
- Distillation. Distilling an MoE into a small dense model is common, but the teacher’s “multi-expert voting” characteristic is hard for a single model to fully absorb.
4.4 Selection Advice
- Chasing a single model’s quality ceiling, with mature distributed inference infrastructure → MoE is worth considering.
- Needing frequent domain post-training, small-team maintainability, or edge/multi-device deployment → A dense model’s total cost of ownership is usually lower.
- Edge/embedded → Dense-dominant. With memory capacity, memory bandwidth, and operator coverage all constrained at once, MoE’s routing and gather operations have limited support on most edge inference runtimes, and the sparse memory-access pattern of expert weights is unfriendly to edge memory controllers.
- A pragmatic approach: Use a mid-size dense model as the workhorse, put a large MoE model on the server to handle hard requests, and split traffic through a routing layer. This essentially turns the “which model” problem into a “which architecture” problem.
5. Why On-Device Models Are Especially Sensitive to the KV Cache
Ultra-small models (usually under a billion parameters, some as low as a few hundred million) are willing to make aggressive architectural tradeoffs because on-device constraints differ structurally from the cloud side:
- Memory is a hard ceiling. A phone or embedded device often has only a few GB of usable memory, shared with apps and the system. Weights, KV cache, and transient tensors all squeeze into the same budget.
- Bandwidth is the main bottleneck. On-device memory bandwidth is typically one to two orders of magnitude lower than a data-center GPU’s, pushing the memory-bound nature of decoding to the extreme.
- Limited operator coverage. On-device inference runtimes support custom operators far less than server-side ones; any architecture needing a custom kernel (like a low-rank compression’s up-projection) may be impossible to deploy, or degrade to a slow generic implementation.
- Sustained power and thermal limits. In the cloud you can trade cards for time; on-device, generating a few hundred tokens in a row can trigger throttling.
- More concentrated context-length use cases. Typical on-device usage is document Q&A, long-conversation memory, and code completion — context lengths are often not short, but batch is always 1, so there’s no concurrency to amortize the KV cache cost, and every unit of cache is its own burden.
Under these constraints, “cross-layer KV reuse + fewer KV heads + 4-bit weight quantization + a moderate context window” is a reasonable combination. Its logic isn’t “most advanced,” but “spending every byte wisely under the leanest budget.”
6. Additional Topics in the Long-Context Era
Beyond the KV cache, several architectural changes belong in the same picture.
Hybrid local and global attention. Not every layer needs to see the full sequence. A common practice is to let most layers use a sliding window and a few layers keep global vision, responsible for cross-segment semantic integration. This can pair with KV eviction to push memory usage down to near-constant levels.
Positional-encoding extrapolation. Context-length extension mostly relies on length extrapolation during training (adjusting the base frequency of rotary positional encoding, adding position interpolation) and can’t be remedied at inference time. This also explains why “the model supports 128K context” and “the model is actually usable at 128K context” are two different things.
The position of normalization. In the past two years, schemes have appeared that move normalization inside the attention and FFN branches (the so-called QK-Norm family), aiming to keep the residual path an identity mapping and improve deep-training stability and inference numerics. Such changes affect compatibility with older frameworks — watch out when upgrading the inference runtime.
Numerical stability of attention. Under long context, the dynamic range of attention scores grows, and fp16 easily overflows; bf16 or a chunked-softmax online-normalization implementation is more robust. This is a consideration that pairs with KV quantization.
7. How to Evaluate: A Reproducible Checklist
The easiest trap in architectural changes is “paper gains, no felt improvement in practice” or “average score unchanged, long-tail tasks collapse.” It’s recommended to build a minimal evaluation set along the lines below.
Metrics you must test
- Memory curve: Fix batch=1, sweep context length 1K → 4K → 16K → 64K → 128K, record KV cache usage and peak memory, and verify the decrease really is linear.
- Measure TTFT and TPOT separately: They’re affected by different factors, and merging them into a single “average latency” masks problems.
- Long-context retrieval: Needle-in-a-haystack tests, burying key information at the beginning, middle, and end and testing each. The degradation of cross-layer reuse and KV eviction usually appears first at the “middle position.”
- Multi-hop reasoning: Combining two pieces of information across a long distance is most sensitive to KV fidelity.
- Batch throughput: Increase concurrency from 1 to 32/64 and observe whether throughput grows linearly and at which tier it hits the memory wall.
- Post-quantization regression: Test the three combinations — “weight quantization + no KV quantization,” “KV quantization + no weight quantization,” and “both quantized” — separately, to avoid attributing the two kinds of loss together.
A minimal load-test skeleton (depends only on the standard library, avoiding binding to any specific client):
import jsonimport timeimport urllib.requestENDPOINT = "http://127.0.0.1:8000/v1/chat/completions" # point to your own inference servicedef measure(prompt, max_tokens=256):body = json.dumps({"messages": [{"role": "user", "content": prompt}],"max_tokens": max_tokens,"stream": True,}).encode()req = urllib.request.Request(ENDPOINT, data=body,headers={"Content-Type": "application/json"},)t_start = time.perf_counter()first_token_at = Nonen_tokens = 0with urllib.request.urlopen(req) as resp:for raw in resp:line = raw.decode().strip()if not line.startswith("data:"):continuepayload = line[5:].strip()if payload == "[DONE]":breakchunk = json.loads(payload)delta = chunk["choices"][0]["delta"].get("content")if delta:if first_token_at is None:first_token_at = time.perf_counter()n_tokens += 1total = time.perf_counter() - t_startttft = (first_token_at - t_start) if first_token_at else float("nan")decode_window = total - ttfttpot = decode_window / max(n_tokens - 1, 1) # time per output tokenreturn {"ttft": ttft, "tpot": tpot, "tokens": n_tokens}
Two reminders about the evaluation method itself
First, any single measurement needs a warm-up: the first few requests include operator compilation, memory allocation, and cache cold starts, and mixing them into the statistics skews results severely optimistic or pessimistic. Second, hardware and runtime versions must be fixed and fully recorded, or numbers from different batches can’t be compared side by side; for cross-machine reproduction, bringing the container-orchestration platform, model repository, and monitoring/alerting into version control is far more reliable than manual record-keeping.
8. Common Misconceptions
- “A small KV cache means fast inference.” Not true. Compressing the KV only improves memory usage and decode bandwidth; prefill’s compute cost is untouched.
- “More layers is always better; reuse doesn’t affect quality.” Inter-layer representation differences carry information; cross-layer reuse trades that information for memory and must be measured.
- “MoE activates fewer parameters, so it should be fast on-device too.” The weights still need to be fully resident, expert access is sparse and irregular, and it’s unfriendly to on-device memory controllers.
- “Supporting long context equals long context being usable.” Positional extrapolation, attention fidelity, and the KV eviction strategy together determine the actual effective length.
- “Quantization is a free lunch.” Layer quantization sensitivities can differ greatly — pay special attention to the numerical stability of attention scores and routing logits.
9. Selection Decision Checklist
Compressing the above analysis into an actionable decision table:
| Scenario | Priority consideration | Suggested direction |
|---|---|---|
| Edge / embedded | Tight memory and bandwidth, limited operators | Small dense model + few KV heads + cross-layer reuse + 4-bit weights |
| Single-machine local inference | Moderate memory, single user | Mid-size dense model + GQA + fp8 KV |
| High-concurrency online serving | Memory as the main constraint | Paged KV management + prefix sharing + tiered swapping |
| Long-document / codebase Q&A | Effective context length | Hybrid local+global attention + careful KV eviction |
| Quality-first, with distributed capability | Single-model ceiling | MoE + expert parallelism, accepting higher operational complexity |
| Frequent domain customization | Post-training cost | Dense model; mature toolchain, low regression risk |
10. Conclusion
Spread out this latest round of architectural iteration, and the main threads are really just two.
The first is that the memory-and-bandwidth ledger is being calculated more and more finely. From reducing KV heads, to cross-layer reuse, to low-rank compression, quantization, and sparse eviction — all are searching for new dimensions of compression under the same constraint. These changes share a common trait: gains are quantifiable, costs are locatable, and they must be verified by long-context and multi-hop task measurements, not judged by how pretty the architecture diagram is.
The second is that the tradeoff between inference efficiency and post-training efficiency has been put on the table. MoE trades sparse activation for low per-token compute, at the cost of memory, communication, and post-training complexity; the dense model’s compute is linear, but its total cost across customization, distillation, quantization, and on-device deployment is lower. That one open-weight series offers three product lines — on-device small models, MoE, and Dense — is essentially telling users: there’s no universally optimal architecture, only architectures that match deployment conditions.
Practical advice for developers: first write down four numbers for your own scenario — context-length distribution, concurrency level, memory budget, and post-training frequency — then look at architectural features. Once the numbers are clear, the vast majority of architecture choices converge on their own.
