Mixture of Experts LLMs: Principles, Training Costs, and Engineering Practices
This article explains how Mixture of Experts (MoE) large language models work, including gated routing, sparse activation, and load balancing. It also covers the difference between total and active parameters, how to estimate training costs, key practices for pretraining and inference deployment, and the factors to consider in model evaluation and selection.
1. Why Mixture of Experts Architectures Are Needed
In a dense model, every layer uses all of its parameters in each forward pass. As the parameter count grows, the compute per token rises, and both training and inference costs increase with it. Model capability is clearly correlated with scale, but simply adding parameters quickly exceeds the limits of available compute and GPU memory.
Mixture of Experts (MoE) offers a more economical path. It splits the feed-forward network into multiple parallel expert sub-networks. A gating network, called the router, then selects a small number of experts for each token. The total parameter count can therefore be very large, while each token passes through only a fraction of those parameters. This approach is called sparse activation, and it is the starting point for understanding the advantages and costs of MoE.
2. Core Mechanism: Gated Routing and Sparse Activation
A typical MoE layer consists of three components:
- Expert networks: feed-forward networks, usually with identical structures, where each expert has its own independent parameters.
- Gating network: a linear layer followed by a normalization function that outputs a score for each expert.
- Combination module: a weighted sum of the selected experts’ outputs, using their weights.
Routing mostly uses a Top-k strategy. It keeps only the k experts with the highest scores, and the rest do not take part in computing the current token. k is usually 1 or 2, which is a small value. The following pseudocode illustrates the process:
function moe_layer(x, experts, gate_weight, k):scores = softmax(x * gate_weight) # Score for each experttopk_idx, topk_w = select_topk(scores, k) # Select the k experts with the highest scorestopk_w = topk_w / sum(topk_w) # Normalize the selected weightsoutput = zeros_like(x)for i in range(k):output += topk_w[i] * experts[topk_idx[i]](x)return output
A smaller k saves compute. A larger k gives each token more expressive capacity but increases compute. Choosing k requires balancing quality against cost.
Load Balancing
If routing consistently favors a few experts, two problems arise. First, some experts become overloaded and turn into bottlenecks during training and inference. Second, other experts receive almost no training samples, so their parameters are underused. Common engineering approaches include:
- Adding an auxiliary balancing term to the loss function to penalize load differences among experts.
- Setting a capacity limit for each expert, with tokens beyond the limit routed to a second-best expert or skipped.
- Monitoring the hit ratio of each expert during training to detect signs of routing collapse early.
3. Total Parameters Versus Active Parameters
When evaluating an MoE model, distinguish between two metrics. Total parameters determine model capacity and storage requirements. Active parameters determine the compute per token.
Suppose a model has 600 billion total parameters and activates 37 billion parameters per token. The activation ratio is about:
37B / 600B ≈ 6.2%
This ratio applies only to the expert portion. Attention layers, embedding layers, and other modules are usually dense, and every token passes through them. The actual activation ratio is therefore slightly higher than this estimate.
Storage requirements still depend on total parameters. If weights are stored in half precision at 2 bytes per parameter, 600 billion parameters need about:
600B × 2 bytes = 1.2 TB
This figure excludes optimizer states, KV cache, and activation values. When planning hardware, estimate weight storage, compute throughput, and communication overhead separately. Do not look only at active parameters.
4. Estimating Training Cost
The basic unit of training cost is the GPU-hour, calculated as follows:
gpu_hours = num_gpus * wall_clock_hourstraining_cost = gpu_hours * price_per_gpu_hour
Consider a hypothetical scenario: training on 2,048 accelerator cards consumes 2,788 thousand GPU-hours, or 2,788,000 GPU-hours in total. The average wall-clock time per card is:
2,788,000 ÷ 2,048 ≈ 1,361 hours ≈ 56.7 days
Training compute can also be estimated with a common approximation: total floating-point operations ≈ 6 × N × D, where N is the number of parameters actually used per token and D is the number of training tokens. With N = 37 billion and D = 15 trillion, the training compute is about:
6 × 3.7×10¹⁰ × 1.5×10¹³ ≈ 3.3×10²⁴ floating-point operations
Publicly reported training costs often include only the final formal training run. Preliminary small-scale experiments, ablation studies, data engineering, and R&D staffing are usually excluded. When comparing costs across models, confirm that they use the same accounting scope.
5. Key Stages of Pretraining
Pretraining quality depends heavily on engineering details. Five stages matter most.
Data preparation. Data must be deduplicated, filtered for quality, and screened for harmful content. The mix of languages, disciplines, and text types directly affects model capability. The share of structured corpora such as mathematics and code noticeably affects performance on reasoning tasks.
Training stability. Large-scale training often shows sudden loss spikes. Common remedies include learning-rate warmup followed by decay, gradient clipping, and checking gradient norms for anomalies at key points. Mixed-precision training reduces memory use but requires loss scaling to prevent numerical underflow.
Parallelism strategy. When a single device cannot hold the full model, multiple parallelism methods must be combined. Data parallelism replicates the model and splits the data. Tensor parallelism splits the matrix operations within a layer. Pipeline parallelism assigns different layers to different devices. Expert parallelism places different experts on different devices. MoE models also need to handle communication between experts, and communication efficiency often determines training throughput.
Checkpointing and fault tolerance. Training runs are long, and hardware failures are unavoidable. Save checkpoints at fixed step intervals and keep several historical versions. After a failure, resume from the most recent checkpoint instead of starting over. Saving checkpoints also consumes storage bandwidth, so the frequency needs to be controlled.
Context length extension. Training on long sequences significantly increases compute and memory use. A common approach is to complete most training on shorter sequences, then increase the sequence length in stages and adjust the position encoding parameters to match. Evaluate long-context task performance separately at each stage.
6. Inference Deployment Practices
The core metrics for inference are time to first token, throughput per unit time, and cost per token.
Memory planning. GPU memory mainly consists of three parts: model weights, KV cache, and intermediate activations. The KV cache grows linearly with concurrency and context length. In long-context scenarios, it often becomes the bottleneck before the weights do.
Communication overhead in expert parallelism. When deploying an MoE model across multiple devices, each token must be sent to the devices hosting its selected experts, and the results must be gathered back after computation. The communication volume depends on batch size and k. Optimization approaches include sensible expert placement, overlapping communication with computation, and limiting the number of devices each token can access.
Batching and scheduling. Dynamic batching combines requests that arrive at different times to improve hardware utilization. However, overly large batches increase queuing latency, so set an upper limit based on the latency requirements of the application.
Quantization. Reducing weights from half precision to lower-bit formats can significantly cut memory use and bandwidth pressure. After quantization, re-evaluate accuracy on the target tasks, especially mathematical reasoning and code generation, which are sensitive to numerical error.
Monitoring. After launch, continuously track P50 and P99 latency, tokens generated per second, error rate, and the load distribution across experts. A persistent skew in load distribution usually means routing needs adjustment or the model needs recalibration.
7. Evaluation and Selection Guidance
When evaluating large models, a single leaderboard score is not enough to support a decision. Break the evaluation down by the following dimensions:
- Task dimensions: mathematical reasoning, code generation, Chinese language comprehension
