Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

fix(sft): keep Mixture-of-Experts routers balanced during SFT

FareedKhan-dev59a089aabe49
diff --git a/scripts/train_sft.py b/scripts/train_sft.py
index 977bdc1..17a33a8 100644
--- a/scripts/train_sft.py
+++ b/scripts/train_sft.py
@@ -33,7 +33,14 @@ from src.post_training.distributed import cleanup, ddp_setup, ddp_wrap, reduce_s
from src.post_training.logging_utils import MetricsLogger
from src.post_training.optim import configure_optimizer, cosine_lr, set_lr
from src.post_training.sft import sft_loss
-from src.post_training.utils import amp_autocast, load_backbone_from_ckpt, save_stage_ckpt, set_seed, unwrap
+from src.post_training.utils import (
+ amp_autocast,
+ load_backbone_from_ckpt,
+ moe_balance_loss,
+ save_stage_ckpt,
+ set_seed,
+ unwrap,
+)
@torch.no_grad()
@@ -113,9 +120,11 @@ def main():
sync = micro == cfg.grad_accum - 1 or not ctx.enabled
with (contextlib.nullcontext() if sync else model.no_sync()), amp_autocast(cfg.amp_dtype, ctx.device):
logits, _ = model(tokens)
- loss = sft_loss(logits, tokens, mask) / cfg.grad_accum
+ ce = sft_loss(logits, tokens, mask)
+ # Mixture-of-Experts models also keep their experts balanced (0 for dense models)
+ loss = (ce + moe_balance_loss(model)) / cfg.grad_accum
loss.backward()
- loss_sum += loss.item()
+ loss_sum += ce.item() / cfg.grad_accum # log the plain SFT loss
if epoch >= cfg.epochs and cfg.max_steps <= 0:
break
loss = torch.tensor(loss_sum)
diff --git a/src/post_training/utils.py b/src/post_training/utils.py
index 0737a8a..ff99981 100644
--- a/src/post_training/utils.py
+++ b/src/post_training/utils.py
@@ -25,6 +25,7 @@ from src.checkpoint import (
unwrap_model,
)
from src.models.factory import LanguageModel, build_model
+from src.models.modern import ModernTransformer
def amp_autocast(amp_dtype: str | None, device: str):
@@ -92,6 +93,19 @@ def unwrap(model: nn.Module) -> nn.Module:
return unwrap_model(model)
+def moe_balance_loss(model: nn.Module) -> torch.Tensor | float:
+ """The Mixture-of-Experts balancing loss of the last forward pass, times its coefficient.
+
+ The modern model adds this loss itself only when it is given targets. The post-training
+ losses are computed outside the model, so the stages add it with this helper. It is 0 for
+ dense models.
+ """
+ inner = unwrap(model)
+ if isinstance(inner, ModernTransformer) and inner.aux_loss is not None:
+ return inner.config.moe_aux_loss_coef * inner.aux_loss
+ return 0.0
+
+
def make_frozen_copy(model: nn.Module, device: str | None = None) -> nn.Module:
"""
Deep-copy a model, put it in eval mode, and disable all gradients. Used for the
diff --git a/tests/test_modern_model.py b/tests/test_modern_model.py
index 012fc68..f7fcda0 100644
--- a/tests/test_modern_model.py
+++ b/tests/test_modern_model.py
@@ -187,6 +187,21 @@ def test_moe_loss_includes_aux_and_active_params_are_smaller() -> None:
assert model.active_params() < model.num_params()
+def test_post_training_adds_the_moe_balancing_loss() -> None:
+ from src.models.transformer import Transformer
+ from src.post_training.utils import moe_balance_loss
+
+ model = _model(VARIANTS["moe"])
+ logits, _ = model(torch.randint(0, BASE.vocab_size, (2, 8))) # no targets, like the SFT trainer
+ extra = moe_balance_loss(torch.nn.DataParallel(model)) # wrappers are looked through
+ assert isinstance(extra, torch.Tensor) and model.aux_loss is not None
+ assert torch.allclose(extra, BASE.moe_aux_loss_coef * model.aux_loss)
+ extra.backward()
+ assert model.blocks[0].mlp.router.weight.grad is not None
+ assert moe_balance_loss(_model(BASE)) == 0.0 # dense modern model
+ assert moe_balance_loss(Transformer(n_head=2, n_embed=16, context_length=8, vocab_size=32, N_BLOCKS=1)) == 0.0
+
+
def test_tied_embeddings_share_one_matrix() -> None:
tied, untied = _model(BASE), _model(replace(BASE, tie_embeddings=False))
assert tied.lm_head.weight is tied.token_embed.weight