Million-Token LLM Architecture and Engineering Practices Explained
This article breaks down the engineering challenges of million-token context in large language models and how modern architectures address them. It covers a cost model for long-context attention and KV cache, hybrid attention designs that combine compressed sparse attention with local enhancement, KV cache compression and tiering techniques, training and inference practices for stability and throughput, and an evaluation framework based on efficiency, long-range recall, stability, and cost. Readers will find capacity estimation formulas, pseudocode, and a practical benchmarking workflow for moving ultra-long context from demo to production.
Introduction: From “Fitting It In” to “Affordable to Compute, Feasible to Store”
The capability boundary of large language models keeps being pushed higher by test-time scaling: models are expected not only to generate longer chains of thought, but also to retrieve, compare, reason, and make decisions across extremely long contexts. When the context grows from tens of thousands of tokens toward the million-token scale, the question is no longer whether the window can be advertised as supported. Three practical engineering questions matter instead: whether per-token inference compute is affordable, whether the cached state fits in memory, and whether long-range information remains reliably usable.
Standard Transformer self-attention grows quadratically with sequence length, which creates two direct bottlenecks. The first is FLOPs cost: generating each new token requires one access and one weighted aggregation over all historical Key/Value entries, so the longer the context, the higher the compute per token. The second is KV cache overhead: autoregressive decoding must cache the Key and Value representations of historical tokens at every layer, and at million-token sequences the cache becomes the main source of memory and bandwidth pressure, directly determining concurrency and unit cost.
Recent industry technical roadmaps (represented by the publicly described design ideas of a new-generation mixture-of-experts model) therefore define the goal as optimizing compute, storage, and stability simultaneously at million-token context, rather than simply extending the window. The discussion below follows the order: problem modeling, architecture design, cache optimization, training and inference engineering, and deployment evaluation.
1. Problem Modeling: Breaking Long-Context Cost into Optimizable Quantities
Before optimizing long context, write the cost structure explicitly. Let the sequence length be L, the hidden dimension be d, and the number of layers be N. The main overhead of standard attention can be approximated as:
Per-token attention FLOPs ≈ O(N * L * d) # Linear in context length, repeated at every layerKV cache memory ≈ 2 * N * L * d * bytes # 2 for K and V; bytes depends on precision
This yields three optimization tracks:
- Reduce the coefficient of “every layer, every token attends to the full history” by reshaping attention itself;
- Reduce the “bytes per token” of the cache by compressing the KV representation;
- Reduce the effective compute length through sparsification and hierarchical reuse.
One point deserves emphasis: any optimization must preserve long-range recall. If distant critical information is dropped to save compute, long context degrades into “short context plus noise.” The evaluation system must therefore track both efficiency metrics and long-range task metrics.
2. Architecture Layer: Why Hybrid Attention Has Become the Mainstream Choice
Relying on a single attention form rarely satisfies both efficiency and quality. The common industry approach is hybrid attention: attention modules with different characteristics are combined by layer or by block, so that “precise global retrieval” and “efficient local aggregation” divide the work. Two component types commonly described in public technical material can be abstracted as:
- Compressed sparse attention (understandable as a CSA-style component): historical tokens are first compressed at block or segment level into a small number of representative representations, and the current token attends only to these compressed representations, reducing complexity from “all tokens” to “a few summaries”;
- Hierarchical/local-enhanced attention (understandable as an HCA-style component): higher-resolution attention is kept within a local window to capture nearby details and local syntactic dependencies, while a hierarchical structure aggregates upward.
The logic of this combination is that local layers handle “seeing clearly” and compressed layers handle “seeing far,” and stacking the two brings per-token compute at million-token context into an acceptable range. Engineering practice usually adds the following:
- Attention head grouping and sharing: some heads handle global retrieval and others handle local modeling, reducing redundancy;
- Block-level sparse patterns: windowed access with a fixed block size, which favors operator fusion and memory continuity;
- Extrapolation-friendly positional encoding design: an extrapolable positional scheme combined with a training strategy, so positional relationships do not break after length extension.
Illustrative pseudocode (structure only, not corresponding to any specific implementation):
# Pseudocode: execution order of one hybrid attention layerdef hybrid_attention(x, kv_cache):local = local_window_attention(x, kv_cache, window=w) # High resolution nearbysummary = build_block_summary(kv_cache, block=b) # Block-level compressed representation for distant tokensglobal_ = compressed_attention(x, summary) # Low-resolution retrieval for distant tokensreturn fuse(local, global_) # Gated or weighted fusion
3. Cache Layer: KV Cache Compression Is Key to Long-Context Usability
Even with sparse attention, the cache remains the memory bottleneck. Common industry practices fall into four categories:
- Low-precision storage: the KV cache is stored at lower numerical precision, significantly reducing bytes, with per-channel scaling to limit accuracy loss;
- Low-rank/latent representation: Key/Value are projected into a lower-dimensional latent space for caching and restored when used, trading compute for memory;
- Cross-layer sharing and reuse: adjacent or grouped layers share part of the cached representation, reducing duplicate storage;
- Eviction and tiered swap-in/swap-out: a hot/cold hierarchy is built for the cache, inactive history segments are pushed down to host memory or external storage, and fetched back when needed.
Here is a capacity estimation template for capacity planning:
Cache memory (GB) ≈ 2 * layers * sequence length * hidden dimension * bytes per element / 1e9Example: 61 layers, hidden dimension 7168, sequence length 1e6, 2 bytes≈ 2 * 61 * 1e6 * 7168 * 2 / 1e9 ≈ 1.75 GB / request
At million-token context, a single request’s cache already reaches the GB scale, so concurrency is highly sensitive to cache compression and tiered management. In practice, “cache memory per request” and “cache hit rate” should be treated as core capacity metrics and included in monitoring, alerting, and logging.
4. Training and Inference Engineering: Stability and Throughput Matter Equally
Long context is not a problem that appears only at inference time; it must be addressed during training as well, otherwise “length extrapolation collapses” occurs. Common practices include:
- Progressive length extension: gradually extend from shorter sequences to the target length, with learning rate and data mix adjustments, avoiding one-shot extrapolation that destabilizes the attention distribution;
- Long-range data construction: add samples requiring retrieval, summarization, and comparison across long passages, so the model genuinely learns to use distant information;
- Numerical stability handling: scale and normalize attention logits to reduce overflow risk on long sequences;
- Continuous batching and paged cache on the inference side: split the cache into fixed-size blocks allocated on demand, reducing fragmentation and improving concurrent throughput;
- Separate deployment of prefill and decode: the prefill stage is compute-intensive while the decode stage is bandwidth-intensive, so separating them allows independent hardware selection and better overall resource utilization.
For deployment, million-context serving typically needs a container platform for elastic replicas, object storage for long documents and offloaded cache data, a message queue for request peak shaving, and logging plus monitoring and alerting for full-link observability. Baidu AI Cloud’s general cloud-native capabilities in these categories (containers, storage, queues, monitoring, and so on) can serve as a reference foundation, but the final selection should be based on load test results.
5. Evaluation: Don’t Only Look at “How Long It Supports”
Evaluating long-context capability should cover at least four metric groups:
- Efficiency metrics: per-token inference FLOPs, cache memory, time to first token, decode throughput;
- Long-range recall metrics: cross-passage retrieval, multi-hop question answering, structured extraction from long documents;
- Stability metrics: output consistency across different length ranges, robustness to positional offsets;
- Cost metrics: the curve relating unit request cost to the concurrency ceiling.
An executable evaluation process is to fix a task set, measure the above metrics at four length tiers (8K/32K/128K/1M), and plot a three-dimensional “length–cost–accuracy” curve to find a working point acceptable for the business. If accuracy drops sharply at a given tier while cost does not decrease, the sparse pattern or cache eviction policy needs adjustment.
Conclusion
The competition around million-token context has shifted from parameter scale and advertised window size to “effective context per unit cost.” Hybrid attention spreads out the compute, cache compression holds down memory, and training and inference engineering underpin stability and throughput. For developers, what really needs to be built is a quantifiable evaluation and capacity planning method: calculate cache and FLOPs first, then talk about window length, so that ultra-long context moves from demo to production.
