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: carry the Qwen3-MoE router auxiliary loss across stages (#16406)
Daniel Han31dac5002b24
diff --git a/tests/test_pp_moe_aux_gloo.py b/tests/test_pp_moe_aux_gloo.pynew file mode 100644index 00000000000..aad58be72ff--- /dev/null+++ b/tests/test_pp_moe_aux_gloo.py@@ -0,0 +1,443 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Pipeline parallelism over a mixture-of-experts model carries the router auxiliary (load-balancing) loss+between stages: a gloo CPU world of 2 stages vs gradient accumulation over the same micro-batches in one+process (transformers adds router_aux_loss_coef x aux per forward), fp32, tiny random Qwen3-MoE."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None or getattr(+ multiprocessing.current_process(), "_inheriting", False+):+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib.machinery # noqa: E402+import importlib.util # noqa: E402+import sys # noqa: E402+import tempfile # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def _load(name):+ """unsloth/models/<name>.py without importing the unsloth package (which needs a GPU)."""+ full = f"unsloth.models.{name}"+ if full in sys.modules:+ return sys.modules[full]+ pkg = types.ModuleType("unsloth")+ pkg.__path__ = [os.path.join(REPO, "unsloth")]+ models = types.ModuleType("unsloth.models")+ models.__path__ = [os.path.join(REPO, "unsloth", "models")]+ for package in (pkg, models):+ package.__spec__ = importlib.machinery.ModuleSpec(package.__name__, None, is_package = True)+ package.__spec__.submodule_search_locations = package.__path__+ sys.modules.setdefault("unsloth", pkg)+ sys.modules.setdefault("unsloth.models", models)+ spec = importlib.util.spec_from_file_location(+ full, os.path.join(REPO, "unsloth", "models", f"{name}.py")+ )+ module = importlib.util.module_from_spec(spec)+ sys.modules[full] = module+ spec.loader.exec_module(module)+ return module+++ppn = _load("pp_native")+assert os.path.realpath(ppn.__file__).startswith(os.path.realpath(REPO)) # this checkout's tree++VOCAB = 128+DEEPSEEK_V3 = "trl-internal-testing/tiny-DeepseekV3ForCausalLM"+++def build(+ aux = True,+ coef = 0.01,+ lora = False,+ layers = 4,+ mlp_only_layers = (),+ family = "qwen3_moe",+ seed = 0,+):+ import transformers++ common = dict(+ vocab_size = VOCAB,+ hidden_size = 64,+ intermediate_size = 96,+ num_hidden_layers = layers,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ tie_word_embeddings = False,+ output_router_logits = aux,+ router_aux_loss_coef = coef,+ attention_dropout = 0.0,+ )+ if family == "qwen3_moe":+ config = transformers.Qwen3MoeConfig(+ head_dim = 16,+ moe_intermediate_size = 32,+ num_experts = 8,+ num_experts_per_tok = 2,+ norm_topk_prob = True,+ mlp_only_layers = list(mlp_only_layers),+ **common,+ )+ elif family == "mixtral":+ config = transformers.MixtralConfig(+ head_dim = 16, num_local_experts = 8, num_experts_per_tok = 2, **common+ )+ elif family == "olmoe":+ config = transformers.OlmoeConfig(num_experts = 8, num_experts_per_tok = 2, **common)+ else:+ raise ValueError(family)+ config._attn_implementation = "eager"+ torch.manual_seed(seed)+ model = transformers.AutoModelForCausalLM.from_config(config, dtype = torch.float32)+ with torch.no_grad():+ for name, p in model.named_parameters():+ if "norm" in name and p.ndim == 1:+ p.add_(torch.randn_like(p) * 0.1)+ if name.endswith("mlp.gate.weight"):+ p.normal_(0.0, 0.5) # uneven routing: a load-balancing loss far from its minimum+ if not lora:+ return model.train()+ from peft import LoraConfig, get_peft_model++ torch.manual_seed(seed + 1)+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]+ target_parameters = ["mlp.experts.gate_up_proj", "mlp.experts.down_proj", "mlp.gate.weight"]+ if not any(name.endswith("mlp.experts.gate_up_proj") for name, _ in model.named_parameters()):+ # transformers 4.x keeps the experts as a ModuleList of Linears (no fused gate_up_proj parameter).+ target_modules = (+ r".*\.(q_proj|k_proj|v_proj|o_proj|experts\.\d+\.(gate_proj|up_proj|down_proj))$"+ )+ target_parameters = ["mlp.gate.weight"]+ config = LoraConfig(+ r = 4,+ lora_alpha = 8,+ target_modules = target_modules,+ target_parameters = target_parameters,+ init_lora_weights = False,+ lora_dropout = 0.0,+ )+ return get_peft_model(model, config).train()+++def batch(+ bsz = 4,+ seq = 8,+ seed = 1,+ mask = True,+):+ g = torch.Generator().manual_seed(seed)+ ids = torch.randint(0, VOCAB, (bsz, seq), generator = g)+ labels = ids.clone()+ labels[0, :3] = -100 # uneven token counts per micro-batch: num_items normalisation matters+ attention_mask = None+ if mask:+ attention_mask = torch.ones(bsz, seq, dtype = torch.long)+ attention_mask[1, -3:] = 0 # right padding: the auxiliary loss weights tokens by the mask+ attention_mask[-1, -1:] = 0+ labels[attention_mask == 0] = -100+ return ids, labels, attention_mask+++def _chunks(t, n):+ return [None] * n if t is None else list(t.chunk(n))+++def _reference(model, ids, labels, attention_mask, n_mb, steps):+ """Gradient accumulation over the pipeline's micro-batches in one process: each forward adds+ router_aux_loss_coef x its own load-balancing loss (transformers), the CE loss is normalised by the token+ count of the whole batch."""+ params = [p for p in model.parameters() if p.requires_grad]+ opt = torch.optim.AdamW(params, lr = 1e-2, foreach = False)+ n_items = int((labels[:, 1:] != -100).sum())+ losses, auxes, grads = [], [], None+ for step in range(steps):+ total, aux_total = 0.0, 0.0+ for i, l, m in zip(ids.chunk(n_mb), labels.chunk(n_mb), _chunks(attention_mask, n_mb)):+ out = model(+ input_ids = i, labels = l, attention_mask = m, num_items_in_batch = n_items, use_cache = False+ )+ out.loss.backward()+ total += float(out.loss)+ aux_total += float(out.aux_loss) if out.aux_loss is not None else 0.0+ if step == 0:+ grads = {+ n: p.grad.detach().clone()+ for n, p in model.named_parameters()+ if p.grad is not None+ }+ opt.step()+ opt.zero_grad(set_to_none = True)+ losses.append(total)+ auxes.append(aux_total)+ return {"losses": losses, "aux": auxes, "grads": grads}+++def _group(name):+ prefix = "lora_" if "lora_" in name else ""+ if "mlp.gate." in name:+ return prefix + "router"+ if "mlp.experts" in name:+ return prefix + "experts"+ if "self_attn" in name:+ return prefix + "attention"+ return prefix + "other"+++def _case_parity(+ rank,+ world,+ tmp,+ n_mb = 2,+ schedule = "gpipe",+ mask = True,+ steps = 2,+ **build_kw,+):+ from torch.distributed.device_mesh import init_device_mesh++ ids, labels, attention_mask = batch(mask = mask)+ ref = _reference(build(**build_kw), ids, labels, attention_mask, n_mb, steps)+ out = {"ref": {k: ref[k] for k in ("losses", "aux")}}+ if build_kw.get("aux", True) and build_kw.get("coef", 0.01) >= 1.0:+ # The auxiliary loss is visible: dropping it changes the router / adapter gradients by far more than+ # the parity tolerance.+ dropped = _reference(+ build(**{**build_kw, "aux": False}), ids, labels, attention_mask, n_mb, 1+ )["grads"]+ out["aux_effect"] = max(+ float((ref["grads"][n] - g).abs().max())+ for n, g in dropped.items()+ if _group(n) in ("router", "lora_router", "lora_attention")+ )+ model = build(**build_kw)+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))["pp"]+ pp = ppn.apply_pipeline_parallel(model, mesh, n_microbatches = n_mb, schedule = schedule)+ params = pp.parameters()+ opt = torch.optim.AdamW(params, lr = 1e-2, foreach = False)+ losses, auxes, diffs, missing = [], [], {}, []+ for step in range(steps):+ loss = pp.step(ids, labels, attention_mask = attention_mask)+ if step == 0:+ for name, p in model.named_parameters():+ if not p.requires_grad:+ continue+ want = ref["grads"].get(name)+ if p.grad is None:+ if want is not None and float(want.abs().max()) > 0:+ missing.append(name)+ continue+ d = float((p.grad - want).abs().max())+ scale = float(want.abs().max())+ group = _group(name)+ prev = diffs.get(group, (0.0, 0.0, 0))+ diffs[group] = (max(prev[0], d), max(prev[1], scale), prev[2] + 1)+ opt.step()+ opt.zero_grad(set_to_none = True)+ losses.append(float(loss))+ auxes.append(float(pp.last_aux_loss) if pp.last_aux_loss is not None else None)+ out.update(losses = losses, aux = auxes, diffs = diffs, missing = missing, stage = (pp.start, pp.end))+ return out+++def _case_refusals(rank, world, tmp):+ from torch.distributed.device_mesh import init_device_mesh++ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))["pp"]+ out = {}++ def catch(key, fn):+ try:+ fn()+ out[key] = None+ except (ValueError, RuntimeError) as exc:+ out[key] = str(exc)++ catch("mixtral", lambda: ppn.apply_pipeline_parallel(build(family = "mixtral"), mesh))+ catch("olmoe", lambda: ppn.apply_pipeline_parallel(build(family = "olmoe"), mesh))++ def deepseek():+ from transformers import AutoConfig, AutoModelForCausalLM++ config = AutoConfig.from_pretrained(DEEPSEEK_V3)+ config.num_hidden_layers = 2+ ppn.apply_pipeline_parallel(AutoModelForCausalLM.from_config(config), mesh)++ catch("deepseek_v3", deepseek)+ for schedule in ("interleaved1f1b", "loopedbfs", "zbvzerobubble"):+ catch(+ schedule,+ lambda: ppn.apply_pipeline_parallel(build(), mesh, n_microbatches = 4, schedule = schedule),+ )+ # A changed transformers formula refuses instead of training on another loss.+ module = sys.modules[type(build()).__module__]+ original = module.load_balancing_loss_func+ module.load_balancing_loss_func = lambda *a, **k: original(*a, **k) * 2+ try:+ catch("formula", lambda: ppn.apply_pipeline_parallel(build(), mesh))+ finally:+ module.load_balancing_loss_func = original+ # pipeline_sharded_loading keeps refusing mixture-of-experts models.+ model = build()+ catch(+ "sharded_loading",+ lambda: ppn._refuse_unsupported(model, ppn._find_parts(model), allow_moe = False),+ )+ # pp x dp over a mixture-of-experts stage (shard_model checks it before sharding).+ pp = ppn.apply_pipeline_parallel(build(), mesh)+ dp = init_device_mesh("cpu", (world, 1), mesh_dim_names = ("pp", "dp"))["dp"]+ catch("pp_dp", lambda: ppn.check_pp_dp_composition(pp.model, dp))+ return out+++CASES = {"parity": _case_parity, "refusals": _case_refusals}+++def _worker(rank, world, port, case, tmp, kwargs):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ LOCAL_WORLD_SIZE = str(world),+ )+ import datetime++ import torch.distributed as dist++ torch.set_num_threads(2)+ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 180)+ )+ try:+ res = CASES[case](rank, world, tmp, **kwargs)+ torch.save(res, os.path.join(tmp, f"result_{rank}.pt"))+ finally:+ dist.destroy_process_group()+++def _spawn(+ case,+ world = 2,+ **kwargs,+):+ try:+ ppn._check_torch_pipelining()+ except RuntimeError as exc:+ pytest.skip(str(exc))+ from tests._rendezvous_port import free_port++ ctx = multiprocessing.get_context("spawn")+ port = free_port()+ with tempfile.TemporaryDirectory() as tmp:+ procs = [+ ctx.Process(target = _worker, args = (r, world, port, case, tmp, kwargs))+ for r in range(world)+ ]+ for p in procs:+ p.start()+ for p in procs:+ p.join(600)+ codes = [p.exitcode for p in procs]+ assert codes == [0] * world, f"rank exit codes {codes}"+ return [+ torch.load(os.path.join(tmp, f"result_{r}.pt"), weights_only = False)+ for r in range(world)+ ]+++CELLS = {+ "full_coef0.01_gpipe_mask": dict(coef = 0.01),+ "full_coef1_1f1b_mask_dense_layer": dict(coef = 1.0, schedule = "1f1b", mlp_only_layers = (1,)),+ "full_coef1_gpipe_nomask_mb4": dict(coef = 1.0, mask = False, n_mb = 4),+ "lora_coef1_gpipe_mask": dict(coef = 1.0, lora = True),+ "lora_coef0.01_1f1b_nomask": dict(coef = 0.01, lora = True, schedule = "1f1b", mask = False),+ "full_aux_off_gpipe_mask": dict(aux = False, coef = 1.0),+ "lora_aux_off_1f1b_mask": dict(aux = False, lora = True, schedule = "1f1b"),+}++[email protected]("cell", sorted(CELLS))+def test_pp2_moe_aux_matches_gradient_accumulation(cell):+ kwargs = CELLS[cell]+ results = _spawn("parity", 2, **kwargs)+ ref = results[0]["ref"]+ aux_on = kwargs.get("aux", True)+ for res in results:+ assert res["losses"] == pytest.approx(ref["losses"], rel = 1e-5, abs = 1e-6), (+ res["losses"],+ ref,+ )+ if aux_on:+ assert res["aux"] == pytest.approx(ref["aux"], rel = 1e-5, abs = 1e-6), (res["aux"], ref)+ assert min(ref["aux"]) > 0+ else:+ assert res["aux"] == [0.0, 0.0] and ref["aux"] == [0.0, 0.0]+ assert not res["missing"], res["missing"]+ for group, (diff, scale, count) in res["diffs"].items():+ assert diff <= 1e-6 + 1e-4 * scale, (cell, res["stage"], group, diff, scale)+ groups = set(results[0]["diffs"]) | set(results[1]["diffs"])+ want = {"router", "experts", "attention"}+ want = {"lora_" + g for g in want} if kwargs.get("lora") else want | {"other"}+ assert want <= groups, groups+ if "aux_effect" in results[0]:+ assert results[0]["aux_effect"] > 1e-3, results[0]["aux_effect"]+ print(cell, {r["stage"]: r["diffs"] for r in results}, results[0].get("aux_effect"))+++def test_pp2_moe_refusals_for_unproven_cases():+ out = _spawn("refusals", 2)[0]+ for key in ("mixtral", "olmoe", "deepseek_v3", "formula"):+ assert "mixture-of-experts" in (out[key] or ""), (key, out[key])+ assert "Qwen3MoeForCausalLM" in out[key], (key, out[key])+ for key in ("interleaved1f1b", "loopedbfs", "zbvzerobubble"):+ assert "'gpipe' / '1f1b'" in (out[key] or ""), (key, out[key])+ assert "pipeline_sharded_loading" in (out["sharded_loading"] or ""), out["sharded_loading"]+ assert "pp x dp" in (out["pp_dp"] or ""), out["pp_dp"]+++def test_router_statistics_sum_over_stages_to_transformers_loss():+ from transformers.models.qwen3_moe.modeling_qwen3_moe import load_balancing_loss_func++ g = torch.Generator().manual_seed(3)+ logits = tuple(torch.randn(10, 8, generator = g, requires_grad = True) for _ in range(4))+ mask = torch.ones(2, 5, dtype = torch.long)+ mask[1, 2:] = 0+ for m in (None, mask):+ want = load_balancing_loss_func(logits, 8, 2, m)+ (want_grads) = torch.autograd.grad(want, logits)+ stats = sum(ppn._router_statistics(logits[i : i + 1], 8, 2, m) for i in range(4))+ got = ppn._load_balancing_from_statistics(stats, 8)+ got_grads = torch.autograd.grad(got, logits)+ assert torch.allclose(want, got, rtol = 1e-6, atol = 1e-7)+ for a, b in zip(want_grads, got_grads):+ assert torch.allclose(a, b, rtol = 1e-5, atol = 1e-8)+++ "aux, reentrant, refused",+ [(True, True, True), (True, False, False), (False, True, False), (True, None, False)],+)+def test_aux_loss_refuses_reentrant_checkpointing(aux, reentrant, refused):+ # Failing before: reentrant checkpointing captured router logits under no_grad, so the auxiliary loss added+ # its value to the pipeline loss but no gradient.+ model = build(aux = aux)+ if reentrant is not None:+ model.gradient_checkpointing_enable(+ gradient_checkpointing_kwargs = {"use_reentrant": reentrant}+ )+ if refused:+ with pytest.raises(ValueError, match = "non-reentrant"):+ ppn._refuse_aux_with_reentrant_checkpointing(model, model.config)+ else:+ ppn._refuse_aux_with_reentrant_checkpointing(model, model.config)diff --git a/tests/test_pp_native_gloo.py b/tests/test_pp_native_gloo.pyindex dfdecf06577..3b329622a4d 100644--- a/tests/test_pp_native_gloo.py+++ b/tests/test_pp_native_gloo.py@@ -56,6 +56,7 @@ GEMMA2 = "trl-internal-testing/tiny-Gemma2ForCausalLM"GEMMA3 = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"MISTRAL = "hf-internal-testing/tiny-random-MistralForCausalLM"QWEN3_MOE = "trl-internal-testing/tiny-Qwen3MoeForCausalLM"+OLMOE = "hf-internal-testing/tiny-random-OlmoeForCausalLM"DEEPSEEK_V3 = "trl-internal-testing/tiny-DeepseekV3ForCausalLM"ARCHS = {"llama": LLAMA, "qwen3": QWEN3, "gemma2": GEMMA2, "gemma3": GEMMA3, "mistral": MISTRAL}@@ -339,7 +340,8 @@ def _case_refusals(rank, world, tmp):except (ValueError, RuntimeError) as exc:out[key] = str(exc)- catch("moe", lambda: ppn.apply_pipeline_parallel(build(QWEN3_MOE, layers = 2), mesh))+ # Qwen3-MoE carries its router auxiliary loss between stages (test_pp_moe_aux_gloo.py); OLMoE is unproven.+ catch("moe", lambda: ppn.apply_pipeline_parallel(build(OLMOE, layers = 2), mesh))catch("mla", lambda: ppn.apply_pipeline_parallel(build(DEEPSEEK_V3, layers = 2), mesh))def tied_trainable():diff --git a/unsloth/models/pp_load.py b/unsloth/models/pp_load.pyindex 197e4c6351c..39854294ba4 100644--- a/unsloth/models/pp_load.py+++ b/unsloth/models/pp_load.py@@ -140,7 +140,7 @@ def _split_for(model, mesh, schedule, config):for p, _ in flags:p.requires_grad_(False)try:- _refuse_unsupported(model, parts)+ _refuse_unsupported(model, parts, allow_moe = False)finally:for p, flag in flags:p.requires_grad_(flag)diff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.pyindex 6836d92e18b..f8580fb81b8 100644--- a/unsloth/models/pp_native.py+++ b/unsloth/models/pp_native.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport astimport collectionsimport dataclasses+import functoolsimport inspectimport mathimport re@@ -51,6 +52,15 @@ __all__ = [_PP_FLAG = "_unsloth_pp"_SCHEDULES = SCHEDULE_NAMES_MOE_CONFIG_KEYS = ("num_experts", "num_local_experts", "n_routed_experts", "moe_num_experts")+# Mixture-of-experts CausalLMs whose router auxiliary loss PipelineParallel carries between stages: every stage+# adds its layers' load-balancing statistics to the ones it received and the last stage forms the loss+# (tests/test_pp_moe_aux_gloo.py proves each against one process). Every other MoE family stays refused.+_PP_MOE_AUX_FAMILIES = ("Qwen3MoeForCausalLM",)+_PP_MOE_AUX_SCHEDULES = ("gpipe", "1f1b")+_PP_MOE_COMPOSED = (+ "Unsloth: pipeline parallelism carries the mixture-of-experts router auxiliary loss on a pp-only mesh; "+ "pp x dp / pp x tp over a mixture-of-experts model is not supported yet."+)# Layers reading another layer's state, or extra per-layer inputs: a stage boundary would cut them._CROSS_LAYER_CONFIG_KEYS = ("num_kv_shared_layers",@@ -243,6 +253,8 @@ def check_pp_dp_composition(model, dp_mesh):)if stage.stages_per_rank > 1:raise ValueError(_MULTI_STAGE_DP)+ if stage.ctx.moe is not None:+ raise ValueError(_PP_MOE_COMPOSED)if dp_mesh is None:raise ValueError("Unsloth: native FSDP2 over a pipeline parallel model needs FSDP2Config(mesh = mesh['dp']), the "@@ -427,7 +439,158 @@ def _check_loss_normalization(inner):)-def _refuse_unsupported(model, parts):+class _MoEAux:+ """How a stage collects its routers' logits and forms the load-balancing loss (_moe_aux_plan)."""++ owner: (+ nn.Module+ ) # the CausalLM (num_experts, num_experts_per_tok, router_aux_loss_coef, config)+ router_class: type # the module whose output[index] is a layer's router logits+ index: int+ num_experts: int+ routers: dict = dataclasses.field(default_factory = dict) # {decoder layer: routers in it}+++def _moe_marker(text, layers):+ """Why the model counts as mixture-of-experts (a config key / an experts module), else None."""+ for key in _MOE_CONFIG_KEYS:+ value = getattr(text, key, None)+ if isinstance(value, int) and value > 0:+ return f"{key} = {value}"+ for name, module in layers.named_modules():+ leaf = name.rsplit(".", 1)[-1]+ cls = type(module).__name__+ if leaf == "experts" or "Experts" in cls or "SparseMoe" in cls or "MoE" in cls:+ return f"{name}: {cls}"+ return None+++def _router_statistics(+ logits,+ num_experts,+ top_k,+ attention_mask = None,+):+ """float32 [2 E + 1]: per-expert top-k assignments, per-expert routing probability sums (differentiable)+ and the row count over `logits` (router logits of several layers), weighted by the 2-D attention mask as+ transformers' load_balancing_loss_func weights them. Summed over all layers, they give that loss."""+ device = (+ logits[0].device+ if logits+ else (attention_mask.device if attention_mask is not None else None)+ )+ counts = torch.zeros(num_experts, dtype = torch.float32, device = device)+ probs = torch.zeros(num_experts, dtype = torch.float32, device = device)+ rows = torch.zeros((), dtype = torch.float32, device = device)+ flat = None+ if attention_mask is not None:+ if attention_mask.dim() != 2:+ raise ValueError(+ "Unsloth: pipeline parallelism over a mixture-of-experts model takes a 2-D attention_mask "+ f"(the router auxiliary loss weights tokens by it), got {tuple(attention_mask.shape)}."+ )+ flat = attention_mask.reshape(-1).to(device = device, dtype = torch.float32)+ for gate in logits:+ weights = torch.nn.functional.softmax(gate.to(device), dim = -1)+ _, selected = torch.topk(weights, top_k, dim = -1)+ if flat is None:+ counts = counts + torch.bincount(selected.reshape(-1), minlength = num_experts).float()+ probs = probs + weights.float().sum(dim = 0)+ rows = rows + weights.shape[0]+ else:+ if weights.shape[0] != flat.numel():+ raise ValueError(+ f"Unsloth: router logits have {weights.shape[0]} rows but the attention_mask "+ f"{flat.numel()} tokens."+ )+ counts = counts + torch.zeros(+ num_experts, dtype = torch.float32, device = device+ ).scatter_add_(0, selected.reshape(-1), flat.repeat_interleave(top_k))+ probs = probs + (weights.float() * flat.unsqueeze(-1)).sum(dim = 0)+ rows = rows + flat.sum()+ return torch.cat([counts, probs, rows.reshape(1)])+++def _load_balancing_from_statistics(stats, num_experts):+ counts, probs, rows = stats[:num_experts], stats[num_experts : 2 * num_experts], stats[-1]+ return torch.sum((counts / rows) * (probs / rows)) * num_experts+++def _statistics_match_transformers(module, num_experts, top_k):+ """The family's own load_balancing_loss_func equals the loss formed from per-stage statistics on random+ router logits (with and without a padding mask): a transformers change to the formula refuses instead of+ training on a different loss."""+ reference = getattr(sys.modules.get(module), "load_balancing_loss_func", None)+ if not callable(reference):+ return False+ g = torch.Generator().manual_seed(0)+ logits = tuple(torch.randn(6, num_experts, generator = g) for _ in range(3))+ mask = torch.tensor([[1, 1, 1], [1, 0, 0]])+ try:+ for m in (None, mask):+ expected = reference(logits, num_experts, top_k, m)+ stats = _router_statistics(logits[:1], num_experts, top_k, m) + _router_statistics(+ logits[1:], num_experts, top_k, m+ )+ got = _load_balancing_from_statistics(stats, num_experts)+ if not torch.allclose(torch.as_tensor(expected).float(), got, rtol = 1e-5, atol = 1e-6):+ return False+ except Exception:+ return False+ return True+++def _moe_aux_plan(parts):+ """_MoEAux for a family in _PP_MOE_AUX_FAMILIES whose decoder records router logits with a transformers+ OutputRecorder and whose load_balancing_loss_func is the statistics form; None otherwise (refused)."""+ inner = parts.inner+ if type(inner).__name__ not in _PP_MOE_AUX_FAMILIES:+ return None+ recorder = (getattr(type(parts.decoder), "_can_record_outputs", None) or {}).get(+ "router_logits"+ )+ router_class = getattr(recorder, "target_class", None)+ index = getattr(recorder, "index", None)+ if (+ not isinstance(router_class, type)+ or not isinstance(index, int)+ or getattr(recorder, "layer_name", None)+ ):+ return None+ num_experts = getattr(inner, "num_experts", None)+ top_k = getattr(inner, "num_experts_per_tok", None)+ if (+ not isinstance(num_experts, int)+ or not isinstance(top_k, int)+ or not 0 < top_k <= num_experts+ ):+ return None+ routers = {}+ for i, layer in enumerate(parts.layers):+ count = sum(isinstance(m, router_class) for m in layer.modules())+ if count:+ routers[i] = count+ if not routers or not _statistics_match_transformers(+ type(inner).__module__, num_experts, top_k+ ):+ return None+ return _MoEAux(inner, router_class, index, num_experts, routers)+++def _record_router(ctx, module, args, output):+ if ctx.router_logits is not None: # inside this stage's forward (not a checkpoint recompute)+ index = ctx.moe.index+ ctx.router_logits.append(output[index] if isinstance(output, (tuple, list)) else output)+++def _refuse_unsupported(+ model,+ parts,+ allow_moe = True,+):+ """Refusals before anything is cut. Returns the _MoEAux of a mixture-of-experts family whose router+ auxiliary loss PipelineParallel carries (allow_moe), else None."""text = _text_config(model)inner = parts.innerconfig = getattr(inner, "config", None)@@ -437,13 +600,21 @@ def _refuse_unsupported(model, parts):f"Unsloth: pipeline parallelism v1 supports text decoders only ({type(inner).__name__} has "f"{key}). Use native FSDP2 (UNSLOTH_FSDP2=1) instead.")- for key in _MOE_CONFIG_KEYS:- value = getattr(text, key, None)- if isinstance(value, int) and value > 0:+ moe = None+ marker = _moe_marker(text, parts.layers)+ if marker is not None:+ moe = _moe_aux_plan(parts) if allow_moe else None+ if moe is None:+ how = (+ "pipeline_sharded_loading does not load mixture-of-experts models yet (load the whole model, "+ "then apply_pipeline_parallel)"+ if allow_moe is False and type(inner).__name__ in _PP_MOE_AUX_FAMILIES+ else "the router auxiliary loss is carried between stages only for "+ f"{', '.join(_PP_MOE_AUX_FAMILIES)} (transformers 5.x); {type(inner).__name__} is not proven"+ )raise ValueError(- f"Unsloth: pipeline parallelism v1 does not support mixture-of-experts models ({key} = "- f"{value}): the router auxiliary loss is not carried between stages. Use native FSDP2 "- "(UNSLOTH_FSDP2=1) instead."+ f"Unsloth: pipeline parallelism v1 does not support this mixture-of-experts model ({marker}): "+ f"{how}. Use native FSDP2 (UNSLOTH_FSDP2=1) instead.")for key in _CROSS_LAYER_CONFIG_KEYS:value = getattr(text, key, None)@@ -465,13 +636,6 @@ def _refuse_unsupported(model, parts):"Unsloth: pipeline parallelism v1 needs one decoder layer class, got "f"{sorted(classes)} (non-homogeneous stacks are v2).")- for name, module in parts.layers.named_modules():- leaf = name.rsplit(".", 1)[-1]- cls = type(module).__name__- if leaf == "experts" or "Experts" in cls or "SparseMoe" in cls or "MoE" in cls:- raise ValueError(- f"Unsloth: pipeline parallelism v1 does not support mixture-of-experts layers ({name}: {cls})."- )for m in _model_chain(model):if m.__dict__.get("_unsloth_tp") is not None:raise ValueError(@@ -503,6 +667,7 @@ def _refuse_unsupported(model, parts):"last stage would each update their own copy). Freeze them, or untie them before splitting.")_check_loss_normalization(inner)+ return moe# ---------------------------------------------------------------------------------- layer call format@@ -759,6 +924,11 @@ class _StageContext:# The step's token count, given to every stage forward from here rather than as a schedule kwarg:# a non-tensor kwarg reaches torch's split backward (zero bubble) as a stage input on torch < 2.13.self.num_items_in_batch = None+ # Mixture-of-experts router auxiliary loss carry (_MoEAux), the router logits of the running stage+ # forward, and the last stage's per-micro-batch auxiliary losses of the step.+ self.moe = None+ self.router_logits = None+ self.aux_losses = []def configure(self, start, end, is_first, is_last):"""The stage about to run (several stages of one rank share this context, one runs at a time)."""@@ -803,34 +973,64 @@ class _PPStageModule(nn.Module):self.__dict__["_pp_warned"] = Falseself.__dict__["_pp_stage"] = stage- def forward(self, x, **kwargs):+ def forward(self, x, *carry, **kwargs):stage = self._pp_stageif stage is None:- return self._stage_forward(x, **kwargs)+ return self._stage_forward(x, *carry, **kwargs)start, end, is_first, is_last, swaps = stageself._pp_ctx.configure(start, end, is_first, is_last)originals = [(container, key, container._modules[key]) for container, key, _ in swaps]for container, key, stand_in in swaps:container._modules[key] = stand_intry:- return self._stage_forward(x, **kwargs)+ return self._stage_forward(x, *carry, **kwargs)finally:for container, key, original in originals:container._modules[key] = original- def _stage_forward(self, x, **kwargs):+ def _router_statistics(self, captured, carry, attention_mask, device):+ """This stage's load-balancing statistics added to the received ones (`carry`, from the previous+ stage), or None when the auxiliary loss is off (config.output_router_logits)."""+ ctx = self._pp_ctx+ moe = ctx.moe+ if not getattr(moe.owner.config, "output_router_logits", False):+ return None+ if torch.is_grad_enabled(): # checkpointing can be turned on after the split+ _refuse_aux_with_reentrant_checkpointing(self, moe.owner.config)+ expected = sum(moe.routers.get(i, 0) for i in range(ctx.start, ctx.end))+ if len(captured) != expected:+ raise RuntimeError(+ f"Unsloth: pipeline stage layers [{ctx.start}, {ctx.end}) ran {len(captured)} "+ f"{moe.router_class.__name__} routers, expected {expected}: the router auxiliary loss "+ "would miss some of them (a forward that bypasses the router module)."+ )+ stats = _router_statistics(+ captured, moe.num_experts, int(moe.owner.num_experts_per_tok), attention_mask+ )+ if stats.device != device:+ stats = stats.to(device)+ return stats + carry[0] if carry else stats++ def _stage_forward(self, x, *carry, **kwargs):ctx = self._pp_ctx+ moe = ctx.moeif ctx.is_first:input_ids = xelse:input_ids = torch.zeros(x.shape[:2], dtype = torch.long, device = x.device)ctx.stage_input = xctx.active = True+ captured = Nonetry:# Pass-through layers return hidden states only: no per-layer attentions / hidden states.kwargs.update(output_attentions = False, output_hidden_states = False)if ctx.num_items_in_batch is not None:kwargs["num_items_in_batch"] = ctx.num_items_in_batch+ if moe is not None:+ # The model would add an auxiliary loss over the last stage's routers only: it is formed+ # here from every stage's statistics instead.+ kwargs["output_router_logits"] = False+ ctx.router_logits = []out = self.model(input_ids = input_ids, use_cache = False, **kwargs)except _StageOutput as stop:hidden = stop.hidden@@ -848,10 +1048,25 @@ class _PPStageModule(nn.Module):stacklevel = 2,)hidden = hidden.to(self._pp_dtype)- return hidden+ if moe is None:+ return hidden+ stats = self._router_statistics(+ ctx.router_logits, carry, kwargs.get("attention_mask"), hidden.device+ )+ if stats is None: # auxiliary loss off: nothing to carry (a zero placeholder)+ if carry:+ # Still tied to the received carry: torch 2.10 / 2.11 pipelining needs a gradient for every+ # received input (a zero one here).+ stats = carry[0].to(hidden.device) * 0+ else:+ stats = torch.zeros(+ 2 * moe.num_experts + 1, dtype = torch.float32, device = hidden.device+ )+ return hidden, statsfinally:ctx.active = Falsectx.stage_input = None+ captured, ctx.router_logits = ctx.router_logits, Noneif not ctx.is_last:raise RuntimeError("Unsloth: a pipeline stage finished its forward without reaching its boundary."@@ -861,6 +1076,18 @@ class _PPStageModule(nn.Module):loss = out[0]if not isinstance(loss, torch.Tensor) or loss.dim() != 0:raise RuntimeError("Unsloth: the last pipeline stage needs labels to return a loss.")+ if moe is not None:+ stats = self._router_statistics(+ captured, carry, kwargs.get("attention_mask"), loss.device+ )+ if stats is not None:+ # transformers' CausalLM forward: loss += router_aux_loss_coef * load_balancing_loss.+ aux = _load_balancing_from_statistics(stats, moe.num_experts)+ ctx.aux_losses.append(aux.detach())+ loss = loss + moe.owner.router_aux_loss_coef * aux.to(loss.device)+ elif carry:+ # Auxiliary loss off: a zero term keeps the received carry in the graph (see the stage return).+ loss = loss + 0 * carry[0].sum().to(loss.device)return loss@@ -903,6 +1130,21 @@ def _check_torch_pipelining():)+def _refuse_aux_with_reentrant_checkpointing(model, config):+ """Reentrant checkpointing (transformers' default, Unsloth smart checkpointing) runs the first layer forward+ under no_grad, so the captured router logits carry no graph and the auxiliary loss would add its value but+ no gradient."""+ if not getattr(config, "output_router_logits", False):+ return+ if non_reentrant_checkpointing_only(model) is False:+ raise ValueError(+ "Unsloth: pipeline parallelism carries the router auxiliary loss only with gradient checkpointing "+ "off or torch's non-reentrant checkpointing (gradient_checkpointing_kwargs = {'use_reentrant': "+ "False}); reentrant checkpointing would drop its gradient. Or set config.output_router_logits = "+ "False to train without the auxiliary loss."+ )++def _check_schedule(model, spec, props):"""Refusals for the schedule `spec` whose compute order has `props` (pp_schedules.validate_schedule)."""if (@@ -1021,6 +1263,7 @@ class PipelineParallel:)self._mb_losses = []self._loss_multiplier = 1+ self.last_aux_loss = None # mixture-of-experts models: the step's router auxiliary lossself.dp_mesh = None # set by shard_model (FSDP2 over the data parallel dimension)# composition with FSDP2 (dp) / tensor parallelism (tp): every other mesh dimension must be applied@@ -1145,6 +1388,7 @@ class PipelineParallel:return self._shapes[key]device = self.devicehidden = (mb, seq, self.hidden_size)+ moe = self.ctx.moestages = []for index, module in zip(self.local_stages, self.stage_modules):if index == 0:@@ -1162,6 +1406,19 @@ class PipelineParallel:example_out = torch.empty(hidden, dtype = self.activation_dtype, device = "meta", requires_grad = True)+ if moe is not None:+ # The router load-balancing statistics travel with the hidden states (gradient back to+ # every stage's routers).+ stats = torch.empty(+ (2 * moe.num_experts + 1,),+ dtype = torch.float32,+ device = "meta",+ requires_grad = True,+ )+ if index != 0:+ example_in = (example_in, stats)+ if index != self.total_stages - 1:+ example_out = (example_out, stats)stages.append(PipelineStage(module,@@ -1198,12 +1455,20 @@ class PipelineParallel:optimizer.zero_grad between steps). Returns the batch loss (sum over tokens / num_items_in_batch,unscaled) on every rank.+ A mixture-of-experts model with config.output_router_logits adds router_aux_loss_coef x the+ load-balancing loss of each micro-batch (over all stages' routers), as gradient accumulation over the+ same micro-batches does in one process; their sum (without the coefficient) is in last_aux_loss.+With FSDP2 over a dp mesh, each dp replica passes its own slice of the global batch (pp / tp peers thesame one); num_items_in_batch is the token count of the whole global batch (default: this slice'scount summed over dp) and the returned loss is the global batch loss."""import torch.distributed as distself._check_composed()+ if self.ctx.moe is not None and (+ self.composed or self.dp_mesh is not None or self.tp_mesh is not None+ ):+ raise ValueError(_PP_MOE_COMPOSED)unknown = sorted(set(kwargs) - set(_STEP_KWARGS))if unknown:raise ValueError(@@ -1264,6 +1529,7 @@ class PipelineParallel:self._bind_scaler(scaler)self._step_scaler = scaler if scaler is not None and scaler.is_enabled() else Noneself._mb_losses = []+ self.ctx.aux_losses = []args = (input_ids.to(device),) if self.is_first else ()target = step_kwargs["labels"] if self.is_last else Nonetry:@@ -1280,12 +1546,21 @@ class PipelineParallel:)total = torch.stack([l.float() for l in self._mb_losses]).sum().reshape(1).to(device)self._mb_losses = []+ if self.ctx.moe is not None:+ aux = [a.float().reshape(1).to(device) for a in self.ctx.aux_losses]+ aux = torch.cat(aux).sum() if aux else torch.zeros((), device = device)+ total = torch.cat([total, aux.reshape(1)])else:- total = torch.zeros(1, dtype = torch.float32, device = device)+ total = torch.zeros(1 + (self.ctx.moe is not None), dtype = torch.float32, device = device)+ self.ctx.aux_losses = []if self.num_stages > 1:dist.broadcast(total, src = self._last_global_rank, group = self.group)if dp_group is not None:dist.all_reduce(total, group = dp_group) # each replica's sum / global tokens+ if self.ctx.moe is not None:+ # Sum over micro-batches of the router load-balancing loss (unscaled by router_aux_loss_coef;+ # 0 with config.output_router_logits off). The returned loss already holds coef x this.+ self.last_aux_loss = total[1]return total[0]def _average_replicated_grads(self):@@ -1658,7 +1933,15 @@ def apply_pipeline_parallel(f"Unsloth: the 1F1B schedule needs n_microbatches >= stages ({n_microbatches} < {pp}).")parts = _find_parts(model)- _refuse_unsupported(model, parts)+ moe = _refuse_unsupported(model, parts)+ if moe is not None and (schedule not in _PP_MOE_AUX_SCHEDULES or stages_per_rank != 1):+ raise ValueError(+ f"Unsloth: pipeline parallelism over a mixture-of-experts model ({type(parts.inner).__name__}) "+ f"carries the router auxiliary loss with schedule = {' / '.join(map(repr, _PP_MOE_AUX_SCHEDULES))} "+ f"(one stage per rank) only; got {schedule!r} with {stages_per_rank} stages per rank."+ )+ if moe is not None:+ _refuse_aux_with_reentrant_checkpointing(model, moe.owner.config)total_stages = pp * stages_per_rankrank = pp_mesh.get_local_rank()if stages_per_rank > 1:@@ -1711,6 +1994,13 @@ def apply_pipeline_parallel(start, end = bounds[local[0]]is_first, is_last = pp_stage.is_first, pp_stage.is_lastlayers = parts.layers+ if moe is not None:+ # This stage's routers report their logits into the context while its forward runs.+ pp_stage.ctx.moe = moe+ for i in owned:+ for module in layers[i].modules():+ if isinstance(module, moe.router_class):+ module.register_forward_hook(functools.partial(_record_router, pp_stage.ctx))for i in range(len(layers)):if i not in owned:layers[i] = _PPPassThrough(i, pp_stage.ctx, layers[i])diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex a5d357fb478..49784dece51 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -1983,6 +1983,9 @@ def _check_pp_tp_composition(model, tp_mesh):"Unsloth: tensor parallelism does not compose with Unsloth pipeline parallelism ""(apply_pipeline_parallel) here: pass the model apply_pipeline_parallel was given.")+ if stage.ctx.moe is not None:+ from .pp_native import _PP_MOE_COMPOSED+ raise ValueError(_PP_MOE_COMPOSED)if stage.dp_mesh is not None:raise ValueError("Unsloth: apply_tensor_parallel must come before shard_model on a pipeline parallel model "