LLM Architecture Evolution: Shrinking KV Cache for Long-Context Serving

    As LLMs evolve toward long contexts, reasoning models, and agentic applications, reducing KV Cache has become a central theme in architecture design. This article explains why KV Cache is now the main memory-capacity bottleneck, breaks down the formula that governs its memory footprint, and surveys the mainstream techniques for shrinking it—grouped-query attention, cross-layer KV sharing, KV quantization, sliding-window attention, and cache eviction. It takes a closer look at cross-layer KV sharing (its principle, benefits, and tradeoffs), weighs dense versus mixture-of-experts (MoE) architectures, and outlines a scenario-based model matrix. It closes with the significance of KV Cache reduction for long-context and agentic workloads, plus practical engineering recommendations for inference-side optimization and quality guardrails.

    1. Why KV Cache Became a Central Architectural Concern

    The evolution of mainstream LLMs over the past period has followed a clear trajectory: finding ways to shrink the KV Cache. This is not a single-point optimization but an inevitable outcome driven jointly by long-context requirements, reasoning models, and agentic applications.

    To understand why, start with the basic mechanism of autoregressive generation. When a Transformer generates token by token, each step requires the Key and Value vectors of all preceding tokens. If every forward pass recomputed the keys and values for the entire history, the computation would grow quadratically with sequence length—completely unacceptable. That is why KV Cache is standard engineering practice: it stores the already-computed Keys and Values so subsequent steps can reuse them directly, avoiding redundant computation.

    The problem is that this cache is not free. It must remain resident in GPU memory, and its footprint grows linearly with context length and scales up with the number of concurrent requests. As a result, KV Cache has gradually shifted from a “performance optimization technique” to the primary source of the “GPU memory capacity bottleneck.”

    2. Where the KV Cache Memory Footprint Comes From

    In terms of magnitude, the size of the KV Cache can be roughly understood as:

    1. KV Cache memory ≈ 2 (key/value) × num_layers × sequence_length × hidden_dim × bytes_per_value × batch_size

    Here, the “2” represents the two tensors—Key and Value. This formula reveals several key amplification paths:

    • More layers and larger hidden dimensions make each token’s cache more expensive;
    • Longer contexts make the cache grow linearly with the sequence;
    • More concurrent requests multiply the total footprint;
    • Higher precision (e.g., FP16/BF16) doubles the byte count.

    This explains why, in scenarios pursuing ultra-long contexts and many concurrent requests, the KV Cache can quickly exhaust GPU memory, which in turn limits critical metrics such as “how long a context a single request can use” and “how many users a single GPU can serve simultaneously.” Shrinking the KV Cache essentially serves two goals at once: longer contexts and higher throughput.

    3. Mainstream Techniques for Shrinking KV Cache

    The industry has accumulated a set of fairly general approaches, which can be grouped roughly as follows and are often combined in practice:

    1. Multi-Query / Grouped-Query Attention (MQA/GQA)
      The core idea is to let multiple Query heads share the same group of Key-Value heads, compressing the KV copies from “one per head” to “one shared per group of heads.” This is currently a foundational technique for reducing cache footprint.

    2. Cross-layer sharing / cross-layer reuse (the focus of this article)
      Rather than having each subsequent layer compute its own full key-value states, later layers reuse Keys/Values already computed by earlier layers, cutting the cache scale along the layer dimension.

    3. Key-value quantization
      Compressing the cache from high precision (e.g., BF16) to a low-bit representation, trading precision for memory, usually paired with a small amount of error compensation.

    4. Sliding window and local attention
      Keeping only the keys and values within a recent window, exploiting the observation that attention in ultra-long contexts actually focuses on a limited region.

    5. Cache eviction / sparsification strategies
      Discarding the keys and values of some historical tokens by importance when memory is tight, trading a controllable quality loss for capacity.

    4. Cross-Layer KV Sharing: Principle, Benefits, and Costs

    Among these approaches, one direction worth particular attention recently is cross-layer KV Tensor reuse—letting subsequent layers directly reference the key-value tensors computed by earlier layers instead of recomputing them.

    The basic idea can be expressed with the following illustrative code:

    1. class LayerWithKVSharing(nn.Module):
    2. def __init__(self, kv_provider_index=None):
    3. super().__init__()
    4. # If not None, this layer does not recompute KV
    5. # but reuses the result from the specified layer
    6. self.kv_provider_index = kv_provider_index
    7. self.layer_index = None # populated at runtime
    8. def forward(self, x, kv_cache):
    9. q = self.compute_query(x)
    10. if self.kv_provider_index is not None:
    11. # Cross-layer reuse: directly take the upstream layer's cached Key/Value
    12. k, v = kv_cache[self.kv_provider_index]
    13. else:
    14. # This layer acts as a provider: compute and write to the cache
    15. k, v = self.compute_kv(x)
    16. kv_cache[self.layer_index] = (k, v)
    17. return self.attention(q, k, v)

    Why does it work? Intuitively, adjacent layers are highly correlated in representation space, and a later layer’s attention can to a large extent “borrow” the key-value information already built by an earlier layer. By having multiple layers share the same KV, the model saves a large amount of redundant cache along the layer dimension, significantly lowering both GPU memory usage and memory-access cost under long contexts. This idea has long been explored in academia (for example, in research around “cross-layer attention”), but its real significance is that it has now been deployed at scale in mainstream open-source architectures—demonstrating its feasibility in industrial-grade models, not just feasibility on paper.

    What is the cost? There is no free lunch. The main tradeoffs introduced by cross-layer sharing are:

    • Potentially limited expressiveness: forcing later layers to reuse upstream keys and values effectively constrains the degrees of freedom of attention, which may cause a slight quality degradation on some tasks;
    • Higher training-stability and tuning cost: the shared structure alters gradient paths, so training and post-training stages require more careful tuning;
    • Increased inference implementation complexity: how the cache is organized and how layers depend on each other must be handled at the kernel and scheduling levels, raising the bar for engineering implementation.

    For this reason, cross-layer sharing is usually not a blanket “reuse across all layers,” but a selective design where some layers reuse while others compute independently—seeking a balance between capacity and quality.

    5. Architecture-Level Tradeoffs: Dense vs. Mixture-of-Experts

    Alongside the KV Cache discussion, another notable divergence in recent model architecture is the competition between dense architectures and Mixture-of-Experts (MoE) architectures. The two make different tradeoffs in inference efficiency and post-training friendliness, and selection should be based on the specific scenario.

    Mixture-of-Experts (MoE) architecture uses a routing mechanism to activate only a subset of parameters for each token, thereby maintaining a low per-token computation cost while carrying a large total parameter count. Its advantages include:

    • Under the same compute budget, it can hold greater knowledge capacity;
    • Few activated parameters at inference time make per-token compute cost more controllable in principle.

    But its challenges are also clear:

    • Harder post-training and tuning: sparse activation from routing spreads gradient signals more thinly, so fine-tuning, alignment, and instruction tuning all require more careful engineering and data strategies;
    • Higher load-balancing and engineering complexity: uneven routing can overload certain experts, making distributed deployment and memory management more complex.

    Dense architecture, by contrast, routes every token through all parameters. Its characteristics are:

    • A more mature, controllable post-training pipeline, well suited for high-quality alignment and domain adaptation;
    • More predictable behavior, with a relatively simpler engineering and evaluation chain;
    • The cost is that, to reach an equivalent “quality” target, it often requires larger activated compute.

    6. A Layered, Scenario-Based Productization Approach

    Turning these technical judgments into practice, a common and reasonable approach is to design a model matrix layered by scenario, letting models of different scales and structures each do what they do best:

    • For on-device and small local devices: prioritize controlling GPU memory and power consumption, favoring small dense models and layering on cross-layer sharing, key-value compression, and other techniques to bring the long-context memory cost within what the device can bear;
    • For efficient local inference: the Mixture-of-Experts architecture can be used to pursue a balance of “large capacity, low activation” when compute is limited;
    • For high-quality generation and convenient post-training: favor dense architectures for a more stable, controllable fine-tuning and alignment experience.

    The core logic of this layered strategy is: there is no “optimal architecture,” only the “architecture combination that best fits the scenario.” On-device work demands extreme memory efficiency; efficient local inference must balance capacity against compute; high-quality generation prioritizes the controllability of post-training.

    7. Why It Matters for the Age of Agents and Reasoning Models

    Why is “shrinking the KV Cache” especially important today? Because the shape of applications has changed.

    • Long context is a hard requirement: understanding codebases, analyzing long documents, and accumulating multi-turn conversations all keep stretching the context window, and the memory bottleneck is precisely the direct ceiling on long context;
    • Reasoning models bring ultra-long chains of thought: reasoning-oriented models generate large amounts of intermediate reasoning, significantly lengthening sequences and further amplifying KV Cache growth;
    • Agentic scenarios emphasize multi-turn interaction and concurrency: a single agent often calls the model repeatedly over a long history, and many concurrent paths multiply the cache footprint.

    In these scenarios, slimming down the KV Cache is no longer a nice-to-have but a decisive factor in “whether it can run at all” and “whether it can be scaled to serve at scale.” Techniques such as cross-layer sharing, key-value compression, and sliding windows are clearing the path for long-context and agentic deployment.

    8. Practical Engineering Recommendations

    If you are working on inference-side optimization, you can consider the following:

    1. Quantify the bottleneck first: use the memory formula above to estimate the current KV Cache share and identify whether the “layer dimension,” “sequence dimension,” or “concurrency dimension” contributes the most;
    2. Start with foundational techniques: first enable mature, clearly beneficial, low-risk optimizations such as grouped/multi-query attention and key-value quantization;
    3. Then consider structural changes: structural schemes like cross-layer sharing involve model architecture, so they require evaluating quality degradation and pairing them with more thorough evaluation sets and post-training tuning;
    4. Combine with elastic infrastructure: general cloud capabilities such as horizontal scaling of inference services, elastic resource scheduling, monitoring and alerting, and log analysis (for example, containerized deployment, object storage for models and data, and monitoring services to observe memory and throughput) can significantly reduce the operational cost of scaling;
    5. Establish quality guardrails: any scheme that trades memory/latency for quality should have clear regression evaluation to prevent “running fast but answering poorly.”

    Conclusion

    The evolution of LLM architecture is shifting from “stacking parameters and layers” toward “finely managing every memory access and every portion of the cache.” Slimming down the KV Cache—especially structural optimizations like cross-layer key-value reuse—together with the tradeoffs between dense and mixture-of-experts architectures, jointly form the main theme of current architecture design. Understanding the tradeoff logic behind these mechanisms is what lets you choose a genuinely fitting technology combination for different business scenarios in the age of long context and agents.