How to Build a Million-Token MoE Long-Context LLM
This article explains how to design and validate a million-token long-context MoE large model. It focuses on three core engineering areas: lower-bounded decay parameterization for linear attention, auxiliary-loss-free dynamic expert load balancing (QB), and block-level attention residuals. It also covers staged context-length training, agentic reinforcement learning, engineering risks, and practical acceptance criteria.
Conclusion First: Prioritize Three Engineering Questions for Long-Context MoE Models
If the target is a large model that natively supports million-token context while using an ultra-large sparse MoE architecture, technical selection cannot focus only on “whether the parameter count is large enough.” It must also answer three engineering questions:
Is long-context computation cheap and numerically stable enough?
Focus on linear attention and its improved variants, especially whether lower-bounded decay parameterization can avoid numerical overflow in chunked parallel computation.Will massive numbers of experts suffer from load collapse?
Focus on auxiliary-loss-free dynamic load balancing, such as quantile threshold adjustment, online expert load calibration, and overheated or overcooled expert detection.Can deep networks still transfer information effectively?
Focus on block-level attention residuals, including block granularity, cross-layer information paths, and the conditions under which memory and communication savings are actually realized.
The following sections follow this structure: background, key techniques, training workflow, engineering deployment, and frequently asked questions.
1. Background: Dual Challenges of Long Context and Large Sparse MoE
A multimodal MoE large model designed for million-token context usually faces two types of pressure at the same time:
| Challenge | Typical manifestation | Key metrics to validate |
|---|---|---|
| Attention compute growth | Standard Softmax attention compute and memory overhead grow roughly quadratically with context length | Long-text throughput, peak memory, single-forward latency |
| Expert load skew | Routing favors a small number of experts over time, causing expert collapse or compute waste | Expert load variance, idle expert ratio, Drop Token ratio |
| Numerical stability | Cumulative decay factors in linear attention may underflow or overflow | Decay reciprocal range, BF16/FP16 worst cases, tile length boundaries |
| Deep representation decay | As depth increases, gradient backpropagation becomes harder, and shallow-layer information is less able to serve deep-layer computation | Per-layer contribution, block residual ablation, deep-task metrics |
For parameter scale, it is safer to use an illustrative reference. Some public materials may mention “trillion-level total parameters and tens to hundreds of billions of activated parameters per token,” for example about 2.8 trillion total parameters and about 104.0 billion activated parameters. However, such numbers need to be interpreted together with the original technical report, release time, and counting methodology. They should not be treated as a fixed baseline for all MoE long-context models.
A more practical engineering approach is to focus on the combined constraints of:
- total parameters,
- activated parameters,
- context length,
- hardware topology,
rather than memorizing a single parameter value.
2. Technique 1: Lower-Bounded Decay Parameterization for Linear Attention
1. Why Is Standard Softmax Attention Expensive at Million-Token Context?
Standard Softmax attention rapidly expands the attention matrix as context length grows. If the context length is L, the attention matrix size is approximately O(L^2). When L reaches the million-token level, memory and compute costs become difficult to support.
| Approach | Complexity | Memory characteristics | Numerical stability | Suitable scenarios |
|---|---|---|---|---|
| Softmax attention | Approximately O(L^2) |
Clear memory pressure in long-context settings | Usually relatively stable | Short context, strong precision requirements |
| Plain linear attention | Approximately O(L) |
More controllable memory usage | Chunk-wise cumulative decay may overflow or underflow | Long context, but numerical optimization is required |
| Lower-bounded decay linear attention | Approximately O(L) |
More controllable memory usage | Lower-bound constraints improve computability | Exploring million-token context; long-text evaluation is still needed |
2. Where Do the Numerical Problems in Linear Attention Come From?
Linear attention and its variants often introduce cumulative decay factors. To compress long-sequence states into a lower-cost form, the model typically computes a recurrence similar to the following:
S_t = D_t * S_{t-1} + K_t^T * V_t
Here, D_t is the decay factor.
In chunked parallel computation, an intra-chunk cumulative decay needs to be calculated within each chunk. If some decay factors are extremely small, their reciprocals may overflow under limited precision formats such as BF16 or FP16. If decay factors are close to 1, state updates may become too slow.
In traditional implementations, logarithmic decay terms may not have a strict lower bound. In extreme cases, the numerical range of intra-chunk cumulative decay becomes hard to control. As a result, some implementations must use special position-pair computation paths for diagonal blocks and cannot directly invoke dense Tensor Core matrix multiplication. This limits throughput.
3. How Does Lower-Bounded Decay Parameterization Help?
One practical improvement is to change the logarithmic decay term from an unbounded form to a scaled Sigmoid form with a lower bound:
g_min = -5.0g = g_min * sigmoid(A_h @ z_th) # g is constrained to [g_min, 0]decay = exp(g) # decay is constrained to [exp(g_min), 1]
After this change, the lower bound of decay is locked to g_min.
For example, if g_min = -5, the per-position decay factor approximately falls within:
[e^-5, 1]
That is, approximately:
[0.0067, 1]
A more reliable engineering statement is:
With g_min = -5, a tile length of 16, and a BF16 or FP16 implementation, combined with intra-tile scaling and safe-range checks, the decay reciprocal can be kept within a computable range. If FP16 is used, additional worst-case dynamic range testing is recommended.
For BF16, the numerical range is usually wider, but worst-case behavior after intra-chunk accumulation still needs to be checked. For FP16, overflow risk must be explicitly validated.
4. Applicability Boundaries and Acceptance Criteria
Lower-bounded decay parameterization is not unconditional. It is recommended to validate it along the following boundaries:
- Data type: BF16, FP16, and FP32 behave differently and should be tested separately.
- Tile length: If validation is performed for a tile length of 16, increasing the tile to 32, 64, or 128 requires re-evaluating the decay reciprocal range.
- Value of
g_min: A smallerg_minmeans stronger decay, which may help compress long states, but it also increases numerical risk. - Implementation path: Whether the special diagonal-block path is removed and whether the implementation can directly use dense Tensor Core GEMM depends on the specific operator implementation.
- Throughput gains: Throughput improvements depend on hardware, parallelism strategy, and operator implementation. They should not be treated as unconditional conclusions.
5. Relationship with NoPE
Absolute claims such as “native NoPE support” should be avoided. A more rigorous statement is:
If training already adopts NoPE and lower-bounded parameters are controlled, lower-bounded decay linear attention can improve the feasibility of million-token extrapolation. However, long-context evaluation is still required.
In other words, lower-bounded decay linear attention can reduce the numerical risk of long-context extrapolation, but it cannot replace real-task validation such as retrieval evaluation, long-document question answering, or codebase reasoning.
3. Technique 2: Auxiliary-Loss-Free Dynamic Load Balancing (QB)
1. Why Does MoE Experience Expert Collapse?
The essence of MoE routing is to let tokens select a small number of experts. If routing favors a small number of experts over time, several problems can occur:
- Hot experts become overloaded, causing unstable training.
- Cold experts receive insufficient gradient.
- Effective parameter utilization drops.
- Compute efficiency decreases.
- Expert selection becomes imbalanced during inference, affecting service efficiency.
A traditional approach is to add a load-balancing auxiliary loss. However, auxiliary loss introduces additional gradient interference and requires weight tuning. If the weight is too large, it may harm the main task. If the weight is too small, it may fail to prevent expert collapse.
2. Basic Idea of QB: Use Thresholds and Online Calibration Instead of Auxiliary Loss
Auxiliary-loss-free dynamic load balancing usually relies on routing thresholds, expert biases, or quantile calibration. The goal is not to add another loss term, but to directly control the distribution of tokens received by experts.
Let the total number of tokens in the current window be N, and the number of experts be E. The target load can be written as:
q* = 1 / E
If expressed in absolute token counts:
L* = N / E
Let N_e be the number of tokens received by expert e in the current window. The actual load is:
q_e = N_e / N
To reduce short-term fluctuation, a sliding window or exponential moving average can be used:
q_tilde_e(t) = (1 - lambda) * q_tilde_e(t-1) + lambda * q_e(t)
Here, lambda can typically be set between 0.05 and 0.2, depending on training scale and update frequency.
3. How to Determine Whether an Expert Is Overheated or Overcooled?
A fixed threshold can be used, or a quantile-based threshold can be introduced.
Overheated condition:
q_tilde_e > q* + alpha
or:
q_tilde_e > Q_p(q_tilde) + delta_p
Here, Q_p denotes the p-th quantile of the load distribution across all experts. For example, p = 0.9 can be used. alpha can be set between 0.15 and 0.30, depending on the number of experts and tolerance level.
Overcooled condition:
q_tilde_e < q* - beta
or:
q_tilde_e < Q_{1-p}(q_tilde) - delta_p
beta can also be set between 0.15 and 0.30. When the number of experts is very large, it is recommended to use both a fixed target threshold and a quantile threshold, so that local skew is not hidden by average behavior.
4. How Should Thresholds or Biases Be Updated?
One common approach is to add a learnable bias b_e to the routing score:
s'_{x,e} = s_{x,e} + b_e
When an expert is overheated, its selection probability should be reduced. Therefore, the bias can be updated as:
b_e(t+1) = clip(b_e(t) + eta_b * (q* - q_tilde_e(t)),b_min,b_max)
If q_tilde_e > q*, the update term is negative, so the bias decreases. If q_tilde_e < q*, the update term is positive, so the bias increases.
If an explicit threshold theta_e is used, the update can be written as:
theta_e(t+1) = clip(theta_e(t) + eta_theta * (q_tilde_e(t) - q*),theta_min,theta_max)
Usually, a higher threshold means an expert is harder to select, which can reduce the load of an overheated expert.
5. How Should Update Frequency Be Chosen?
A practical design is:
- Small-scale experiments or fewer experts: Update once per step.
- Thousands of experts: Use a sliding window or EMA, and update every 8, 16, or 32 steps.
- Learning rate: The bias update step size should not be too large. Start with a small step size and set upper and lower bounds.
- Rollback conditions: If abnormal load-balancing behavior causes noticeable fluctuation in the main task loss, roll back to the previous stable threshold version or reduce the update frequency.
The value of QB is that it does not introduce an auxiliary loss, avoiding extra gradient contamination of the main task. The balancing process is dynamic and online, which is more suitable for thousand-expert scale. However, expert utilization, Drop Token rate, and main-task metrics must be monitored. It is not enough to check only whether the load is “balanced.”
4. Technique 3: Block-Level Attention Residuals (Block AttnRes)
1. Definition of Block-Level Attention Residuals
A block-level attention residual can be understood as follows: Transformer layers are organized into blocks, the outputs of the attention modules within each block are aggregated, and the resulting block-level information is injected into subsequent blocks.
This is not a simple layer-by-layer residual connection. Instead, it transfers attention state at the block level.
A relatively robust definition is:
- Divide model layers into several blocks, with each block containing
glayers. - Within each block, each layer keeps the regular attention residual.
- At the end of each block, aggregate attention outputs within the block, for example by summation, averaging, gated aggregation, or low-rank projection.
- Inject the aggregated block-level residual into the first layer or selected layers of the next block.
Formally, this can be written as:
R_b = sum_{l in Block_b} alpha_l * A_l
Here, A_l is the attention output of layer l, and alpha_l is a learnable or fixed weight.
In the next block, the following can be applied:
H'_{l+1} = H_{l+1} + gamma * R_b
A gated form can also be used:
H'_{l+1} = H_{l+1} + g_l ⊙ R_b
2. How Should Block Granularity Be Chosen?
Block granularity g can be set according to model depth. For example:
g = 4: Finer block division, with more frequent cross-layer information transfer.g = 8: A common compromise.g = 16: Suitable for ultra-deep networks, reducing cross-block synchronization frequency.
Larger block granularity is not always better. If the block is too large, the block-level residual may be too coarse. If the block is too small, the block-level mechanism may degrade into an ordinary layer-by-layer residual.
Ablation experiments are recommended to compare effectiveness and overhead under different g values.
3. Cross-Layer Information Transfer Paths
Block-level attention residuals usually have three types of cross-layer information transfer paths:
- Block-end aggregation: After each block finishes, aggregate attention outputs within the block to form a block-level summary.
- Cross-block injection: The block-level summary is projected through a linear layer and injected into the first layer or intermediate layers of the next block.
- Selective retrieval: Later layers read only selected block summaries to reduce information redundancy.
The purpose of this mechanism is to allow shallow-layer features to serve deep-layer computation more effectively, mitigating information decay in deep networks. However, whether it is effective should be validated through deep-task evaluation, long-context tasks, and ablation experiments.
4. Conditions for Memory and Communication Savings
It cannot be assumed that block-level attention residuals always save memory or communication. The following conditions must hold:
- Memory savings: Memory is saved only when block-level summaries are stored or synchronized at block boundaries, instead of storing complete activations for all layers. If full intermediate states are still stored, the memory benefit is limited.
- Communication savings: Cross-device communication should exchange only block summaries, low-rank projections, or compressed states, rather than synchronizing complete hidden states layer by layer.
- Parallelism compatibility: Under tensor parallelism, pipeline parallelism, and expert parallelism, communication can decrease only if block-level summaries effectively reduce synchronization frequency.
- Operator overhead control: If block-level aggregation introduces additional GEMM or gather operations, it is necessary to evaluate whether these costs cancel out the memory and communication benefits.
A more rigorous statement is:
Block-level attention residuals may bring memory and communication benefits only when block granularity is reasonably designed, cross-layer information transfer paths are controlled, and synchronization is truly reduced from full-state synchronization to block-level summaries. Final effectiveness should be confirmed through baseline comparison.
5. Training Workflow: Multi-Stage Context Expansion + Agentic Reinforcement Learning
Million-token context capability usually cannot be achieved in one step. A more reliable approach is progressive context expansion.
| Stage | Training goal | Suggested learning rate strategy | Key metrics to monitor | Example rollback conditions |
|---|---|---|---|---|
| 8K | Build foundational instruction following, multimodal alignment, and short-context capability | Use peak learning rate with warmup | Loss, gradient norm, expert load | Loss spikes, gradient explosion, severe expert load skew |
| 64K | Adapt to longer documents and interleaved multimodal inputs | Slightly lower than the 8K peak, maintaining stability | Long-text perplexity, retrieval accuracy, peak memory | Long-text metrics decline, memory keeps growing |
| 256K | Improve long-document reasoning and codebase-level context understanding | Small-step decay, with a focus on stability | Long-context QA, cross-paragraph citation, expert utilization | Long-range metrics decline, load imbalance |
| 1M | Explore million-token extrapolation and agentic long-horizon tasks | Very low learning rate or segmented learning rate; avoid abrupt updates | Ultra-long-context evaluation, extrapolation stability, inference latency | Extrapolation collapse, throughput anomaly, memory overflow |
In the post-training stage, if the goal includes AI Agent capabilities, million-token-level agentic reinforcement learning can be introduced. Reward signals should not depend only on the final answer. They should also include:
- Whether tool calls succeeded.
- Whether multi-step planning was completed.
- Whether results passed verification.
- Whether invalid loops occurred.
- Whether tools were called excessively.
This can more directly train the model to maintain goals, call tools, and verify results in long-chain tasks.
6. Engineering Deployment and Risk Warnings
Training a long-context MoE large model imposes high infrastructure requirements. In addition to compute scheduling and parallelism strategy, the following risks require attention.
1. Checkpoint and Recovery Risks
- Checkpoints should be saved regularly; they should not rely only on the final save.
- A multi-replica, versioned checkpoint strategy is recommended.
- After an interruption, validate checkpoint integrity, optimizer state, data loader position, and expert routing state.
- For long-context training, perform a small-scale validation after recovery to confirm that loss and metrics do not show abnormal jumps.
2. Object Storage and Permission Risks
- When object storage is used for training data, code packages, model weights, or checkpoint storage, configure least-privilege access.
- Different projects and teams should use isolated buckets or prefixes.
- Enable access logs, audit records, and necessary encryption policies.
- For checkpoint directories, enable versioning or lifecycle policies where appropriate to avoid accidental deletion.
3. Monitoring and Alerting Risks
Long-context MoE training should monitor the following:
- Whether loss spikes occur.
- Whether gradient norms become abnormal.
- Whether expert load remains skewed over time.
- Whether the number of idle experts increases.
- Whether memory keeps growing.
- Whether throughput suddenly drops.
- Whether data loading shows long-tail behavior.
- The frequency of training interruptions and recovery time.
4. Acceptance Criteria
The key question is not only whether training “can run,” but whether the following acceptance criteria are met:
- Peak memory remains controllable under million-token input.
- Long-context task metrics outperform the baseline.
- Expert load distribution converges to the target range.
- Metrics remain reproducible after interruption recovery.
- Inference throughput meets business requirements.
7. Frequently Asked Questions
Q1: What Is Lower-Bounded Decay Parameterization?
Lower-bounded decay parameterization sets a controllable lower bound for the logarithmic decay term in linear attention, preventing the decay factor from becoming infinitely small. The goal is to reduce the risk of overflow or underflow in chunked computation, making it easier to use dense Tensor Core paths.
Q2: How Can Expert Collapse Be Identified?
Several signals can be checked:
- A small number of experts receive most tokens.
- Many experts remain idle for a long time.
- Expert load variance continues to rise.
- The Drop Token ratio becomes abnormal.
- Training metrics become unstable, and load-balancing adjustments do not help.
Q3: Should QB or Auxiliary Loss Be Chosen?
If the model scale is large, the number of experts is large, and the goal is to avoid auxiliary-loss contamination of the main-task gradient, QB can be evaluated first.
If the model is smaller, the training objective is simpler, and a mature auxiliary-loss solution already exists, auxiliary loss can still be used, but its weight should be controlled and main-task metrics should be monitored.
A hybrid approach such as “small-weight auxiliary loss plus QB calibration” can also be tried, but ablation validation is required.
Q4: What Are Common Mistakes in NoPE Extrapolation?
Common mistakes include:
- Assuming NoPE supports extrapolation without actually using NoPE during training.
- Evaluating only short-text performance without million-token long-text evaluation.
- Ignoring the matching between lower-bounded decay parameters and tile length.
- Failing to validate BF16 or FP16 worst-case behavior.
- Pursuing theoretical complexity without measuring real throughput.
8. Summary
Combining million-token context with ultra-large sparse MoE is fundamentally a coordination problem involving compute efficiency, training stability, and engineering reliability.
Lower-bounded decay linear attention focuses on numerical safety and operator efficiency under long context. Auxiliary-loss-free dynamic load balancing focuses on load convergence during training with massive numbers of experts. Block-level attention residuals focus on cross-layer information transfer in deep networks.
Together with multi-stage context expansion and agentic reinforcement learning, these techniques can form a more complete technical solution.
For teams planning to develop or optimize long-context multimodal large models, small-step validation is recommended:
- First confirm numerical boundaries.
- Then validate expert load behavior.
- Finally evaluate the benefit of deep-layer residual mechanisms.
Only when the baseline is clear, metrics are reproducible, and risks can be rolled back should context length and parameter scale be gradually increased.
