Skip to content
SurogateSurogateDocs
↑↓ to move↵ to openesc to close

Mixture-of-Experts (MoE) Models

You 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 models:

ModelArchitectureExpertsActive (top-k)
Qwen3-MoE-30B-A3Bqwen3_moe1288
GPT-OSS-20Bgpt_oss1284
Nemotron-H (MoE layers)nemotron_h644

To pre-train an MoE model from scratch, run the surogate pt command with an MoE model preset:

yaml
# pt-moe-config.yaml
model: Qwen3-MoE-30B-A3B # Or path to model
model_type: qwen3_moe
# Pre-training specific settings
sequence_len: 4096
per_device_train_batch_size: 1
gradient_accumulation_steps: 16
# Dataset for pre-training
datasets:
- path: "HuggingFaceFW/fineweb-edu"
type: text
text_field: text

The router makes MoE fine-tuning need more care than a dense model. There are three approaches:

Train all model weights, including the experts and the router:

yaml
# moe-fft.yaml
model: ./my-moe-model
model_type: qwen3_moe
output_dir: ./output-moe-fft
lora: false # Disable LoRA for full fine-tuning
# Critical: Use lower learning rate than dense models
learning_rate: 1e-4
warmup_ratio: 0.15
max_grad_norm: 0.5
weight_decay: 0.01
# MoE models don't support CUDA graphs due to dynamic routing
use_cuda_graphs: false
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
gpus: 4

Train LoRA adapters on the expert weights and keep the router frozen (see LoRA settings):

yaml
# moe-lora.yaml
model: ./my-moe-model
model_type: qwen3_moe
output_dir: ./output-moe-lora
merge_adapter: true
lora: true
lora_rank: 16
lora_alpha: 32
lora_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-4
warmup_ratio: 0.15
max_grad_norm: 0.5
use_cuda_graphs: false

You can fine-tune MoE models with QLoRA to use less memory. All QLoRA variants (BnB, FP8, FP4) work:

yaml
# moe-qlora-bnb.yaml
model: Qwen/Qwen3-30B-A3B
model_type: qwen3_moe
output_dir: ./output-moe-qlora
lora: true
lora_rank: 16
lora_alpha: 32
# Enable BitsAndBytes NF4 quantization
qlora_bnb: true
qlora_bnb_block_size: 64
qlora_bnb_double_quant: true
# Optional: Router training works with QLoRA too
train_router: true

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):

yaml
# MoE router loss coefficients
router_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:

ScenarioAux Loss CoefZ-Loss CoefReasoning
Default/pre-trained modelsUse model defaultUse model defaultWell-tuned for the architecture
Router collapse detectedIncrease 2-5xIncrease 2-5xStronger regularization to stabilize routing
Over-uniform routingDecrease 2-5xKeep defaultAllow more routing specialization
Large batch trainingKeep defaultKeep defaultUsually stable
Small batch trainingIncrease 2xIncrease 2xMore regularization helps with noisy gradients

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:

ParameterRecommended ValueNotes
learning_rate#1e-4 to 2e-4Standard LoRA learning rate
warmup_ratio#0.03-0.10Standard warmup
max_grad_norm#1.0Standard clipping
train_router#falseRouter is already trained

Fine-tuning (SFT/LoRA):

ScenarioMinimumRecommendedNotes
Task-specific (e.g., code, math)5,00050,000–100,0001–3 epochs; diminishing returns beyond ~100k for narrow tasks
General instruction tuning50,000200,000–500,0001 epoch typically sufficient; mix diverse sources
MoE with router training100,000300,000+Router needs more signal to converge; extend warmup to 0.15

Pretraining and continual pretraining:

ScenarioMinimumRecommendedNotes
Domain adaptation500M tokens5B–20B tokensLess than this risks catastrophic forgetting
Full pretraining from scratch1T tokens5T–20T tokensScale data with model size; follow Chinchilla ratios
Vocabulary / architecture extension50B tokens200B–500B tokensEnough to stabilize new parameters before mixing

