Sparse Mixture-of-Experts at Scale: Engineering Practices and Deployment Guide

    This article examines the engineering challenges of large-scale sparse Mixture-of-Experts (MoE) models and the practices used to address them. It explains how sparse activation decouples total parameter count from per-token computation, then covers top-k gated routing, load balancing through auxiliary loss, capacity factors and routing noise, and expert parallelism with all-to-all communication. It also discusses attention design trade-offs among MHA, GQA and MQA, training stability measures, the distinction between base and instruct models, and a memory estimation method for long-context KV cache. The article provides a concise technical reference for teams designing, training and deploying MoE models.

    1. Background: Scaling Limits of Dense Models

    In dense architectures, every token passes through all parameters, so the number of model parameters and the computation per inference grow together. As parameter scale moves from tens of billions to trillions, training and inference costs quickly exceed the budgets of most teams.

    Mixture of Experts (MoE) breaks this coupling through sparse activation. The model contains many expert subnetworks, and each token is routed to only a few of them. Total parameter count determines the model’s knowledge capacity, while activated parameter count determines per-step computation; the two can be designed separately.

    2. Core MoE Mechanisms

    2.1 Gated Routing

    The gate network outputs scores for each expert for every token. After softmax normalization, the system selects the top-k experts and renormalizes their weights, which are then used as coefficients for the expert outputs. A simplified routing module example is shown below:

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class TopKRouter(nn.Module):
    5. def __init__(self, d_model: int, num_experts: int, top_k: int):
    6. super().__init__()
    7. self.gate = nn.Linear(d_model, num_experts, bias=False)
    8. self.top_k = top_k
    9. def forward(self, x: torch.Tensor):
    10. # x: [tokens, d_model]
    11. logits = self.gate(x) # [tokens, num_experts]
    12. probs = F.softmax(logits, dim=-1)
    13. topk_probs, topk_idx = probs.topk(self.top_k, dim=-1)
    14. topk_probs = topk_probs / topk_probs.sum(dim=-1, keepdim=True)
    15. return topk_idx, topk_probs

    2.2 Load Balancing

    If routing persistently favors a small number of experts, some experts remain idle and device load becomes uneven. Common responses fall into three categories:

    • Auxiliary loss: penalizes the sum over experts of the product of selection frequency and average gate probability, encouraging more uniform token allocation.
    • Capacity factor: limits the number of tokens each expert can process in a single batch. Tokens beyond capacity are skipped or sent to the residual path.
    • Routing noise: adds a small amount of random perturbation early in training to help different experts gradually develop specialization.

    A common form of auxiliary loss is:

    1. aux_loss = num_experts * sum_i( f_i * P_i )
    2. f_i: fraction of tokens assigned to expert i
    3. P_i: average gate probability for expert i

    2.3 Expert Parallelism

    When the number of experts is large, a single accelerator cannot hold all experts, so experts must be distributed across multiple devices. According to routing results, tokens are sent to the corresponding devices through all-to-all communication, and after computation they are returned to their original positions. Communication overhead often becomes a bottleneck, so expert granularity and the degree of overlap between communication and computation need to be considered together.

    3. Attention Architecture Trade-offs

    The number of attention heads and key-value (KV) heads directly affects memory usage and inference latency. Grouped Query Attention (GQA) lets multiple query heads share the same group of KV heads, significantly reducing KV cache.

    With a fixed total parameter budget, increasing the number of experts can expand parameter capacity, while reducing attention heads or KV heads can compress inference overhead. The balance depends on the target scenario: offline batch processing can prioritize capacity, while low-latency online serving needs to compress attention overhead.

    Approach KV cache usage Expressiveness Typical scenario
    Multi-Head Attention (MHA) Highest Strongest Small scale, quality first
    Grouped Query Attention (GQA) Medium Close to MHA General LLM inference
    Multi-Query Attention (MQA) Lowest Some degradation Extreme low latency

    4. Training Stability

    Common issues in large-scale training include loss spikes, gradient explosion and numerical overflow. Engineering measures generally include:

    1. Learning rate warmup and decay: gradually increase the learning rate early in training, then decay it using a cosine or linear schedule.
    2. Gradient norm clipping: set a threshold to prevent overly large single-step updates.
    3. Mixed-precision training: keep higher precision for numerically sensitive operators such as softmax and normalization.
    4. Checkpointing and rollback: save checkpoints periodically and roll back to the most recent stable state when training anomalies occur, avoiding a restart from scratch.

    For optimizer choice, Adam and its variants remain mainstream. Research on new optimizers for matrix parameters is also growing, but whether they provide benefits needs to be verified through small-scale ablation experiments. Changing only one variable at a time is necessary to determine the source of any effect.

    5. Base Models and Instruct Models

    The same model is often released in two versions with different purposes:

    • Base model: retains the general language distribution from pretraining and is suitable for continued training, domain adaptation and research reproduction.
    • Instruct model: built on the base model through supervised fine-tuning and preference optimization; it can follow instructions and produce structured content, and is suitable for direct use in dialogue and task execution.

    The selection principle is straightforward. If custom training is needed, start from the base model. If rapid deployment is needed, use the instruct model directly and adjust results through prompt design and business evaluation.

    6. Memory Estimation for Long Context

    The main cost of long-context serving comes from the KV cache. The memory occupied by a single sequence can be estimated with:

    1. memory ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per element × concurrent requests

    The following example uses assumed parameters: 60 layers, 8 KV heads, head dimension 128, FP16 (2 bytes per element), and a single sequence length of 256K.

    1. 2 × 60 × 8 × 128 × 256000 × 2 = 62,914,560,000 bytes, about 58.6 GiB

    This result is only an estimate under the assumed parameters and does not represent measured data from any specific model. It shows that even a single long sequence can exceed the memory capacity of a single accelerator, and the pressure grows with concurrency.

    Mitigation approaches include paged KV cache management.