Key Training Techniques for Large-Scale MoE and Long-Context Modeling

    As large language models expand in both parameter scale and context length, combining long-context modeling with large-scale Mixture of Experts (MoE) introduces significant engineering challenges. This article explores three critical areas of these challenges: computational efficiency in long-sequence attention via chunked linear attention with bounded log decay, MoE training stability through quantile-based dynamic biasing, and cross-layer information sharing in deep networks using attention mechanisms. Additionally, it covers a staged context extension strategy, providing practical engineering solutions for training advanced, agent-capable models.

    1. Background: Why Long-Context and Large-Scale MoE Are Simultaneously Becoming Harder

    Expanding the capabilities of large language models typically advances along three dimensions: parameter scale, context length, and training data volume. Once context length enters the million-token range, the computational and memory overhead of standard softmax attention grows quadratically with sequence length, making it unsustainable to rely solely on hardware stacking.

    The Mixture of Experts (MoE) architecture decouples total parameter count from single forward-pass computation through sparse activation. However, as the number of experts increases, issues such as unbalanced routing allocation, prolonged idleness of certain experts, and mid-training divergence are amplified simultaneously. Furthermore, agent-based applications require models to perform multi-turn tool calls and long-chain reasoning, which imposes higher stability requirements on the post-training phase.

    This article focuses on three engineering problems: the computational efficiency of long-sequence attention, the training stability of sparse experts, and information passing in deep networks. Each section explains the mechanism behind the problem and provides a corresponding general solution.

    2. Linear Attention and Chunked Computation

    Linear attention replaces softmax with a commutative kernel function form, making the computational complexity approximately linear with respect to sequence length. By introducing a decay term, the model can gradually forget historical information based on position, which aligns with the local dependency characteristics of natural language.

    In engineering implementations, a chunking strategy is commonly adopted: intra-chunk computation is parallelized using matrix multiplication, while state is passed recursively between chunks. Intra-chunk computation requires the cumulative decay factor and its reciprocal. When the decay factor approaches zero, its reciprocal increases rapidly, causing overflow or underflow in low-precision formats (e.g., BF16). Once a numerical anomaly occurs, implementers often have to fall back to a slow, position-by-position path, failing to fully utilize the hardware’s matrix multiply-accumulate units.

    2.1 Log-Domain Decay and Lower Bound Constraint

    A common approach to handle this is to parameterize the decay in the log domain and set a lower bound. Let the log decay at position t be $g_t$, which can be written as:

    $gt = g{min} \times \text{sigmoid}(zt)$, where $g{min} < 0$

    Since the output of sigmoid lies in (0, 1), $gt$ falls within the interval $[g{min}, 0)$. Taking $g_{min} = -5$, the lower bound of the single-step decay factor $\exp(g_t)$ is approximately $e^{-5}$, or 0.0067. Within a chunk of length 16, the minimum cumulative log decay is -80, corresponding to a maximum reciprocal factor of approximately $e^{80}$, or $5.5 \times 10^{34}$. This value remains lower than the maximum representable value of BF16 (approximately $3.4 \times 10^{38}$), ensuring that the intra-chunk reciprocal calculation does not overflow.

    Below is a sample code snippet illustrating how this constraint can be applied within a chunk:

    1. import torch
    2. G_MIN = -5.0 # Log decay lower bound, limits the numerical upper bound of the reciprocal factor
    3. def bounded_log_decay(z: torch.Tensor) -> torch.Tensor:
    4. """Maps the raw output to the [G_MIN, 0) interval."""
    5. return G_MIN * torch.sigmoid(z)
    6. def chunk_scale_factors(log_decay: torch.Tensor):
    7. """
    8. log_decay: [batch, heads, chunk_len]
    9. Returns intra-chunk prefix decay and its reciprocal.
    10. The upper bound of the reciprocal is determined jointly by G_MIN and the chunk length.
    11. """
    12. cum = torch.cumsum(log_decay, dim=-1) # Intra-chunk cumulative log decay
    13. decay = torch.exp(cum) # Prefix decay, value in (0, 1]
    14. inv_decay = torch.exp(-cum) # Reciprocal factor, numerically bounded
    15. return decay, inv_decay
    16. # A one-time check can be added in engineering to confirm the reciprocal factor is within the representable range of the target precision
    17. decay, inv_decay = chunk_scale_factors(bounded_log_decay(torch.randn(2, 8, 16)))
    18. assert inv_decay.max().item() < torch.finfo(torch.bfloat16).max

    The cost of this approach is minimal. It only changes the parameterization of the decay without altering the model’s computational structure, allowing it to be directly integrated into existing chunked implementations. It is important to note that the value of $g_{min}$ affects the model’s expressive capacity: a lower bound that is too small restricts the forgetting speed, while a lower bound that is too large may cause the reciprocal factor to exceed the safe range. This value should be evaluated in conjunction with the chunk length and target precision, and its distribution should be monitored during the early stages of training.

    2.2 Engineering Validation Checkpoints

    After adopting bounded decay, the following aspects should be checked:

    • Whether the maximum value of the intra-chunk reciprocal factor is below the upper limit of the target precision.
    • Whether the relative error of the output is within an acceptable range when compared against a high-precision reference implementation.
    • Whether the computation time maintains the expected linear growth trend across different sequence lengths.

    3. MoE Load Balancing and Training Stability

    3.1 Problems Caused by Load Imbalance

    The MoE router selects a small number of experts for each token. If certain experts are consistently selected, they become overloaded, creating computational bottlenecks and slowing down synchronization steps during distributed training. Conversely, other experts rarely receive gradients, preventing their parameters from being effectively updated, which equates to wasted model capacity.

    A common practice is to add an auxiliary loss to the training loss to penalize load imbalance. The problem with such methods is that the coefficient is difficult to tune: an excessively large coefficient will forcibly flatten the routing, hindering expert differentiation; an excessively small coefficient will leave the load still unbalanced. Auxiliary loss can also interfere with the gradients of the main task, which becomes particularly pronounced when the number of experts is large.

    3.2 Quantile-Based Dynamic Biasing

    An alternative approach avoids introducing additional loss terms and instead directly adjusts the routing scores based on recent load. The specific steps are:

    1. Count the proportion of tokens received by each expert at fixed step intervals.
    2. Calculate the quantiles of the load distribution to categorize experts into overloaded, normal, and underloaded.
    3. Apply a negative bias to the routing scores of overloaded experts and a positive bias to underloaded experts. This bias only affects routing selection and does not participate in the gradient calculation of the main loss.

    The following code provides a schematic implementation of this idea (not a complete reproduction of any specific scheme):

    1. import torch
    2. def quantile_bias_update(load: torch.Tensor, step_size: float = 1e-3) -> torch.Tensor:
    3. """
    4. load: [num_experts], the proportion of tokens recently received by each expert
    5. Returns the routing bias increment for each expert.
    6. """
    7. q_hi = torch.quantile(load, 0.75)
    8. q_lo = torch.quantile(load, 0.25)
    9. delta = torch.zeros_like(load)
    10. delta[load > q_hi] = -step_size # Overloaded experts: decrease probability of being selected
    11. delta[load < q_lo] = step_size # Underloaded experts: increase probability of being selected
    12. return delta
    13. # Update the bias after each training step; the bias only acts on routing scores
    14. # bias += quantile_bias_update(recent_load)

    The advantage of this method lies in its fine-grained control and decoupling from the main loss. Using quantiles instead of the mean reduces the impact of individual extreme experts on the update direction. The step size is the primary hyperparameter: a step size that is too large will cause routing to oscillate among experts, while a step size that is too small will lead to slow convergence.

    Because sparse activation causes each expert to see only a portion of the data, the gradient noise is greater than that of dense models. Common mitigation measures include:

    • Normalizing the router’s logits or adding regularization terms to suppress the excessive expansion of individual logits.
    • Using Gated Linear Unit (GLU) structures in the expert feed-forward layers to improve gradient flow.
    • Applying initialization scaling to expert parameters that matches the number of layers to prevent the variance of deep layer outputs from amplifying layer by layer.
    • Monitoring gradient norms and loss curves, and rolling back to the latest checkpoint promptly when anomalies are detected.

    3.4 Training Monitoring Metrics

    It is recommended to record at least the following metrics:

    • The entropy of expert load, or the ratio of maximum load to average load.
    • The proportion of tokens dropped due to capacity limits.
    • The distribution of parameter update magnitudes across experts.

    These metrics can expose routing degradation and expert idleness in advance, providing more diagnostic value than simply looking at the total loss.

    4. Cross-Layer Information Sharing in Deep Networks

    Standard residual connections accumulate outputs layer by layer according to $h_{l+1} = h_l + F_l(h_l)$. As the network deepens, the representations from early layers are continuously superimposed, causing the information received by later layers to become homogeneous and making it difficult to select earlier features on demand.

    An improved approach is to treat the outputs of each layer as a set of selectable historical representations, using an attention mechanism to weight and aggregate them, replacing the direct addition with a fixed weight of 1. To control memory and cross-device communication overhead, the network can be divided into several blocks: standard residual connections are retained within blocks, while the outputs between blocks are aggregated via an attention format. This way, each layer does not need to store the entire history but only needs to access block-level summaries.

    The engineering key points of this design include:

    • Weighing the granularity of block division. Smaller blocks allow for more sufficient information sharing but increase the number of communication passes.
    • The aggregation weights must be normalized; otherwise, the magnitude of deep layer outputs will spiral out of control as the number of layers increases.
    • In model parallel scenarios, the transmission timing of block-level summaries should be aligned with the pipeline schedule to avoid introducing additional waiting.

    5. Staged Context Extension

    Training directly from scratch with ultra-long sequences incurs high computational costs, and it makes it difficult for the model to first learn local language patterns. A more common practice is staged context extension: first complete the main language capability training on shorter sequences, and then progressively extend the sequence length, retaining the weights from the previous stage at each level.

    During each extension, the positional encoding needs to be adjusted synchronously. Taking Rotary Positional Encoding (RoPE) as an example, the base frequency parameter can be adjusted to allow the model to maintain at longer distances.