Long Context and Large-Scale MoE: Three Reusable Techniques

    This article examines three techniques for scaling large language models: bounded log-decay parameterization for chunked linear attention, auxiliary-loss-free quantile load balancing for MoE routing, and chunked residual attention for deep networks. It explains their mechanisms, implementation considerations, and trade-offs, with illustrative pseudocode and practical checks for numerical stability and routing behavior.

    Introduction: Three Bottlenecks, Three Techniques

    Scaling large language models involves three major bottlenecks.

    The first is sequence length. Standard attention has quadratic computational complexity, making latency and memory consumption difficult to manage for long-context workloads.

    The second is sparse expert routing. Mixture-of-experts (MoE) models activate only a subset of their parameters, but uneven routing can leave some devices idle while others become overloaded, reducing overall throughput.

    The third is network depth. As more layers are added, information from earlier layers can dilute the contribution of deeper representations. Transferring intermediate results across devices can also increase communication overhead.

    This article examines three reusable techniques that address these bottlenecks: lower-bounded log-decay parameterization in linear attention, auxiliary-loss-free quantile load balancing, and chunked residual attention. The code examples are illustrative pseudocode, not complete implementations of any specific system.

    1. Chunked Linear Attention and Numerical Stability

    1.1 Background: From Global Attention to Chunked Recurrence

    Standard softmax attention computes similarities between tokens, with O(n²) complexity. Linear attention uses a kernel-based formulation to express attention as a recurrence. The model maintains a fixed-size state matrix and updates it as each token arrives, so the computational cost of an individual step does not depend on sequence length.

    A purely recurrent implementation offers limited training parallelism. In practice, training therefore often uses chunking: the sequence is divided into fixed-length chunks, information passes between chunks through the state, and matrix operations process positions within each chunk in parallel.

    The within-chunk computation produces a lower-triangular causal matrix. Efficiently computing this matrix is an important factor in training throughput.

    1.2 The Challenge: Reciprocal Decay Factors in Low Precision

    Linear attention commonly includes a decay mechanism: historical information is multiplied by a factor smaller than one at each step. Computing relative decay between two positions in parallel requires ratios of cumulative decay factors, including their reciprocals.

    This creates a numerical-range problem. A decay factor close to zero has a very large reciprocal. Even factors closer to one can produce very small cumulative values over enough steps. In low-precision formats such as BF16, intermediate values can overflow, underflow, or lose precision.

    To avoid these problems, conventional implementations often use an explicit position-pair computation path for diagonal blocks—the regions containing nearby positions within a chunk. This prevents the entire causal matrix from being handled uniformly through dense matrix multiplication.

    Specialized matrix hardware is most effective on dense matrix operations. Separate computational paths complicate scheduling and can reduce throughput.

    1.3 Lower-Bounded Log-Decay Parameterization

    The proposed change is to parameterize log decay differently. A conventional softplus-based formulation allows log decay to become arbitrarily negative. The bounded formulation instead restricts it to an interval with a finite lower bound:

    1. def log_decay(x, g_min=-5.0):
    2. # Map the raw output to the interval (g_min, 0).
    3. # Log decay never falls below g_min, so each decay factor
    4. # is at least exp(g_min).
    5. return g_min * sigmoid(x)

    With g_min = −5 and a chunk length of 16 tokens, the cumulative log decay is bounded below by:

    16 × (−5) = −80

    The corresponding cumulative decay is approximately exp(−80) ≈ 1.8 × 10⁻³⁵, and its reciprocal is approximately 5.5 × 10³⁴.

    Both values lie within BF16’s representable range: its maximum value is approximately 3.4 × 10³⁸, and its smallest positive normal value is approximately 1.2 × 10⁻³⁸.

    For this 16-token configuration, the reciprocal scaling factors remain within a safe numerical range, removing the need for a separate diagonal-block computation path.

    1.4 Benefits and Trade-Offs

    This parameterization offers two main benefits.

    First, both diagonal and off-diagonal causal blocks can use a unified dense matrix multiplication path. Scheduling becomes simpler, making it easier to approach the hardware’s throughput limits.

    Second, the numerical range is controlled, improving stability in low-precision training.

    The source material also reports compatibility with a no-position-encoding (NoPE) configuration. Any conclusions about length extrapolation should be based on the original experimental results; compatibility alone does not establish extrapolation performance.

    The trade-off is a limit on how quickly the model can forget. Each step’s decay factor is at least exp(−5) ≈ 0.0067, so this decay mechanism cannot completely clear historical information in a single step.

    Tasks that require rapid context changes may need compensation from other model components. In practice, g_min should be chosen by balancing numerical safety against modeling flexibility and validating the result on the target task.

    1.5 Implementation Checklist

    • Verify that reciprocal scaling factors cannot overflow for the chosen chunk size and precision format.
    • Compare low-precision outputs with and without the lower bound, checking how errors accumulate.
    • Monitor decay distributions across layers to ensure that decay values do not remain saturated near the lower bound at most positions.
    • After unifying diagonal and off-diagonal computations, test the implementation against a position-by-position reference.

    2. Auxiliary-Loss-Free Quantile Load Balancing

    2.1 Uneven Routing in MoE Models

    In an MoE layer, the router selects the highest-scoring experts for each token. If most tokens are assigned to a small group of experts, the devices hosting those experts become bottlenecks while other devices wait.

    In large-scale parallel training, this imbalance directly reduces throughput.

    A common solution is an auxiliary loss that penalizes skewed expert loads and encourages the router to distribute tokens more evenly. Although effective, it introduces another optimization objective.

    Its weight requires careful tuning. If the weight is too small, routing remains unbalanced. If it is too large, the auxiliary objective can interfere with language modeling and reduce model quality.

    2.2 Balancing Without an Auxiliary Loss

    Quantile Balancing aims to adjust expert loads dynamically without introducing an auxiliary loss. As the name suggests, quantiles are its central statistical tool.

    The following pseudocode illustrates a generic approach. It should not be treated as an exact reproduction of the source method’s update rule.

    1. def route(scores, bias, k):
    2. # Bias affects expert selection only.
    3. # Gating weights still use the original scores to avoid
    4. # distorting the model output.
    5. adjusted = [s + b for s, b in zip(scores, bias)]
    6. return top_k_indices(adjusted, k)
    7. def update_bias(bias, load_per_expert, target_quantile, lr):
    8. # Use a quantile of the load distribution as the reference,
    9. # rather than the mean.
    10. threshold = quantile(load_per_expert, target_quantile)
    11. new_bias = []
    12. for b, load in zip(bias, load_per_expert):
    13. if load > threshold:
    14. new_bias.append(b - lr) # Reduce selection of overloaded experts.
    15. else:
    16. new_bias.append(b + lr) # Increase selection of lighter-load experts.
    17. return new_bias

    This design moves load adjustment out of the loss function and into direct updates of routing biases.

    The biases affect expert selection, while gating weights are computed from the original scores. Because the balancing adjustment does not add an auxiliary term to the main backpropagated loss, it avoids introducing an additional gradient objective into language modeling.

    2.3 Why Use Quantiles?

    Using a quantile rather than the mean as a reference has two practical motivations.

    First, expert loads can have a long-tailed distribution. A few extremely busy experts can distort the mean, whereas a quantile is more robust to extreme values.

    Second, a high load quantile focuses attention on the busiest experts, which may correspond to the devices limiting throughput. Choosing a higher target quantile therefore prioritizes reducing the loads at the upper end of the distribution.

    2.4 Costs and Engineering Considerations

    An auxiliary-loss-free approach still has operational costs.

    Statistics communication. Expert loads are distributed across devices. Computing a global quantile requires aggregating statistics across those devices. The statistics are small, but synchronization frequency must be chosen carefully to avoid extra waiting.

    Bias drift and oscillation. An overly large update rate can make routing biases oscillate, while an overly small rate may fail to track changes in the data distribution. Bias trajectories should be monitored alongside actual expert loads.

    Model-quality evaluation. Balanced loads are not sufficient evidence of success. Validation loss should also be compared at the same training step count to check whether routing adjustments harm model quality.

    2.5 Deployment Checklist

    • Test whether routing-bias updates converge in a small-scale MoE model first.
    • Track expert-load variance, maximum load, and load quantiles together.
    • Include bias-update frequency and learning rate in hyperparameter searches rather than reusing auxiliary-loss tuning settings.
    • Repeat experiments at different batch sizes to check whether results depend on a particular data order.

    3. Chunked Residual Attention: Deep Representations, Memory, and Communication

    3.1 Representation Bottlenecks in Deep Networks

    Residual connections allow information to pass directly across layers and are essential to training deep networks. However, a shared residual stream can also create a representation bottleneck.

    As successive layer outputs accumulate in the same stream, information from earlier layers may dominate, making later layers’ contributions relatively smaller. This effect is often described as representation dilution and can become more pronounced as depth increases.

    There is also a systems concern. In pipeline or tensor parallelism, intermediate activations must move between devices. If full states are retained and transferred for every layer, memory requirements and communication volume can grow with network depth.

    3.2 The Chunked Residual Approach

    Chunked residual attention groups consecutive layers into blocks. Within each block, computation uses conventional residual connections. Between blocks, the design passes block-level summaries rather than retaining each layer’s full state as a separate cross-block information source.

    Later blocks can combine historical block summaries with different weights, preserving access to a more diverse set of representations.

    The following pseudocode outlines the structure:

    1. def forward(x, blocks):
    2. summaries = [x] # Keep block summaries for cross-block access.
    3. for block in blocks:
    4. h = x
    5. for layer in block:
    6. h = h + layer(h) # Use conventional residuals within a block.
    7. summaries.append(summarize(h))
    8. x = combine(summaries) # Weight historical summaries for the next block.
    9. return x

    Here, summarize and combine are placeholders. The summary construction and weighting mechanism depend on the specific design described in the source material.

    3.3 Memory and Communication Benefits

    The potential benefit comes from reducing the number of objects retained and transferred across blocks.

    Retaining a full state for every layer requires storage that scales with the number of layers. Using block-level summaries instead makes the number of retained cross-block tensors depend on the number of blocks rather than the number of individual layers. This is the basis for the approach’s potential memory and communication savings.