KV Cache Compression for Long-Context Inference
Long-context AI agents often spend more resources processing history than generating new tokens. This article explains how prefill and decoding stress compute and memory differently, how cross-layer sharing, lower-precision storage, and sequence compression reduce KV cache costs, and how to estimate capacity, validate accuracy, and schedule workloads in production.
After modifying code, a coding agent often reads entire source files, test logs, and tool responses before producing a short next action. Across multiple turns, the compute and GPU memory spent processing history can easily exceed the resources spent generating new tokens.
Understanding this workload matters more than memorizing a particular model name: inputs are long, context must be extended repeatedly, and each step generates relatively little new content.
Tokens, Hidden States, and What Attention Reads
Text is first split into tokens, which may represent characters, parts of words, or symbols. As each token passes through the network, it develops a hidden vector at each layer. Attention retrieves information from the context already available, and feed-forward networks apply nonlinear transformations to that information.
Attention commonly uses three quantities: queries, keys, and values. Intuitively, the current position issues a query, keys determine which historical positions are relevant, and values carry the content to retrieve. For a single query in a conventional attention head, the basic operation is:
o = softmax(q · K^T / scale) · V
Here, q is the current query, while K and V contain the keys and values for the visible history. The scaling factor stabilizes score magnitudes, and softmax converts relevance scores into weights.
Real implementations also involve multiple heads, rotary positional embeddings, masks, and various compressed storage formats. This formula provides intuition; it does not describe any particular implementation’s memory layout.
Why Inference Keeps a KV Cache
When generating the next token, the keys and values from previous positions remain valid. Inference systems retain them in a KV cache rather than recomputing them.
If every layer maintains its own cache, memory use grows roughly with:
sequence length × layer count × head count × channels per head × bytes per element
As sequences grow, the cache can exhaust GPU memory before model weights do. Even when a step generates only one new token, attention still reads keys and values across the history, creating substantial bandwidth pressure.
A request therefore has two distinct phases:
- Prefill: Process the existing input, either at once or in chunks, and build the states needed for subsequent generation. Long documents and logs place most of their initial processing cost here. Compute grows approximately linearly with sequence length or faster, and the system must write the cache for the entire input.
- Decoding: Append a small number of new tokens at a time, reuse the existing cache, and compute the new positions’ queries, keys, and values. Each step requires relatively little computation, but repeatedly reading an increasingly long history can make decoding memory-bandwidth-bound.
Coding agents often sit at the extreme of heavy prefill and light decoding. Accelerating token-by-token generation alone may do little for total request cost. Effective optimization must also reduce cache-building computation, cache size, and data movement during continuation.
Splitting the Network: Build State First, Use Full Depth for Generation
One architectural approach for long inputs divides the network into two parts. Earlier layers behave more like a causal encoder, primarily turning the long input into reusable states during prefill. Later layers behave more like a decoder, joining the earlier layers to run the full network when generating new tokens.
For inputs containing tens of thousands of tokens, this avoids applying equally expensive full-sequence updates at every layer. When generating the next few hundred tokens, the system uses the full depth so that each decision still passes through deeper transformations.
The benefit comes from workload asymmetry—not simply from reducing the layer count. The prefill sequence may be tens or hundreds of times longer than the number of decoding steps. Concentrating long-sequence processing in the earlier layers, while letting later layers work more with compressed or shared states, can reduce total floating-point operations and memory traffic.
The trade-off is that layers no longer see identically structured history. Positional information, masks, and state alignment must remain consistent. Otherwise, continuation can repeat content, miss relevant information, or contradict earlier context.
How Cache Size Can Fall to Roughly One Quarter
Compressing representations along the sequence dimension does not automatically reduce KV cache bytes by the same proportion. Two independent factors largely determine reductions in global cache storage: which layers retain separate keys and values, and how many bits each stored element uses.
Cross-Layer Sharing
When multiple layers share one global set of keys and values instead of storing separate copies, the layer-count multiplier becomes smaller.
Some layers can go further and reuse context results that have already been retrieved, avoiding a full scan of the long history at every layer. This requires sufficiently similar query distributions across those layers, or projections that map their queries into a common key space. Otherwise, sharing effectively supplies the wrong historical information to the current layer.
Lower-Precision Storage
Keys and values may be computed at higher precision and then quantized to a lower bit width for cache storage.
If the number of layers maintaining independent caches is approximately halved, and bytes per element are also approximately halved, cache size can fall to roughly one quarter of the original.
This is an order-of-magnitude estimate, not a promise about any product. The actual ratio also depends on grouped heads, sliding-window caches or retrieval indexes, and storage overhead for quantization scales.
Sequence Compression
Sequence compression addresses a different cost: it shortens the effective history that attention must inspect. The softmax candidate set becomes smaller, reducing attention computation and bandwidth demands during prefill.
This is related to cache size, but it is not the same control. Shortening the sequence while retaining full-precision, independent caches at every layer may still leave a large memory footprint. Lowering precision without sharing may still be insufficient for extremely long logs.
Estimating Capacity Without Relying on Marketing Claims
Use the following relationship for an initial estimate, then validate it with real workloads:
cache bytes ≈ effective layer count × sequence length × head count × channels per head × bytes per element × 2
The factor of two accounts for storing both keys and values. After cross-layer sharing, the effective layer count should be smaller than the network’s total layer count. With compression or retrieval, sequence length should mean the number of positions actually written to the cache—not the length of the original document visible to the user.
For example, consider a 10,000-token input with independent caches at every layer and two bytes per element. If roughly half the layers maintain independent caches and storage falls to one byte per element, the cache becomes approximately one quarter of its original size.
If the cached sequence length is also halved, memory use falls further. However, that compression ratio must be evaluated separately to establish whether enough information is preserved.
Capacity estimates must also account for batching, concurrent sessions, prefix-cache hits, and framework block alignment. These factors can turn a theoretical fourfold reduction into less than a twofold reduction in production.
Accuracy Trade-Offs in Quantization and Sharing
Low-bit-width storage is more sensitive to outliers and can affect long-tail logits. The relative magnitudes of keys influence where attention lands, while values determine what content is retrieved.
Excessive key quantization can make the model attend to the wrong positions. Excessive value quantization can let it attend to the correct positions but retrieve distorted information.
Engineering approaches commonly retain per-block or per-head scaling factors and use a higher-precision path for outliers. Validation should use real repositories, long logs, and multi-turn tool interactions—not just perplexity on short text.
Cross-layer sharing introduces another risk: deeper layers may lose their private memory. Earlier layers tend to emphasize local syntax, while deeper layers are more concerned with task-level decisions. Forcing every layer to use the same keys and values can remove fine-grained distinctions needed only by deeper layers.
A more conservative design uses a global cache for reusable long-term history while allowing a small number of layers to retain private short caches or low-rank residuals. These can compensate for expressiveness lost through sharing.
If retrieved context results are also reused, masks and causal ordering must remain correct. A future tool response must not become visible to a step that has not yet been generated.
Serving Long-Context Workloads
A long-context service needs more than additional memory on a single GPU. A practical serving setup combines several measures:
- Use a memory hierarchy. Keep prefix and session caches in fast memory. Move cold history to object storage or a tiered cache, and retrieve it when needed.
- Schedule prefill and decoding separately. Prefill is compute-intensive; decoding is bandwidth-intensive. Putting both in one queue can leave short responses blocked behind long logs.
- Manage caches in blocks. Block-based allocation helps reclaim memory across concurrent sessions and prevents one extremely long trajectory from monopolizing a GPU.
- Monitor three core metrics. Track cache bytes, prefill latency, and GPU memory bandwidth per decoding step. Generated tokens per second alone can be misleading.
- Load-test coding workloads separately. Use requests that ingest tens of thousands of characters of source code and logs, then add only a few hundred characters of actions over subsequent turns. This exposes bottlenecks more effectively than uniformly sized chat requests.
Logging and monitoring should also capture cache hit rates, sampled quantization error, timeouts, and retries. These signals help distinguish a model that cannot produce a correct patch from a system that failed to make the full context available.
Four Questions to Ask Before Deployment
- What is the input-to-output length ratio in real requests? If outputs are not short, optimizations focused on heavy prefill become less valuable.
- Is cache growth driven by layers, sequence length, or concurrency? These point to sharing, compression, and scheduling respectively—not one interchangeable fix.
- After lowering precision, are code localization, line-number references, and tool arguments still reliable? These tasks are more sensitive to reading the wrong few lines than open-ended conversation.
- During continuation, do cached states match the masks and positional encodings used when they were created? An inconsistent cache is unusable, regardless of how small it is.
For agents with long inputs and short decisions, it is worth shifting the resource budget away from a full-precision history at every layer toward storing less, sharing more, and reading on demand.
Layered computation reduces the depth-related cost of prefill. Cross-layer sharing and lower-bit-width storage reduce cache volume. Sequence compression reduces the history that attention must scan.
Together, these techniques can reduce global KV storage to a small fraction of its original size. Promoting only one of them rarely explains the complete GPU memory profile. Evaluate any approach with end-to-end measurements on your own repositories and tool logs rather than relying on headline claims.
