Inside a Trillion-Parameter MoE Multimodal Model: Architecture and Training Engineering

    This article breaks down the architecture and training engineering of a recently published trillion-parameter MoE multimodal large model, stripped of its product specifics so the reusable design ideas stand out. It explains how three attention mechanisms (linear/gated-delta attention, gated multi-head latent attention, and block-level attention residuals) work together, how extreme expert sparsity is kept stable through lower-bounded decay, quantile balancing, and a hierarchical activation function, and how multi-stage context extension and million-token agentic RL move a model from "reads long input" to "completes long-horizon tasks." It also covers the numerical constraints, evaluation frameworks, and production monitoring needed to adopt these techniques responsibly.

    Introduction: Why Are Flagship LLMs Converging on the Same Roadmap?

    Over the past couple of years, the technical reports for flagship large models released by leading teams have followed a strikingly similar path: parameter counts have entered the trillions, sparse activation keeps the cost of each forward pass in check, models natively support multimodal inputs such as vision, context windows have grown from tens of thousands of tokens to a million, and the post-training objective has shifted from “answer well” to “get the job done” on long-horizon tasks. Using a recently published MoE multimodal large model technical report as a sample, this article strips away the specific product characteristics and dissects the technical highlights along two dimensions: architecture design and training engineering. Readers can use it to understand how three attention mechanisms cooperate, how extremely sparse experts stay stable, and what validation and monitoring long context and agentic post-training demand in practice.

    A note up front: the specific numbers and trade-offs of different models vary, and the discussion below only extracts design ideas and engineering methods of general applicability.

    1. Scale and Design Goals at a Glance

    Dimension Key design Problem it solves
    Scale ~2.8T total parameters, ~104B activated per forward pass, sparsity ratio ~27:1 Expand knowledge capacity while controlling per-token compute
    Modality Joint language + vision pretraining, native multimodality Reduce the semantic misalignment caused by “bolted-on” vision modules
    Context Multi-stage 8K→64K→256K→1M Extend the effective window incrementally without wasting compute
    Attention Linear attention (KDA) + gated latent attention (Gated MLA) + block-level attention residuals Compute efficiency on very long sequences and cross-layer information reuse
    Sparse structure Stable LatentMoE: 896 routed experts + SiTU-GLU activation + Quantile Balancing (QB) Training stability under extreme sparsity
    Post-training Million-token-scale agentic RL Long-horizon reasoning and tool use for agents

    These designs do not exist in isolation; they revolve around three threads:

    • Efficiency thread: Linear attention lowers the compute complexity of long sequences, and latent attention compresses the KV cache. Together they support million-token context.
    • Capacity thread: Trillion-scale parameters provide knowledge capacity, while sparse activation keeps inference cost at the level of the activated parameters.
    • Stability thread: Lower-bounded decay, quantile balancing, block-level residuals, hierarchical ordered activation, and multi-stage context extension together reduce the risk of training divergence.

    These three threads interweave to form the overall framework of the report.

    2. Attention Layers: Actually Putting Sparse Attention to Work on the Hardware

    2.1 The Numerical Trap of Linear Attention

    The compute of standard self-attention grows quadratically with sequence length. At a million tokens, attention itself becomes the dominant cost. Linear attention rewrites “summing over all historical tokens” as a state matrix that can be maintained recursively, so both per-step compute and memory grow linearly with sequence length. This makes it well suited to long context and streaming inference.

    Gated delta attention adds decay and incremental-update mechanisms on top:

    • Decay term: controls how fast historical information is forgotten;
    • Incremental update: writes new information by the Delta rule, reducing mutual overwriting of old and new knowledge.

    These models typically compute in fixed-size chunks. Within a chunk, the state is rescaled by the reciprocal of the “accumulated in-chunk decay,” which lets the chunked computation still be expressed as matrix multiplications and take advantage of the GPU’s matrix-multiply units.

    The problem: the accumulated decay is a product of many factors smaller than 1, and its reciprocal can be very large. In conventional implementations, the log decay is generally taken as the negative softplus function, which is theoretically unbounded below. Once some direction keeps emitting very large activations, the reciprocal of the accumulated decay can exceed the representable range of bfloat16, becoming Inf or NaN and contaminating the whole chunk. As a result, engineering practice often has to fall back to a per-position-pair scalar computation path. This path is more numerically robust, but it is hard to vectorize, so the in-chunk computation effectively never uses the matrix-multiply units.

    2.2 Lower-Bounded Decay Parameterization: A High-Value-For-Low-Cost Change

    The fix in this report is to change how the log decay is parameterized. Replacing the unbounded negative softplus with a sigmoid gate that has a lower bound constrains the log decay to a controllable interval:

    g_log = g_min · σ(αh + βz_t), with g_min = −5

    where h is the hidden state, z_t is the input, α and β are learnable parameters, and σ is the sigmoid function. A sketch of the implementation:

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class LowerBoundedDecay(nn.Module):
    5. """Lower-bounded decay: the log decay is constrained to a range near [g_min, 0]."""
    6. def __init__(self, head_dim: int, g_min: float = -5.0):
    7. super().__init__()
    8. self.g_min = g_min
    9. self.A = nn.Parameter(torch.ones(1, 1, head_dim))
    10. self.B = nn.Parameter(torch.ones(1, 1, head_dim))
    11. def forward(self, h: torch.Tensor, z: torch.Tensor) -> torch.Tensor:
    12. # h, z: [B, H, L, D]
    13. # Apply a sigmoid gate to the input first, so that multiplying z directly
    14. # onto the log decay does not produce an unbounded range.
    15. a = torch.sigmoid(self.A * h + self.B * z)
    16. return self.g_min * a

    Numerical analysis

    • Single-step decay g = exp(g_log) ∈ [e^−5, 1), i.e. [0.0067, 1).
    • Assume a tile is 16 tokens, i.e. k = 16. Any in-tile accumulated decay Γ satisfies Γ ≥ e^−80 ≈ 1.8 × 10^−35.
    • Correspondingly, 1/Γ ≤ e^80 ≈ 5.5 × 10^34, which falls within the safe range of bfloat16. bfloat16 shares the same exponent bits as fp32, with a maximum of about 3.39 × 10^38.

    In other words, as long as g_min × k ≳ −87, the reciprocal will not easily overflow. The presence of a lower bound also brings a side benefit: the model retains at least an e^−80-level weight on the most recent k tokens, so in-chunk local information is never completely forgotten.

    Thus k, g_min, and numerical precision form a quantifiable constraint relationship. Other teams using gated linear attention can re-solve this inequality for their own precision, chunking strategy, and hardware capabilities rather than copying the specific values.

    Engineering payoff

    • Once the reciprocal is locked within a safe range, the in-chunk decay rescaling can first normalize all states to the same order of magnitude with a single shared scaling factor, then rewrite the per-position-pair multiplications as matrix multiplications.
    • The GPU’s matrix-multiply units are used more fully, and memory and communication overhead may also drop.
    • The implementation change only touches the value function of the decay parameters; it does not change the operator interface or the weight structure, so existing weights and parallelism strategies can usually be carried over.
    • This “constrain the range of parameter values in exchange for numerical stability” idea generalizes to RMSNorm scaling, attention softmax temperature, MoE routing logits, and any other place involving accumulation or exponentiation.

    2.3 Gated Multi-Head Latent Attention (Gated MLA)

    For the dense attention layers, the report uses gated multi-head latent attention. The core idea of multi-head latent attention (MLA) is that each token caches only a single low-dimensional latent vector that is independent of the number of heads, and the per-head K/V are then reconstructed by an up-projection matrix. So the KV cache no longer grows linearly with the number of attention heads. In million-token scenarios, this design directly determines whether inference memory stays controllable.

    Adding an input-dependent gate on top of the latent representation lets the model dynamically suppress or amplify specific information according to context needs, instead of passively accepting the information loss caused by compression. The costs are mainly three:

    • The attention implementation must cooperate with the latent projection and may not be able to use off-the-shelf efficient attention operators directly;
    • The gating parameters add to the parameter count, requiring extra memory and communication;
    • Both the compression dimension and the gating form become tuning parameters that need to be searched.

    2.4 Block Attention Residuals

    Deep Transformers commonly exhibit representation degeneration: the contribution of earlier layers may be diluted by later ones, and there is information redundancy across layers. Block attention residuals raise the granularity of the “cross-layer connection” from the layer to the block:

    • The sequence is split into token blocks;
    • Part of each block’s input is a softmax-normalized weighted sum of the attention outputs of several preceding blocks;
    • Because it is computed per block rather than summing token by token over all history, the memory and communication cost is tied mainly to the number of blocks.

    This design offers three benefits:

    • Every block receives the raw representations of preceding layers directly, shortening the gradient back-propagation path;
    • A preceding block only needs to retain part of its output for later blocks’ aggregation, lowering the memory footprint of cross-layer activations;
    • It is an architectural change and does not alter the base computational complexity of attention.

    A sketch of the implementation:

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class BlockAttentionResidual(nn.Module):
    5. """Block attention residual: the current block's input aggregates the partial
    6. attention outputs of several preceding blocks."""
    7. def __init__(self, max_blocks: int, inject_every: int = 2):
    8. super().__init__()
    9. self.logits = nn.Parameter(torch.zeros(max_blocks)) # inter-block aggregation weights
    10. self.scale = nn.Parameter(torch.zeros(1)) # injection strength, initialized to 0
    11. self.inject_every = inject_every
    12. def forward(
    13. self,
    14. block_id: int,
    15. x: torch.Tensor,
    16. partial_attn_out: list[torch.Tensor],
    17. ) -> torch.Tensor:
    18. # x: current block input [B, L, D]
    19. # partial_attn_out[i]: local attention output of block i [B, L, D]
    20. if block_id % self.inject_every != 0 or not partial_attn_out:
    21. return x
    22. hist = torch.stack(partial_attn_out[-self.logits.numel():], dim=0)
    23. w = F.softmax(self.logits[:hist.shape[0]], dim=0).view(-1, 1, 1, 1)
    24. injected = (hist * w).sum(dim=0)
    25. return x + torch.tanh(self.scale) * injected

    As the block size approaches 1, this structure degenerates into “a weighted residual over the outputs of all previous layers.” It can therefore be seen as a sparsified, along-the-sequence variant of dense cross-layer connections. The injection frequency, the number of blocks participating in the aggregation, and the injection strength are the hyperparameters to ablate with the most care.

    2.5 How the Three Attention Types Cooperate

    Combining the three attention types lets a single model serve different needs:

    • Most layers use linear attention to maintain long-range state cheaply;
    • A small number of layers use latent attention to provide precise global retrieval;
    • Block-level residuals gather representational information from different layers across layers and across blocks.

    This hybrid mode of “mostly sparse-linear plus a little dense” has become one of the mainstream choices for long-context models. The key to the design is determining the ratio and placement of linear versus dense layers, which usually needs validation through benchmarks such as needle-in-a-haystack, multi-needle retrieval, cross-segment summarization, and repository-level code Q&A.

    3. Sparse Layers: Training 896 Experts Stably Under Extreme Sparsity

    3.1 Expert Structure and Activation Function

    The model’s MoE layer contains 896 routed experts. Each token activates only a few of them, so the activated parameters are only about 3.7% of the total. A single expert is essentially a scaled-down Transformer block: its internal attention processes only the subset of tokens that expert receives, and the MLP between the up- and down-projections uses SiTU-GLU, a hierarchical variant of SwiGLU.

    A few terms can be understood as follows:

    • KDA: can be understood as one implementation route of gated delta attention, focused on recursive state updates, decay control, and chunked-compute efficiency.
    • Gated MLA: multi-head latent attention plus an input-dependent gate; the former compresses the KV cache, the latter strengthens dynamic selection over context.
    • SiTU-GLU: a hierarchical ordered variant of SwiGLU that emphasizes grouping of activation channels and more regular numerical distributions.

    The key points of SiTU-GLU include:

    • SiLU gating: smooth and non-monotonic, with generally friendly gradient properties;
    • Hierarchical structure: makes activations in different layers or groups closer in numerical distribution;
    • Latent-space compression: the up- and down-projections go through a low-rank latent space, trading a few extra parameters for storage and communication efficiency of the weight matrices.

    3.2 Auxiliary-Loss-Free Load Balancing

    The more extreme the sparsity ratio, the more prone routing is to a “Matthew effect”: a few experts get repeatedly selected and become stronger with training, while most experts get no gradient and the model’s effective capacity declines. The traditional approach adds an auxiliary balancing loss on top of the main loss, but it has two problems:

    • The extra gradient interferes with the main task, and its coefficient needs fine-tuning;
    • At trillion-parameter scale, it requires maintaining extra statistics and gradient synchronization.

    The Quantile Balancing (QB) approach in this report introduces no auxiliary loss; it only computes an expert bias vector dynamically during the routing-selection stage. The basic flow is:

    1. Count how many tokens each expert was selected for within the batch or a sliding window, and normalize to obtain a load distribution;
    2. Take a certain quantile of that load distribution as a reference: experts below the reference get a positive bias, those above get a negative bias, steering tokens toward the relatively cold experts;
    3. The bias only affects the top-k selection and does not change the routing weights used for the weighted sum after selection, so it injects no extra gradient into the main task.

    A sketch of the implementation:

    1. import torch
    2. @torch.no_grad()
    3. def quantile_balancing_bias(
    4. probs: torch.Tensor, # routing probabilities [B, L, E], E is the number of experts
    5. bias: torch.Tensor, # routing bias [E]
    6. top_k: int = 2,
    7. quantile: float = 0.5,
    8. rate: float = 1e-3,
    9. clip: float = 1.0,
    10. ) -> torch.Tensor:
    11. """Update the bias from expert load statistics; affects only top-k selection."""
    12. scores = probs + bias
    13. top_idx = scores.topk(top_k, dim=-1).indices
    14. # Count how many tokens were routed to each expert
    15. counts = torch.bincount(
    16. top_idx.reshape(-1),
    17. minlength=probs.size(-1)
    18. ).to(probs.dtype)
    19. # Normalize the load and use a quantile as the reference point
    20. load = counts / counts.sum().clamp_min(1.0)
    21. ref = torch.quantile(load, quantile)
    22. # Experts below the reference get a positive bias; those above get a negative bias
    23. update = torch.sign(ref - load) * rate
    24. return (bias + update).clamp(-clip, clip)
    25. def moe_route(
    26. probs: torch.Tensor, # original routing probabilities [B, L, E]
    27. bias: torch.Tensor, # balancing bias [E]
    28. top_k: int = 2,
    29. ):
    30. """Return top-k indices and weights; the weights come from the original probs,
    31. not from the bias-adjusted scores."""
    32. scores = probs + bias
    33. top_idx = scores.topk(top_k, dim=-1).indices
    34. # Output weighting still uses the original routing probabilities, so the
    35. # balancing bias does not change the output weights
    36. weights = probs.gather(-1, top_idx)
    37. return top_idx, weights

    A quantile, rather than the mean, is a more robust reference point for long-tailed distributions where “a few experts are extremely overloaded.” And because the adjustment happens only at the discrete selection level, the balancing process injects no extra gradient into the main task.

    It should be pointed out that the success of such methods depends heavily on batch size and statistics-update frequency: when the statistical noise is too large, the bias oscillates back and forth; when updates are too slow, it cannot correct in time. So dedicated ablations should be run before launch, and metrics such as the Gini coefficient of expert load, entropy, and the maximum expert share should be monitored.

    3.3 Stability from Hierarchical Ordering

    The hierarchical variant of SwiGLU organizes activations into hierarchical, ordered channel groups, making the magnitudes of each group’s activations closer to one another. This lowers the probability of a loss spike triggered by an individual channel with an excessively large value. This is in line with numerical-stability measures such as RMSNorm and z-loss: in large-scale training, stability often comes not from any single formula but from the accumulation of a series of small changes.

    4. Training and Post-Training: From Short Context to Long-Horizon Agents

    4.1 Multi-Stage Context Extension

    The report extends context in four steps during pretraining: 8K→64K→256K→1M. The rationale is straightforward: if you trained at the longest sequence the whole time, the attention cost would grow quadratically, while the vast majority of training data does not need such a long window. The arrangement can be summarized as:

    • 8K stage: build foundational language and multimodal capability with high-quality corpora;
    • 64K stage: introduce longer-structured data such as long documents, repository-level code, and web pages;
    • 256K stage: continue extending on fewer but more carefully curated long samples;
    • 1M stage: do final adaptation around high-value long-horizon tasks.

    For positional encoding, extrapolation methods such as RoPE base-frequency scaling can be used to let the model gradually adapt to longer distances.

    Two engineering points matter here:

    • Sequence packing: when packing multiple short samples into one sequence, use a block-diagonal attention mask or document-level attention reset so that different documents cannot see each other. Otherwise the model learns spurious cross-document dependencies, which is one reason many long-context models behave abnormally on short inputs.
    • Long-sample quality: million-scale long samples are scarce and noisy, so a stable data pipeline needs to be built on log services, object storage, and distributed storage, with deduplication, quality filtering, and license review for the very long samples.

    4.2 Agentic RL: Million-Token-Scale Post-Training

    Long context only means the model can “take in” the input; an agent still has to “get it done.” After pretraining, the report adds million-token-scale agentic reinforcement learning: under verifiable rewards, the model learns multi-step tool calls, code execution, and result reflection. It can be understood through four parts: problem, method, engineering cost, and acceptance metrics.

    Problem

    A single agent trajectory may span dozens or even hundreds of tool-call turns. Back-propagating directly over the full trajectory makes memory and scheduling costs hard to bear, and credit assignment over long trajectories is unstable.

    Method

    Common approaches include advantage broadcasting, trajectory-level rewards, importance-sampling correction, staged rewards, and local replay. Their core is to turn “whether the long trajectory ultimately succeeds” into several computable local signals, such as whether each step chose a reasonable tool, whether it produced a parseable result, and whether it completed an intermediate goal.

    Engineering cost

    The main costs come from environment management, tool sandboxes, trajectory replay, concurrent scheduling, and failure retries. This usually calls for a container platform to enable elastic scaling, together with a monitoring and alerting system to track environment availability and trajectory success rates.

    Acceptance metrics

    It is advisable to observe at least the following metrics:

    • Tool-call success rate;
    • Trajectory rollback rate;
    • Reward pass rate;
    • Average number of turns per task;
    • Overly-long-trajectory interruption rate;
    • Frequency of the reward being gamed.

    5. Three Engineering Practices Most Worth Reusing

    1. Lower-Bounded Decay Parameterization

    • Payoff: a small engineering change that lets the in-chunk computation of gated linear attention make fuller use of the matrix-multiply units.
    • How to reuse: first decide the chunk size and numerical precision, then set the decay lower bound accordingly; at the kernel level, replace the per-position-pair scalar path with the matrix-multiply path.
    • Risk: the lower bound limits the model’s ability to forget. If the task has no requirement to retain local information, the bound can be relaxed; otherwise, pair it with a larger chunk or higher precision.

    2. Auxiliary-Loss-Free Quantile Balancing

    • Payoff: suppresses expert collapse in extremely sparse MoE without introducing an auxiliary gradient.
    • How to reuse: add a bias computed from quantile statistics during routing scoring; it affects only top-k selection, not the output weighting.
    • Risk: with too small a batch or too frequent statistics updates, it tends to oscillate. Monitor balancing metrics such as the Gini coefficient of expert load, and adjust the statistics window and update step size accordingly.

    3. Block Attention Residuals

    • Payoff: breaks the representation bottleneck of deep networks while keeping memory and communication cost at block granularity.
    • How to reuse: maintain partial attention outputs per block, aggregate them with learnable softmax weights, and inject the result into the current block.
    • Risk: too high an injection frequency adds overhead; too low leaves insufficient cross-layer information. Using injection frequency as the first hyperparameter to ablate is recommended.

    6. From Technical Report to Production: Evaluation and Selection

    For teams that want to borrow these techniques, an evaluation framework can be built along four dimensions:

    • Capability: overall performance on standard benchmarks;
    • Efficiency: long-context time-to-first-token, throughput, KV-cache footprint;
    • Stability: task completion rate and regression rate on long-trajectory tasks;
    • Cost: training and inference cost per token.

    How to Choose a Model?

    Start by looking at the business workload, not just the parameter count. If the tasks are mainly long-document Q&A, code-repository understanding, and multimodal material analysis, focus on evaluating long-context efficiency, KV-cache footprint, and multi-needle retrieval ability. If the tasks are mainly agentic tool calls, focus on trajectory success rate, tool-sandbox stability, and reward design.

    How to Validate Effective Context?

    The nominal context length is not the effective context length. It is advisable to build a separate evaluation set that includes:

    • Multi-needle retrieval: hide multiple key pieces of information in a long text and require the model to locate and answer them;
    • Cross-segment reasoning: information scattered across different segments that must be combined to reach a judgment;
    • Long-document summarization: checks whether key constraints are missed;
    • Repository-level code Q&A: checks understanding of cross-file dependencies;
    • Overly-long conversation memory: checks whether information stays consistent across many turns.

    What Are the Common Mistakes?

    Common mistakes include:

    • Looking only at the activated parameter count and ignoring expert parallelism and memory-offloading strategies;
    • Running only capability evaluations, without latency, throughput, and memory stress tests;
    • Lacking document-level attention reset in the long-context stage, causing cross-document contamination;
    • Lacking expert-load monitoring after MoE launch, so expert collapse goes undetected;
    • Overly simplistic agentic RL reward design, leading the model to learn gaming shortcuts.

    Production Recommendations

    • Sparse does not mean low-cost: MoE inference usually needs to load, or be able to offload, all expert weights, depending on expert parallelism, memory offloading, and the inference framework. Before deployment, evaluate activated parameter count, number of experts, parallel sharding strategy, and hardware topology together, informed by monitoring data.
    • The engineering focus of long context: paged KV cache, prefix-cache reuse, quantization compression, and operator-level optimization often bring more direct cost benefits than merely extending the window.
    • Standardize platform capabilities first: the full model lifecycle involves compute scheduling, distributed and object storage, container platforms, log services, monitoring, and alerting. Some cloud platforms or cloud providers typically package these capabilities as standard components that teams can compose as needed, rather than building all the infrastructure themselves.
    • Keep the integration swappable: when building scenarios such as intelligent assistants, intelligent coding tools, or knowledge-base Q&A at the application layer, it is advisable to integrate model capabilities through standard interfaces. This allows flexible switching between models and A/B comparisons, avoiding lock-in to a single model.

    7. Limitations and Risks

    • Effective context: a nominal million tokens does not mean the model can retrieve precisely at any position. Independent validation with multi-needle retrieval and cross-segment reasoning tasks is recommended.
    • Training stability: the combination of trillions of parameters and extreme sparsity is very sensitive to communication and numerical precision. Any change should first be ablated at small and medium scale.
    • Reward design: once an agentic RL reward is gamed, long-horizon ability may actually degrade, so continuous red-teaming and regression testing are needed.
    • Cost control: a sparse architecture does not automatically mean low cost; it must be measured against business workload, concurrency model, and hardware supply.
    • Canary release: before launching a new model, new inference framework, or new routing strategy, support releasing by traffic percentage; first observe latency, error rate, expert load, and task success rate, then ramp up gradually.
    • Rollback plan: model weights, routing bias, context configuration, reward thresholds, and inference parameters should all be versioned. If a metric goes abnormal, one should be able to quickly roll back to the last stable version.
    • Key monitoring metrics: cover at least expert load, loss spikes, effective-context performance, trajectory success rate, tool-call success rate, reward pass rate, time-to-first-token, and memory footprint.
    • Data permissions and log auditing: training data, evaluation sets, user inputs, and tool-call logs should all have access controls, anonymization mechanisms, and audit records, to avoid leaking sensitive information during long-chain inference or replay.

    Conclusion

    The most valuable lesson from this technical report is not the two numbers—2.8T total parameters and 104B activated parameters—but the systematic trade-offs it makes among efficiency, capacity, and stability: lower-bounded decay keeps linear attention able to run, gated latent attention keeps long context storable, block-level residuals keep deep networks remembering, quantile balancing keeps the massive experts evenly distributed, and multi-stage context extension together with agentic RL let the model grow large and be useful.

    For engineering teams, rather than chasing parameter scale, it is better to introduce methods such as the numerical-constraint design, auxiliary-loss-free balancing, and chunked aggregation residuals into your own business scenarios step by step, and continuously measure their effect under real workloads. That is where the true reusable value of this kind of technical report lies.