Trillion-Parameter MoE and Million-Token Context: An Architecture Breakdown
A structured walkthrough of how modern ultra-large models are built: super-sparse MoE routing, hybrid attention, native multimodality, staged long-context pretraining, and agentic RL post-training. You will learn why each module exists, what it costs, and where it breaks down.
Trillion-Parameter MoE and Million-Token Context: An Architecture Breakdown
Public technical reports on trillion-parameter-scale models have become noticeably more frequent. They share a common technical path: push parameter count into the trillion range with a super-sparse mixture-of-experts (MoE) architecture, then layer on native multimodal input and a million-token context window, with the post-training stage focused on long-horizon agentic capability. A summary card from one such publicly disclosed report captures a representative set of headline numbers:
- Roughly 2.8 trillion total parameters, about 104 billion activated parameters per token;
- Native vision multimodal support with a 1M-token context window;
- An attention module that mixes incremental (linear) attention with gated latent attention;
- Cross-layer shared attention residuals, and nearly 900 routed experts in the sparse expert layers;
- A smooth GLU activation family, plus a quantile-based load-balancing mechanism;
- Multi-stage pretraining from 8K to 64K to 256K to 1M;
- Million-token-scale agentic reinforcement learning in post-training.
These designs are rarely isolated technical highlights. Most of them are engineering responses to three tensions: parameter capacity versus per-token compute; context length versus the quadratic cost of attention; and a huge number of experts versus training stability. Memorizing “how many billion parameters” or “how many hundred thousand tokens” has limited value. Understanding what problem each module solves, what price it pays, and under what conditions it fails is far more useful.
The breakdown below follows the order: design goals — attention — MoE — multimodality — long-context pretraining — inference and post-training — evaluation and selection.
1. Design Goals: Trading Off Four Dimensions at Once
To judge whether a very large model’s design is coherent, start by listing the four dimensions it must optimize simultaneously:
| Dimension | Representative metric | Main constraint | Typical design levers |
|---|---|---|---|
| Capacity | Total parameters, number of routed experts | Memory capacity, expert-parallel communication | Super-sparse MoE, weight offloading |
| Efficiency | Activated compute per token, KV cache footprint | Training throughput, inference latency and concurrency | Fine-grained experts, low-rank attention, hybrid attention |
| Information | Effective context length | Attention complexity, data quality, position-encoding extrapolation | Staged extension, position-encoding scaling, document-level data |
| Behavior | Multi-step tool calls, long-horizon task completion rate | Reward sparsity, environment cost, trajectory length | Agentic RL, process rewards, automatic curricula |
These four pull against each other. Activated parameters, context length, and trajectory length together determine inference-time compute, memory, and latency. This is why a well-designed model report typically covers architecture, data recipe, parallelism strategy, and post-training method at the same time. Reading only one of them makes it hard to tell whether the design holds together.
2. Rebuilding Attention: Fighting Quadratic Cost with a Hybrid
2.1 Why Quadratic Complexity Becomes the Bottleneck
Standard multi-head attention costs roughly:
Attention compute: O(L² · d) (L = sequence length, d = model dimension)KV cache size: 2 · L · n_kv · d_head · b(2 for K and V, n_kv = number of KV heads, b = bytes per element)
Make the sequence ten times longer and attention compute grows by roughly a hundred times. During inference, the KV cache grows linearly with context length; in the decode phase, every generated token re-reads the entire history, so memory bandwidth becomes the dominant bottleneck. Once context reaches the hundreds-of-thousands or millions of tokens, this overhead can no longer be ignored.
2.2 Three Families of Optimization
The industry has mainly three routes:
- Sparse / block attention: Compute only a subset of attention blocks, or schedule attention in blocks to improve memory-access efficiency. The implementation change is relatively small, but whether long-range information is fully captured depends on how blocks and routing are designed.
- Linear / incremental attention: Maintain a fixed-size state matrix that is continuously updated to approximate the influence of the entire history on the current token. It naturally supports streaming inference with constant memory, but a single update has limited expressive power and limited exact-retrieval ability.
- Low-rank latent attention: Compress keys and values into a low-dimensional latent before computing. The KV cache shrinks substantially while global interaction is largely preserved.
2.3 Incremental Attention: Recursive Updates and the Forgetting Problem
The core of incremental attention is a recurrence. Let the state be S, the key k, and the value v:
Standard incremental attention: S_t = S_{t-1} + k_t v_tᵀ, o_t = φ(q_t)ᵀ S_tWith a forgetting factor: S_t = α_t · S_{t-1} + k_t v_tᵀ(α_t is a scalar or matrix-valued forgetting/decay coefficient)
α_t acts as a memory gate: it decays the old state when content needs to be forgotten and preserves the state when content needs to be retained. The forgetting coefficient lets the model dynamically allocate a finite memory budget.
Either way, a fixed-size state has an information ceiling. Early information can be overwritten or diluted by later writes, and the model itself struggles to learn which segment should be remembered. Incremental attention therefore tends to excel at local modeling, streaming processing, and low-cost long-sequence modeling.
2.4 Latent Attention and Gating: Memory Compression and Channel Selection
The general form of low-rank latent attention can be written as:
# Illustrative code: multi-head splitting and scaling omitted;# focus is the normalized attention weightsc = W_dkv @ x # compress keys and values into a low-dimensional latentk, v = W_uk @ c, W_uv @ c # project back up to keys and values at compute timeo = (focus @ v) @ W_o # global attention outputg = W_g @ x # channel gating (per-channel gating or binary gate)out = g * o + (1 - g) * mlp(W_in @ x) # gate sets the mix of attention vs. per-position FFN
- Low-rank compression means only the latent c and its related parts are cached instead of full keys and values, which directly reduces KV cache memory.
- Gating lets the model decide per channel and per position which information goes to global attention and which is handled by the per-position feed-forward network. Gating introduces multiplicative interaction, giving expressive power beyond plain linear weighting.
It is worth being precise: compression or not, as long as global attention remains, the theoretical complexity stays quadratic. Low-rank compression solves the memory-bandwidth problem, not the compute problem.
2.5 Hybrid: Spend Global Attention Where It Counts
A practice adopted by a growing number of public roadmaps is to use linear/incremental attention in most layers and keep global (latent) attention in a few:
| Aspect | Incremental attention | Global latent attention |
|---|---|---|
| Per-token state | Fixed-size state matrix | KV cache that grows with length |
| Exact long-range retrieval | Weaker, vulnerable to overwriting | Stronger |
| Memory growth with length | None | Linear |
| Training compute | Roughly linear in length | Quadratic |
| Best fit | Long-sequence streaming inference, low-cost scaling | Precise recall of critical information |
With a global-attention layer ratio of p, model dimension d, and sequence length L, the attention compute that a hybrid saves relative to fully global attention is roughly:
Savings ratio ≈ (1 - p) × [1 - c / (L · d)] (c is a constant set by the feature-map dimension)
The larger L is, the more the incremental layers save; the smaller p is, the lower the overall cost. But the choice of p is not purely an efficiency question, as the next section explains.
2.6 Why “One Global Layer in Eight” Works
How many global attention layers are needed can be understood by borrowing results from information theory on the structure of data-compression systems. Intuitively, the representation dimension of the sensing stage can be far smaller than the information dimension: as long as compression stays above the information dimension, no information is lost. The decision stage, by contrast, must reach the information dimension to preserve everything.
Mapped onto a model:
- Attention layers responsible for feature sensing and layer-by-layer processing can operate at a lower “effective dimension”;
- The global attention layers that actually integrate information across the full sequence should not be over-compressed.
This matches the intuition behind hybrid attention: the more numerous linear/incremental layers handle per-layer transformation and feature processing, while the fewer layers that retain a full global view handle “decision-level” integration. In practice, global attention layers are usually distributed on a fixed period. The ratio should not be too small, or exact retrieval ability may degrade; it should not be too large either, or the long-context efficiency advantage is cancelled out.
2.7 How Multimodal Input Affects a Hybrid
Visual input is typically encoded into “visual tokens” equivalent to language tokens, which lets the model process interleaved image-text sequences with a unified attention mechanism. But high-resolution images or long video can produce thousands or even tens of thousands of visual tokens after the encoder, making them one of the main sources of context bloat.
Common countermeasures:
- Visual token compression: Merge features of adjacent regions, or keep only task-relevant regions;
- Adaptive resolution: Allocate the visual token budget dynamically based on image complexity;
- Block attention for interleaved image-text: Local attention within an image, global attention between image and text.
2.8 Cross-Layer Attention Residuals: Fighting Deep-Network Collapse
Very deep networks often exhibit a phenomenon: as depth increases, representations gradually lose distinctiveness, layers become highly similar to one another, and information is “drowned out” in the residual stream. One approach propagates key-values from shallower layers (especially the first few), or the normalized attention output scaled by a factor, to deeper layers, so that deep layers regain the raw information from shallow ones. This is a continuation of the residual-connection idea of reusing information across layers.
The benefits are threefold:
- Deep attention no longer has to build keys and values “from scratch”, saving some compute;
- Deep layers get a more raw and more diverse information source, mitigating representation homogenization;
- Shorter gradient paths early in training help large models converge.
The costs are equally clear:
- Memory must hold and broadcast shallow-layer keys/values or attention states simultaneously, competing with the KV cache and expert parallelism for memory;
- Implementation complexity rises, and combining it with various parallelism schemes requires careful handling;
- The choice of which layers to broadcast from, and the strength of the cross-layer scaling, both need to be settled by ablation.
3. Super-Sparse MoE: Where Scale Comes From, What Keeps It Stable
3.1 Conditional Computation and Activated Parameters
MoE replaces the feed-forward layer with N “experts” plus a router. Each token is routed to only k of them, which achieves “enormous total parameters, controllable per-token compute”. At equal training compute, a sparse model typically holds a larger parameter capacity within the same compute budget. The super-sparse route pushes k lower and N higher, keeping more parameters in storage rather than on the compute path.
3.2 Fine-Grained Experts: Split, Don’t Inflate
“Fine-grained” here means cutting each expert’s intermediate dimension smaller and increasing the count, not making individual experts larger. With standard FLOPs F, an intermediate dimension split into m parts, and routing count k:
Standard FFN: compute ≈ F, parameters ≈ PFine-grained MoE: experts ≈ m, per-expert parameters ≈ P/m, routing ≈ k·mPer-token total compute ≈ k·m·F/m = k·F, per-token total parameters ≈ k·m·(P/m) = k·P
So with k fixed, fine-grained splitting does not change per-token compute or per-token parameter count, yet it expands the space of “available combinations” from C(N,k) to something on the order of C(mN, km). Token assignment across experts becomes more flexible and the division of labor among experts finer.
The trillion-scale example above, with close to 900 routed experts, reflects a fairly “fine-grained” orientation: more experts, each smaller, achieving combinatorial scaling through gating.
3.3 Routing: Robustness of the Normalization Scheme
The gating network usually outputs continuous logits, and the router picks the top-k experts per token, normalizes the scores, and sums them with those weights.
softmax normalization: g = exp(s_i) / Σ_j exp(s_j) (i, j ∈ Top-k)sigmoid + normalization: g = σ(s_i) / Σ_j σ(s_j) (σ is Sigmoid)
In super-sparse settings with a huge number of experts:
- The scale of logits on the softmax path drifts as the expert count grows, and is prone to overflow in low-precision training;
- Applying z-score-style standardization to the logits keeps the scale of routing inputs stable;
- The sigmoid form avoids the numerical range problems of exp.
The “quantile balancing” (QB) mechanism in the example report belongs, by its public description, to this family of load-balancing ideas. It typically collects per-token routing scores across all experts by quantile statistics, then adjusts routing thresholds or load weights accordingly. Quantile statistics are insensitive to extreme values, making them more robust than mean- or maximum-based balancing when the expert count is large and a few experts have anomalously high scores.
3.4 Load Balancing: From Auxiliary Loss to Auxiliary-Loss-Free
Load imbalance is the number-one enemy of MoE training. A few “hot experts” get overused while many “cold experts” never train. Three common remedies:
| Approach | Method | Strength | Risk |
|---|---|---|---|
| Auxiliary load loss | Add a balancing loss to the training objective that penalizes variance in expert load | Simple to implement, predictable effect | Too large a coefficient hurts main-task quality |
| Auxiliary-loss-free balancing | Maintain a dynamic bias per expert, adjusted by load, affecting routing only and not gradients | Does not perturb the main-task gradient | Bias update cadence needs careful tuning |
| Expert-choice routing | Experts choose tokens, inherently balancing load per expert | Strictly balanced load | Must handle the same token being processed by multiple experts |
In practice the two are often combined: keep a small auxiliary balancing loss while using a dynamic bias for fine-grained correction. For a super-sparse structure with close to 900 experts, the waste from imbalance is global. Because the capacity factor must be reserved for the maximum load, any hotspot raises the effective compute of all experts.
3.5 Smooth GLU Activation: Letting Gradients Flow Through Experts
The general form of a GLU-style feed-forward structure is:
GLU(x) = (A(x) ⊙ B(x)) · W_out A, B are two parallel linear projections, ⊙ is elementwise product
Replacing one branch with an activation function yields different variants:
- ReLU → ReGLU;
- GELU → GEGLU;
- SiLU/Swish → SwiGLU;
- A tanh approximation of the Gaussian CDF (the tanh approximation of GELU) → an approximate-GELU gated variant.
What these variants share is a “smooth GLU”: the activation is continuous and differentiable, bounded, and has non-zero gradients almost everywhere, avoiding the ReLU-style problem of gradients going to zero on the negative half-axis.
Inside an MoE, the effect of smooth activations is amplified:
- The multiplicative structure of gating and activation lets gradients flow along both branches at once, reducing gradient variance early in training;
- More stable activation distributions reduce routing drift caused by differing activation scales across experts;
- Under low-precision training such as bf16/fp16, continuous, bounded activations are less likely to produce inf/nan.
Similarly, root-mean-square normalization (RMSNorm) at attention outputs is now used by nearly all modern large models, because it needs no mean subtraction, is cheap to compute, and is numerically stable.
3.6 Low-Precision Training and Numerical Stability
Numerical stability in trillion-parameter training is an engineering problem in its own right:
- Precision tiering: Keep higher precision for numerically sensitive parts such as embeddings, normalization, and routing; use low precision for the main body of matrix multiplications; accumulate losses and optimizer states in high precision.
- Router z-loss: Apply a small-coefficient mean-square penalty to routing logits to suppress logit blow-up.
- Gradient clipping and loss scaling: Paired with dynamic loss scaling to prevent overflow and gradient explosion.
- Fine-grained quantization: Determine scale factors per small block (for example, a few channels per group per token), reducing the impact of outliers on the precision of the whole block.
- Expert dropout and initialization: Apply random dropping to expert outputs so that a few experts do not dominate early on.
3.7 Parallelism and Communication: The Real MoE Bottleneck
The performance bottleneck of MoE training is often not compute but communication:
- Expert parallelism places different experts on different devices, so each MoE layer requires two All-to-All operations: one to dispatch tokens by expert, one to gather results back;
- Tensor parallelism splits a single expert’s matrix multiplications across GPUs, introducing All-Reduce;
- Pipeline parallelism splits layers across stages, introducing point-to-point communication;
- Sequence/context parallelism splits a long sequence across GPUs, so attention requires cross-device key/value exchange.
# Illustrative code: MoE routing with load balancing and capacity limits# (specific parallelism implementations omitted)def moe_forward(x, router, experts, capacity, bias=None):scores = router(x) # [T, N], T = tokens, N = expertstopk_idx, topk_w = topk(scores + bias, k) if bias is not None else topk(scores, k)topk_w = normalize(topk_w) # softmax or sigmoid normalizationout = zeros_like(x)counts = zeros(N)for e in unique(topk_idx):mask = (topk_idx == e) # tokens routed to expert en = mask.sum()# truncate over capacity; capacity is reserved for the maximum loadtok = x[mask][:capacity]y = experts[e](tok)out[mask][:capacity] += topk_w[mask][:capacity, ...] * ycounts[e] = nreturn out, counts # counts feed routing-bias updates and load stats
In real training, this layer must also handle overlapping communication with computation, sharded storage of expert weights, and coordination with pipeline-parallel partitioning.
4. Multimodality: Division of Labor and Compression in a Unified Token Space
Multimodal models typically run image, video, and other inputs through a vision encoder into visual tokens, concatenate them with text tokens, and feed the result into the backbone. Native multimodality means vision participates from the very start of pretraining rather than being trained as a language model first and “aligned” with a vision module afterwards. The benefit is more thorough cross-modal alignment; the cost is heavier data engineering and training expense.
The native multimodal route has to handle three key issues:
- Resolution and token budget: High-resolution images produce many visual tokens. There is a trade-off between preserving detail and staying within the context budget, usually handled with dynamic resolution and visual token compression.
- Organizing interleaved image-text data: Documents, web pages, and video subtitles are naturally interleaved long sequences, which makes them good material for training long-context ability.
- Imbalance across modalities: Visual data differs from text in volume, annotation quality, and task distribution, so per-modality mixing ratios, sampling temperatures, and dynamic curriculum adjustments are needed.
5. Long Context: Staged Extension and the Engineering Around It
5.1 Why Stage It Instead of Going Straight to 1M
If training began at a 1M context length:
- Attention (including the long-sequence recurrence of the linear part) would be extremely expensive, and each unit of compute would process very few tokens;
- The total supply of high-quality long-document data is limited, and repeated sampling causes overfitting and memorization;
- Extrapolation errors in position encoding at extreme lengths are hard to detect in time.
Staged extension (8K → 64K → 256K → 1M) lets the model fully learn language and knowledge at short context, then progressively raise position resolution and long-range dependency modeling. Each stage can combine position-encoding scaling (NTK-aware interpolation, YaRN, and similar) with a small amount of long data in continued training, pulling extrapolation error back inside the training distribution.
5.2 What Long-Context Data Consists Of
Long-context ability is not just “a longer window”; it depends on whether the long sequences contain tasks that genuinely require crossing long distances. Usable data forms include:
- Repository-level multi-file code context;
- Long documents such as books, papers, and legal contracts;
- Multi-turn dialogues and tool-call logs;
- Multimodal temporal data such as video.
The key is the combination of “long input plus long output”: the model must both read a very long context and generate output long enough and coherent enough within it.
5.3 Position Encoding and Extrapolation
Common extrapolation strategies include:
- Absolute position interpolation (PI): Compress position indices into the original training range;
- NTK-aware scaling: Adjust the base frequencies of rotary position embeddings (RoPE) non-uniformly across frequency dimensions;
- YaRN: Apply different interpolation strengths to different frequency components, plus an attention temperature correction;
- Length extrapolation training: Continue training directly at the target length so the model adapts to the new position distribution itself.
No single strategy is universal; the final result depends on model scale, data mixture, and how training stages are arranged.
5.4 KV Cache Management on the Inference Side
The core engineering problem of long-context inference is KV cache memory management. For standard multi-head attention, the approximate KV cache size is:
KV_bytes ≈ 2 · L · n_kv · d_head · bExample: L=1,000,000, n_kv=8, d_head=128, b=2 (bf16)≈ 2 × 1e6 × 8 × 128 × 2 ≈ 4 GB per sequence
With low-rank latent attention, the cache holds mainly the latent rather than full keys and values, cutting memory by a factor of several under the same conditions. Common engineering measures include:
- Paged KV cache management to reduce memory fragmentation;
- Prefix caching, so repeated system prompts in multi-turn and agent scenarios are not recomputed;
- Chunked prefill, splitting long prompts into chunks and interleaving them with decode scheduling;
- Context/sequence parallelism, splitting a long sequence across multiple GPUs to compute attention in parallel;
- KV quantization, dropping the cache from bf16 to int8 or lower;
- Prefill/decode disaggregation, moving prefill and decode onto different resource pools so compute and bandwidth can be tuned separately.
6. Post-Training: Million-Token-Scale Agentic Reinforcement Learning
Pretraining sets the ceiling on model capability; post-training determines whether that capability converts reliably into task completion. For long-context multimodal models, the focus of post-training is shifting from “single-turn QA alignment” to “long-horizon task alignment”, whose core is agentic reinforcement learning (Agentic RL).
6.1 Why Agentic RL Is Needed
Long-horizon tasks are difficult because:
- Sparse rewards: A task may involve dozens of tool calls with a reward only on the final outcome, making credit assignment across intermediate steps hard;
- Long trajectories: A single trajectory can span tens of thousands or even a million tokens, making training memory and compute expensive;
- Tool diversity: Code execution, retrieval, file operations, and browsers each have different failure modes;
- Environment cost: Every step needs real tool execution, so rollout throughput is limited by environment concurrency.
6.2 Training Paradigm
A typical Agentic RL loop can be summarized as:
1. Task sampling: draw from a task pool (multimodal, multi-tool, multi-difficulty)2. Trajectory rollout: the model calls tools across multiple turns; record full trajectories3. Reward computation: rule checks / execution-result comparison / reward-model scoring4. Advantage estimation: GRPO/PPO compute group-wise or per-token advantages5. Policy update: clipped objective + KL constraint, preventing drift too far from the reference model6. Difficulty curriculum: adjust the task distribution by pass rate to keep the learning signal strong
- GRPO samples several trajectories per task and uses within-group relative reward as the advantage, removing the need for a value network;
- PPO relies on a value network for per-token credit assignment, which is more sensitive to intermediate steps in long trajectories;
- In practice, rule-based rewards (whether unit tests pass, whether files match) are combined with a reward model: the former is reliable but narrow in coverage, the latter broad but vulnerable to reward hacking.
6.3 Engineering Challenges
- Sandboxing and isolation: Code execution and network access must run in a controlled environment;
- Trajectory compression: Very long trajectories need segmentation or summarization so a single sample does not exceed the training window;
- Sampling efficiency: Rollout is the Agentic RL bottleneck, requiring asynchronous sampling, environment pooling, and retry on failure;
- Reproducibility: Tool versions, network state, and random seeds all affect results, so fixed environment snapshots are needed.
6.4 Relationship to SFT and CoT
Before RL, models are usually supervised-finetuned (SFT) on high-quality trajectories so they learn basic tool-call formats and task decomposition; then chain-of-thought (CoT) or reasoning-process data is added to strengthen multi-step reasoning. RL builds on that to further align with the objective of “task success”. The three are progressive rather than substitutes.
7. Evaluation: Where Exactly Is the Strength?
For a trillion-scale MoE long-context multimodal model, evaluation needs to cover four layers:
- General capability: language understanding, knowledge QA, code generation, mathematical reasoning;
- Long-context capability: Needle-in-a-Haystack, multi-document reasoning, long-document summarization;
- Multimodal capability: image-text QA, document understanding, video temporal understanding;
- Agentic capability: tool-call accuracy, multi-step task completion rate, long-horizon task success rate.
Three points deserve attention:
- Contamination: public benchmarks may be covered by training data, so private or dynamic benchmarks are needed;
- Long context is not long output: being able to read it in does not mean being able to write it out; the two should be evaluated separately;
- Cost awareness: a single million-token-scale evaluation is expensive, so stratified sampling and budget control are required.
8. Trends and Common Misconceptions
8.1 Five Trends
- Sparsification: total parameters keep growing while activated parameters stay restrained;
- Hybridization: attention, feed-forward, and normalization all trend toward hybrid structures, trading a little global compute for efficiency;
- Native multimodality: vision participates from day one of pretraining rather than being aligned afterwards;
- Long context as a baseline: 1M-level context is shifting from a selling point to a baseline, with the supporting data, position encoding, and inference engineering becoming the real differentiators;
- Agentic post-training: RL is shifting from “aligning with human preferences” to “aligning with task completion”.
8.2 Four Misconceptions
- More parameters is always better: a super-sparse model’s “effective parameters” depend on routing quality, and load imbalance leaves many parameters dormant;
- Longer context is always better: a long window is not long memory; it needs targeted data and evaluation;
- Activated parameters determine inference cost: KV cache, expert-parallel communication, and the number of tool-call rounds matter just as much;
- RL can fix everything: RL’s ceiling is set by pretrained capability; data quality and task design are fundamental.
8.3 Selection Guidance
When evaluating this class of model, developers can look at:
- Memory budget: weights + KV cache + expert-parallel communication buffers;
- Latency budget: time-to-first-token (prefill) and per-token latency (decode) assessed separately;
- Fit between context length and task: not longer is better, better-matched is better;
- Toolchain maturity: inference-framework support, quantization capability, monitoring and observability.
Overall, trillion-scale MoE and million-token context are not two isolated “parameter race” metrics but a tightly coupled system design: hybrid attention solves efficiency, super-sparse routing solves capacity, staged pretraining solves long-horizon ability, and agentic RL solves task completion. Understanding the trade-offs at each layer is worth more than memorizing any single number.
