KV Cache Compression and Layered Inference for Long-Input Workloads
This article explains why reading context costs more than writing output in long-input LLM workloads, and how KV cache size is determined by layers, sequence length, channels, and element width. It covers the prefill versus decode bottleneck split, a layered design that separates a causal encoder from a decoder, cross-layer cache sharing, and lower-precision storage, followed by practical guidance on capacity estimation, layered deployment, cache governance, precision rollout, and observability.
1. Background: Why Reading Costs More Than Writing
In scenarios such as AI coding assistants, document Q&A, and log analysis, a single request often carries tens of thousands of characters of source code, test output, and tool-returned content, while the next action the model actually generates may be only a few hundred characters. This kind of workload — extremely long input, very short output, and multiple follow-up turns — differs fundamentally from traditional short question answering.
The core tension is this: the generation phase advances token by token in sequence, and every step must read the entire history context once. The longer the input, the more expensive each single read becomes; the shorter the output, the less that cost can be amortized. So the optimization focus for long-context inference is usually not making writes faster, but making reads cheaper.
A request can typically be split into two phases:
- Prefill phase: processes all input tokens at once, compute-intensive, constrained mainly by compute capacity and parallelism;
- Decode phase: generates new tokens one at a time, accessing the history cache at every step, constrained mainly by memory capacity and bandwidth.
Understanding the different bottlenecks of these two phases is the prerequisite for all the optimizations that follow.
2. Where the KV Cache Comes From and Its Capacity Model
2.1 Starting from the attention formula
Transformer attention can be abstracted as: the current query computes a similarity against historical keys, then takes a weighted sum over historical values. Expressed for a single query and a single attention head:
o = softmax(q · Kᵀ / √c) · Vq ∈ R^{1×c} current query vectorK, V ∈ R^{t×c} keys and values for t visible history positionsc number of channels per vectoro ∈ R^{1×c} read-back result
When generating a new token, the K and V of historical positions do not change, so they can be cached and reused — this is the KV cache. If each layer stores its own copy, the cache size is roughly proportional to “layers × sequence length × channels.”
2.2 A capacity formula that is easy to estimate with
cache_bytes ≈ 2 × layers × seq_len × channels × bytes_per_element × batch
The factor of 2 accounts for the two tensors, K and V. This formula shows that only four variables can be moved to reduce the cache: number of layers, sequence length, channels, and bytes per element. Every optimization discussed below is essentially a tradeoff along one of these dimensions.
3. Layered Architecture: Dividing Work Between Encoding and Decoding
One approach widely discussed for long-input scenarios is to split the network into two parts: the front part acts as a causal encoder, mainly handling the reading and compression of long input; the back part acts as a decoder, responsible for generating new content over the compressed representation.
The operating logic can be described as:
- When processing long input, mainly run the front half, avoiding repeated high-cost computation across all layers;
- When generating new tokens, run the full network to preserve generation quality;
- The representation produced by the front part is reused by the back part, reducing repeated reads.
The scheduling logic looks schematically like this (pseudocode, expressing control flow only):
def run(request):enc_out = encoder.forward(request.prompt) # long input goes through the front part onlycache = enc_out.kv # reused laterfor step in range(max_new_tokens):token = decoder.forward(last_token, cache) # generation runs the full networkcache = cache.append(token)return token
The value of this division is that it decouples the “expensive but one-time” prefill from the “cheap but high-frequency” decode in terms of resources, making it easier to apply parallelism and caching strategies to each separately.
4. Cross-Layer Sharing and Lower-Precision Storage
Beyond layering, there are two orthogonal compression techniques:
- Cross-layer cache sharing: instead of every layer keeping a full copy of K and V, layers share one global cache, and some layers even directly reuse retrieval results from earlier layers. The layer factor is significantly weakened.
- Lower storage precision: changing cache elements from high-precision floats to a lower-bit-width representation directly reduces bytes per element.
Combined, these two can bring the global cache down to roughly one quarter of the previous generation, even when the compression along the sequence dimension is modest. This explains a seemingly contradictory phenomenon: lighter compression, yet a smaller cache — because the savings come mainly from cross-layer sharing and storage precision, not from sequence truncation.
One engineering constraint to note: lower precision introduces quantization error, and sharing introduces coupling between layers. Both require quality regression on an evaluation set; you cannot look at the memory curve alone.
5. Engineering Practice Recommendations
- Do the capacity math first: use the formula above to estimate peak cache and determine whether the bottleneck is capacity or bandwidth;
- Deploy in layers: put prefill and decode in separate resource pools and scale them independently;
- Cache governance: define sensible retention and eviction policies for continued sessions to avoid ineffective occupancy;
- Gradual precision rollout: get lower-precision storage through offline evaluation first, then release it to a small traffic share;
- Observability: set up monitoring and alerts for cache hit rate, per-step read latency, and peak memory, and use general capabilities such as logging services and monitoring alerts to locate long-tail requests.
6. Conclusion
Optimizing long-input workloads comes down to decomposing the cost of reading structurally: layering divides the computation, sharing keeps the layer count from scaling the cache linearly, and lower precision makes each element lighter. Only the combination of the three can compress the cache to around one quarter while the input has already covered most of the distance. For developers, mastering the capacity model and the gradual rollout method matters more than chasing a single metric.
