Trillion-Parameter Sparse MoE LLM Architecture: A Technical Breakdown

    This article breaks down the transferable engineering patterns behind trillion-parameter, million-token sparse mixture-of-experts (MoE) large language models. It covers hybrid linear and full attention with lower-bounded decay and block-level residuals, ultra-sparse MoE routing with quantile-based load balancing, a staged long-context curriculum from 8K to 1M tokens, and million-token agentic reinforcement learning. A practical checklist helps you decide which techniques to validate and reuse on your own models.

    When you open a model technical report advertising trillions of parameters, million-token context, and 896 routed experts, it is easy to fall into one of two traps. The first is to be captivated by the sheer parameter and length numbers and rush to “reproduce the same thing.” The second is to marvel at the long-context demos while overlooking the numerical stability and load-balancing problems behind them.

    In reality, the real value of this class of work lies in a set of transferable engineering patterns: how to scale attention under limited compute, how to keep extremely sparse routing stable, and how to turn a longer context window into agentic capability. This article draws on publicly available model technical reports to unpack these patterns layer by layer and offers practical advice on reusing them.

    1. Clarifying the concepts: from “AI assistant product” to “trillion-parameter sparse MoE model”

    Most people first encounter large models through a consumer-facing “AI assistant product.” These products typically accept long-form input, support document understanding, content writing, and data analysis, and are delivered through web pages, apps, and open APIs. They are the final outlet for model capability; the real technical foundation is the large model behind them.

    Recent public frontier model reports show a highly consistent direction:

    • Total parameters entering the trillions, with only a small fraction activated per token;
    • Native multimodal support (e.g., vision) fused from the ground up;
    • Context windows steadily pushing toward one million tokens;
    • Post-training aimed directly at long-horizon agentic tasks.

    This article focuses on the technical category of “trillion-parameter sparse multimodal LLMs” and the common designs that recur across public reports. For readability, I refer to these models collectively as “this class of model” and to their design ideas as “a certain style of public technical report.” Every parameter count, structure, and mechanism mentioned here is used only to explain technical principles and does not correspond to any specific product.

    2. Architecture overview: a hybrid-attention + ultra-sparse-MoE + native-multimodal backbone

    The core skeleton can be summarized as four tightly coupled parts:

    Module Core design Problem addressed
    Attention Gated delta-net linear attention (lower-bounded decay parameterization) mixed with gated multi-head latent attention; block-level attention residual shares information across layers Long-context attention cost; BF16 numerical stability; deep representation degradation
    MoE Routed experts combined with shared experts; expert parameters placed in a low-rank space (Latent MoE); gated activation variants; auxiliary-loss-free quantile balancing Load skew under extreme sparsity; numerical saturation; expert-count blow-up
    Multimodal Native visual input, modeled jointly with text Difficulty aligning a bolt-on vision adapter with the language backbone
    Training 8K→64K→256K→1M context curriculum pre-training; million-token agentic RL post-training Length extrapolation; long-horizon reasoning and tool use

    Take a typical configuration as an example: 2.8 trillion total parameters, roughly 104 billion activated per token—about 97% of parameters remain inactive; a single MoE layer has 896 routed experts plus shared experts.

    This is not merely “bigger” but “sparser.” The lower the activation ratio, the cheaper the compute per token—but the higher the demands on:

    • routing assignment quality;
    • communication efficiency of expert parallelism;
    • numerical precision during training.

    So judging whether this class of model is any good cannot rely on total parameter count alone. You have to examine the chain “attention → MoE → context curriculum → post-training” item by item.

    3. The attention module: lower-bounded decay + block-level residual

    3.1 Pain point: BF16 numerical risk and Tensor Core utilization

    The core of gated delta-net linear attention is a state recurrence with a forget gate. You can think of it as maintaining an ever-updating “memory matrix”: each time a token is read in, the old memory is scaled by a decay factor and then incrementally corrected with the new token’s key-value pair.

    Let the decay factor at position t be γt ∈ (0, 1). The effective decay between two positions i ≤ j is their cumulative product Γ. When computing in parallel over sequence blocks, the team typically first computes the within-block cumulative log-decay, then exponentiates it to get within-block attention weights. This fundamentally relies on the reciprocal of the cumulative decay: the relative weight of position j on an earlier position i is proportional to Γ_j / Γ{i+1}.

    Existing approaches usually parameterize the per-step log-decay as a negative softplus, g_t = -softplus(x_t). As the input approaches positive infinity, it approaches 0 and the decay slows indefinitely. The problem is that it has no lower bound: as long as x_t is small enough, g_t can go arbitrarily negative.

    This creates risk in two ways:

    • When the decay is too small and the cumulative product approaches 0, its reciprocal blows up quickly and overflows under low precision;
    • During backpropagation, the gradient of an exponential equals its output, so overflow rapidly degenerates into gradient explosion.

    To avoid this risk, a common engineering workaround is: for “diagonal blocks” shorter than 15, skip the matrix multiply and compute position-by-position (position-pair) instead. The result is that this segment cannot efficiently use Tensor Cores, becoming a performance sink within the linear-attention kernel, while branching the kernel logic and increasing maintenance cost.

    3.2 Mechanism: writing the decay lower bound into the parameterization

    The idea of lower-bounded decay parameterization is straightforward: replace the unbounded negative softplus with a lower-bounded, scaled sigmoid. The per-step log-decay is given by the following, where g_min is a configurable constant (this class of model uses -5):

    1. g_t = g_min · Sigmoid(w^T h_t), γ_t = exp(g_t)

    The sigmoid output is strictly confined to (0, 1), so g_t is clamped between (g_min, 0). Taking a block length L=15 as an example, the worst-case within-block cumulative log-decay is 15×(-5)=-75, and both the cumulative product and its reciprocal fall within a BF16-safe range.

    Intuitively, the model always retains a “minimum memory retention line”:

    • Even if a step “wants to forget completely,” the per-step decay cannot be faster than exp(-5)≈6.7×10⁻³;
    • True long-range memory is achieved naturally through multi-step chaining.

    From the kernel implementation standpoint, this is often overlooked. Take BF16: its exponent width is the same as FP32, and the maximum representable value is about 3.39×10³⁸. For the reciprocal not to overflow, the absolute value of the cumulative log-decay must not exceed about 88.7—that is, g_min·L must not fall below this order of magnitude. So the “decay lower bound” must be designed jointly with the “block length”; you cannot just pick a -5 and copy it.

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class BoundedLogDecay(nn.Module):
    5. """Illustrative implementation: lower-bounded log decay
    6. (for gated delta-net linear attention)"""
    7. def __init__(self, d_model: int, g_min: float = -5.0):
    8. super().__init__()
    9. self.g_min = g_min
    10. # Low-rank projection: first compute each position's
    11. # "forgetting tendency" x_t = W_g · h_t
    12. self.proj = nn.Linear(d_model, 1, bias=True)
    13. # Optional: output per-head decay rates in gated form
    14. # self.proj = nn.Linear(d_model, num_heads, bias=True)
    15. def forward(self, h: torch.Tensor, chunk_len: int = 15):
    16. # h: [B, T, D]
    17. x = self.proj(h).squeeze(-1) # [B, T]
    18. # Lower-bounded: g_t ∈ (g_min, 0); no longer uses -softplus(x)
    19. g = self.g_min * torch.sigmoid(x) # [B, T]
    20. # Numerical self-check: ensure the reciprocal does not
    21. # overflow within a block (BF16 threshold ≈ 88.7)
    22. worst = self.g_min * chunk_len
    23. assert abs(worst) < 80, "decay lower bound and block length mismatch: overflow risk under BF16"
    24. return g
    25. def block_decay_weights(g: torch.Tensor):
    26. """Within-block relative decay A[i, j] = exp(Σ g), i ≥ j (causal)"""
    27. cum = g.cumsum(dim=-1) # [B, L]
    28. log_a = cum.unsqueeze(-1) - cum.unsqueeze(-2) # [B, L, L]
    29. mask = torch.triu(torch.ones_like(log_a), diagonal=1)
    30. return (log_a.masked_fill(mask.bool(), float("-inf"))).exp()

    A few key points for reproduction:

    • Watch the scaling: some open-source gated linear attention implementations multiply the log-decay by a coefficient smaller than 1 to ensure the product does not decay to 0 at block length 32. After introducing lower-bounded parameterization, this coefficient needs to be recalibrated.
    • Adapt parallelism: tensor parallelism in training frameworks needs additional attention parallelism to correctly shard the forget gate. Once the operators are unified, this logic can be simplified.
    • Always measure: the benefit of this design depends heavily on kernel implementation quality. When evaluating, compare the two kernels—“diagonal block via position-pair” versus “diagonal block via dense matmul”—on the target hardware and confirm with real measurements.

    3.3 Extension: gated multi-head latent attention and positional encoding

    • Gated multi-head latent attention: it first uses low-rank projection to compress keys and values into a latent space to shrink the cache, then applies a learnable gate to the attention output to suppress noise activation along irrelevant directions. It is an “extrapolatable global attention” that complements linear attention on the “within-block / across-block” division of labor.
    • Positional encoding (NoPE): the decay factor itself carries relative positional information, so you can avoid relying on explicit rotary positional encoding. This helps window extrapolation, but the effect must be verified with position-extrapolation tests and cannot be assumed.
    • Practical constraints: the mixing ratio (some linear-attention layers paired with some full-attention layers), gate initialization, and coordination with normalization layers should all first be ablated on a mid-size proxy model before scaling up.

    3.4 Advanced: block-level attention residual

    A common problem in deep models: the attention module aggregates global information, but that information must be passed layer by layer to be used by deeper layers—the greater the depth, the more easily it decays.

    The idea of the block-level attention residual (Block AttnRes) is: divide several layers into a block, and let every layer’s attention output inside the block act directly on a shared block-level residual stream. The effect is like a cross-layer shortcut:

    • Deeper attention modules can directly see the global representation formed in shallower layers;
    • Gradient paths are shorter during training;
    • The shared attention residual stream reduces the memory and cross-device communication that each layer would otherwise maintain independently.

    When introducing this structure, pay attention to extra memory usage, initialization of the residual scaling coefficient, and an ablation comparison against the standard cross-layer residual.

    4. The MoE module: stability engineering under ultra-sparse routing

    4.1 Expert structure: routed experts + shared experts + low-rank experts

    896 routed experts means each token is processed by only a very few experts for the bulk of the computation. To offset the capacity loss from sparsity, this class of model uses three structural designs:

    • Shared experts: every token passes through them; they carry general knowledge;
    • Routed experts: differentiate by token content and learn specialized abilities;
    • Low-rank space (Latent MoE): expert weights no longer each maintain a full wide matrix; instead they are combined within a shared low-rank space, greatly reducing parameters and communication.

    This aligns with a naive intuition: more capacity does not mean every token must “use up” that capacity.

    4.2 Load skew: the “side effect” of auxiliary loss

    The traditional approach adds a load-balancing auxiliary loss that penalizes uneven assignment. But under extreme sparsity with only a few percent activation, it amplifies two problems:

    • The main-task gradient signal is diluted; if the auxiliary weight is slightly too large, it interferes with the language modeling objective;
    • The auxiliary term usually only acts on routed tokens, so the “dead expert” problem (experts that get almost no gradient) caused by expert expansion is not fundamentally resolved.

    4.3 Quantile balancing: replacing auxiliary loss with statistics

    The core idea of quantile balancing: instead of adding a term to the total loss, apply a dynamic bias to the routing scores. Concretely, track the sliding-window quantile of each expert’s load so that high-load experts’ scores are suppressed and low-load experts’ scores are raised.

    The following shows a “bias-based” implementation. Teams may differ in specifics; this only illustrates the idea:

    1. class QuantileBalancer:
    2. """Illustrative implementation: auxiliary-loss-free dynamic load balancing
    3. Idea: track the expert load distribution and adjust routing bias by
    4. quantile, so that actual load converges to the target distribution;
    5. the bias does not participate in gradient backprop.
    6. """
    7. def __init__(self, n_experts: int, decay: float = 0.99,
    8. q: float = 0.9, lr: float = 1e-3):
    9. self.n_experts = n_experts
    10. self.decay = decay
    11. self.q = q
    12. self.lr = lr
    13. self.bias = None # [E] routing bias, lazily initialized in the training loop
    14. @torch.no_grad()
    15. def update(self, router_logits: torch.Tensor, topk_idx: torch.Tensor):
    16. # router_logits: [N_tokens, E]; topk_idx: [N_tokens, k]
    17. e = router_logits.shape[-1]
    18. if self.bias is None:
    19. self.bias = torch.zeros(e, device=router_logits.device)
    20. # 1) Count how many times each expert is selected (E-step update;
    21. # you can also accumulate over steps and update once)
    22. counts = torch.bincount(topk_idx.reshape(-1), minlength=e).float()
    23. load = counts / counts.sum().clamp_min(1)
    24. # 2) Use quantiles as the "target line" to dynamically widen the gap
    25. # between high- and low-load experts
    26. hi, lo = torch.quantile(load, self.q), torch.quantile(load, 1 - self.q)
    27. target = (load - hi) * (load > hi) + (load - lo) * (load < lo)
    28. # 3) Low-load experts get a positive bias, high-load experts a negative bias
    29. self.bias.add_(-self.lr * target)
    30. self.bias.clamp_(-1.0, 1.0)
    31. return self.bias
    32. def balanced_topk(router_logits: torch.Tensor, k: int, bias: torch.Tensor):
    33. """Top-K routing with bias-adjusted scores"""
    34. scores = router_logits + bias.unsqueeze(0)
    35. return scores.topk(k, dim=-1).indices

    The benefits of this design are:

    • The balancing objective is independent of the main loss and does not pollute gradients;
    • The bias adapts to expert count automatically, with no manual tuning of the auxiliary weight;
    • The target distribution is set by quantiles, naturally tolerating load-scale differences across layers.

    Engineering details to watch:

    • Quantile window length, bias update rate, and bias cap are all hyperparameters to tune;
    • Whether the bias carries over at inference time and how it cooperates with the expert cache should be decided ahead of time in the serving design;
    • Routing scores should use the same precision as the main model.

    5. The context curriculum: 8K → 64K → 256K → 1M

    Pulling the context to 1M in one shot is expensive: attention cost grows quadratically with length, the KV cache grows linearly, and training memory and communication overhead both scale up. Pushing in stages is more robust, and there are two layers of logic behind it.

    The first is compute efficiency. The 8K stage spends most of its compute learning language and knowledge; by 256K and 1M, the training objective shifts to “locating and integrating information within ultra-long sequences.” Each stage’s data mix, learning rate, and batch size should differ from the previous stage.

    The second is data availability. Corpora that truly “need a million-token context” (complete code repositories, long documents, multi-turn dialogue histories) are relatively scarce. A common approach is to mix in long documents, repository-level code, and concatenated long dialogues by proportion, and to use position bucketing and document-level attention masks (different documents within the same packed sample cannot see each other) to avoid interference from irrelevant context.

    Three engineering points to note:

    • Migration order: structural changes like the attention residual from Section 3.4 are best completed in the short-context stage;
    • Curriculum scheduling: the pace of context-window expansion should be coupled with learning-rate decay and data mix;
    • Evaluation: use position-bucketed perplexity and retrieval-style tasks to verify that information use is balanced across depths, avoiding “middle forgetting.”

    6. Post-training: million-token agentic reinforcement learning

    Long-context capability does not equal long-horizon task capability. Agentic tasks often require dozens of tool calls, multiple file reads/writes, and retrievals, with decisions made across long trajectories. This class of model introduces million-token-context agentic reinforcement learning in post-training, with four key problems.

    1. Credit assignment: outcome rewards are sparse—only whether the task completed is known. You need trajectory-level advantage estimation, or process-reward design for intermediate steps, to reasonably distribute the final payoff to each step.
    2. Training-inference consistency: agentic inference involves tool calls, multi-turn interactions, and concatenation of retrieval results; the sampling environment during training must match the online serving environment as closely as possible, otherwise the policy overfits to a specific tool return format.
    3. Engineering cost: sampling under a million-token context makes each forward and backward pass extremely expensive. In practice, partial trajectory reuse, context compression, and retrieval caching are introduced to control sampling cost.
    4. Evaluation: long-horizon tasks cannot be judged by final-answer accuracy alone; you also need to examine step count, failure recovery, and tool-call success rate.

    7. How to reuse rationally: a practical checklist

    Technique Scope of change Main benefit Main risk Suggested priority
    Lower-bounded decay parameterization Attention operator Removes the diagonal-block special branch, improves kernel throughput Must be co-designed with block length; needs real measurement High: change parameterization first, then the kernel
    Quantile load balancing MoE routing layer Auxiliary-loss-free, suppresses load skew Many hyperparameters; inference must be consistent High: can validate first on a mid-size model
    Block-level attention residual Model structure Improves deep representations and gradient paths More memory and communication Medium: evaluate before large-scale pre-training
    Context curriculum Training pipeline Obtains long-context capability at lower cost Complex data mix and scheduling High: when long-context needs are clear
    Agentic RL Post-training Improves long-horizon task ability High environment cost, hard to evaluate Case-by-case

    For the vast majority of teams, there is no need to reproduce the entire architecture. A more pragmatic path is:

    1. Identify the bottleneck on your own task: is it long-context cost, expert load, or slow deep convergence?
    2. Pick a single technique for small-scale validation;
    3. Use metrics such as position-bucketed perplexity, expert-load variance, and convergence curves to judge whether it works;
    4. Then consider whether to roll it out to full-scale training.

    At the compute and infrastructure level, this class of work places clear demands on the foundation:

    • Training jobs typically run on containerized platforms;
    • Training data and checkpoints are stored in object storage;
    • Job status and logs are collected by a logging service;
    • Together with monitoring and alerting, this helps catch card drops, communication timeouts, and gradient anomalies promptly.

    If you use Baidu AI Cloud, these general capabilities can be integrated under a unified standard, without special customization for a single model design.

    8. Boundaries and misreading reminders

    Finally, let’s cool down the “trillion parameters, million context” hype:

    • Parameters and window: the activated parameters determine per-inference compute; the total parameters determine memory and serving cost. 896 routed experts mean routing and communication complexity rise sharply, raising the engineering bar;
    • Evaluation: long-context benchmarks each have their own focus; passing a “retrieval-type” one does not mean “integration-type” capability is there;
    • Agents: a million-token window expands the range of tasks that can be handled, but the more steps, the more obvious the accumulation of error and cost. Whether an ultra-long context is needed should be evaluated against the business scenario;
    • Usage advice: for ordinary-user needs like long-text processing, document understanding, and data analysis, prefer mature, well-validated service capabilities rather than implementing the entire architecture yourself.

    9. Summary

    The real lesson from this class of model is not “how big the parameters are or how long the window is,” but three transferable engineering judgments:

    • Attention: use bounded decay to write numerical stability into the parameterization, and use block-level residuals to improve deep information flow;
    • MoE: under extreme sparsity, transform load balancing from a “loss term” into “statistics-driven”;
    • Training: the context curriculum and agentic post-training determine whether the model can truly support long-horizon tasks.

    For developers, first understand the engineering problem each design solves, then make trade-offs based on your own data, compute, and business scenario—this matters more than copying any technical report.