Cross-Layer KV Reuse: A Guide to Memory Optimization for Long-Context Inference
Cross-Layer Attention (CLA) reduces KV Cache memory by letting some Transformer layers reuse the K/V tensors cached by earlier layers instead of computing their own. This article explains why long contexts exhaust GPU memory, how cross-layer KV sharing works, its benefits and trade-offs, a pre-deployment checklist, a reference implementation, accuracy evaluation methods, common pitfalls, and how CLA differs from MQA and GQA.
1. Why Long Contexts Exhaust GPU Memory
When a large language model generates text, every new token must attend to all previous tokens. To avoid recomputing the Keys and Values of historical tokens, the inference engine caches them — this is the KV Cache.
The size of the KV Cache can be estimated with the following formula:
KV Cache bytes = 2 × L × H_kv × D × S × B × P
Here, 2 accounts for the two tensors K and V, L is the number of layers, H_kv is the number of KV heads, D is the per-head dimension, S is the sequence length, B is the batch size, and P is the bytes per element (2 for FP16).
The formula shows that memory grows linearly with sequence length and batch size. Scaling the context from 4K to 128K grows the KV Cache 32x. With small models, large batches, or very long contexts, the KV Cache can exceed the size of the model weights themselves. On edge devices with limited memory, this problem is even more pronounced.
2. How Cross-Layer KV Reuse Works
In a standard Transformer, every layer independently computes and stores its own K and V. Cross-Layer Attention (CLA) changes this: some layers compute only their own Query, while their K and V are taken directly from the cache of an earlier source layer.
This design involves three kinds of layers:
- Source layers: compute and store K and V.
- Reuse layers: do not compute K or V; they read from a source layer’s cache.
- Independent Query layers: every layer keeps its own Query projection, because the Query determines which parts of the context that layer attends to.
If every two layers share one source layer, the number of KV layers that must be stored is halved. With one source layer per four layers, it drops to one quarter.
This idea has academic grounding. The 2024 preprint “Reducing Transformer Key-Value Cache Size with Cross-Layer Attention” proposed cross-layer KV sharing and discussed its feasibility. Its experimental results depend on specific model scales and training recipes, so refer to the original paper when citing them.
Some recent open-source models targeting edge devices have adopted similar KV-sharing designs in their architectures. For the specific model names, release dates, and performance figures, refer to the official technical reports from their publishers.
3. Benefits and Costs
The table below shows a worked example of how different sharing schemes affect KV Cache memory:
| Scheme | KV layers to store | Estimated KV Cache memory |
|---|---|---|
| Independent per layer (standard) | 32 | 4 GiB |
| Shared every 2 layers | 16 | 2 GiB |
| Shared every 4 layers | 8 | 1 GiB |
Example configuration: 32 layers, 8 KV heads, 128 dimensions per head, sequence length 32,768, batch size 1, FP16. The table counts only the KV Cache, excluding model weights and intermediate activations. With standard multi-head attention using 32 KV heads, the standard scheme at the same sequence length would require roughly 16 GiB of KV Cache.
Cross-layer reuse offers three main benefits:
- With lower memory usage, the same hardware can support longer contexts or larger batches.
- Edge devices gain a better chance of running models with long-text capabilities.
- Larger batches indirectly improve throughput and reduce compute cost per request.
The costs also need attention:
- Reuse layers cannot adjust their own K and V representations. On tasks that require precise cross-position retrieval or multi-hop reasoning, performance may degrade — the higher the compression ratio, the greater the risk.
- This structure usually must be adopted during training, or adapted through continued training. Directly modifying the inference code of a standard model typically leads to a noticeable drop in output quality.
Therefore, before deployment, first confirm whether the model weights were trained with a KV-sharing structure. The model configuration file usually specifies the layer-to-layer mapping.
4. Pre-Deployment Checklist
- Confirm the model configuration contains the KV mapping and that the weights match this structure.
- Check the documentation and issues of your inference framework’s current version to confirm whether it supports cross-layer KV. Support varies significantly across versions — do not rely on memory.
- Confirm that PagedAttention’s block tables allow multiple layers to reference the same physical blocks. If the framework does not support this, you need to share block tables between source and reuse layers.
- Confirm that during batch scheduling, each request’s KV mapping is not corrupted by batch merging.
- Stress-test maximum sequence length, maximum batch size, and peak memory; record the results and compare against the standard model.
- Keep the standard model or a previous version of the inference service available, with a rollback plan ready.
5. Inference Framework Modification Example
The following code demonstrates the core logic of cross-layer KV reuse. It is illustrative code: before integrating a real model, you need to replace it with concrete module implementations and add residual connections, normalization, MLP, and position encoding.
import torchimport torch.nn.functional as Fclass CrossLayerKVRunner:"""Illustrative code: manage cross-layer KV Cache via a layer mapping."""def __init__(self, kv_source):# kv_source[i] is the source layer whose KV is used by layer i.# A source layer satisfies kv_source[s] == s; a reuse layer must# reference a source layer with an index smaller than its own.self.kv_source = list(kv_source)self.num_layers = len(self.kv_source)self.kv_cache = {} # {source layer index: (K, V)}self._validate()def _validate(self):for i, s in enumerate(self.kv_source):if not (0 <= s < self.num_layers):raise ValueError(f"Layer {i}'s source layer {s} is out of range")if s > i:raise ValueError(f"Layer {i} cannot reference later layer {s}")if self.kv_source[s] != s:raise ValueError(f"Layer {s} is not a source layer; layer {i} cannot reference it")def reset(self):"""Call before each new request to clear that request's cache."""self.kv_cache.clear()def forward(self, hidden, layers, is_prefill):"""hidden: [B, T, C]. T is the prompt length during prefill and 1 during decode.layers: module for layer i, must provide q_proj, k_proj, v_proj, o_proj."""for i, layer in enumerate(layers):s = self.kv_source[i]# Every layer keeps its own Query projectionq = layer.q_proj(hidden) # [B, T, H, D]if s == i:# Source layer: compute new K, V and write to cachek_new = layer.k_proj(hidden) # [B, T, H_kv, D]v_new = layer.v_proj(hidden)if is_prefill or s not in self.kv_cache:self.kv_cache[s] = (k_new, v_new)else:k_past, v_past = self.kv_cache[s]self.kv_cache[s] = (torch.cat([k_past, k_new], dim=1), # append along the time dimensiontorch.cat([v_past, v_new], dim=1),)# Reuse layers read directly from the source layer's cache.# The source layer has already run this step, so the cache# includes the current token.k, v = self.kv_cache[s]# Transpose to [B, H, T, D]. With GQA, broadcast the KV heads# to the number of Query heads first.q_t = q.transpose(1, 2)k_t = k.transpose(1, 2)v_t = v.transpose(1, 2)# During decode there is only 1 Query, so no causal mask is neededout = F.scaled_dot_product_attention(q_t, k_t, v_t, is_causal=is_prefill)out = out.transpose(1, 2).flatten(2) # [B, T, H*D]hidden = hidden + layer.o_proj(out)# Post-residual normalization and MLP are omitted herereturn hidden
Three points in the code need attention:
_validatecan only check whether the mapping is legal; it cannot check execution order. Thereforeforwardmust execute layers in ascending order so that source layers write to the cache before reuse layers read from it.- During prefill, the KV of the entire prompt is written at once. During decode, only one token’s KV is appended per step.
- With GQA, there are fewer KV heads than Query heads, so the KV heads must be broadcast to the Query head count before computation.
In a real inference engine, you also need to map the above logic onto PagedAttention’s block tables and handle alignment across batched requests.
6. How to Evaluate Accuracy Loss
Do not rely on a single average score. The recommended evaluation steps are:
- Select a task set consistent with your business and compare output quality between the standard model and the shared model.
- Run long-context retrieval tests. For example, embed a fact in a long document and ask the model questions related to it.
- Run multi-hop reasoning tests. Cross-layer sharing may affect tasks that require retrieving information multiple times.
- Record the accuracy curve as a function of context length, and identify the length range where performance starts to degrade noticeably.
- Use A/B testing in production: validate with a small portion of traffic first, then ramp up gradually.
7. Common Mistakes
- A reuse layer reads stale cache. This usually happens because the source layer did not execute before the reuse layer.
- Under GQA, forgetting to broadcast KV heads, causing shape mismatches in matrix multiplication.
- Writing to the cache only during prefill, so the cache does not grow during decode and the generated content drifts away from the context.
- An incorrect mapping table where a reuse layer points to a non-source layer.
_validatecan catch this kind of error early. - Directly modifying the inference code of a standard model and expecting quality to remain unchanged.
8. Differences from MQA and GQA
MQA, GQA, and cross-layer attention address different dimensions of the problem:
- MQA (Multi-Query Attention): all Query heads within the same layer share one set of KV, reducing the number of KV heads within a layer.
- GQA (Grouped-Query Attention): Query heads are divided into groups, each sharing one set of KV — a middle ground between standard multi-head attention and MQA.
- CLA (Cross-Layer Attention): reduces KV storage across layers, cutting overhead along the layer dimension.
All three can be combined. A model can use both GQA and cross-layer sharing to further compress the KV Cache.
9. Risks and Summary
Cross-layer reuse can reduce the memory pressure of long-context inference, but it is not a free optimization. The higher the compression ratio, the more limited the expressiveness of reuse layers, and the greater the risk of errors on tasks that depend on precise retrieval. Before going live, run A/B tests on your target tasks and regression tests at maximum context length.
For developers, the most valuable part of this technique is understanding the memory composition of the KV Cache and using that understanding to assess optimization headroom. First confirm whether the model was trained with a shared structure, then verify framework support, and finally validate quality with your own task data. Following this order minimizes deployment risk.
