Key Techniques for Training Long-Context, Sparse MoE Large Models

    This article breaks down the engineering challenges of combining million-token context windows with extremely sparse Mixture-of-Experts (MoE) architectures. It covers multi-stage context extension, numerically stable linear attention and gated latent attention, load balancing without auxiliary loss, and post-training with reinforcement learning, along with a reusable checklist and common pitfalls.

    1. Background: Why “Long Context + Extreme Sparsity” Is Hard Together

    The competition in large model capabilities has shifted over the past two years from raw parameter count to the combination of two dimensions: expanding the context window from a few thousand tokens to the million-token scale, and moving model architectures from dense to extremely sparse Mixture-of-Experts (MoE). Each of these has a mature path on its own, but doing both at once amplifies three classes of engineering problems to a level that cannot be avoided.

    The first is the efficiency and memory footprint of attention. Standard full attention grows quadratically in both computation and memory with sequence length L; at the million-token scale, even with efficient kernels, it hits the limits of hardware and memory bandwidth. The second is numerical stability. Linear attention and state-space-style structures need to accumulate decay factors during chunked parallel computation, and under finite precision these easily overflow or underflow, forcing implementations onto a slow non-matrix-multiplication path. The third is load balancing in sparse models. When the number of routed experts reaches hundreds or even thousands, a few experts get over-selected while the rest sit nearly idle, pushing actual compute utilization far below the theoretical value and making training curves prone to spikes and divergence.

    Understanding how these three classes of problems couple is the prerequisite for judging whether a technical approach is reliable. The rest of this article follows the order of scale and training orchestration, attention, sparse structure, and post-training.

    2. Scale and Training Orchestration: Multi-Stage Context Extension

    Long-context capability is not a switch; it is a product of training strategy. The common industry practice is progressive extension: complete the main pre-training on a shorter window (for example 8K) so the model quickly acquires language and knowledge, then transition through 64K and 256K, and finally to the 1M scale. This brings three benefits.

    • Controllable cost: per-step computation at short sequence lengths is small, so most of the token budget goes to “learning knowledge” rather than “learning long-range dependencies.”
    • Better stability: starting directly with an ultra-long window leaves no buffer for attention distribution and position extrapolation, so the loss curve oscillates more easily.
    • Clear capability layering: each stage can set its own learning rate, data mixture, and evaluation criteria, making regressions easier to localize.

    Three things are needed on the engineering side. The first is constructing long-range samples on the data side, including document-level concatenation, cross-section question answering, and repository-level code, to avoid “a long window with very short effective dependencies.” The second is consistency of the position scheme; if a design without explicit positional encoding is used, it must stay consistent across stages so the model can extrapolate by relying on its own state. The third is evaluation criteria: long context must be assessed on retrieval-type tasks, aggregation-type tasks, and multi-hop reasoning tasks at the same time, since looking at a single metric easily leads to wrong conclusions.

    An illustrative stage configuration (pseudocode, expressing orchestration only):

    1. stages = [
    2. {"seq_len": 8192, "lr": 3e-4, "tokens": "60%"},
    3. {"seq_len": 65536, "lr": 8e-5, "tokens": "25%"},
    4. {"seq_len": 262144,"lr": 4e-5, "tokens": "10%"},
    5. {"seq_len": 1048576,"lr": 1e-5, "tokens": "5%"},
    6. ]
    7. for st in stages:
    8. trainer.set_context(st["seq_len"])
    9. trainer.train(token_budget=st["tokens"], lr=st["lr"])

    3. Attention Layers: Why Combine Linear Attention with Gated Latent Attention

    Full attention is unaffordable over long sequences, so the mainstream approach introduces linear attention or state-space-style recurrence to reduce complexity to linear, while keeping a small number of global exact attention layers to compensate for long-range exact retrieval. Two reusable engineering points stand out.

    The first is the lower-bound constraint on decay parameterization. Chunked parallel linear attention needs the reciprocal of the accumulated decay within each chunk; if decay is parameterized as an unbounded negative value, that reciprocal overflows or underflows quickly under BF16. Changing decay to a scaled Sigmoid form with a fixed lower bound locks the scaling factor of any chunk into a safe range:

    1. # Decay parameterization with a lower bound (illustrative)
    2. g_min = -5.0
    3. g = g_min * torch.sigmoid(raw_log_decay) # bounded below, numerically controllable
    4. # The reciprocal of the accumulated decay within a chunk therefore stays in a safe range

    The benefit is not only “it does not blow up.” More importantly, it removes the special branch for diagonal chunks. In traditional implementations, the diagonal part within a chunk needs explicit per-position-pair computation and cannot call dense matrix multiplication; once unified, both diagonal and off-diagonal chunks can take the high-throughput tensor core path. Measured throughput gains usually come from here, not from a change in algorithmic complexity.

    The second is gated multi-head latent attention. Its core idea is to compress keys and values into a low-dimensional latent space and then use gating to control how much information each head retains, balancing cache footprint against representational capacity. The direct value on the inference side is a smaller cache and lower bandwidth pressure, which matters especially for long-context serving.

    The third is cross-layer information sharing. Representations in deep networks tend to converge, leading to insufficient effective depth. Introducing attention residuals at chunk granularity and injecting shallow-layer information into deeper layers by chunk can mitigate this without significantly increasing activations; compared with per-tensor residuals, the chunk-level scheme is more controllable in memory and communication overhead.

    4. Sparse Structure: Massive Experts and Auxiliary-Loss-Free Balancing

    When the number of routed experts scales to the hundreds, training stability becomes the main conflict. Three components deserve separate attention.

    The first is a stable latent expert structure. Placing expert parameters in a low-rank latent space reduces per-expert parameter count and routing noise, making optimization smoother. The second is the interplay of activation functions and gating. Using a gated linear unit-style activation with a learnable temperature keeps gradient scales reasonable under sparse activation. The third is the choice of load balancing mechanism. The traditional approach relies on an auxiliary loss, but the weight of that loss is hard to tune: too large harms the main task, too small makes balancing ineffective. The auxiliary-loss-free approach instead applies quantile constraints directly to routing scores, pressing the probability of each expert being selected into a preset quantile range, achieving “soft constraints with no extra loss term.”

    1. # Pseudocode sketch of quantile balancing
    2. probs = router_logits.softmax(dim=-1) # [tokens, experts]
    3. q_low, q_high = 0.8 / num_experts, 1.2 / num_experts
    4. probs = probs.clamp(min=q_low) # lower bound prevents starvation
    5. probs = probs / probs.sum(-1, keepdim=True) # renormalize
    6. # The upper bound is implemented via temperature/scaling, avoiding an explicit aux loss

    Two pieces of tuning experience: the quantile range should not be too narrow, or it squeezes routing freedom; monitoring should look at “expert selection entropy,” “per-step max/min load ratio,” and “dropped token ratio” at the same time, and only when all three are normal is balancing truly in effect.

    5. Post-Training: Reinforcement Learning for Long-Horizon Agent Behavior

    Ultra-long context and sparse structure solve “can compute”; post-training solves “can use.” Reinforcement learning for agents must handle long-horizon sparse rewards. Common practices include: breaking tasks into verifiable intermediate steps and replacing a single terminal reward with rule-based rewards; introducing process supervision that scores intermediate artifacts such as tool calls, retrieval, and code execution; and limiting trajectory length and replay strategy under million-level context to control memory and sampling cost. Evaluation should cover multi-turn tool use, cross-section reasoning over long documents, and failure recovery, rather than only single-turn question answering.

    6. Reusable Checklist and Common Pitfalls

    • Do numerical stabilization first, then talk about kernel optimization; otherwise optimization gains get eaten by precision problems.
    • Context extension must be staged, with long-range dependency data and a separate evaluation set prepared for each stage.
    • For sparse model balancing, try the no-extra-loss-term approach first to minimize tuning cost.
    • Residual and cache designs must be evaluated for memory, communication, and throughput together; looking at only one is easy to misjudge.
    • To carry the above training and inference workloads, container platforms can orchestrate training jobs, object storage can hold checkpoints and datasets, and logging services with monitoring and alerting can track loss spikes, expert load, and throughput fluctuations; Baidu AI Cloud can serve as one reference for infrastructure selection in these general capabilities.

    Overall, the focus of competition in long-context and ultra-sparse models has shifted from “parameter and window numbers” to engineering details such as numerical stability, kernel utilization, and balancing mechanisms. Only by getting these four points solid can you achieve reproducible, stable training and inference under limited compute.