Technical Routes for Long-Context and Sparse Mixture-of-Experts Large Language Models
This article outlines the main engineering challenges of scaling large language models in both context length and parameter count. It covers the compute and memory costs of long-sequence attention, chunked linear attention and the numerical stability of its decay parameters, and the training stability of sparse Mixture of Experts (MoE) models, including load balancing, the trade-offs of auxiliary losses, and a quantile-based bias update method.
1. Background
Large language models are scaling in two directions. The first is input context length. A model may need to read hundreds of thousands, or even a million, tokens of material at once, such as a full technical manual, a large code repository, or a long conversation log. The second is parameter count. The Mixture of Experts (MoE) architecture allows a model’s total parameter count to far exceed the number of parameters used in a single forward pass.
When these two directions combine, engineering teams usually face three problems:
- As sequences grow longer, the compute and memory cost of attention rises sharply.
- With many experts, the risk of load imbalance and training divergence increases.
- As networks grow deeper, information from early layers gets diluted as it passes through each layer, which limits representational capacity.
Long-horizon agent tasks also require the model to keep its goals consistent across multiple rounds of tool calls and long planning sessions. These problems are interrelated. Optimizing one part in isolation often affects the others.
2. Computational Bottlenecks of Long Context
2.1 Quadratic Complexity of Standard Attention
Standard self-attention computes the correlation between every pair of positions in a sequence of length n, producing an n×n correlation matrix. Both the compute and the explicitly stored memory grow with n². For example, scaling from 8K to 1M tokens multiplies the sequence length by 128, which theoretically multiplies the compute by about 16,384. This is an arithmetic estimate, not a measured result from any specific system.
Inference also faces the key-value (KV) cache problem. The cache size is proportional to sequence length, so long contexts consume large amounts of memory. This directly limits how many concurrent requests a single GPU can serve.
2.2 Linear Attention and Chunked Computation
Linear attention changes the order of matrix multiplications so that computational complexity scales approximately linearly with sequence length. The trade-off is that the recurrent state can suffer numerical drift over long sequences, and a purely recurrent form cannot fully use matrix multiplication hardware.
A common compromise is chunked computation. Within each chunk, the model uses parallel matrix operations. Between chunks, information passes through a recurrent state. Chunk sizes are typically powers of two, such as 16, 32, or 64, so they align well with the matrix computation units of the hardware.
2.3 Numerical Stability of Decay Parameters
Linear attention with decay factors needs to scale data within each chunk by the reciprocal of the cumulative decay. When a decay factor approaches zero, its reciprocal becomes very large and can easily overflow in half-precision floating-point formats. When decay approaches 1, related computations can lose precision through underflow.
One engineering approach is to bound the range of the log decay. For example, constrain the log decay to the interval (g_min, 0):
# Pseudocode: constrain the log decay to the interval (g_min, 0)def bounded_log_decay(x, g_min=-5.0):return g_min * sigmoid(x)
Take 16 tokens per chunk and a lower bound of -5 for the single-step log decay. The lower bound of the cumulative decay within a chunk is then about e⁻⁸⁰. Its reciprocal is about e⁸⁰, which remains within the representable range of common floating-point formats. This constraint has two direct effects:
- The cumulative decay within a chunk has a known numerical bound, so the overflow risk of scaling operations stays under control.
- Diagonal blocks and off-diagonal blocks can use the same matrix multiplication path. This reduces branching and makes efficient implementation easier.
2.4 Positional Information and Length Extrapolation
In some linear attention designs, the decay itself encodes relative distance, so explicit positional encodings can be omitted. This reduces the model’s reliance on extrapolating positional encodings. However, architecture alone is only a necessary condition. To achieve reliable long-range retrieval and reasoning at the 1M scale, a model still needs training on data near the target length. The architecture cannot guarantee length extrapolation by itself.
3. Training Stability of Sparse Mixture of Experts
3.1 Basic MoE Structure
An MoE layer consists of multiple feed-forward networks (experts) and a router. For each token, the router computes a score for every expert and activates only the top k experts with the highest scores. As a result, each token passes through only a small fraction of the model’s parameters, even though the total parameter count can be very large.
# Pseudocode: top-k routingscores = softmax(router_logits(h))topk_idx = argtop_k(scores, k)out = sum(scores[i] * expert[i](h) for i in topk_idx)
As the number of experts increases, each expert’s capacity shrinks, and expressive capacity per unit of compute improves. However, the sparsity introduced by routing also amplifies sources of training instability.
3.2 Load Imbalance
If routing consistently favors a few experts, those experts receive most of the tokens. The remaining experts get too few gradient updates and gradually degrade. In distributed training, imbalanced load also leaves devices idle during communication and computation, which slows overall throughput.
To check whether the load is healthy, observe the proportion of tokens each expert receives in a batch and plot the distribution as a histogram. The ideal state is that the proportions are close to uniform and the distribution converges steadily over training.
3.3 Common Costs of Auxiliary Losses
A widely used industry practice is to add an auxiliary loss to the training objective that encourages uniform routing. Its advantage is simple implementation. Its drawbacks are also clear. The auxiliary loss gradients conflict with the language modeling loss. A coefficient that is set too high harms model quality, while one that is set too low fails to balance the load effectively. The coefficient is sensitive to the data distribution and the number of experts, so tuning it is costly.
3.4 Quantile-Based Dynamic Bias
One approach avoids relying on an auxiliary loss. Instead, it maintains a bias term for each expert. The bias affects only the top-k selection and does not participate in computing the gating weights. After each training step, the system adjusts each expert’s bias based on how its load compares with a reference quantile:
# Pseudocode: quantile-based bias updatedef update_bias(bias, load, q=0.5, step=1e-3):ref = quantile(load, q) # use the quantile as the reference linereturn bias + step * sign(ref - load)
