LLM Inference Memory Optimization: Cross-Layer KV Cache Reuse

    In long-context, high-concurrency, and on-device inference, KV Cache is often the dominant memory bottleneck. This article explains where KV Cache memory cost comes from, how cross-layer KV reuse works, what it gains, and where it breaks down. It also compares the engineering tradeoffs between MoE and Dense architectures and provides a practical deployment checklist covering memory estimation, group_size tuning, accuracy regression, OOM fallback, and a minimal reproduction procedure. The goal is to help readers decide when cross-layer KV reuse is worth adopting and how to combine it safely with quantization, scheduling, and evaluation.

    In long-context, high-concurrency, and on-device inference, two questions come up repeatedly: why does the KV Cache consume GPU memory, and how can you reduce long-context memory usage? When the cache grows too large, it not only shrinks the number of concurrent requests but can also trigger OOM. Starting from where the KV Cache cost comes from, this article breaks down the principle, benefits, limitations, and engineering practices of reusing KV tensors across layers. It also compares the tradeoff logic between MoE and Dense architectures for efficient inference.

    1. Why the KV Cache Consumes GPU Memory

    Autoregressive generation references the Keys and Values of all previous tokens every time it emits a new token. If the K and V of historical tokens were recomputed at every step, the compute cost would rise quickly. To avoid repeated computation, inference frameworks typically cache the K and V that have already been produced. This is the KV Cache. It turns decoding from recomputing the entire history at each step into simply reading the cache and performing attention, substantially lowering the computational complexity.

    However, the KV Cache introduces a new memory cost. Its footprint can be approximated as:

    1. KV Cache ≈ batch size × sequence length × num layers × 2 × num KV heads × head dim × bytes per element

    Here, “2” accounts for the two parts, K and V. In long-context scenarios, this value expands rapidly. For example, for a hypothetical model with 32 layers, 8 KV heads, and a head dimension of 128, using FP16 with a batch size of 1 and a sequence length of 32768, the KV Cache is on the order of about 4GB; raise the batch size to 8, and it can reach the order of about 32GB. If the model weights also need to be loaded into GPU memory, the KV Cache is very likely to become the primary bottleneck for long-context inference.

    There are usually a few paths to reduce KV Cache memory: reduce the number of KV heads per layer, compress the numerical precision of K/V, reuse the KV of some layers, or adopt a more compact attention structure. Cross-layer KV reuse is one of these optimizations. It is tightly coupled to the model structure, but its engineering gains are fairly direct.

    2. Core Mechanism of Cross-Layer KV Reuse

    Cross-layer reuse starts from a simple observation: the Key-Value states produced by adjacent Transformer layers often contain a degree of redundancy. If several subsequent layers no longer generate KV independently but instead reuse the KV tensors already computed by certain earlier layers, you can reduce both redundant caching and redundant writes.

    The following code is illustrative only. It shows the basic idea of grouped reuse and does not by itself prove that the approach is deployable:

    1. # Illustrative code: demonstrates the basic idea of cross-layer KV reuse; must be validated against a real model
    2. def forward_standard(hidden_states, layer_idx, kv_cache):
    3. q = Wq[layer_idx](hidden_states)
    4. k = Wk[layer_idx](hidden_states)
    5. v = Wv[layer_idx](hidden_states)
    6. kv_cache[layer_idx] = concat(kv_cache[layer_idx], k, v)
    7. return attention(q, kv_cache[layer_idx])
    8. def forward_cross_layer(hidden_states, layer_idx, group_size, kv_cache):
    9. group_head = layer_idx - (layer_idx % group_size)
    10. if layer_idx == group_head:
    11. # The group-head layer computes and writes the KV
    12. k = Wk[layer_idx](hidden_states)
    13. v = Wv[layer_idx](hidden_states)
    14. kv_cache[group_head] = concat(kv_cache[group_head], k, v)
    15. # Other layers in the group reuse the group-head KV
    16. q = Wq[layer_idx](hidden_states)
    17. return attention(q, kv_cache[group_head])

    The benefits of this approach are mainly twofold. First, the number of cached layers drops from the total layer count L to the number of groups L / group_size, which in long-context settings can roughly reduce KV Cache memory in a near-linear fashion. Second, during decoding there is no longer a need to read and write KV for every layer, which reduces the pressure of K/V projections, cache writes, and memory access bandwidth.

    However, cross-layer reuse is not unconditional. Running inference directly on a model that was not built with a similar structure may cause a noticeable quality drop. In general, you need to satisfy or evaluate the following preconditions:

    1. Consistent KV dimensions: The K and V dimensions output by the reused layers and the group-head layer must match, otherwise the tensors cannot be concatenated or shared.
    2. Consistent head count: The number of KV heads, the per-head dimension, and the KV mapping structure must be compatible. If the model uses structures such as grouped-query attention, you also need to confirm whether cross-group reuse breaks the existing sharing relationships.
    3. Consistent positional encoding: If positional encodings such as RoPE are used, the positional encoding method across layers within a group must be identical; otherwise the positional semantics of historical tokens may become misaligned.
    4. Whether training or calibration is required: Some research and open-source practices have already explored similar ideas and need to be validated against a specific implementation. If the model did not learn cross-layer shared KV during pretraining or post-training, applying it directly at inference may cost accuracy; a safer approach is to introduce the structure through continued pretraining, fine-tuning, distillation, or a calibration pipeline.
    5. Accuracy degradation risk: The larger the group, the more obvious the memory savings, but the more the independent representational capacity across layers declines. Tasks such as long-range dependency handling, code generation, mathematical reasoning, and long-document question answering are more likely to expose problems.

    Cross-layer reuse is not mutually exclusive with other KV compression methods, but their positioning and costs differ:

    Method Primary optimization target Main benefit Main limitation
    Cross-layer KV reuse Between layers Fewer cached layers, lower memory and memory access Requires consistent dimensions, head count, and positional encoding; may need training or calibration
    In-group sharing such as GQA Multiple Q heads within the same layer Fewer KV heads Depends on model-structure training; high change cost
    Low-rank compression such as MLA How K/V is represented Significantly compresses the KV representation Complex to implement; requires deep adaptation to the inference framework
    KV quantization Numerical precision Fewer bytes of KV per token Quantization error may affect long-context accuracy
    Paged memory management How memory is allocated Reduces fragmentation, improves utilization Requires framework support; does not change the total KV amount

    For this reason, cross-layer reuse is better suited to memory-constrained, long-context-heavy scenarios where you are willing to do accuracy regression and adaptation training.

    3. Architecture Selection: Engineering Tradeoffs Between MoE and Dense

    Beyond KV Cache optimization, the inference architecture itself also affects memory, throughput, and quality. Common current routes include the mixture-of-experts (MoE) architecture and the dense architecture.

    Dimension MoE architecture Dense architecture
    Parameter activation Each token activates only some experts Each token activates all parameters
    Memory pressure Total weights may be large, but the activated compute is smaller Both weights and activations are relatively predictable
    Compute efficiency May offer a compute-efficiency advantage when activated parameters are limited, but total weight memory and loading cost must be evaluated Simple path, suited to stable inference
    Post-training cost Routing adds complexity; expert branches make unified fine-tuning harder Post-training and tuning workflows are smoother
    Quality ceiling Capacity can be raised via total parameter size, but tuning is harder More favorable for stable quality and engineering maintainability

    MoE works by routing so that only some expert networks are activated for each token, controlling the number of activated parameters per token while keeping the total parameter count large. This may offer a compute-efficiency advantage when activated parameters are the limiting factor, but total weight memory, loading cost, routing stability, and post-training complexity all need to be evaluated separately. If the total weights must all be loaded into GPU memory, the memory advantage of MoE does not simply hold.

    The Dense architecture is more straightforward: each token uses all parameters, the inference path is simple, behavior is more predictable, and it is easier to fine-tune and post-train. For scenarios that pursue stable quality, frequent iteration, and fine-grained tuning, Dense is often easier to maintain.

    A common strategy is as follows: for low-memory, on-device, or embedded tiers, prioritize evaluating compact Dense models or optimizations that combine KV reuse, quantization, and low-rank caching; on the mid-to-high-end serving side, if you value the quality ceiling and ease of post-training more, Dense remains a safe choice. The final selection should weigh four dimensions together: the number of activated parameters, total parameter capacity, memory footprint, and post-training cost.

    4. Engineering Deployment Checklist

    To actually deploy cross-layer KV reuse, you cannot look only at “did memory drop”; you must also validate quality, throughput, and stability at the same time. The following checklist can serve as a pre-launch action list.

    1. Memory Estimation

    When estimating total memory, include at least four parts:

    1. Total memory ≈ model weight memory + KV Cache memory + activations and temporary tensors + inference framework overhead

    With cross-layer reuse enabled, the KV Cache can be approximated as:

    1. KV Cache ≈ batch size × sequence length × effective cached layers × 2 × num KV heads × head dim × bytes per element
    2. effective cached layers ≈ total layers / group_size

    For example, with 32 total layers and a group_size of 4, the effective cached layers are about 8. Compared with caching every layer, KV memory drops to roughly one quarter of the original. In real deployments, you also need to reserve space for the framework, communication, fragmentation, and peak activations; you cannot configure based on the theoretical value alone.

    group_size is the key parameter in the tradeoff between memory savings and quality loss. In general, start testing from smaller values:

    • group_size = 2: smaller gains, but quality risk is usually easier to control.
    • group_size = 4: a fairly common compromise range, suitable as an initial experiment point.
    • group_size = 8: noticeable memory savings, but long-context tasks must be regression-tested carefully.
    • group_size = 16 and above: use with caution; typically requires training adaptation, distillation, or calibration support.

    It is recommended to treat group_size as an independent hyperparameter and run a grid search, separately recording peak memory, first-token latency, throughput, perplexity, and downstream task metrics. If task metrics drop beyond the business tolerance threshold as group_size increases, roll back or adopt a hybrid grouping strategy, for example using a smaller group_size in shallow layers and a larger one in deeper layers.

    3. Accuracy Regression Metrics

    Before launch, at least the following metrics should be covered:

    • Perplexity: to verify whether overall language modeling has degraded.
    • Long-context tasks: long-document summarization, document question answering, cross-section retrieval, and code repository understanding.
    • Generation quality: factual consistency, instruction following, and structured-output stability.
    • Inference stability: repeated generation, truncation, hallucination rate, and boundary behavior on very long inputs.
    • Performance changes: throughput, first-token latency, per-token decode latency, and peak memory.

    In particular, passing short-context tests does not mean passing long-context tests. Cross-layer reuse is more sensitive to long-range dependencies, so you must build a dedicated long-context regression set.

    4. OOM Fallback Strategy

    An inference service should not chase the maximum batch size only. It is recommended to set memory warning and protection thresholds, for example alerting when memory usage exceeds 80% and entering degradation or rejecting new requests when it exceeds 90%. When memory usage crosses the threshold, progressively shorten the maximum context, reduce the batch size, and enable KV eviction or quantization. This order can be adjusted based on business priority, but there must be a clear circuit-breaker path rather than endlessly expanding the batch size.

    Executable fallback rules include:

    1. Shorten the maximum context length.
    2. Reduce the current batch size or the queue concurrency.
    3. Enable KV quantization.
    4. Enable sliding window, importance-based eviction, or other KV eviction strategies.
    5. Switch to a smaller model or a more conservative group_size configuration.
    6. Queue or reject overly long requests to avoid dragging down the entire service.

    5. Minimal Reproduction Steps

    Before a real launch, it is recommended to first complete a minimal reproduction experiment:

    1. Pin the model version, inference framework version, and CUDA or runtime version.
    2. Record the number of model layers, hidden dimension, number of KV heads, per-head dimension, and data precision.
    3. Fix the batch size, input length, output length, and sampling parameters.
    4. Measure three configurations separately: standard KV, cross-layer reuse, and cross-layer reuse plus quantization.
    5. Record peak memory, first-token latency, throughput, perplexity, and long-context task scores.
    6. Run a two-dimensional grid search over group_size, maximum context, and batch size.
    7. Compare output quality on the same inputs, focusing on long-range dependencies, instruction following, and factual errors.

    5. Common Mistakes and Summary

    Cross-layer KV reuse is a low-cost, pluggable memory-optimization direction, but there are also quite a few common mistakes. Typical problems include: ignoring training adaptation and directly applying a sharing structure to a model that has not been adapted; ignoring consistency of KV dimensions, head count, and positional encoding; looking only at the memory drop without validating long-context quality; measuring only average throughput without observing tail requests; and tuning only the batch size without designing an OOM fallback strategy.

    Overall, the KV Cache is the core memory cost in long-context inference, and cross-layer reuse offers a viable path to reduce memory usage by cutting the number of effective cached layers. But it is not a universal switch; it needs to work together with the model structure, training adaptation, quantization strategy, scheduling rules, and accuracy regression. For MoE versus Dense, the decision should be made by combining the number of activated parameters, total weight memory, post-training cost, and the target hardware. Understanding the boundaries and the synergy of these two layers of optimization is what truly enables a stable, efficient, and deployable large-model inference system.