KV Cache Optimization for Long-Context Inference: Architecture and Engineering Practices
This article explains why reading long inputs costs more than generating short outputs in long-context LLM inference, and how KV cache size is determined by layers, sequence length, and channel count. It introduces a layered design that splits a deep network into a causal encoder and a decoder, shares global KV cache across layers, and reuses retrieval results. It also covers practical concerns such as layered cache management, storage precision trade-offs, staged scheduling, and observability.
1. Background: Why Reading Costs More Than Writing
In scenarios such as AI coding assistants, document question answering, and long-log analysis, a typical request can contain tens of thousands of words of source code, test output, and tool responses, while the next action the model generates may be only a few hundred words. This kind of workload—very long input, very short output, and multiple follow-up turns—exposes a structural tension in inference cost: the resources spent on reading can easily exceed those spent on writing.
To understand this, split a single inference request into two stages:
- Prefill: processes the existing input in one pass, computes hidden states layer by layer, and builds the cache state that later generation depends on. This stage scales with input length and is compute-intensive.
- Decode: generates new tokens one at a time, and every step looks back at the full history. This stage scales with cache capacity and memory bandwidth, and is memory-intensive.
When the input is far longer than the output, prefill and cache reads dominate the cost, while generation accounts for only a small share. So for this type of workload, the point of model architecture optimization is not to make writing faster, but to make reading cheaper.
2. Why the KV Cache Exists and How to Estimate Its Size
A language model splits text into tokens. Each token passes through multiple Transformer layers and forms a different hidden vector at each layer. The attention mechanism reads information from historical positions, and the feed-forward network processes it further. Attention commonly uses three symbols: Q, K, and V. Q is the query issued by the current position, K determines which historical positions are relevant, and V carries the information that is actually read back.
For a single query and a single attention head, the computation can be written as:
o = softmax(q * K^T) * Vwhere q ∈ R^(1×c), K, V ∈ R^(t×c), o ∈ R^(1×c)c is the number of channels, t is the visible history length
When generating a new token, the K and V of historical positions do not need to be recomputed and can be reused, so the system caches them. This is the KV cache. If each layer keeps its own copy, the cache size is roughly proportional to number of layers × sequence length × number of channels. The longer the sequence and the more layers, the larger the cache; even to generate a single new token, the system must read from the historical cache.
This also explains a common misconception: cache pressure is not determined by sequence-direction compression alone. Whether layers share the cache, what precision it is stored at, and whether external retrieval results are reused all change actual memory usage significantly.
3. A Layered Architecture: Causal Encoder Plus Decoder
For the workload above, one workable design is to split the deep network into two parts: the first half acts as a causal encoder that mainly encodes the long input, and the second half acts as a decoder that generates new tokens over the full network.
The runtime logic can be summarized as:
- When processing long input, mainly run the first half to compress the lengthy context into a more compact representation.
- When generating new tokens, run the full network to preserve generation quality.
- Share a global KV cache across layers, and for some layers reuse retrieval results as well.
The benefit of this design is that long input no longer needs a full cache at every layer, which reduces total cache size without noticeably sacrificing generation quality. It is worth stressing that sequence-direction compression can be done more lightly, while the cache reduction mainly comes from cross-layer sharing and lower storage precision. These are optimizations in different dimensions and should not be conflated.
4. Engineering Implementation Notes
- Layered cache management: distinguish cache that must be kept per layer from cache that can be shared across layers, and define sharing boundaries and invalidation policies.
- Storage precision trade-offs: balance precision against capacity, and keep higher precision for layers that are sensitive to it.
- Retrieval result reuse: cache and reuse external retrieval content that is accessed repeatedly, to avoid repeated encoding.
- Staged scheduling: give prefill and decode differentiated resource quotas so that long inputs do not crowd out generation resources.
- Observability: use logging services and monitoring alerts to track cache hit rate, prefill latency, and memory-access bottlenecks.
5. Conclusion
The core tension in long-context inference is the cache and memory-access pressure created by reading much and writing little. Layered encoding, cross-layer sharing, low-precision storage, and retrieval reuse form an optimization path that does not rely on crudely truncating the sequence. For developers, understanding the resource differences between prefill and decode is the prerequisite for evaluating the benefits of such architectures.
