A straightforward method for training your LLM, from downloading data to generating text.
fix(ddp): Mixture-of-Experts models no longer crash multi-GPU training
FareedKhan-dev1da431713758
diff --git a/src/post_training/distributed.py b/src/post_training/distributed.pyindex ec2151c..5aa75ae 100644--- a/src/post_training/distributed.py+++ b/src/post_training/distributed.py@@ -17,6 +17,7 @@ import torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom src.device import configure_cpu_threads, resolve_device+from src.models.modern.moe import MoE@dataclass@@ -74,11 +75,13 @@ def ddp_wrap(model: torch.nn.Module, ctx: DDPContext, find_unused_parameters: boPass ``find_unused_parameters=True`` for a model where some parameters do not receive agradient on every step (for example the reward model, which uses the backbone's``forward_hidden`` and a reward head but never its ``lm_head``). Without it, DDP raises- a "did not get a gradient" error on the first backward.+ a "did not get a gradient" error on the first backward. Mixture-of-Experts models turn it+ on automatically: an expert that no token picked in a step gets no gradient either."""if not ctx.enabled:return modeldevice_ids = [ctx.local_rank] if ctx.device.startswith("cuda") else None+ find_unused_parameters = find_unused_parameters or any(isinstance(m, MoE) for m in model.modules())return DDP(model, device_ids=device_ids, find_unused_parameters=find_unused_parameters)diff --git a/tests/test_ddp_moe.py b/tests/test_ddp_moe.pynew file mode 100644index 0000000..d0f9ba1--- /dev/null+++ b/tests/test_ddp_moe.py@@ -0,0 +1,34 @@+"""DDP with Mixture of Experts: an expert that gets no tokens in a step must not crash training."""++from __future__ import annotations++from pathlib import Path++import pytest+import torch+import torch.distributed as dist++from src.models.modern import ModernConfig, ModernTransformer+from src.post_training.distributed import DDPContext, ddp_wrap++[email protected](not dist.is_available(), reason="torch.distributed is not available")+def test_ddp_wrap_lets_moe_experts_skip_a_step(tmp_path: Path) -> None:+ store = (tmp_path / "store").as_posix()+ dist.init_process_group("gloo", init_method=f"file:///{store.lstrip('/')}", rank=0, world_size=1)+ try:+ torch.manual_seed(0)+ cfg = ModernConfig(vocab_size=32, context_length=16, n_embed=32, n_head=4, n_blocks=1, n_experts=4, moe_top_k=1)+ model = ModernTransformer(cfg)+ with torch.no_grad(): # expert 0 wins every token, so experts 1 to 3 get no gradient+ router = model.blocks[0].mlp.router.weight+ router.zero_()+ router[0] = 1.0+ # world_size=2 in the context only so ddp_wrap wraps; the process group itself has one rank+ ddp = ddp_wrap(model, DDPContext(rank=0, local_rank=0, world_size=2, device="cpu"))+ idx = torch.randint(0, 32, (2, 8))+ for _ in range(2): # without find_unused_parameters the second step raises+ _, loss = ddp(idx, idx)+ loss.backward()+ finally:+ dist.destroy_process_group()