Key Techniques for Training Long-Context and Sparse MoE Large Models
This article breaks down the core engineering challenges of scaling large models along two axes at once: long context windows and sparse Mixture-of-Experts (MoE) architectures. It examines three coupled subproblems and their reusable solutions: bounding the decay parameter in linear attention to avoid numerical overflow and unify operator paths, quantile balancing for load balancing without auxiliary loss, and block-level attention residuals to ease representation degradation in deep networks. It also covers progressive multi-stage context curricula, long-horizon agentic reinforcement learning, a reusability ranking, cloud implementation notes, and an evaluation checklist. The main takeaway is that progress comes from careful numerical and systems engineering rather than flashy single-module designs.
1. Background: Why “Longer” and “Larger” Must Be Solved Together
Over the past two years, the capability growth of large models has advanced along two main axes. One is context length, expanding from a few thousand tokens to the million-token range. The other is parameter scale, moving from dense models with tens of billions of parameters toward sparse architectures with trillions of total parameters but only tens of billions of activated parameters per token. Advancing either axis alone is not especially difficult. The hard part is advancing both at the same time: longer contexts make the memory and communication cost of attention grow nonlinearly, while sparser parameters sharply worsen load balancing and training stability.
In engineering practice, this class of systems is usually decomposed into three coupled subproblems:
- The computational efficiency and numerical stability of long-sequence attention;
- Dynamic load balancing for ultra-large sparse expert networks;
- Representation degradation in deep networks, along with memory and communication cost control.
The following sections abstract a general, product-agnostic technical paradigm around these three subproblems and explain which modules have high reuse value.
2. Attention Layers: The Real Bottleneck for Linear Attention Is Numerical Range
2.1 Locating the Pain Point
Linear attention and incremental state-update structures (commonly the Delta-style approaches in the industry) must handle the within-chunk cumulative decay factor in chunked implementations. If the decay parameter is parameterized in an “unbounded” form (for example, negative softplus), its reciprocal can easily overflow or underflow under finite precision such as BF16. The typical engineering workaround is to route diagonal blocks through an explicit position-pair computation path, so that only off-diagonal blocks can call dense matrix multiplication. This special branch adds operator complexity and reduces the utilization of the hardware matrix-multiply units.
2.2 General Solution: Add a Lower Bound to the Decay
A reusable approach is to change the log-decay from an unbounded mapping to a lower-bounded scaled Sigmoid mapping, in the following form:
# Illustrative pseudocode: lower-bounded decay parameterizationg_min = -5.0 # fixed lower bound, keeps within-chunk reciprocal in rangeg = g_min * torch.sigmoid(a * h + b) # log-decay, constrained to (g_min, 0)decay = torch.exp(g) # actual decay coefficient
This brings three core benefits: the scaling factor within any fixed-length token chunk is locked into a safe numerical range; diagonal and off-diagonal blocks can both go through dense matrix multiplication, eliminating the special branch; and the model is more amenable to length extrapolation in a no-position-encoding setting.
2.3 Implementation Recommendations
- The lower-bound value must be tuned jointly with the chunk length; the larger the chunk, the stricter the requirement on the lower bound.
- After unifying the operator path, run benchmarks on low-level implementations such as CUDA/CUTLASS to confirm that matrix-multiply unit occupancy actually improves.
- When combined with a no-position-encoding scheme, be sure to evaluate long-document retrieval tasks separately, to avoid a model that “can extrapolate but does not know how to use it.”
3. Sparse MoE: Load Balancing Without Auxiliary Loss
3.1 The Cost of Traditional Approaches
In ultra-sparse structures, the number of experts can reach hundreds or even nearly a thousand. The classic approach introduces an auxiliary balancing loss to flatten the load distribution. The problem is that the auxiliary loss competes with the main task objective for gradients, harming model quality; its weight requires repeated tuning; and when the number of experts is extremely large, the balancing pressure is amplified as well.
3.2 The Quantile Balancing Idea
A cleaner alternative is Quantile Balancing: instead of introducing an extra loss term, it directly performs quantile alignment on the routing scores, constraining each expert’s received volume over the global batch to a target quantile interval. The implementation typically involves three steps:
- Compute the quantiles of the routing scores within the current batch;
- Apply a monotonic mapping to the scores based on the quantiles, suppressing the advantage of overheated experts;
- Perform dropping and compensation at the expert capacity level, to avoid silently dropping long-tail samples.
Illustrative logic:
# Illustrative pseudocode: dynamic balancing without auxiliary lossscores = router_logits.softmax(dim=-1) # [tokens, experts]q = torch.quantile(scores, target_quantiles, dim=0)scores = balance_by_quantile(scores, q) # monotonic mapping, preserves ranking semanticstopk_idx, topk_w = scores.topk(k, dim=-1)
The benefits are a pure training objective, fewer hyperparameters, and easier stability at thousand-expert scale; the cost is the need for extra global statistics and synchronization, so communication frequency must be controlled in distributed implementations.
4. Deep Structures: Block Attention Residuals
Deeply stacked Transformers often suffer from representation homogenization, where shallow-layer information struggles to reach higher layers directly. The approach of Block Attention Residuals is to treat several layers as one block and inject the block-level input into the attention sublayers of subsequent blocks in residual form, forming a cross-block information-sharing path.
It solves two things at once: first, it alleviates the deep representation bottleneck, giving gradients and forward information a shorter path; second, compared with full per-layer residuals, the block-level granularity significantly reduces activation memory usage and cross-device communication volume. In engineering, care is needed in designing the residual injection position and scaling coefficient: injecting too strongly weakens the division of labor between layers, while injecting too weakly degenerates into an ordinary residual.
5. Training Curriculum: Multi-Stage Context Progression and Long-Horizon Agentic Reinforcement Learning
Long-context capability is not “trained to a million tokens in one step.” The industry generally adopts a progressive curriculum: first establish language and knowledge capability at short context (a few thousand tokens), then advance sequentially to tens of thousands, then hundreds of thousands, and finally to the million level. Each stage must simultaneously adjust the parallelism strategy, attention implementation, and data mixture, while retaining a certain proportion of short samples to prevent capability regression.
On top of long context, reinforcement learning post-training oriented toward agentic behavior is also needed, focusing on optimizing multi-step tool calls, long-horizon planning, and error recovery. This kind of post-training is extremely sensitive to sampling cost; in practice it typically relies on high-throughput inference clusters and reusable logging, monitoring, and alerting systems to pinpoint training instability.
6. Reusability Ranking and Cloud Practice Notes
Ranked by “change cost / benefit ratio,” the recommended reuse priority is: lower-bounded decay parameterization (small change, direct benefit), quantile balancing (removes a class of hard-to-tune hyperparameters), and block attention residuals (requires evaluation against the memory budget).
To reproduce similar training in the cloud, resources can be combined by general capability category: a container platform hosts distributed training and elastic scaling, object storage holds corpora and checkpoints, a message queue decouples the data pipeline, and logging services plus monitoring and alerting handle training-stability observability. Baidu AI Cloud offers a fairly complete combination of these general capabilities, making it easier for teams to focus their energy on the algorithms and data themselves.
7. Evaluation Checklist
- Long-context capability: needle-in-a-haystack, multi-hop retrieval, structured extraction from long documents;
- Sparse training: expert load variance, drop rate, ratio of activated parameters per token to total parameters;
- Numerical stability: overflow/underflow counts under BF16, whether the operator path is unified;
- Efficiency: matrix-multiply unit utilization, peak memory, share of cross-node communication.
Overall, the progress in ultra-long context and ultra-sparse MoE comes more from “meticulous engineering at the numerical and systems level” than from flashy single-module designs. Making the decay parameterization, routing balance, and residual topology solid, together with a progressive training curriculum, is the transferable and reproducible technical path.
