Scaling MoE Models for Million-Token Contexts: Engineering Attention, Sparse Routing, and Training Stability

    This article examines the engineering patterns behind ultra-large-scale Mixture-of-Experts (MoE) multimodal models that support million-token contexts. Using a representative model with roughly 2.8 trillion total parameters and about 104 billion activated per token as a sample, it breaks down the core bottlenecks of long-context, sparse, multimodal systems: the quadratic cost of attention, numerical stability in linear attention, load balancing across hundreds of experts, progressive context extension, and native multimodal deployment. Readers will find reusable techniques such as lower-bounded decay parameterization, auxiliary-loss-free quantile balancing, block-level attention residuals, and a multi-stage training curriculum, along with a practical checklist for turning scale problems into solvable operator, numerical, and scheduling challenges.

    1. Why Scale Is No Longer the Only Question

    Over the past two years, the focus of large-model competition has shifted from parameter count to effective capability per unit of compute. Once total parameters reach the trillion level and context length advances to the million-token range, the real bottleneck is no longer whether a model can hold more knowledge. It is three things: whether attention over extremely long sequences is affordable, whether massive numbers of experts can train stably under extreme sparsity, and whether the model can maintain reasoning consistency across multi-turn tool calls and long-horizon tasks.

    This article uses a typical ultra-large-scale Mixture-of-Experts (MoE) multimodal model as a technical sample and abstracts the general engineering patterns in its architecture. The model has roughly 2.8 trillion total parameters and activates about 104 billion per token. It natively supports visual multimodality and million-token context. Its attention design combines incremental linear attention with gated multi-head latent attention, and uses cross-layer attention residuals to share information between layers. On the expert side, it adopts a large-scale routed expert structure, together with smooth gated activations and a quantile-based balancing mechanism to keep training stable. These designs are not isolated tricks; they are a systematic response to the triple pressure of sparsification, long sequences, and multimodality.

    2. The First-Principles Challenge of Long Context: Attention Operators and Numerical Precision

    2.1 Quadratic Complexity and the Memory Wall

    The compute and memory cost of standard self-attention grows quadratically with sequence length. When context expands from 8K to 1M, sequence length grows 128x and theoretical cost grows by roughly 16,000x. In practice, there are three common paths: sparse or sliding-window attention, low-rank or latent-compression attention, and linear attention (including state-space and incremental-update variants). The first two reduce complexity but may lose long-range dependencies. Linear attention reduces complexity to linear, but has long been constrained by operator implementation efficiency and numerical stability.

    2.2 Lower-Bounded Decay Parameterization: Fully Utilizing Matrix Units in Linear Attention

    When linear attention is computed in chunks, it must handle cumulative decay factors. The conventional approach parameterizes the log decay as an unbounded negative function, whose reciprocal can easily overflow or underflow under finite precision such as BF16. The engineering consequence is concrete: the diagonal blocks of the chunked matrix must take a special position-wise branch, cannot call dense matrix-multiply instructions, and leave a large portion of the hardware’s matrix compute units idle.

    A reusable improvement is to change the log decay into a scaled Sigmoid form with a lower bound, constraining the decay value between a fixed lower bound and zero:

    1. # Example: lower-bounded decay parameterization (g_min is a fixed negative constant, e.g., -5)
    2. g = g_min * torch.sigmoid(logits) # g in (g_min, 0)
    3. decay = torch.exp(g) # decay in (exp(g_min), 1)
    4. inv = 1.0 / decay # reciprocal locked in a safe numerical range

    The benefits are threefold. First, the reciprocal scaling factor within any fixed-length chunk is bounded to a safe range and no longer overflows under BF16. Second, diagonal and off-diagonal blocks both take the dense matrix-multiply path, eliminating branches and significantly improving throughput. Third, combined with a no-position-encoding design, the model’s extrapolation behavior on ultra-long context becomes more predictable, without relying on remedies such as position interpolation.

    2.3 Latent-Compression Attention and Cross-Layer Residuals

    Gated multi-head latent attention compresses keys and values into a low-dimensional latent space, significantly reducing memory bandwidth pressure, while gating adjusts the information retention ratio across different heads. The accompanying block-level attention residual injects shallow-layer representations into deeper layers in blocks, alleviating the representation bottleneck of deep networks. Compared with per-tensor residuals, the block-level approach is more controllable in memory usage and cross-device communication, making it suitable for large-scale training topologies that stack tensor parallelism and pipeline parallelism.

    3. Ultra-Large-Scale MoE: Stability Engineering for Sparsification

    3.1 Expert Count and Routing Entropy

    When the number of routed experts reaches hundreds or nearly a thousand and each token activates only a tiny fraction of them, model capacity and compute are fully decoupled. But extreme sparsity brings two risks: routing collapse (a few experts are over-selected) and load skew (severe imbalance in computation and communication across devices).

    3.2 Auxiliary-Loss-Free Load Balancing

    The conventional approach relies on an auxiliary balancing loss, which creates gradient conflicts with the main task objective and introduces a weight that requires careful tuning. The quantile-balancing idea directly constrains the selection ratio of each expert to a preset quantile range, adjusting routing scores with dynamic thresholds to achieve fast balancing without any extra loss term:

    1. # Example: dynamically adjust routing thresholds by quantile to down-weight overloaded experts
    2. load = tokens_per_expert.float() / tokens_per_expert.sum()
    3. upper = torch.quantile(load, q_high)
    4. gate = gate - upper * overload_mask # down-weight overloaded experts

    This approach converges faster with fewer hyperparameters and contributes noticeably to the stability of ultra-large-scale training.

    3.3 Gated Activations and Training Stability

    Smooth gated activations (such as gated variants of the Sigmoid linear unit) retain more gradient information than ReLU-family activations in deep networks. Combined with chunked residuals and proper initialization, they can significantly reduce the probability of loss spikes in trillion-parameter models. In practice, this also requires gradient clipping, optimizer state sharding, and fault-tolerant restart mechanisms.

    4. Training Curriculum: Progressive Expansion from 8K to 1M

    Training directly at million-token context is neither economical nor stable. The common practice is progressive context extension: complete the main learning at 8K first, then advance through 64K, 256K, and 1M in stages, adjusting learning rate, data mix, and parallelism strategy at each stage. On the data side, it is important to ensure a diverse mix of long documents, code repositories, structured tables, and multi-turn dialogues to avoid capability forgetting during the long-context stage.

    The post-training stage introduces million-token-level agentic reinforcement learning, focusing on long-horizon planning, tool calling, and error recovery. Reward design typically includes three components: task completion, process compliance, and an efficiency penalty, preventing the model from trading redundant steps for short-term gains.

    5. Multimodality and Engineering Deployment

    Native multimodality means the vision encoder and language backbone are jointly pre-trained rather than stitched together afterward. Deployment requires attention to the impact of image-text token ratios on memory, tiling strategies for high-resolution inputs, and cache management during inference. When building services on general cloud capabilities, a typical setup combines a container platform to host the inference cluster, object storage to hold models and datasets, logging and monitoring with alerting for observability, and a message queue for request peak shaving.

    6. Reusable Checklist

    1. For linear attention, prefer lower-bounded decay parameterization to gain matrix-unit utilization.
    2. For ultra-large-scale MoE, try auxiliary-loss-free quantile balancing first to reduce tuning cost.
    3. In deep networks, replace per-tensor residuals with block-level attention residuals to control memory and communication.
    4. Use a multi-stage curriculum for long context rather than a single step.
    5. In post-training, optimize primarily for long-horizon task metrics rather than single-turn metrics.

    The common logic behind these approaches is to turn “scale problems” into three problems that can be precisely solved by engineering means: operator efficiency, numerical stability, and scheduling balance.