Trillion-Parameter MoE and Million-Token Context Architectures: A Technical Breakdown
This article examines how sparse Mixture-of-Experts (MoE) architectures can be combined with million-token context capabilities to support long-document understanding, repository-level development, and agentic tasks. It explains key attention designs such as Gated MLA and lower-bound KDA, MoE routing and load balancing, staged context expansion, agentic reinforcement learning, and memory/parallelism engineering. It also highlights common misconceptions and the practical costs behind trillion-parameter, million-token systems, without promoting any specific product.
1. Introduction: Why Focus on Sparse MoE and Million-Token Context
Large models are moving from simple question answering to long-document understanding, repository-level code development, and multi-step agentic task execution. This shift creates dual pressure:
- Context pressure: Documents, code repositories, and tool-call traces can contain hundreds of thousands to millions of tokens. Standard attention scales quadratically with sequence length, so memory and compute costs for long contexts quickly become difficult to control.
- Capacity pressure: Complex long-horizon reasoning requires greater knowledge capacity and deeper reasoning ability. Dense models typically scale all parameters proportionally, causing training and inference costs to rise together.
A representative technical approach combines sparse Mixture-of-Experts (MoE) with million-token context support and attempts to address both problems at once. Instead of debating whether a particular model is “strong,” a more fundamental question is worth asking: At million-token context length and trillion-parameter scale, which design choices actually work, and what engineering costs do they require?
At a Glance
| Dimension | Key content |
|---|---|
| Typical scale | About 2.8 trillion total parameters, about 104 billion activated parameters per token, with an activation ratio of about 3.7% |
| Multimodality | Native vision support with joint language-vision pretraining |
| Context | Pretraining progressively expands context from 8K to 64K, 256K, and finally 1M |
| Attention | Hybrid stacking of lower-bound gated linear attention (KDA) and gated latent attention (Gated MLA), with Block AttnRes |
| MoE | Latent-space routing, 896 fine-grained routed experts, SiTU-GLU activation, quantile balance (QB) |
| Post-training | Million-token-scale long-horizon agentic reinforcement learning |
Note: The parameters in the table summarize public technical reports and are only intended to illustrate a design paradigm. They do not represent measured performance of any specific product.
Key conclusion first: The value of this type of technical report is not the parameter count itself, but three engineering capabilities:
- Turning linear attention into high-performance kernels that can be executed efficiently.
- Keeping an extremely large sparse MoE stable and load-balanced during training.
- Making long context truly usable in both training and inference.
2. How to Evaluate This Kind of Technical Report
Open-source large-model technical reports usually cover architecture, data, training, evaluation, and open-source release. Four areas deserve particular attention, each of which is discussed later.
- The relationship between architecture and scale: What mechanisms support total parameters, activated parameters, and context length?
- Training recipe: How does pretraining expand context in stages, and how does the sparse structure avoid training collapse?
- Engineering details: How are parallelism, numerical precision, communication, and memory managed?
- Evaluation approach: Do benchmarks cover long context and agentic tasks, and is there a risk of training-data contamination?
3. Attention Layers: Balancing Efficiency and Global Capability at Million-Token Scale
3.1 Three Approaches: No Silver Bullet, Only Combinations
There are roughly three approaches to handling long context:
- Compressed and sparsified global attention: Compress the KV cache into a low-rank space, or let each token attend only to a subset of tokens.
- Linear attention: Replace per-token softmax computation with state recurrence. It compresses sequence information into a fixed-size state, reducing complexity from quadratic to linear, but its ability to perform lossless exact retrieval is weaker than full attention.
- Hybrid architectures: Interleave linear attention layers and global attention layers in a certain ratio, letting the former compress long-range information and the latter perform precise cross-distance retrieval.
For the scenario of “million-token context plus trillion parameters,” hybrid architectures are almost a necessary path. The real difficulty is not conceptual but lies in kernel implementation and numerical stability.
3.2 Gated Latent Attention: Compressing the KV Cache While Suppressing Irrelevant Information
The core idea of Multi-head Latent Attention (MLA) is to project each token’s key-value pair into a low-dimensional latent vector for caching, and then up-project on demand during attention computation. It also separates a dedicated rotary-position component so that compression and positional encoding do not interfere with each other. This is especially valuable for long-context inference:
- During decoding, every generated token must read the entire historical KV cache, and memory bandwidth is often the main bottleneck. A compressed KV cache directly reduces bandwidth pressure.
- Compared with “compressed memory” methods that aggregate several tokens into a summary, latent vectors preserve token-level information and are better suited for needle-in-a-haystack style precise retrieval.
“Gating” adds another layer of modulation on top of compression: the current token generates a gating signal that scales or selectively updates the compressed representation, allowing the model to suppress irrelevant information according to context needs. When inference frameworks implement paged KV caches, they must also adapt the cache layout for latent vectors plus positional components.
3.3 Linear Attention and Lower-Bound Decay: Engineering Progress for Intra-Block Parallelism
3.3.1 State Recurrence in Gated Linear Attention
Linear attention with a forgetting gate can be written as the following recurrence: each token first produces a decay factor; the old state is decayed by a proportion, then the new key-value information is written in, and finally the output is obtained by multiplying the query with the state.
If this recurrence is executed token by token, it can only run serially and cannot exploit hardware parallelism. Industrial implementations usually split the sequence into tiles of length C, use matrix operations in parallel within each tile, and perform a scan-style recurrence across tiles along the time dimension. Within a tile, the decay between row i and column j, where i ≥ j, is the accumulated product of two-step decay factors.
3.3.2 Numerical Risk: Underflow and Overflow in BF16
For off-diagonal blocks, where queries and keys are not at the same positions, it is possible to decay the keys first and then the queries and directly perform matrix multiplication, which is naturally suitable for Tensor Core.
Diagonal blocks handle intra-block attention, and many implementations need to construct the inverse of a cumulative decay matrix. The inverse of the cumulative decay matrix contains the reciprocal of cumulative decay factors, roughly in the form (e^{\Delta{ij}}), where (\Delta{ij}) is the difference between two log-decay terms. If the log decay is generated through a parameterization without a lower bound, such as a negative softplus, then (g_t) can approach negative infinity. In BF16, if the reciprocal exceeds the representable range, it overflows and must fall back to explicit pairwise position computation. For a tile width of 16, this path is difficult to map to matrix multiplication instructions and becomes a performance bottleneck.
Small note: A common misconception is that BF16’s 7 mantissa bits necessarily destroy precision in diagonal blocks. In fact, the issue is not mantissa precision but exponent overflow.
3.3.3 Lower-Bound Decay Parameterization: Solving Numerical and Expressive Problems with One Curve
KDA (Kimi incremental attention) provides a lower-bound decay parameterization scheme. Instead of using a lower-bound-less negative softplus for log decay, it uses a bounded scaled sigmoid:
import math# Illustrative implementation: bounded parameterization of log decayg_min = -5.0 # Fixed lower bound of log decay, usually a hyperparameterdef log_decay(a):"""Given gating-network output a, compute per-step log decay g_t = g_min * sigmoid(a).g_t ∈ (g_min, 0), equivalent retention alpha_t = exp(g_t) ∈ (e^g_min, 1].a can be positive or negative; the gate still adapts to the input."""return g_min * torch.sigmoid(a)# Check the numerical range of the inverse of the cumulative decay matrix in a 16-wide tilelo = g_min * 16 # Lower bound of cumulative log decay: -80print(f"Lower bound of cumulative decay e^lo = {math.exp(lo):.2e}") # ≈ 1.81e-35print(f"Upper bound of its reciprocal e^-lo = {math.exp(-lo):.2e}") # ≈ 5.54e34print("The maximum representable value in BF16 is about 3.39e38, and the reciprocal is still within a safe range.")
Key implementation points:
- Role of bounded parameterization: The parameter (a) can still be any real number, so the model can freely adjust how long information is retained. Only the retention rate is constrained to be at least (e^{g_{\min}}).
- Tile width and numerical range: The parameter lower bound and tile width together determine the worst-case numerical range. Implementations should validate this accordingly. If tile width increases significantly, the design must be re-evaluated, or higher-precision intermediate computation must be used.
- Gradient optimization: The derivative of the scaled sigmoid, (g_{\min}\sigma(1-\sigma)), is always nonzero and finite, making backward propagation smoother as well.
- Differences from gated linear attention and Gated DeltaNet: Compared with similar gated linear attention designs and Gated DeltaNet, this approach avoids a special branch for diagonal blocks. All causal blocks, both diagonal and off-diagonal, can use dense matrix multiplication, giving a unified kernel structure, simpler loop unrolling, and better register allocation and instruction-level parallelism. It also avoids computing and storing an inverse matrix for every diagonal block.
Deployment advice: Rather than copying a specific parameter value directly, it is better to abstract the idea into a general constraint—gating parameterization must satisfy numerical boundedness—and then re-derive a safe range for the target hardware.
3.3.4 Natural Fit with NoPE
Traditional Transformers rely on rotary position encoding to provide positional information, and scaling to million-token context often requires additional intervention. In linear attention with a forgetting gate, the decay itself acts as an implicit positional signal, so explicit positional encoding can be omitted entirely, known as NoPE. Because the decay already has a lower bound, extremely long sequences will not suffer numerical degradation from complete forgetting. This saves a dedicated adaptation step for extrapolating to million-token contexts.
3.4 Hybrid Stacking and Block Attention Residuals
3.4.1 Layer Ratio
A typical design alternates linear attention layers and global attention layers at a fixed ratio, for example one global layer for every three linear layers, and introduces sparse mechanisms such as sliding windows in some layers. About three quarters of the layers run at linear complexity, while the global layers handle precise cross-distance retrieval.
3.4.2 Block AttnRes: A Connection Patch for Deep Representations
Deep Transformers commonly suffer from representation degeneration: outputs across layers become too similar, and fine-grained information from shallow layers is difficult to propagate to deeper layers. Common mitigations include Pre-LN, depth-scaled initialization, and over-Bridge connections, but at the scale of dozens or even hundreds of layers, representation bottlenecks can still occur.
Block AttnRes follows an idea similar to dense connections: the output of one block is sent to several subsequent blocks as an inter-block residual. Compared with a layer-by-layer fully connected “deep dense” design, the number of connections depends on the number of blocks rather than the number of layers. This makes information paths denser while keeping overhead more controllable.
This design has three engineering considerations:
- Compute and memory: Additional residuals require extra attention computation and activation storage. With tensor parallelism, residual shards on each rank must be all-gathered before concatenation.
- Pipeline parallelism: Block-level residuals span multiple pipeline stages, requiring additional activation transfer between stages. Pipeline scheduling becomes more complex, and both bubbles and memory usage can increase.
- Source of gains: The benefit of Block AttnRes mainly comes from improved information flow and optimization. Designers may also adjust details such as layer normalization, so evaluations should use ablation studies to isolate the contribution.
3.5 Combining Native Multimodality with Long Context
Native multimodality means vision and language are jointly optimized during pretraining, rather than attaching a vision encoder to a language model. Key points include:
- Visual tokenization: Images are split into visual tokens, or processed by a vision encoder and then projected into the language model’s embedding space.
- Resolution and token budget: When high-resolution images, video frames, and long documents are combined, visual tokens can grow rapidly, requiring token budgets to be allocated dynamically according to resolution and task.
- Combination with long context: Charts, scanned pages, and long videos in documents naturally produce many visual tokens. Only when multimodality is combined with million-token context can tasks such as “an entire book with illustrations” or “several hours of screen recordings” be supported.
4. MoE Layers: How Trillion-Parameter Models Remain Both Sparse and Stable
4.1 Fine-Grained Experts: Enabling More Precise Routing
A key fact is that activated parameters are about 3.7% of total parameters. This means the model’s “effective capacity” is far smaller than 2.8 trillion, so total parameters and activated parameters should be distinguished during evaluation.
Fine-grained experts split a single expert’s intermediate dimension into smaller pieces and increase the number of experts, for example 896 routed experts, while a small number of shared experts carry general knowledge. This brings three benefits:
- The routing combination space grows combinatorially, allowing finer specialization.
- The absolute number of activated parameters per token decreases, making computation cheaper.
- However, more experts make all-to-all communication and load balancing harder, and routing quality requirements become stricter.
4.2 Latent-Space Routing: Solving Routing in a Lower-Dimensional Space
Routing can be performed in a latent space. The token representation is first compressed into a low-dimensional latent vector, and a small number of routing parameters then score it. This reduces routing computation and storage overhead. The cost is that the low-dimensional space may lose discriminative power, leading to homogeneous routing and some experts remaining idle. Auxiliary measures such as load balancing, expert grouping, and noise injection are often used.
4.3 Activation Function: A Variant Within the GLU Family
Feed-forward layers commonly use the Gated Linear Unit (GLU) family, with SwiGLU being the most common in industry. SiTU-GLU can be viewed as a variant: it replaces SiLU with a sigmoid-type transformation as the gating branch in the GLU structure.
Mathematically, it is not very different from SwiGLU, and the choice is mainly driven by empirical experiments. In trillion-parameter training, such choices need large-scale ablation, because details such as numerical precision and gradient distributions are amplified by scale. It is worth emphasizing that switching activation functions is a “nice-to-have” optimization; MoE stability depends mainly on routing and optimization rather than the activation function.
4.4 Load Balancing: From Auxiliary Loss to Loss-Free Balancing
4.4.1 Why Load Balancing Determines the Success or Failure of Sparse Training
Common failure modes in MoE training include:
- Routing collapse: A few experts are repeatedly selected, while the rest receive no gradient.
- Capacity overflow: Popular experts exceed their capacity and drop tokens, wasting compute.
- Slow-expert tail latency: Under expert parallelism, the slowest expert determines the duration of the entire step.
4.4.2 Two Main Approaches
- Auxiliary load-balancing loss: Add a balancing penalty on top of the language modeling loss. It is simple to implement, but it introduces gradients that are not perfectly aligned with the main objective, which can hurt model quality, and the coefficient must be tuned carefully.
- Loss-free balancing: Guide load by adding a “bias” to routing scores, while the model optimizes only the language modeling loss. The bias is adjusted dynamically according to load feedback: if an expert is overloaded, its score is lowered; if it is underloaded, its score is raised.
Quantile balance (QB) belongs to the latter class of ideas. It estimates load quantiles for each expert and dynamically sets capacity and thresholds accordingly. Quantiles are less sensitive to extreme outliers, so the same threshold scheme can adapt to both sparse and crowded situations, making it suitable for extremely large-scale MoE. The three approaches compare as follows:
| Dimension | Auxiliary-loss balancing | Loss-free balancing (bias method) | Quantile balance (QB) |
|---|---|---|---|
| Training objective | Language loss + balance term | Language loss only | Language loss only |
| Impact on model quality | Excessive balance coefficient can hurt quality | Relatively small | Relatively small |
| Hyperparameter sensitivity | Sensitive to balance coefficient | Sensitive to update step size | Sensitive to quantile selection |
| Additional overhead | Very low | One bias update per step | Requires estimating load distribution |
| Large-scale suitability | General | Relatively good | Relatively good |
# Illustrative pseudocode: core idea of quantile balancedef quantile_balance_adjust(load, capacity, q=0.9):"""load: number of tokens received by each expert in this stepcapacity: capacity limit of each expertq: load quantile. Using quantiles instead of the mean to set thresholds reduces the influence of extreme experts"""hi = quantile(load, q) # e.g., 90th-percentile load as the "overload" linelo = quantile(load, 1 - q) # Low-percentile load as the "underload" linereturn where(load > hi, -delta, where(load < lo, +delta, 0))
4.5 A Stability Checklist for Trillion-Scale Sparse Training
In addition to load balancing, large-scale MoE training commonly uses the following stability measures:
- Regularization: Add regularization to routing logits and normalization to attention scores to suppress numerical explosions.
- Routing initialization: Initialize routing outputs with positive and negative splits to improve early discriminative power and reduce collapse risk.
- Routing temperature annealing: Start with higher routing smoothness and lower it later, avoiding premature fixation.
- μP-style parameter transfer: Use proxy models for hyperparameter sweeps and transfer them to the target scale.
- Precision management: In mixed precision, keep sensitive modules in FP32 and apply gradient clipping.
- Observability: Continuously monitor expert load, routing entropy, gradient norms, and loss spikes, and roll back promptly when anomalies appear.
5. Training Recipe: Staged Context Expansion and Agentic Reinforcement Learning
5.1 Context Expansion: 8K → 64K → 256K → 1M
Instead of training directly at million-token context from the start, a more robust approach is to expand context in stages:
- 8K stage: Learn language, knowledge, and reasoning fundamentals at maximum throughput on short sequences.
- 64K stage: Introduce medium-length data such as long documents and long code, while adjusting the scaling coefficients of positional encodings.
- 256K stage: Greatly increase the proportion of long samples, with an emphasis on tasks that span multiple documents or involve long-distance dependencies.
- 1M stage: Keep only high-quality ultra-long samples and use a small learning rate for fine-tuning to prevent degradation of short-text capabilities.
Each stage requires three things:
- Adjust the attention implementation and parallelism strategy to avoid memory overflow.
- Mix “long samples” with the original short samples in proportion to prevent catastrophic forgetting.
- Train stress-test sets such as needle-in-a-haystack and multi-hop retrieval to validate the “effective context length.”
5.2 Data Mixing and Long-Context Synthesis
Long-context corpora are naturally scarce, so programmatic synthesis is common:
- Construction based on real documents: Concatenate code repositories, insert unrelated passages in the middle of a document, and embed questions that require reasoning across multiple sections in long text.
- Task level: Summarization, retrieval, multi-hop reasoning, long-code completion, and refactoring.
- Multimodal: Retrieval in text-image combinations and long-video question answering.
Synthetic data requires two precautions: the answer to a question should not depend only on the final paragraph, otherwise the model may degrade into “only looking at the tail”; and inserted distractor passages should not be too templated, otherwise the model may learn superficial patterns.
5.3 Post-training: Million-Token-Scale Agentic Reinforcement Learning
Million-token-scale agentic RL lets the model repeatedly try and fail in real tool environments, learning long-horizon task decomposition, error recovery, and multi-turn interaction. The main difficulties are:
- Sparse rewards: The task may only provide a success/failure signal at the endpoint, making it hard to give timely feedback for intermediate steps.
- Context inflation: Multi-turn interaction history grows rapidly, requiring context compression and memory mechanisms.
- Trajectory length and sampling efficiency: A single trajectory can contain thousands of tokens, making sampling expensive. This often requires asynchronous sampling, trajectory reuse, and batch-relative advantage credit assignment.
- Reward hacking: The model may exploit flaws in the reward function, such as mechanically stacking tool calls, requiring diverse tasks and human spot checks.
6. Engineering Deployment: Memory, Communication, and Cloud Deployment
6.1 A Memory Ledger: Item-by-Item Estimation
| Item | Main influencing factors | Optimization methods |
|---|---|---|
| Weights | Total parameters × precision bytes | Quantization, expert offloading |
| Optimizer states | Trainable parameters × precision bytes | ZeRO sharding, 8-bit optimizers |
| Activations | Sequence length × layer width × number of layers | Recomputation, sequence parallelism, context parallelism |
| KV cache | Number of layers × context length × concurrency | Latent-vector compression, paged management |
| Communication buffers | Parallelism strategy | Overlap communication with computation, gradient bucketing |
In long-context scenarios, optimization usually focuses on activations and the KV cache: activations grow linearly with sequence length, while the KV cache grows linearly with concurrency.
6.2 Parallelism Strategies: Trade-Offs Across Dimensions
| Dimension | What is split | Main communication | Typical use cases |
|---|---|---|---|
| Data parallelism | Batch | Gradient All-Reduce | General foundation |
| Tensor parallelism | Intra-layer matrices | All-Reduce / All-Gather | When a single layer does not fit or low latency is desired |
| Expert parallelism | MoE experts | All-to-All | Many experts, high sparsity |
| Pipeline parallelism | Layers (stages) | Point-to-point sends | Many layers, cross-machine training |
| Sequence/context parallelism | Sequence dimension | Ring/All-Gather | Ultra-long context |
A common lesson is that when the sequence is long enough, activation memory replaces weights as the bottleneck. In that case, introducing context parallelism is often more cost-effective than simply increasing tensor parallelism. MoE all-to-all communication is large and must be sufficiently overlapped with computation; otherwise communication will dominate step time.
6.3 Cloud Training and Inference: General Product Capabilities
If a similar architecture needs to be trained or deployed on a cloud platform, it is better to organize requirements by capability category rather than by vendor-specific product names:
- Compute resources: Container platforms host distributed training and inference, with elastic scaling to handle tidal workloads.
- Storage: Object storage holds training corpora and model weights, supporting version management.
- Data and flow control: Message queues decouple data preprocessing pipelines, while logging services centrally collect training logs.
- Observability: Monitoring and alerting track key metrics such as GPU utilization, memory watermark, loss spikes, and expert load.
For example, Baidu AI Cloud may be evaluated as one such option, depending on region and product availability. Specific features and configurations should be checked in the official documentation.
7. A Rational View: Several Common Misreadings
- “Trillion parameters mean trillion-level intelligence”: Activated parameters are only about 104 billion, so the actual computation is far smaller than the trillion total parameter count implies. Both evaluation and selection should focus on activated parameters and compute per token.
- “Supporting 1M context means effectively using 1M context”: The claimed window often differs from the actual effective length. Long-range retrieval and multi-hop reasoning evaluations should be examined carefully.
- “Linear attention can completely replace full attention”: Hybrid architectures still contain global layers for precise retrieval. When the proportion of global layers decreases, needle-in-a-haystack tasks need particular verification.
- “Loss-free balancing means no monitoring is needed”: Expert load, routing entropy, and related metrics still need continuous observation, and the hyperparameters of the balancing strategy itself also need tuning.
- “Numbers in architecture papers are all measured results”: Some performance data comes from specific hardware and kernels, and conclusions may reverse when migrated to other hardware.
8. Reusable Takeaways
- Lower-bound KDA decay: Use a scaled sigmoid to impose a fixed lower bound on log decay, eliminate the special branch for diagonal blocks, and let all blocks use Tensor Core matrix multiplication, while also reducing gradient risk in backward propagation.
- Quantile balance (QB): Use quantiles instead of the mean to set load thresholds, achieving fast dynamic balancing without introducing an auxiliary loss.
- Block AttnRes: Use block-level connections to mitigate deep representation degeneration while controlling memory and communication overhead.
- Progressive context expansion: 8K → 64K → 256K → 1M, with each stage paired with data mixing, parallelism adjustments, and effective-length evaluation.
- Stability engineering: Routing regularization, initialization, and temperature annealing, combined with continuous monitoring and fast rollback.
These techniques are not unique to any single model; they are common design ideas across similar open-source models. For developers, understanding the problem–mechanism–cost triangle behind each design is more important than chasing new models, and each design should be validated against the specific business scenario.
