KV Cache Optimization and LLM Architecture Evolution: A Deep Dive into Cross-Layer KV Reuse and Dense vs. MoE

    This article explains why KV Cache has become the dominant bottleneck in long-context LLM inference. It breaks down how KV caching works, presents an approximation of its memory footprint, and shows which factors drive that footprint. The article then examines cross-layer KV reuse as a key optimization technique, including its benefits, its potential quality tradeoff, and illustrative pseudocode. It also compares Dense and MoE architectures for inference efficiency and post-training complexity, outlines a three-tier model strategy from edge devices to the cloud, and closes with practical guidance on quantization, selective KV reuse, architecture selection, cloud infrastructure, and evaluation.

    1. Introduction: Long Context Is Redefining the Inference Bottleneck

    Over the past two years, the competition in large language models has gradually shifted from “parameter count” to “context length.” From a few thousand tokens to hundreds of thousands or even millions of tokens, long-context capability has become a core requirement for document understanding, codebase analysis, multi-turn agent interactions, and similar use cases.

    However, as sequence length keeps growing, what truly constrains inference performance is often no longer the number of model parameters, but an easily overlooked component: the KV Cache.

    Understanding and optimizing the KV Cache has become essential knowledge for putting large models into production. This article starts from the caching mechanism, systematically reviews key optimization approaches led by “cross-layer KV reuse,” and combines these with the two mainstream model architecture families in use today to offer technology selection guidance and practical recommendations for different deployment scenarios.

    2. KV Cache: What It Is and Why It Is Expensive

    2.1 How It Works

    When a Transformer generates tokens autoregressively, every new token requires attention over “all preceding tokens.” If the Key and Value vectors of all historical tokens had to be recomputed at every step, the computational cost would grow quadratically with sequence length.

    The core idea of the KV Cache is to cache the already-computed Key and Value tensors at each layer. Subsequent tokens only need to compute their own Query and then perform attention against the cached historical K/V, turning repeated computation into one-time storage and reuse.

    This mechanism trades space for time: inference speed improves markedly, but the cost is a continuous accumulation of GPU memory usage.

    2.2 Where the Overhead Comes From

    The memory footprint of the KV Cache can be approximated as:

    1. KV_Cache_Size ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × batch_size × bytes_per_element

    The coefficient of 2 accounts for the two tensors, Key and Value. Several key points follow from this formula:

    • Proportional to the number of layers and the sequence length: more layers and longer context mean a larger cache;
    • Proportional to the concurrent batch size: in high-concurrency online serving, the amplification effect of batch_size is substantial;
    • Dependent on data precision: FP16/BF16 halves the footprint compared with FP32, and quantizing to INT8 compresses it further.

    Under the combination of long context and high concurrency, the KV Cache tends to consume most of the available GPU memory very quickly, directly limiting the concurrency and maximum context length that can be served, and becoming the decisive factor for throughput and cost.

    3. Key Optimization Approach #1: Cross-Layer KV Reuse

    3.1 The Core Observation

    Transformer layers show a high degree of semantic correlation when extracting features. Adjacent layers or layers at similar depths in particular often have highly similar Key/Value distributions. Since the redundancy across layers is obvious, a natural idea emerges: let later layers directly reuse KV tensors already computed by certain earlier layers, rather than having every layer compute and cache its own KV independently.

    This is the core idea behind what academia discusses as “cross-layer attention / cross-layer KV sharing (Cross-Layer Attention).” It is not a capability unique to any single vendor, but a general optimization direction widely studied across the industry.

    3.2 Benefits and Costs

    The benefits of cross-layer reuse are direct:

    • Lower memory usage: fewer layers need cached KV, which markedly relieves memory pressure in long-context scenarios;
    • Less computation: reused layers no longer need to recompute the K/V projections, reducing inference latency;
    • Higher concurrency: the freed memory can support larger batches or longer context windows.

    The cost is that reducing independent KV representations may cause a slight quality degradation. In engineering practice, therefore, the relationship between the “reuse ratio” and “quality preservation” needs to be balanced, and compensation can be applied through continued pre-training or fine-tuning.

    3.3 Illustrative Code

    The pseudocode below illustrates the difference between the “shared KV” and “independent KV” strategies to help clarify the implementation logic:

    1. class AttentionLayer:
    2. def __init__(self, share_kv_from=None):
    3. # share_kv_from: if specified, reuse KV from that layer instead of computing it separately
    4. self.share_kv_from = share_kv_from
    5. self.k_proj = None if share_kv_from else build_kv_projection("k")
    6. self.v_proj = None if share_kv_from else build_kv_projection("v")
    7. self.q_proj = build_q_projection()
    8. def forward(self, x, kv_cache_store):
    9. layer_id = self.layer_id
    10. # Reuse mode: fetch the KV cache of the designated layer directly
    11. if self.share_kv_from is not None:
    12. keys, values = kv_cache_store.get(self.share_kv_from)
    13. else:
    14. # Independent mode: compute and write to the cache
    15. keys = self.k_proj(x)
    16. values = self.v_proj(x)
    17. kv_cache_store.set(layer_id, keys, values)
    18. queries = self.q_proj(x)
    19. return scaled_dot_product_attention(queries, keys, values)

    It is worth emphasizing that this is only illustrative code meant to explain the mechanism. Specific interfaces and implementations differ considerably across frameworks.

    4. Key Optimization Approach #2: The Trade-Off Between Dense and MoE Architectures

    Beyond optimizing the KV Cache, the choice of model architecture itself has a profound impact on inference efficiency and deployment complexity. Current mainstream architectures fall into roughly two families.

    4.1 Dense Architecture

    In a Dense architecture, every token passes through all parameters. Its advantages are a simple structure, mature and stable training and post-training pipelines, and a well-developed toolchain for fine-tuning and quantization. It therefore remains the first choice for scenarios that prioritize the highest generation quality and easy post-training. Its drawback is that at equal quality levels, inference compute and memory overhead grow linearly with parameter count.

    4.2 MoE (Mixture of Experts) Architecture

    An MoE architecture uses a gating network to dynamically select a small number of expert networks to participate in the computation for each token, so that a “very large total parameter count” coexists with a “small number of activated parameters per token.” It offers clear advantages in inference efficiency and capacity scaling, and suits small-to-medium scale scenarios that pursue efficient local inference. Its costs, however, are higher training stability challenges, expert load balancing, and greater complexity in post-training and fine-tuning, which raises the tuning barrier.

    4.3 Selection Guidance

    • Pursuing ultimate quality and a maintainable post-training pipeline → prioritize Dense;
    • Pursuing inference throughput and resource efficiency → prioritize MoE;
    • The two are not mutually exclusive; the choice should be weighed against the business’s sensitivity to latency, cost, and quality.

    5. A Tiered Model Strategy for Deployment Scenarios

    A mature model portfolio typically offers tiered product forms for different hardware conditions, commonly in three tiers:

    1. Edge / embedded (e.g., IoT and mobile devices): emphasizes minimal memory and compute footprint, fitting the model onto resource-constrained devices through parameter compression, KV Cache sharing, and low-precision quantization;
    2. Efficient local inference: targets personal computers or single-GPU servers, using architectures such as MoE to deliver higher capability under limited resources;
    3. High-quality general-purpose scenarios: adopts Dense architectures to pursue peak capability, serving complex tasks that are most sensitive to quality.

    This approach of “tiering plus differentiated optimization” is essentially about making different techniques serve different constraint boundaries, rather than expecting a single model to cover everything.

    6. Practical Recommendations: Building a Deployable Inference Optimization System

    Combining the techniques above into engineering practice yields the following optimization path:

    • Quantization first: prioritize INT8/low-precision weight quantization to compress the KV Cache; this offers the best return on investment;
    • Reuse on demand: introduce cross-layer KV reuse in long-context scenarios, but quantify quality degradation with an evaluation set to determine an appropriate reuse ratio;
    • Match architecture to the scenario: choose between Dense and MoE in line with latency, concurrency, and quality goals and business needs;
    • Leverage general-purpose cloud capabilities: in cloud deployments, model weights can be hosted on object storage, request spikes smoothed with message queues, container platforms used for elastic scaling, and logging plus monitoring and alerting services used to observe cache hit rates and memory utilization, forming a complete observability and elasticity system;
    • Maintain a continuous evaluation loop: any optimization (quantization, reuse, architecture changes) should establish a four-dimensional evaluation baseline of “quality–latency–memory–cost” to avoid fixing one aspect at the expense of another.

    7. Conclusion

    The competition in long-context inference ultimately comes down to “how to use every computation and every bit of memory efficiently under limited resources.” As the key bottleneck of long-sequence inference, the KV Cache and its optimization techniques—especially cross-layer KV reuse—are becoming an important direction of architectural evolution. Meanwhile, the divide between Dense and MoE, together with the tiered strategy from edge to cloud, collectively form the technical landscape of modern large-model deployment.

    For developers, understanding these underlying mechanisms, building a scientific evaluation loop, and making good use of general-purpose cloud infrastructure is what makes it possible to find the optimal solution among quality, performance, and cost for one’s own business.