KV Cache Compression for Long-Input Workloads: How It Works
This article explains why long-input LLM workloads make reading from the KV cache more expensive than writing to it, and how modern systems reduce that cost. It covers how the KV cache originates in attention, the difference between sequence-direction and layer-direction compression, encoder-decoder network segmentation that enables cross-layer cache sharing, the role of storage precision, and a practical capacity estimation formula with a tuning checklist for developers.
1. The Starting Point: Why Reading Costs More Than Writing
In applications like AI coding assistants, document Q&A, and log analysis, a single interaction often looks like this: the tool modifies a few files, then feeds tens of thousands of characters of source code, test output, and stack traces back to the model, and the model finally produces only a few hundred characters of next-step instructions. Input and output are severely asymmetric in length, and every round has to re-attach the previous round’s context.
This kind of workload puts pressure on the inference system in two places. First, the prefill stage has to process the entire input at once, which is compute-intensive. Second, the decode stage has to look back over the full history for every generated token, which is memory-access-intensive. The latter determines the actual throughput and memory footprint of long-context serving.
2. Where the Cache Comes From: Q, K, V in Attention
A language model splits text into tokens, and each token passes through multiple Transformer layers, forming hidden vectors layer by layer. Attention is responsible for pulling information from historical positions, and the feed-forward network continues the processing. The read-back for a single query and a single attention head can be written as:
o = softmax(q · Kᵀ / √c) · Vq ∈ R^{1×c} # query at the current positionK, V ∈ R^{t×c} # keys and values for t visible history positionso ∈ R^{1×c} # read-back result
The key point: when generating token t+1, the K and V of historical positions stay completely unchanged. Recomputing them at every layer would be prohibitively expensive, so the system keeps them instead. This is the KV cache. Its size grows roughly linearly with “number of layers × sequence length × channels × cached heads per layer,” and long-input scenarios amplify it directly through sequence length.
A request is therefore split into two phases:
- Prefill: processes the existing input and builds the state needed for subsequent generation. Compute-intensive.
- Decode: generates token by token, repeatedly reading the historical cache. Bandwidth- and capacity-intensive.
3. The Main Thread: Sequence-Direction and Layer-Direction Compression Are Two Different Things
The industry’s approaches to reducing cache overhead fall into two categories, and understanding the difference is a prerequisite for making sense of designs like this one.
Sequence-direction compression aims to reduce the storage per position. Common approaches include multi-query/grouped-query attention (letting multiple heads share the same K and V), sparse or windowed attention (keeping only part of the history), and low-rank projection that squeezes K and V into a smaller dimension.
Layer-direction compression aims to reduce the duplicated storage caused by the number of layers. The idea is to have adjacent or cross-segment layers reuse the same global cache instead of each keeping its own copy.
The phenomenon described in the original text sits exactly at the mismatch between the two: sequence-direction compression is done more lightly (keeping more positional information to preserve long-text capability), yet the total global cache is instead reduced to about one quarter of the previous generation. The difference does not come from the sequence direction, but from cross-layer sharing and lower storage precision — the same global cache is referenced across multiple layers, and it is written out at lower numerical precision, so the byte count of a single copy drops significantly.
4. Segmented Networks: Causal Encoder Plus Decoder
One structure that pairs with cache sharing is splitting the deep network into two segments: the front segment acts as a causal encoder, responsible for compressing long input into a compact representation; the back segment acts as a decoder, responsible for autoregressive generation. The engineering implications are:
- When processing long input, mainly the front segment runs, avoiding full-depth participation in costly prefill;
- When generating new tokens, the full network runs to guarantee output quality;
- The state produced by the front segment is referenced jointly by multiple layers of the back segment, forming “compute once, reuse across layers.”
Illustration (pseudocode, expressing scheduling relationships only):
def forward(long_input, past_state):enc = causal_encoder(long_input) # only the front segment runs, compute stays boundedstate = share_global_kv(enc, past_state) # global cache, referenced by multiple layersreturn decoder(state) # full depth, token-by-token generation
5. Precision Is the Layer Most Easily Overlooked
Cache bytes = number of elements × bytes per element. The former is addressed by sharing and compression; the latter is addressed by numerical precision. Lowering the cache from high-precision floating point to a smaller bit width is the optimization with the most direct payoff and a relatively contained change surface, but note that numerical range and outliers affect the precision choice. It is usually combined with scaling, block-wise quantization, or mixed-precision strategies, and cumulative error should be validated on long sequences.
6. Capacity Estimation and a Tuning Checklist
For estimation, the following simplified formula helps build intuition (the exact coefficients depend on the implementation):
cache_bytes ≈ 2 × L_shared × t × d_kv × bytes_per_elem × batch# 2 accounts for K and V; L_shared is the number of layers with independent caches, far smaller than the total layer count after sharing
Actionable checklist items:
- Quantify the workload first: measure the distribution of input/output lengths and the number of continuation rounds to confirm whether it is truly long-input.
- Separate the bottlenecks: for prefill look at compute and batching strategy; for decode look at memory capacity and bandwidth.
- Prioritize cross-layer sharing, then evaluate sequence-direction compression, to avoid losing long-text recall too early.
- Any precision reduction must go through long-sequence regression, watching long-distance dependencies at the tail.
- Use segmented scheduling to confine the cost of long input within the front-segment network.
- Plan capacity in combination with general cloud capabilities: container platforms host inference instances, object storage holds sessions and snapshots, monitoring and alerting track cache hit rate and memory watermark, and log services retain long-request traces.
7. Conclusion
The essential tension in long-input workloads is “read-heavy, write-light,” and the optimization focus is not a single algorithm but the storage structure of the cache: who stores it, how many copies exist, and at what precision. Segmenting the network, letting multiple layers share a global cache, and pairing that with lower storage precision is a reasonable explanation path for compressing the cache to roughly one quarter of its size while barely sacrificing long-text capability. For developers, measuring the workload first, then identifying the bottleneck, and finally proceeding in the order of sharing and precision is the lowest-risk sequence for putting this into practice.
