Optimizing Long-Context KV Cache: Encoder-Decoder Split and Cross-Layer Sharing
In AI agent applications characterized by "read-heavy, write-light" workloads, traditional autoregressive inference causes significant resource misallocation by processing all tokens through the entire network depth. This article explores an optimization strategy that splits the model depth into a causal encoder and decoder, allowing long inputs to traverse only half the network. Combined with cross-layer KV cache sharing and reduced storage precision, this approach compresses the global KV cache to approximately one-quarter of its original size, significantly reducing memory footprint and inference latency.
Long-Context KV Cache Optimization: Encoder-Decoder Split and Cross-Layer Sharing Practices
1. The Problem: Why Agent Workloads Are “Read-Heavy, Write-Light”
In AI agent applications such as automated programming, document analysis, and log diagnostics, a typical execution loop looks like this: a tool modifies a file, and the model must read back tens of thousands of words of source code, test outputs, and call logs, only to ultimately generate a few hundred words of instructions for the next step. In such cycles, the computing and memory resources consumed by “reading” often far exceed those consumed by “writing.”
These types of workloads share three distinct characteristics:
- Extremely long inputs: The concatenated context per turn can reach tens of thousands or even hundreds of thousands of tokens;
- Very short outputs: Decision-based outputs typically consist of only a few dozen to a few hundred tokens;
- High-frequency context reuse: Between adjacent turns, the majority of the prefix content is identical, with only incremental parts being new.
Traditional autoregressive inference architectures treat all tokens equally: whether it is an input or an output, every token must pass through all network layers. This creates a clear resource mismatch in “read-heavy, write-light” scenarios—massive computing power is consumed on full-depth encoding of long inputs, and these intermediate layer results may not even be fully utilized in subsequent generation.
The optimization approach discussed in this article directly targets this pain point: splitting the network along its depth into a “causal encoder + decoder” structure, where long inputs only traverse the first half, and generation traverses the full network; simultaneously sharing the KV cache across layers and reducing cache storage precision. In empirical tests, this combination compresses the global KV cache to approximately one-quarter of unshared approaches.
2. Fundamentals: Where KV Cache Comes From and Why It’s So Large
2.1 Attention Computation and the Inevitability of Caching
Language models split text into tokens, and each token is mapped into Query (Q), Key (K), and Value (V) vectors at every layer. Intuitively, Q is the “question” posed by the current position, K measures the relevance between historical positions and the current position, and V carries the actual information to be read back. The core computation of single-head attention can be written as:
o = softmax(q · Kᵀ / √c) · V
Where q is the current query vector, K and V contain the keys and values of all visible historical positions, c is the channel dimension, softmax normalizes the relevance scores into weighting coefficients, and o is the weighted read-back result.
The key to autoregressive generation is that once the K and V of historical tokens are computed, they never change. Therefore, inference systems cache them to avoid recalculating the entire history every time a new token is generated. This is the KV cache.
2.2 Estimating Cache Scale
If each layer independently stores a copy of K and V, the total cache size can be estimated as:
Total bytes ≈ 2 × num_layers × seq_len × kv_dim × bytes_per_element
Consider a configuration with 40 layers, a KV dimension of 512 per layer, a sequence length of 100,000 tokens, and 2-byte floating-point storage. The cache size will reach the tens of gigabytes (GB) range. It is evident that cache size scales linearly with number of layers, sequence length, and storage precision—these three factors are the exact entry points for subsequent optimization: either reduce the number of independently stored layers or compress the storage overhead per element.
2.3 The Hidden Cost: Bandwidth Over Capacity
It is worth emphasizing that the pressure of the KV cache is reflected not only in memory capacity but also in memory bandwidth. For every token generated, the decoding phase must read K and V from the entire historical cache to participate in attention computation. For long sequences, inference is often memory-bound rather than compute-bound. Therefore, compressing the KV cache offers dual benefits: it frees up memory to support longer contexts or higher concurrency, and it directly reduces the read latency per generation step.
3. Architecture Design: Half Journey for Input, Full Journey for Generation
3.1 Depth Split of Encoder-Decoder
This approach divides a 40-layer network into two functional segments:
- First 20 layers: Causal Encoder. Maintains causal masking (each position can only attend to previous positions) and is responsible for encoding the long input into a compact intermediate representation;
- Last 20 layers: Decoder. Receives the encoder’s output and is responsible for autoregressively generating new tokens.
The workflow is as follows: when processing a long input, tokens primarily flow through the first half (the encoder), and the intermediate representation produced serves as the context foundation for subsequent decoding; when generating new tokens, the new token still traverses the full 40-layer network, ensuring that generation quality is not compromised.
The rationale for this design comes from an empirical observation: in deep networks, lower layers primarily handle local syntax and surface feature extraction, while higher layers handle semantic integration and decision-making. For input tokens that are “only read, not generated,” half-journey encoding is sufficient to provide the context signals required by the decoder; for tokens “to be generated,” full depth ensures the precision of the output distribution.
3.2 Difference from Traditional Prefill-Decode Separation
A common inference optimization in the industry is the scheduling separation of “prefill and decode,” which allocates the two phases to different resources at the system level. The split discussed in this article goes a step further; it is a structural split at the model architecture level: input tokens structurally bypass the latter half of the network. This brings two additional benefits:
- The computation volume during the prefill phase drops directly, significantly reducing the latency and cost of processing long inputs;
- Input tokens do not generate intermediate activations in the latter half, creating conditions for subsequent cross-layer cache reuse.
It is important to note that structural splitting requires alignment during the training phase to match the encoder’s output distribution with the decoder’s input distribution. It is not a simple “amputation” of an already trained dense model. This is the fundamental difference between it and purely inference-side optimizations.
3.3 Simplified Inference Flow Illustration
def forward(input_ids, mode, kv_cache):if mode == "prefill":# Long input only passes through the encoder halfhidden = encoder_layers(input_ids) # First 20 layerskv_cache.write_encoder(hidden) # Write to shared cachereturn hiddenelse:# Generation phase passes through the full networkhidden = encoder_layers(input_ids) # First 20 layershidden = decoder_layers(hidden, kv_cache) # Last 20 layers, read shared KVkv_cache.append(hidden) # Append new token's KVreturn sample(hidden)
4. The Quarter-Sized Cache Mystery: Sharing and Quantization
A seemingly contradictory phenomenon is that while the new architecture’s compression along the sequence dimension is not particularly aggressive, the global KV cache is reduced to about a quarter of previous generation schemes. The saved space mainly comes from two orthogonal dimensions.
4.1 Dimension One: Cross-Layer Sharing of Global KV Cache
In traditional implementations, each attention layer holds an independent copy of K and V. The sharing approach allows multiple decoder layers to reuse the same global KV, and some layers even share the intermediate results of attention retrieval. The intuitive basis is that adjacent layers have highly correlated judgments on “which historical positions are important.” Rather than each storing redundant copies, it is more efficient to let a group of layers share a single key-value table, with each layer retaining only lightweight private projection parameters.
Assuming 20 decoder layers originally stored their own copies, changing to one shared copy per 5 layers brings about a 4x compression in the layer dimension alone. The trade-off for sharing is a slight decrease in expressive power. In practice, grouped sharing (e.g., groups of 4 to 8 layers) is often used to strike a balance between compression ratio and quality, and the model is trained to adapt to the shared structure.
4.2 Dimension Two: Lower Cache Storage Precision
The second source of compression is the quantized storage of the KV cache. Reducing the cache from 16-bit floating-point to 8-bit or even 4-bit integer representations can linearly halve memory and bandwidth overhead. Key engineering practices include:
- Group Quantization: Maintaining scaling factors per channel or per token group to prevent extreme values from degrading overall precision;
- Mixed Precision Strategy: Retaining high precision for recently generated, high-attention-weight tokens, and using low precision for distant historical tokens;
- Quantization-Aware Training (QAT): Simulating low-precision reads during the training phase to make the model robust to quantization noise, avoiding the quality collapse caused by offline quantization.
4.3 The Multiplicative Effect of the Two Dimensions
Cross-layer sharing and lower precision have a multiplicative, rather than additive, relationship: sharing reduces the “number of copies,” and quantization reduces the “size of each copy.” Combined, they explain the roughly one-quarter total compression. This also prompts engineering teams that when evaluating cache optimization schemes, they should separately account for the contributions of the layer dimension, sequence dimension, and precision dimension, and then verify the end-to-end quality after combination, rather than looking at any single technique in isolation.
5. Engineering Implementation: Evaluation and Adoption in Production
5.1 Profiling the Benefits
Before introducing such an architecture, it is recommended to first quantify three metrics of your workload:
- Input/Output Length Ratio: The higher the ratio (e.g., greater than 20:1), the more obvious the benefit of half-journey encoding;
- Prefix Reuse Rate: The more overlap in adjacent request prefixes, the greater the value of cache reuse;
- Concurrency and Context Length Targets: The degree of memory constraint determines the actual benefit of cache compression.
Typical beneficiary scenarios include repository-level code Q&A, long log inspection agents, multi-turn tool-calling pipelines, and long-document structured extraction. Conversely, if the business primarily involves “short input, long generation” (such as creative writing tasks), the advantages of this architecture will be significantly diminished.
5.2 Deployment Infrastructure
This type of architecture places specific requirements on inference infrastructure. Deploying it on a cloud platform typically requires the coordination of the following general capabilities:
- Elastic Inference Compute: Long-context prefilling exhibits bursty computing characteristics, requiring compute resources to scale on demand;
- High-Speed Cache and Object Storage: Persisting cross-session historical prefix caches to avoid re-encoding during session recovery;
- Monitoring, Alerting, and Logging Services: Establishing observation baselines for cache hit rates, time-to-first-token, and per-request memory usage to promptly identify long-tail quality issues caused by the shared structure;
- Gradual Rollout Mechanism: Structural changes affect the generation quality distribution. Releases should be gradual with small traffic increments, combined with manual evaluation sets.
Taking Baidu AI Cloud’s general cloud services as an example, teams can deploy model inference services on elastic compute, use object storage to host persistent prefix caches, and build quality dashboards using log services and monitoring alerts to form an “inference-observation-tuning” closed loop. It must be emphasized that specific selections should be based on benchmark testing of your own workload characteristics, rather than relying on vendor-claimed metrics.
5.3 Quality Regression Evaluation Checklist
The risks of structure-compression optimizations are concentrated on the quality side. It is recommended to cover at least the following evaluation items:
- Recall accuracy in long-context retrieval benchmarks (such as needle-in-a-haystack tests);
- The quality decay curve from turn 1 to turn N in multi-turn continuation scenarios;
- Perplexity and downstream task score differences before and after enabling quantization;
- Behavioral stability at extreme length boundaries (when the cache is nearly full or prefixes are truncated).
6. Conclusion and Future Outlook
Returning to the original question: if input only travels half the journey, how can the KV cache still drop to a quarter? The answer lies in the superposition of two independent optimizations—in the depth dimension, the encoder-decoder split exempts long inputs from full-depth computation, reducing intermediate states at the source; in the storage dimension, multi-layer sharing of the global KV cache eliminates redundant inter-layer copies, and low-precision quantization further compresses the volume of each copy. Multiplied together, they achieve a significant magnitude of cache reduction without aggressive sequence compression.
The takeaway for engineering teams is that KV cache optimization is not a single-point technology, but a co-design of “model architecture × storage precision × system scheduling.” When evaluating any compression scheme, you should first characterize the input-output ratio and prefix reuse features of your workload, then separately account for the benefits across the layer, sequence, and precision dimensions, and finally safeguard the quality baseline through strict gradual rollouts and regression evaluations. As AI agent applications evolve towards longer contexts and higher-frequency tool calls, this approach of “customizing model architecture for workload characteristics” is expected to become an important direction for inference efficiency optimization.
