Million-Token Context in Large Language Models: Technical Evolution and Engineering Practices
This article examines how million-token context windows in large language models evolved from a headline feature into a usable capability, and what it takes to ship it in production. It covers why sparse Mixture-of-Experts (MoE) architectures fit long-context workloads, why attention remains the primary bottleneck, and which data and training strategies support stable long-sequence behavior. It then walks through the engineering side: estimating KV cache memory, applying paged caching, prefix reuse, chunked prefill, continuous batching, and speculative decoding, organizing context in layers rather than filling the window, and building the surrounding serving infrastructure. It closes with a reproducible five-dimension checklist for evaluating long-context models, including retrieval accuracy at different depths, multi-hop reasoning, latency and cost, stability under very long inputs, and license terms.
1. From a “Longer Window” to a “Usable Window”: Reframing the Problem
Since 2026, long context has become one of the central directions in large language model iteration. After a major version release in the first half of the year, one model team announced general availability in mid-June, expanding the context window from roughly 200K tokens to the 1M token range while releasing the weights under a permissive open-source license. Two forces drove this pace. On the technical side, sparse architectures gradually matured, lowering the marginal cost of long-sequence inference. Externally, an overseas model service suspended access for users outside its home region due to export control requirements, pushing many developers to look for self-hostable alternatives in a short period.
The key point: “supports a 1M context” is not the same as “still produces high-quality output at a 1M context.” What actually matters in engineering practice is how long the effective context is, whether retrieval and aggregation over long sequences stay stable, and whether the memory and throughput costs are acceptable. This article therefore treats the topic as a general technical question: how to build and deploy million-token context inference for large language models.
2. The Technical Foundation: Sparse MoE and Attention Complexity
2.1 Why Sparse Mixture-of-Experts Fits Long Context
In a dense model, compute grows linearly with parameter count. MoE decouples total parameters from per-token compute by using a gating network that activates only a subset of experts on each forward pass. For long context, this matters because the attention cost introduced by longer sequences is unavoidable, but if per-token expert compute stays bounded, the overall cost curve flattens considerably.
A schematic routing logic looks like this:
# Pseudocode: Top-K sparse routinglogits = gate(x) # [batch, num_experts]topk_val, topk_idx = logits.topk(k=2, dim=-1)weights = softmax(topk_val, dim=-1)y = sum(weights[i] * expert[topk_idx[i]](x) for i in range(k))
In practice, load balancing loss, expert capacity factor, and communication overhead need attention as well. Otherwise, long sequences tend to produce expert skew, turning some devices into bottlenecks.
2.2 Attention Remains the Main Bottleneck
The time and memory complexity of standard self-attention grows quadratically with sequence length. The industry generally relies on three mitigations. First, sparse or local window attention, which computes only neighboring tokens and a set of globally important ones. Second, linear attention and state-space style structures, which compress history into a fixed-size state. Third, position encoding extrapolation schemes such as position interpolation and frequency scaling, which keep inference stable beyond the training length. Multi-query and grouped-query attention reduce KV cache memory substantially during long-sequence decoding by compressing keys and values.
2.3 Long-Context Data and Training Strategy
Architecture alone is not enough to support a million-token window. It also takes continued pretraining on long samples, retrieval-based synthetic data construction, and needle-in-a-haystack style position probing evaluations. A common approach is to first strengthen retrieval and multi-hop reasoning at moderate lengths, then extend the length gradually, avoiding instability in long-sequence training.
3. Engineering Delivery: Turning a Million-Token Window into a Service
3.1 Estimating Memory and Throughput
Take the KV cache as an example. Its memory footprint is approximately: number of layers × 2 × sequence length × hidden dimension × bytes per element of the chosen precision × concurrency. Increase the sequence length fivefold and the cache cost scales by the same factor, which is why long-context serving almost always depends on paged caching, prefix reuse, and quantization-based compression.
3.2 Key Optimizations in the Inference Path
- Paged KV cache: manage the cache in blocks to reduce fragmentation and enable cross-request prefix sharing;
- Prefix cache reuse: when the system prompt and long documents stay fixed, compute them only once;
- Chunked prefill: split very long prompts into chunks and combine with pipeline parallelism to lower time-to-first-token;
- Continuous batching: insert new requests dynamically during decoding to improve device utilization;
- Speculative decoding: a small model drafts and the main model verifies, with particularly clear gains under long context.
3.3 Context Engineering: Organize, Don’t Fill
The more effective strategy in practice is layered context organization: a stable layer (role and output rules), a retrieval layer (relevant passages), a conversation layer (recent turns), and a scratch layer (tool return values). Combined with retrieval-augmented generation and reranking to filter out irrelevant content, this often improves accuracy more than simply enlarging the window.
{"stable": "System role and output specification","retrieved": ["Passage A", "Passage B"],"recent": "Summary of the last few conversation turns","scratch": "Tool calls and intermediate results"}
3.4 Supporting Service Capabilities
Production environments typically need object storage to hold long documents, a message queue to decouple asynchronous tasks, a container platform to host elastic inference replicas, and logging plus monitoring and alerting to track time-to-first-token, throughput, and cache hit rate. For self-hosted open weights, model version management, canary releases, and rollback mechanisms should also be in place.
4. Selection and Validation Checklist
When evaluating long-context capability, run reproducible tests across five dimensions. First, retrieval accuracy for information placed at different depths. Second, multi-hop reasoning and global summarization quality. Third, time-to-first-token and cost per token. Fourth, stability and truncation strategy under very long inputs. Fifth, whether the license satisfies commercial use and redistribution requirements. The value of a permissive open-source license lies in being self-hostable, fine-tunable, and auditable, which is especially important for scenarios with strict data compliance needs.
5. Conclusion
The significance of a million-token context is not the number itself, but that it turns long-document understanding, whole-repository code analysis, and long-session memory from demos into deliverable capabilities. For developers, real competitiveness comes from combining architectural understanding with engineering optimization: use sparsity to control compute, caching and batching to control cost, and context engineering to control quality. Baidu AI Cloud provides general capabilities in model serving and compute scheduling that developers can build on to assemble their own long-context application pipeline.
