KV Cache Compression for Long-Context Inference

    When agents read far more than they write, KV cache—not the context window—becomes the bottleneck. This article explains how to cut global KV memory without a large quality drop by splitting encode and decode paths, sharing KV across layers, lowering storage precision, and reusing prefixes.

    In workloads such as coding agents, code review, and multi-turn tool use, models rarely write a lot and read little. A typical turn looks like this: the agent edits files, then reads tens of thousands of words of source, test logs, and tool output, and finally emits only a few hundred words of the next action. As turns accumulate, compute and memory cost tilt toward reading history rather than writing new tokens. Long-context inference is no longer only a question of whether the window is large enough. It becomes a systems problem: how historical keys and values are reread, compressed, and reused.

    This article treats that as a general technical problem: with long inputs and frequent context continuation, how to lower global KV cache footprint without a clear loss in generation quality. The discussion is not tied to one model or product line. It stays with common industry ideas around Transformer attention, cache lifetime, the split between encoding and decoding, and reuse across layers.

    Why the cache grows so fast

    A language model splits text into tokens. After a token enters the network, it becomes a hidden vector at each layer. Attention pulls information from the context already seen; the feed-forward network then applies a nonlinear transform. The three familiar quantities in attention are query Q, key K, and value V. Q is the question from the current position, K decides which past positions matter, and V carries the content that is actually read back.

    For one query and one attention head, the calculation is:

    [
    o=\mathrm{softmax}\left(\frac{qK^{\top}}{\sqrt{c}}\right)V
    ]

    Here (q\in\mathbb{R}^{1\times c}) is the current query, (K,V\in\mathbb{R}^{t\times c}) store keys and values for (t) visible past positions, and (c) is the channel dimension. When the next token is generated, K and V for past positions usually do not need to be recomputed. The system stores them. That store is the KV cache. If every layer keeps its own copy, cache size grows roughly with layers × sequence length × number of heads × dimension per head × bytes of precision. Even when this step writes only one new token, the system still has to read the historical cache.

    A request therefore splits naturally into two phases: prefill processes the existing long input, and decode generates step by step. In agent settings, prefill is often far heavier than decode: the input may be a repository slice plus logs, while the output is short. If every turn caches the full history at full precision in every layer, GPU memory becomes the bottleneck and throughput is limited by bandwidth.

    Workload shape: much more reading than writing

    Coding agents add two traits that increase cache pressure.

    First, continuation is frequent. Tool output, patches, and failure stacks from the previous turn enter the next turn as-is. The sequence grows almost monotonically, and whole spans are rarely dropped. Second, useful information is sparse. In tens of thousands of words, only a few hundred may decide which line to change next, yet attention still has to relate over the visible history. That creates an engineering tension: keep a long enough context to retrieve from, but do not let every layer store K and V independently at full precision and full length.

    For this kind of load, the usual optimization is not a single move that “makes the sequence shorter.” It moves three axes at once: the compute path (which layers must run during prefill), the storage layout (which layers can share one global KV), and numeric precision (whether lower-bit K and V are acceptable). Stacking the three can produce a counterintuitive result: compression along the sequence is not extreme, yet global KV footprint drops clearly. Most of the saved space comes from sharing across layers and from lower storage precision, not from squeezing every token into a very short vector.

    Compute path: long inputs through the front half, generation through the full network

    One structured approach splits a deep network by role. The front half behaves more like a causal encoder. The back half handles decoding and generation. For a very long input, the system mainly runs the front half and encodes the sequence into reusable representations and cache. When it actually generates new tokens, it runs the full network so the back half can do fine-grained attention and language modeling on the already encoded context.

    The motive is direct. In prefill, compute grows approximately linearly with sequence length, or faster, depending on the attention implementation. Running full self-attention over tens of thousands of tokens in all 40 layers makes both latency and activation memory high. Concentrating “understand the long input” in the front half means a shallower causal encode does most of the context compression and feature extraction. The back half runs at full depth only when the number of decode steps is small, so deep compute per output token stays acceptable.

    Causality still matters in implementation: the encoder side must remain visible in one time direction so the future does not leak. Encoded results must also line up with the decoder interface—head count, the phase of positional encodings such as RoPE, and residual scale. Otherwise prefill is fast and generation quality drops because the two sides are misaligned. In practice, the first N layers of one weight set are used as the encode path, and the later layers are stacked on during decode, rather than training two unrelated networks. That keeps parameters shared and behavior consistent.

    For an agent, reading source and logs mainly pays the cost of shallow encoding. Writing a patch explanation pays the cost of deep decoding. The read/write resource ratio is recalibrated.

    Storage layout: share global KV across layers, and reuse retrieval results

    Cache is large less because each token’s vector is especially wide than because of the product of layer count and length. If every layer stores K and V on its own, 40 layers mean 40 copies of history. Cross-layer sharing of global KV means several layers use one key-value store. Queries are still produced per layer, but they retrieve from the same history, or from a small number of copies.

    Sharing loses some layer specificity. Shallow layers lean toward local syntax; deeper layers lean toward semantics and task state. A common compromise is to keep more independent KV in shallow layers and share in the middle and deep layers, or to share in blocks (one copy every k layers). For very long context, retrieval results can be reused as well. If one layer has already pulled top relevant spans or compressed memory slots for a query, later layers do not rescan the full history. They attend on the same retrieval view. That is similar to recall first, then read carefully: full-sequence attention becomes repeated queries over shared memory.

    After sharing, compression along the sequence can stay relatively mild. Each token does not have to be pushed to a very low dimension for total cache to fall, because the multiplier changes from “number of layers” to “number of share groups.” Comparisons in report-style material often show that sequence-direction compression is less aggressive than more extreme schemes, while global KV can fall to a smaller fraction of the previous configuration. What matters more than any one percentage is the mechanism: space comes mainly from cross-layer sharing and precision, not from harsher token compression.

    Precision and layout: low-bit KV, paging, and prefix reuse

    The third axis is storage precision. Quantizing K and V is often more sensitive than quantizing weights, but it is also more worth doing, because K and V grow linearly with the sequence. Common practice includes group quantization, per-channel scaling, and keeping higher bits on critical channels. Agent logs contain many numbers, paths, and error codes, so calibration should use the real distribution of tool output. Otherwise the key space of important tokens gets crushed.

    Memory layout sits beside precision. Paged cache, block allocation, and prefix cache—storing one copy of a shared system prompt and repository header—cut fragmentation and duplication. In multi-turn dialogue, stable prefixes should hit the prefix cache when possible; changing tool output is appended as new pages. Global footprint then falls not only from algorithmic compression, but also from not storing the same prefix a second time.

    In a cloud deployment, these capabilities usually sit in general inference-engine, elastic GPU, and monitoring features: log services to watch cache hit rate and per-layer memory, and metrics to see whether decode-stage bandwidth is saturated. There is no need to bind this to one vendor’s proprietary interface. The principle is to treat KV as a first-class resource, not as an array attached to attention.

    Quality and the system: how to offset sharing and shallow encoding

    Any compression carries quality risk. Sharing across layers can make deep layers “miss” shallow detail. Shallow encoding can drop long-range dependencies that only form in deeper layers. Compensations include:

    • Still run the full network during decode, and use generation steps to restore deep representations.
    • Keep full-precision, all-layer KV for the recent window, and apply sharing and quantization only to distant history.
    • Keep position information when retrieval is reused, so the time order of tool output is not scrambled.
    • Evaluate on the task, not only on perplexity. Whether a patch applies and whether tests turn green matters more than fluent generation.

    Scheduling should match the load. Prefill can be batched, and very long inputs can be encoded in segments. Decode needs low latency and a small batch. The compute split between the encoder path and the decoder path should follow average input length over average output length. Agents often have a very high input-to-output ratio, so giving more compute to the encode path is reasonable.

    A practical checklist: from principle to steps you can measure

    To try the same ideas in your own inference stack, move in this order. Each step can be measured.

    1. Profile the load: input tokens, output tokens, turns, and the share of repeated prefixes. Confirm that the workload really is read-heavy and write-light.
    2. Split the compute graph: mark the front layers as the main prefill path, and attach the later layers at decode time. Align positional encoding and layer normalization.
    3. Introduce KV share groups: start with two layers per group, watch generation and code-task metrics, then widen sharing.
    4. Store distant KV at low bit width and keep the near window at high precision. Calibration data should include logs and diffs.
    5. Turn on prefix cache and paging so multi-turn runs do not store the system prompt again.
    6. Monitor global KV bytes, bandwidth, prefill latency, decode latency, and task success rate. If quality drops, shrink the share group or enlarge the near full-precision window first, rather than immediately compressing the sequence more aggressively.

    Illustrative pseudocode (control flow only, not an API of any framework):

    1. def infer(tokens, cache):
    2. # Long input: mainly run the front layers and write shared KV
    3. h = embed(tokens)
    4. for layer in encoder_layers:
    5. h, cache = attn_ffn(layer, h, cache, share_group=layer.group)
    6. # Generation: all layers, reusing the same global KV
    7. for _ in range(max_new):
    8. x = h[:, -1:]
    9. for layer in all_layers:
    10. x, cache = attn_ffn(layer, x, cache, share_group=layer.group)
    11. h = concat(h, x)
    12. return decode(h)

    The function names are not the point. Prefill runs fewer layers, decode runs all layers, and the cache is shared by group.

    Summary

    Long-context agents turn a language model from a dialogue generator into a system that repeatedly reads a large workspace. The KV cache is the hardest resource constraint on that path. Split the network into an encode-leaning front half and a full network for decode, let multiple layers share global keys and values and reuse a retrieval view, then combine that with lower precision and prefix paging. Global cache can come down even when sequence compression is not extreme. The space comes mainly from removing the layer multiplier and from fewer storage bits. In production, use real tool logs as the quality gate, and put cache hits, bandwidth, and task success rate on the same dashboard, so the architecture choice becomes a stable production capability.