Three Paths to KV Cache Compression for Long-Input Agent Workloads
This article examines why long-input AI agent workloads break the usual "cost scales with output length" assumption, and lays out three complementary paths to compressing the KV cache: reducing sequence length, sharing a global KV cache across layers, and lowering storage precision. It also covers a structural option that runs only half the network on long inputs, explains how the three paths combine multiplicatively, and lists the metrics and evaluation practices needed to validate the gains. Readers will find the capacity formulas, sample code, and a practical checklist for estimating, layering, and measuring cache behavior.
1. Where the Problem Starts: The Read/Write Asymmetry of Agent Workloads
A coding agent typically reads back tens of thousands of words of source code, test logs, and tool output after modifying a file, yet produces only a few hundred words describing the next step. Over multiple loop iterations, the resources a model spends on “reading” far exceed those spent on “writing.” These workloads share three traits: extremely long input sequences, context that must be reconnected frequently, and relatively short outputs. The traditional approach of estimating cost by “generation length” is badly distorted here; the real bottleneck shifts to the prefill stage and to KV cache capacity.
2. Why the Cache Balloons: A Computable Model
After text is split into tokens, each layer forms hidden vectors, and attention retrieves information from past positions. 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 t is the visible history length and c is the number of channels. When generating a new token, the historical K and V can be reused directly, so they are cached. Storing one copy per layer, the capacity is approximately:
bytes ≈ 2 × L × t × c × bL: number of layers t: sequence length c: channels b: bytes per element
A rough estimate: with L=40, c=4096, t=100k, and fp16 (b=2), a single request’s cache is on the order of 65 GB. Double the sequence and it doubles linearly—this is the real source of pressure in long-input scenarios.
A request therefore splits into two phases: Prefill processes the existing input and builds the state needed for subsequent generation—compute-intensive and parallelizable; Decode generates token by token, constrained by memory bandwidth and cache capacity.
3. Path One: Lighter Compression Along the Sequence Direction
The goal of sequence-direction compression is to reduce t without noticeably hurting retrieval ability. Common industry approaches include combining sliding windows with global tokens, evicting historical positions by importance, and striding to keep representative positions. The benefit is linear, but compressing too aggressively damages long-range dependencies, so it must be validated on a “long input, short output” task set.
4. Path Two: Sharing a Global KV Cache Across Layers
The more significant gains come from the layer dimension. If the keys and values of adjacent layers are highly similar, multiple layers can share one global cache, and some layers can even reuse retrieval results directly, effectively lowering L in the formula. Illustrative logic:
def kv_for_layer(layer_id, shared_groups):owner = shared_groups[layer_id] # the shared group this layer belongs tocache = global_cache[owner] # zero extra storage on a hitreturn cache
The hit rate and how the shared groups are partitioned are the core tuning points: larger groups save more memory, but carry a higher risk of reduced expressive power.
5. Path Three: Lower Storage Precision
Storing the cache at fp16, int8, or even lower precision can cut it roughly in half again with almost no structural change. Note the distinction between “storage precision” and “compute precision”: on read-back, dequantization feeds the computation, and the error accumulates along long contexts, so it must be evaluated layer by layer.
6. Structural Optimization: Making the Input Travel Only Half the Way
Split the network into a causal encoder and a decoder: process long inputs mainly through the first half, and run the full network only when generating new tokens. This directly reduces prefill computation and means the second half need not keep a separate cache for very long inputs. It is a structural change with stable gains but the highest modification cost.
7. Attributing the Gains: Where the One-Quarter Comes From
The three paths stack multiplicatively rather than simply adding up. Taking “effective layers halved × storage precision halved” as an example, the theoretical capacity drops to about one-quarter, with sequence-direction compression fine-tuning further on top of that. Attribution must be done by toggling each item on and off in an ablation, otherwise structural gains are easily misattributed to quantization.
8. Implementation Points and Validation Metrics
- Estimate capacity first: use the formulas above to bound the target sequence length;
- Layer the cache: keep hot data in GPU memory and push cold data down to object storage or a caching service, with logging and monitoring/alerting to observe hit rates;
- Core metrics: cache hit rate, prefill/decode time share, read/write byte ratio per request, peak memory, and cost per token;
- The evaluation set must cover long input and short output, otherwise the optimization gains stay invisible.
9. Common Pitfalls
First, planning capacity based only on average output length; second, maxing out sharing and quantization simultaneously without ablation; third, ignoring the consistency requirements of retrieval-result reuse. The correct way to use the three paths is to take the large gains from quantization and sharing first, then apply sequence compression and the split structure for targeted optimization, closing each step with reproducible metrics.
