How to Build Trillion-Parameter MoE Multimodal Long-Context Models
This article breaks down the engineering behind a new class of models that combine native multimodal input, trillion-parameter scale, and million-token context windows. It explains why long context, sparsity, and multimodal capability now appear together, then walks through the architecture: a sparse MoE backbone with hybrid attention and a three-stage training pipeline. The core technical takeaways are bounded decay parameterization for linear attention, auxiliary-loss-free quantile-based load balancing for MoE routing, and block-level attention residuals (Block AttnRes) for cross-layer reuse. The article covers the cost of quadratic attention, the mechanics of gated delta-rule linear attention and Gated MLA, multi-stage context extension (8K to 1M), long-horizon agentic RL post-training, and how application teams can turn million-token windows into stable, cost-controlled products. Readers will find both the reasoning behind each design and concrete guidance on implementation, validation, and reuse.
As long-context modeling and sparsification become the main axes of large-model evolution, a representative technical form is taking shape. It delivers native multimodal capability, reaches the trillion-parameter scale, and supports context windows of up to one million tokens. Public materials indicate that models of this kind have achieved leading results on open-model benchmarks. This article draws on a recently published class of technical reports to distill the design ideas with broad, transferable value. We cover both “why it is done this way” and “how to implement and validate it,” for readers working on model training, inference optimization, and long-document application development.
1. Requirements: Why Long Context, Multimodality, and Trillion Parameters Appear Together
1.1 Long Context and Native Multimodality Have Become Baseline Capabilities
The nature of the content we work with is changing. Enterprise documents, research reports, contracts, code repositories, and audio/video transcripts routinely run into hundreds of thousands of characters, and users want the model to “read it all at once and understand it as a whole.” At the same time, charts, scanned pages, and UI screenshots are mixed in with text, and the “recognize first, then understand” cascade pipeline is costly in both information loss and error accumulation.
These capabilities are typically delivered through three paths:
- Conversational and office assistants for general users;
- API access for developers;
- Platform-based or private deployment for scenarios with strict data-governance requirements.
Whatever the form, all of them rely on a unified model capability foundation rather than a separate custom build for each scenario.
1.2 Trillion Parameters and Extreme Sparsification
Scaling up parameters is the most direct way to increase model capacity, but for dense models the compute cost grows linearly with parameter count, which is hard to sustain. The sparse Mixture-of-Experts (MoE) architecture activates only a subset of parameters per token, decoupling “total capacity” from “compute per token” and providing a realistic path to the trillion-parameter scale.
Once capacity goes up, new tensions appear:
- The number of experts can reach hundreds or more;
- Routing noise and load skew are amplified by scale;
- Communication overhead rises;
- Training stability is put to a severe test.
1.3 Three Core Problems Distilled From This
Taken together, models of this kind must solve three problems at once:
- Compute efficiency for ultra-long context: at one million tokens, how to control the overhead introduced by quadratic complexity;
- Training stability under massive numbers of experts: how to balance load and avoid collapse under low-precision training;
- Agentic long-horizon capability: given interaction traces that can run to hundreds of thousands or even millions of tokens, can the model stay goal-consistent and complete multi-step tasks reliably.
The analysis below is organized around these three threads.
2. Overall Architecture: One Sparse Backbone and Three Stages
The design of this class of models can be summarized as “one sparse backbone, hybrid attention, three-stage training”:
[Images / charts / scans] --visual encoding--> projection alignment --+|[Long documents / dialogue history / tool returns] --tokenize & embed -+->[ Sparse MoE backbone (N layers) ]--> output head --> text|Most layers: bounded linear attention (gated delta-rule, KDA-style)A few layers: Gated MLA (full attention)Across layers: Block AttnRes shares attention outputsTraining: pretraining (8K -> 64K -> 256K -> 1M, multi-stage context extension) -> mid-training / domain enhancement -> post-training (million-token-scale agentic RL)
This design reflects a shared consensus in current large-model engineering: no single structure can solve every problem; the key is to let different structures each do what they do best.
- Sparse MoE handles capacity scaling;
- Hybrid attention handles long-context efficiency;
- Cross-layer sharing and bounded parameterization handle training stability and operator efficiency;
- Staged training and reinforcement learning push capabilities all the way to the million-token scale.
3. Evolution of Attention: From Quadratic Complexity to Hybrid Structures
3.1 The Cost of Quadratic Complexity
In standard self-attention, every token interacts with all historical tokens. Ignoring constant factors, with hidden dimension d, number of layers n_layer, and sequence length L, the attention compute for a single token in a single layer is roughly 4·L·d FLOPs.
A quick estimate:
- With d=8192, n_layer=61, increasing the sequence length from 4K to 1M;
- The per-token attention compute grows from roughly 8×10^9 to 2×10^12 FLOPs, an increase of about 256x.
At the same time, the KV cache grows linearly with length, and memory quickly becomes the bottleneck. In other words, simply adding memory cannot solve the long-context problem; you have to start from the attention structure itself.
3.2 Linear Attention and the Delta Rule
Linear attention compresses history into a fixed-size state matrix S, turning “backtracking token by token” into “updating state token by token”:
S_t = A_t · S_{t-1} + β_t · v_t · k_t^To_t = S_t^T · q_t
Here A_t is the forgetting (decay) term, and β_t is the write strength. The delta rule (DeltaNet-style) adds a key improvement on top of this: before writing a new value, it first erases the old value associated with k_t from the state, making the state update closer to “online correction.”
The gated delta rule can be written as:
S_t = α_t · (I − β_t · k_t · k_t^T) · S_{t-1} + β_t · v_t · k_t^T
- α_t ∈ (0,1] is a per-channel scalar gate that controls how fast old state is forgotten;
- β_t ∈ (0,1] is the write step size, balancing “preserving old knowledge” against “overwriting outdated knowledge.”
The advantage of this structure is that both compute and state update are linear in the sequence length. The limitation is equally clear: the state has fixed capacity, so on its own it struggles to do precise needle-in-a-haystack retrieval. For this reason, the industry generally adopts a hybrid scheme of “linear layers as the main body, full-attention layers as a supplement.”
3.3 Gated Multi-head Latent Attention (Gated MLA)
The idea behind Multi-head Latent Attention (MLA) is to compress each token’s K/V into a low-rank latent vector c, have all heads share the same latent representation, and cache only c (plus a small amount of decoupled position-related keys). Because the cache is independent of the number of heads, memory overhead drops sharply under long context.
“Gated” means adding an output gate on each attention head:
g = σ(W_g · x) # per-head, per-channel gate valuesy = g ⊙ softmax(Q·K^T / √d_k) · V
The gating brings three benefits:
- It suppresses over-attention to a few “accumulating” tokens (attention sinks);
- It provides per-token, per-channel control of the information flow, similar to transform gating in highway networks;
- It smooths the attention distribution and, indirectly, improves numerical stability under low-precision training.
3.4 Block-Level Attention Residual (Block AttnRes)
Deep Transformers commonly suffer from two kinds of degeneration:
- Representation homogenization: deep token representations converge, and attention entropy drops quickly;
- Gradient and memory bottlenecks: layer-by-layer stacked K/V are repeatedly generated and passed between layers, adding memory and communication overhead.
The idea of attention residual is to make the output of an “attention block” a resource that can be shared across layers: attention results produced in shallow layers can be reused by several subsequent layers, so that deep layers only handle transformation and combination rather than generating complete K/V from scratch every time.
A schematic form can be expressed as:
# Layer j within block io_i,j = Attn_i,j (h_i,j)c_i,j = o_i,j + Σ_{t ∈ R(i,j)} γ_t · o_i,t # R is the set of reusable shallow attention blocksh_i,j+1 = h_i,j + c_i,j
The benefits can be summarized in three points:
- Gradients can flow directly from “shallow-layer output to deep-layer fusion point,” shortening the gradient path in deep layers;
- Redundant K/V generation and inter-layer transfer are reduced, lowering memory and communication overhead;
- The distinctiveness of deep token representations is enhanced.
4. Three Technical Points With the Highest Reuse Value
4.1 Technical Point 1: Bounded Decay Parameterization for Linear Attention
Reuse value: high. The engineering change is minimal, mainly in gate computation and operator calls.
The pain point. Linear attention operators (whether vanilla linear attention or the gated delta rule) rely on chunked parallelism. Chunked parallelism splits the sequence into segments of length C (C is commonly 16 or 64):
- Between chunks: state S is passed sequentially, equivalent to one “state × key-value” matrix multiply;
- Within a chunk: with a UT-transform-like technique, the intra-chunk causal product accumulation is written in matrix form.
The problem is that the standard linear-attention within-chunk formula requires multiplying Q by the reciprocal of the accumulated decay Γ_j^{-1}:
U_i = Σ_{j≤i} [ q_i / Γ_i ] · [ Γ_j · k_j · v_j^T ]
Γj = ∏{t=1..j} α_t is the accumulated decay up to position j.
If the parameterization uses the common -softplus(w), then when w is large, log α can trend toward very negative values without bound, α approaches 0, and the reciprocal Γ^{-1} blows up exponentially within a chunk. Under finite precision such as BF16/FP16, it will quickly overflow, or turn into Inf/NaN on the next multiply.
The engineering consequence: only the diagonal blocks (near the diagonal, local blocks with small position differences) must fall back to an explicit “position-pair” compute path and cannot use efficient dense matrix multiply. Off-diagonal blocks can use matrix multiply, so the whole attention operator is forced to split into two paths of unequal speed, which both increases implementation and maintenance cost and drags down hardware utilization.
The mechanism. Bounded decay parameterization changes the log-decay from an unbounded negative softplus to a scaled sigmoid with a lower bound:
log α = g_min · σ(w) # g_min is a negative constant, e.g. −5; w is the gate network output
At this point:
- log α ∈ (g_min, 0);
- the reciprocal of the within-chunk accumulated decay satisfies Γ_C^{-1} ≤ e^{−C·g_min};
- with C=16, the worst case is about e^80 ≈ 5.5×10^34, still within the representable range of BF16 (BF16 max is about 3.4×10^38).
The end result is:
- All causal blocks (both diagonal and off-diagonal) are handled uniformly as dense matrix multiply, so the operator path converges to one;
- The matrix multiply sizes are more regular, making better use of tensor cores;
- The memory-access pattern is consistent, the kernel implementation is simpler, and it is easier to extend to changes in head dimension.
Implementation notes.
import mathimport torchCHUNK = 16 # chunk size, commonly 16 or 64def log_decay_bounded(w, g_min=-5.0):"""Bounded decay: w is the gate network output; returns per-token log α in (g_min, 0)"""return g_min * torch.sigmoid(w)def log_decay_softplus(w):"""Traditional parameterization: -softplus(w), unbounded, prone to numerical underflow"""return -torch.nn.functional.softplus(w)# Magnitude of the reciprocal of within-chunk accumulated decay (in log domain)# Note: the empirical coefficient slightly enlarges the worst case, so leave some margin# exp(16 * 5) ≈ 5.5e34 < BF16 max 3.4e38print("bounded :", math.exp(CHUNK * 5))# If softplus lets log α drop as low as -80, the reciprocal is exp(1280) -> overflows even in double precisiontry:print("softplus :", math.exp(CHUNK * 80))except OverflowError:print("softplus : overflow (Inf)")
Comparison and benefits (relative to similar structures such as GDN and gated linear attention):
| Dimension | Traditional parameterization | Bounded parameterization |
|---|---|---|
| Diagonal blocks | Must use an explicit position-pair path | Unified with off-diagonal blocks as dense matrix multiply |
| Operator paths | Two paths, high maintenance cost | One path |
| Hardware utilization | Dragged down by small local matrices | Regular matrix multiply, friendly to tensor cores |
| Numerical risk | Reciprocal may blow up exponentially | Reciprocal is bounded, always in representable range |
In addition, linear attention is itself “position-encoding friendly”: the state update is inherently ordered and does not depend on an extra position encoding to distinguish sequence order. This makes extrapolation from shorter contexts to the million-token scale more natural, and the position-extrapolation problem is avoided altogether.
4.2 Technical Point 2: Auxiliary-Loss-Free Quantile Load Balancing (QB)
Reuse value: high. It only affects routing logic and is a “high-reward, low-risk” change in MoE training.
The pain point. In very large MoE models, tiny deviations in the router are amplified through positive feedback: an expert that is selected slightly more often becomes more “practiced” and is more likely to be selected again after gradient updates. In the end, a few experts are overused while a large number sit idle.
The traditional approach adds an auxiliary load-balancing loss, but it has two drawbacks:
- It introduces an extra weight coefficient that must be tuned by hand—too large and it interferes with the main task, too small and it fails to balance;
- Once the number of experts reaches the hundreds, a fixed coefficient is hard to keep appropriate across different training stages.
The mechanism. The idea of Quantile Balancing (QB) is:
- Within a training step, tally the actual number of tokens each expert handles (the load);
- Take a quantile of the current load distribution (for example the median) as the “target load”;
- Move the routing bias in the negative-gradient direction: experts with a target load below the quantile get a positive bias, and those above the quantile get a negative bias;
- The magnitude of the bias is set by the ratio of the load deviation to the load variance, with a signed taper to avoid oscillation.
Load below the quantile (spare capacity): Δb ∝ + (q − L_e) / σLoad above the quantile (already overloaded): Δb ∝ − (L_e − q) / σ
This way, the direction of the bias update always points toward “reducing overload and filling underload.” At the same time, no auxiliary loss term is needed—the routing objective is always the language-modeling main objective, avoiding the tug-of-war between multiple objectives. Because the balancing amount is given directly by the actual load, the strategy applies equally well to hundreds or more experts.
A schematic implementation:
def quantile_balancing_bias(gate_logits, bias, eta=1e-3, quantile=0.5, eps=1e-6):"""Auxiliary-loss-free quantile load balancing (schematic implementation)gate_logits: [B, T, E] gate scoresbias: [E] routing bias, added to the gate scoresreturns: the updated bias"""B, T, E = gate_logits.shapen = B * Tk = 8 # top-kscores = (gate_logits + bias).reshape(n, E)idx = scores.topk(k, dim=-1).indices # [n, k]# Use bincount to tally how many times each expert was selected (load L_e)load = torch.bincount(idx.reshape(-1), minlength=E).float()mean = load.mean()var = ((load - mean) ** 2).mean()# Target the quantile and give a signed, tapered bias update toward "underload"q = load.quantile(quantile)delta = torch.sign(q - load) * (q - load).abs() / (var.sqrt() + eps)bias = bias + eta * deltareturn bias
Engineering tips:
- The statistics window should not be too large, or the bias will arrive too late, after load imbalance has already happened;
- The variance estimate should use a moving average to dampen random fluctuations from a single batch;
- The bias update magnitude should be clamped to prevent routing from oscillating back and forth between experts;
- Before going live, run controlled experiments along two dimensions—downstream tasks and expert utilization—to evaluate its payoff.
4.3 Technical Point 3: Block-Level Attention Residual (Block AttnRes)
Reuse value: medium-high. It requires changing the network structure and adjusting the parallelism/sharding strategy accordingly.
Its form was introduced above; here are a few points to note when putting it into practice:
- Block partitioning must serve two meanings at once. A “block” should correspond both to a group of layers in the model structure and to a pipeline stage in the parallelism strategy. Most reuse can happen within a block, while ordinary residual passing is still needed between blocks.
- The reuse coefficient γ must be constrained. It can be generated dynamically from the input (gated) or fixed as a learnable scalar initialized to a small value. This avoids deep layers directly “copying” the shallow-layer answer in the early stages of training.
- The memory and communication accounting must be done carefully. Caching the reused attention outputs adds a little memory, but the savings in repeated K/V generation and transfer are usually larger. If sequence or tensor parallelism is used, the reuse set should align with the sharding boundaries, and reuse should be kept within the same parallel group as much as possible to avoid extra cross-device communication.
- Validation should focus on two metrics. One is the similarity curve of representations across layers, the other is long-context retrieval accuracy. The former reflects whether representations are more diverse; the latter reflects whether long-range information is passed effectively.
5. Training Strategy: Multi-Stage Context Extension and Agentic Reinforcement Learning
5.1 Multi-Stage Context Extension: 8K → 64K → 256K → 1M
Pretraining directly at one million tokens is both expensive and inefficient. In early text, dependencies that genuinely require very long distances are rare, and the model’s language ability is not yet mature. The common practice in the field is a “curriculum-style” multi-stage extension:
| Stage | Sequence length | Main goal | Key actions |
|---|---|---|---|
| 1 | 4K–8K | Build a solid language-modeling and knowledge foundation | Large-scale pretraining on general corpora; establish stable routing and decay gates |
| 2 | 64K | Learn medium-distance dependencies | Introduce long documents; adjust position-related parameters (e.g. RoPE base frequency, YaRN-style scaling) |
| 3 | 256K | Strengthen cross-chapter and cross-document association | Mix long documents with short samples to prevent degradation of short-text ability |
| 4 | 1M | Support extreme long-horizon tasks | Control the proportion of long samples; work with the parallelism strategy to keep throughput and stability |
A few practical points:
- Keep short-sample replay. Every stage should mix in a sufficient number of short-sequence samples to prevent “long-text ability goes up while short-text ability drops.”
- Combine length increases with position-extrapolation techniques. Linear-attention states are naturally extrapolatable; full-attention layers need position-extrapolation schemes (such as adjusting the rotary position embedding base frequency) to work alongside them.
- Evaluate long context in layers. Move from needle-in-a-haystack (NIAH) retrieval tests, to multi-hop reasoning and long-document summarization, and on to cross-document comparison, validating layer by layer.
5.2 Agentic Long-Horizon Reinforcement Learning Post-Training
A defining feature of agentic tasks is that trajectories are long. A complex coding task may include dozens of tool-call rounds plus a large amount of file reads, command outputs, and error messages; a single trajectory easily accumulates to hundreds of thousands or even millions of tokens. This puts three kinds of pressure on post-training: memory, sampling cost, and credit assignment.
Common practices include:
- Outcome-based rewards. Use whether the task is genuinely completed (e.g. whether all unit tests pass) as the main reward, supplemented by format constraints and process norms;
- Curriculum-based task sets. Progress from short trajectories to long ones, letting the model first learn the “plan–execute–verify” loop within a controllable range;
- Efficient RL infrastructure. The inference engine handles sampling while the training engine handles parameter updates, deployed separately. Multi-round trajectories can reuse the KV cache of dialogue prefixes, and a length budget is set for extra-long trajectories.
Only after training can the model stay goal-consistent and self-correct in time on long-horizon tasks, rather than “getting lost” partway through.
6. Engineering Practice: How to Make Good Use of These Models for Long-Context Applications
For developers, model capability is only the starting point; turning a million-token window into a stable, controllable application experience is just as critical.
Context construction. Prioritize the native multimodal capability and feed images, charts, and text from long documents in together, avoiding the information loss of “recognize first, then understand.” Retrieval-augmented generation does not have to be abandoned—it works with long context: use retrieval to narrow the scope, and use long context for fine-grained comparison.
Memory and parallelism. On the model side, latent-vector compression, linear-attention states, and cross-layer reuse of attention outputs can all reduce KV-cache overhead. On the serving side, memory budget, concurrency, and context length must be planned together:
def kv_cache_bytes(tokens, layers, kv_heads, head_dim, dtype_bytes=2):"""Estimate standard KV-cache memory (schematic)"""per_token = 2 * layers * kv_heads * head_dim * dtype_bytes # 2 for both K and Vreturn tokens * per_token# Using a dense multi-head structure: layers=60, kv_heads=8, head_dim=128, BF16print(kv_cache_bytes(1_000_000, 60, 8, 128) / 1024**3) # ~244 GiB, a single request can fill several accelerators
This is why long-context models generally need both “cache compression” and “parallel sharding”:
- Tensor parallelism splits attention heads;
- Sequence parallelism distributes extra-long activations;
- Expert parallelism spreads expert weights;
- Pipeline parallelism splits depth.
Serving optimization.
- Chunked prefill, so that chunked computation of long inputs interleaves with decode requests and no single long request monopolizes resources;
- Prefix-cache reuse, so system prompts and long documents are computed only once across multiple turns;
- Batching and speculative decoding to raise throughput under high concurrency.
Observability. Long-context requests consume resources very differently from ordinary requests. It is advisable to record input length, time to first token, per-token latency, and cache hit rate separately, and to set dedicated alerting thresholds for long requests.
At the infrastructure level, enterprises can build the whole system on top of general cloud capabilities:
- Use a container platform to orchestrate training and inference tasks and enable elastic scaling;
- Use object storage to hold checkpoints and long-document datasets;
- Use a message queue to connect the asynchronous pipeline of “document parsing → retrieval → model inference → result write-back”;
- Use a logging service and monitoring/alerting to achieve full-chain tracing and cost attribution.
7. Evaluation and Reuse Roadmap
7.1 Evaluation Dimensions
Evaluating models of this kind cannot rely on general Q&A scores alone. At a minimum, cover five dimensions:
- Long context: NIAH-style retrieval, multi-hop reasoning, long-document summarization, cross-document comparison;
- Multimodality: chart understanding, scan and layout reconstruction, Q&A over mixed text-and-image documents;
- Agentic: multi-step tool calls, long-trajectory task completion rate, and recovery ability after errors;
- Efficiency: time to first token for long requests, throughput, cost per token;
- Stability: output consistency under extreme load and extra-long inputs.
7.2 Reuse Roadmap Recommendations
| Team type | Reuse focus | Expected benefit |
|---|---|---|
| Operator/kernel team | Bounded decay parameterization | Unify operator paths, raise tensor-core utilization |
| MoE training team | Quantile load balancing | Eliminate auxiliary-loss tuning, improve expert utilization |
| Model architecture team | Block AttnRes, hybrid attention | Ease representation degeneration, lower long-context cost |
| Application development team | Multi-stage context-extension ideas, serving optimization | Turn long-context capability into a stable product |
8. Conclusion
Long context, multimodality, and trillion parameters are not three independent goals; they point to the same direction: under finite compute, trade smarter structures for larger effective capacity.
From a recently published class of model technical reports, what is most worth borrowing is not any single module but the design logic that runs through the whole thing:
- Use bounded decay parameterization to resolve the tension between linear attention being “fast to compute” and “stable to compute”;
- Use auxiliary-loss-free load balancing to resolve the tension between massive experts being “open to scaling” and “evenly used”;
- Use cross-layer sharing and staged training to resolve the tension between “context long enough” and “actually usable.”
For developers, understanding the trade-offs behind these designs is more valuable than memorizing parameter specifications. Long-context model capability is evolving rapidly, and the most reliable way to keep up with fast technical iteration is to keep tracking public technical reports and reproducing them hands-on.
