A Troubleshooting Framework for Long-Context and Large-Scale MoE Training

    This article presents a structured troubleshooting framework for training large language models that combine long context windows with large-scale Mixture-of-Experts architectures. It covers three recurring problem areas—numerical stability in linear attention, auxiliary-loss-free load balancing with many experts, and the memory and communication overhead of deep residual streams—and provides actionable checklists, pseudocode, and fallback procedures for each.

    1. Background: New Constraints from Simultaneous Scaling of Size and Context

    There are two common routes to improving large language models: scaling up parameter counts and extending the context window. When both are applied together, training bottlenecks shift from raw compute alone to a combination of memory, communication, and numerical stability issues.

    Standard attention scales quadratically with sequence length. Mixture-of-Experts (MoE) reduces per-step computation by activating only a small subset of experts per token, but it introduces routing imbalance, amplified cross-device communication, and training instability. As networks get deeper, residual information is passed repeatedly between layers, and saved intermediate results grow linearly with depth.

    This article organizes three recurring problem areas, each structured around causes, steps or pseudocode, and risk boundaries:

    1. Numerical stability and chunked execution efficiency of linear attention;
    2. Auxiliary-loss-free load balancing when the number of experts is very large;
    3. Memory and communication overhead of deep residuals as networks grow deeper.

    A recommended troubleshooting order: check numerical issues first, since NaNs interrupt training directly. Then check load balancing, which determines throughput and expert specialization. Finally, check memory and communication, which usually determine whether a configuration can run at all, as well as the ceiling on scale.

    2. Numerical Stability of Linear Attention

    2.1 Basic Chunked-Parallel Form

    Linear attention replaces softmax attention with a recurrent kernel function. With a fixed chunk length C, computation grows roughly linearly with sequence length. If the chunk length grows with the sequence, the linear complexity assumption no longer holds.

    In practice, the sequence is split into chunks of length C. Within a chunk, computation is parallelized via matrix multiplication; across chunks, historical information is passed through state recurrence. Causality within a chunk must be handled with masking. Diagonal and off-diagonal sub-blocks have different computation patterns; if the diagonal sub-block takes a per-position special branch, it cannot reuse highly optimized dense matrix-multiplication kernels. Making all sub-blocks go through a unified dense matmul path is therefore the key engineering concern.

    2.2 Numerical Risks from Decay Factors

    Many variants introduce a per-token decay factor γ, expressing the inductive bias that recent information matters more. If decay is tracked in log form, the cumulative log decay at position i within a chunk, b_i, is the sum of log γ over the first i positions, and it is negative.

    A common formulation computes relative relationships in reciprocal form, i.e., multiplying by exp(-b_i). When b_i is very negative, exp(-b_i) becomes extremely large. The table below shows upper limits for common formats, in natural logarithm units.

    • FP16: maximum representable value approximately 65504, natural log approximately 11.09.
    • BF16 and FP32: maximum representable value approximately 3.4e38, natural log approximately 88.7. BF16 shares FP32’s exponent bits but has only 7 mantissa bits, so it has low precision; its overflow threshold is not lowered by this.

    The root cause is that log decay has no lower bound. As long as log γ can go arbitrarily negative, the cumulative quantity within a chunk cannot be estimated in advance, and numerical safety depends entirely on empirical tuning.

    2.3 Bounded Parameterization and Range Checks

    A more robust approach is to bound the log decay:

    g_t = g_min × sigmoid(a_t), where g_min < 0 and a_t is a learnable parameter.

    Per-step log decay is thus confined to the interval [g_min, 0). The theoretical lower bound of the chunk-level cumulative quantity is C × g_min, and the maximum exponent needed by the reciprocal form is C × |g_min|. The pseudocode below demonstrates the mapping, accumulation, and range check.

    1. # Pseudocode for illustration only; does not correspond to any specific framework's API
    2. def bounded_log_decay(a, g_min):
    3. # Map unconstrained parameters into [g_min, 0)
    4. return g_min * sigmoid(a)
    5. def chunk_cumsum(log_decay):
    6. # Accumulate along the time dimension within a chunk in FP32, shape [heads, chunk_len, dim]
    7. return cumsum(log_decay.astype(fp32), axis=1)
    8. def range_check(g_min, chunk_len, dtype_max_log, margin=1.0):
    9. # The reciprocal form needs a maximum exponent of chunk_len * |g_min|
    10. exp_arg = chunk_len * abs(g_min)
    11. return exp_arg, exp_arg <= dtype_max_log - margin
    12. # dtype_max_log: approximately 11.09 for FP16, approximately 88.7 for BF16 and FP32
    13. a = random_normal(shape=(8, 16, 64)) # 8 heads, chunk length 16, feature dim 64
    14. g = bounded_log_decay(a, g_min=-5.0)
    15. cum = chunk_cumsum(g)
    16. print(min(cum), max(cum)) # Actual range of the cumulative quantity
    17. print(max(exp(-cum))) # Theoretical upper bound ~ exp(80), about 5.5e34
    18. print(range_check(-5.0, 16, 88.7)) # (80.0, True), FP32 can handle it
    19. print(range_check(-5.0, 16, 11.09)) # (80.0, False), FP16 will overflow

    This example shows that with g_min = -5 and chunk length 16, exp(80) ≈ 5.5e34. It is representable in FP32 but exceeds the FP16 limit, so under FP16 it becomes inf, and subsequent multiplication or subtraction with zero produces NaN. Also note that even if individual factors are in range, the products q·exp(b) and k·exp(-b) can still overflow, so checks should cover the combined intermediate results.

    2.4 Choosing g_min and Fallback Procedures

    The value of g_min is constrained from both ends. The upper limit comes from the numerical range: |g_min| too large causes overflow. The lower limit comes from modeling capacity: |g_min| too small makes all decays close to 1, and the model struggles to forget distant information. The selection process:

    1. Perform accumulation and reciprocal computation in FP32, and determine the target compute precision.
    2. Compute the upper limit from chunk length and precision: |g_min| ≤ (dtype_max_log − margin) / C. For example, with FP32 and chunk length 64, the limit is about 1.37; with FP16 and chunk length 16, about 0.63.
    3. Take several candidate values within the limit, run short training, and record loss curves, NaN occurrences, and retrieval or continuation metrics at the target length.
    4. Among candidates that meet task metrics, choose the one with the largest numerical margin.

    If NaN or inf appears during training, fall back in this order: first raise the decay path to FP32; then shorten the chunk length; finally tighten |g_min|. Change only one variable at a time so you can tell which step helped.

    2.5 Risk Boundaries

    Bounded constraints are more numerically controllable, but that does not mean risk-free. They limit the model’s ability to express very recent and very distant information. When extrapolating to longer sequences, effectiveness must be confirmed with evaluation sets of the corresponding length; it cannot be inferred from the decay range alone. The example numbers in this section illustrate magnitudes only; actual configurations should be based on measurements on the target hardware and precision.

    3. Auxiliary-Loss-Free Load Balancing with Massive Numbers of Experts

    3.1 Causes and Costs of Routing Imbalance

    MoE top-k routing selects several experts for each token. Without constraints, a few experts receive a large number of tokens while most remain nearly idle. Overloaded experts become compute and communication bottlenecks, idle experts waste parameter capacity, and training throughput drops.

    The more experts, the more pronounced the problem. When experts are distributed across multiple devices, imbalance amplifies cross-device communication, with some devices waiting for long periods and overall utilization dragged down.

    3.2 Side Effects of Auxiliary Losses

    The industry commonly uses auxiliary losses to penalize load imbalance, but their side effects are equally clear.

    • The coefficient is hard to tune. When too large, it interferes with the main language-modeling objective, sacrificing quality for balance; when too small, balancing is insufficient.
    • Auxiliary loss gradients act on the router, changing the assignment pattern and indirectly affecting expert specialization.
    • As the number of experts grows, the optimal coefficient often shifts, raising tuning costs.

    For these reasons, more and more approaches aim to achieve balance without modifying the loss function.

    3.3 Quantile-Based Dynamic Bias

    This approach maintains a non-trainable bias b_i for each expert, following three rules.

    1. The bias participates only in top-k selection, i.e., ranking by s_i + b_i. Gating weights still use the original scores s_i, so the bias does not change the output weighting.
    2. The bias does not enter the loss and receives no gradients; it is updated only by statistical rules.
    3. The statistics window covers expert receive counts over the most recent W steps. The reference value uses a quantile rather than the mean, because a few extreme experts skew the mean.
    1. # Pseudocode for illustration only; does not correspond to any specific framework's API
    2. def route(scores, bias, k):
    3. # scores: [tokens, experts], affinity scores
    4. topk_idx = topk(scores + bias, k) # Bias participates in selection only
    5. gate = softmax(gather(scores, topk_idx)) # Gating weights still use original scores
    6. return topk_idx, gate
    7. def update_bias(bias, counts, eta=1e-3, b_max=1.0, tau=0.1):
    8. # counts: tokens received by each expert over the last W steps, shape [num_experts]
    9. ref = quantile(counts, 0.5) # Median as the reference load
    10. overloaded = counts > ref * (1 + tau)
    11. underloaded = counts < ref * (1 - tau)
    12. bias = bias - eta * overloaded + eta * underloaded
    13. return clip(bias, -b_max, b_max) # Bound the bias to prevent drift

    The median and tolerance tau are implementation choices that need validation on your own load distribution. Updates can happen every step or every K steps. Higher frequency means faster response but also more noise.

    3.4 Risk Boundaries and Monitoring Metrics

    Too large an η causes bias oscillation, with experts switching back and forth between overload and idleness. Too small an η makes balancing too slow. The bias range b_max must match the score scale, otherwise the bias overwhelms the semantic scores. When the capacity factor is set too tightly, tokens get dropped due to individual spikes even when the distribution is balanced.

    The following metrics should be tracked continuously during training:

    • Coefficient of variation of expert load, to measure distribution uniformity;
    • Proportion of tokens dropped due to capacity overflow;
    • Share of cross-device communication waiting in per-step time;
    • Value range of each expert’s bias;
    • Tokens processed per second.

    4. Memory and Communication Overhead of Deep Residuals

    4.1 Memory Causes

    Backpropagation requires saving forward-pass intermediate tensors. In an L-layer network, per-layer activation is roughly B × S × D × bytes × k, where B is batch size, S is sequence length, D is hidden dimension, and k is the number of intermediate tensors that must be saved per layer. k has no theoretical value and must be calibrated empirically.

    The deeper the network, the larger the residual stream and the greater the memory pressure. Long sequences amplify this term proportionally to S.

    4.2 Memory Estimation and Activation Recomputation

    The function below provides a rough estimate and compares with and without activation recomputation.

    1. # Pseudocode; factor is k, which must be calibrated with one real measurement
    2. def activation_gb(layers, batch, seq, hidden, bytes_per=2, factor=12, ckpt=False):
    3. per_layer = batch * seq * hidden * bytes_per * factor
    4. if ckpt:
    5. # Save only each layer's input; recompute intermediates during backward
    6. total = layers * batch * seq * hidden * bytes_per + per_layer
    7. else:
    8. total = layers * per_layer
    9. return total / 1024**3

    Activation recomputation trades compute for memory. Full recomputation roughly adds one extra forward pass, noticeably increasing compute time. Therefore, recomputation granularity should be chosen based on memory headroom: when headroom is sufficient, recompute only some blocks; when tight, expand the scope.

    4.3 Cross-Device Communication

    At each pipeline-parallel stage boundary, each micro-batch requires transferring B_mb × S × D × bytes. This amount is transferred once in the forward pass and once in the backward pass. It can overlap with computation, but only if communication bandwidth is sufficient to cover the compute time.

    In tensor parallelism, each block involves several collective communications with data volume on the order of B × S × D. Sequence parallelism can shard the residual along the sequence dimension, reducing both residual memory and communication, at the cost of higher implementation complexity.

    4.4 Depth Growth and Initialization

    The output variance of residual branches accumulates with depth. Uncontrolled, the residual norm of deep networks keeps growing, and numerical instability tends to appear late in training. A common practice is to initialize residual branch output layers scaled by 1/sqrt(2L), and to log per-layer residual norms during training to check for monotonic growth with depth.

    4.5 Risk Boundaries

    Memory and communication estimates only give magnitudes. The k value, degree of communication overlap, and kernel fusion all change actual costs, so profiler output should be the source of truth. Both activation recomputation and sequence parallelism have clear costs; before choosing either, confirm the bottleneck really is in the corresponding place.

    5. Selection Checklists

    Linear attention:

    • Chunk length C is fixed and does not vary with sequence length;
    • Accumulation and reciprocal computation use FP32;
    • The |g_min| upper limit has been computed as (dtype_max_log − margin) / C and passed the range check;
    • Retrieval or continuation metrics at the target length have been validated with short experiments;
    • The fallback order (raise precision, shorten chunks, tighten g_min) is written into the training script.

    Load balancing:

    • Number of experts, number of devices, and experts per device are fixed, and the communication topology has been verified;
    • Capacity factor is set, and the token drop rate is within an acceptable range;
    • Bias update frequency, η, and b_max have been validated at small scale;
    • Expert load coefficient of variation, cross-device wait share, and throughput are monitored;
    • The bias does not enter the loss, and gating weights still use original scores.

    Residuals and memory:

    • The activation coefficient k has been calibrated with a real measurement, and a memory budget has been produced;
    • Activation recomputation granularity is set based on memory headroom;
    • Per-transfer volume at pipeline boundaries is smaller than compute time, or overlap has been verified;
    • Residual branches are initialized with depth-scaled factors, and per-layer residual norms are logged;
    • The benefits and implementation costs of sequence parallelism have been evaluated.

    All code in this article is pseudocode for illustrating numerical behavior and workflows; thresholds and coefficients must be re-validated on the target model, hardware, and data.