Cache Optimization for Long-Context Inference: Shrinking the Multipliers
This article explains why long-context workloads, such as coding agents that read far more than they write, make KV cache a bottleneck, and how to reduce it. It covers how attention and KV cache work, the prefill and decode phases, the causal encoder plus decoder split, and three multipliers to shrink: cross-layer cache sharing, lower storage precision, and lightweight sequence compression. It also includes a practical engineering checklist for capacity planning, precision trade-offs, reuse, eviction, observability, and cloud deployment.
1. Where the Problem Comes From: A Read-Heavy, Write-Light Coding Agent
Imagine a coding tool modifying a single file in a repository. It first reads back tens of thousands of characters of source code, then ingests test logs, compiler warnings, and structured output returned by tool calls, and finally produces only a few hundred characters describing the next step. When the round ends, the context is retained for the next round, so the cost of “reading” is paid over and over, while the “written” output stays tiny.
This kind of workload has two defining traits: the input sequence is extremely long, and the context must carry across rounds. A traditional implementation that stores one key-value cache per layer gets amplified on both traits at once. The longer the sequence, the more layers there are, and the more rounds the context is carried forward, the closer cache usage grows to linear or even faster, eventually crowding out the GPU memory budget available for batch concurrency.
2. Attention and Cache, Clarified
A language model splits text into tokens. Each token enters the network and forms hidden vectors layer by layer: attention pulls information from the historical context, and the feed-forward network keeps processing it. Within attention, Q, K, and V can be understood this way: Q is the query issued by the current position, K is used to decide which historical positions are relevant, and V carries the content that is actually read back. The computation for a single query and a single attention head can be written as:
o = softmax(q · Kᵀ / √c) · Vq ∈ R^{1×c}, K,V ∈ R^{t×c}, o ∈ R^{1×c}
Here c is the number of channels and t is the length of visible history. When generating a new token, the K and V of historical positions do not need to be recomputed and can be reused directly. This is the origin of the key-value cache (KV Cache). It trades memory for compute, a classic case of “space for time.”
A single request therefore splits naturally into two phases with completely different resource profiles:
- Prefill: processes the entire input in parallel, compute-intensive, and able to slice a long sequence into chunks for pipelined processing.
- Decode: generates one token at a time, repeatedly reads the historical cache, bandwidth-intensive, with latency dominated by “reading the cache.”
Understanding this is the key to understanding why compressing more lightly along the sequence direction can still sharply reduce total cache: sequence-direction compression only affects t, while cross-layer sharing and storage precision affect the multiplier term of “number of layers × precision.”
3. A Recurring Structure: Causal Encoder Plus Decoder Split
One approach to handling long inputs is to split the deep network into two segments: the front segment acts as a causal encoder, responsible for compressing the long input into a more compact representation; the back segment acts as a decoder, responsible for autoregressive generation. When processing long inputs, mainly the front half runs; only when generating new tokens does the full network run.
input x ──► [causal encoder, first N layers] ──► compact representation ──► [decoder, remaining layers] ──► next token▲ long input runs only here ▲ runs every time during generation
There are three benefits: the repeated computation over long inputs is absorbed by the front segment; the per-layer cost during generation stays unchanged, keeping tail latency controllable; and the compressed representation from the front segment is better suited to being cached and reused.
4. Why the Cache Can Drop to One Quarter: Shrink Three Multipliers Together
Roughly, the global cache can be written as number of layers × sequence length × number of channels × bytes per element × number of cache heads. Only four of these multipliers can be reduced.
- Share a global cache across layers: multiple layers share the same global key-value, so the multiplier drops from “number of layers” to “number of shared groups”; some layers even reuse the retrieval results as well, further reducing repeated reads.
- Lower storage precision: the cache is stored at a lower bit width, directly halving the multiplier or more, at the cost of precision loss that must be evaluated.
- Lightweight sequence-direction compression: this only affects t, and on its own the magnitude is limited; only when stacked with the first two does it form an order-of-magnitude difference.
Illustrative estimate (only to demonstrate the multiplier effect, not measured data from any product):
Baseline: 40 layers × 8 heads × 128 channels × 2 bytes = 81920 bytes per token per sequenceAfter sharing: 8 groups × 8 heads × 128 channels × 1 byte ≈ 8192 bytes per token # about 1/10Stacking sequence compression and block-level eviction, landing around the 1/4 magnitude overall is a reasonable engineering range
5. Engineering Implementation Checklist
- Capacity planning: estimate the peak as
concurrency × average context length × cache bytes per token, leaving room for fragmentation and temporary activation space. - Precision trade-offs: before storing the cache at a lower bit width, first run quality regression on tasks such as long-context retrieval and code completion, paying attention to long-tail positions.
- Reuse strategy: requests with identical prefixes share the cache; stable prefixes such as system prompts and repository skeletons should stay resident first.
- Eviction and chunking: manage the cache in blocks, use paged allocation to reduce fragmentation, and set a sliding window or layered summary for extremely long contexts.
- Observability: monitor cache hit rate, the share of prefill time, and decode-phase bandwidth utilization, and tune parameters driven by data.
- Cloud form: container platforms host the inference service, object storage holds models and datasets, logging and monitoring with alerts close the loop, and a message queue smooths request peaks.
6. Conclusion
The focus of long-context inference optimization is shifting from “compressing the sequence shorter” to “shrinking the cache multipliers.” The stacking of the three approaches, split encoding, cross-layer sharing, and low-precision storage, is the main reason the cache drops by an order of magnitude. For developers, first quantifying your own workload profile and then optimizing each multiplier one by one is more reliable than chasing a single metric.
