Architecture and Engineering Practice for Million-Token Context in Large Language Models
Million-token context is now a core requirement for production LLMs, but simply stretching sequence length fails because attention cost grows quadratically and KV cache grows linearly. This article covers the architecture, data and training, and infrastructure choices that make long context usable, and the engineering tradeoffs that decide whether the model actually uses distant tokens.
Million-token context has become a core capability for deploying large language models. Conversation memory, repository-level code understanding, long-document question answering, and multi-turn tool use all require a model to cover hundreds of thousands to a million tokens in a single inference pass. Simply “stretching” sequence length does not work: standard attention scales quadratically with length, while the KV cache grows linearly and quickly becomes a hard limit on memory and bandwidth. This article focuses on techniques that are directly relevant to million-token context. It covers architecture, data and training, and infrastructure, and offers reusable engineering judgments rather than the marketing claims of any particular closed or open model.
Why Million-Token Context Hits the KV Cache First
Standard multi-head attention stores a set of keys and values for every token. With batch size 1 and KV stored in BF16/FP16, memory can be approximated as:
KVCache ≈ L_ctx × N_layers × N_kv_heads × (d_K + d_V) × 2 bytes
When L_ctx grows from 4K or 32K to 1,000,000, even grouped-query attention (GQA), which keeps the number of KV heads far below the number of query heads, still leaves a multi-layer, wide model with a cache on the order of hundreds of gigabytes. Multi-head attention (MHA) is worse at the same width. Million-token context therefore has to do three things at once: reduce the amount of KV that must be persisted, lower the compute density of long-range attention, and still make long-range dependencies retrievable.
In practice you also have to account for variable-length batches, paged cache, prefix reuse, extra slots from speculative decoding, and the accuracy–throughput tradeoff of quantization such as INT8 or INT4 KV. The formula is a lower-bound order of magnitude. A real system also pays for fragmentation, alignment, and communication buffers.
Architecture: Combine Compression, Sparsity, and Local Structure
Relative to “full dense attention plus full RoPE,” the usual path for very long context is to drop or weaken some high-bandwidth attention variants, introduce compressed sparse attention and highly compressed attention, and add RMSNorm, partial rotary position embeddings, sliding-window attention, and attention sinks in selected sublayers.
Compressed Sparse Attention
Not every query needs a dense dot product against every historical key. History can be split into learned or rule-based compressed blocks: aggregate inside a block, then match remotely, while keeping fine-grained attention over recent tokens. KV slots then change from “one set per token” to “full recent tokens plus compressed remote representatives,” so memory and bandwidth fall roughly linearly with the compression ratio. Implementation details that matter include compression granularity and window alignment, whether position information is lost at block boundaries, and whether the compression operator remains stable under backpropagation.
Highly Compressed Attention
On some layers or some heads, further reduce the dimension or head count of remote KV so that long range keeps only a summary channel. That channel is not meant to preserve per-token precision. It carries topic-, entity-, and section-level cues. Paired with compressed sparse attention, nearby or shallow layers usually keep higher resolution, while deeper layers compress more aggressively. The result is a resolution pyramid, so not every layer runs full-sequence dense attention.
RMSNorm in Selected Places
On very long sequences, the scale of activations and attention scores drifts more easily. Adding RMSNorm on the attention input, around the compression module, or on residual branches—not only at the start and end of a layer—helps stabilize dot-product magnitude and reduces overflow and attention collapse. Normalization, quantization, and mixed precision should be evaluated as one numerical policy, so that Norm does not amplify quantization error.
Partial RoPE
Full RoPE rotates every dimension. Under long extrapolation, high-frequency components distort easily. Partial RoPE rotates only some dimensions and leaves the rest as absolute or position-free features. That is a compromise between “relative position can extrapolate” and “content channels are not damaged by rotation.” When it is combined with a larger base frequency or piecewise position encoding, run extrapolation stress tests at medium lengths. Do not judge only perplexity inside the training length.
Sliding-Window Attention and Attention Sinks
A sliding window confines most computation to a local neighborhood, with near-linear complexity, which fits line-level code and within-paragraph reference. A window alone cuts long-range dependencies, so it is usually combined with global compressed heads or sparse global tokens. An attention sink explicitly keeps the KV of the sequence start or of special tokens, so later queries can always “see” a stable global reference and attention does not concentrate only on the most recent tokens during very long decoding. Window size, sink count, and compression ratio need to be searched together: too large a window brings compute back; too small a window fragments local meaning.
These mechanisms are usually stacked: fine-grained local windows, compressed sparse attention at long range, a few highly compressed heads, and inter-layer Norm plus Partial RoPE for numerics and position. Evaluation should report separately whether short tasks regress and whether long tasks actually use distant information. Do not rely only on synthetic needle-in-a-haystack scores.
Data and Training: Long Sequences Are Not Concatenated Short Data
Architecture only supplies capacity. Filling a million-token context depends on the data distribution and the training schedule.
The data needs to cover document-level coherence, cross-file code dependencies, distant constraints in multi-turn dialogue, and weakly structured long sequences such as tables and logs. Naively repeating and concatenating short samples produces sequences that look long but have short dependencies, and the model learns to ignore the middle. A more reliable approach is to build supervision that can be answered only by spanning tens of thousands of tokens, and to lengthen context gradually during pretraining rather than starting at full length on day one.
A common training combination is: thorough pretraining at medium length, then continued pretraining for long context (adjusting RoPE, windows, and compression modules), then mixing long samples into instruction and preference alignment. Besides language-modeling loss, auxiliary reconstruction or contrastive losses on compressed representations can stop the compression channel from collapsing to a constant. Curriculum length, the mix of lengths in a batch, and whether very long samples are down-weighted all affect short-task regression. If alignment is almost entirely short instructions, the model truncates effective context at inference time: it can ingest 1M tokens but only uses the last few thousand.
Infrastructure: Put Cache, Compute, and Communication on One Diagram
For million-token context, infrastructure is not about peak single-GPU FLOPs. It is about paging and offloading KV, whether attention kernels support block-sparse or compressed layouts, how sequences are split under pipeline and tensor parallelism, and how prefill and decode differ in compute shape.
Prefill is compute-heavy with large activations, so sequence parallelism or selective recomputation fits. Decode is limited by KV read bandwidth, so quantized cache, prefix sharing, and continuous batching fit. Compression and sparsity change the physical layout of KV. Kernels can no longer assume a regular [T, H, D] tensor; they need custom gather/scatter and a block table. Across nodes, communicate the compressed remote KV rather than synchronizing the full history.
On the storage and scheduling side, long requests occupy cache slots for a long time. Short requests need isolation so they are not stuck behind head-of-line blocking. Object storage or a fast cache can offload rarely accessed distant blocks, but hit rate and PCIe or network latency must be counted in end-to-end time per output token. Monitoring should be split out: memory watermark, KV hits, compression ratio, window hit rate, and effective context utilization (the distribution of positions the model actually weights highly). Otherwise it is hard to tell whether an optimization saved memory or hurt quality.
In the cloud, training and inference can sit on an elastic container platform, with logs and alerts tracking queueing and out-of-memory events for long requests, and checkpoints and data on object storage. These are general capabilities and do not depend on any vendor’s proprietary interface names.
Tradeoff Checklist for Production
- Memory: compression ratio, KV quantization bits, GQA head count, and whether compression is applied per layer.
- Quality: whether short benchmarks regress, whether long-range dependencies are detectable, and whether sinks and windows are interpretable.
- Latency: prefill throughput, decode bandwidth, and whether sparse kernels actually saturate the hardware.
- Stability: RMSNorm placement, mixed-precision overflow, and position encoding under very long extrapolation.
- Operations: variable-length batches, prefix reuse, offload policy, and request isolation.
Million-token context is a systems problem. Architecture supplies the freedom to be sparse and compressed, data forces the model to use distant information, and infrastructure makes the KV layout and operators runnable on a real cluster. Ablations along these layers produce a more maintainable capability than chasing a single paper number. As context keeps growing, hierarchical-resolution attention, learned compression, and better long-range evaluation sets will remain the main battleground.
