Engineering Practices for Ultra-Long Context and Sparse Expert LLMs
This article explores the engineering challenges and practical solutions for scaling large language models across three dimensions: sequence length, parameter scale (using Mixture of Experts), and model depth. It covers mitigating the quadratic complexity of standard attention in ultra-long contexts through linear attention and bounded decay parameterization, stabilizing MoE training via quantile-based bias adjustment, and addressing the deep representation bottleneck with block-level attention residuals.
I. Background: Why Three Bottlenecks Emerge Simultaneously
The improvement of large language model (LLM) capabilities typically advances along three dimensions: processing longer inputs, expanding parameter scales, and enhancing multi-step reasoning. Each dimension introduces specific engineering challenges that can mutually amplify each other.
The first bottleneck appears in the sequence dimension. The computational complexity of standard scaled dot-product attention is proportional to the square of the sequence length, and memory consumption grows accordingly. When context expands from a few thousand tokens to the million level, attention becomes the primary overhead in the entire forward pass.
The second bottleneck appears in the parameter dimension. The Sparse Mixture of Experts (MoE) architecture uses a routing mechanism so that each token only passes through a few experts. The total parameter count can be massive, while the active parameters per forward pass remain small. The trade-off is that load balancing among experts is easily disrupted, and the training process is prone to oscillation.
The third bottleneck appears in the depth dimension. As the number of layers increases, later layers struggle to effectively utilize representations from earlier layers, causing information to dilute along the residual path. Cross-layer information sharing therefore becomes critical for improving representation quality.
The following sections discuss the causes, common solutions, and implementation details of these three types of bottlenecks.
II. Computational Bottlenecks in Ultra-Long Contexts
2.1 Quadratic Complexity of Standard Attention
For a sequence of length $N$, standard attention computes an $N \times N$ score matrix. When $N$ exceeds 100,000, materializing this intermediate matrix alone exceeds single-GPU memory, requiring block-wise computation (such as fused kernels with block-wise read/write) to avoid full materialization. Block-wise computation reduces peak memory but cannot change the quadratic growth of computation.
Therefore, long context scenarios generally follow two paths: the first retains softmax attention but reduces actual access through sparsification, sliding windows, or chunking strategies; the second adopts linear complexity attention variants, replacing the full KV cache with recursive states. Both paths have trade-offs: the former preserves precise global retrieval capabilities, while the latter keeps inference memory essentially independent of sequence length.
2.2 Chunked Parallelism in Linear Attention
Linear attention replaces softmax with kernel decomposition, allowing computation to be written in a recursive form. Pure recursion cannot fully utilize matrix computation units during training, so chunking is widely adopted in engineering: intra-chunk parallel computation is done via matrix multiplication, while inter-chunk information is passed through state vectors.
There is a hidden risk in chunked implementation. Intra-chunk computation often involves the reciprocal of cumulative decay factors, which shrink exponentially in long sequences. Under low-precision formats (like BF16), the reciprocal may overflow or underflow, leading to numerical errors. To avoid this, developers often write separate computation paths for the diagonal blocks of a chunk rather than directly calling a unified matrix multiplication kernel. This special branch reduces overall throughput and increases maintenance costs.
2.3 Bounded Decay Parameterization
A straightforward approach is to constrain the range of decay parameters so that the intra-chunk cumulative factor always falls within a representable numerical interval. Assuming the original log decay is an unbounded real number, a scaled sigmoid can map it to a bounded interval:
$g = g{\min} \cdot \sigma(x), \quad g{\min} < 0$
Where $\sigma$ is the sigmoid function. The range of $g$ is $(g_{\min}, 0)$, so the cumulative decay for $L$ tokens within a chunk satisfies:
$\exp(L \cdot g{\min}) < \prod{t=1}^{L} e^{g_t} \le 1$
Taking a chunk length of $L=16$ and $g_{\min}=-5$ as an example, the range of the cumulative factor is roughly from $e^{-80}$ to $1$. Its maximum reciprocal is about $e^{80} \approx 5.5 \times 10^{34}$, which falls within the representation range of 32-bit floating-point numbers (approx. $3.4 \times 10^{38}$). BF16 shares the same exponent bit-width as 32-bit floating-point numbers, making it equally applicable.
This constraint brings two benefits. First, all intra-chunk tiles can use the same matrix multiplication path without designing a special branch for diagonal blocks. Second, with a bounded decay upper limit, the model’s extrapolation on ultra-long sequences is more stable.
Below is a schematic code snippet, solely for illustrating the handling of numerical boundaries:
import torchG_MIN = -5.0 # Lower bound constant; its value should be verified with chunk length and target precisiondef bounded_log_decay(x: torch.Tensor) -> torch.Tensor:"""Map the unbounded original parameter to the (G_MIN, 0) interval."""return G_MIN * torch.sigmoid(x)def chunk_cumulative_decay(log_decay: torch.Tensor) -> torch.Tensor:"""Calculate intra-chunk cumulative decay, input shape is [..., chunk_len]."""cum = torch.cumsum(log_decay, dim=-1)return torch.exp(cum)# Example: With chunk length 16, the lower bound of the cumulative factor is exp(16 * -5) = exp(-80)x = torch.randn(2, 16)decay = chunk_cumulative_decay(bounded_log_decay(x))inv_decay = 1.0 / decay # The reciprocal is bounded under fp32 and can be directly used for matrix computation
During actual deployment, a combined verification of $g_{\min}$ and chunk length should be performed to ensure no overflow in both gradients and forward results under the target precision.
2.4 Positional Encoding and Length Extrapolation
Another issue in long-context training is positional information. Schemes like Rotational Positional Encoding (RoPE) experience out-of-distribution shifts beyond the training length. Common practices include interpolation, frequency scaling, or randomized position techniques.
An alternative route is not explicitly injecting positional encoding (NoPE), letting decay and causal masks carry sequential information themselves. This approach reduces the engineering burden of positional extrapolation but requires the model to sufficiently observe dependency relationships at various distances during training. The choice of route should be comprehensively judged based on target length, data distribution, and the support level of the inference framework.
III. Training Stability in Sparse Expert Architectures
3.1 The Fundamental Contradiction Between Sparsity and Routing
The core benefit of MoE is achieving larger parameter capacity with less computation. Taking a model with a total parameter scale reaching the trillion level and active parameters at a few percent of that, each token only needs to pass through very few experts, yet the model retains a large amount of expert knowledge.
The higher the sparsity, the fewer samples each individual expert receives, and the router is more likely to concentrate most tokens onto a few popular experts. This load imbalance leads to two consequences: popular experts overload and become computational bottlenecks, while cold experts receive sparse gradients and ultimately learn insufficiently. The higher the sparsity, the more prominent this contradiction.
3.2 Side Effects of Auxiliary Loss
The traditional approach is to add a load balancing auxiliary loss to the training objective to encourage the router to distribute tokens evenly. The coefficient of the auxiliary loss needs careful tuning: if too small, the imbalance cannot be corrected; if too large, it interferes with the language modeling objective, making expert division artificial and unnatural.
At an ultra-large scale with numerous experts, this trade-off becomes even more sensitive. Therefore, the industry is also exploring load balancing methods that do not rely on auxiliary loss.
3.3 Quantile-Based Bias Adjustment
One approach is to detach load balancing from the loss function and instead directly adjust routing biases. The bias only participates in top-k selection, not in the calculation of gate weights. Therefore, it does not change the numerical values of expert outputs, nor does it force the balancing objective onto the language modeling loss.
The key point of the quantile method is to use the quantile of the current batch’s load as a reference line, rather than the mean. The mean is easily skewed by extreme experts, whereas the quantile is more robust to outliers.
import torchdef quantile_bias_update(bias: torch.Tensor,expert_load: torch.Tensor,q: float = 0.5,step: float = 1e-3,) -> torch.Tensor:"""Update routing bias based on the quantile of expert load.expert_load: Number of tokens received by each expert in the current batch, shape [num_experts]"""load = expert_load.float()threshold = torch.quantile(load, q)# Decrease bias for experts with load above the threshold, increase for those belowbias = bias + step * torch.sign(threshold - load)return bias# During routing, bias is only used to influence top-k selectiondef route(logits: torch.Tensor, bias: torch.Tensor, k: int):scores = logits + biastopk_idx = torch.topk(scores, k, dim=-1).indices# Gate weights still use original logits to ensure expert output is unaffected by bias valuesgate = torch.softmax(torch.gather(logits, -1, topk_idx), dim=-1)return topk_idx, gate
The adjustment step step and quantile q need to be determined through experiments. Too large a step will cause bias oscillation, while too small a step results in insufficient balancing speed.
3.4 Choice of Gating Activation Functions
Experts typically use Gated Linear Units (GLU) and their variants. The gating structure allows the network to perform element-wise selection on inputs, and its expressive power is generally superior to standard two-layer feed-forward networks. In sparse scenarios, the gradient characteristics of the activation function are particularly important: gradients that are too small make it hard for cold experts to update, while gradients that are too large may trigger training instability.
In practice, you can compare the convergence speed and gradient norm distribution of different gating forms under the same parameter budget before deciding which to adopt. No single activation function dominates in all settings; conclusions should be drawn from your own data and scale.
IV. Cross-Layer Information Passing in Deep Networks
4.1 The Deep Representation Bottleneck
Standard residual connections add each layer’s output to the main trunk. As the number of layers increases, information on the trunk is constantly overwritten by subsequent layers, making it difficult for later layers to directly read features from early layers. This phenomenon is sometimes referred to as the deep representation bottleneck.
An intuitive remedy is to let each layer access the outputs of all previous layers, but fully storing all intermediate representations brings significant memory and communication pressure, especially in pipeline parallelism or multi-node training.
4.2 Block-Level Attention Residuals
A compromise is to divide the network layers into several blocks. Computation proceeds normally within each block, while information is shared between blocks via attention-style weighted aggregation. Each layer only needs to access a few block summaries rather than all historical representations, resulting in lower memory and communication overhead.
import torchimport torch.nn as nnclass BlockResidualMix(nn.Module):"""Illustration: weighted aggregation of completed block summaries, added to the current layer output."""def __init__(self, dim: int, max_blocks: int):super().__init__()self.query = nn.Parameter(torch.randn(dim) * 0.02)self.key_proj = nn.Linear(dim, dim, bias=False)def forward(self, hidden: torch.Tensor, block_summaries: list[torch.Tensor]):if not block_summaries:return hidden# Stack block summaries into the shape [num_blocks, batch, seq, dim] to calculate weightssummaries = torch.stack(block_summaries, dim=0)keys = self.key_proj(summaries)scores = torch.einsum("d,nbsd->nbs", self.query, keys)weights = torch.softmax(scores, dim=0)# Aggregate block summaries and add to the current hidden statemixed = torch.einsum("nbs,nbsd->bsd", weights, summaries)return hidden + mixed
