Cross-Layer Shared KV Cache: Optimizing Memory and Decoding Bandwidth for Long-Context LLM Inference
This article explains how KV cache affects memory usage and decoding bandwidth in long-context LLM inference, reviews major KV cache optimization approaches, and focuses on cross-layer KV sharing. It covers the core design, implementation requirements, expected benefits, evaluation methods, and practical deployment considerations.
1. The Hidden Cost of Long Context: KV Cache
Large language models are moving beyond simple one-shot question answering toward long-document understanding, repository-level code QA, and multi-turn agent interactions. Contexts with hundreds of thousands of tokens are gradually moving from demonstrations to production systems. However, as context length grows, one easily underestimated cost becomes increasingly important: KV Cache.
1.1 Where KV Cache Comes From
Autoregressive generation produces output token by token. If every new token required the entire history to be fed through the network again, computational cost would grow quadratically with sequence length. The mainstream approach is to cache the Key and Value vectors of each attention layer during the forward pass. Later tokens only compute their own Query and attend to the cached Keys and Values. As a result, the K/V for each historical token only needs to be computed once.
The cost is that memory usage grows with a region proportional to “context length × number of concurrent requests.” For a typical Transformer decoder structure, the KV Cache footprint per token can be estimated as:
KV_bytes_per_token = 2 × L × H_kv × d_head × bytes_per_element
Where:
- 2: one copy for Key and one copy for Value;
- L: number of layers;
- H_kv: number of heads participating in KV cache per layer. With Grouped Query Attention,
H_kvis usually much smaller than the number of query heads; - d_head: dimension of each attention head;
- bytes_per_element: bytes per element. FP16/BF16 uses 2 bytes, while FP8 or INT8 uses 1 byte.
The total KV memory for a batch of requests is approximately:
KV_memory ≈ KV_bytes_per_token × avg_seq_len × max_batch_size
1.2 A Concrete Example
The following assumptions are illustrative and are used only to show the order of magnitude:
- The model has 32 layers, with 8 KV heads per layer and 128 dimensions per head;
- BF16 is used for storage.
Using the formula above, each token per layer takes about 2 × 8 × 128 × 2 = 4096 bytes, or 4 KiB. For the whole model, each token takes about 128 KiB. Converting this into request-level memory:
| Context Length | KV Cache per Request |
|---|---|
| 4K | About 512 MiB |
| 16K | About 2 GiB |
| 32K | About 4 GiB |
| 128K | About 16 GiB |
This is only the KV Cache for one request. Once model weights, activations, inference framework buffers, and concurrent requests are added, memory usage may become the limiting factor before weights do.
1.3 It Is Not Just a Memory Problem
KV Cache growth also slows inference. During autoregressive decoding, generating each token requires reading all historical K/V again. For long-context requests, decoding is often no longer compute-bound but memory-bandwidth-bound:
One decoding step for a request ≈ read all historical K/V + read all model weights (including activated experts in MoE)
For example, with a 32K context and a single-request KV Cache of about 4 GiB, assuming a memory bandwidth of 2 TB/s, reading K/V alone takes at least about 2 milliseconds. This means every additional cached K/V copy adds another bandwidth cost during decoding. Whether this hidden bill can be reduced directly affects the cost, concurrency, and latency of long-context applications.
2. Main Routes for KV Cache Optimization
Most KV Cache optimizations follow one of two ideas: store less or read less.
- Compression along the head dimension: Multi-Query Attention allows all query heads to share one set of K/V. Grouped Query Attention divides query heads into groups, with K/V shared within each group. Compared with standard multi-head attention, where every head stores its own K/V, KV Cache can be reduced by several times. Many such models can also be converted from existing models through a small amount of continued pretraining.
- Compression along the sequence dimension: Sliding Window Attention lets each token attend only to a recent window. A small number of global layers can carry information across windows, forming a local-plus-global hybrid structure. This gives cache usage an upper bound for long texts.
- Compression along the representation dimension: Low-rank attention methods first project K/V into a lower-dimensional latent space and cache that representation. The original K/V is reconstructed on demand during inference, trading a small amount of extra computation for a smaller cache.
- Compression along the layer dimension: Cross-layer KV sharing allows some layers to directly reuse K/V already computed by other layers.
- Compression at the storage format level: KV quantization, such as FP8 or INT8, reduces bytes per element. Paged cache management reduces fragmentation and improves memory utilization.
These methods operate on different dimensions. Most can be combined, and none is universally better than the others.
The following table compares representative approaches by compression dimension:
| Approach | Compression Dimension | Main Benefit | Main Cost | Compatibility with Other Approaches |
|---|---|---|---|---|
| MQA / GQA | Attention heads | Cache reduced by a multiple; decoding read cost also reduced | Heads within a group share information, with some loss of expressiveness | High, almost orthogonal |
| Sliding Window / Hybrid Attention | Sequence | Cache has an upper bound; strong scalability for long text | Distant information relies on global layers | High, independent of layer count |
| Low-Rank Compression | Per-head vector dimension | Cache greatly reduced | Additional projection/reconstruction computation and implementation complexity | Medium; stacking with quantization requires numerical validation |
| Cross-Layer KV Sharing | Layers | Cache and decoding bandwidth reduced according to sharing ratio | Limited cross-layer expressiveness; inference implementation must support cross-layer reuse | High; can be combined with GQA, quantization, and window attention |
| KV Quantization | Storage bit width | Simple to implement, direct benefit | Possible accuracy loss at very low bit widths | High; can be stacked with almost all approaches |
| Paged Cache Management | Storage layout | Reduces fragmentation, improves effective utilization | Requires inference framework support | High; a foundational capability |
It is worth noting that architecture-level optimization and inference-level optimization have different goals:
- The former determines how much can be cached and how fast it can be read, and usually requires training or post-training;
- The latter optimizes how data is stored and managed without changing the model.
Combining both often works better than using either approach alone.
3. Cross-Layer KV Reuse: From “One Copy per Layer” to “One Copy per Group”
3.1 Core Idea: Project Once, Share Across Layers
Recently released open-weight model series have sent a clear signal to developers: cross-layer KV reuse is moving from research into mainstream engineering practice.
These model series can generally be divided into three categories:
- Lightweight models for mobile and embedded devices: designed to run under limited memory and compute resources;
- Medium-sized models with Mixture-of-Experts architecture: balancing capacity and inference efficiency through sparse activation;
- Large dense models: focused on higher generation quality, with more mature post-training and fine-tuning workflows, since MoE routing mechanisms are often harder to tune.
The lightweight edge-oriented versions were the first to introduce the shared KV Cache mechanism: some layers no longer compute K/V themselves but directly reuse the Key/Value states from an earlier layer. This reduces both memory usage and computation cost under long context.
This idea has been explored in academic work such as Cross-Layer Attention. Previously, it was mostly used in research prototypes and small-scale experiments. The significance of these model series is that they apply it at scale to mainstream open-source architectures, making it an engineering feature that developers can use directly.
The core idea can be summarized in one sentence: within a shared group, only the first layer of the group projects K/V and writes it to the cache; the remaining layers skip this step and directly read the first layer’s cache for attention computation.
Standard structure (each layer projects its own K/V):hidden ──► [Wq·Wk·Wv] ──► Attention(Query_i, Key_i, Value_i)▲Key_i / Value_i each write to KV Cache (L copies total)Cross-layer sharing structure (group leader projects; other layers reuse):hidden ──► Layer i (group leader): Wq/Wk/Wv ──► Attention(Q_i, K_i, V_i) ──► Write to KV Cache│ K_i / V_i are passed down along the residual stream▼Layer i+1 (sharing layer): only Wq ──► Attention(Q_{i+1}, K_i, V_i) ──► Direct read│▼Layer i+2 (sharing layer): only Wq ──► Attention(Q_{i+2}, K_i, V_i) ──► Direct read
3.2 Why K/V from Different Layers Can Be Substituted
Intuitively, each layer receives different input representations, so it seems natural to compute dedicated K/V for each layer. Cross-layer sharing is feasible for the following reasons:
- The residual stream acts as an information bus shared across layers. In a standard Transformer, each layer writes its output back to the same residual stream through residual addition. The inputs seen by adjacent layers differ only by one attention-plus-feedforward increment and are therefore highly correlated.
- Different layers ask common questions about historical information. Lower layers tend to focus on local and shallow semantics, while higher layers handle more integration and reasoning. However, all of them frequently need to revisit entities, references, and facts in prior text. Keeping a separate historical view for every type of “question” introduces obvious redundancy.
- Deep information integration can be partially moved earlier. Since adjacent layers have highly similar K/V, it is not necessary to rebuild the historical view at every layer. A small number of layers can build it once, and later layers can retrieve what they need through their own Queries.
An analogy: the traditional structure is like a group of readers sitting around a long table, each with a full copy of the archive. Cross-layer sharing is like putting one archive in the center of the group, with each person bringing a different question. As long as the archive is complete enough, retrieval efficiency does not depend on the number of copies, but on how precise the questions are.
3.3 Example Code: Organizing Shared Groups
The following pseudocode shows an example where every g layers form a group and the first layer in the group projects K/V. It expresses design intent and does not represent the implementation of any specific framework.
SHARED_GROUP_SIZE = 2 # Share one K/V cache every 2 layers; adjust based on model size and evaluation results.def build_layer_specs(num_layers, shared_group_size=SHARED_GROUP_SIZE):"""Generate per-layer specs: the group leader projects K/V, and sharing layers reuse the previous layer's K/V."""specs = []for layer_idx in range(num_layers):in_group_pos = layer_idx % shared_group_sizespecs.append({"layer_index": layer_idx,"is_kv_owner": in_group_pos == 0, # Whether this layer is responsible for projecting K/V for the group"kv_source_layer": layer_idx - in_group_pos, # Source layer of K/V})return specsdef layer_forward(layer, hidden_states, kv_cache, layer_cache):spec = layer.layer_specif spec["is_kv_owner"]:# Group leader: projects K/V for the whole group and writes to its own cache slot.q = layer.q_proj(hidden_states)k = layer.k_proj(hidden_states)v = layer.v_proj(hidden_states)layer_cache[spec["layer_index"]] = (k, v)else:# Sharing layer: does not project or write K/V; only computes its own query.q = layer.q_proj(hidden_states)k, v = layer_cache[spec["kv_source_layer"]]attn_out = attention(q, k, v, kv_cache=layer_cache)return hidden_states + layer.attn_out_proj(attn_out)
Note: The pseudocode only expresses the core logic of who computes K/V and who reuses them. A real inference engine also needs to handle Rotary Position Embedding, causal masking, variable-length sequences, operator fusion, and other details.
4. Engineering Implementation and Common Pitfalls
The idea behind cross-layer sharing is not complex. What really determines deployment quality is the engineering detail.
4.1 KV Cache Management: Group Leader Has a Slot; Sharing Layers Allocate Nothing
The most straightforward approach is to reserve a cache slot for every layer. However, when the number of layers is not divisible by the shared group size, or when shared boundaries are not aligned, sharing-layer slots may remain idle and waste memory.
A better approach is to let the cache manager allocate by group: each shared group gets one slot, and sharing layers point to that slot by index. At the same time, mechanisms such as paged cache management and prefix caching are usually organized by layer. When integrating cross-layer sharing, the layer-to-slot mapping must be adjusted to avoid allocating the same data in multiple places.
4.2 Inference Engine and Kernels: Do Not Let Optimization Stop at Implementation
Cross-layer sharing requires the inference framework to explicitly understand which layers own K/V and which layers reuse them. This involves three parts:
- Cache management module: maintains the layer-to-slot mapping;
- Model execution flow: dispatches behavior based on each layer’s role;
- Attention operators: support directly accepting K/V tensors produced by other layers.
The reason is that some high-performance attention kernels implicitly read and write K/V inside the kernel. If the call path for sharing layers is not connected, the optimization will not take effect. When evaluating whether a model truly saves resources, both theoretical memory usage and actual memory usage and throughput in runtime should be checked.
4.3 Stacking with Quantization and Speculative Decoding
Cross-layer sharing and KV quantization operate on different dimensions, and their benefits are approximately multiplicative. Suppose cross-layer sharing halves the cache and quantization halves it again. In theory, total usage can be reduced to one quarter of the original. However, low-bit quantization introduces numerical error, so the combined approach must be re-evaluated for accuracy in the target scenario. The benefits cannot simply be extrapolated.
When used with speculative decoding, the speculative smaller model needs to maintain its own KV state, and the shared group structure should follow the same rules to avoid cache misalignment during draft generation and verification.
4.4 Long-Context Extrapolation and Post-Training
When context length exceeds the model’s training range, position encoding extrapolation methods such as position interpolation, NTK-based scaling, and YaRN are almost mandatory. Cross-layer sharing changes how information is passed between layers. Whether extrapolation parameters need to be calibrated separately at shared group boundaries should be confirmed through actual evaluation.
When fine-tuning models that use cross-layer sharing for domain-specific tasks, special attention should be paid to Query projection parameters and the K/V projection parameters of group leader layers. Sharing layers do not have dedicated K/V projection parameters, so gradient signals flow back through shared paths. Hyperparameters such as learning rate and training steps may need adjustment. For MoE models, expert routing balance must also be considered, making tuning more complex.
5. Evaluating Benefits: How Much Is Actually Saved?
5.1 Memory Benefit Estimation
Suppose the model has L layers and the shared group size is g, meaning one K/V cache is shared every g layers. The actual number of layers that need to cache K/V is:
L_cached = ceil(L / g)
For example, with 32 layers and a group size of 2, the number of cached layers drops to 16, and KV Cache usage is halved directly. With a group size of 4, it drops to one quarter of the original.
The amount of K/V data that must be read during each decoding step also drops by the same ratio. If decoding is truly memory-bandwidth-bound, single-request decoding throughput will typically improve accordingly.
5.2 Do Not Look Only at Averages
Actual benefits depend on three factors:
- Input and output length distribution: KV Cache mainly grows with input length;
- Concurrency: higher concurrency makes the benefits of sharing more obvious;
- Remaining memory: the more memory the framework can allocate to KV, the higher the concurrency it can support.
Therefore, evaluation should use the length distribution of real traffic for stress testing, not just averages. The following formula only provides an estimation baseline:
Memory usage ≈ weight memory + activation and framework overhead + KV_bytes_per_token × sequence length × concurrency
Output token counts vary by scenario and are not listed separately here. Framework overhead can be calibrated with measured values.
5.3 Effectiveness Side: Four Required Evaluations
Reducing memory usage is only the first step. Sharing layers no longer have dedicated K/V projection parameters, which may theoretically weaken the model’s ability to distinguish fine-grained information. Before deployment, at least the following evaluations should be covered:
- General capability regression: Compare scores before and after sharing on public benchmarks and internal evaluation sets, focusing on whether reasoning, math, and code tasks show obvious degradation.
- Long-context-specific evaluation: Use tasks such as needle-in-a-haystack retrieval, multi-hop QA, and long-document summarization at lengths such as 4K, 8K, 16K, and 32K to confirm that long-distance information recall does not degrade because of sharing.
- Business scenario validation: Use real business samples for human or automated comparison, especially scenarios involving coreference resolution and multi-turn dialogue consistency.
- Engineering stress testing: Under the same hardware and input distribution, compare peak memory usage, time to first token, decoding throughput, and maximum concurrency before and after sharing.
6. Practical Guidance for Cloud Deployment
6.1 Capacity Planning: Calculate First, Then Deploy
It is recommended to first estimate single-request KV usage and total memory demand using the input and output length distribution of real business traffic. Then, based on GPU specifications, determine the maximum concurrency per instance. Finally, plan the number of instances and elasticity strategy accordingly.
In practice, developers can use a cloud AI platform to manage model weights and inference services, leverage elastic scaling to handle traffic fluctuations, and use logging, monitoring, and alerting to continuously track metrics such as memory usage, time to first token, decoding throughput, and request error rate. When KV-related metrics approach thresholds, the system can scale out or degrade gracefully instead of waiting until memory is exhausted and reacting passively. For specific product capabilities and integration methods, refer to the official documentation of the selected platform.
6.2 Layered Deployment: Choose Model Specifications by Scenario
The three model specifications are suitable for different deployment locations:
- Lightweight models: suitable for mobile devices, embedded systems, or edge devices, especially for localized and low-latency scenarios;
- MoE models: suitable for server-side medium-scale concurrency, using sparse activation to obtain capacity;
- Large dense models: suitable for core business scenarios that require high generation quality and frequent post-training.
Cross-layer sharing makes long context feasible even on edge devices. This is especially important for edge deployment: device memory is limited, and the compression ratio of KV cache almost directly determines how long an input can be supported.
6.3 Observability: Treat KV Cache as a First-Class Metric
At least the following metrics should be collected:
| Metric | Meaning | Reference Threshold Idea |
|---|---|---|
| KV Cache usage / available memory | Cache water level | Sustained use above 80% should trigger scaling or throttling |
| Maximum concurrent requests | Concurrency supported by memory | Use as a baseline for capacity planning |
| Time to first token, TTFT | Affected by prefill computation | Set based on business SLA |
| Decoding throughput, tokens/s | Mainly affected by memory bandwidth | Compare improvement before and after sharing |
| Prefix cache hit rate | Reuse efficiency for requests with identical prefixes | If low, check routing and cache strategy |
| Memory fragmentation rate | Effectiveness of paged management | If persistently high, consider adjusting paging granularity |
7. Best Practices Checklist
Based on the analysis above, the following practices are recommended:
- Quantify before optimizing: Before deploying any KV optimization, use formulas and stress tests to confirm that the bottleneck is indeed KV Cache, not weight loading or computation itself.
- Prefer combination over replacement: Cross-layer sharing, GQA, KV quantization, and paged management operate on different dimensions. Combining them usually provides greater benefit than using one method alone.
- Pay attention to layer-to-slot mapping: Ensure that shared group boundaries align with cache allocation, prefix caching, speculative decoding, and other mechanisms to avoid invalid allocations and cache misalignment.
- Evaluation first: Memory benefits must be based on the premise that general capability, long-context capability, and business scenario evaluations show no regression.
- Edge-cloud collaboration: On edge devices, prefer lightweight models combined with cross-layer sharing; in the cloud, handle long-context and high-concurrency tasks. The two should connect through a unified interface layer.
8. Conclusion
KV Cache is an unavoidable cost for long-context models. Cross-layer KV reuse represents an approach to reduce this cost at the structural level. It does not pursue extreme optimization at a single point. Instead, it lets a small number of layers build the historical view once and lets the remaining layers retrieve from it on demand, significantly reducing memory usage and decoding bandwidth pressure while maintaining generation quality.
From research prototypes to practical use in mainstream open-source models, the engineering maturity of this technique is improving rapidly. For developers, the key is not to memorize a specific model name, but to master the methodology: where is the bottleneck, which compression method should be used, and how should the result be validated. Applying this methodology to capacity planning, deployment architecture, and observability will help long-context capabilities move from “can run” to “run stably and run economically.”
