Cross-Layer KV Tensor Reuse: How to Save VRAM and What to Check Before Deployment
This article explores how cross-layer reuse of Key and Value (KV) tensors in Large Language Models can significantly reduce VRAM consumption. It covers the fundamentals of KV Cache, compares MHA, GQA, and MQA, and details the mechanisms, mathematical savings, and deployment considerations of cross-layer reuse. A six-point checklist is provided to guide engineers through pre-deployment validation.
1. Why KV Cache Consumes VRAM
Large Language Models generate tokens sequentially. When generating a new token, the attention layer must read the Key and Value vectors of all previous tokens. Recomputing the Key and Value of the historical context at every step would cause the total computation volume to grow rapidly with sequence length, resulting in unacceptable speeds. Inference systems therefore cache the computed Keys and Values in VRAM for subsequent steps to read directly. This cache, known as the KV Cache, trades VRAM for computation time.
The size of the KV Cache is determined by four factors: sequence length, the number of concurrent requests, the number of model layers, and the number of KV heads and head dimension per layer. Longer contexts require larger caches. Each concurrent request maintains its own cache. Every layer must independently store its own Keys and Values.
When calculating, it is important to distinguish two metrics. The KV Cache size per token is calculated as:
Per token size = 2 × layers × KV heads × head dimension × bytes per element
The KV Cache size for a single sequence is the above result multiplied by the sequence length:
Single sequence size = per token size × sequence length
The coefficient 2 accounts for the two separate tensors for Key and Value. To estimate a 128K context (131,072 tokens), multiply the per token size by 131,072. When running multiple requests simultaneously, multiply further by the number of concurrent requests. This formula does not include batch alignment and framework overhead, so actual usage is typically higher.
In scenarios such as long-document comprehension, multi-turn tool calling, and long chains of thought, the context can reach tens or even hundreds of thousands of tokens. In these cases, the KV Cache often becomes the primary bottleneck limiting context length and concurrency.
2. Three Approaches and What They Compress
The earliest Multi-Head Attention (MHA) equipped each query head with an independent Key and Value head. The KV Cache scales proportionally with the number of heads, resulting in maximum VRAM overhead. Two subsequent approaches emerged to reduce the number of KV heads.
| Approach | Compressed Dimension | Number of KV Heads (e.g., 32 query heads) | Main Trade-off |
|---|---|---|---|
| MHA | None | 32, same as query heads | Maximum VRAM overhead |
| GQA | Number of KV heads | 8, query heads divided into 4 groups, each sharing 1 group of KV heads | A compromise between VRAM and quality |
| MQA | Number of KV heads | 1, all query heads sharing the same group of KV heads | Noticeable impact on model quality |
MQA allows all query heads to share a single group of KV heads. GQA divides query heads into several groups, with heads within a group sharing a set of KV heads. Both compress the number of KV heads, while the head dimension D typically remains unchanged. GQA is now widely used in many mainstream open-source models.
GQA only compresses the number of KV heads. Each layer still needs to independently store its own KV tensors, meaning the overhead along the layer dimension is not reduced. Cross-layer reuse specifically targets this aspect.
3. Cross-Layer Reuse: Compressing Along the Layer Dimension
Cross-layer reuse is based on an observation: the KV states of adjacent layers often exhibit a certain degree of similarity. Subsequent layers can utilize the KV results already computed by previous layers, eliminating the need to generate and cache their own. Specific implementations vary across different research papers.
Some methods allow adjacent layers to share KV projections, meaning a group of layers caches only a single KV tensor. Other methods, such as YOCO, allow the majority of layers to read from the same global KV cache. Both approaches reduce the number of KV tensors that need to be stored, but their structures differ; they should not simply be understood as subsequent layers directly copying the tensors of preceding layers. When reading papers or model cards, it is necessary to confirm which design is being used.
Specifically, the model’s L layers are divided into several groups, each containing N layers. Ideally, the effective number of KV layers drops from L to L/N, yielding a theoretical reduction ratio of 1/N.
If L is not perfectly divisible by N, the last group will have fewer than N layers. In this case, the effective number of KV layers becomes ceil(L/N), and the cache ratio is no longer strictly 1/N; it must be calculated based on the actual number of groups. For example, when L=30 and N=4, the effective number of KV layers is ceil(30/4)=8, not 7.5. Regardless, the first layer of each group must still compute and cache KV; this overhead cannot be saved through sharing. How the final group is handled must be explicitly defined in the structural design.
Several boundary conditions must be kept in mind:
- Shared layers still retain their own query projections and output projections.
- If the sharing scheme also shares KV projections, the KV projection parameters in the model will be reduced. If only the cache layout is changed without sharing projections, the parameter count remains the same.
- Attention computation for shared layers still occurs; the primary saving is in VRAM. How much computation is saved depends on the specific implementation.
- Cross-layer reuse requires the shared structure to be adopted during training.
Academic research has already explored this area. In 2024, Brandon et al. published “Reducing Transformer Key-Value Cache Size with Cross-Layer Attention,” proposing Cross-Layer Attention, which allows adjacent layers to share KV projections. The paper reported further KV Cache reductions when combined with MQA and GQA. Specific experimental setups and figures should be verified against the original paper. In the same year, a Microsoft research team published “You Only Cache Once: Decoder-Decoder Architectures for Language Models,” proposing the YOCO architecture, which allows most layers to reuse the same global KV cache.
Models already trained with a standard structure cannot directly enable sharing during inference. The representations between layers would deviate from their training distribution, likely causing a noticeable drop in quality. To utilize this technology, the model must adopt a shared structure during training or undergo specialized modifications and continued training.
4. Crunching the Numbers
Let’s demonstrate the calculation using a hypothetical configuration. The model has 32 layers, 32 attention heads, a head dimension of 128, uses FP16 storage (2 bytes per element), and has a context length of 131,072 tokens (128K).
- Standard MHA: Per token = 2 × 32 × 32 × 128 × 2 = 524,288 bytes (512 KiB). 128K context: 512 KiB × 131,072 = 64 GiB.
- GQA with 8 KV heads: Per token = 2 × 32 × 8 × 128 × 2 = 131,072 bytes (128 KiB). 128K context: 128 KiB × 131,072 = 16 GiB, which is one-quarter of MHA.
- GQA with cross-layer reuse, sharing group size of 2: Effective KV layers = 32 / 2 = 16. Per token = 2 × 16 × 8 × 128 × 2 = 65,536 bytes (64 KiB). 128K context: 64 KiB × 131,072 = 8 GiB.
By multiplying the two compression dimensions, the final VRAM drops to one-eighth of MHA. If running four 128K requests simultaneously, the KV Cache for GQA with cross-layer reuse is approximately 32 GiB. This calculation ignores batch alignment, model weights, activations, and framework overhead, serving only to illustrate the magnitude of the compression effect.
During actual deployment, you must also verify whether the inference engine allocates VRAM according to the shared layout. If the engine still allocates independent caches for each layer, the numbers above do not hold. You can compare the actual VRAM usage after startup under the same configuration with the formula’s result to verify empirically.
5. Benefits and Constraints in Three Deployment Scenarios
Mobile and Embedded Devices. Edge-side memory is typically very constrained. A smaller KV Cache allows the same device to support longer contexts or run larger models under the same context. Whether this benefit can be realized depends on whether the edge inference engine correctly supports the shared memory layout.
High-Concurrency Server-Side Inference. On the server side, VRAM directly determines how many concurrent sequences a single accelerator card can hold. A smaller KV Cache allows for higher concurrency, thereby increasing throughput. This effect has a prerequisite: VRAM must be the current bottleneck. If the bottleneck is computation or scheduling, the gains from compressing the KV Cache will be limited. Profiling should be done before going live to confirm that VRAM is indeed the limiting factor. Engine optimizations such as paged memory management and continuous batching can complement this approach.
Ultra-Long Context Applications. For codebase comprehension or lengthy legal document analysis targeting millions of tokens, the KV Cache is often the hardest hardware barrier to break. Cross-layer reuse can be combined with quantization, sparse attention, and other methods. The quality of the combined approach must be individually validated on specific tasks; the quality losses from different compression methods cannot simply be added together.
6. A Six-Point Pre-Deployment Checklist
Verify the model source. Check the model card or technical report to confirm whether the model was trained with a cross-layer shared structure. Models not trained with a shared structure cannot have sharing enabled simply by modifying the configuration.
Determine the sharing ratio. First measure the baseline VRAM usage and task quality, then start by trying 2 layers per group, moving to 4 layers per group if results are stable. At each step, record long-document retrieval accuracy, tool calling success rate, and throughput. A larger sharing ratio saves more VRAM but carries a higher quality risk. If any metric falls below a preset threshold, revert to the previous ratio.
Verify the inference engine’s shared layout support. Confirm that the engine can allocate the KV cache according to the shared structure, rather than allocating independent space for each layer. Compare the actual peak VRAM usage before and after compression under the same configuration, and compare it with the formula estimate. If the discrepancy is large, first check whether the engine is ignoring the sharing configuration.
Conduct quality evaluation. Evaluate on real business data rather than relying solely on public leaderboards. The evaluation should include long-context QA, multi-turn tool calling, and long reasoning tasks, compared item by item with the uncompressed baseline model. If combined with other compression methods, evaluate the combined results separately.
Confirm the bottleneck. Use profiling to confirm that the current bottleneck is indeed VRAM. If the bottleneck is computation or scheduling, optimize those areas first before considering KV Cache compression.
Prepare a rollback plan and live monitoring. Retain the uncompressed baseline model to ensure you can switch back at any time. Use a gradual rollout for release, incrementally increasing the traffic ratio. Monitor peak VRAM, OOM occurrences, p99 latency, throughput, and quality sampling scores. If any metric exceeds its threshold, roll back immediately and log the reason.
Only after completing these six checks should you decide whether to expand the deployment scope.
