Cache Optimization and System Design for Million-Token Context Models
This article explains how to manage the KV cache in large language models that handle million-token contexts. It covers why memory capacity, computation, and data movement must be analyzed separately, and it describes design options such as splitting prompt processing from generation, layering local and global caches, storing caches at lower precision, and recomputing states on demand. It ends with metrics for checking whether these changes improve quality, latency, and total cost.
1. The Key Problem of Long Context: Computable Does Not Mean Affordable
When an agent reads large volumes of documents, calls tools repeatedly, and runs multi-step reasoning, the context stops being a one-time input and becomes a growing working state. The system must handle the user’s question while also keeping tool outputs, past decisions, and intermediate evidence that later generation steps access again and again.
Traditional autoregressive inference usually caches the keys and values at earlier positions and reuses them in later generation steps, which avoids repeated computation. This cache is called the KV cache.
The cache removes repeated computation, but it adds a new resource constraint. The longer the context, the larger the cache. The more concurrent requests, the more historical state must stay resident in memory or be loaded when needed. Even with sparse attention, which reduces how many positions take part in each step, the full historical cache does not shrink automatically.
Long-context optimization must therefore separate three questions:
- Compute: How many attention and network operations does each generated token require?
- Capacity: How much device memory or host memory do the historical states occupy?
- Data movement: How much data must be read, transferred, and reloaded for each computation?
These three costs are related, but they are not equivalent. A method that reduces computation may still keep a huge historical state. A method with a high compression ratio may fail to raise real throughput if decompression or irregular memory access slows it down.
Evaluating a long-context architecture should therefore move from single-point optimization to analysis of the complete data path.
2. Establish the Cache Budget First, Then Assess Architectural Gains
For a conventional layer-by-layer cache, the KV cache footprint can be roughly estimated with:
M_KV ≈ B × N × L × 2 × H_KV × D × S
where:
- B is the number of sequences whose caches are kept at the same time;
- N is the cache length of each sequence;
- L is the number of network layers that store a cache;
- H_KV is the number of key-value heads;
- D is the dimension of each head;
- S is the number of bytes per cache element;
- the factor 2 accounts for keys and values.
This formula shows how capacity changes with each parameter. It does not apply to every compressed attention structure. Real deployments must also account for memory alignment, paged management, quantization parameters, position encoding state, and runtime workspace.
Cache optimization has at least four paths:
- Reduce the number of layers that must keep historical state;
- Reduce the cache dimension at each position;
- Lower the storage precision of cache elements;
- Shorten the range over which part of the cache must be kept long-term.
These paths can be combined, but their gains do not simply multiply. Different optimizations may act on the same state, and they may add metadata or temporary buffers.
For example, a design may reduce the long-term cache but need to rebuild some local state temporarily during generation. In that case, lower long-term usage does not guarantee that peak runtime memory drops by the same proportion. Engineering evaluation must measure long-term usage, temporary usage, and peak usage together.
3. Architectural Idea: Separate Prompt Processing from Step-by-Step Generation
1. Why Redivide Network Responsibilities
In a conventional decoder-only architecture, the prompt passes through the full network, and each layer produces key-value states that later generation steps use. The longer the prompt, the higher the computation and cache-building cost in the prefill stage.
One design to consider splits prompt processing and output generation along the network depth:
- The front part of the network builds prompt representations under causal constraints;
- The back part performs subsequent generation based on those representations;
- Some of the global key-value states the back part needs can be built from the front part’s output through layer-specific mappings.
“Causal” means that a position’s representation cannot access future positions. This keeps the information boundary that autoregressive modeling requires.
The main point of this design is not simply to reduce the number of layers. It redefines how information enters the generation network and which historical states are worth keeping long-term.
2. How Global Representations Enter the Decoding Stage
If the encoder output is H, the global keys and values needed by the l-th decoder layer can be illustrated as:
K_l = H W_K,l
V_l = H W_V,l
These equations describe one possible layer-specific linear projection. They do not mean that any model can gain the same capability by adding a projection layer. Mapping dimensions, position handling, attention organization, and training objectives must be designed together with the overall architecture.
The potential benefit is that the back part of the network no longer has to build every historical state layer by layer for the full prompt.
Projection also has a cost. If each decoder layer still generates high-dimensional, full-length key-value representations, the global cache may still grow linearly with context length. Splitting responsibilities is only an entry point. It must be combined with compression and hierarchical access.
3. Why Prefill Cost Cannot Be Assumed to Drop by Half
Suppose the front part handles most of the full-prompt computation, and the back part processes only a local window while reading the global representation that was already built. Some computation may then indeed decrease.
Real prefill time, however, also includes global projection, cache compression, data layout conversion, device communication, and scheduling overhead. If the back part still needs heavy global attention, that cost must be counted as well.
So, a reduced network depth for the full prompt does not mean that end-to-end latency falls proportionally. Reliable conclusions must come from measurements on the same hardware, with the same input lengths, and under the same quality requirements.
4. Hierarchical Cache: Let Recent Details and Distant Evidence Serve Different Roles
Long-context tasks usually involve two kinds of information needs.
The first is precise dependence on recent content. Examples include tool results just returned, the current code snippet, and the paragraph being edited. These need high-fidelity local representations.
The second is access to distant evidence. Examples include constraints stated in early documents, important commitments made earlier in a conversation, and entity links across chapters. These need global retrieval capability.
Storing both in the same cache structure often wastes resources. A better approach is a hierarchy of states with different fidelity and different access ranges.
1. Local Windows Keep the Details
Local window attention accesses only a recent segment of history. With a fixed window size, this part of the cache does not grow without limit as the context grows.
Local windows suit continuous semantics, recent tool interactions, and local generation consistency. They cannot handle long-range dependencies alone. If an early constraint has left the window, local attention by itself may not produce a correct result.
2. Global States Handle Cross-Distance Access
Global states can control cost by reducing dimensionality, compressing historical representations, or selecting a subset of positions.
Reducing the number of accessed positions and compressing storage are different things. Reading only a few positions per query mainly reduces access and computation. If every position is still stored at full precision, the capacity problem remains.
Check these points separately:
- Whether all historical information is retained;
- Whether the retained data is the original state or a compressed representation;
- How relevant positions are selected during a query;
- Whether the compressed form can still distinguish similar but different
