Attention and Memory Optimization for Million-Token Context Windows
Scaling context to a million tokens is not just a matter of enlarging the window. This article explains why the key-value (KV) cache is the first real bottleneck, how to estimate its memory footprint, and which compression, positional, training, and serving strategies make long context usable in practice. You will learn how to size the cache, choose between local windows, sparse access, global compression, and quantization, align position encoding and normalization with each compression path, design training data that forces the model to use distant history, and build serving infrastructure around the cache lifecycle. The goal is to turn a nominal million-token window into a capability that actually runs.
Long-context capability is often understood as “just making the window bigger.” In engineering, the first wall you hit is the inference-time key-value cache: every token that has been generated or read in must retain the keys and values needed for later attention reads. When the context grows from tens of thousands to a million tokens, the cache size often exceeds the weights themselves, and batch size, concurrency, and acceptable latency all get bottlenecked by the same block of GPU memory. So a design aimed at a million tokens must answer three things at once: what exactly is stored per token, which history must be remembered precisely, and how the system moves the cache in and out without collapsing throughput.
1. Get the memory magnitude right first
In standard multi-head attention, every layer, every key-value head group, and every token stores one key vector and one value vector. Considering only a single request with half-precision storage, the footprint can be approximated as:
cache bytes ≈ context length × number of layers × number of KV heads × (key dim + value dim) × bytes per element
With a length of one million, dozens of layers, and common head counts and head dimensions, a full multi-head cache easily lands in the hundreds-of-gigabytes range. Grouped-query or multi-query attention reduces the number of KV heads and shrinks the cache proportionally to the head count, but the length term stays linear: widen the window tenfold and the cache grows roughly tenfold. So “reducing heads” is a necessary constant-factor optimization, but it is not enough on its own to support a million-token window.
When estimating, you also have to add prefix reuse, chunked prefill, and peak concurrency, rather than looking only at a single nominal length. The same model has completely different cache hotspots under “one very long document” versus “many medium-length sessions sharing a prefix.” Capacity planning should be based on the effective cache footprint at peak concurrency, with headroom reserved for activations, communication buffers, and framework overhead.
2. The goal of compression is recoverable history, not uniform information loss
What attention needs to preserve is not the full original representation of every token, but the historical evidence that later queries can still align to. Common approaches can be combined rather than used as replacements for one another.
First, local windows. Most tokens depend on nearby context. A sliding window limits each query’s visible range to a fixed width, and both computation and part of the cache can be evicted on a rolling basis by window. The window must cover the task’s real local structure, such as a function body in code or a paragraph in a document; too narrow a window causes failures in coreference and bracket matching.
Second, sparse access. Not every layer performs dense attention over the full history. Some layers or heads can attend only to downsampled positions, or select a few representative blocks by block. The sparse pattern must be indexable: at inference time the system must know “which blocks this query should read,” otherwise the compression exists only in the paper’s formulas while the kernel still moves data along the dense path. Block boundaries, downsampling stride, and selection rules should stay consistent between training and inference.
Third, a heavily compressed global channel. The sliding window handles the near range, but you still need a cheap global path to remember the setup at the start of the document, the table of contents, and key entities. The usual approach is to pool, merge, or apply a low-rank projection to the history so that the length of the global keys and values is far smaller than the original sequence. The higher the compression ratio, the more easily detail is lost, so it is suited to carrying “what the document is about” rather than replacing evidence that requires word-for-word alignment. In practice, local precise attention and global compressed attention are often combined in layers or heads: high fidelity nearby, low cost far away.
Fourth, key-value quantization and sharing. Moving from half precision to a lower bit width directly reduces the byte count, but the error accumulates across layers. In response, calibrate keys and values separately, use a higher-precision channel for outliers, and re-test perplexity and retrieval-style tasks on long sequences rather than looking only at short-text loss. Prefix caching is another kind of “compression”: the same system prompt or the same document prefix is materialized only once and shared across requests, effectively lowering per-user memory.
3. Position and normalization must match the compression method
Rotary position encoding writes relative distance into the keys and values. If keys are downsampled or merged across blocks, the rotation angle must correspond to the true position after merging, not reuse the deleted intermediate indices; otherwise distant queries align to the wrong relative distance. Using rotation on some dimensions while keeping the rest unrotated is meant to reduce high-frequency oscillation when extrapolating length; which dimensions participate in rotation should be fixed and kept unchanged during continued pretraining or long-context fine-tuning.
Applying root-mean-square normalization to the query, key, or selected branches inside attention is meant to control the magnitude of the compressed branch versus the full-dimension branch, preventing one path’s scaling from drowning out the other. It is not an optional numerical decoration: the variance of sparse and dense branches often differs, and without normalization, longer training easily produces loss spikes or attention-entropy collapse.
Attention sinks (often called absorbed tokens or stable starting positions) absorb a large amount of uniform attention mass and reduce the distribution drift that occurs after early tokens are repeatedly overwritten by later ones. If the cache strategy discards the start of the sequence, you must be explicit about whether these sink positions stay resident; dropping them makes a sliding-window model more prone to repetition or going off track during very long generation.
4. Data and training paradigm decide whether compression actually learns to use long history
The architecture provides a path to read long history; the data decides whether the model is willing to take that path. Training only on short text and then extrapolating the position encoding to a million tokens often leaves the model still using only nearby context. A more reliable curriculum is: first stabilize language ability at regular lengths, then gradually lengthen sequences and mix in samples that must look far back, such as constraints stated at the beginning of a document, cross-paragraph references, multi-document comparison, and definitions and calls in a large codebase.
The loss function itself does not distinguish “saw it” from “used it.” Evaluation should set up separate probes: the answer appears only tens of thousands to hundreds of thousands of positions away from the current token, with distractors nearby. If probe accuracy drops rather than rises after lengthening, the compression or sparse index is dropping key blocks, and you should fix the selection rules and position alignment first, rather than keep enlarging the window.
During continued training, batch size and sequence length must be considered together. With the same token budget, very long sequences reduce the number of samples per batch and increase gradient noise. You can use gradient accumulation to maintain the effective batch, but the cost of communication and activation checkpointing rises, so it needs to be budgeted together with the target context length rather than extended without limit.
5. Infrastructure should be designed around the cache lifecycle
For a million-token serving system, the core object is the cache block, not one contiguous tensor.
Paged management splits the cache into fixed-size blocks allocated on demand, avoiding fragmentation from reserving the maximum length for every request. When a request ends or the sliding window slides out, blocks return to the pool. Requests with the same prefix hit the same set of blocks and only prefill the incremental part.
Prefill and decode should be scheduled separately. Prefill is compute-intensive, while decode under a long cache is bandwidth-intensive. If both compete for the same executor, a very long prefill stretches the tail latency of short requests. Queue by remaining cache, prefix hit, and deadline, and set an admission threshold for the maximum cache per request.
On the kernel side, use chunked, fused attention implementations so that computation and cache reads and writes are pipelined by block, avoiding materializing the full attention matrix. The indices for sparse or compressed branches should first be turned into a block list on the host side or a lightweight device core, then handed to the main compute core for sequential reads, reducing random memory access.
Precision, offloading, and recomputation are the last safety valve. Hot blocks stay in accelerator memory, while cold blocks move to host memory or a remote cache in the style of object storage; the swap-in and swap-out granularity must equal the paging block, otherwise fragmentation cancels out the compression gains. When bandwidth is more expensive than compute, recomputing very cold history is sometimes more cost-effective than repeatedly moving it, but this only applies to reproducible prefixes, not to generation trajectories with random sampling that cannot be replayed.
Observability should include at least: cache bytes per layer, prefix hit rate, block fragmentation rate, prefill and decode time, and long-range probe accuracy. Without these metrics, the compression ratio and window width are just configuration items, and you cannot tell whether you saved memory or lost capability.
6. The order of trade-offs in practice
Proceed by dependency rather than turning on every switch at once. First use the formula to compute the cache ceiling under the target length, concurrency, and precision, and determine the required compression factor. Then introduce the sliding window and resident sink positions to ensure local tasks do not regress. Next add the global compression path and sparse block selection, and validate with far-range probes. Fix the position encoding and normalization along with each path. Only then apply low-bit quantization, paging, prefix sharing, and hot/cold tiering. Each step should be independently rollback-able, because failures at a million tokens usually show up as “occasional misalignment” rather than an immediate error.
A million tokens is not a matter of changing the length parameter in the attention formula. It is a system-design problem constrained jointly by cache layout, access sparsity, positional consistency, and serving scheduling. Once you align the memory formula, the read paths, and the evaluation probes, long context turns from a nominal window into a capability that runs.
