# Adaptive Training System

Source: https://docs.surogate.ai/engine/about/adaptive-training/

Surogate watches your training run as it happens and tells you what to fix when something goes wrong. It detects loss plateaus, gradient explosions, MoE routing collapse and wasted compute, and logs a concrete recommendation for each.

Most of the system is **always on** and needs no configuration. Three optional features each take a single flag to enable.

## Quick Start

To enable the full adaptive system, add these flags to your training YAML:

```yaml
# Optional features (always-on components need no config)
auto_lr_reduction: true   # Auto-fix loss spikes and gradient explosions
early_stop: true           # Stop when training converges or diverges
epoch_adjustment: true     # Scale epochs to Chinchilla-optimal token budget
```

Everything else (phase detection, plateau detection, gradient tracking, MoE monitoring and the cross-component advisor) runs automatically. The flags are also listed under [Training Diagnostics & Automation](/engine/reference/config/#training-diagnostics--automation) in the config reference.

## Training Advisor

The **TrainingAdvisor** sits at the center of the adaptive system. It combines signals from all the other components, so it can make recommendations that no single component could make on its own.

For example, LossGuard detects a loss spike and cuts the LR. If MoEMonitor shows routing collapse at the same time, though, the right fix is `router_aux_loss_coef`, and lowering the LR will not help. The TrainingAdvisor catches this case.

### Advisory Rules

The advisor runs 6 cross-signal checks on every training step:

#### Rule 1: Plateau with High LR

**Detects:** loss has plateaued and gradients are flat, but the LR is still high.

**What you'll see:**
```
[Advisor] Plateau with flat gradients at step 5000: loss stalled for 50 steps
while LR=2.00e-04 is still high. Consider reducing learning rate or adjusting schedule.
```

**What to do:** reduce `learning_rate` or switch to a schedule that decays faster.

#### Rule 2: Divergence from MoE Routing Collapse

**Detects:** training is diverging with rising gradients AND MoE routing is unhealthy.

**What you'll see:**
```
[Advisor] MoE routing collapse driving divergence at step 3200: loss is diverging
with rising gradients (trend=+25.00%) AND routing is unhealthy (balance=0.15,
utilization=40%). Fix routing first — increase router_aux_loss_coef rather than reducing LR.
```

**What to do:** increase `router_aux_loss_coef` (for example 0.01 → 0.05). Do NOT reduce the LR first.

#### Rule 3: Gradient Vanishing

**Detects:** training looks like it is converging, but gradients are shrinking and loss improvement is stalling.

**What you'll see:**
```
[Advisor] Gradient vanishing at step 8000: gradients shrinking (trend=-3.50%)
for 20 steps while loss improvement stalls.
Consider increasing learning rate or reducing weight decay.
```

**What to do:** try raising `learning_rate` slightly, or reduce `weight_decay`.

#### Rule 4: Loss Spike Correlated with MoE Issues

**Detects:** LossGuard triggered recently AND MoE expert utilization dropped.

**What you'll see:**
```
[Advisor] Loss spike correlates with MoE routing issues at step 4100: LossGuard
triggered at step 4095 and expert utilization is low (35%).
Routing instability is likely the root cause — increase router_aux_loss_coef before adjusting LR.
```

**What to do:** increase `router_aux_loss_coef` before you change the LR.

#### Rule 5: LR Reductions Not Helping

**Detects:** LossGuard has applied 2+ permanent LR reductions, but training still isn't converging.

**What you'll see:**
```
[Advisor] LR reductions not helping at step 6000: 2 permanent LR reductions applied
but training is still in plateau phase. The problem may not be learning rate —
check data quality, batch size, or model architecture.
```

**What to do:** the LR is probably not the problem. Check your dataset for quality issues, try a different batch size, or reconsider the model architecture.

#### Rule 6: Warmup Too Short

**Detects:** loss is still dropping steeply when warmup ends (checked once).

**What you'll see:**
```
[Advisor] Warmup may be too short: loss still dropping steeply (8.5% over last 10 steps)
as warmup ends at step 200. Consider increasing warmup_steps from 200 to ~300.
```

**What to do:** increase `warmup_ratio` or `warmup_steps`.

### Cooldown

Each advisor rule has a per-category cooldown (default: 200 steps) to keep the logs readable. A rule fires at most once per cooldown period.

## Training Phases

The **PhaseDetector** puts your run into one of five phases by comparing the older and newer halves of a rolling loss window:

| Phase          | Meaning                       | What Happens                             |
| -------------- | ----------------------------- | ---------------------------------------- |
| **WARMUP**     | First 50 steps                | Statistics unreliable, no classification |
| **CONVERGING** | Loss steadily decreasing      | Normal healthy training                  |
| **PLATEAU**    | Loss improvement < 0.1%       | Training may be stalled                  |
| **UNSTABLE**   | High loss variance (CV > 15%) | Loss is erratic                          |
| **DIVERGING**  | Loss trending upward          | Training is failing                      |

Every phase change is logged:

```
Training phase: converging -> plateau at step 5000 (previous phase lasted 3200 steps)
```

The current phase is also sent to wandb/Aim as the `phase` field of `StepMetrics` (see [Training Metrics & Monitoring](/engine/guides/metrics/)).

**How classification works:** the detector keeps a rolling window (default: 100 steps), splits it in half, and compares the mean loss of the older half with the newer half:

- Relative improvement > 0.1% → CONVERGING
- Improvement between -1% and 0.1% → PLATEAU
- Improvement < -1% (loss increasing) → DIVERGING
- Coefficient of variation > 15% → UNSTABLE

## Plateau Detection

The **PlateauDetector** watches for loss that has stopped improving and logs a warning when the stall persists:

```
Plateau detected at step 5000: loss barely improving over last 200 steps
(older_mean=2.3456, recent_mean=2.3412, improvement=0.0019%).
Consider adjusting learning rate or stopping early.
```

To avoid noise, it uses patience (3 consecutive checks) and a cooldown (200 steps between warnings). It only warns; it takes no action.

## Gradient Tracking

The **GradientTracker** keeps a short rolling window (default: 20 steps) of gradient norms and computes:

| Statistic         | Description                                |
| ----------------- | ------------------------------------------ |
| `grad_norm_mean`  | Rolling mean of recent gradient norms      |
| `grad_norm_max`   | Rolling maximum                            |
| `grad_norm_trend` | Slope of linear regression over the window |

These go into every `StepMetrics` and are logged to wandb/Aim.

The tracker warns when gradients are **accelerating**. A sustained upward trend predicts an explosion before any single step crosses a threshold:

```
Gradient acceleration at step 3200: grad norms trending upward over last 20 steps
(mean=0.4523, max=0.8901, trend=0.2341, relative=51.77%).
Consider reducing learning rate.
```

Because the threshold uses the relative trend (trend / mean), it does not depend on scale: it works the same whether your gradient norms are 0.01 or 100.

## Loss Guard (Auto LR Reduction)

**Config:** `auto_lr_reduction: true`

The **LossGuard** detects loss spikes and gradient explosions and lowers the learning rate for you, in two stages:

### Detection Criteria

| Anomaly            | Trigger                                              |
| ------------------ | ---------------------------------------------------- |
| Loss spike         | Loss > rolling mean + 3σ AND absolute change > 0.5   |
| Gradient explosion | Gradient norm > 10× rolling mean OR > 100 (absolute) |
| Non-finite values  | `inf` or `nan` in loss or gradient norm              |

### Escalation Policy

```
Normal → Temporary Override → Temporary Override → Permanent Reduction
         (1st anomaly)        (2nd anomaly)         (3rd anomaly)
```

1. **Temporary override** (first 2 anomalies): the LR is cut to 50% of the scheduled value, then blends linearly back to the schedule over 50 steps (the grace period).
2. **Permanent reduction** (after 2 temporary overrides without recovery): the base LR is scaled by 0.5× for the rest of the run, up to 5 permanent reductions in total.

Log output:

```
Auto LR override: loss spike at step 1200 (loss=4.5678, grad_norm=0.89).
LR: 2.00e-04 -> 1.00e-04 (temporary, 50 step grace) [override 1/2]
```

```
Auto LR reduction: gradient explosion at step 2400 (loss=3.2100, grad_norm=145.23).
LR: 2.00e-04 -> 1.00e-04 (permanent) [reduction 1/5]
```

### How the Temporary Override Works

A temporary override blends back into the schedule smoothly:

```
LR ─────────┐
             │  ← spike detected, LR cut to 50%
             └──────────────── gradually blend back to schedule
                 50 steps (grace period)
```

A brief anomaly therefore does not cost you a permanent LR cut.

## MoE Routing Health

The **MoEMonitor** tracks MoE routing metrics over a rolling window and warns when routing degrades. It is always on, and does nothing for dense (non-MoE) models.

### Warning Types

| Warning           | Trigger                    | Log Prefix                       |
| ----------------- | -------------------------- | -------------------------------- |
| Routing imbalance | `load_imbalance` > 3×      | `[MoE] Routing imbalance`        |
| Severe imbalance  | `load_imbalance` > 10×     | `[MoE] Severe routing imbalance` |
| Low utilization   | `expert_utilization` < 80% | `[MoE] Low expert utilization`   |
| Expert collapse   | `expert_utilization` < 50% | `[MoE] Expert collapse risk`     |
| Aux-loss spike    | `aux_loss` > mean + 3σ     | `[MoE] Aux-loss spike`           |

### Routing Diagnostics

The monitor exposes a structured health report through `get_routing_diagnostics()`, which the TrainingAdvisor combines with its other signals:

| Field               | Range | Meaning                              |
| ------------------- | ----- | ------------------------------------ |
| `healthy`           | bool  | True if no issues detected           |
| `balance_score`     | 0–1   | 1.0 = perfect balance, lower = worse |
| `utilization_score` | 0–1   | Fraction of experts receiving tokens |
| `aux_loss_trend`    | float | Positive = aux-loss increasing (bad) |
| `recommendations`   | list  | Actionable fix suggestions           |

For more details on MoE metrics and tuning, see [Mixture-of-Experts Models](/engine/guides/moe/).

## Least-Loaded Expert Parallelism (LLEP)

Well-trained MoE models naturally route tokens unevenly: some experts specialise in particular domains and receive far more tokens than others. That is good for model quality, but standard Expert Parallelism (EP) assumes a balanced load. When routing is skewed, the GPU hosting the busiest experts becomes a bottleneck. Latency spikes, memory use grows, and in extreme cases the overloaded GPU runs out of memory.

**Least-Loaded Expert Parallelism (LLEP)** is Surogate's dynamic load-balancing algorithm for EP training and inference. It leaves the model's routing logic alone, since changing it would change the model's behaviour. Instead, at runtime it moves *excess tokens*, together with the matching expert weights, from overloaded GPUs to underloaded ones. The result is mathematically identical to standard EP; only the execution schedule changes.

LLEP turns on automatically when `ep_size > 1` and routing imbalance crosses a configurable threshold.

### How LLEP Works

At each MoE layer, LLEP looks at the per-GPU token load across the EP group:

1. **Measure**: global expert token counts are collected across all EP ranks (on plan-refresh steps; see sticky plans below).
2. **Check threshold**: if `max_gpu_load / mean_gpu_load` is below `ep_load_balance_threshold`, standard EP runs unchanged (no overhead).
3. **Assign**: the Least-Loaded Assignment (LLA) algorithm redistributes excess tokens from overloaded GPUs to underloaded ones, subject to a per-GPU capacity limit (the `α` factor).
4. **Transfer**: both the token batches and the corresponding expert weight slices are transferred peer-to-peer to the receiving GPU.
5. **Compute**: each GPU runs grouped GEMMs for its native experts plus any spilled experts it received.
6. **Combine**: outputs and gradients are routed back to the originating GPU and accumulated.

LLEP computes the exact MoE forward pass, with no approximations and no changes to routing probabilities. Gradients flow through it normally, so it works for training as well as inference.

### Configuration

Setting `ep_size > 1` enables LLEP. The threshold controls how readily it activates (see [Expert Parallelism (MoE) Options](/engine/reference/config/#expert-parallelism-moe-options)):

```yaml
gpus: 8
ep_size: 4                       # 4-way expert parallelism
ep_load_balance_threshold: 1.3   # activate LLEP when max/mean > 1.3 (default)
```

| Parameter | Type | Default | Effect |
| --- | --- | --- | --- |
| `ep_size` | int | 1 | Number of GPUs per EP group. Must divide `gpus` and `num_experts`. |
| `ep_load_balance_threshold` | float | 1.3 | Imbalance ratio above which LLEP activates. Lower = more aggressive rebalancing. |
| `ep_plan_refresh_interval` | int | 16 | Sticky plans: recompute the expert placement every N forward dispatches per layer. `1` = plan every step. |

**Threshold guidance:**

| Value | Behaviour |
| --- | --- |
| `1.0` | Always active — LPT scheduling runs every layer regardless of balance |
| `1.3` | Default — activates only when meaningful imbalance is present |
| `2.0+` | Conservative — only triggers under severe imbalance |

For post-training and fine-tuning on domain-specific data, where experts specialise most, use `1.0` or `1.3`. For pre-training, where routing is more uniform, `1.3` is a safe default.

### Performance Characteristics

LLEP is most effective when:

- **Imbalance is high**: under 80–95% token concentration into a small number of experts, LLEP achieves 4–6× speedup over standard EP with stable memory usage.
- **Batch size is large**: larger batches fill per-GPU capacity, so spreading the load evenly pays off more. With smaller batches, the communication overhead may outweigh the benefit.
- **Model hidden size is large**: larger GEMMs are more compute-efficient, so the cost of weight transfers is easier to amortise.

With perfectly balanced routing, LLEP adds very little overhead: below the threshold it falls back to standard EP automatically.

**Sticky plans and prefetch.** LLEP recomputes the expert placement every `ep_plan_refresh_interval` forward dispatches per layer (default 16), not every step. Any placement gives exact results for any batch (routing counts only affect how well balanced it is). Between refreshes, LLEP therefore skips the per-layer imbalance all-reduce and the LPT computation entirely, and prefetches the next layer's foreign expert weights while the current layer computes, in both forward and backward. In practice, the hot experts stay the same across adjacent steps, so using a slightly stale plan costs almost nothing, and the next refresh corrects any drift. Under `cpu_training`, foreign expert weights are fetched directly from the shared pinned host masters, and expert LoRA gradients are sent back to their owner ranks. Training stays mathematically exact.

### Relationship to MoEMonitor Warnings

The MoEMonitor and LLEP do different jobs. MoEMonitor detects *training-level* routing problems (collapse, instability), while LLEP handles *system-level* load imbalance in the background.

If you see MoEMonitor warnings while using EP, read them with LLEP in mind:

| Warning | With LLEP active | Recommended action |
| --- | --- | --- |
| `[MoE] Routing imbalance` | Normal — LLEP is redistributing work | No action needed; monitor if imbalance grows |
| `[MoE] Severe routing imbalance` | LLEP may be saturated; very extreme skew | Lower `ep_load_balance_threshold` to `1.0`, check `router_aux_loss_coef` |
| `[MoE] Expert collapse risk` | Routing collapse, not a load problem | Increase `router_aux_loss_coef`; LLEP cannot fix collapse |
| `[Advisor] MoE routing collapse driving divergence` | Training instability | Fix `router_aux_loss_coef` first; LLEP is a throughput tool, not a stability fix |

LLEP is built to tolerate and exploit natural expert specialisation. It cannot fix genuine router collapse; use `router_aux_loss_coef` and `router_z_loss_coef` for that.

### LLEP with QLoRA and Expert Offloading

LLEP works with all QLoRA variants (see the [QLoRA guide](/engine/guides/qlora/)). With `qlora_offload_experts: true`, each GPU offloads only its local expert shard to CPU, and spilled experts are fetched on demand during LLEP redistribution:

```yaml
model: Qwen/Qwen3-30B-A3B
gpus: 4
ep_size: 2
ep_load_balance_threshold: 1.0

lora: true
lora_rank: 16
qlora_fp8: true
qlora_offload_experts: true
```

See [Expert Parallelism](/engine/guides/moe/#expert-parallelism-ep) for the full EP configuration reference.


## Early Stopping

**Config:** `early_stop: true`

The **EarlyStopping** module checks four independent criteria and stops training as soon as ANY of them fires:

| Criterion            | Check Frequency | Trigger                                         |
| -------------------- | --------------- | ----------------------------------------------- |
| Convergence score    | Every eval      | Score > 0.85 for 5 consecutive evals            |
| Compute efficiency   | Every step      | Loss reduction per FLOP drops below 50% of peak |
| Sustained divergence | Every step      | DIVERGING phase for 200+ consecutive steps      |
| Sustained plateau    | Every step      | PLATEAU phase for 500+ consecutive steps        |

### Convergence Score

The convergence score combines two signals:

- **Stability** (60% weight): 1 minus the coefficient of variation of the last 5 eval losses. High stability means the loss has settled.
- **Improvement rate** (40% weight): how much the eval loss improved since the previous eval. No improvement pushes the score up.

A score > 0.85 means the model has largely stopped learning. If that holds for 5 consecutive evals, training stops.

### Compute Efficiency

This check uses the Chinchilla `6N` approximation (FLOPs/token = 6 × model parameters) to estimate loss reduction per FLOP. Once that drops below 50% of the peak efficiency seen during the run, more compute is unlikely to help.

Log output:

```
Early stopping at step 15000: compute efficiency collapsed
(current 1.23e-15 < 50% of peak 4.56e-15)
```

## Recommended Corrective Actions

| Log Message                                         | Meaning                           | Recommended Action                                      |
| --------------------------------------------------- | --------------------------------- | ------------------------------------------------------- |
| `Training phase: converging -> plateau`             | Loss stopped improving            | Check if LR is too low or if model has converged        |
| `Training phase: converging -> diverging`           | Loss is increasing                | Reduce LR, check for data issues                        |
| `Training phase: converging -> unstable`            | Loss is erratic                   | Reduce LR, increase batch size, check gradient clipping |
| `Plateau detected at step N`                        | Sustained stagnation              | Consider reducing LR, adjusting schedule, or stopping   |
| `Gradient acceleration at step N`                   | Gradients growing fast            | Reduce LR before explosion occurs                       |
| `Auto LR override: loss spike`                      | Transient anomaly                 | Usually self-resolves with the temporary override       |
| `Auto LR reduction: ... (permanent)`                | Repeated anomalies                | Training may need fundamental changes                   |
| `[MoE] Expert collapse risk`                        | Most tokens to few experts        | Increase `router_aux_loss_coef`, enable `train_router`  |
| `[MoE] Severe routing imbalance`                    | Very uneven expert load           | Increase `router_aux_loss_coef`                         |
| `[MoE] Aux-loss spike`                              | Router destabilising              | Increase `router_z_loss_coef`                           |
| `[Advisor] Plateau with flat gradients`             | LR too high for plateau           | Reduce `learning_rate`                                  |
| `[Advisor] MoE routing collapse driving divergence` | Routing is the root cause         | Fix `router_aux_loss_coef` before LR                    |
| `[Advisor] Gradient vanishing`                      | Gradients shrinking               | Increase LR or reduce `weight_decay`                    |
| `[Advisor] Loss spike correlates with MoE`          | Routing caused the spike          | Fix routing before LR                                   |
| `[Advisor] LR reductions not helping`               | Problem is not LR                 | Check data quality, batch size, architecture            |
| `[Advisor] Warmup may be too short`                 | Loss still dropping at warmup end | Increase `warmup_ratio`                                 |
| `Early stopping at step N: convergence`             | Model converged                   | Training complete                                       |
| `Early stopping at step N: compute efficiency`      | Diminishing returns               | Further training unlikely to help                       |
| `Early stopping at step N: sustained divergence`    | Unrecoverable failure             | Fix hyperparameters and restart                         |
| `Early stopping at step N: sustained plateau`       | Permanently stalled               | Training has stalled, stop and evaluate                 |

## Chinchilla Token Budget (only for Pre-Training)

**Config:** `epoch_adjustment: true`

When training starts, Surogate computes the Chinchilla-optimal token budget:

```
tokens_optimal = 20 × model_parameters
```

It is always logged, for reference:

```
Chinchilla budget: 12.0B tokens (20 × 600.0M params) | Planned: 8.4B tokens (70.0% of budget)
```

With `epoch_adjustment: true`, Surogate adjusts `num_epochs` so the total token count matches the Chinchilla budget:

```
Epoch adjustment: 3 -> 5 epochs (Chinchilla budget 12.0B tokens, dataset 2.4B tokens)
```

This only happens when `max_steps` is not set explicitly.

## Configuration Reference

### Config Flags

| Option              | Type | Default | Description                                         |
| ------------------- | ---- | ------- | --------------------------------------------------- |
| `auto_lr_reduction` | bool | `false` | Enable LossGuard (automatic LR reduction on spikes) |
| `early_stop`        | bool | `false` | Enable multi-criteria early stopping                |
| `epoch_adjustment`  | bool | `false` | Adjust epochs to Chinchilla-optimal token budget    |


## See Also

- [Training Metrics & Monitoring](/engine/guides/metrics/): every metric logged during training
- [Debugging Training Issues](/engine/guides/debugging/): what to do when the advisor's fixes are not enough
- [Mixture-of-Experts Models](/engine/guides/moe/): MoE-specific configuration and tuning
- [Configuration Reference](/engine/reference/config/): every YAML config option
