KV Cache Compression for Long-Context Inference: A Layered Architecture
Long-context workloads such as coding agents spend far more resources processing input than generating output. This article explains how KV caches contribute to that cost and examines an asymmetric architecture that combines partial-network prefill, full-network decoding, cross-layer cache sharing, and lower-precision storage. It also explores the trade-offs between compression and information retention, along with the deployment metrics developers should evaluate.
1. Why Reading Is Becoming the Inference Bottleneck
Coding agents often operate with highly asymmetric workloads. After modifying files, an agent may feed tens of thousands of words of source code, test logs, and tool output back into the context, only for the model to generate a few hundred words describing its next action. As these rounds accumulate, the compute and GPU memory costs of “reading” can become several times greater than those of “writing.”
This exposes a structural mismatch in conventional decoder architectures: input processing and output generation receive essentially the same treatment. Whether the model is processing existing context or generating a new token, it runs the full network and maintains attention state at the same scale. When inputs are much longer than outputs, that symmetry becomes inefficient.
KV cache memory can be estimated with a simple formula:
Cache size ≈ 2 × number of layers × sequence length × number of KV heads × head dimension × bytes per element
The factor of two accounts for the separate key and value tensors. The formula points to four main ways to reduce cache memory: reduce the number of cache-bearing layers, compress the sequence, share representations across heads or layers, and lower storage precision. Efficient inference architectures increasingly combine these approaches.
2. What a KV Cache Stores
After text is tokenized, each token produces a hidden representation at every Transformer layer. Attention retrieves information from the visible context, while the feed-forward network further processes the result.
Attention uses three core tensors:
- Q, or query: The retrieval request from the current position.
- K, or key: The representation used to determine which historical positions are relevant to the query.
- V, or value: The representation carrying the information retrieved from those positions.
In simplified single-head form, attention can be written as:
o = softmax(q · K^T) · V
Here, q is the current query vector, while K and V cover all visible historical positions.
The key observation is that the keys and values for historical positions can be reused when generating new tokens. Storing them avoids recomputing those representations. This stored state is the KV cache.
Longer sequences and deeper networks require larger caches. Even when generating just one token, attention must retrieve information from the relevant cached history.
An inference request therefore has two phases:
- Prefill: Processes the existing input in batches and builds the KV state. This phase is generally compute-intensive.
- Decode: Generates output one token at a time. This phase is generally memory-intensive, with cache access becoming a major bottleneck.
3. Separating Reading from Writing
The architectural approach examined here divides a 40-layer network by function: the first 20 layers act as a causal encoder, and the remaining 20 layers act as a decoder.
- During prefill: Only the first 20 encoder layers process the long input. The encoder does not depend on the later generation layers, allowing compressed representations to be constructed within this stage.
- During decoding: New tokens pass through all 40 layers, retaining the full generation path to preserve output quality.
The intent is to roughly halve the network-processing cost of reading while keeping the full network available for writing. This allocation is particularly attractive for agent workloads in which input processing greatly outweighs output generation.
The cache design adds two further measures:
- Global KV cache sharing across layers: Groups of neighboring layers share a global representation instead of maintaining separate full caches. Some layers also reuse intermediate attention retrieval results, reducing duplicate computation as well as storage.
- Lower-precision storage: The global cache uses low-bit quantization, providing approximately proportional memory savings as the number of storage bits decreases.
Together, these measures lead to a notable reported result: sequence compression is less aggressive than in the previous generation, retaining more fine-grained information, yet the global KV cache falls to about one-quarter of its previous size.
The reduction therefore does not primarily come from compressing the sequence more aggressively. Cross-layer sharing and lower storage precision account for much of the saving.
4. Why Lighter Sequence Compression and Greater Sharing Can Help
Compression along the sequence dimension—for example, token merging or sparse attention—can introduce information loss. More aggressive compression increases the risk of losing long-context details, such as a particular variable name in source code or a specific stack-trace line in a log.
Cross-layer sharing targets a different source of overhead: redundant representations rather than directly removing historical content. Different layers can produce substantially similar key and value representations of the same context, creating an opportunity for sharing with limited information loss.
This does not make sharing automatically lossless, but it explains the appeal of the design: compress the sequence less, eliminate more cross-layer redundancy, and reduce storage precision. The combination aims for a better balance between retained detail and inference cost.
5. What This Means for Developers
For developers building agent applications, this class of architecture can produce three practical benefits:
- Higher concurrency: When KV cache memory is the limiting factor, the number of concurrent sessions a GPU can support is approximately inversely proportional to per-session cache usage. Reducing cache memory to one-quarter can therefore allow the same hardware to serve several times as many sessions.
- More room for context: Within the same memory budget, applications can include more complete project code and execution logs, reducing the fragmentation caused by splitting context into separately retrieved chunks.
- Lower round-trip latency: Running only half the network during prefill can substantially improve time to first token, or TTFT, for long inputs.
When evaluating self-hosted deployments, focus on three metrics:
- Time to first token with long inputs.
- Steady-state generation throughput.
- Overall serving cost per million tokens.
Use real application workloads for load testing rather than relying solely on vendor benchmarks.
For cloud inference deployments, message queues can help smooth request spikes. Monitoring and alerts can track cache hit rates and GPU memory utilization as part of a broader observability setup.
6. Conclusion
Long-context agent workloads are changing the economics of inference and, in turn, model architecture. When reading dominates writing, an asymmetric design—partial-network encoding, full-network decoding, and cross-layer cache sharing—offers a way to allocate resources more efficiently.
Understanding the KV cache size formula and the trade-offs behind each compression dimension is essential when evaluating efficient-inference claims. When a cache is reported to be one-quarter of its previous size, ask where the savings came from: sequence compression, fewer independent layer caches, or lower precision?
That distinction helps determine whether the memory savings are likely to come at the expense of the contextual detail the application needs.
