Long Context and Sparse MoE: Key Techniques for Training Large Language Models

    This article breaks down the architecture and training techniques behind million-token context, trillion-parameter sparse MoE multimodal models. It covers the overall design across four dimensions, the hybrid attention stack (linear attention, gated MLA, and block attention residuals), MoE stability mechanisms such as quantile balancing, the multi-stage context extension and agentic RL pipeline, and practical engineering concerns around inference cost and observability. The three highlighted techniques are platform-independent and offer high reuse value for in-house architectures.

    1. Introduction: Why Long Context and Ultra-Sparse MoE Are Driving LLM Evolution

    Over the past two years, the frontier of large model capability has shifted from “does a single-turn answer read smoothly” to “can the model retrieve, summarize, reason, and act over extremely long materials.” This shift imposes two coupled requirements on the underlying architecture: first, the context window must be long enough while keeping compute and memory overhead under control for long sequences; second, model capacity must keep growing without a proportional increase in inference activation. Sparse mixture-of-experts (MoE) and efficient attention mechanisms have therefore become the common technical choices across the industry.

    This article takes the general technical form of a “million-token context plus trillion-parameter sparse MoE multimodal model” as its subject, abstracts its architectural components, training stage breakdown, and three engineering techniques with high reuse value, and presents a technical brief for R&D teams. It does not reference any specific vendor product, and all capability descriptions are confined to the general technical scope that is publicly available and broadly accepted in the industry.

    2. Overall Architecture: Four Dimensions of Technical Density

    A natively multimodal sparse model that supports million-token context typically requires design trade-offs across four dimensions.

    • Parameter scale and activation ratio: Total parameters reach the trillion level, while the parameters activated per token account for only a few percent of the total, with a typical form of roughly 2.8 trillion total parameters and about 104 billion activated. This ratio decouples “capacity” from “single forward-pass cost.”
    • Native multimodal support: Modalities such as vision are incorporated into a unified token space during the pre-training stage rather than bolted on later through adapters, avoiding representation misalignment across modalities.
    • Hybrid attention system: Linear attention handles the linear-complexity backbone for long sequences, while gated multi-head latent attention handles high-precision modeling of key positions, with the two complementing each other.
    • Extreme expert sparsity: The number of routed experts can reach the hundreds, combined with activation function modifications and load-balancing mechanisms to keep training from collapsing.

    It is worth emphasizing that the figures above come from the public technical reports for this class of architecture and are meant to illustrate the design scale; they should not be read as acceptance metrics for any specific implementation.

    3. Attention Layer Design: Linear Backbone + Gated Latent Attention + Cross-Layer Residuals

    3.1 The Engineering Value of Incremental Linear Attention (KDA)

    Linear attention writes the within-sequence cumulative decay as a continued product, in theory reducing complexity from quadratic to linear. On real GPUs, however, chunked computation needs the reciprocal of the cumulative decay factor, which is prone to numerical overflow or underflow under the limited precision of BF16/FP16. The common engineering compromise is that diagonal chunks go through an explicit position-pair path, and only off-diagonal chunks can be accelerated with matrix multiplication. The result is two operator branches within the same layer, which adds implementation complexity and wastes Tensor Cores.

    The lower-bounded decay parameterization changes the log decay from an unbounded negative softplus to a scaled sigmoid form with a lower bound, illustrated below:

    1. # g: per-step log decay; g_min is a fixed lower bound (e.g., -5)
    2. g = g_min * torch.sigmoid(logit) # lower-bounded, reciprocal range is controllable
    3. decay = torch.exp(g) # numerical range is locked to a safe interval

    The benefit is twofold. Once the numerical range is constrained, the reciprocal scaling factor for any chunk of 16 tokens falls within a safe interval, so diagonal chunks no longer need a special branch and all causal chunks go through dense matrix multiplication uniformly. At the same time, this form naturally fits a no-positional-encoding (NoPE) setup, so extrapolating to million-level context does not rely on extra position interpolation tricks.

    3.2 Gated Multi-Head Latent Attention (Gated MLA)

    Latent attention reduces cache footprint by compressing key-value representations in a low-rank form, while gating applies adaptive scaling to the attention output to suppress noise from irrelevant heads. Two points need attention in practice: first, the ratio of compression dimension to head count needs to be tuned in tandem with context length; second, the quantization strategy for the KV cache must match the numerical distribution of the compressed representation, otherwise accuracy drops noticeably during the long-context stage.

    3.3 Block Attention Residuals (Block AttnRes)

    Representation degradation in deep networks usually comes from “a single additive path between layers.” Block residuals partition residual information by block and share it across layers, letting shallow-layer details reach deep layers across several layers. Compared with storing all intermediate activations per token, block granularity strikes a balance between memory footprint and communication volume, and is especially friendly under pipeline parallelism, because what is transferred across stages is a block summary rather than a full tensor.

    4. MoE Design: Three Pillars of Stability Under Extreme Sparsity

    4.1 Stable Latent-Space MoE Architecture

    Placing routing and expert computation in the latent space reduces the projection overhead for expert inputs and outputs. When the number of routed experts reaches the hundreds, top-k selection and the expert capacity factor must be tuned jointly: too small a k wastes capacity, while too large a k pushes activation cost back up.

    4.2 SiTU-GLU-Style Activation Functions

    Gated linear unit family activations are widely used in MoE, and their improved versions mainly adjust the shape of the nonlinear segment so that gradients are more balanced across the positive and negative ranges, reducing the probability of expert “death.” The practical recommendation is to keep adjustments consistent with the initialization scale and the position of expert normalization layers; replacing the activation function on its own often yields limited gains.

    4.3 Quantile Balancing (QB)

    The traditional approach adds an auxiliary load-balancing loss, but the auxiliary loss competes with the main task gradient and causes loss jitter in large-scale training. The idea behind QB is to set dynamic thresholds directly by the quantiles of the routing scores to achieve balancing, with no extra loss term. Illustrative logic:

    1. # Determine the set of selected experts per step by quantile, no auxiliary loss needed
    2. thr = torch.quantile(scores, 1 - capacity_ratio, dim=-1, keepdim=True)
    3. topk_idx = (scores >= thr).nonzero(as_tuple=True)

    The engineering benefit is fewer hyperparameters, cleaner gradients, and better robustness to changes in the number of experts.

    5. Training Pipeline: Multi-Stage Context Extension and Agentic Reinforcement Learning

    Context capability is not trained in a single pass but advanced stage by stage: first build a solid foundation of language and multimodal alignment on short sequences (such as 8K), then extend successively to 64K, 256K, and up to 1M. Each stage requires synchronized adjustments to the parallel partitioning strategy, learning rate, and data mix, and the long stages also need a blend of “long-document retrieval” synthetic data to maintain attention quality.

    The post-training stage introduces million-token-level agentic reinforcement learning, focusing on planning, tool calling, and error recovery for long-horizon tasks. Practical recommendations include reproducible task environments, layered reward signals (outcome reward plus process reward), and truncation and credit-assignment strategies designed for long trajectories, to avoid the convergence difficulty caused by long-horizon sparse rewards.

    6. Engineering Practice: Inference Cost and Observability

    • Cache management: Paged KV cache plus prefix reuse is key to cutting costs in multi-turn long-document scenarios.
    • Parallelism strategy: Expert parallelism and sequence parallelism need to align with the partitioning granularity of block residuals and block attention.
    • Observability: Bring expert load distribution, routing entropy, and block numerical ranges into monitoring and alerting, and use logging services and monitoring/alerting systems to locate training collapse and accuracy anomalies.
    • Deployment form: On the enterprise side, a container platform can host inference services, with object storage managing corpora and checkpoints, and a message queue decoupling asynchronous tasks.

    If you want a lower barrier to long-context and document-understanding capability, you can also evaluate general-purpose large model service offerings in the cloud and access file parsing, content generation, and data analysis through a unified API, rather than building a full training pipeline in-house.

    7. Conclusion

    Combining long context with ultra-sparse MoE is essentially fine-grained engineering within the triangle of “capacity, cost, and stability.” Lower-bounded decay parameterization solves operator efficiency and numerical safety, quantile balancing solves load balancing without an auxiliary loss, and block attention residuals solve deep representation together with memory and communication overhead. None of these three changes depend on a specific platform, they have high reuse value, and they are worth validating first in in-house architectures.