Cross-Layer KV Cache Reuse: Cutting Memory and Cost in Long-Context LLM Inference

    KV Cache is an unavoidable cost center in long-context LLM inference, scaling linearly with sequence length, layer count, and batch size. This article explains why KV Cache becomes the bottleneck, introduces cross-layer KV reuse (sharing one Key-Value tensor across groups of layers), and shows how it complements Grouped-Query Attention. It walks through the key design decisions, the requirement that sharing be built in at training time, adoption across mainstream open-source architectures, and a balanced view of benefits and costs, followed by cloud engineering practices for moving these optimizations into production.

    1. Why KV Cache Becomes the Bottleneck for Long Context

    During autoregressive decoding, a Transformer needs the Keys and Values of every previously generated token to produce each new token. To avoid recomputing them, engineering practice caches these tensors — this is the KV Cache. It trades memory for speed and is a key mechanism for inference acceleration.

    The problem is that the KV Cache grows linearly with sequence length. Its approximate memory footprint can be estimated as:

    1. KV_Cache ≈ 2 × L × H_kv × d_head × S × B × bytes
    2. where:
    3. L = number of layers
    4. H_kv = number of KV attention heads
    5. d_head = dimension per head
    6. S = sequence length
    7. B = batch size
    8. bytes = bytes per element (2 for FP16)

    As the formula shows, whenever the sequence length S, the layer count L, or the batch size B increases, memory usage scales up proportionally. In long-context scenarios such as long-document summarization, multi-turn dialogue, and codebase understanding, the KV Cache often exceeds the model weights themselves and becomes the main consumer of memory. This leads to two direct consequences: first, the number of requests that can be processed concurrently is squeezed, limiting throughput; second, a large share of decoding time is spent reading the KV from memory, making it a classic memory-access bottleneck rather than a compute bottleneck.

    Reducing the size of the KV Cache is therefore one of the core entry points for improving long-context inference efficiency.

    2. The Core Idea of Cross-Layer KV Reuse

    A natural observation is that not every layer must maintain its own independent, complete Key-Value. Adjacent layers are highly correlated in feature space, and the key-value information their attention needs is often largely redundant. Where redundancy exists, it can be eliminated through sharing.

    The basic approach of cross-layer KV reuse (commonly framed as Cross-Layer Attention) is this: divide the network into several “sharing groups,” and let the multiple layers within the same group reuse one shared Key-Value tensor instead of each holding its own. In other words, the KV that each layer originally computed and cached is now computed once per group, and the Query of every layer in the group accesses this shared cache.

    This is complementary to another orthogonal optimization — Grouped-Query Attention (GQA/MQA, which compresses the cache by reducing the number of KV heads): GQA compresses the “head-count dimension,” while cross-layer reuse compresses the “layer dimension.” The two can be stacked to further reduce memory.

    It is worth emphasizing that this is not an entirely new concept. Academic research proposed similar mechanisms and validated their feasibility years ago, but the idea long remained at the research and small-scale validation stage. Its recent value lies in being genuinely adopted into the production-grade architectures of mainstream open-weight models and being tested by large-scale training and deployment — marking a shift from “feasible on paper” to “usable in engineering.”

    3. Implementation and Technical Details

    Getting cross-layer reuse into practice hinges on three design decisions.

    First, the granularity of sharing groups. Which layers are grouped together directly determines the trade-off between memory savings and quality loss. The larger the groups and the more layers within each group, the more significant the savings — but over-sharing sacrifices expressiveness; smaller groups approach the original design. Two strategies are common in practice: uniform grouping, for example sharing one KV every 2 layers; and irregular grouping, where some layers keep independent KV while others share, making a trade-off between critical layers and redundant ones.

    Second, how the KV projection parameters are organized. One intuitive approach is to have all layers in a group share the same set of K/V projection weights, achieving sharing at the parameter level. Another is for each layer to keep its own projection but, at inference time, only keep and compute the first layer’s KV and pass it down. The former is more thorough and delivers larger gains; the latter involves fewer changes and is easier to insert into existing models.

    Third, consistency between training and inference. The sharing structure must exist during training so the model can learn parameters that match under the sharing constraint; if independent, fully trained KVs are simply forced to share at inference time, this usually brings a noticeable quality drop. This means cross-layer reuse is an architecture choice “designed at training time,” not a patch that can be freely attached afterward.

    The following illustrative code shows the core logic of the shared cache (for illustration only, not a specific framework implementation):

    1. import math
    2. class CrossLayerKVModel:
    3. def __init__(self, num_layers, group_size):
    4. # Layers share one KV group every group_size layers
    5. self.num_layers = num_layers
    6. self.group_size = group_size
    7. # The number of sharing groups determines the KV cache size
    8. self.num_kv_groups = math.ceil(num_layers / group_size)
    9. def kv_cache_size(self, kv_heads, head_dim, seq_len, batch, bytes_per=2):
    10. # Compute the cache from the number of sharing groups, not all layers
    11. return (2 * self.num_kv_groups * kv_heads * head_dim
    12. * seq_len * batch * bytes_per)
    13. def is_shared_group_start(self, layer_idx):
    14. # Check whether the current layer starts a sharing group
    15. # (and therefore computes this group's KV)
    16. return layer_idx % self.group_size == 0

    Compared with computing over num_layers, computing over num_kv_groups roughly halves the KV Cache when every 2 layers share one group; the larger the groups, the more pronounced the savings.

    One noteworthy industry trend is that this kind of shared-KV mechanism is being adopted across different categories of model architectures, showing that it is not limited to a single network structure but is broadly adaptable. Taking current mainstream open-weight models as examples, roughly three design orientations targeting different scenarios can be summarized, and all of them benefit from KV reuse:

    • Lightweight models for mobile and embedded devices. These models run on memory-constrained terminals, where every bit of KV Cache memory is extremely valuable. Sharing KV significantly lowers the memory peak under long context, letting edge devices handle longer dialogues and document processing.
    • Mixture-of-Experts (MoE) architectures for efficient local inference. MoE reduces the compute per token through sparse activation, but the memory overhead of the KV Cache does not automatically shrink just because activation is sparse. Stacking KV sharing on top of MoE optimizes both the “compute” and “memory” dimensions at once.
    • Dense architectures for high quality and easy post-training. Dense models are usually easier to fine-tune and align. Combining KV reuse with a dense structure helps keep post-training friendliness while controlling inference cost.

    What the three types share is this: whether the underlying model is dense or sparse, and whether the target is a large cloud deployment or a small terminal, the KV Cache is an unavoidable memory and memory-access bottleneck, so cross-layer reuse carries universal value.

    5. A Rational Trade-Off of Benefits and Costs

    No optimization is free, and cross-layer reuse calls for an objective view of its trade-offs:

    • Benefits: memory usage drops significantly, directly enabling higher concurrent throughput, longer supported context lengths, and room to deploy a larger model or larger batch on the same hardware. Because the decoding stage is often constrained by memory bandwidth, a smaller cache also indirectly eases memory-access pressure.
    • Costs: sharing weakens the independent expressiveness of some layers, and if grouping is too aggressive, it may cause quality regressions on tasks that require fine-grained discrimination. It is therefore essential to make a controllable trade-off through group granularity.
    • Validation: before going live, run quality evaluations on the target business’s own data (not just general leaderboards), and use monitoring to quantify the actual changes in memory peak, first-token latency, and throughput — deciding data-drivenly whether to adopt the approach and how aggressive the sharing granularity should be.

    6. Recommendations for Cloud Engineering Deployment

    To bring this kind of inference optimization into production, model-side architecture design alone is not enough; supporting engineering capabilities are also needed. In practice, the foundational capabilities of a cloud platform can be used to close the loop on validation and operations:

    • Inference services and containerized deployment: elastically schedule inference instances through a container platform, and scale up or down based on memory and throughput metrics to make full use of the concurrency gains from KV compression.
    • Monitoring, alerting, and logging services: collect key metrics such as memory usage, latency, and throughput, and set up alerts to continuously track the before/after comparison curves and promptly detect quality or performance regressions.
    • Object storage and data management: used to store model weights, evaluation datasets, and version snapshots, supporting multi-version comparison and gradual rollout with rollback.

    Using the general-purpose cloud capabilities offered by Baidu AI Cloud — containers, monitoring and alerting, logging, and object storage — teams can build a release pipeline for inference optimization that runs from evaluation to gradual rollout to full deployment, moving KV Cache optimization smoothly from the experimental environment into production.

    7. Summary

    The KV Cache is an unavoidable cost center in long-context inference; its size grows linearly with sequence length, layer count, and batch size, and it has long constrained throughput and concurrency. Cross-layer KV reuse lets adjacent layers share one Key-Value tensor, compressing the cache along the layer dimension, which complements Grouped-Query Attention’s compression along the head-count dimension; the two can be stacked. Its correct use is “designed at training time, weighed by granularity, and fully evaluated before going live”: the more aggressive the grouping, the greater the gains but the higher the quality risk, so a trade-off must be made according to the business scenario. As this mechanism moves from academic research to production-grade adoption in mainstream open-source architectures, developers now have mature patterns to follow; combined with a cloud platform’s general-purpose capabilities in containerized deployment, monitoring and alerting, and data management, teams can reliably deliver cost- and efficiency-reducing inference optimizations into real business workloads.