Rules of thumb:

  • When memory is tight, prefer more short sequences over fewer long ones. truncation_strategy: split keeps 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_utilization early in training. Below 0.5 after warmup suggests the dataset is too narrow or router_aux_loss_coef needs to go up.

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.

MetricDescriptionHealthy Range
aux_loss#Load balancing auxiliary loss (sum across layers)0.001 - 0.1
z_loss#Router z-loss for logit regularization0.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.

MoE metrics are logged automatically for MoE models. To send them to an external backend, set report_to (see Logging & reporting):

yaml
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)

The fraction of experts that receive tokens each step. Where to find it:

  • Console: not shown inline
  • JSON logs: the moe_expert_utilization field in step logs
  • wandb/Aim: train/moe_expert_utilization
ValueInterpretation
0.9 - 1.0Excellent - all experts contributing
0.7 - 0.9Good - most experts active
0.5 - 0.7Warning - some experts underutilized
< 0.5Critical - possible router collapse

How evenly tokens spread across active experts, computed as max_expert_tokens / mean_expert_tokens. Where to find it:

  • Console: the imbal field on the step line
  • JSON logs: the moe_load_imbalance field in step logs
  • wandb/Aim: train/moe_load_imbalance

Expected ranges per architecture (pre-trained models with a trained router):

ArchitectureExpertsTop-kExpected ImbalanceWarning Threshold
Small MoE (e.g., 8x2)821.5 - 3.0> 5.0
Nemotron-H MoE layers6443.0 - 6.0> 10.0
GPT-OSS (128 experts, top-4)12844.0 - 6.0> 10.0
Qwen3-MoE-30B-A3B (128 experts, top-8)12888.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

The load-balancing loss that pushes for uniform expert utilization. Where to find it:

  • Console: the aux field on the step line
  • JSON logs: the moe_aux_loss field in step logs
  • wandb/Aim: train/moe_aux_loss
  • Config: adjust its strength with router_aux_loss_coef (see Configuring MoE Loss Coefficients)
ValueInterpretation
< 0.01Very low - router may be too uniform
0.01 - 0.1Normal range
0.1 - 1.0Elevated - router learning to balance
> 1.0High - significant load imbalance

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_loss field in step logs
  • wandb/Aim: train/moe_z_loss
  • Config: adjust its strength with router_z_loss_coef (see Configuring MoE Loss Coefficients)
ValueInterpretation
< 0.001Normal
0.001 - 0.01Slightly elevated
> 0.01Warning - router logits may be unstable
> 0.1Critical - possible routing collapse

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.

Router collapse is when the router stops spreading tokens across experts:

SymptomMetric Indicator
All tokens to few expertsexpert_utilization < 0.2
Severe load imbalanceload_imbalance > 2x the expected range for architecture
Router instabilityz_loss > 0.1 or spiking
Training divergenceaux_loss > 2.0

To recover:

  1. Lower the learning rate by 2-5x.
  2. Raise the warmup ratio to 0.15-0.20.
  3. Turn on gradient clipping with max_grad_norm: 0.5.
  4. Turn on router training with train_router: true.
  5. Raise the loss coefficients: set router_aux_loss_coef: 0.05 and router_z_loss_coef: 0.01 for stronger regularization.
  6. Check the batch size. Very small batches can make routing unstable.

MoE models have more parameters than dense models but similar active compute:

ModelTotal ParamsActive ParamsVRAM (BF16)VRAM (QLoRA BnB)
Qwen3-0.6B (dense)0.6B0.6B~2GB~1GB
Qwen3-0.6B 8x2 MoE~2.4B~0.6B~6GB~2GB
Qwen3-MoE-30B-A3B30B3B~60GB~12GB

To reduce memory:

  • Use QLoRA (qlora_bnb: true or qlora_fp8: true) for large models.
  • Use Expert Parallelism (ep_size: N) to shard experts across GPUs, so each GPU holds 1/N of the experts.
  • Set qlora_offload_experts: true to offload inactive expert weights to CPU.
  • Lower per_device_train_batch_size and raise gradient_accumulation_steps.
  • Keep recompute on (the default; see Recomputation).

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.

