Cross-Layer KV State Reuse: A New Paradigm for LLM Inference Memory Optimization

    This article explains why KV Cache has become the central memory bottleneck in long-context LLM inference, quantifies its memory footprint, and systematically reviews the four main optimization levers: intra-layer sharing (GQA/MQA), cross-layer KV sharing, KV quantization, and sliding-window/sparse attention. It also provides practical engineering guidance for deploying long-context inference services, including model selection, inference configuration, capacity planning, and platform observability.

    Cross-Layer KV State Reuse: The Evolution and Practice of KV Cache Optimization for LLM Inference

    Introduction: Why KV Cache Became the Core Bottleneck of the Inference Era

    Over the past year, the application patterns of large language models have changed dramatically: from single-turn Q&A to long-document understanding, multi-turn reasoning, and autonomous agents. These scenarios share a common trait—rapidly expanding context lengths. A single agent task often needs to carry system prompts, tool definitions, historical trajectories, and retrieved snippets, easily exceeding tens or even hundreds of thousands of tokens. During autoregressive decoding, every generated token requires the model to access the Key and Value tensors produced at every layer for all preceding tokens. These tensors are cached to avoid recomputation—this is the KV Cache.

    The problem is that KV Cache memory usage grows linearly with context length and is proportional to “number of layers × sequence length × number of heads × head dimension × data precision.” For a medium-sized dense model, at 32K context with a batch size of 1, the KV Cache alone can exceed the size of the model weights. As cache squeezes out memory, it directly limits the deployable context window, concurrent batch size, and hardware choices. This is exactly why “shrinking the KV Cache” has become a central theme in modern LLM architecture design.

    1. Quantifying KV Cache Memory Usage

    To understand the optimization strategies, let’s first do the math. For standard multi-head attention (MHA), the KV Cache size for a single sequence is:

    1. KV Cache (bytes) = 2 × L × S × H × D × P

    Here, 2 accounts for the separate Key and Value caches, L is the number of layers, S is the sequence length, H is the number of attention heads, D is the dimension per head, and P is the bytes per element (2 bytes for FP16, 1 byte for INT8).

    This formula directly reveals four optimization levers:

    1. Reduce the number of heads H: the GQA/MQA direction, where multiple query heads share KV heads;
    2. Reduce the number of layers L: the cross-layer sharing direction, where multiple layers reuse the same KV state;
    3. Reduce precision P: the KV quantization direction;
    4. Reduce the effective sequence length S: sliding windows, sparse attention, and cache eviction.

    Nearly all architectural evolution in the industry over the past two years has revolved around these four paths.

    2. Intra-Layer Sharing: From MHA to GQA and MQA

    Grouped Query Attention (GQA) is now the standard configuration of mainstream open-source architectures. Its core idea is to let several query heads share the same set of Key-Value heads: if a model has 32 query heads but retains only 8 KV heads, the head dimension of the KV Cache shrinks to one quarter of the original, saving 75% of memory. Its extreme form, MQA (Multi-Query Attention), keeps only a single KV head, achieving the highest compression ratio but with more noticeable degradation in model quality.

    GQA has been widely adopted because it hits the sweet spot between quality and cost: extensive experiments show that reducing the number of KV heads to 1/4 or even 1/8 of the query heads causes very limited degradation on downstream task metrics, while the inference memory and bandwidth gains are immediate. Moreover, a smaller KV Cache means less data read from memory at each decoding step, which—for memory-bandwidth-bound autoregressive decoding—translates directly into higher token throughput.

    However, GQA’s compression is powerless along the “layer” dimension—each layer still maintains its own independent KV state. When the model is deep and the context is extremely long, the layer count L remains a major item on the memory bill.

    3. Inter-Layer Sharing: Reusing KV Tensors Across Layers

    Cross-layer KV sharing (Cross-Layer Attention / Shared KV Cache) goes one step further by breaking through layer boundaries: several subsequent layers directly reuse the Key-Value tensors already computed by an earlier layer, instead of projecting and caching KV separately for each layer.

    A typical configuration is: divide the model layers into groups; the first layer in each group computes KV normally and writes it to the cache, while the remaining layers in the group read this shared cache during attention. If every 2 layers share once, the layer dimension of the KV Cache is halved; with a more aggressive sharing ratio (e.g., only 1/3 of layers hold independent KV), memory can be compressed by an order of magnitude. Academic research validated the feasibility of this direction long ago, but only recently has it been introduced at scale into mainstream open-weight models targeting edge and local deployment, significantly reducing memory and compute costs in long-context scenarios—particularly suitable for memory-constrained mobile devices and embedded environments.

    Its costs and engineering considerations should be clearly understood:

    • Quality trade-offs: Cross-layer sharing reduces the independent expressive capacity of each layer’s KV. It usually requires structural adjustments (such as interleaving global attention layers with shared layers) and sufficient pretraining to compensate, rather than simply being retrofitted onto existing models.
    • Simplified cache management: Layer sharing also brings an engineering bonus—cache allocation, swapping in and out, and lifecycle management can be performed at the granularity of “sharing groups,” reducing the implementation complexity of inference frameworks.
    • Orthogonal and stackable with GQA: Cross-layer sharing acts on the L dimension while GQA acts on the H dimension; the two can be combined for multiplicative compression.

    4. Supporting Techniques: Quantization, Sliding Windows, and Hybrid Attention

    A complete KV Cache optimization strategy is usually a combination of techniques:

    1. KV quantization: Compressing the cache from FP16 to INT8 or even INT4, combined with group-wise quantization and per-layer calibration, can save another 50%–75% of memory with almost no quality loss. Note that quantization errors accumulate over long contexts, so it is advisable to use different quantization granularities for Keys and Values.
    2. Sliding Window Attention: Some layers retain only the KV of the most recent N tokens, discarding anything beyond the window—changing S from “the full sequence” to “a fixed window.” A common practice is to alternate sliding-window layers with global attention layers, balancing local efficiency with long-range dependencies.
    3. Cache eviction and compression: For ultra-long sessions, low-importance historical KV can be evicted or merged based on attention scores, keeping memory usage within budget.
    4. Paged memory management: At the inference framework level, a paging mechanism similar to OS virtual memory manages KV blocks, eliminating fragmentation and improving memory utilization for concurrent batches.

    5. Practical Engineering Recommendations

    For teams deploying long-context inference services in enterprise environments, the following path is recommended:

    • Model selection: Prioritize open-weight models that natively support GQA and cross-layer sharing architectures; for edge scenarios, focus on small-parameter variants optimized for low memory;
    • Inference configuration: Set KV quantization precision and sliding-window size based on the context-length distribution of your business, and validate quality regressions by replaying real traffic;
    • Capacity planning: Include KV Cache memory in your capacity model, estimating memory as “weights + peak concurrency × per-request cache” to avoid OOM after going live;
    • Platform support: Use general-purpose container platforms for elastic scaling of inference services, manage model versions with object storage, and continuously track metrics such as time-to-first-token, per-token latency, and memory watermark using logging and monitoring/alerting services. For example, on platforms such as Baidu AI Cloud, a stable serving pipeline can be quickly built on containerized inference and observability tooling.

    Conclusion

    From GQA to cross-layer KV sharing, the main logic of KV Cache optimization is clear: continuously compress the cache along the four dimensions of H, L, P, and S while preserving model quality as much as possible. In the era of reasoning models and agents, whoever has the leaner KV Cache can run longer contexts, higher concurrency, and lower costs on the same hardware. For developers, understanding these architectural mechanisms is not only the basis for model selection, but also a fundamental capability for designing efficient inference systems.