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 x native FSDP2 data parallel x tensor parallel for dense decoders (#15204)
Daniel Han85234fe37cde
diff --git a/tests/test_pp_fsdp2_gloo.py b/tests/test_pp_fsdp2_gloo.pynew file mode 100644index 00000000000..28ae49e3701--- /dev/null+++ b/tests/test_pp_fsdp2_gloo.py@@ -0,0 +1,560 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Pipeline parallel composed with native FSDP2 data parallel and / or tensor parallel on a gloo CPU world+(pp 2 x dp 2, pp 2 x tp 2, pp 2 x dp 2 x tp 2) vs the same model in one process on the global batch, fp32."""++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 socket # noqa: E402+import sys # noqa: E402+import tempfile # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_pp_native_gloo import _clip_fp64, ppn # noqa: E402+from test_tp_native_oracle import tpn # noqa: E402++LLAMA = "hf-internal-testing/tiny-random-LlamaForCausalLM"+QWEN3 = "trl-internal-testing/tiny-Qwen3ForCausalLM"+GEMMA3 = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"+# Overrides so the head counts split over tp = 2 (as the TP suite).+ARCHS = {+ "llama": (LLAMA, {}),+ "qwen3": (QWEN3, {}),+ "gemma3": (GEMMA3, {"num_attention_heads": 4, "num_key_value_heads": 2}),+}+N_LAYERS = 6+STEPS = 3+# Step-0 grad norm tolerance vs the one-process reference. Gemma3's own fp32 grad norm sits 1.0e-4 from fp64 on one+# process (Llama 7.8e-7), so any change of summation order (TP splits, CPU ISA) moves it by that much.+STEP0_NORM_REL = {"llama": 1e-5, "qwen3": 1e-5, "gemma3": 3e-4}+++def _native():+ module = sys.modules.get("unsloth.models.fsdp2_native")+ if module is None:+ from test_fsdp2_native_units import _load_native+ module = _load_native()+ return module+++def build(+ repo,+ overrides = None,+ seed = 0,+):+ from peft import LoraConfig, get_peft_model+ from transformers import AutoConfig, AutoModelForCausalLM++ probe = AutoConfig.from_pretrained(repo)+ values = probe.to_dict()+ values["num_hidden_layers"] = N_LAYERS+ values.pop("layer_types", None)+ config = type(probe).from_dict(values)+ text = config.get_text_config()+ for key, value in (overrides or {}).items():+ setattr(text, key, value)+ for key in ("attention_dropout", "hidden_dropout", "dropout"):+ if isinstance(getattr(text, key, None), float):+ setattr(text, key, 0.0)+ config._attn_implementation = "eager"+ torch.manual_seed(seed)+ model = AutoModelForCausalLM.from_config(config, torch_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)+ torch.manual_seed(seed + 1)+ lora = LoraConfig(+ r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False, lora_dropout = 0.0+ )+ return get_peft_model(model, lora).train()+++def global_batch(+ model,+ bsz,+ seq = 8,+ seed = 1,+):+ vocab = ppn._text_config(model).vocab_size+ 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 dp replica / micro-batch: the global count matters+ labels[-1, -2:] = -100+ labels[1, -1] = -100+ return ids, labels+++def _reference(model, ids, labels, steps):+ params = [p for p in model.parameters() if p.requires_grad]+ opt = torch.optim.AdamW(params, lr = 1e-2, foreach = False)+ losses, norms, grads = [], [], None+ for step in range(steps):+ out = model(input_ids = ids, labels = labels, use_cache = False)+ out.loss.backward()+ if step == 0:+ grads = {+ n: p.grad.detach().clone()+ for n, p in model.named_parameters()+ if p.grad is not None+ }+ norms.append(_clip_fp64(params, 1.0))+ opt.step()+ opt.zero_grad(set_to_none = True)+ losses.append(float(out.loss))+ return {"losses": losses, "norms": norms, "grads": grads}+++def _trainable_param_groups(model, trainable = True):+ from torch.distributed.fsdp import FSDPModule++ groups = []+ for m in model.modules():+ if isinstance(m, FSDPModule):+ state = m._get_fsdp_state()+ found = getattr(state, "_fsdp_param_groups", None)+ if found is None:+ group = getattr(state, "_fsdp_param_group", None)+ found = [group] if group is not None else []+ for group in found:+ if not trainable or any(fp.sharded_param.requires_grad for fp in group.fsdp_params):+ groups.append(group)+ return groups+++def _count_reduces():+ """Wrap FSDP2's gradient reduce (one call per param group per synced backward)."""+ import torch.distributed.fsdp._fully_shard._fsdp_param_group as pg++ calls = [0]+ original = pg.foreach_reduce++ def counted(*args, **kwargs):+ calls[0] += 1+ return original(*args, **kwargs)++ pg.foreach_reduce = counted+ return calls+++def _raised(fn):+ try:+ fn()+ except (ValueError, RuntimeError) as exc:+ return str(exc)+ return None+++def _case_compose(+ rank,+ world,+ tmp,+ arch,+ dims,+ schedule = "gpipe",+ n_mb = 2,+ fit_layout = None,+ rows = 4,+):+ """apply_pipeline_parallel over mesh['pp'], then apply_tensor_parallel over mesh['tp'] and / or shard_model+ over mesh['dp']. Each dp replica trains on its rows of the global batch."""+ import torch.distributed as dist+ from safetensors.torch import load_file+ from torch.distributed.device_mesh import init_device_mesh++ native = _native()+ repo, overrides = ARCHS[arch]+ names = tuple(dims)+ mesh = init_device_mesh("cpu", tuple(dims.values()), mesh_dim_names = names)+ dp = dims.get("dp", 1)+ dp_rank = mesh["dp"].get_local_rank() if "dp" in dims else 0+ ref = build(repo, overrides)+ ids, labels = global_batch(ref, rows * dp)+ ref_res = _reference(ref, ids, labels, STEPS)+ if rank == 0:+ ref.save_pretrained(os.path.join(tmp, "ref"))+ mine = slice(rows * dp_rank, rows * (dp_rank + 1))+ model = build(repo, overrides)+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = n_mb, schedule = schedule)+ refusals = {}+ if (+ world != dims["pp"]+ ): # a pp mesh smaller than the world: the other dimensions must be applied first+ refusals["step_before_all_dims"] = _raised(lambda: pp.step(ids[mine], labels[mine]))+ if "tp" in dims:+ tpn.apply_tensor_parallel(model, mesh["tp"])+ if "dp" in dims:+ refusals["shard_model_pp_mesh"] = _raised(+ lambda: native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["pp"])+ )+ )+ refusals["shard_model_no_mesh"] = _raised(+ lambda: native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ )+ refusals["shard_model_inner_level"] = _raised(+ lambda: native.shard_model(+ model.base_model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"])+ )+ )+ refusals["shard_model_cpu_offload"] = _raised(+ lambda: native.shard_model(+ model,+ native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"], cpu_offload = True),+ )+ )+ refusals["fsdp_after_refusals"] = sum(+ type(m).__name__.startswith("FSDP") for m in model.modules()+ )+ native.shard_model(+ model,+ native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"], fit_layout = fit_layout),+ )+ from torch.distributed.fsdp import FSDPModule++ layouts = tpn._param_layouts(model)+ groups = _trainable_param_groups(model)+ calls = _count_reduces()+ params = pp.parameters()+ opt = torch.optim.AdamW(params, lr = 1e-2, foreach = False)+ losses, norms, reduces, grads = [], [], [], None+ for step in range(STEPS):+ before = calls[0]+ loss = pp.step(ids[mine], labels[mine])+ reduces.append(calls[0] - before)+ if step == 0:+ grads = {+ n: tpn._full(p.grad, layout = layouts.get(id(p))).detach().clone()+ for n, p in model.named_parameters()+ if p.grad is not None+ }+ norms.append(float(pp.clip_grad_norm_(1.0)))+ opt.step()+ opt.zero_grad(set_to_none = True)+ losses.append(float(loss))+ pp.save_adapter(os.path.join(tmp, "pp"))+ dist.barrier()+ placements = {+ n: tuple(str(pl) for pl in p.placements)+ for n, p in model.named_parameters()+ if p.requires_grad and tpn._is_dtensor(p)+ }+ return {+ "ref": ref_res,+ "losses": losses,+ "norms": norms,+ "grads": grads,+ "owned": {n for n, p in model.named_parameters() if p.requires_grad},+ "reduces": reduces,+ "groups": len(groups),+ # torchtitan's PP default: no unit reshards after forward (each micro-batch would all-gather again).+ "reshard_after_forward": [+ g.post_forward_mesh_info is not None+ for g in _trainable_param_groups(model, trainable = False)+ ],+ "stage_root_fsdp": isinstance(pp.module, FSDPModule),+ "placements": placements,+ "refusals": refusals,+ "stage": pp.stage_index,+ "saved_ref": load_file(os.path.join(tmp, "ref", "adapter_model.safetensors"))+ if rank == 0+ else None,+ "saved_pp": load_file(os.path.join(tmp, "pp", "adapter_model.safetensors"))+ if rank == 0+ else None,+ }+++def _case_scaler(rank, world, tmp):+ """pp 2 x dp 2: an inf on one rank's (last stage, dp replica 1) gradient skips the step on every rank."""+ from torch.distributed.device_mesh import init_device_mesh++ native = _native()+ mesh = init_device_mesh("cpu", (2, 2), mesh_dim_names = ("pp", "dp"))+ model = build(LLAMA)+ ids, labels = global_batch(model, 8)+ dp_rank = mesh["dp"].get_local_rank()+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"]))+ scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)+ opt = torch.optim.SGD(pp.parameters(), lr = 1.0)+ pp.step(+ ids[4 * dp_rank : 4 * dp_rank + 4], labels[4 * dp_rank : 4 * dp_rank + 4], scaler = scaler+ )+ if rank == world - 1:+ # One rank (last stage, dp replica 1) finds an inf in its unscale (as a replicated gradient would);+ # set on its found_inf directly: an inf in a DTensor shard is already reduced over dp by GradScaler.+ unscale = scaler.unscale_++ def unscale_with_inf(optimizer):+ unscale(optimizer)+ for t in scaler._per_optimizer_states[id(optimizer)]["found_inf_per_device"].values():+ t.fill_(1.0)++ scaler.unscale_ = unscale_with_inf+ before = [tpn._local(p).detach().clone() for p in pp.parameters()]+ pp.unscale_(scaler, opt)+ scaler.step(opt)+ scaler.update()+ after = [tpn._local(p).detach().clone() for p in pp.parameters()]+ return {+ "unchanged": all(torch.equal(a, b) for a, b in zip(before, after)),+ "scale": scaler.get_scale(),+ }+++def _case_order_refusals(rank, world, tmp):+ """TP or FSDP2 before the pipeline split, and a non-composable pp mesh, are refused before any change."""+ from torch.distributed.device_mesh import init_device_mesh++ native = _native()+ mesh = init_device_mesh("cpu", (2, 2), mesh_dim_names = ("pp", "dp"))+ out = {}+ model = build(LLAMA)+ tpn.apply_tensor_parallel(model, mesh["dp"])+ layers = len(model.get_base_model().model.layers)+ out["tp_first"] = _raised(lambda: ppn.apply_pipeline_parallel(model, mesh["pp"]))+ out["tp_first_unchanged"] = not ppn.is_pipeline_parallel(model) and layers == N_LAYERS+ model = build(LLAMA)+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"]))+ out["fsdp_first"] = _raised(lambda: ppn.apply_pipeline_parallel(model, mesh["pp"]))+ out["fsdp_first_unchanged"] = not ppn.is_pipeline_parallel(model)+ # pp mesh over all 4 ranks = world: a plain v1 split; a 2-D mesh is refused.+ model = build(LLAMA)+ out["mesh_2d"] = _raised(lambda: ppn.apply_pipeline_parallel(model, mesh))+ # pp x dp: TP after shard_model is refused.+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"])+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"]))+ out["tp_after_fsdp"] = _raised(lambda: tpn.apply_tensor_parallel(model, mesh["dp"]))+ out["shard_twice_is_noop"] = native.shard_model(model) is model+ out["composed"] = pp.composed+ return out+++def _case_pp_tp_mesh_refusal(rank, world, tmp):+ """pp 2 x tp 2: a tp mesh that is the pp mesh itself is refused before anything is sharded."""+ from torch.distributed.device_mesh import init_device_mesh++ mesh = init_device_mesh("cpu", (2, 2), mesh_dim_names = ("pp", "tp"))+ model = build(LLAMA)+ ppn.apply_pipeline_parallel(model, mesh["pp"])+ err = _raised(lambda: tpn.apply_tensor_parallel(model, mesh["pp"]))+ return {"err": err, "tp": tpn.is_tensor_parallel(model)}+++CASES = {+ "compose": _case_compose,+ "scaler": _case_scaler,+ "order": _case_order_refusals,+ "pp_tp_mesh": _case_pp_tp_mesh_refusal,+}+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++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(1)+ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 240)+ )+ 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 = 4,+ **kwargs,+):+ try:+ ppn._check_torch_pipelining()+ except RuntimeError as exc:+ pytest.skip(str(exc))+ native = _native()+ if not native._supports_ignored_params(native._fsdp_api()[2]):+ pytest.skip("native FSDP2 composition needs fully_shard(ignored_params) (torch 2.7+)")+ 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(900)+ 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)+ ]+++def _check(+ results,+ dims,+ n_mb = 2,+ norm_rel = 1e-5,+):+ ref = results[0]["ref"]+ union = set()+ for rank, res in enumerate(results):+ assert res["losses"] == pytest.approx(ref["losses"], rel = 1e-5, abs = 1e-6), (+ rank,+ res["losses"],+ ref["losses"],+ )+ assert res["norms"][0] == pytest.approx(ref["norms"][0], rel = norm_rel), (+ rank,+ res["norms"],+ ref["norms"],+ )+ # Later norms follow 1-2 AdamW steps (lr 1e-2), whose first updates are ~lr * sign(grad): fp32 summation+ # order on near-zero grads moves them up to ~5e-4 (Gemma3; the pp-only split alone moves it 2.6e-4).+ assert res["norms"] == pytest.approx(ref["norms"], rel = 2e-3), (+ rank,+ res["norms"],+ ref["norms"],+ )+ assert set(res["grads"]) == res["owned"], sorted(set(res["grads"]) ^ res["owned"])[:6]+ num = den = 0.0+ for name, grad in res["grads"].items():+ want = ref["grads"][name]+ # Tensor parallel row-parallel sums reorder fp32 additions: tolerance relative to the tensor's scale.+ atol = max(1e-6, 2e-5 * float(want.abs().max()))+ torch.testing.assert_close(grad, want, rtol = 1e-4, atol = atol, msg = name)+ num += float((grad.double() - want.double()).square().sum())+ den += float(want.double().square().sum())+ assert (num / den) ** 0.5 < 5e-5, (rank, (num / den) ** 0.5)+ union |= set(res["grads"])+ refusals = res["refusals"]+ if len(results) != dims["pp"]:+ assert "Apply the other mesh dimensions" in (+ refusals["step_before_all_dims"] or ""+ ), refusals+ if "dp" in dims:+ assert res["stage_root_fsdp"]+ # FSDP2 shards the trainable weights over dp; each group reduces once per step, not per micro-batch.+ assert res["placements"] and all(+ any("S(" in pl or "Shard" in pl for pl in pls) for pls in res["placements"].values()+ ), res["placements"]+ assert res["groups"] >= 1 and res["reduces"] == [res["groups"]] * STEPS, (+ res["reduces"],+ res["groups"],+ )+ assert res["reshard_after_forward"] and not any(res["reshard_after_forward"]), res[+ "reshard_after_forward"+ ]+ assert "meeting only at this rank" in (refusals["shard_model_pp_mesh"] or ""), refusals+ assert "needs FSDP2Config(mesh = mesh['dp'])" in (+ refusals["shard_model_no_mesh"] or ""+ ), refusals+ assert "not a level inside it" in (refusals["shard_model_inner_level"] or ""), refusals+ assert "cpu_offload is not supported on a pipeline parallel model" in (+ refusals["shard_model_cpu_offload"] or ""+ ), refusals+ assert refusals["fsdp_after_refusals"] == 0, refusals+ if dims["dp"] == 1:+ continue+ else:+ assert res["reduces"] == [0] * STEPS+ if "tp" in dims:+ assert res["placements"], "no tensor parallel DTensors"+ assert union == set(ref["grads"]), sorted(union ^ set(ref["grads"]))[:6]+ saved_ref, saved_pp = results[0]["saved_ref"], results[0]["saved_pp"]+ assert set(saved_pp) == set(saved_ref), sorted(set(saved_pp) ^ set(saved_ref))[:6]+ for key, value in saved_ref.items():+ assert saved_pp[key].shape == value.shape, key+ # 3 AdamW steps (lr 1e-2) carry fp32 summation order differences (as the pp-only suite).+ torch.testing.assert_close(saved_pp[key], value, rtol = 1e-3, atol = 2e-3, msg = key)++[email protected]("arch", sorted(ARCHS))+def test_pp2_x_fsdp2_dp2_matches_one_process(arch):+ dims = {"pp": 2, "dp": 2}+ _check(_spawn("compose", arch = arch, dims = dims), dims, norm_rel = STEP0_NORM_REL[arch])+++def test_pp2_x_fsdp2_dp2_1f1b_sharded_layout_matches_one_process():+ # 1F1B, 4 micro-batches, the sharded layout (one FSDP2 unit per owned decoder layer, frozen weights sharded).+ dims = {"pp": 2, "dp": 2}+ _check(+ _spawn("compose", arch = "llama", dims = dims, schedule = "1f1b", n_mb = 4, fit_layout = False),+ dims,+ )++[email protected]("arch", sorted(ARCHS))+def test_pp2_x_tp2_matches_one_process(arch):+ dims = {"pp": 2, "tp": 2}+ _check(_spawn("compose", arch = arch, dims = dims), dims, norm_rel = STEP0_NORM_REL[arch])++[email protected]("other", ["dp", "tp"])+def test_pp2_x_size_one_dp_or_tp_matches_one_process(other):+ # (pp 2, dp 1) / (pp 2, tp 1) on 2 ranks: FSDP2 / TP DTensors on a 1-rank mesh, the shape the 2-GPU proof runs.+ dims = {"pp": 2, other: 1}+ _check(_spawn("compose", world = 2, arch = "llama", dims = dims), dims)+++def test_pp2_x_dp2_x_tp2_matches_one_process():+ dims = {"pp": 2, "dp": 2, "tp": 2}+ _check(_spawn("compose", world = 8, arch = "llama", dims = dims), dims)+++def test_pp2_x_dp2_grad_scaler_skip_is_global():+ results = _spawn("scaler")+ for res in results:+ assert res["unchanged"], res+ assert res["scale"] == 512.0, res+++def test_pp_composition_order_and_meshes_are_refused_before_any_change():+ for res in _spawn("order"):+ assert "must come before apply_tensor_parallel" in (res["tp_first"] or ""), res+ assert res["tp_first_unchanged"], res+ assert "must come before FSDP2" in (res["fsdp_first"] or ""), res+ assert res["fsdp_first_unchanged"], res+ assert "1-D pp mesh" in (res["mesh_2d"] or ""), res+ assert res["tp_after_fsdp"], res+ assert res["shard_twice_is_noop"], res+ assert res["composed"], res+ for res in _spawn("pp_tp_mesh"):+ assert "does not compose with Unsloth pipeline parallelism on these meshes" in (+ res["err"] or ""+ ), res+ assert not res["tp"], resdiff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 425f3bfd932..d78798d9f0c 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -349,7 +349,8 @@ def _is_block_list(container, no_split):"""A ModuleList whose children are all blocks (modules with submodules and parameters). Classes may mix(Jamba, Zamba / Zamba2, OlmoHybrid, Mllama text); lists of bare Linear / norm modules (Gemma3n altupprojections, also after PEFT wraps them) are not blocks."""- children = list(container.children())+ # Pipeline parallel pass-throughs (layers another stage owns, no parameters) are not blocks.+ children = [c for c in container.children() if "_pp_index" not in c.__dict__]if not children:return Falsefor child in children:@@ -379,7 +380,7 @@ def find_shard_units(model, ignored_params = ()) -> list:continueif isinstance(module, nn.ModuleList) and _is_block_list(module, no_split):for child in module.children():- if id(child) not in inside:+ if id(child) not in inside and "_pp_index" not in child.__dict__:_take(child)if no_split and not units:# Fallback only when no block list exists: the existing `_no_split_modules` classes (transformers 5.x@@ -1439,6 +1440,23 @@ def shard_model(model, config: Optional[FSDP2Config] = None):if config.units is not None:# Sharing is checked once the replicated set is known (ignored and, if replicated, frozen params).check_shard_units(model, list(config.units), ignored_params = None)+ pp_stage = None+ if any(m.__dict__.get("_unsloth_pp") for m in model.modules()):+ # Unsloth pipeline parallel x FSDP2 data parallel (torchtitan order: split, then shard each stage over+ # the dp dimension of the same mesh). Checked before any change.+ from .pp_native import check_pp_dp_composition++ pp_stage = check_pp_dp_composition(model, config.mesh)+ if config.cpu_offload:+ # The stage's device (token counts, pipeline send / recv buffers) would follow the offloaded params.+ raise RuntimeError(+ "Unsloth: native FSDP2 cpu_offload is not supported on a pipeline parallel model yet; shard it "+ "without cpu_offload."+ )+ if config.reshard_after_forward is None:+ # torchtitan's PP default (distributed/fsdp.py get_fsdp_reshard_after_forward_policy): keep units+ # gathered after forward, else every micro-batch all-gathers them again.+ config = dataclasses.replace(config, reshard_after_forward = False)if _refuse_tensor_parallel_model(model, config.mesh, compose = True):# Unsloth tensor parallel x FSDP2 data parallel: the frozen weights are this rank's tp slices,# replicated over the data parallel mesh; FSDP2 shards only the trainable (LoRA) DTensors over it.@@ -1606,7 +1624,7 @@ def shard_model(model, config: Optional[FSDP2Config] = None):model._unsloth_fsdp2_units = wrappedmodel._unsloth_fsdp2_extra_units = [u for u in extra_units if isinstance(u, FSDPModule)]model._unsloth_fsdp2_root_only = layout.root_only- if config.wrap_generate:+ if config.wrap_generate and pp_stage is None: # a pipeline stage refuses generate itself_wrap_generate(model)model._unsloth_fsdp2_mp_policy = mp_policymodel._unsloth_fsdp2_replicated = sum(1 for p in model.parameters() if p in replicated)@@ -1622,6 +1640,9 @@ def shard_model(model, config: Optional[FSDP2Config] = None):from .fsdp2_save import install_dcp_bnb_state_dictinstall_dcp_bnb_state_dict()install_native_fsdp2_hooks()+ if pp_stage is not None:+ # The pipeline stage module becomes the outer FSDP2 root: one gradient reduce-scatter per step.+ pp_stage._attach_data_parallel(mesh, mp_policy)global _SHARDED_ANY_SHARDED_ANY = True # fsdp2_launch then leaves a custom loop's Accelerator aloneclasses = sorted({type(u).__name__.removeprefix("FSDP") for u in wrapped})@@ -3624,10 +3645,12 @@ def _refuse_tensor_parallel_model("apply_tensor_parallel(model, mesh['tp']) over the same 2-D (dp, tp) mesh.")if any(m.__dict__.get("_unsloth_pp") for m in model.modules()):+ if compose and mesh is not None:+ return False # shard_model checked the pp x dp composition (pp_native.check_pp_dp_composition)raise RuntimeError(- "Unsloth: native FSDP2 does not compose with Unsloth pipeline parallelism "- "(apply_pipeline_parallel) yet; train a pipeline parallel model with PipelineParallel.step "- "over the pp ranks only (data parallel size 1)."+ "Unsloth: native FSDP2 does not compose with Unsloth pipeline parallelism (apply_pipeline_parallel) "+ "here; for pipeline x data parallel call shard_model(model, FSDP2Config(mesh = mesh['dp'])) on the "+ "split model and train it with PipelineParallel.step (not the Trainer).")if (tp_size or 1) > 1 or dtensor:raise RuntimeError(diff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.pyindex dba438c6ffd..f7d295b7a4d 100644--- a/unsloth/models/pp_native.py+++ b/unsloth/models/pp_native.py@@ -7,8 +7,8 @@pp = apply_pipeline_parallel(model, init_device_mesh("cuda", (pp,), mesh_dim_names = ("pp",))["pp"],n_microbatches = 4)-v1: LoRA / QLoRA training of dense decoders over pp ranks only (no data parallel, Trainer, FSDP2, TP,-generate). Custom loop (torchrun --nproc_per_node pp), the same batch on every rank:+LoRA / QLoRA training of dense decoders (no Trainer, generate). Custom loop (torchrun --nproc_per_node pp),+the same batch on every rank:optimizer = torch.optim.AdamW(pp.parameters(), lr = 2e-4) # this stage's trainable parametersloss = pp.step(input_ids, labels) # one optimizer step's batch: n_microbatches micro-batches@@ -23,6 +23,19 @@ input_ids, later stages substitute the received hidden states before their firstafter their last layer, and the last stage returns the model's own loss (lm_head + fused cross entropy, nologits are sent). The loss of each micro-batch is its summed token loss over the token count of the wholebatch, as with gradient accumulation on one GPU.++Composed with data / tensor parallelism (torchtitan's order: pp outermost, then dp, then tp; split first,+then parallelize each stage), on one mesh covering every rank:++ mesh = init_device_mesh("cuda", (pp, dp, tp), mesh_dim_names = ("pp", "dp", "tp")) # any 2 or all 3+ pp = apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 4) # 1. this rank's stage+ apply_tensor_parallel(model, mesh["tp"]) # 2. optional: tp inside the stage+ shard_model(model, FSDP2Config(mesh = mesh["dp"])) # 3. optional: FSDP2 over dp+ loss = pp.step(input_ids, labels) # this dp replica's slice of the global batch (same on pp / tp peers)++The loss then averages over the tokens of the whole global batch (every dp replica), clip_grad_norm_ counts+every gradient element once over the world, the GradScaler skip is decided over the world and save_adapter+writes the 1-GPU adapter from global rank 0."""from __future__ import annotations@@ -45,8 +58,11 @@ __all__ = ["PPConfig","PipelineParallel","apply_pipeline_parallel",+ "check_mesh_composition",+ "check_pp_dp_composition","derive_pp_split","is_pipeline_parallel",+ "pipeline_stage_of","split_layers",]@@ -151,6 +167,110 @@ def is_pipeline_parallel(model) -> bool:return any(m.__dict__.get(_PP_FLAG) is not None for m in chain)+def pipeline_stage_of(model):+ """The PipelineParallel of `model` (any wrapper level below it), else None."""+ if not isinstance(model, nn.Module):+ return None+ for level in _model_chain(model):+ stage = level.__dict__.get("_unsloth_pp_stage")+ if stage is not None:+ return stage+ return None+++# ------------------------------------------------------------------------------- composed meshes+++def _root_mesh(mesh):+ get = getattr(mesh, "_get_root_mesh", None)+ if callable(get):+ try:+ return get()+ except Exception:+ pass+ try:+ from torch.distributed.device_mesh import _mesh_resources+ return _mesh_resources.get_root_mesh(mesh)+ except Exception:+ return None+++def check_mesh_composition(meshes, what = "pipeline parallel composition"):+ """`meshes` ({name: 1-D DeviceMesh}) must be dimensions of one init_device_mesh covering every rank:+ 1-D, meeting only at this rank (orthogonal) and with sizes multiplying to the world size. Returns the+ world size covered; ValueError otherwise (nothing is changed)."""+ import torch.distributed as dist++ world = dist.get_world_size() if dist.is_initialized() else 1+ me = dist.get_rank() if dist.is_initialized() else 0+ names = sorted(meshes)+ sizes = {name: meshes[name].size() for name in names}+ for name in names:+ if meshes[name].ndim != 1:+ raise ValueError(+ f"Unsloth: {what} takes 1-D meshes (mesh['{name}']), got a {meshes[name].ndim}-D one."+ )+ ranks = {name: set(meshes[name].mesh.flatten().tolist()) for name in names}+ for i, a in enumerate(names):+ for b in names[i + 1 :]:+ if ranks[a] & ranks[b] != {me}:+ raise ValueError(+ f"Unsloth: {what}: the {a} mesh (ranks {sorted(ranks[a])}) and the {b} mesh (ranks "+ f"{sorted(ranks[b])}) must be two dimensions of one init_device_mesh, meeting only at "+ f"this rank ({me})."+ )+ roots = [_root_mesh(meshes[name]) for name in names]+ if all(r is not None for r in roots) and any(r is not roots[0] for r in roots):+ raise ValueError(+ f"Unsloth: {what}: the {', '.join(names)} meshes must come from one init_device_mesh(..., "+ f"mesh_dim_names = (...)) (e.g. mesh['pp'] and mesh['dp'] of the same mesh)."+ )+ covered = math.prod(sizes.values())+ if covered != world:+ raise ValueError(+ f"Unsloth: {what}: {' x '.join(f'{n} {sizes[n]}' for n in names)} = {covered} ranks, but the world "+ f"has {world}; every rank must be in one pipeline stage of one data / tensor parallel replica."+ )+ return covered+++def check_pp_dp_composition(model, dp_mesh):+ """shard_model(model, FSDP2Config(mesh = dp_mesh)) on a model split by apply_pipeline_parallel: valid on+ the model apply_pipeline_parallel was given, once, with dp_mesh orthogonal to the pp mesh (and to the tp+ mesh, applied before) and pp x dp (x tp) covering the world. Returns the PipelineParallel; ValueError+ before anything is sharded otherwise."""+ stage = pipeline_stage_of(model)+ if stage is None:+ raise ValueError("Unsloth: this model is not split by apply_pipeline_parallel.")+ if stage.model is not model:+ raise ValueError(+ "Unsloth: native FSDP2 over a pipeline parallel model needs the model apply_pipeline_parallel was "+ f"given ({type(stage.model).__name__}), not a level inside it ({type(model).__name__})."+ )+ if stage.dp_mesh is not None:+ raise ValueError(+ "Unsloth: this pipeline stage is already sharded over a data parallel mesh."+ )+ if dp_mesh is None:+ raise ValueError(+ "Unsloth: native FSDP2 over a pipeline parallel model needs FSDP2Config(mesh = mesh['dp']), the "+ "data parallel dimension of the mesh whose mesh['pp'] apply_pipeline_parallel used."+ )+ meshes = {"pp": stage.mesh, "dp": dp_mesh}+ if stage.tp_mesh is not None:+ meshes["tp"] = stage.tp_mesh+ try:+ check_mesh_composition(meshes, "pipeline parallel x native FSDP2 data parallel")+ except ValueError as exc:+ root = _root_mesh(stage.mesh)+ names = getattr(root, "mesh_dim_names", None) or ()+ hint = ""+ if "tp" in names and "tp" not in meshes:+ hint = " Apply apply_tensor_parallel(model, mesh['tp']) before shard_model."+ raise ValueError(f"{exc}{hint}") from None+ return stage++# ----------------------------------------------------------------------------------------------- parts@@ -299,9 +419,16 @@ def _refuse_unsupported(model, parts):for m in _model_chain(model):if m.__dict__.get("_unsloth_tp") is not None:raise ValueError(- "Unsloth: pipeline parallelism does not compose with Unsloth tensor parallelism "- "(apply_tensor_parallel) in v1."+ "Unsloth: apply_pipeline_parallel must come before apply_tensor_parallel (each pipeline "+ "stage is tensor parallel inside): load the model again, call apply_pipeline_parallel(model, "+ "mesh['pp']), then apply_tensor_parallel(model, mesh['tp']).")+ if any(type(m).__name__.startswith("FSDP") for m in model.modules()):+ raise ValueError(+ "Unsloth: apply_pipeline_parallel must come before FSDP2 (each pipeline stage is sharded over the "+ "data parallel mesh): call apply_pipeline_parallel(model, mesh['pp']) first, then "+ "shard_model(model, FSDP2Config(mesh = mesh['dp']))."+ )try:from torch.distributed.tensor import DTensorexcept ImportError:@@ -314,8 +441,6 @@ def _refuse_unsupported(model, parts):"Unsloth: this model is already distributed (DTensor parameters or a transformers tp_plan); ""load it without tp_plan before apply_pipeline_parallel.")- if any(type(m).__name__.startswith("FSDP") for m in model.modules()):- raise ValueError("Unsloth: pipeline parallelism v1 does not compose with FSDP2.")if parts.tied and parts.embed.weight.requires_grad:raise ValueError("Unsloth: pipeline parallelism v1 cannot train tied input / output embeddings (the first and "@@ -741,6 +866,75 @@ class PipelineParallel:self._shapes = collections.OrderedDict()self._scaler = Noneself._mb_losses = []+ self._loss_multiplier = 1+ self.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+ @property+ def tp_mesh(self):+ for level in _model_chain(self.model):+ mesh = level.__dict__.get("_unsloth_tp_mesh")+ if mesh is not None:+ return mesh+ return None++ @property+ def composed(self):+ """True when the stage spans more ranks than its pp group (dp and / or tp)."""+ import torch.distributed as dist+ return dist.is_initialized() and dist.get_world_size() != self.num_stages++ def _meshes(self):+ meshes = {"pp": self.mesh}+ if self.dp_mesh is not None:+ meshes["dp"] = self.dp_mesh+ if self.tp_mesh is not None:+ meshes["tp"] = self.tp_mesh+ return meshes++ def _check_composed(self):+ if not self.composed:+ return+ meshes = self._meshes()+ try:+ check_mesh_composition(meshes)+ except ValueError as exc:+ names = getattr(_root_mesh(self.mesh), "mesh_dim_names", None) or ("tp", "dp")+ missing = (+ " then ".join(+ call+ for name, call in (+ ("tp", "apply_tensor_parallel(model, mesh['tp'])"),+ ("dp", "shard_model(model, FSDP2Config(mesh = mesh['dp']))"),+ )+ if name not in meshes and (name in names or not set(names) & {"tp", "dp"})+ )+ or "apply_tensor_parallel over the tp dimension / shard_model over the dp dimension"+ )+ raise RuntimeError(+ f"Unsloth: this pipeline stage spans {', '.join(meshes)} only ({exc}). Apply the other mesh "+ f"dimensions before training: {missing}."+ ) from None++ def _attach_data_parallel(+ self,+ dp_mesh,+ mp_policy = None,+ ):+ """shard_model(model, FSDP2Config(mesh = dp_mesh)) sharded this stage: make the PipelineStage's module+ the outer FSDP2 root (no parameters of its own), so torch's PipelineStage defers the gradient+ reduce-scatter to the end of the step (set_requires_gradient_sync(False) per micro-batch backward,+ one post_backward in perform_reduce_grad), as torchtitan's stage submodule does."""+ from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard++ policy = MixedPrecisionPolicy(+ param_dtype = None,+ reduce_dtype = getattr(mp_policy, "reduce_dtype", None),+ cast_forward_inputs = False, # the received hidden states keep PPConfig.activation_dtype+ )+ fully_shard(self.module, mesh = dp_mesh, mp_policy = policy, reshard_after_forward = False)+ self.dp_mesh = dp_mesh+ self._shapes.clear() # stages built before hold the unwrapped module@propertydef is_first(self):@@ -770,6 +964,10 @@ class PipelineParallel:# schedule per (micro-batch size, sequence length): static stage metadatadef _loss_fn(self, output, target):self._mb_losses.append(output.detach())+ if self._loss_multiplier != 1:+ # FSDP2 averages gradients over dp: dp x (sum of this replica's token losses / global tokens)+ # averages to the global batch gradient.+ output = output * self._loss_multiplierreturn output if self._scaler is None else self._scaler.scale(output)def _schedule_for(self, mb, seq):@@ -826,9 +1024,14 @@ class PipelineParallel:"""Forward + backward of one optimizer step's batch (the same batch on every pp rank), split inton_microbatches micro-batches. Gradients accumulate into this stage's parameters (calloptimizer.zero_grad between steps). Returns the batch loss (sum over tokens / num_items_in_batch,- unscaled) on every rank."""+ unscaled) on every rank.++ With FSDP2 over a dp mesh, each dp replica passes its own slice of the global batch (pp / tp peers the+ same one); num_items_in_batch is the token count of the whole global batch (default: this slice's+ count summed over dp) and the returned loss is the global batch loss."""import torch.distributed as dist+ self._check_composed()unknown = sorted(set(kwargs) - set(_STEP_KWARGS))if unknown:raise ValueError(@@ -850,15 +1053,22 @@ class PipelineParallel:raise ValueError(f"Unsloth: the batch size {bsz} must be a multiple of n_microbatches = {m}.")+ device = self.device+ dp_group = self.dp_mesh.get_group() if self.dp_mesh is not None else Noneif num_items_in_batch is None:# Tokens the loss averages over in one process: shifted labels that are not ignored.- num_items_in_batch = int((labels[:, 1:] != -100).sum())+ count = (labels[:, 1:] != -100).sum()+ if dp_group is not None:+ # ... over the whole global batch: every dp replica's slice.+ count = count.to(device = device, dtype = torch.int64)+ dist.all_reduce(count, group = dp_group)+ num_items_in_batch = int(count)if isinstance(num_items_in_batch, torch.Tensor):num_items_in_batch = int(num_items_in_batch) # a non-tensor kwarg is replicated per micro-batchnum_items_in_batch = max(num_items_in_batch, 1)- device = self.device+ self._loss_multiplier = self.dp_mesh.size() if self.dp_mesh is not None else 1schedule = self._schedule_for(bsz // m, seq)step_kwargs = {}for key, value in kwargs.items():@@ -886,6 +1096,8 @@ class PipelineParallel:schedule.step(*args, target = target, return_outputs = False, **step_kwargs)finally:self._scaler = None+ if self.dp_mesh is not None:+ self._average_replicated_grads()if self.is_last:if len(self._mb_losses) != m:raise RuntimeError(@@ -897,24 +1109,82 @@ class PipelineParallel:total = torch.zeros(1, dtype = torch.float32, device = device)if self.num_stages > 1:dist.broadcast(total, src = self._global_ranks[-1], group = self.group)+ if dp_group is not None:+ dist.all_reduce(total, group = dp_group) # each replica's sum / global tokensreturn total[0]+ def _average_replicated_grads(self):+ """Trainable parameters FSDP2 keeps replicated (Unsloth averages them over dp like DDP from an+ autograd callback, deferred while gradient sync is off): the pipeline schedule runs every micro-batch+ backward with sync off and reduces FSDP2's own groups outside autograd, so average them here once.+ Averaging equal values is a no-op, so an earlier per-backward average stays correct."""+ params = self.model.__dict__.get("_unsloth_replicated_grad_params")+ if not params:+ return+ import torch.distributed as dist++ from .fsdp2_save import _sync_replicated_grads, model_mesh++ state = self.model.__dict__.setdefault("_unsloth_replicated_grad_state", {"queued": False})+ _sync_replicated_grads(+ params, dist, model_mesh(self.model) or self.dp_mesh, state.setdefault("buffers", {})+ )++ def _grad_copies(self, grad):+ """(local tensor, number of ranks holding the same values) for this rank's gradient. Stages hold+ disjoint parameters; inside a stage plain gradients are replicated over its world // pp ranks and+ a DTensor's local shard repeats over that count divided by its shard dimensions."""+ stage_ranks = torch.distributed.get_world_size() // self.num_stages if self.composed else 1+ try:+ from torch.distributed.tensor import DTensor, Replicate+ except ImportError:+ DTensor = None+ if DTensor is None or not isinstance(grad, DTensor):+ return grad, grad, stage_ranks+ if any(pl.is_partial() for pl in grad.placements):+ grad = grad.redistribute(+ grad.device_mesh,+ [Replicate() if pl.is_partial() else pl for pl in grad.placements],+ )+ mesh = grad.device_mesh+ shards = math.prod(+ mesh.size(i)+ for i, pl in enumerate(grad.placements)+ if pl.is_shard() or "StridedShard" in type(pl).__name__+ )+ if stage_ranks % mesh.size() or stage_ranks % shards:+ raise ValueError(+ f"Unsloth: a gradient on a {mesh.size()}-rank mesh does not fit this stage's {stage_ranks} ranks."+ )+ local = getattr(grad, "_local_tensor", None)+ return grad, (grad.to_local() if local is None else local), stage_ranks // shards+def clip_grad_norm_(self,max_norm,parameters = None,eps = 1e-6,):- """Clip by the global 2-norm over every stage (squares summed over pp). Returns the norm."""+ """Clip by the global 2-norm over every stage (squares summed over pp). Returns the norm.+ Composed with dp / tp: every gradient element counted once over the world (a local square sum+ divided by the ranks holding a copy of it, summed over every rank)."""import torch.distributed as distparams = self.parameters() if parameters is None else list(parameters)- grads = [p.grad for p in params if p.grad is not None]+ params = [p for p in params if p.grad is not None]device = self.devicesq = torch.zeros((), dtype = torch.float64, device = device)- for g in grads:- sq = sq + g.detach().double().square().sum().to(device)- if self.num_stages > 1:+ grads = []+ for p in params:+ full, local, copies = self._grad_copies(p.grad)+ if full is not p.grad:+ p.grad = full+ grads.append(local)+ part = local.detach().double().square().sum().to(device)+ sq = sq + (part / copies if copies != 1 else part)+ if self.composed:+ dist.all_reduce(sq) # the meshes cover the world (checked by step)+ elif self.num_stages > 1:dist.all_reduce(sq, group = self.group)total = sq.sqrt()coef = torch.clamp(float(max_norm) / (total + eps), max = 1.0)@@ -936,7 +1206,9 @@ class PipelineParallel:total = torch.zeros(1, dtype = torch.float32, device = device)for t in found.values():total = torch.maximum(total, t.reshape(1).float().to(device))- if self.num_stages > 1:+ if self.composed:+ dist.all_reduce(total, op = dist.ReduceOp.MAX) # every stage of every dp / tp replica+ elif self.num_stages > 1:dist.all_reduce(total, op = dist.ReduceOp.MAX, group = self.group)if not found:found[device] = total@@ -958,25 +1230,38 @@ class PipelineParallel:from peft import get_peft_model_state_dictlocal = {}+ raw = gather = None+ if self.composed or self.dp_mesh is not None or self.tp_mesh is not None:+ # FSDP2 / tensor parallel DTensors: gathered whole (collective over the stage's dp / tp ranks, the+ # same keys in the same order on each), fused tp layouts back in their 1-GPU order.+ raw = self.model.state_dict(keep_vars = True)+ from .tp_native import _full, _param_layouts++ layouts = _param_layouts(self.model)++ def gather(v):+ return _full(v, v, layouts.get(id(v)))+with torch.no_grad():for adapter in self._adapters(kwargs):# PEFT selects per stage: only this stage's tuner layers exist here.selected = get_peft_model_state_dict(self.model,+ state_dict = raw,adapter_name = adapter,save_embedding_layers = kwargs.get("save_embedding_layers", "auto"),)local[adapter] = {- k: v.detach().cpu().clone()+ k: (gather(v) if gather is not None else v).detach().cpu().clone()for k, v in selected.items()if not k.startswith(self._foreign_prefixes)}if self.num_stages == 1:- return local+ return local if not self.composed or dist.get_rank() == 0 else Nonegathered = [None] * self.num_stages if self.is_first else Nonedist.gather_object(local, gathered, dst = self._global_ranks[0], group = self.group)- if not self.is_first:- return None+ if not self.is_first or (self.composed and dist.get_rank() != 0):+ return None # one pp group (the one holding global rank 0) writesmerged = {adapter: {} for adapter in local}for part in gathered:for adapter, state in part.items():@@ -988,7 +1273,7 @@ class PipelineParallel:import torch.distributed as distmerged = self.adapter_state_dict(**kwargs)- if self.is_first:+ if merged is not None:import peft.peft_model as peft_modelselection = peft_model.get_peft_model_state_dict@@ -1009,7 +1294,9 @@ class PipelineParallel:peft_model.PeftModel.save_pretrained(self.model, save_directory, **kwargs)finally:peft_model.get_peft_model_state_dict = selection- if self.num_stages > 1:+ if self.composed:+ dist.barrier()+ elif self.num_stages > 1:dist.barrier(group = self.group)@@ -1058,10 +1345,22 @@ def apply_pipeline_parallel(raise ValueError("Unsloth: apply_pipeline_parallel takes a 1-D pp mesh (pass mesh['pp']).")pp = pp_mesh.size()if dist.is_initialized() and pp != dist.get_world_size():- raise ValueError(- f"Unsloth: pipeline parallelism v1 runs over every rank (pp mesh {pp} of "- f"{dist.get_world_size()} ranks): data parallel x pipeline parallel is v2."- )+ # pp x dp / pp x tp: the pp mesh must be one dimension of a mesh covering every rank; the other+ # dimensions are applied after the split (apply_tensor_parallel, shard_model), checked again by step.+ root = _root_mesh(pp_mesh)+ if (+ root is None+ or root is pp_mesh+ or root.ndim < 2+ or root.size() != dist.get_world_size()+ or dist.get_world_size() % pp+ ):+ raise ValueError(+ f"Unsloth: the pipeline parallel mesh has {pp} of {dist.get_world_size()} ranks. Pass mesh['pp'] of "+ "one init_device_mesh(..., (pp, dp), mesh_dim_names = ('pp', 'dp')) (or ('pp', 'tp') / ('pp', "+ "'dp', 'tp')) covering every rank, then shard_model(model, FSDP2Config(mesh = mesh['dp'])) / "+ "apply_tensor_parallel(model, mesh['tp']); or a pp mesh over all ranks."+ )n_microbatches = int(n_microbatches or pp)if n_microbatches < 1:raise ValueError("Unsloth: n_microbatches must be >= 1.")@@ -1133,7 +1432,7 @@ def apply_pipeline_parallel(gc.collect() # the dropped layers sit in reference cycles: free their weights now, not at a later collectionif torch.cuda.is_available():torch.cuda.empty_cache()- if rank == 0:+ if (dist.get_rank() if dist.is_initialized() else rank) == 0:print(f"Unsloth: pipeline parallel over {pp} stages ({schedule}, {n_microbatches} micro-batches, "f"{parts.source} parts): decoder layers per stage {[e - s for s, e in bounds]}"diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex 62fdd8fc79c..bb66b618ea1 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -407,7 +407,8 @@ def derive_tp_plan(path = f"{layers_path}.{index}.{child_name}"regions.append(_region(path, child, kind, compiled, text, tp_size))found += 1- replicated += found == 0+ # A pipeline parallel pass-through (a layer another stage owns) is not a replicated layer.+ replicated += found == 0 and "_pp_index" not in layer.__dict__if not regions:raise ValueError("Unsloth: tensor parallelism found no attention / MLP modules to shard in the decoder layers."@@ -1131,10 +1132,9 @@ def apply_tensor_parallel("load it without tp_plan before apply_tensor_parallel.")if any(level.__dict__.get("_unsloth_pp") is not None for level in _tp_chain(model)):- raise ValueError(- "Unsloth: tensor parallelism does not compose with Unsloth pipeline parallelism "- "(apply_pipeline_parallel) in v1."- )+ # pp x tp (torchtitan order): each pipeline stage is tensor parallel over the tp dimension of the+ # same mesh. Checked before any change.+ _check_pp_tp_composition(model, tp_mesh)tp_plan = derive_tp_plan(model, tp, plan)covered = set()for region in tp_plan.regions:@@ -1264,6 +1264,57 @@ def _shard_projection(region, proj, mesh, rank, tp):module.forward = types.MethodType(_tp_projection_forward, module)+def _check_pp_tp_composition(model, tp_mesh):+ from .pp_native import check_mesh_composition, pipeline_stage_of++ stage = pipeline_stage_of(model)+ if stage is None or stage.model is not model:+ raise ValueError(+ "Unsloth: tensor parallelism does not compose with Unsloth pipeline parallelism "+ "(apply_pipeline_parallel) here: pass the model apply_pipeline_parallel was given."+ )+ if stage.dp_mesh is not None:+ raise ValueError(+ "Unsloth: apply_tensor_parallel must come before shard_model on a pipeline parallel model "+ "(pp, then tp inside each stage, then FSDP2 over dp)."+ )+ import torch.distributed as dist++ meshes = {"pp": stage.mesh, "tp": tp_mesh}+ world = dist.get_world_size() if dist.is_initialized() else 1+ if stage.mesh.size() * tp_mesh.size() == world:+ try:+ check_mesh_composition(meshes, "pipeline parallel x tensor parallel")+ except ValueError as exc:+ raise ValueError(+ "Unsloth: tensor parallelism does not compose with Unsloth pipeline parallelism on these "+ f"meshes. {exc}"+ ) from None+ else:+ # pp x dp x tp: the dp dimension comes with shard_model; here only orthogonality and divisibility.+ pp_ranks, tp_ranks = set(stage.mesh.mesh.tolist()), set(tp_mesh.mesh.tolist())+ if (+ tp_mesh.ndim != 1+ or pp_ranks & tp_ranks != {dist.get_rank()}+ or world % (stage.mesh.size() * tp_mesh.size())+ ):+ raise ValueError(+ "Unsloth: tensor parallelism does not compose with Unsloth pipeline parallelism on these "+ f"meshes: the tp mesh (ranks {sorted(tp_ranks)}) must be the tensor parallel dimension of the "+ f"mesh whose pp dimension (ranks {sorted(pp_ranks)}) apply_pipeline_parallel used: pass "+ "mesh['tp'] of init_device_mesh(..., (pp, tp)) or (pp, dp, tp)."+ )+ return stage+++def _pp_size(model):+ for level in _tp_chain(model):+ info = level.__dict__.get("_unsloth_pp")+ if info is not None:+ return int(info.get("size", 1))+ return 1++def check_tp_dp_composition(model, dp_mesh):"""shard_model(model, FSDP2Config(mesh = dp_mesh)) on a model sharded by apply_tensor_parallel: valid whendp_mesh and the tp mesh are the two dimensions of one (dp, tp) mesh covering the world. Marks the model."""@@ -1284,7 +1335,9 @@ def check_tp_dp_composition(model, dp_mesh):)dp_ranks, tp_ranks = set(dp_mesh.mesh.tolist()), set(tp_mesh.mesh.tolist())me = dist.get_rank()- if dp_ranks & tp_ranks != {me} or dp_mesh.size() * tp_mesh.size() != dist.get_world_size():+ # A pipeline parallel model (apply_pipeline_parallel first): every stage is one (dp, tp) slice of the world.+ pp = _pp_size(model)+ if dp_ranks & tp_ranks != {me} or dp_mesh.size() * tp_mesh.size() * pp != dist.get_world_size():raise ValueError(f"Unsloth: native FSDP2's mesh (ranks {sorted(dp_ranks)}) must be the data parallel dimension of the "f"(dp, tp) mesh whose tp dimension (ranks {sorted(tp_ranks)}) apply_tensor_parallel used, covering "