yaml
gpus: 4
ep_size: 2 # 2-way expert parallelism
ep_load_balance_threshold: 1.3 # LLEP activation threshold (default)
ParameterTypeDefaultDescription
ep_size#int1Number of GPUs in each expert-parallel group. Must divide gpus. Each GPU holds num_experts / ep_size local experts.
ep_load_balance_threshold#float1.3Imbalance 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#int16LLEP 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_size must evenly divide gpus
  • num_experts must be evenly divisible by ep_size
  • ep_size = 1 (default) disables EP and uses pure data parallelism

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 / 2 local 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)

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):

  1. At each layer, expert token counts are measured across the EP group
  2. If max_gpu_load / mean_gpu_load exceeds ep_load_balance_threshold, the LPT (Longest Processing Time) scheduler activates
  3. Overloaded experts are temporarily transferred to underloaded GPUs along with their weights
  4. 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:

ValueBehavior
1.0Always active — LPT scheduling runs every layer
1.3Default — activates only when significant imbalance is detected
2.0+Rarely activates — only under extreme imbalance

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:

yaml
model: Qwen/Qwen3-30B-A3B
model_type: qwen3_moe
gpus: 4
ep_size: 2
lora: true
lora_rank: 16
lora_alpha: 32
qlora_fp8: true
qlora_offload_experts: true
ep_load_balance_threshold: 1.0
lora_target_modules:
- q_proj
- k_proj
- v_proj
- o_proj
- gate_proj
- up_proj
- down_proj
ScenarioRecommendation
Model fits on one GPU with QLoRAEP not needed (ep_size: 1)
Many GPUs, want faster throughputUse EP to parallelize expert compute
Expert weights too large for one GPU even with QLoRAUse EP to shard experts across GPUs
High routing imbalanceUse EP with ep_load_balance_threshold: 1.0
  1. CUDA graphs: MoE models can’t use CUDA graphs, because expert routing is dynamic. Always set use_cuda_graphs: false.

  2. ZeRO-3: you can shard MoE expert weights with ZeRO-3, but routing overhead grows with world size.

  3. EP checkpoints: to resume a checkpoint saved with EP, use the same ep_size.

yaml
model: Qwen/Qwen3-30B-A3B
model_type: qwen3_moe
output_dir: ./output-pt
per_device_train_batch_size: 2
gradient_accumulation_steps: 8
gpus: 8
use_cuda_graphs: false
sample_packing: true
sequence_len: 4096
truncation_strategy: split
use_chat_template: false
loss_scale: all
max_steps: 10000
eval_steps: 500
save_steps: 1000
learning_rate: 3e-4
lr_scheduler_type: cosine
warmup_ratio: 0.05
max_grad_norm: 1.0
weight_decay: 0.1
recipe: fp8-hybrid
optimizer: adamw_8bit
lora: false
# Expert parallelism across all 8 GPUs
ep_size: 8
ep_load_balance_threshold: 1.0
router_aux_loss_coef: 0.001
router_z_loss_coef: 0.0001
dataloader_num_workers: 4
datasets:
- path: "HuggingFaceFW/fineweb-edu"
type: text
text_field: text
split: train
yaml
model: Qwen/Qwen3-30B-A3B
model_type: qwen3_moe
output_dir: ./output-30b
per_device_train_batch_size: 1
gradient_accumulation_steps: 16
gpus: 4
use_cuda_graphs: false
sequence_len: 2048
num_epochs: 3
learning_rate: 2e-4
warmup_ratio: 0.03
max_grad_norm: 1.0
lora: true
lora_rank: 32
lora_alpha: 64
# QLoRA for memory efficiency
qlora_bnb: true
qlora_bnb_block_size: 64
qlora_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: auto

To confirm the router is training when you set train_router: true:

  1. Check the adapter checkpoint. The exported adapter should contain router weights:

    python
    from safetensors.torch import load_file
    weights = 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)
  2. Watch the gradient norms. Router gradients add to the total gradient norm during training, so you should see non-zero gradients being clipped.

  3. 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.