Cross-Layer KV Cache Sharing for Long-Context Inference
Long-context agent workloads often spend more resources processing inputs than generating outputs. This article explains how partial-depth input encoding, cross-layer KV cache sharing, and lower-precision storage can reduce that overhead. It also covers cache lifecycle management, capacity planning, validation, and the limits of these approaches for workloads that require precise access to source code, logs, and tool results.
Long-context inference is not simply a matter of increasing the context window. In a single turn, a coding agent may read source files, test logs, and tool outputs, then generate only a short patch or a few hundred words of instructions. The next turn appends new material to the context and repeats the process.
The compute and GPU memory spent on “reading” can easily exceed the resources spent on “writing.” Making these workloads reliable requires more than adding a larger cache. It requires separating the computation that must process the full history, the state that can be reused across layers, and the data that can be stored at lower precision.
Why Attention Creates Such a Large Cache
Text is first divided into tokens. Each token acquires a hidden representation at every layer. Attention allows the current position to look back over the visible history: the query vector Q represents what the current position needs, keys K determine which historical positions are relevant, and values V carry the content retrieved from those positions.
For a single query and attention head, scaled dot-product attention can be written as:
o = softmax(q K^T / sqrt(d)) V
Here, q is the current query, K and V cover t historical positions, and d is the head dimension. Softmax converts relevance scores into attention weights.
When the model generates another token, it does not need to recompute all the keys and values for previous positions. Instead, the system retains them in a KV cache.
Cache size grows roughly with:
number of layers × sequence length × number of heads × head dimension × storage precision
With many layers and a long context, generating even one token requires accessing information from a substantial history.
An inference request therefore has two distinct phases:
- Prefill processes the existing input sequence.
- Decode generates new tokens autoregressively.
Prefill consumes compute and cache-write capacity across the input sequence. Decode depends on the bandwidth and latency of repeatedly reading cached state. For workloads that read much more than they write, optimizing prefill and cache layout can matter more than accelerating the decode kernel alone.
Partial-Depth Encoding: Long Inputs Need Not Traverse the Entire Network
One architectural approach divides a deep network into two stacks with different responsibilities. The earlier stack acts more like a causal encoder, converting long inputs into reusable state. The later stack acts more like a decoder; during generation, both stacks participate so that new tokens traverse the full network.
When processing input-only tokens, the model primarily activates the earlier stack and writes keys and values into a shared cache. Once generation begins, new tokens still pass through the full depth to preserve the representational capacity available at each generation step.
The intuition is that many tokens in a long context exist to be read later, not to produce an immediate continuation. If every layer independently processes and stores the entire history, cache size grows linearly with depth even though many layers encounter highly correlated contextual information.
Separating “building the index” from “making the decision” allows prefill to skip later-stage computation that primarily serves generation, without limiting generated tokens to a shallow encoder.
Three engineering constraints matter:
- Preserve causal masking. The encoder must not see future tokens. Otherwise, the cached state used for continuation will conflict with the model’s training assumptions.
- Keep the interface between stacks stable. The later stack must be able to consume the earlier stack’s hidden states, positional representations, and cache layout directly.
- Match the workload. The benefit is most pronounced when the input is much longer than the expected output. For long-form generation, the later stack still accounts for substantial work, diluting the savings from partial-depth prefill.
Cross-Layer Sharing: Reducing More Than Sequence Length
Sequence compression can reduce t by merging adjacent tokens, writing to the cache less frequently, or retaining only salient positions. But increasingly aggressive compression also loses detail. Code identifiers, line numbers, and stack traces are particularly sensitive to such losses.
Another approach is to reduce the number of independent copies of K and V.
If multiple layers use a global KV cache instead of maintaining a separate cache for every layer, cache growth with depth can be substantially reduced. Some layers may also reuse attention lookup results: positions identified as relevant by earlier layers do not necessarily need to be searched again in a completely independent key space. Later layers can instead apply lighter transformations to shared values.
This makes it possible to use more conservative sequence compression. Most of the memory savings then come from fewer cross-layer copies and lower storage precision.
Precision is the second lever. Inference caches can store K and V at a lower bit width than training activations, using narrower floating-point formats or integer approximations.
Keys and values have different sensitivities to error:
- Errors in keys affect whether attention finds the right positions.
- Errors in values affect how accurately the retrieved content is represented.
They should not automatically receive the same precision setting. Before lowering precision, evaluate perplexity, tool-call success rates, and patch compilation rates on representative continuation workloads—not just GPU memory usage.
Sharing also has limits. The representation spaces used by different layers are not always interchangeable. Forcing one set of keys to serve every layer may weaken deeper layers’ ability to distinguish fine-grained dependencies.
A more conservative design keeps most historical state in a global cache while allowing a small number of layers to retain private low-rank residuals or short-window caches. These supplement patterns that the shared representation does not adequately capture.
Managing the Cache Across the Request Lifecycle
An agent turn typically assembles system constraints, repository excerpts, and tool results, performs prefill, and decodes the next action. Executing that action produces new logs, which become part of the next continuation.
Cache management must follow this lifecycle rather than optimize only a single forward pass.
- Retain stable prefixes. System prompts and rarely changing repository indexes are suitable reusable prefixes. Frequently changing log tails are poor candidates for long-term retention.
- Track invalidation by range rather than clearing everything indiscriminately. File edits should trigger invalidation for affected cached ranges, avoiding unnecessary full-history prefill where reuse remains valid.
- Keep retrieval caches and attention caches separable. Retrieved excerpts must still follow the same causal and positional rules once they enter the context. Reusing relevance lookups means avoiding repeated work; it does not mean bypassing permission or visibility checks.
- Isolate concurrent sessions. Cross-layer sharing means sharing within the same request, not sharing different users’ histories. Cross-request reuse is appropriate only for explicitly identical prefixes that are permitted to be cached.
Capacity planning can use an order-of-magnitude estimate without relying on hardware marketing figures:
cache bytes ≈ layer-copy count × sequence length× key/value dimensions per token× bytes per element × batch size
When the design changes from one cache copy per layer to one global copy plus a small amount of private residual state, the dominant savings often come from the number of layer copies and storage precision—not from compressing the sequence until important details become unreadable.
As batch size increases, memory bandwidth can become the bottleneck before compute does. Cache layout should therefore favor contiguous access and alignment by head or sequence, rather than turning decode into a series of random reads.
Validating That the Savings Do Not Come from the Wrong Trade-Offs
Evaluate at least four categories of signals.
- Quality. Use a fixed task set to compare patch correctness, whether references point to real line numbers, and whether tool arguments are complete. A common regression after cache sharing or quantization is output that sounds fluent but identifies the wrong file.
- Cost. Measure prefill latency, per-token decode latency, cache occupancy, and GPU memory bandwidth separately. A single average token-latency metric can hide the cost of long inputs.
- Continuation stability. Append tool outputs over multiple turns and check whether cache hit rates decrease appropriately after edits. A cache that never hits is ineffective; a cache that continues hitting stale content is unsafe.
- Failure behavior. Truncate or summarize exceptionally long logs before they enter the context window, while retaining traceable references to the original text. Do not obtain cache savings by silently dropping tokens.
An illustrative cache key can include:
session, prefix version, layer group, precision, position range
A change to any component identifies a different cached state. Prefix versions should come from a digest of the input content rather than wall-clock time, so identical prefixes can be recognized and safely reused.
Where This Architecture Fits
Partial-depth encoding combined with cross-layer KV sharing is well suited to agents with long inputs, short outputs, and frequent context continuation.
It is not a universal default for every model or workload. Generation-heavy tasks, such as mathematical derivations and long-form writing, still incur the cost of full-depth processing and decode bandwidth. Aggressive sequence compression, excessively low key precision, or unversioned reuse across turns can turn memory savings into incorrect tool actions.
The practical sequence is to first measure the time spent in prefill versus decode and identify what accounts for the cache’s byte footprint. Then decide whether to reduce layer copies, lower storage precision, or apply modest sequence compression only to log-like tokens.
Validate each change against a reproducible task set, with particular attention to accurate source and error localization. The goal is an explainable cache architecture—not a reduction in memory usage whose consequences cannot be traced.
