# Mixture-of-Experts (MoE) Models

Source: https://docs.surogate.ai/engine/guides/moe/

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

To pre-train an MoE model from scratch, run the [`surogate pt`](/engine/reference/cli/#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
```

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

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
```

### 2. LoRA Fine-Tuning (Experts Only)

Train LoRA adapters on the expert weights and keep the router frozen (see [LoRA settings](/engine/reference/config/#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
```

## QLoRA for MoE Models

You can fine-tune MoE models with [QLoRA](/engine/guides/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
```

## 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](/engine/reference/config/#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:

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

:::note
Values you set in the config override the model's default coefficients. Leave them out to use the model's own values.
:::

## Hyperparameter Recommendations

### 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

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: split` keeps all tokens in pretraining (see [Chat template settings](/engine/reference/config/#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.

## 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](/engine/guides/metrics/#moe-metrics) lists all of them.

### 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](#load-imbalance) for each architecture.

### Enabling MoE Metrics

MoE metrics are logged automatically for MoE models. To send them to an external backend, set `report_to` (see [Logging & reporting](/engine/reference/config/#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)

### Interpreting the Metrics

#### Expert Utilization

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`

| 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

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`

:::note[Important]
The expected load imbalance depends heavily on the number of experts and top-k. With more experts, the most popular expert naturally gets many more tokens than the average, even with a well-trained router, so no single threshold fits every architecture.
:::

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

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](#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

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](#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

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](#load-imbalance)).
- Aux loss is falling, or stable in the 0.01-0.1 range.

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

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.


## 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](/engine/guides/qlora/) (`qlora_bnb: true` or `qlora_fp8: true`) for large models.
- Use [Expert Parallelism](#expert-parallelism-ep) (`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](/engine/reference/config/#recomputation)).

## 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

```yaml
gpus: 4
ep_size: 2                       # 2-way expert parallelism
ep_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](/engine/reference/config/#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

### 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 / 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)

### 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](/engine/about/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](/engine/reference/config/#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

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
```

### 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

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](/engine/guides/multi-gpu/), but routing overhead grows with world size.

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

## Example Configurations

### MoE Pretraining

```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
```

### Large MoE Model with QLoRA

```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
```

## Verifying Router Training

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](/engine/guides/metrics/#moe-metrics) lists every MoE metric and log field, and [Multi-GPU training](/engine/guides/multi-gpu/) covers the data-parallel side that EP runs alongside.
