KV Cache Compression for Long-Input Workloads: Layered Causal Encoding and Cross-Layer Sharing
This article examines why KV cache compression becomes the central engineering problem in long-input, short-output workloads such as coding agents, code review assistants, and log analysis agents. It breaks down the workload into prefix encoding, incremental decoding, and context concatenation, then explains a layered inference design in which the first half of the layers acts as a causal encoder and the second half performs full decoding. It also details how cross-layer global cache sharing, reuse of retrieved key-value states, and lower storage precision combine to reduce cache size to roughly one quarter, along with practical guidance on capacity planning, prefix reuse, precision-versus-quality validation, observability, and general cloud capabilities on Baidu AI Cloud.
KV Cache Compression for Long-Input Workloads
1. The Problem: Why Reading Costs More Than Writing
In scenarios like intelligent coding tools, code review assistants, and log analysis agents, a single task often shows an extremely asymmetric read/write ratio. After the tool modifies a few files, tens of thousands of words of source snippets, test output, stack traces, and dependency lists have to be pushed back into the context. What the model finally produces, however, may be only a few hundred words of change notes or the next instruction.
This workload has three characteristics:
- Very long input: the prefill stage must process tens of thousands of tokens or more in one pass.
- Frequent continuation: context is appended repeatedly between multi-turn tool calls, so the historical prefix is recomputed over and over.
- Very short output: the number of tokens generated during decode is far smaller than the input size.
Traditional inference systems usually optimize for generation throughput, but in these scenarios the bottleneck shifts to prefill compute and KV cache capacity. When the cache cannot hold everything, swapping, recomputation, or truncation kicks in, directly raising latency and cost. Compressing the KV cache without noticeably hurting quality therefore becomes the key engineering problem for long-context inference.
2. Workload Profile: Long Input, Short Output, Multi-Turn Continuation
The resource consumption of one agent run can be split into three phases:
- Prefix encoding: causal encoding of the system prompt, tool definitions, conversation history, and retrieval results.
- Incremental decoding: token-by-token generation based on the already cached key-value states.
- Context concatenation: appending tool output to the tail of the prefix and entering the next round.
When the second and third phases are triggered repeatedly, the prefix gets “read” many times. If the cache is stored at full precision and independently per layer, memory usage grows linearly with the number of layers, sequence length, and concurrent sessions. Common mitigations in the industry include paged cache management, prefix reuse, quantized compression, and cross-layer sharing; this article focuses on the combined effect of the last two.
3. Layered Inference Structure: Causal Encoding Up Front, Full Decoding at the Back
One approach worth attention is to split the deep network into two parts with different responsibilities:
- Front segment (causal encoder): about half of the layers, responsible for compressing the long input into a compact representation.
- Back segment (decoder): the other half of the layers, responsible for full decoding on top of the compressed representation.
The runtime strategy then diverges:
Processing long input (prefill):input -> [front-segment causal encoding] -> compact state -> write to global cacheGenerating a new token (decode):compact state -> [front segment + back segment full network] -> next token
The benefit is that long input only travels “half the distance,” so prefill compute and memory access drop significantly, while the generation stage keeps full depth and avoids over-reducing expressive power. The cost is higher implementation complexity: representation alignment between the two segments and consistent training objectives must be guaranteed.
4. Why the KV Cache Can Drop to One Quarter
Compressing more lightly along the sequence dimension while cutting the cache substantially usually comes not from a single trick but from three effects stacking up:
- Cross-layer sharing of a global cache: layers no longer each keep their own copy of the keys and values but reuse the same global state, so storage falls as the layer count factor shrinks.
- Reuse of retrieval results in some layers: in retrieval-augmented scenarios, the key-value states for matched snippets are reused directly across layers, reducing duplicate writes.
- Lower storage precision: the cache is kept at low precision, and combined with paging and quantization strategies this compresses the byte count further.
Roughly speaking:
total cache ≈ sequence length × hidden dimension × layer count × bytes per element × concurrency
Sharing reduces the “layer count” factor and low precision reduces the “bytes per element” factor; multiplying the two yields a several-fold reduction. It is worth stressing that such gains depend on the specific model architecture and training recipe and cannot be simply extrapolated to any model.
5. Engineering Implementation Points
- Capacity planning: estimate memory as peak concurrency × average context length × cache bytes per token, and leave headroom for swapping.
- Prefix reuse: place the system prompt, tool definitions, and stable retrieval results in a fixed prefix region to maximize hit rate.
- Balancing precision and quality: validate whether low-precision caching degrades tasks such as long-document understanding and code completion using evaluation sets.
- Observability: track cache hit rate, swap counts, and prefill latency in the monitoring and alerting system.
- Complementary general cloud capabilities: combine container platforms for elastic scaling, object storage for saving session snapshots, and log services plus monitoring and alerting to locate long-tail requests.
6. General Recommendations from Practice on Baidu AI Cloud
To deploy a similar approach on Baidu AI Cloud, rely mainly on combinations of general capabilities: use a container platform to host inference services and scale with load, use object storage to archive long-context sessions, and use log services with monitoring and alerting to observe cache metrics. On the model side, first evaluate whether layered encoding, cross-layer sharing, and low-precision caching match the business workload, validate quality and latency with a small-scale canary, then ramp up gradually.
7. Conclusion
The core tension of long-input workloads is that the cost of “reading” is amplified repeatedly by multi-turn continuation. Layered causal encoding lowers prefill overhead, while cross-layer sharing and low-precision storage shrink the cache footprint; only the combination preserves long-context capability under limited memory. For developers, the key is not chasing a single trick but designing the workload profile, cache strategy, and observability system together, which is what delivers stable gains in real scenarios such as intelligent coding.
