Architecture and Training Engineering Practices for Ultra-Large Sparse MoE Models
This article explores the engineering practices and architectural considerations for training ultra-large sparse Mixture of Experts (MoE) models. It covers the decoupling of parameter scale and compute, sparse expert routing mechanisms, attention bottlenecks in long-context scenarios, training stability in deep networks, native multimodal training routes, critical training infrastructure components, and deployment strategies following weight release.
1. Decoupling Parameter Scale and Compute
The scale of model parameters continues to grow, but each token does not need to utilize all parameters. Dense models use all parameters during forward computation. Sparse Mixture of Experts (MoE) models split the feed-forward network into a large number of expert sub-networks, where a router selects a few experts for each token to participate in the computation.
Here, two concepts need to be distinguished. The total parameter count determines the model’s knowledge capacity and weight storage cost. The activated parameter count determines the computational load for a single token. Taking forward computation as an example, the floating-point operations (FLOPs) for a single token can be approximated as 2 multiplied by the number of activated parameters. Assuming a total parameter count of 1 trillion and 32 billion activated parameters per token, the forward computation for a single token is about 6.4×10^10 FLOPs, which is far lower than that of a dense model with the same total parameter count.
This decoupling allows teams to expand model capacity within a limited compute budget. The trade-off is that memory usage increases with the total number of parameters, and the communication cost between experts requires separate planning.
2. Basic Mechanisms of Sparse Expert Routing
The router is typically a linear layer that maps hidden states to a score for each expert. The standard practice is to apply softmax normalization to the scores, select the top-k experts with the highest scores, and then re-normalize these k weights. Below is a schematic implementation that does not rely on any third-party libraries:
import mathdef softmax(xs):m = max(xs)exps = [math.exp(x - m) for x in xs]s = sum(exps)return [e / s for e in exps]def topk_route(logits, k):probs = softmax(logits)ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)[:k]total = sum(probs[i] for i in ranked)return [(i, probs[i] / total) for i in ranked]logits = [0.1, 2.3, -0.5, 1.7, 0.0, 0.9]print(topk_route(logits, k=2))# Output is approximately [(1, 0.65), (3, 0.35)]
In actual training, routing design must also address three issues:
- Load Balancing: If a few experts are consistently selected, other experts will not receive enough training, wasting model capacity. An auxiliary loss is usually added during training to encourage an even distribution of tokens across experts.
- Expert Capacity: There is an upper limit to the number of tokens an expert can process in a single step. Tokens exceeding this limit must be dropped or routed through other paths, which affects training stability and performance.
- Inference Communication: When experts are distributed across multiple accelerator cards, each token must be sent to the device hosting the corresponding expert, and the results must be retrieved. This all-to-all communication is often one of the primary sources of inference latency.
3. Attention Bottlenecks in Long-Context Scenarios
The computational complexity of standard self-attention is proportional to the square of the sequence length. During inference, the memory footprint of the Key-Value (KV) Cache is proportional to the sequence length. The cache size can be estimated using the following formula:
Cache Bytes = 2 × Number of Layers × Number of KV Heads × Head Dimension × Sequence Length × Bytes per Element
Assuming a model has 60 layers, 8 KV heads, a head dimension of 128, and a sequence length of 128K, using 16-bit floating-point storage, the KV cache for a single sequence is approximately 32 GB (decimal). As concurrent requests increase, this number scales linearly and quickly exceeds single-card memory limits.
To address this issue, common industry practices include the following:
- Linear Attention: Rewriting attention computation into a recursive form with a fixed state size, where computation grows linearly with sequence length.
- Hybrid Architectures: Most layers use linear or window-based attention, with a full attention layer retained every few layers for precise retrieval.
- KV Head Sharing and Compression: Reducing the storage per token in the cache through grouped-query attention or low-rank projection.
The main trade-off in hybrid architectures is that the exact recall capability of linear layers is weaker than that of full attention. Therefore, the ratio and placement of full attention layers must be determined empirically through long-text retrieval tasks, rather than relying solely on theoretical complexity.
4. Training Stability in Deep Networks
As networks grow deeper, signal variance along the residual path is more likely to accumulate with depth, leading to amplified activation values, unstable gradients, and loss spikes during training. Common engineering countermeasures include:
- Normalization Position: Using pre-normalization to keep the input of each sublayer within a stable numerical range.
- Residual Scaling: Multiplying the sublayer output by a depth-dependent coefficient to control the growth rate of residual accumulation.
- Learning Rate Warmup and Gradient Clipping: Slowly increasing the learning rate during the initial training phase and limiting the per-step gradient norm.
- Adjusting Residual Aggregation: Instead of simply adding the outputs of all historical layers, applying learnable weights to the contributions of different layers to make deep representations more controllable.
Monitoring this stability requires attention to three types of metrics: global gradient norm, activation variance distribution across layers, and the frequency of loss spikes. When anomalies occur, first locate the specific layer, and then decide whether to adjust the initialization, learning rate, or normalization configuration.
5. Training Routes for Native Multimodal and Vision Encoders
There are two common routes for multimodal large models. The first connects a pre-trained vision encoder to the front of the language model, followed by alignment training using image-text data. This approach has lower costs, but the degree of matching between visual representation and language objectives depends on the data quality during the alignment phase. The second route trains the vision encoder and the language model from scratch under a unified objective, where the visual representation directly serves next-token prediction.
The advantage of the second route is the consistency between the representation and the language modeling objective. The disadvantage is the need for a massive amount of high-quality interleaved image-text data, and continuous monitoring during training to ensure the visual representation does not degrade. To determine if training is stable, periodic small-scale probing evaluations can be conducted on downstream tasks such as image classification, image-text retrieval, and visual question answering.
6. Key Aspects of Training Infrastructure
The training efficiency of ultra-large sparse models depends heavily on the infrastructure. The following components require dedicated design:
- Expert Parallelism: Placing different experts on different devices, combined with data parallelism and pipeline parallelism to form multi-dimensional partitioning.
- Communication-Computation Overlap: Executing non-dependent computations in advance while all-to-all communication between experts is underway to hide communication latency.
- Long-Sequence Operator Optimization: Fusing and tiling core operators related to attention and routing to reduce memory read/write operations.
- Fault Tolerance and Checkpointing: Large-scale training runs for long durations, requiring frequent incremental checkpointing and automatic fault recovery mechanisms.
- Agent Training Environments: When models are used for tool calling or multi-step tasks, reproducible sandbox environments, clear reward definitions, timeout control, and resource isolation are necessary; otherwise, training signals will be disrupted by environmental fluctuations.
7. Deployment and Secondary Development Following Weight Release
After weights are released, teams typically need to complete the following steps:
- Verify the License: Confirm commercial usage rights, redistribution conditions, and constraints on derivative models.
- Verify File Integrity: Compare the downloaded files against officially released hash values (e.g., SHA256) to prevent file corruption or tampering.
- Estimate VRAM: Weight memory can be estimated by multiplying the parameter count by the bytes per parameter.
def weight_memory_gb(params_billion, bits_per_param):bytes_total = params_billion * 1e9 * bits_per_param / 8return bytes_total / 1e9for bits in (16, 8, 4):print(bits, "bit:", weight_memory_gb(1000, bits), "GB")# 16 bit: 2000.0 GB# 8 bit: 1000.0 GB# 4 bit: 500.0 GB
The results above include only the weights. Actual deployment also requires reserving memory for the KV cache, activations, and runtime overhead, typically requiring an additional proportional margin.
- Select an Inference Solution: Determine the parallelism strategy, batching method, and whether to use quantization based on hardware specifications. Quantization incurs precision loss, so performance before and after quantization should be compared on the target tasks.
- Establish Baseline Evaluation: Construct an evaluation set using internal business data, covering scenarios such as long-text retrieval, code generation, and multi-step reasoning, to determine whether to proceed to the next phase.
