Trillion-Parameter MoE Architecture: Training Stable Models with Million-Token Contexts and Sparse Experts
An open-source MoE multimodal model with trillion-scale parameters, sparse token activation, native multimodal input, and up to a 1M-token context highlights three engineering challenges: stable training under extreme expert routing, efficient attention over long sequences, and post-training for long-horizon agentic behavior. This article distills three reusable design patterns—bounded-decay linear attention, auxiliary-loss-free quantile-based load balancing, and block-level attention residuals—and adds practical guidance for staged context expansion, agentic post-training, deployment, and evaluation.
Introduction: Large-Model Engineering Is Fighting Three Hard Battles at Once
A 2026 open-source MoE multimodal model, referred to below as “the model,” disclosed several key facts in its technical report: its total parameter count reaches the trillion scale; each token activates only a small fraction of those parameters; it natively supports multimodal inputs such as vision; its context length can reach one million tokens; and it ranks near the top among open-source models on several public benchmarks.
The engineering value of this kind of model is not simply its parameter count. It is that the model compresses three of the hardest problems in current large-model development into one architecture:
- Can sparse activation still train stably under extreme routing conditions?
- Can attention keep compute and memory overhead under control at million-token sequence lengths?
- Can limited compute be used efficiently for post-training aimed at long-horizon agentic capabilities?
Using the model’s public technical information as a guide, this article extracts three designs with the highest reuse value. For each one, it explains the implementation logic, provides illustrative code, and offers practical recommendations. It also adds engineering perspectives on long-context training, post-training, deployment, and evaluation.
1. Architecture Overview: How Scale, Sparsity, and Multimodality Coexist
Before examining individual innovations, it helps to understand the overall architecture.
Large models usually scale along three dimensions:
- Parameter scale: more knowledge capacity.
- Sequence length: more context that can be processed at once.
- Modality count: a broader perception space.
These three dimensions constrain one another. More parameters increase communication and memory pressure. Longer sequences increase attention and cache overhead. More modalities make the input distribution more complex.
The model’s approach is a combination of three ideas:
- Ultra-sparse MoE.
- Hybrid attention.
Native multimodality.
Ultra-sparse MoE: total parameters reach the trillion scale, but each token is routed only to a small number of experts. Activated parameters are roughly 3% to 4% of the total. This preserves enormous knowledge capacity while keeping per-token computation far below what a dense model of comparable capacity would require.
- Hybrid attention: most layers use linear attention with a decay mechanism, giving near-linear complexity for long sequences. A smaller number of layers retain full attention to preserve global and precise retrieval ability. The two types are interleaved in proportion.
- Native multimodality: visual information is jointly modeled with text in the same sequence at relatively shallow layers, rather than being encoded separately and then concatenated. This makes cross-modal reference and mixed image-text reasoning more natural, but it also requires attention to handle a much longer sequence.
- Dense and sparse mixing: shallow layers retain some dense structure to preserve general representation quality, while deeper layers mainly use MoE to expand capacity.
| Architecture component | Role | Key trade-off |
|---|---|---|
| Trillion-scale total parameters with sparse activated parameters | Decouples capacity from per-token compute | Expert parallelism communication, memory usage, and routing load balance |
| Mainly linear attention with limited full attention | Near-linear complexity for long sequences while preserving precise retrieval | Numerical stability and long-range precision of linear attention |
| Gated Multi-Head Latent Attention (Gated MLA) | Low-rank compression of K/V reduces cache usage; gating adjusts information flow per head | Balance between low-rank expressiveness and compression rate |
| Gated GLU-style activation functions | Improves representational efficiency per parameter | Additional compute and memory from extra gating projections |
| Shallow layers partly dense; MoE and dense mixed by proportion in deeper layers | Shallow layers preserve representation quality; deeper layers expand capacity | Layer ratio needs empirical tuning |
| Native multimodal inputs such as vision | Unified sequence modeling for text and images | Visual tokens consume context budget |
Note: The items in this table are general summaries based on public technical information. Exact layer ratios, expert granularity, and hidden dimensions should be taken from the official technical report.
2. Reusable Design One: Decay Lower-Bound Constraints for Linear Attention
2.1 Why Long Context Requires a Different Attention Mechanism
Standard self-attention has compute and memory costs that grow quadratically with sequence length. In a million-token context, every token must interact with all previous tokens. This becomes difficult to sustain during both training and inference.
Linear attention replaces the attention matrix with a state matrix. Historical information is continuously compressed into a fixed-size state, so complexity drops to linear.
Traditional attention: O_t = Σ_{i≤t} softmax(q_t · k_i) · v_iLinear attention: S_t = S_{t-1} + k_t v_tᵀ, O_t = q_t S_t
However, continuously adding information can cause old information to remain too long. The model may struggle to forget information when needed.
Gated incremental linear attention introduces a decay factor c_t ∈ (0, 1):
S_t = c_t · S_{t-1} + v_t k_tᵀ, O_t = q_t S_t
- When c_t is close to 1, the state is retained for a long time, similar to long-term memory.
- When c_t is small, the state is refreshed quickly, similar to short-term memory.
- c_t is usually generated dynamically from the current token’s hidden state, making it data-dependent.
2.2 The Problem: Diagonal Blocks Become a Bottleneck in Chunk Parallelism
Token-by-token recurrence has low complexity but cannot fully exploit matrix multiplication accelerators and has poor parallelism.
In practice, chunked parallelism is commonly used. The sequence is split into chunks of length L. Computation recurs across chunks along the time dimension, while computation inside a chunk is performed with a single matrix multiplication.
For a single head and single channel, the output can be expressed as:
Block output = (Q · Kᵀ) ⊙ M ⊙ D + Q · S_prevwhere M[i,j] = 1(j ≤ i), D[i,j] = (c_{j+1} ··· c_i)^{-1} (j ≤ i)
- The off-diagonal part, Q · S_prev, is an ordinary matrix multiplication, so tensor cores can run at full speed.
- The diagonal part, Q · Kᵀ, requires element-wise multiplication with a lower-triangular mask and multiplication by D, which is the inverse of accumulated decay.
Within a chunk, the accumulated decay d may become extremely small. Its inverse 1/d may therefore become extremely large, or even overflow.
If d underflows to zero in limited precision, 1/d may become infinite. In that case, the diagonal block can only be computed element-wise and cannot be merged into the dense matrix multiplication path. The overall operator implementation is forced into two paths: one efficient and one inefficient. The diagonal block happens to sit on the critical path.
| Comparison | Original schemes such as GDN or GLA-style linear attention | Decay lower-bound constrained scheme |
|---|---|---|
| Diagonal block computation | Requires element-wise handling of accumulated decay and its inverse | Handled along the same path as dense matrix multiplication |
| Use of matrix multiplication accelerators | Some paths cannot fully exploit accelerators | Both diagonal and off-diagonal blocks can fully exploit accelerators |
| Numerical risk under low precision | Too-small decay can cause inverse overflow or underflow | The inverse has a determined upper bound and remains representable |
| Long-context extrapolation | Often needs extra positional encoding handling | Naturally suited to long-context extrapolation without explicit positional encoding |
2.3 The Mechanism: Constrain Log-Decay to a Bounded Interval
The core idea can be stated in one sentence: the constrained object is not the decay c_t itself, but its logarithm g_t = log c_t.
Original scheme: g_t = -softplus(θ_t) ∈ (-∞, 0)This scheme: g_t = g_min · sigmoid(w_t) ∈ (g_min, 0), g_min = -5c_t = exp(g_t) ∈ [e^{-5}, 1) ≈ [0.0067, 1)
The two parameterizations are theoretically equivalent in expressive range because both can cover any decay inside (0, 1).
The difference is that the unbounded parameterization allows g_t to take any negative value, while the lower-bounded parameterization compresses g_t into a known finite interval.
A common misunderstanding is that having a lower bound means the model can only have short memory. This is not correct. The upper bound of c_t is still 1, so the model can still learn decay close to 1 and retain very long memory. The only behavior being limited is the small region where forgetting is more aggressive than about 1/150.
Why choose -5?
Assume chunk length L = 16. The theoretical upper bound of the inverse of accumulated decay inside one chunk is:
max(1 / D[i,j]) ≤ e^{-g_min · (L - 1)} = e^{75} ≈ 3.7 × 10^32
This value is still well within the representable range of bfloat16, approximately 3.4 × 10^38, and remains far from underflow.
Without a lower bound, a single token’s decay could fall to around 10^-10. After a few tokens accumulate, the inverse could exceed the upper limit of float32.
import mathimport torchimport torch.nn.functional as Fclass BoundedDecayGate(torch.nn.Module):"""Lower-bounded log-decay gate (illustrative implementation, not official code)."""def __init__(self, d_model: int, g_min: float = -5.0):super().__init__()self.proj = torch.nn.Linear(d_model, 1) # Generate one scalar per tokenself.g_min = g_mindef forward(self, x: torch.Tensor):# x: [B, L, D]w = self.proj(x).squeeze(-1) # [B, L]g = self.g_min * torch.sigmoid(w) # Log-decay, strictly within (g_min, 0)c = torch.exp(g) # Decay factor, within [e^g_min, 1)return g, cdef tile_inverse_bound(g_min: float, tile_len: int) -> float:"""Estimate the theoretical upper bound of accumulated decay inverse in a tile."""return math.exp(-g_min * (tile_len - 1))
2.4 Benefits and Practical Recommendations
- Unified operator paths: all causal blocks use the same dense matrix multiplication path, without a separate diagonal-block branch. The kernel code is simpler, easier to optimize with generic GEMM template libraries, and easier to adapt to new hardware backends.
- Controlled memory access: there is no need to separately cache element-wise log-decay tensors for diagonal blocks. Intermediate results are reduced, lowering memory access pressure.
- Long-context friendly: linear attention does not depend on positional encoding to convey relative position. It naturally supports direct extrapolation and is especially suitable for building million-token contexts without explicit positional encoding.
When implementing this design, keep four points in mind:
- A tighter lower bound is not always better. If g_min is too small, for example -10, numerical risk can return. If it is too large, the ability to refresh quickly is weakened. Choose g_min based on the actual tile length.
- Tile length and numerical range must be considered together. The upper bound grows exponentially with tile length. Increasing the tile from 16 to 32 raises the upper bound from about 10^32 to about 10^65, exceeding the bfloat16 range. The tile length for linear attention should be conservative, or float32 accumulation should be used for intermediate values.
- Precision alignment matters. Before deployment, compare numerical results layer by layer against an fp32 reference implementation, especially for the later part of long sequences.
- Combine with global attention. A linear attention state is a compressed representation. It is less reliable than full attention for precise retrieval such as finding a needle in a haystack. It is usually necessary to keep a small number of full-attention layers or introduce sliding-window attention as a fallback.
3. Reusable Design Two: Auxiliary-Loss-Free Quantile Load Balancing
3.1 Routing Imbalance Under Extreme Sparsity
The key to MoE is that each token activates only a small number of experts. However, when the number of experts reaches hundreds or even thousands, load imbalance is amplified.
- A small number of popular experts receive most tokens and become compute bottlenecks.
- Many cold experts receive almost no gradient updates, so parameter utilization is low and memory is effectively wasted.
- Under expert parallelism, compute load can differ significantly across devices, and overall throughput is limited by the slowest device.
| Load balancing method | Common approach | Main problem |
|---|---|---|
| Auxiliary loss balancing | Add a load-balancing loss to the training objective, often using the dot product of assignment probability and actual load | The weight must be tuned carefully: too large harms the main task, too small fails to suppress imbalance; harder to tune as expert count grows |
| Capacity factor plus dropping | Set a capacity limit for each expert; overflow tokens are dropped or sent through a residual path | Loose capacity wastes compute and creates uneven communication; tight capacity loses information |
| Statistics-based dynamic balancing | Use runtime statistics, such as quantiles, to dynamically determine routing and capacity | No extra loss term and no balancing weight to tune; however, statistics must be globally consistent |
3.2 The Mechanism: Replace Loss Functions with Quantiles
Quantile load balancing changes load balancing from part of the loss function into a statistical constraint inside the router itself.
- During training, continuously track the distribution of token counts received by each expert, that is, expert load.
- Compute quantiles of this distribution and use them as a reference for a high-water mark of capacity.
- Experts below the high-water mark receive tokens normally. Experts above the high-water mark trigger rerouting, transferring overflow tokens to experts with the next-best scores.
- Statistics are updated with smoothing so they can track changes in training stage and data distribution.
Why use quantiles instead of the mean or maximum?
- The mean is sensitive to long tails. A single extreme expert with huge load can push the whole threshold upward.
- The maximum is equivalent to a blunt cutoff. If one expert is overloaded, capacity for the whole layer increases.
- Quantiles describe the real position of most experts in the load distribution and are more robust. For example, using the 85th percentile means about 85% of experts will not have capacity reduced. Only the most crowded experts are suppressed. This avoids individual experts being overwhelmed while also avoiding broad token dropping.
# Illustrative code: quantile-based dynamic capacity and overflow rerouting# (not official code)def quantile_capacity(load, q=0.85, smooth=0.99, state=None):"""Estimate per-layer capacity from expert-load quantiles; load: [num_experts]"""state = load.clone() if state is None else statestate.mul_(smooth).add_(load, alpha=1 - smooth) # Smoothed statisticshigh = torch.quantile(state.float(), q) # High-water mark: 85th percentilecap = (high * state / state.sum().clamp_min(1.0)).round().long()# Allocate capacity by current load share instead of spreading it evenlyreturn cap.clamp_min(1), statedef capacity_aware_route(scores, top_k=8, q=0.85, state=None):"""scores: [num_tokens, num_experts] routing scoresReturns (selected-expert mask, weights): [T, E], [T, E]"""num_experts = scores.shape[1]values, indices = scores.topk(top_k, dim=-1)mask = torch.zeros_like(scores).scatter_(1, indices, values) # Keep highest-score token per expertfor _ in range(2): # At most two rerouting roundsload = mask.sum(0)cap, state = quantile_capacity(load, q=q, state=state)overflow = (load - cap).clamp_min(0) # Overflow count per expertif overflow.sum() == 0:breakfor e in range(num_experts):if overflow[e] == 0:continuevictims = mask[:, e].topk(int(overflow[e])).indices # Lowest-score tokens yield firstmask[victims, e] = 0candidates = scores[victims].masked_fill(mask[victims] > 0, float("-inf"))nxt = candidates.argmax(dim=-1) # Move to next-best expert with capacitymask[victims, nxt] = candidates.gather(1, nxt[:, None]).squeeze(1)return mask, mask * scores
3.3 Key Implementation Points
- Global statistics: load must be aggregated globally across all devices participating in routing. Otherwise, different devices will use inconsistent thresholds, and rerouting decisions will conflict.
- Smoothed updates: if the statistics window is too short, capacity may fluctuate sharply with each batch, causing training instability. If it is too long, the statistics may fail to track changes in data distribution.
- Bounded rerouting: each token should be moved at most one or two times to avoid cascading rerouting and extra latency.
- Gradient handling: directly zeroing overflow positions cuts off gradients for those tokens. A better approach is to let rerouted tokens keep a small weight during computation. This preserves gradient signals while expressing that these experts are alternatives.
- Sample efficiency: unlike auxiliary losses, dynamic balancing does not require tuning an extra weight. It often removes the need for an empirical warm-up procedure to adjust balancing weight.
For extremely large sparse models, mechanism-based balancing is easier to reuse than parameter-tuning-based balancing across different scales and data mixes. However, the quantile level itself, such as 85%, is still a hyperparameter that should be tuned according to expert count and parallel topology.
4. Reusable Design Three: Block-Level Attention Residuals
4.1 The Dilemma of Deep Transformers
As Transformer depth increases, each layer’s output becomes more abstract. However, lexical and syntactic information learned in shallow layers can be diluted as it passes through later layers. Deep layers may struggle to reuse it.
Traditional per-layer residuals save every layer’s input and output as independent tensors. For long sequences, this is expensive.
Example: sequence length 1,048,576, hidden dimension 8,192, bfloat16 (2 bytes)Single-layer activation: 1,048,576 × 8,192 × 2 B ≈ 16 GB60 layers saved in full: ≈ 960 GB
If only layer-wise residual streams are kept, memory grows linearly with depth. If cross-layer connections are introduced, the number of AllReduce operations under tensor parallelism also grows with the number of connections.
4.2 The Mechanism: Share a Residual Stream Within Blocks and Inject Summaries Across Blocks
Block Attention Residuals work as follows:
- Divide L layers into several blocks.
- Keep normal residual connections inside each block. This requires little change and is easy to implement.
- At the end of each block, generate a compact block-level summary, such as pooled or gated weighted aggregation.
- Inject summaries from previous blocks into the attention input of later blocks, so shallow-layer information can be reused through a query mechanism.
The key is not whether cross-layer connections exist, but the cost of those connections. Saving every layer’s residual stream is linear in cost. Saving block summaries is constant in cost.
# Illustrative code: block-level attention residuals (not official code)class BlockResidualStream(torch.nn.Module):def __init__(self, layers, block_size, d_model):super().__init__()self.layers = torch.nn.ModuleList(layers)self.block_size = block_size# Retrieve shallow-layer information from block summaries using attention scoresself.query = torch.nn.Linear(d_model, d_model)def forward(self, x):blocks = [] # Save only block summariesfor i, layer in enumerate(self.layers):x = x + layer(x) # Normal residual within blockif (i + 1) % self.block_size == 0:blocks.append(x)if blocks:kv = torch.stack(blocks, dim=1) # [B, num_blocks, L, D]q = self.query(x).unsqueeze(1) # [B, 1, L, D]w = torch.softmax((q * kv).sum(-1) / x.shape[-1] ** 0.5, dim=1)x = x + (w.unsqueeze(-1) * kv).sum(1) # Inject shallow-layer informationreturn x
4.3 Benefits
- Memory: if one block is defined every 8 layers, a 60-layer model needs to save about 7 or 8 block summaries instead of 60 residual streams. The memory usage of block summaries is roughly on the same order as a single-layer activation, and can be lower if the sequence dimension is further pooled. Overall reduction can approach one order of magnitude.
- Communication: cross-layer information is passed through block summaries. Synchronization within a parallel group grows with the number of blocks rather than the number of layers.
- Expressiveness: deep layers can directly retrieve shallow-layer features, alleviating representation dilution. It also provides an additional information pathway for gradient flow.
Two issues should be avoided when using this design:
- If the summary is too coarse, such as global mean pooling, positional information may be lost.
- If blocks are too fine, the design may degenerate into per-layer connections, losing the memory and communication savings.
5. Context Construction and Training Strategy
5.1 Expand the Context Window in Four Stages
The model expands its context window progressively:
8K → 64K → 256K → 1M
- 8K stage: main pre-training stage, building language ability, world knowledge, and basic reasoning.
- 64K stage: introduce medium-length documents, multi-document comparison, and repository-level code corpora.
- 256K stage: add long reports, long code repositories, and multi-turn dialogue histories.
- 1M stage: focus on data mixture and stability, ensuring the model does not degrade at extreme lengths.
This approach follows the way capabilities form. Short context determines basic capability. Long context mostly extends the span over existing capabilities rather than requiring the model to relearn language. Directly jumping to one million tokens can waste compute and make training less stable.
Two engineering points also matter:
- Long-context data must be carefully constructed. Truly long documents are limited, so techniques such as long-text concatenation and document-level restructuring can expand the corpus. However, semantic discontinuities caused by concatenation must be controlled.
- Positional encoding should extrapolate smoothly. For full-attention layers that depend on positional encoding, the base frequency of rotary position embeddings should be adjusted as context length expands, avoiding distortion in the high-position region.
5.2 Use Million-Token Agentic Post-Training to Build Long-Horizon Reasoning
Long-context ability is not the same as long-horizon task ability. A model that can “read” one million tokens may still struggle to plan continuously, call tools, detect mistakes, and correct itself across a million-token task.
The model’s million-token-level agentic reinforcement learning post-training is designed for this gap.
| Typical pain point in long-horizon tasks | Possible engineering measures |
|---|---|
| Reward is extremely sparse; success is revealed only at the end | Introduce verifiable intermediate rewards, such as test pass/fail, format validity, and tool-call success |
| Credit assignment over long trajectories is difficult | Use stepwise backtracking, denser sampling at critical nodes, and decomposed advantage estimation |
| Tools and environments are unstable | Build reproducible sandbox environments and fix random seeds and dependency versions |
| Sampling is expensive | Expand trajectories on high-value prefixes and reuse computations from shared prefixes |
| Training is prone to collapse | Use sequence-level importance sampling, clipped ratios, and monitor entropy and reward variance |
6. User-Facing Capabilities and Access Patterns
From a product perspective, the model covers three scenarios that general users use most often:
- Document understanding: supports uploading documents, tables, and images for reading and analysis. Long-context ability determines how much material can be consumed at once.
- Content generation: drafting and rewriting reports, proposals, and marketing copy.
- Data analysis: statistical analysis, summarization, and visualization suggestions for structured tables and text data.
For access, a practical offering usually needs to balance “zero barrier” and “integration friendly”:
- For general users, out-of-the-box interactive interfaces and clients are typically expected.
- For developers and business teams, standardized APIs should be provided, along with basic capabilities such as authentication, rate limiting, and usage statistics.
7. Deployment and Evaluation Checklist Before Enterprise Adoption
- Memory budget: for sparse models, memory is mainly determined by all parameters, not activated parameters. Estimate using “parameter count × bytes per parameter + KV cache + activations,” and leave room for framework overhead.
- Parallel topology: use a combination of tensor parallelism, expert parallelism, and context parallelism. Under expert parallelism, align expert placement with device interconnect topology to avoid cross-machine All-to-All becoming a bottleneck.
- KV cache management: use paged cache allocation based on requests, and enable prefix caching to reuse computation for identical system prompts.
- Low precision and quantization: for inference, evaluate weight quantization such as 8-bit or lower and KV cache compression, but always validate accuracy loss on target business data.
- Long-context routing: not every request needs a million-token context. Use “retrieve then generate” or tiered routing to send requests to processing paths of different lengths, controlling cost.
- Observability: collect metrics such as time to first token, token generation speed, context length distribution, and expert-load skewness to support capacity planning.
- Cloud elasticity: model inference involves memory management, multi-machine communication, and elastic scaling. On cloud platforms such as Baidu AI Cloud, enterprises can use common capabilities such as containers, object storage, and monitoring/alerting as needed to build their own inference services. They can also use model-serving platforms to obtain API access and usage management, scaling elastically with business load.
To assess whether this architecture fits a business, the following order is recommended:
- Define the scenario: long-document understanding, codebase question answering, or agentic automation.
- Verify capability boundaries: whether long context is actually needed and whether multimodality is a hard requirement.
- Run evaluations on proprietary data: focus on long-context retrieval accuracy, multi-turn instruction following, and tool-call success rate.
- Calculate cost: estimate total cost of ownership using “cost per million tokens × average daily call volume,” and compare it with existing solutions.
Conclusion: Architectural Innovation Must Return to Reusability, Evaluability, and Deployability
From trillion parameters to million-token context, the real lesson from this model is not the numbers themselves. It is three engineering principles:
- Use mechanisms instead of parameter tuning. Make decay bounds and load balancing into analyzable, constrained mathematical structures, reducing reliance on empirical trial and error.
- Use hybrid architectures to exchange design choices for efficiency. Linear attention provides throughput for long sequences, full attention preserves precise retrieval, and sparse MoE decouples capacity from compute.
- Use progressive training to exchange shortcuts for stability. Context length should expand in stages, and post-training should focus on long-horizon capabilities, avoiding the risks of jumping directly to the final scale.
Developers do not need to copy the trillion-parameter scale. They can reuse the engineering ideas: validate decay lower bounds, quantile balancing, and block-level residuals on small and medium models, then perform precision alignment and benchmark evaluation on target hardware. This allows teams to obtain the benefits of long-context and sparse inference at lower cost.
