Cross-Layer KV Cache Reuse: Memory Optimization for Long-Context Inference

    Long-context inference often remains difficult to deploy even when model weights fit in memory, because the KV cache grows with context length and concurrent sequences. This article explains what the KV cache stores, how cross-layer reuse groups attention layers to share key/value states, how to estimate capacity savings, why lower cache usage does not automatically translate into proportional speedup, and what training and adaptation constraints apply. It also covers shared-cache lifecycle management, related optimization techniques, and a practical evaluation framework for memory, latency, throughput, and model quality.

    1. Why Long Contexts Remain Hard to Deploy Even After Models Shrink

    In edge devices, embedded systems, and local inference services, developers often start by focusing on parameter count: whether weights fit in memory, whether compute is low enough, and whether response speed meets interactive requirements. However, when input expands from short Q&A to long documents, multi-turn conversations, or code analysis, another resource cost quickly becomes prominent: the key-value cache, or KV cache.

    Autoregressive models generate one token at a time. To avoid recomputing the keys and values of historical tokens at every step, the inference system stores these intermediate states. The cache improves generation efficiency, but it continuously occupies device memory; on accelerators, this usually appears as GPU memory usage.

    Therefore, “the model weights fit” does not mean “long contexts can run reliably.” Real deployment must also reserve space for the KV cache, temporary tensors, operator workspaces, and runtime management structures.

    Cross-layer reuse of key-value states addresses exactly this problem: instead of requiring every attention layer to keep an independent set of historical keys and values, some layers use states already generated by other layers, reducing the number of caches at the architecture level.

    2. Understanding the KV Cache: What Is Actually Cached

    2.1 Queries, Keys, and Values in Standard Attention

    In a typical autoregressive attention structure, a layer receives the current hidden state and generates queries, keys, and values through different projections, denoted as Q, K, and V.

    The core computation can be summarized as:

    Attention(Q, K, V) = softmax(QKᵀ / √d + M)V

    Here, d is the dimension of each attention head, and M is the mask that restricts visible positions. For autoregressive generation, the current position can only access historical positions within the allowed range and the current position; it cannot read future tokens.

    During incremental decoding, the model usually computes new states only for the new token, appends the newly generated K and V to the existing cache, and then performs attention between the current query and the cached historical keys and values.

    In a conventional design, different layers have different hidden states and therefore generate different K and V. As a result, each layer generally needs to maintain its own cache.

    2.2 Why Cache Capacity Grows Quickly

    For a model with full-history attention and identical layer configurations, the effective data capacity of the KV cache can be approximated as:

    Cache bytes ≈ 2 × L × B × T × Hkv × Dh × S

    The terms are as follows:

    • L: number of layers that independently maintain KV caches;
    • B: number of sequences processed concurrently;
    • T: number of cached tokens per sequence;
    • Hkv: number of KV heads;
    • Dh: dimension of each KV head;
    • S: bytes per cache element;
    • factor 2: corresponds to the two tensor types, keys and values.

    This formula reveals several direct relationships: the longer the context, the more concurrent sequences, and the more independent cache layers, the higher the cache usage.

    In actual runtime, additional overhead also appears, including memory alignment, paging metadata, preallocation, and fragmentation. If different layers use different window lengths or different numbers of KV heads, the calculation must be performed layer by layer rather than applying a single uniform configuration.

    3. The Core of Cross-Layer Reuse: Shared States, Not Merged Layers

    Cross-layer reuse can organize several attention layers into shared groups. One layer in a group generates keys and values, and designated later layers read that group’s key-value states instead of generating and storing their own independent versions.

    As an example of adjacent-layer sharing:

    Layer 1: generates Q₁, K₁, V₁, computes its own attention, and stores K₁, V₁.

    Layer 2: generates Q₂ from its own hidden state and uses K₁, V₁ to compute attention.

    Layer 3: generates a new set of Q₃, K₃, V₃ for itself and designated later layers.

    Three distinctions are important here.

    First, sharing the KV cache does not mean sharing queries. Different layers can still generate different queries from their own hidden states and perform different retrieval and aggregation over the same historical states.

    Second, sharing the KV cache does not mean all layers perform identical computation. Each layer can still retain its own residual connections, normalization, output projection, and feed-forward computation.

    Third, sharing a cache is not equivalent to sharing all parameters. The key point is that multiple consumer layers depend on the same set of K and V states; which projection parameters are retained, removed, or shared depends on the model design.

    This mechanism reduces the historical representations that must be stored independently, but it also changes the data dependencies between attention layers. It should therefore be treated as an architectural design choice, not merely a cache-compression switch.

    4. How to Estimate Memory Benefits, and Which Benefits Do Not Follow Directly

    4.1 Calculate Capacity by the Number of Independent Cache Groups

    If a model has L attention layers but ultimately only G independent KV cache groups, then under ideal conditions where other dimensions and precision remain unchanged, the effective KV cache data ratio is approximately:

    Shared cache size / original cache size ≈ G / L

    For example, if every two layers share one set of key-value states, the number of independent cache groups is about half the original number of layers, and the effective cache data volume is also roughly halved. This is only a structural capacity estimate, not a measured performance result for a specific model.

    It is also important to note that this reduces the KV cache portion, not the entire inference process memory. Weights, activations, runtime buffers, and other overhead do not decrease by the same ratio.

    4.2 Less Cache Does Not Mean Proportional Decoding Speedup

    Cross-layer reuse may reduce repeated key-value projection computation and cache writes, but each consumer layer usually still needs to compute its own query and perform attention aggregation, output projection, and feed-forward network computation.

    For full-history attention, a new token still needs to match against an increasingly long history of keys. Shared caches reduce the number of independent storage copies, but they do not automatically eliminate the computational cost of each consumer layer accessing historical states.

    Actual speed is also affected by:

    • the time share of attention computation versus feed-forward computation;
    • the memory layout and read efficiency of shared tensors;
    • whether operators introduce implicit copies or extra format conversions;
    • batch size, context length, and hardware bandwidth;
    • whether inference scheduling can effectively exploit shared dependencies.

    Therefore, “lower cache usage,” “lower peak memory,” and “faster generation” should be validated separately; they cannot be treated as the same conclusion.

    5. Why Existing Models Cannot Simply Drop Some Caches

    A common misunderstanding is that if adjacent layers can share, then deleting the cache of a later layer in an existing model and reading the earlier layer’s cache should produce the same result.

    The problem is that different layers originally learn different key-value representations. The query projection of a later layer is usually trained together with its own key space. Using it directly with another layer’s keys may distort the matching relationship; changes to value representations can also affect attention outputs.

    Therefore, cross-layer reuse usually needs to be introduced explicitly during model design and training, or through a validated conversion and adaptation process that allows the model to relearn the new state dependencies. It should not be assumed that any pretrained model can switch losslessly.

    Training and adaptation also need to consider:

    • whether the shared group size is too large and significantly limits representation capacity;
    • whether long-distance information retrieval and long-document reasoning degrade;
    • whether gradients from multiple consumer layers to the shared KV projection remain stable;
    • whether positional encoding, causal masking, and local windows are compatible;
    • whether quality changes on long contexts are noticeably larger than in short-text scenarios.

    A larger sharing scope usually offers higher potential cache savings, but more layers must use the same historical representation, and the trade-off between quality and efficiency may become more pronounced.

    6. Engineering Implementation: What Is Shared Is Storage, and Also Lifecycle

    6.1 Manage Caches with Shared Groups

    Traditional implementations often look up caches by layer index. With cross-layer sharing, a more appropriate approach is to establish a mapping from “layer to shared group,” with the cache entity owned by the shared group.

    Consumer layers store only references and no longer allocate equally sized caches separately. Otherwise, even if the same data is logically used, copy operations may eliminate the memory benefit.

    A conceptual decoding flow is shown below; the exact normalization and projection order should still follow the model definition:

    1. For each new token:
    2. Execute layers in order:
    3. Compute the current layer query
    4. If the current layer is the KV producer for a shared group:
    5. Compute the key and value for the new token
    6. Append once to that group's cache
    7. Perform attention using the group's complete valid cache
    8. Update the hidden state

    The key constraint is that the same shared group may append key-value states only once for the same token. Consumer layers must not append again; otherwise, cache length and token positions will become inconsistent.

    6.2 Ensure Position and Layout Compatibility

    The producer and consumer layers within a shared group must agree on the shape of key-value tensors, head organization, positional semantics, and valid length.

    If positional transformations have already been applied to keys, consumer layers must not apply the same transformation again. If different layers use different attention windows, it is also necessary to determine whether one cache group can satisfy the historical access requirements of all consumer layers.

    These issues should be handled through explicit metadata and validation rather than implicit conventions.

    6.3 Handle Cleanup, Branching, and Rollback Uniformly

    In multi-request serving, shared caches must be bound to request boundaries and must not mix data from different users because of incorrect reference relationships.

    If decoding involves multiple candidate branches, speculative generation, or rollback, the cache must also perform consistent copy, truncation, or release operations by shared group. Updating only one consumer layer’s logical length can cause layers in the same group to read inconsistent historical states.

    For chunked or paged caches, release conditions should also be managed by group, ensuring that underlying storage can be reclaimed only after the last valid consumer exits.

    7. How It Differs from Other Cache Optimizations

    Cross-layer reuse primarily reduces the number of layers with independent caches. It can also be combined with other optimization directions, but the combined benefit needs to be revalidated.

    Reducing the number of KV heads affects Hkv in the formula. Multiple query heads in the same layer can use fewer KV heads, but this is not equivalent to cross-layer sharing.

    Lowering cache precision affects the bytes per element, S. It can further compress storage, but it introduces numerical error and quantization/dequantization overhead.

    Limiting the attention window reduces the history length actually retained by some layers. However, a shorter window may affect long-distance dependencies and should not be adopted arbitrarily without evaluating its effects.

    Chunked or paged management mainly improves allocation efficiency and fragmentation. It does not necessarily reduce the amount of key-value data required per valid token, but it can improve resource utilization in real serving.

    These mechanisms act on different dimensions and may therefore be complementary. However, cache layout conversion, precision handling, and access patterns may also introduce additional costs. Theoretical compression ratios should not simply be multiplied and treated as final deployment benefits.

    8. How to Build a Reliable Evaluation Plan

    When validating cross-layer reuse, it is recommended to split evaluation into three levels.

    8.1 Memory and Capacity

    Measure effective cache data volume, runtime allocated memory, and actual peak usage separately, covering multiple context lengths and concurrency levels. A single test with fixed input length is unlikely to reflect the resource pressure caused by mixed long and short sequences in real requests.

    8.2 Latency and Throughput

    Distinguish between prompt prefill and token-by-token decoding. Record time to first output token, average generation interval, overall throughput, and high-percentile latency.

    Keep hardware, precision, input distribution, and scheduling policy consistent during testing. If space freed by shared caches is used to increase concurrency, report per-request benefits and service-capacity benefits separately.

    8.3 Model Quality and Correctness

    In addition to general tasks, cover long-document retrieval, multi-turn conversation, cross-paragraph information integration, and long-distance constraint following. At the same time, validate engineering behaviors such as batch request isolation, cache truncation, release at sequence end, and abnormal interruption.

    A reasonable acceptance condition should be: quality changes remain within an acceptable range, peak memory is actually reduced, and the target workload achieves measurable improvement in latency or concurrency capacity.

    9. Conclusion: Treat Cache Optimization as a Joint Model-and-System Design

    Cross-layer reuse of key-value states provides a different optimization path for long-context inference than simply reducing parameter count. By reducing the number of independent cache groups, it lowers the storage requirement for historical states and may reduce some repeated computation and writes.

    However, this mechanism is not a lossless patch applicable to any existing model, nor does it guarantee that a smaller cache will produce a proportional speedup. A practical solution requires coordinated design across model architecture, training process, attention operators, cache lifecycle, and serving scheduling.

    For developers, the most important step is not to pursue a single compression ratio, but to build a complete judgment: whether the current bottleneck comes from the KV cache, whether quality after sharing meets task requirements, and whether the freed memory can be converted into longer context, more stable responses, or higher serving concurrency.