Cross-Layer KV Cache Reuse: Reducing GPU Memory in LLM Inference

    As context windows grow, the KV cache often becomes the first memory bottleneck in large language model inference. This article explains why KV cache size scales with sequence length, batch size, and model structure, and how cross-layer reuse (sharing key-value state across layers) can lower both memory footprint and compute. It covers the core idea and its boundaries, three reuse granularities (full sharing, group sharing, and representative-layer retention) with a comparison table and example pseudocode, how cross-layer reuse differs from GQA/MQA, and why Dense and MoE models require separate memory accounting. It closes with guidance on when cross-layer KV sharing is worth adopting and when to proceed with caution.

    1. Why the KV Cache Becomes the First Bottleneck in Long Context

    During the autoregressive decoding stage of a large language model, every newly generated token must reference the Key and Value vectors of all previous tokens. To avoid recomputation, mainstream inference systems cache the Key-Value tensors that have already been computed. This is the KV cache. It is a classic “trade memory for compute” engineering compromise: sacrifice some memory to gain the speed benefit of not recomputing the history during decoding.

    The problem is that KV cache overhead grows quickly with context length, batch size, and model structure. A rough formula helps convey its scale:

    1. KV_Cache bytes ≈ 2 (K and V)
    2. × number of layers
    3. × number of KV heads
    4. × head dimension
    5. × sequence length
    6. × batch size
    7. × bytes per element

    The “bytes per element” term depends on storage precision: FP16 is typically 2 bytes, FP8/INT8 typically 1 byte; the exact value depends on the quantization scheme actually used.

    To make the formula concrete, plug in a common set of parameters: a model with 32 layers, 8 KV heads, head dimension of 128, sequence length of 8192, batch size of 16, and FP16 (2 bytes) per element:

    1. KV_Cache bytes
    2. = 2 × 32 × 8 × 128 × 8192 × 16 × 2
    3. ≈ 17,179,869,184 bytes
    4. ≈ 16 GiB

    Switching to 8-bit or lower storage could theoretically drop the same configuration to about 8 GiB or less. Note, however, that real systems must also account for framework overhead, memory fragmentation, paging management, and batch scheduling, so every savings figure needs to be measured on the target workload and will vary with the model, context length, concurrency, and inference framework.

    For scenarios such as long-document understanding, codebase analysis, multi-turn long conversations, and long-context RAG, the KV cache is often not a marginal optimization but a key bottleneck that determines whether a service can launch at high concurrency and stably handle long context.

    2. The Core Idea of Cross-Layer Reuse and Its Boundaries

    Since KV cache overhead mainly comes from “every layer keeping its own separate copy,” a natural optimization direction emerges: can some layers stop keeping separate copies and instead share the same key-value state?

    Cross-layer reuse, also called cross-layer attention sharing or cross-layer parameter sharing, is built on this idea: in a deep network, the key-value representations learned by adjacent layers, or layers several positions apart, exhibit some redundancy and similarity. Therefore, subsequent layers can stop independently computing and caching their own K and V, and instead reuse the Key-Value tensors of a previous layer, or have a group of layers share one Key-Value tensor.

    This optimization delivers benefits on two levels:

    1. Memory dimension: fewer layers need to be cached, so memory usage for long context drops accordingly.
    2. Compute dimension: reused layers skip the forward computation of the K and V projection matrices, lowering inference compute cost.

    This idea is not new. Academia and industry already have related work on cross-layer parameter sharing and cross-layer attention sharing, and there are named methods such as YOCO and LayerKV; some open-source model families may also adopt similar designs. For specific implementations, parameter configurations, and applicable boundaries, refer to the respective papers, official model cards, and code repositories.

    That said, cross-layer reuse is not a “free lunch,” nor can every model adopt it directly. Three key boundaries must be made clear:

    First, cross-layer reuse changes the model’s attention structure. It usually requires post-training or continued training to land in practice. Applied directly to existing weights, especially without continued training or distillation, model accuracy may degrade. In other words, it is not a simple inference-framework flag; it is more like a structural optimization that requires a training and evaluation loop.

    Second, the benefit may be limited when context is short and concurrency is low. KV cache memory pressure scales with context length and batch size. If the average context is only a few hundred or a few thousand tokens and concurrency is low, the memory savings from cross-layer reuse may not be enough to offset the accuracy risk and post-training cost.

    Third, cross-layer sharing and GQA/MQA are optimizations along different dimensions. GQA (Grouped-Query Attention) and MQA (Multi-Query Attention) mainly address cross-head sharing, that is, reducing the number of KV heads. Cross-layer KV cache reuse addresses cross-layer sharing, that is, reducing the number of layers that must be cached independently. The two can be combined, but they should not be conflated.

    3. Choosing Among Three Reuse Granularities: Full Sharing, Group Sharing, and Representative-Layer Retention

    Cross-layer reuse is not a black-and-white choice but a set of options with different “compression strengths.” In practice, three granularities are usually considered: full sharing, group sharing, and representative-layer retention.

    Reuse granularity Compression Memory savings Accuracy risk Post-training cost Typical use case
    Full sharing Most aggressive Highest Higher Higher Accuracy-insensitive scenarios, or those with sufficient post-training capability
    Group sharing Medium Medium Medium Medium Common balance point for most long-context inference
    Representative-layer retention Conservative Low-to-medium Relatively controllable Determined by experiment Accuracy-sensitive teams that want to introduce sharing gradually

    Full sharing lets all layers use the same set of K and V. It compresses most aggressively and yields the largest memory savings, but also carries the highest risk of losing representational capacity. Unless the model is thoroughly post-trained, or the workload tolerates a fair amount of accuracy loss, it is not recommended to start here.

    Group sharing divides layers into several groups, with each group sharing one K and V. It is a common balance point between benefit and quality. For example, sharing one KV every 2, 4, or 8 layers both noticeably reduces the number of cached copies and retains some inter-layer representational capacity.

    Representative-layer retention lets only a few key layers actually hold and project K and V, while the remaining layers reuse the representative layers’ cache. Which layers to keep must be determined through experiments. One actionable approach is to observe, in offline evaluation, each layer’s output error, differences in attention distribution, or impact on downstream tasks, and keep as representative layers those with the largest error or attention differences, or keep the layers the task is most sensitive to as the ones that truly compute K and V.

    The pseudocode below illustrates an intuitive implementation of “group sharing.” It is intended only to explain the mechanism and does not represent any specific framework’s API:

    1. class GroupSharedKVAttention(nn.Module):
    2. def __init__(self, hidden_dim, num_layers, group_size):
    3. super().__init__()
    4. self.hidden_dim = hidden_dim
    5. self.group_size = group_size
    6. # Only the first layer of each group acts as the "owner" that holds KV projections
    7. self.kv_owner = nn.ModuleDict({
    8. str(i): KVProjection(self.hidden_dim)
    9. for i in range(0, num_layers, group_size)
    10. })
    11. # Each request or sequence needs its own independent KV cache
    12. self.kv_cache = KVCache(num_layers)
    13. def forward(self, x, layer_idx, position):
    14. # Find the owner layer of this layer's group
    15. owner_idx = (layer_idx // self.group_size) * self.group_size
    16. if layer_idx == owner_idx:
    17. # Owner layer computes K/V and writes it to the cache
    18. kv = self.kv_owner[str(owner_idx)](x)
    19. self.kv_cache.write(owner_idx, position, kv)
    20. return self.attend_with_kv(x, kv)
    21. else:
    22. # Non-owner layers do not recompute K/V; they only read the owner's cache by position
    23. kv = self.kv_cache.read(owner_idx, position)
    24. return self.attend_with_kv(x, kv)

    In this pseudocode, only the owner layer owner_idx calls KVProjection to compute K and V and write to the cache; the other layers only read from the corresponding owner layer’s cache. This is precisely the key to how cross-layer reuse skips part of the K/V projection computation and reduces the number of cached copies.

    In engineering practice, a few additional issues need attention. First, under batched serving, different requests’ KV must be managed independently per sequence and cannot simply share the same contiguous block of memory. Second, consider how paged memory allocation coordinates with the sharing logic, for example page-table management after sharing, cache reclamation, and request isolation. Third, after cross-layer sharing, positional encoding is injected only once at the owner layer while each layer’s Query remains independent; in this case, watch whether the attention distributions converge and whether such convergence causes accuracy changes.

    4. Dense and MoE: Do Not Mix the Two Memory Ledgers

    Recent open-source model families often release multiple structures: a small-parameter version for edge or embedded devices, a mid-scale version using Mixture of Experts (MoE), and a larger version using a Dense structure. Behind this variety lies a trade-off between inference efficiency and trainability.

    The advantage of MoE is that each token activates only some of the experts, so the number of activated parameters is small and inference uses less compute. However, its routing mechanism makes post-training more complex: the stability of fine-tuning, alignment, and distillation is harder to control, and the tuning space is more sensitive.

    It is especially important to emphasize that MoE only reduces the compute and weight reads for a single token’s activation. KV cache memory still grows with the number of layers, KV heads, head dimension, and sequence length, and does not decrease because of expert sparsity. When selecting a model, memory and concurrency must be accounted for separately; do not assume that because “MoE saves compute,” it also relieves the KV cache memory bottleneck.

    The Dense structure runs each token through the full network, but it is more intuitive and controllable in post-training stages such as domain adaptation, instruction tuning, and distillation. Therefore, choosing Dense or MoE is essentially a trade-off between inference efficiency and trainability/controllability. If a team has mature inference optimization capabilities and pursues peak throughput, MoE is more attractive; if it values predictable fine-tuning and fast delivery, Dense is often the more hassle-free choice.

    5. FAQ: Does Cross-Layer KV Sharing Hurt Accuracy?

    Yes, it may hurt accuracy, and it usually requires post-training or continued training to absorb the structural change. Cross-layer reuse changes the attention computation path; if the model has not been adapted, applying it directly may not preserve the original representational quality. So do not treat it as a zero-cost switch.

    How do you choose the group size? Start with a smaller compression, for example, do local group sharing first, then evaluate memory, TTFT, throughput, and accuracy changes on the real business dataset. Do not look only at the average context length; instead, base the assessment on the context length of long-tail requests in the business, otherwise it is easy to underestimate the bottleneck.

    Can cross-layer sharing be combined with KV quantization and paged memory? Generally yes, because they optimize different dimensions. KV quantization compresses the number of bytes per single KV copy, cross-layer sharing reduces the number of KV copies, and paged memory management reduces fragmentation and scheduling cost. However, after combining them, you need to re-run benchmarks, because quantization noise, sharing error, and scheduling strategy may interact.

    6. Benefits and Costs Under Long Context

    The benefits of cross-layer reuse are mainly in memory and bandwidth. After reducing the number of KV copies, prefill and decode for long sequences become easier to deploy, and the number of concurrent requests that a unit of memory can support may increase. For workloads where context routinely reaches tens of thousands of tokens, this benefit is more pronounced. Still, all savings figures must be measured and will vary with the model, context length, concurrency, and framework.

    The cost is weakened inter-layer differentiation. Different layers of a model originally handle different representations and abstractions; forcing KV sharing may limit representational capacity. This is especially true for tasks such as strong reasoning, long-document retrieval, and code understanding, where accuracy changes need to be compared before and after on datasets that cover the core scenarios.

    A more prudent path is to first use low-risk methods such as KV quantization to compress memory, then evaluate structural changes like cross-layer sharing; any change that alters the KV structure should undergo an accuracy regression on a dataset covering the core scenarios to confirm quality stays within an acceptable range.

    7. Implementation Checklist: Which Scenarios Suit It, and Which Call for Caution

    The following checklist helps teams make a quick judgment.

    Scenarios worth prioritizing:

    1. Clearly long-context tasks, where context often reaches thousands or even tens of thousands of tokens.
    2. High concurrency, where KV cache memory has already become a throughput bottleneck.
    3. A team with post-training, evaluation, or distillation capabilities that can bear some model-adaptation cost.
    4. A workload that can accept a “quantify first, then gradually roll out” cadence.

    Scenarios not suited for direct launch:

    1. Short context and low concurrency, where KV cache pressure is not obvious.
    2. Strongly accuracy-sensitive tasks, such as high-risk scenarios in finance, healthcare, or legal, that have not completed sufficient regression.
    3. Cases where continued training or fine-tuning is impossible and existing weights must be applied as-is.
    4. Cases without a unified observability system spanning TTFT, throughput, memory, and accuracy.

    In engineering practice, it is recommended to track two metrics at the same time: time-to-first-token (TTFT) latency and overall throughput. Do not optimize only one dimension, otherwise one metric may improve while the other worsens. Benchmarks should use the real business distribution and, in particular, cover long-tail long-text requests. Any structural change should be rolled out gradually (canary) before ramping up, using general capabilities such as containerized deployment, monitoring and alerting, and logging to complete benchmarking, canary release, and online observation, so that the gains from memory optimization can be truly quantified.