Mixture-of-Experts (MoE) Models
EngineSurogate EngineYou can pre-train and fine-tune Mixture-of-Experts (MoE) models with Surogate. An MoE model replaces the dense feed-forward network (FFN) with several “expert” FFNs, and a learned router picks which experts process each token. That lets a model grow its parameter count without a matching growth in compute.
Supported MoE Models
Section titled “Supported MoE Models”Supported models:
| Model | Architecture | Experts | Active (top-k) |
|---|---|---|---|
| Qwen3-MoE-30B-A3B | qwen3_moe | 128 | 8 |
| GPT-OSS-20B | gpt_oss | 128 | 4 |
| Nemotron-H (MoE layers) | nemotron_h | 64 | 4 |
Pre-training from Scratch
Section titled “Pre-training from Scratch”To pre-train an MoE model from scratch, run the surogate pt command with an MoE model preset:
# pt-moe-config.yamlmodel: Qwen3-MoE-30B-A3B # Or path to modelmodel_type: qwen3_moe
# Pre-training specific settingssequence_len: 4096per_device_train_batch_size: 1gradient_accumulation_steps: 16
# Dataset for pre-trainingdatasets: - path: "HuggingFaceFW/fineweb-edu" type: text text_field: textFine-Tuning MoE Models
Section titled “Fine-Tuning MoE Models”The router makes MoE fine-tuning need more care than a dense model. There are three approaches:
1. Full Fine-Tuning (FFT)
Section titled “1. Full Fine-Tuning (FFT)”Train all model weights, including the experts and the router:
# moe-fft.yamlmodel: ./my-moe-modelmodel_type: qwen3_moeoutput_dir: ./output-moe-fft
lora: false # Disable LoRA for full fine-tuning
# Critical: Use lower learning rate than dense modelslearning_rate: 1e-4warmup_ratio: 0.15max_grad_norm: 0.5weight_decay: 0.01
# MoE models don't support CUDA graphs due to dynamic routinguse_cuda_graphs: false
per_device_train_batch_size: 1gradient_accumulation_steps: 8gpus: 42. LoRA Fine-Tuning (Experts Only)
Section titled “2. LoRA Fine-Tuning (Experts Only)”Train LoRA adapters on the expert weights and keep the router frozen (see LoRA settings):
# moe-lora.yamlmodel: ./my-moe-modelmodel_type: qwen3_moeoutput_dir: ./output-moe-loramerge_adapter: true
lora: truelora_rank: 16lora_alpha: 32lora_dtype: bf16 # fp32: FP32 masters, expert LoRA gradients accumulated in FP32 (more memory)
# Target expert projections (applied per-expert)lora_target_modules: - q_proj - k_proj - v_proj - o_proj - gate_proj # Expert gate projection - up_proj # Expert up projection - down_proj # Expert down projection
learning_rate: 1e-4warmup_ratio: 0.15max_grad_norm: 0.5use_cuda_graphs: falseQLoRA for MoE Models
Section titled “QLoRA for MoE Models”You can fine-tune MoE models with QLoRA to use less memory. All QLoRA variants (BnB, FP8, FP4) work:
# moe-qlora-bnb.yamlmodel: Qwen/Qwen3-30B-A3Bmodel_type: qwen3_moeoutput_dir: ./output-moe-qlora
lora: truelora_rank: 16lora_alpha: 32
# Enable BitsAndBytes NF4 quantizationqlora_bnb: trueqlora_bnb_block_size: 64qlora_bnb_double_quant: true
# Optional: Router training works with QLoRA tootrain_router: trueConfiguring MoE Loss Coefficients
Section titled “Configuring MoE Loss Coefficients”MoE training adds two loss terms that regularize the router:
- Auxiliary loss (
router_aux_loss_coef) pushes tokens to spread evenly across experts. Higher values push harder for uniform load. - Z-loss (
router_z_loss_coef) keeps router logits from growing too large, which can make routing unstable.
Set both in the training YAML (see MoE settings):
# MoE router loss coefficientsrouter_aux_loss_coef: 0.01 # Load balancing (default: from model config, typically 0.001-0.01)router_z_loss_coef: 0.001 # Logit regularization (default: from model config, typically 0.001)When to adjust them:
| Scenario | Aux Loss Coef | Z-Loss Coef | Reasoning |
|---|---|---|---|
| Default/pre-trained models | Use model default | Use model default | Well-tuned for the architecture |
| Router collapse detected | Increase 2-5x | Increase 2-5x | Stronger regularization to stabilize routing |
| Over-uniform routing | Decrease 2-5x | Keep default | Allow more routing specialization |
| Large batch training | Keep default | Keep default | Usually stable |
| Small batch training | Increase 2x | Increase 2x | More regularization helps with noisy gradients |
Hyperparameter Recommendations
Section titled “Hyperparameter Recommendations”For Pre-trained MoE Models (e.g., Qwen3-MoE-30B-A3B)
Section titled “For Pre-trained MoE Models (e.g., Qwen3-MoE-30B-A3B)”A pre-trained MoE model already has a well-trained router, so standard LoRA hyperparameters work:
| Parameter | Recommended Value | Notes |
|---|---|---|
learning_rate# | 1e-4 to 2e-4 | Standard LoRA learning rate |
warmup_ratio# | 0.03-0.10 | Standard warmup |
max_grad_norm# | 1.0 | Standard clipping |
train_router# | false | Router is already trained |
Dataset Size Guidelines
Section titled “Dataset Size Guidelines”Fine-tuning (SFT/LoRA):
| Scenario | Minimum | Recommended | Notes |
|---|---|---|---|
| Task-specific (e.g., code, math) | 5,000 | 50,000–100,000 | 1–3 epochs; diminishing returns beyond ~100k for narrow tasks |
| General instruction tuning | 50,000 | 200,000–500,000 | 1 epoch typically sufficient; mix diverse sources |
| MoE with router training | 100,000 | 300,000+ | Router needs more signal to converge; extend warmup to 0.15 |
Pretraining and continual pretraining:
| Scenario | Minimum | Recommended | Notes |
|---|---|---|---|
| Domain adaptation | 500M tokens | 5B–20B tokens | Less than this risks catastrophic forgetting |
| Full pretraining from scratch | 1T tokens | 5T–20T tokens | Scale data with model size; follow Chinchilla ratios |
| Vocabulary / architecture extension | 50B tokens | 200B–500B tokens | Enough to stabilize new parameters before mixing |
Rules of thumb:
- When memory is tight, prefer more short sequences over fewer long ones.
truncation_strategy: splitkeeps all tokens in pretraining (see Chat template settings). - Make sure your dataset is varied enough to keep all experts active. A narrow corpus can cause router collapse even with plenty of tokens.
- Watch
expert_utilizationearly in training. Below 0.5 after warmup suggests the dataset is too narrow orrouter_aux_loss_coefneeds to go up.
Monitoring MoE Training
Section titled “Monitoring MoE Training”Surogate logs MoE metrics that show router health and expert utilization. They are logged automatically for every MoE model, and you can read them in the console, the JSON logs, or an external backend (wandb/Aim). Training metrics lists all of them.
MoE-Specific Metrics
Section titled “MoE-Specific Metrics”| Metric | Description | Healthy Range |
|---|---|---|
aux_loss# | Load balancing auxiliary loss (sum across layers) | 0.001 - 0.1 |
z_loss# | Router z-loss for logit regularization | 0.0001 - 0.01 |
expert_utilization# | Fraction of experts receiving tokens (0-1) | 0.7 - 1.0 |
load_imbalance# | Ratio of max to mean expert token counts (1.0 = perfect) | Depends on architecture* |
*The healthy load imbalance range depends on the number of experts. See Load Imbalance for each architecture.
Enabling MoE Metrics
Section titled “Enabling MoE Metrics”MoE metrics are logged automatically for MoE models. To send them to an external backend, set report_to (see Logging & reporting):
report_to: wandb # or [wandb, aim]They appear as:
- wandb/Aim:
train/moe_aux_loss,train/moe_z_loss,train/moe_load_imbalance,train/moe_expert_utilization(logged with each training step)
Interpreting the Metrics
Section titled “Interpreting the Metrics”Expert Utilization
Section titled “Expert Utilization”The fraction of experts that receive tokens each step. Where to find it:
- Console: not shown inline
- JSON logs: the
moe_expert_utilizationfield in step logs - wandb/Aim:
train/moe_expert_utilization
| Value | Interpretation |
|---|---|
| 0.9 - 1.0 | Excellent - all experts contributing |
| 0.7 - 0.9 | Good - most experts active |
| 0.5 - 0.7 | Warning - some experts underutilized |
| < 0.5 | Critical - possible router collapse |
Load Imbalance
Section titled “Load Imbalance”How evenly tokens spread across active experts, computed as max_expert_tokens / mean_expert_tokens. Where to find it:
- Console: the
imbalfield on the step line - JSON logs: the
moe_load_imbalancefield in step logs - wandb/Aim:
train/moe_load_imbalance
Expected ranges per architecture (pre-trained models with a trained router):
| Architecture | Experts | Top-k | Expected Imbalance | Warning Threshold |
|---|---|---|---|---|
| Small MoE (e.g., 8x2) | 8 | 2 | 1.5 - 3.0 | > 5.0 |
| Nemotron-H MoE layers | 64 | 4 | 3.0 - 6.0 | > 10.0 |
| GPT-OSS (128 experts, top-4) | 128 | 4 | 4.0 - 6.0 | > 10.0 |
| Qwen3-MoE-30B-A3B (128 experts, top-8) | 128 | 8 | 8.0 - 12.0 | > 20.0 |
Why large expert counts show high imbalance: the metric is the ratio of the single busiest expert to the average across all experts. With 128 experts and top-8 routing, each expert gets tokens * 8 / 128 = 6.25% of tokens on average. A trained router specializes, so popular experts may get 50-75% of tokens while many get very few. That is normal and does not mean the router has collapsed.
Watch the trend more than the absolute value. Look for:
- Sudden spikes in imbalance (a 2x+ increase within a few steps)
- Imbalance that only ever rises (the router concentrating on fewer experts over time)
- Imbalance together with low utilization (< 0.5), which means the router really has collapsed
Auxiliary Loss
Section titled “Auxiliary Loss”The load-balancing loss that pushes for uniform expert utilization. Where to find it:
- Console: the
auxfield on the step line - JSON logs: the
moe_aux_lossfield in step logs - wandb/Aim:
train/moe_aux_loss - Config: adjust its strength with
router_aux_loss_coef(see Configuring MoE Loss Coefficients)
| Value | Interpretation |
|---|---|
| < 0.01 | Very low - router may be too uniform |
| 0.01 - 0.1 | Normal range |
| 0.1 - 1.0 | Elevated - router learning to balance |
| > 1.0 | High - significant load imbalance |
Z-Loss
Section titled “Z-Loss”The regularization term that keeps router logits from getting too large. Where to find it:
- Console: not shown inline (check the JSON logs or an external backend)
- JSON logs: the
moe_z_lossfield in step logs - wandb/Aim:
train/moe_z_loss - Config: adjust its strength with
router_z_loss_coef(see Configuring MoE Loss Coefficients)
| Value | Interpretation |
|---|---|
| < 0.001 | Normal |
| 0.001 - 0.01 | Slightly elevated |
| > 0.01 | Warning - router logits may be unstable |
| > 0.1 | Critical - possible routing collapse |
Signs of Healthy Training
Section titled “Signs of Healthy Training”In a healthy MoE run:
- Loss goes down steadily, without sudden spikes.
- Gradient norm stays below 0.4 (or 1.0 with
max_grad_norm: 1.0). - Expert utilization stays above 0.7 and is stable or rising.
- Load imbalance is stable and within the expected range for the architecture (see Load Imbalance).
- Aux loss is falling, or stable in the 0.01-0.1 range.
Signs of Router Collapse
Section titled “Signs of Router Collapse”Router collapse is when the router stops spreading tokens across experts:
| Symptom | Metric Indicator |
|---|---|
| All tokens to few experts | expert_utilization < 0.2 |
| Severe load imbalance | load_imbalance > 2x the expected range for architecture |
| Router instability | z_loss > 0.1 or spiking |
| Training divergence | aux_loss > 2.0 |
To recover:
- Lower the learning rate by 2-5x.
- Raise the warmup ratio to 0.15-0.20.
- Turn on gradient clipping with
max_grad_norm: 0.5. - Turn on router training with
train_router: true. - Raise the loss coefficients: set
router_aux_loss_coef: 0.05androuter_z_loss_coef: 0.01for stronger regularization. - Check the batch size. Very small batches can make routing unstable.
Memory Considerations
Section titled “Memory Considerations”MoE models have more parameters than dense models but similar active compute:
| Model | Total Params | Active Params | VRAM (BF16) | VRAM (QLoRA BnB) |
|---|---|---|---|---|
| Qwen3-0.6B (dense) | 0.6B | 0.6B | ~2GB | ~1GB |
| Qwen3-0.6B 8x2 MoE | ~2.4B | ~0.6B | ~6GB | ~2GB |
| Qwen3-MoE-30B-A3B | 30B | 3B | ~60GB | ~12GB |
To reduce memory:
- Use QLoRA (
qlora_bnb: trueorqlora_fp8: true) for large models. - Use Expert Parallelism (
ep_size: N) to shard experts across GPUs, so each GPU holds1/Nof the experts. - Set
qlora_offload_experts: trueto offload inactive expert weights to CPU. - Lower
per_device_train_batch_sizeand raisegradient_accumulation_steps. - Keep
recomputeon (the default; see Recomputation).
Expert Parallelism (EP)
Section titled “Expert Parallelism (EP)”By default every GPU holds a full copy of all expert weights (data-parallel only). For a large MoE model with many experts, each GPU then has to fit every expert in memory, even though only a few experts are active per token.
Expert Parallelism spreads the experts across GPUs, so each GPU holds only num_experts / ep_size local experts. All-to-all communication sends tokens to the right GPU, the experts run in parallel, and the results come back. Each GPU needs less memory, and expert compute runs in parallel across GPUs.
Configuration
Section titled “Configuration”gpus: 4ep_size: 2 # 2-way expert parallelismep_load_balance_threshold: 1.3 # LLEP activation threshold (default)| Parameter | Type | Default | Description |
|---|---|---|---|
ep_size# | int | 1 | Number of GPUs in each expert-parallel group. Must divide gpus. Each GPU holds num_experts / ep_size local experts. |
ep_load_balance_threshold# | float | 1.3 | Imbalance ratio (max_gpu_load / mean_gpu_load) above which dynamic load balancing (LLEP) activates. Set to 1.0 for always-active load balancing. |
ep_plan_refresh_interval# | int | 16 | LLEP sticky plans: recompute the expert placement every N forward dispatches per layer. 1 = recompute every step. |
The full option list is under Expert parallelism (MoE) options.
Constraints:
ep_sizemust evenly dividegpusnum_expertsmust be evenly divisible byep_sizeep_size = 1(default) disables EP and uses pure data parallelism
How EP Works
Section titled “How EP Works”With gpus: 4 and ep_size: 2:
- EP groups: ranks {0, 1} and {2, 3} each form an expert-parallel group
- DP groups: ranks {0, 2} and {1, 3} each form a data-parallel group
- Each GPU holds
num_experts / 2local experts - Dense layer gradients are all-reduced across all 4 GPUs (global)
- Expert weight gradients are all-reduced across the DP group only (2 GPUs)
LLEP Load Balancing
Section titled “LLEP Load Balancing”MoE routing is uneven by nature: some experts get more tokens than others. Without load balancing, the GPU with the busiest experts becomes the bottleneck.
Least-Loaded EP (LLEP) moves work around when it detects imbalance (more in Adaptive Training):
- At each layer, expert token counts are measured across the EP group
- If
max_gpu_load / mean_gpu_loadexceedsep_load_balance_threshold, the LPT (Longest Processing Time) scheduler activates - Overloaded experts are temporarily transferred to underloaded GPUs along with their weights
- After computation, results and gradients are routed back to the native GPU
The expert placement plan is sticky. It is recomputed every ep_plan_refresh_interval forward dispatches per layer (default 16), not every step. Every placement is mathematically exact; routing counts only affect how well the load is balanced. A stable plan lets the runtime prefetch foreign expert weights one layer ahead in both the forward and backward pass, which hides the weight transfers behind compute. Routing drift is picked up at the next refresh. Set the interval to 1 to plan every step again.
LLEP works under cpu_training (see CPU-RAM centric training). Foreign expert weights are fetched straight from the shared pinned host masters, with no peer transfers for base weights. It balances VRAM as well as compute, so the rank that gets the most routing no longer builds up the largest working set.
LLEP turns on automatically when ep_size > 1. ep_load_balance_threshold sets how sensitive it is:
| Value | Behavior |
|---|---|
1.0 | Always active — LPT scheduling runs every layer |
1.3 | Default — activates only when significant imbalance is detected |
2.0+ | Rarely activates — only under extreme imbalance |
EP with QLoRA
Section titled “EP with QLoRA”EP works with all QLoRA variants. Combined with expert offloading (qlora_offload_experts: true), each GPU offloads only its local expert shard, which saves both GPU and CPU memory:
model: Qwen/Qwen3-30B-A3Bmodel_type: qwen3_moegpus: 4ep_size: 2
lora: truelora_rank: 16lora_alpha: 32
qlora_fp8: trueqlora_offload_experts: trueep_load_balance_threshold: 1.0
lora_target_modules: - q_proj - k_proj - v_proj - o_proj - gate_proj - up_proj - down_projWhen to Use EP
Section titled “When to Use EP”| Scenario | Recommendation |
|---|---|
| Model fits on one GPU with QLoRA | EP not needed (ep_size: 1) |
| Many GPUs, want faster throughput | Use EP to parallelize expert compute |
| Expert weights too large for one GPU even with QLoRA | Use EP to shard experts across GPUs |
| High routing imbalance | Use EP with ep_load_balance_threshold: 1.0 |
Limitations
Section titled “Limitations”-
CUDA graphs: MoE models can’t use CUDA graphs, because expert routing is dynamic. Always set
use_cuda_graphs: false. -
ZeRO-3: you can shard MoE expert weights with ZeRO-3, but routing overhead grows with world size.
-
EP checkpoints: to resume a checkpoint saved with EP, use the same
ep_size.
Example Configurations
Section titled “Example Configurations”MoE Pretraining
Section titled “MoE Pretraining”model: Qwen/Qwen3-30B-A3Bmodel_type: qwen3_moeoutput_dir: ./output-pt
per_device_train_batch_size: 2gradient_accumulation_steps: 8gpus: 8use_cuda_graphs: false
sample_packing: truesequence_len: 4096truncation_strategy: splituse_chat_template: falseloss_scale: all
max_steps: 10000eval_steps: 500save_steps: 1000
learning_rate: 3e-4lr_scheduler_type: cosinewarmup_ratio: 0.05max_grad_norm: 1.0weight_decay: 0.1
recipe: fp8-hybridoptimizer: adamw_8bitlora: false
# Expert parallelism across all 8 GPUsep_size: 8ep_load_balance_threshold: 1.0
router_aux_loss_coef: 0.001router_z_loss_coef: 0.0001
dataloader_num_workers: 4datasets: - path: "HuggingFaceFW/fineweb-edu" type: text text_field: text split: trainLarge MoE Model with QLoRA
Section titled “Large MoE Model with QLoRA”model: Qwen/Qwen3-30B-A3Bmodel_type: qwen3_moeoutput_dir: ./output-30b
per_device_train_batch_size: 1gradient_accumulation_steps: 16gpus: 4use_cuda_graphs: false
sequence_len: 2048num_epochs: 3
learning_rate: 2e-4warmup_ratio: 0.03max_grad_norm: 1.0
lora: truelora_rank: 32lora_alpha: 64
# QLoRA for memory efficiencyqlora_bnb: trueqlora_bnb_block_size: 64qlora_bnb_double_quant: true
lora_target_modules: - q_proj - k_proj - v_proj - o_proj - gate_proj - up_proj - down_proj
datasets: - path: "your-dataset" type: autoVerifying Router Training
Section titled “Verifying Router Training”To confirm the router is training when you set train_router: true:
-
Check the adapter checkpoint. The exported adapter should contain router weights:
python from safetensors.torch import load_fileweights = load_file("output/adapter_model.safetensors")router_keys = [k for k in weights.keys() if "mlp.gate" in k]print(f"Router weights in adapter: {len(router_keys)}")# Should show one per layer (e.g., 28 for 28-layer model) -
Watch the gradient norms. Router gradients add to the total gradient norm during training, so you should see non-zero gradients being clipped.
-
Compare before and after. Load the merged model and compare its router weights to the original’s. They should differ if the router was trained.
Next: Training metrics lists every MoE metric and log field, and Multi-GPU training covers the data-parallel side that EP runs alongside.