Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Pipeline parallel: refuse the MoE router aux loss over several micro-batches at Trainer init (#16822)
Daniel Han41c4f6fe7d00
diff --git a/tests/test_parallel_cp_compose_gloo.py b/tests/test_parallel_cp_compose_gloo.pyindex 26253858779..73c2330aaae 100644--- a/tests/test_parallel_cp_compose_gloo.py+++ b/tests/test_parallel_cp_compose_gloo.py@@ -340,6 +340,8 @@ def _case_train(device = "cpu",bypass_pre = False,bypass_post = False,+ args_coef = "unset",+ probe_refusal = False,gc = "none",packed = None,):@@ -532,6 +534,8 @@ def _case_train(# TRL turns the MoE load balancing loss on from the architecture's coefficient unless this is 0.0# (it then sets output_router_logits on the config itself): aux off unless the case asks for it.args.router_aux_loss_coef = aux_coef if (router_aux or trl_aux) else 0.0+ if args_coef != "unset":+ args.router_aux_loss_coef = args_coefif sft_cp:args.context_parallel_size = cpargs.context_parallel_backend = "ulysses"@@ -553,6 +557,44 @@ def _case_train(caps.query_from(layout_now, SequentialSFT, model, args, cp = cp, cp_backend = "ulysses"))tokenizer = AutoTokenizer.from_pretrained(ckpt)+ if probe_refusal:+ before = {n: (p.detach().clone(), p.device) for n, p in model.named_parameters()}++ def untouched():+ now = dict(model.named_parameters())+ return now.keys() == before.keys() and all(+ now[n].device == d and now[n].shape == t.shape and torch.equal(now[n].detach(), t)+ for n, (t, d) in before.items()+ )++ phase = "init"+ try:+ trainer = SequentialSFT(+ model = model,+ args = args,+ train_dataset = data,+ data_collator = collate,+ processing_class = tokenizer,+ )+ phase = "train"+ trainer.train()+ except Exception as e:+ return {+ "error": f"{type(e).__name__}: {e}",+ "phase": phase,+ "split": pp_native.pipeline_stage_of(model) is not None,+ "untouched": untouched(),+ }+ logs = [h for h in trainer.state.log_history if "loss" in h]+ stage = pp_native.pipeline_stage_of(trainer.model)+ return {+ "phase": None,+ "losses": [h["loss"] for h in logs],+ "stage": None if stage is None else int(stage.stage_index),+ "output_router_logits": bool(+ getattr(trainer.model.config, "output_router_logits", False)+ ),+ }trainer = SequentialSFT(model = model,args = args,@@ -779,8 +821,14 @@ _ONE_MICROBATCH_REFUSED = "pipeline schedule cannot run 1 micro-batches over 2 sdef _skip_if_one_microbatch_refused(results):+ from unsloth.models import pp_env+errors = [res.get("error") or "" for res in results]- if errors and all(_ONE_MICROBATCH_REFUSED in e for e in errors):+ # Where GPipe pads a single micro-batch up to the stage count, a batch of one splits too and is refused.+ padded = pp_env._gpipe_needs_stage_count() and all(+ "splits each Trainer batch into 2" in e for e in errors+ )+ if errors and (padded or all(_ONE_MICROBATCH_REFUSED in e for e in errors)):import torch as _torchpytest.skip(f"torch {_torch.__version__}'s GPipe schedule refuses 1 micro-batch over 2 stages (torch < 2.13), and "@@ -1168,6 +1216,52 @@ def test_pp_moe_router_aux_loss_with_accumulation_matches_one_process(_close(res, ref, rel = 5e-4, state_atol = 1e-5, what = (ga, aux, rank))+_PP_AUX_SPLIT = "load-balancing loss per micro-batch"+++ "how",+ [+ dict(router_aux = True, aux_coef = 0.5),+ dict(trl_aux = True, aux_coef = 0.5),+ ],+ ids = ["config_flag", "trl_coef"],+)[email protected]("env", [{}, {"UNSLOTH_PP_SCHEDULE": "1f1b"}], ids = ["default", "1f1b"])+def test_pp_moe_router_aux_loss_split_over_micro_batches_is_refused_at_trainer_init(how, env):+ env = {"UNSLOTH_PP_SIZE": "2", **env}+ for rank, res in enumerate(+ _spawn("train", 2, env, bs = 2, ga = 1, steps = 1, arch = "qwen3_moe", probe_refusal = True, **how)+ ):+ assert _PP_AUX_SPLIT in (res.get("error") or ""), (rank, res)+ assert res["phase"] == "init", (rank, res)+ assert not res["split"] and res["untouched"], (rank, res)+++ "how, env",+ [+ (dict(), {}),+ (dict(router_aux = True, args_coef = 0.0), {}),+ (+ dict(router_aux = True, aux_coef = 0.5, ga = 2),+ {"UNSLOTH_PP_MICROBATCHES": "1", "UNSLOTH_PP_SCHEDULE": "gpipe"},+ ),+ (dict(router_aux = True, aux_coef = 0.5, bs = 1), {"UNSLOTH_PP_SCHEDULE": "gpipe"}),+ ],+ ids = ["aux_off", "config_flag_coef0", "aux_on_one_microbatch", "aux_on_batch_of_one"],+)+def test_pp_moe_router_aux_loss_allowed_layouts_still_train(how, env):+ kw = dict(bs = 2, ga = 1, steps = 2, arch = "qwen3_moe", probe_refusal = True)+ kw.update(how)+ results = _spawn("train", 2, {"UNSLOTH_PP_SIZE": "2", **env}, **kw)+ _skip_if_one_microbatch_refused(results)+ assert sorted(res.get("stage") for res in results) == [0, 1], results+ for rank, res in enumerate(results):+ assert res["phase"] is None and "error" not in res, (rank, res)+ assert len(res["losses"]) == 2 and all(l == l for l in res["losses"]), (rank, res)++# LoRA on the experts is eager only under cp (the registry's qwen3_moe x lora+experts x cp row): its per instance# ParametrizedQwen3MoeTopKRouter type guards recompile more than one process once the router capture hooks are# installed before the first block compiles.diff --git a/tests/test_parallel_env.py b/tests/test_parallel_env.pyindex fb5123d8243..5a04d9b2b11 100644--- a/tests/test_parallel_env.py+++ b/tests/test_parallel_env.py@@ -1263,6 +1263,162 @@ def test_pp_env_refuses_router_aux_loss_split_over_micro_batches():pp_env._refuse_split_router_aux(stage, 2)+def test_pp_env_router_aux_split_is_refused_before_the_trainer_init():+ import types++ import transformers+ from transformers import Qwen3MoeConfig, Qwen3MoeForCausalLM++ from unsloth.models import pp_env++ config = Qwen3MoeConfig(+ vocab_size = 32,+ hidden_size = 8,+ intermediate_size = 8,+ moe_intermediate_size = 8,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ head_dim = 4,+ num_experts = 4,+ num_experts_per_tok = 2,+ router_aux_loss_coef = 0.5,+ output_router_logits = True,+ )+ model = Qwen3MoeForCausalLM(config)++ def layout(mb = None, schedule = "gpipe"):+ return types.SimpleNamespace(+ pp = 2, microbatches = mb, schedule = schedule, env_vars = "UNSLOTH_PP_SIZE=2"+ )++ def args(+ bs,+ coef = "absent",+ eval_strategy = "no",+ eval_bs = 1,+ ):+ a = types.SimpleNamespace(+ per_device_train_batch_size = bs,+ eval_strategy = eval_strategy,+ per_device_eval_batch_size = eval_bs,+ )+ if coef != "absent":+ a.router_aux_loss_coef = coef+ return a++ rows = list(range(64))++ def refuse(*a, **k):+ k = {"train_dataset": rows, "eval_dataset": rows, **k}+ return pp_env._refuse_split_router_aux_at_init(*a, **k)++ T, SFT = transformers.Trainer, type("SFTTrainer", (transformers.Trainer,), {})+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(T, args(2), layout(), model)+ with pytest.raises(NotImplementedError, match = "into 2 micro-batches"):+ refuse(T, args(1), layout(schedule = "1f1b"), model) # 1F1B pads up to pp+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(T, args(1, eval_strategy = "steps", eval_bs = 4), layout(), model)+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(SFT, args(2, coef = None), layout(), model) # TRL takes the architecture's coefficient+ refuse(T, args(4), layout(mb = 1), model)+ # UNSLOTH_PP_MICROBATCHES the schedule cannot run: the split refuses it with the schedule's own reason.+ refuse(T, args(4), layout(mb = 1, schedule = "1f1b"), model)+ if not pp_env._gpipe_needs_stage_count():+ refuse(T, args(1), layout(), model)+ refuse(SFT, args(4, coef = 0.0), layout(), model)+ refuse(T, args(4), layout(mb = 3), model) # the step raises its own error+ model.router_aux_loss_coef = 0.0+ refuse(T, args(4), layout(), model)+ model.router_aux_loss_coef = 0.5+ config.output_router_logits = False+ refuse(T, args(4), layout(), model)+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(SFT, args(4, coef = 0.1), layout(), model) # TRL turns it on inside its __init__+ refuse(T, args(4), layout(), model.model) # not a carried family: the split decides+ # No train_dataset (evaluation only): the unused training batch is not checked.+ config.output_router_logits = True+ eval_only = args(8, eval_strategy = "steps", eval_bs = 1)+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(T, eval_only, layout(), model)+ if not pp_env._gpipe_needs_stage_count():+ refuse(T, eval_only, layout(), model, train_dataset = None)+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(T, args(8, eval_strategy = "steps", eval_bs = 4), layout(), model, train_dataset = None)+ # Fewer rows than one batch per dp rank, no len() or packing: only the step knows the batch size.+ if not pp_env._gpipe_needs_stage_count():+ refuse(T, args(8), layout(), model, train_dataset = [0])+ refuse(+ T, args(8), types.SimpleNamespace(**vars(layout()), dp = 4), model, train_dataset = rows[:4]+ )+ refuse(+ T,+ args(8, eval_strategy = "steps", eval_bs = 8),+ layout(),+ model,+ train_dataset = None,+ eval_dataset = {"a": [0]},+ )+ refuse(+ T, args(5), types.SimpleNamespace(**vars(layout()), dp = 2), model, train_dataset = rows[:8]+ )+ refuse(T, args(8), layout(), model, train_dataset = [0, 1])+ with pytest.raises(NotImplementedError, match = "into 4 micro-batches"):+ refuse(+ T,+ args(8),+ types.SimpleNamespace(**vars(layout()), dp = 2),+ model,+ train_dataset = rows[:16],+ )+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ refuse(+ T,+ args(8, eval_strategy = "steps", eval_bs = 8),+ layout(),+ model,+ train_dataset = None,+ eval_dataset = {"a": [0], "b": rows},+ )+ refuse(T, args(8), layout(), model, train_dataset = iter(rows))+ packed = args(8)+ packed.packing = True+ refuse(T, packed, layout(), model)+++def test_pp_env_refusals_know_whether_the_trainer_trains(monkeypatch):+ import types++ import transformers++ from unsloth.models import _utils as unsloth_utils+ from unsloth.models import pp_env, tp_env++ seen = []+ monkeypatch.setenv("UNSLOTH_PP_SIZE", "2")+ monkeypatch.setattr(+ tp_env,+ "env_layout",+ lambda: types.SimpleNamespace(pp = 2, tp = 1, env_vars = "UNSLOTH_PP_SIZE=2"),+ )+ monkeypatch.setattr(+ pp_env,+ "pp_trainer_refusals",+ lambda *a, **k: seen.append((k["train_dataset"], k["eval_dataset"])),+ )+ trainer = object.__new__(transformers.Trainer)+ init = transformers.Trainer.__init__+ a = types.SimpleNamespace()+ unsloth_utils._pipeline_parallel_env_refusals(trainer, init, (), {"args": a})+ unsloth_utils._pipeline_parallel_env_refusals(+ trainer, init, (), {"args": a, "train_dataset": [1]}+ )+ unsloth_utils._pipeline_parallel_env_refusals(trainer, init, (None, a, None, [1]), {})+ unsloth_utils._pipeline_parallel_env_refusals(trainer, init, (None, a), {"eval_dataset": [1]})+ assert seen == [(None, None), ([1], None), ([1], None), (None, [1])]++def test_pending_expert_lora_counts_in_the_capability_query():# Failing before: SFTTrainer(peft_config = LoraConfig(target_modules = expert projections)) was queried as# attention-only LoRA (expert_lora read only the attached adapters) and hit an unverified cell.diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 55b381e33fc..910299cbb77 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -6420,7 +6420,7 @@ def patch_gradient_accumulation_fix(Trainer):# before anything below splits or shards the model._parallel_capabilities_pre(self, _original_trainer_init, args, kwargs, model)# UNSLOTH_PP_SIZE: trainers / arguments the pipeline step cannot run, refused before the split.- _pipeline_parallel_env_refusals(self, _original_trainer_init, args, kwargs)+ _pipeline_parallel_env_refusals(self, _original_trainer_init, args, kwargs, model)# UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE (unmodified scripts): the pipeline split, then tensor parallel,# before native FSDP2 shards the dp dimension.tp_env = _tensor_parallel_env_trainer_pre(model)@@ -6754,7 +6754,13 @@ def _parallel_capabilities_pre(trainer, init, args, kwargs, model):check_layout(layout, type(trainer), model, training_args, cp_backend = backend)-def _pipeline_parallel_env_refusals(trainer, init, args, kwargs):+def _pipeline_parallel_env_refusals(+ trainer,+ init,+ args,+ kwargs,+ model = None,+):if not os.environ.get("UNSLOTH_PP_SIZE"):returnfrom .tp_env import env_layout@@ -6764,13 +6770,17 @@ def _pipeline_parallel_env_refusals(trainer, init, args, kwargs):returntraining_args = kwargs.get("args")compute_loss_func = kwargs.get("compute_loss_func")- if training_args is None or (compute_loss_func is None and args):+ train_dataset = kwargs.get("train_dataset")+ eval_dataset = kwargs.get("eval_dataset")+ if training_args is None or args:try:import inspectbound = inspect.signature(init).bind_partial(trainer, *args, **kwargs)training_args = bound.arguments.get("args", training_args)compute_loss_func = bound.arguments.get("compute_loss_func", compute_loss_func)+ train_dataset = bound.arguments.get("train_dataset", train_dataset)+ eval_dataset = bound.arguments.get("eval_dataset", eval_dataset)except (TypeError, ValueError):passif layout.tp > 1 and (@@ -6787,7 +6797,15 @@ def _pipeline_parallel_env_refusals(trainer, init, args, kwargs):)from .pp_env import pp_trainer_refusals- pp_trainer_refusals(type(trainer), training_args, layout, compute_loss_func = compute_loss_func)+ pp_trainer_refusals(+ type(trainer),+ training_args,+ layout,+ compute_loss_func = compute_loss_func,+ model = model,+ train_dataset = train_dataset,+ eval_dataset = eval_dataset,+ )def _tensor_parallel_env_trainer_pre(model):diff --git a/unsloth/models/pp_env.py b/unsloth/models/pp_env.pyindex b74616e231a..4da9513a880 100644--- a/unsloth/models/pp_env.py+++ b/unsloth/models/pp_env.py@@ -168,30 +168,13 @@ def resolve_microbatches(layout = getattr(stage, "env_layout", None)explicit = layout.microbatches if layout is not None else Nonewant = int(explicit or stage.n_microbatches)- floor = (- stage.num_stages- if (stage.schedule == "1f1b" and train) or _gpipe_needs_stage_count()- else 1- )- if batch_size % want == 0:- m = want- elif explicit is not None and train:- raise ValueError(- f"Unsloth: UNSLOTH_PP_MICROBATCHES={explicit} must divide the Trainer batch size ({batch_size} rows "- "per device): set per_device_train_batch_size to a multiple of it, or unset UNSLOTH_PP_MICROBATCHES."- )- else:- m = max(d for d in range(1, min(want, batch_size) + 1) if batch_size % d == 0)- pad = 0- if m < floor:- # Whole micro-batches of filler rows after the real ones (the real rows keep their micro-batch shape).- pad = (floor - m) * (batch_size // m)- m = floor+ m, pad = _plan_microbatches(want, explicit, stage.num_stages, stage.schedule, batch_size, train)if m == want and not pad:return m, 0if train and not stage.__dict__.get("_unsloth_mb_note"):stage.__dict__["_unsloth_mb_note"] = Truerows = batch_size + pad+ floor = m if pad else 1note = (f", padded with {pad} fully masked row(s) (this schedule needs {floor} micro-batches; a "f"per_device_train_batch_size of {floor} or more avoids the extra compute)"@@ -205,6 +188,26 @@ def resolve_microbatches(return m, pad+def _plan_microbatches(want, explicit, num_stages, schedule, batch_size, train):+ """(n_microbatches, padded rows); shared with the Trainer init refusals so they predict the per-step count."""+ floor = num_stages if (schedule == "1f1b" and train) or _gpipe_needs_stage_count() else 1+ if batch_size % want == 0:+ m = want+ elif explicit is not None and train:+ raise ValueError(+ f"Unsloth: UNSLOTH_PP_MICROBATCHES={explicit} must divide the Trainer batch size ({batch_size} rows "+ "per device): set per_device_train_batch_size to a multiple of it, or unset UNSLOTH_PP_MICROBATCHES."+ )+ else:+ m = max(d for d in range(1, min(want, batch_size) + 1) if batch_size % d == 0)+ pad = 0+ if m < floor:+ # Whole micro-batches of filler rows after the real ones (the real rows keep their micro-batch shape).+ pad = (floor - m) * (batch_size // m)+ m = floor+ return m, pad++def _pad_rows(input_ids, labels, extra, pad):"""`pad` copies of the first row with every label ignored (attention on, so no fully masked row)."""if not pad:@@ -575,6 +578,9 @@ def pp_trainer_refusals(args,layout,compute_loss_func = None,+ model = None,+ train_dataset = None,+ eval_dataset = None,):"""Before Trainer.__init__ splits anything: the trainers / arguments the pipeline step cannot honour."""hint = _hint()@@ -640,6 +646,106 @@ def pp_trainer_refusals(+ "."+ hint)+ _refuse_split_router_aux_at_init(trainer_cls, args, layout, model, train_dataset, eval_dataset)+++def _router_aux_coef_at_init(trainer_cls, args, model):+ """Router aux coefficient the last stage will apply (0 = none). TRL trainers rewrite output_router_logits and+ router_aux_loss_coef inside their own __init__ (after this check) from args.router_aux_loss_coef (None = the+ architecture's)."""+ from ..parallel_capabilities import _trainer_kind+ from .pp_native import _PP_MOE_AUX_FAMILIES++ if not isinstance(model, nn.Module):+ return 0+ owner = next((m for m in model.modules() if type(m).__name__ in _PP_MOE_AUX_FAMILIES), None)+ config = getattr(owner, "config", None)+ if config is None:+ return 0 # the split refuses other MoE models+ text = config.get_text_config() if hasattr(config, "get_text_config") else config+ coef = getattr(owner, "router_aux_loss_coef", getattr(text, "router_aux_loss_coef", 0)) or 0+ on = bool(getattr(text, "output_router_logits", False))+ if (+ _trainer_kind(trainer_cls) in ("sft", "dpo", "grpo", "other_rl")+ and args is not None+ and hasattr(args, "router_aux_loss_coef")+ and hasattr(text, "router_aux_loss_coef")+ ):+ trl = args.router_aux_loss_coef+ coef = (getattr(text, "router_aux_loss_coef", 0) or 0) if trl is None else trl+ on = hasattr(text, "output_router_logits") and bool(coef)+ return coef if on else 0+++def _largest_batch(dataset, batch_size, dp, packing):+ """`batch_size` when every rank surely gets a full batch from `dataset`, else None (the step decides): no+ dataset (train() / evaluate() cannot run on it), no len(), packing (TRL rebuilds the rows inside __init__),+ or fewer rows than one batch per dp rank (the dataloader's sharding / padding sets the size then)."""+ batch_size = int(batch_size or 0)+ if dataset is None or batch_size < 1 or packing:+ return None+ if isinstance(dataset, dict):+ sizes = [_largest_batch(d, batch_size, dp, packing) for d in dataset.values()]+ return max((size for size in sizes if size), default = None)+ try:+ rows = len(dataset)+ except TypeError:+ return None+ return batch_size if rows >= batch_size * max(int(dp or 1), 1) else None+++def _refuse_split_router_aux_at_init(+ trainer_cls,+ args,+ layout,+ model,+ train_dataset = None,+ eval_dataset = None,+):+ """_refuse_split_router_aux before the stage split; the per-step check covers what only the step knows."""+ if args is None or not _router_aux_coef_at_init(trainer_cls, args, model):+ return+ try:+ from .pp_schedules import schedule_spec+ schedule = schedule_spec(layout.schedule).name+ except Exception:+ schedule = layout.schedule+ want = int(layout.microbatches or 2 * layout.pp)+ dp = getattr(layout, "dp", 1)+ packing = bool(getattr(args, "packing", False))+ eval_packing = getattr(args, "eval_packing", None)+ batches = [+ (+ _largest_batch(+ train_dataset, getattr(args, "per_device_train_batch_size", 0), dp, packing+ ),+ True,+ )+ ]+ strategy = getattr(args, "eval_strategy", getattr(args, "evaluation_strategy", "no"))+ if str(getattr(strategy, "value", strategy) or "no").lower() != "no":+ packed = packing if eval_packing is None else bool(eval_packing)+ batches.append(+ (+ _largest_batch(+ eval_dataset, getattr(args, "per_device_eval_batch_size", 0), dp, packed+ ),+ False,+ )+ )+ for batch_size, train in batches:+ if not batch_size:+ continue+ try:+ m, pad = _plan_microbatches(+ want, layout.microbatches, layout.pp, schedule, batch_size, train+ )+ except ValueError:+ continue # the step raises its own error+ if pad and layout.microbatches:+ continue # this schedule cannot run the UNSLOTH_PP_MICROBATCHES asked for; the split says so+ if m > 1:+ raise NotImplementedError(_split_router_aux_message(layout.env_vars, m))def _dp_info(stage):@@ -682,12 +788,17 @@ def _refuse_split_router_aux(stage, n_microbatches):owner, "router_aux_loss_coef", 0):return- raise NotImplementedError(- f"Unsloth: {_env_vars(stage)} (pipeline parallel) splits each Trainer batch into {n_microbatches} "+ raise NotImplementedError(_split_router_aux_message(_env_vars(stage), n_microbatches))+++def _split_router_aux_message(env_vars, n_microbatches):+ return (+ f"Unsloth: {env_vars} (pipeline parallel) splits each Trainer batch into {n_microbatches} ""micro-batches, and the pipeline adds the router load-balancing loss per micro-batch, which is not the ""loss the Trainer forms over the whole batch on one GPU. Set UNSLOTH_PP_MICROBATCHES=1 with ""UNSLOTH_PP_SCHEDULE=gpipe (where this torch allows one micro-batch), or turn the auxiliary loss off "- f"(model.config.output_router_logits = False).{_hint()}"+ "(model.config.output_router_logits = False, or router_aux_loss_coef = 0.0 in SFTConfig)."+ f"{_hint()}")