Rebuilding Attention for Million-Token Contexts
As context windows scale from tens of thousands of tokens to the million-token range, memory capacity and bandwidth—not compute—become the primary bottleneck. This article explains how to estimate KV cache size, compares two compression strategies (sparse selection and heavy compression), and outlines the data, training, and infrastructure practices needed to make long-context inference practical. Readers will find capacity formulas, selection guidance, sample masking logic, and a deployment checklist.
1. The Starting Point: Million-Token Context Changes the Memory Structure, Not Just the Window Size
When the context window grows from tens of thousands of tokens to the million-token scale, the first thing to break is not compute but the memory budget. Standard attention keeps a set of Key/Value vectors for every token. This cache grows linearly with context length and is multiplied further under batching and concurrency.
Assuming Batch=1 and 16-bit floating-point cache elements, capacity can be estimated with a simplified formula:
KVCache ≈ L_ctx × N_layers × N_kv_heads × (d_k + d_v) × 2 bytes
Here, L_ctx is the context length, N_layers is the number of layers, N_kv_heads is the number of key/value heads that are cached, and d_k/d_v are the per-head dimensions. With L_ctx set to 1,000,000 and 2 bytes per element, a typical multi-head attention structure alone pushes the cache into the hundreds of gigabytes (roughly 524 GB). That far exceeds the memory of a single device, so distributed partitioning or compression is mandatory.
Three basic conclusions follow:
- The core conflict in long context is cache capacity and bandwidth, not peak compute.
- Every long-context approach does one of three things: reduce the number of cached heads, lower per-element precision, or reduce the number of tokens that must be retained.
- Estimation must come first. Running the formula above before launch is far cheaper than tuning parameters after an incident.
2. Two Main Compression Routes: Sparse Selection and Recompression
To mitigate these problems, the industry has developed two complementary ideas: “look at fewer tokens” and “compress tokens harder.”
2.1 Compressed Sparse Attention (CSA-style)
This keeps full key/value precision but selects only a small subset of the most relevant historical tokens for each computation. Memory and bandwidth then scale with the number of selected tokens rather than the total length. The cost is an extra selection mechanism (such as summary-based scoring, chunk scoring, or routing), and selection quality directly determines whether long-range dependencies are truncated.
A common engineering compromise is hierarchical selection: coarse block-level filtering plus fine-grained computation within blocks, with a few global anchor tokens to ensure information is not discarded entirely.
2.2 Heavily Compressed Attention (HCA-style)
Instead of keeping key/value pairs per token, this compresses a contiguous span of tokens into fewer “compressed slots,” stored at significantly lower precision or smaller dimension, and runs the main attention computation over the compressed sequence. The benefit is a cache reduction of one to two orders of magnitude. The cost is that compression is lossy, and fine-grained information (exact numbers, rare identifiers) is easily lost.
2.3 How to Choose
- Retrieval, summarization, and code-base understanding: prefer heavy compression to maximize capacity.
- Long-document QA and tasks requiring precise localization: prefer sparse selection, or a hybrid of “heavy compression as the base plus sparse computation over local windows.”
- Either way, keep an “uncompressed near window” so local syntax and formatting stay intact.
Illustrative masking logic (pseudocode):
# Keep the near window fully, select distant blocks sparsely, plus a few global anchorsmask = local_window_mask(L, window=4096)mask |= block_sparse_mask(L, block=256, top_k_blocks=16)mask |= anchor_mask(L, num_anchors=8)attn = softmax(Q @ K.T / sqrt(d) + log(mask)) @ V
3. Data and Training: Long Context Is Taught
Structure only creates possibility; capability comes from data and training design.
- Data construction: use samples with real long-range dependencies rather than arbitrarily concatenated short documents. Concatenation teaches the model the wrong prior that paragraphs are unrelated.
- Progressive window expansion: stabilize training at moderate lengths first, then increase the target length gradually. Starting with a (long, sparse) combination makes convergence difficult.
- Position encoding extrapolation: length extrapolation must be designed together with the attention structure. A mismatch between the position scheme and the sparse pattern significantly amplifies far-range degradation.
- Layered evaluation: measure near-window accuracy, cross-segment coreference, global aggregation, and long-chain reasoning separately. A single average score hides problems.
4. Infrastructure: Push the Cache Problem Down to the System Layer
Algorithmic designs ultimately land in system implementations. Long-context inference typically requires these capabilities working together:
- Distributed parallelism: partition the cache across devices by layer, head, or sequence, with efficient communication.
- Paged cache management: split the cache into fixed blocks allocated on demand to reduce fragmentation and reserved waste.
- Prefix reuse: compute identical system prompts and document prefixes only once to cut repeated overhead.
- Quantization and mixed precision: store distant cache at lower precision while keeping the near window at high precision.
- Observability: track cache hit rate, memory watermark, time-to-first-token, and throughput through monitoring, alerting, and logging services.
- Elastic scaling: use container platforms and message queues for request queuing and replica scaling to handle resource spikes from long requests.
- Data side: version training corpora and checkpoints with object storage.
In general practice on cloud platforms such as Baidu AI Cloud, these capabilities are typically offered as standard categories—object storage, container platforms, logging services, and monitoring/alerting—so teams can combine them as needed instead of building the entire infrastructure stack themselves.
5. Deployment Checklist
- Estimate the cache size at the target length with the capacity formula and confirm whether compression is needed.
- Clarify whether the business prefers “precise information” or “global coverage,” and choose sparse selection or heavy compression accordingly.
- Design a hybrid structure: compressed distant context + high-precision near window + global anchors.
- Prepare real long-range dependency data on the training side and adopt progressive window expansion.
- Enable paged cache, prefix reuse, and distant quantization on the system side.
- Establish layered evaluation and online observability metrics, and keep regressing.
The competition in long context ultimately comes down to how much effective information a unit of memory can carry. Only by aligning structure, data, and infrastructure can you achieve both capacity and quality in million-token scenarios.
