KV Cache Sharing Across Layers: How to Save Memory for Long-Context Inference
KV Cache grows linearly with context length and can quickly exhaust GPU memory when serving long-context requests. This article explains how KV Cache memory is calculated, how techniques like GQA and cross-layer KV sharing (CLA, YOCO) reduce it, how the benefits differ between Dense and MoE models, and provides practical deployment checklists for both edge devices and cloud serving.
Why Long Contexts Consume So Much Memory
Large language models (LLMs) generate tokens one at a time. For each new token, the attention mechanism needs to read the Keys and Values of all previous tokens. Recomputing them at every step would be prohibitively expensive, so inference frameworks store these intermediate results — this stored data is the KV Cache.
KV Cache size scales proportionally with context length. Extending the context from 4K to 128K tokens makes the cache 32 times larger. When serving multiple users, each request carries its own KV Cache, and memory pressure builds up even faster.
Doing the Math: How Much Memory Does KV Cache Use
The bytes consumed per token can be estimated with this formula:
Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per value
The factor of 2 accounts for storing Keys and Values separately.
As an example, consider a roughly 7B-parameter model with multi-head attention (MHA): 32 layers, 32 KV heads, head dimension of 128, and FP16 precision (2 bytes per value). Plugging in the numbers: 2 × 32 × 32 × 128 × 2 = 524,288 bytes, or about 512 KB per token. A context of 128K tokens would require roughly 64 GiB — enough to fill an 80 GB GPU with a single request, before even counting the model weights.
This formula is the basis for every comparison that follows. Each optimization works by reducing one of its factors.
GQA: Reducing the Number of KV Heads
In MHA, every Query head has its own Key and Value heads. Grouped-Query Attention (GQA) lets a group of Query heads share the same set of KV heads, shrinking the KV Cache by this ratio:
KV Cache ratio = number of KV heads ÷ number of Query heads
For example, with 32 Query heads and 8 KV heads, the KV Cache drops to one quarter of its original size. The same 128K-token context would then require 16 GiB instead of 64 GiB.
Multi-Query Attention (MQA) is the extreme form of GQA, where all Query heads share a single KV head. It compresses the most, but the quality loss is usually more noticeable. GQA strikes a balance between the two and is adopted by many mainstream open-source models.
GQA only reduces the number of KV heads per layer — the layer count stays the same. Total KV Cache still grows linearly with context length, so tasks involving hundreds of thousands of tokens require additional techniques.
Cross-Layer Sharing: Letting Adjacent Layers Reuse One KV Cache
In a standard Transformer, every layer maintains its own KV Cache. The idea behind cross-layer sharing is to have groups of adjacent layers share the same Keys and Values: only some layers actually compute and store KV, while the others simply read it. This compresses the KV Cache along the layer dimension.
There is already relevant research in this area. Brandon et al. proposed Cross-Layer Attention (CLA) in 2024, which lets adjacent layers share KV-related projections. According to their paper, when combined with multi-query attention, KV Cache can be reduced by roughly another half. Another work, YOCO (You Only Cache Once, 2024), uses a decoder-decoder structure where only part of the model caches KV once, and subsequent layers reuse it repeatedly. In the past couple of years, some open-source models have also begun adopting similar designs — refer to each model’s official technical report for implementation details.
When applying this approach, keep the following in mind:
- How layers are grouped affects model quality. Which layers share, and how many, must be determined through experiments.
- Whether the Keys and Values themselves are shared, or only the projection parameters, differs across approaches — verify each one individually.
- This kind of structure generally needs to be fixed during training. Retrofitting an already-trained standard model usually requires continued training or fine-tuning, followed by re-evaluation.
- Sharing may cause some information loss. Whether that is acceptable should be validated with long-context benchmarks such as Needle In A Haystack, RULER, and LongBench, together with real samples from your own workload.
Dense vs. MoE: Different KV Savings Profiles
Dense models use all of their parameters in every forward pass. They offer a higher quality ceiling, mature post-training and fine-tuning workflows, and suit teams that prioritize quality or need deep customization.
MoE (Mixture of Experts) models use a routing mechanism to activate only a subset of expert networks per computation. Their per-pass compute is lower, but total parameter count is large — all expert weights must be kept in GPU or host memory, and routing tuning is more complex.
| Dimension | Dense model | MoE model |
|---|---|---|
| Parameters used per forward pass | All parameters | A subset of experts |
| Primary memory pressure | Weights and KV Cache | Mostly expert weights; KV Cache share rises with long contexts |
| Direct benefit of cross-layer sharing | Significantly reduces long-context memory | Reduces only the KV portion; expert weights need separate solutions |
| Post-training and fine-tuning | Mature workflows | Routing tuning is more complex |
| Best suited for | Quality-first, heavy customization | Throughput-first, large parameter counts |
One important distinction: KV Cache size is determined by the number of attention layers and KV heads, not by the number of experts. Memory saved through cross-layer sharing only translates into direct gains when used for larger batch sizes or longer contexts. Using that freed space to load more experts requires the inference framework to support expert offloading or distributed deployment — otherwise the benefit is limited.
Edge Deployment: A Long-Context Checklist for Small Models
Edge devices can typically only run models of a few billion parameters, such as around 3B. Follow these steps when deploying:
- Define the target context length first, for example 16K or 32K, then use the formula above to estimate KV Cache requirements.
- Quantize the weights to INT4 or INT8. The KV Cache can use FP8 or INT8, but quantization affects quality, so test on your target tasks.
- Choose a lightweight inference framework that supports GQA and KV quantization, such as llama.cpp or MLC LLM, and confirm your chosen model architecture is supported.
- Set a maximum context limit. Beyond it, truncate or summarize in segments to avoid out-of-memory (OOM) errors at runtime.
- Monitor peak memory usage, time-to-first-token, tokens generated per second, and device temperature and power consumption.
