Cross-Layer KV Cache Sharing: A Path to Cheaper Long-Context Inference

    Cross-layer KV cache sharing reduces the number of independent key-value cache copies an LLM maintains during long-context inference. This article explains where KV cache memory goes, what layers actually share, how it differs from GQA, cache quantization, sliding-window attention, and paged management, and what consistency issues, validation steps, and deployment decisions matter in practice.

    1. Why Long-Context Inference Depends on Cache Optimization

    When a large language model generates tokens one by one, every step needs to reference the existing context. Recomputing keys and values for past tokens at each step would create enormous duplicated work. The key-value cache (KV Cache) stores the key and value tensors for historical tokens so they don’t have to be recomputed, making it a foundational mechanism of autoregressive inference.

    But caching isn’t free. As the context grows, the key-value state stored per request keeps growing. For long-document analysis, multi-turn conversation, code understanding, or agent task execution, the cache can become a deciding factor for concurrency and context length.

    Inference optimization therefore can’t focus only on model size. A relatively small model under long-context, high-concurrency conditions may still hit a memory bottleneck purely because of cache usage.

    The core idea of cross-layer KV state sharing is simple: instead of requiring every attention layer to maintain its own full key-value history, some layers reuse key-value states already produced by other layers, reducing cache copies at the model architecture level.

    2. Where KV Cache Memory Actually Goes

    For the common case where all layers have identical cache specs and retain full history, theoretical KV cache capacity can be approximated as:

    M = 2 × B × T × L × Hkv × D × S

    where:

    • M: total cache size in bytes
    • B: batch size
    • T: number of cached tokens per sequence
    • L: number of attention layers that store caches independently
    • Hkv: number of key-value heads per layer
    • D: dimension of each key/value head
    • S: bytes per cached element
    • The factor 2 accounts for keys and values separately

    This formula points directly at several optimization levers: shorten the cached history, reduce the number of key-value heads, lower storage precision, or reduce the number of layers with independent caches.

    For example, suppose a model has 32 independent cache layers, 8 key-value heads, a head dimension of 128, and 2-byte elements. With a single request and a 32,768-token context, the theoretical KV cache is roughly 4 GiB.

    This is a hypothetical example for illustration only, not any real model’s configuration. Real deployments also carry overheads such as memory alignment, paging metadata, allocation reservations, and extra costs from variable-length requests.

    When multiple requests run concurrently, cache requirements accumulate further. Even without touching model weights, optimizing cache structure alone can free up meaningful memory.

    3. What Layers Actually Share

    In a conventional attention structure, layer i generates queries, keys, and values from its own hidden-state input:

    Q_i = X_i Wq_i

    K_i = X_i Wk_i

    V_i = X_i Wv_i

    The current query then attends over that layer’s historical key-value state.

    In a cross-layer sharing design, one layer is designated as the key-value provider. Later consumer layers still produce their own queries but read the keys and values generated by the provider:

    Q_j = X_j Wq_j

    A_j = Attention(Q_j, K_p, V_p)

    Here p denotes the provider layer and j the consumer layer. These expressions illustrate the mechanism only; real implementations must also handle normalization, positional encoding, causal masking, and tensor layout.

    The key difference: consumer layers no longer have to maintain fully independent key-value history. Instead, they access the provider’s state through references or shared storage.

    This does not mean the layers produce identical outputs. Consumer layers still have their own query transforms, output transforms, feed-forward computation, and residual paths, so they can perform different information extraction and feature processing.

    3.1 How the Number of Cached Layers Shrinks

    Suppose a model has 32 attention layers, grouped so that every two adjacent layers share one key-value state — one layer provides, the other reuses. The number of independent cache sets then drops from 32 to 16.

    Under otherwise identical ideal conditions, the corresponding KV cache shrinks by roughly half.

    But this ratio should not be read as “total model memory is halved.” Model weights, temporary activations, execution workspaces, and serving runtime overhead remain. How much total memory you actually save depends on what share of memory the cache occupied in the first place.

    3.2 Where the Compute Savings Come From

    If the architecture allows consumer layers to skip their own key and value projections, some matrix computations and cache writes can be eliminated.

    However, consumer layers still typically need to match their queries against historical keys and compute weighted sums over values. Cross-layer sharing therefore does not eliminate attention computation, nor does it imply generation speed scales with the cache compression ratio.

    What it changes first is state storage and some projection work; the eventual speed gain also depends on memory bandwidth, compute resources, kernel implementations, and sequence length.

    4. How It Differs from Other Cache Optimizations

    Cache optimization is rarely a single technique — it’s a combination across multiple dimensions. Understanding what each one targets helps avoid double-counting benefits.

    4.1 Grouped-Query Attention: Fewer KV Heads per Layer

    Grouped-query attention (GQA) lets multiple query heads share the same set of key-value heads, compressing Hkv in the formula.

    Cross-layer sharing instead reduces the number of independent cache sets, targeting L.

    Since they act on different dimensions, they can be combined where the architecture allows. But the combined quality and performance still need validation — you can’t infer model behavior from the capacity formula alone.

    4.2 Cache Quantization: Fewer Bytes per Element

    Cache quantization represents keys and values at lower precision, reducing S.

    Its engineering challenges include quantization error, storing scale parameters, dequantization cost, and numerical stability over long contexts. Once a set of key-value states is shared across layers, quantization error may accumulate across multiple consumer layers, which deserves attention.

    4.3 Sliding Window: Shorter Retained History

    Sliding-window attention only retains or attends to a bounded range of history, constraining T.

    This controls cache growth but changes which history the model can directly access. Cross-layer sharing itself doesn’t require truncating history; whether full context is retained should be decided by the attention structure and application needs together.

    4.4 Paged Management: Less Allocation Waste

    Paged management splits the cache into smaller blocks, improving memory utilization for dynamic request patterns.

    It mainly addresses allocation and scheduling; it doesn’t directly reduce the theoretical capacity per valid cached element. Cross-layer sharing compresses the number of states, while paging improves how states are stored — the two are complementary.

    5. Why You Can’t Just “Stitch Together” an Existing Model’s Cache

    Cross-layer sharing is not a runtime switch.

    For a model that has finished training with each layer generating its own key-value states, different layers typically have different representation distributions, projection parameters, and semantic roles. Having one layer directly read another layer’s cache can break the original attention behavior and degrade output quality.

    Two things must be distinguished:

    • Sharing cache storage is a runtime engineering problem.
    • Teaching a model to use other layers’ key-value representations is an architecture design and training adaptation problem.

    Reliable solutions usually introduce the relevant structure during training, or require validated structural modification, continued training, and adaptation so consumer layers learn to use the shared state.

    So when optimizing deployment of an existing model, first confirm whether its architecture natively supports cross-layer sharing — don’t just modify cache indexing.

    6. Four Consistency Issues You Must Handle

    6.1 Tensor Dimensions and Head Mapping

    The provider’s key-value head count and head dimension must be compatible with the consumer’s query layout. If they don’t match directly, extra mappings are needed, and those mappings may introduce new parameters, computation, and error.

    Engineering design should define every sharing relationship explicitly, rather than assuming any two layers can exchange caches.

    6.2 Positional Encoding and Visibility

    Key states usually embed positional information. When consumers reuse them, they must follow a consistent positional interpretation — no reapplying position transforms or mismatched position indices.

    If layers use different attention windows or visibility ranges, shared caches also need matching masks and retention policies. A consumer must not read positions that should be invisible, nor lose required history because the cache was reclaimed too early.

    6.3 Lifetime and Reclamation

    Once a cache is referenced by multiple layers, its lifetime must cover all consumers.

    If the runtime reclaims memory using the old rule of “free once the current layer is done,” it can produce invalid accesses. Implementations must make cache ownership, reference relationships, append timing, and release conditions explicit.

    Prefill and token-by-token decode phases should use consistent sharing rules too, otherwise you may see short-sequence tests pass while state misalignment appears during extended generation.

    6.4 Whether Physical Storage Is Actually Shared

    Logically referencing the same cache doesn’t mean the underlying storage isn’t duplicated.

    If the execution path repeatedly produces transposed or contiguous copies to satisfy different kernel layout requirements, the theoretical savings can be partly erased. When evaluating, check actual allocations and data movement — not just the number of cache groups in the model config.

    7. How to Validate the Benefits — Not Just the Memory Number

    A complete evaluation should cover capacity, speed, and quality.

    7.1 Capacity: Measure Actual Peaks, Not Single-Line Estimates

    Record model weights, effective KV cache, temporary workspaces, and runtime reservations separately.

    Testing should span different context lengths and concurrency levels. Under a single short-context request, the impact on total memory may be small; the benefits become clear under long contexts or multiple requests.

    7.2 Speed: Separate Prefill from Decode

    Prefill processes the input sequence, while token-by-token decode repeatedly reads historical state — their bottlenecks differ.

    At minimum, observe:

    • Time to first token
    • Per-token latency during steady-state decoding
    • Total throughput at a given concurrency
    • Tail latency with mixed short and long requests
    • Extra costs from cache growth, allocation, and reclamation

    Even with a significantly smaller cache, speed won’t improve proportionally if attention computation, layout conversion, or scheduling overhead becomes the main bottleneck.

    7.3 Quality: Focus on Long-Range Dependencies

    Don’t just verify the model generates coherent text. Also test long-document retrieval, cross-section information integration, multi-turn factual consistency, structured output, and constraint adherence in long task chains.

    For designs with different sharing group sizes, evaluate quality changes separately. Larger sharing scope means fewer independent key-value representations; how much this affects model expressiveness must be answered through training and experiments, not intuition.

    8. Deployment Considerations

    For memory-constrained devices, the direct value of cross-layer sharing is reducing the state kept resident, allowing longer contexts within limited memory or freeing space for other compute modules.

    For server-side inference, the value can also appear as higher concurrent capacity, reduced memory pressure, and better per-resource utilization. But enterprise deployments should be judged against target workloads: long-context share, request length distribution, and latency requirements differ, and the best structure may differ accordingly.

    A recommended sequence:

    1. Use the capacity formula to build a budget and confirm the cache is actually your bottleneck.
    2. Verify the model supports cross-layer sharing and that the inference runtime can express the sharing relationships correctly.
    3. Validate numerical behavior, state appends, and long-sequence correctness under single-request conditions.
    4. Add concurrency, request cancellation, cache reclamation, and mixed-length scheduling to check engineering stability.
    5. Put quality, latency, throughput, and peak memory into one evaluation table before deciding on production.

    9. Conclusion: Cache Compression Is Really About Redesigning State Reuse

    Cross-layer KV cache sharing moves the optimization lens from “how to make each element cheaper” to “which states don’t need to be duplicated at all.”

    It works on different dimensions than GQA, cache quantization, sliding windows, and paged management, and can combine with them into a layered optimization strategy. But it also changes how layers exchange information, so model architecture, training, and the inference runtime must cooperate.

    For developers, the goal isn’t to chase a particular compression ratio. What matters is converting saved state storage into more usable context, more stable concurrency, and verifiable resource savings — within clearly defined quality boundaries.