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

Adaptive Training System

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.

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 in the config reference.

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.

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

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

Section titled “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.

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

Section titled “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.

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.

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.

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.

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

PhaseMeaningWhat Happens
WARMUPFirst 50 stepsStatistics unreliable, no classification
CONVERGINGLoss steadily decreasingNormal healthy training
PLATEAULoss improvement < 0.1%Training may be stalled
UNSTABLEHigh loss variance (CV > 15%)Loss is erratic
DIVERGINGLoss trending upwardTraining 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).

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

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.

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

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

Config: auto_lr_reduction: true

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

AnomalyTrigger
Loss spikeLoss > rolling mean + 3σ AND absolute change > 0.5
Gradient explosionGradient norm > 10× rolling mean OR > 100 (absolute)
Non-finite valuesinf or nan in loss or gradient norm
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]

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.

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.

WarningTriggerLog Prefix
Routing imbalanceload_imbalance > 3×[MoE] Routing imbalance
Severe imbalanceload_imbalance > 10×[MoE] Severe routing imbalance
Low utilizationexpert_utilization < 80%[MoE] Low expert utilization
Expert collapseexpert_utilization < 50%[MoE] Expert collapse risk
Aux-loss spikeaux_loss > mean + 3σ[MoE] Aux-loss spike

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

FieldRangeMeaning
healthy#boolTrue if no issues detected
balance_score#0–11.0 = perfect balance, lower = worse
utilization_score#0–1Fraction of experts receiving tokens
aux_loss_trend#floatPositive = aux-loss increasing (bad)
recommendations#listActionable fix suggestions

For more details on MoE metrics and tuning, see Mixture-of-Experts Models.

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.

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.

Setting ep_size > 1 enables LLEP. The threshold controls how readily it activates (see 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)
ParameterTypeDefaultEffect
ep_size#int1Number of GPUs per EP group. Must divide gpus and num_experts.
ep_load_balance_threshold#float1.3Imbalance ratio above which LLEP activates. Lower = more aggressive rebalancing.
ep_plan_refresh_interval#int16Sticky plans: recompute the expert placement every N forward dispatches per layer. 1 = plan every step.

Threshold guidance:

ValueBehaviour
1.0Always active — LPT scheduling runs every layer regardless of balance
1.3Default — 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.

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.

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:

WarningWith LLEP activeRecommended action
[MoE] Routing imbalanceNormal — LLEP is redistributing workNo action needed; monitor if imbalance grows
[MoE] Severe routing imbalanceLLEP may be saturated; very extreme skewLower ep_load_balance_threshold to 1.0, check router_aux_loss_coef
[MoE] Expert collapse riskRouting collapse, not a load problemIncrease router_aux_loss_coef; LLEP cannot fix collapse
[Advisor] MoE routing collapse driving divergenceTraining instabilityFix 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 works with all QLoRA variants (see the QLoRA guide). 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 for the full EP configuration reference.

Config: early_stop: true

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

CriterionCheck FrequencyTrigger
Convergence scoreEvery evalScore > 0.85 for 5 consecutive evals
Compute efficiencyEvery stepLoss reduction per FLOP drops below 50% of peak
Sustained divergenceEvery stepDIVERGING phase for 200+ consecutive steps
Sustained plateauEvery stepPLATEAU phase for 500+ consecutive steps

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.

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)
Log MessageMeaningRecommended Action
Training phase: converging -> plateauLoss stopped improvingCheck if LR is too low or if model has converged
Training phase: converging -> divergingLoss is increasingReduce LR, check for data issues
Training phase: converging -> unstableLoss is erraticReduce LR, increase batch size, check gradient clipping
Plateau detected at step NSustained stagnationConsider reducing LR, adjusting schedule, or stopping
Gradient acceleration at step NGradients growing fastReduce LR before explosion occurs
Auto LR override: loss spikeTransient anomalyUsually self-resolves with the temporary override
Auto LR reduction: ... (permanent)Repeated anomaliesTraining may need fundamental changes
[MoE] Expert collapse riskMost tokens to few expertsIncrease router_aux_loss_coef, enable train_router
[MoE] Severe routing imbalanceVery uneven expert loadIncrease router_aux_loss_coef
[MoE] Aux-loss spikeRouter destabilisingIncrease router_z_loss_coef
[Advisor] Plateau with flat gradientsLR too high for plateauReduce learning_rate
[Advisor] MoE routing collapse driving divergenceRouting is the root causeFix router_aux_loss_coef before LR
[Advisor] Gradient vanishingGradients shrinkingIncrease LR or reduce weight_decay
[Advisor] Loss spike correlates with MoERouting caused the spikeFix routing before LR
[Advisor] LR reductions not helpingProblem is not LRCheck data quality, batch size, architecture
[Advisor] Warmup may be too shortLoss still dropping at warmup endIncrease warmup_ratio
Early stopping at step N: convergenceModel convergedTraining complete
Early stopping at step N: compute efficiencyDiminishing returnsFurther training unlikely to help
Early stopping at step N: sustained divergenceUnrecoverable failureFix hyperparameters and restart
Early stopping at step N: sustained plateauPermanently stalledTraining has stalled, stop and evaluate

Chinchilla Token Budget (only for Pre-Training)

Section titled “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.

OptionTypeDefaultDescription
auto_lr_reduction#boolfalseEnable LossGuard (automatic LR reduction on spikes)
early_stop#boolfalseEnable multi-criteria early stopping
epoch_adjustment#boolfalseAdjust epochs to Chinchilla-optimal token budget