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
FSDP2: average tp gradients over dp when every trainable param is ignored (#16180)
Daniel Hanb7880006414f
diff --git a/tests/test_fsdp2_tp_ignored_params_dp_gloo.py b/tests/test_fsdp2_tp_ignored_params_dp_gloo.pyindex 683942e4934..73c9474b7a2 100644--- a/tests/test_fsdp2_tp_ignored_params_dp_gloo.py+++ b/tests/test_fsdp2_tp_ignored_params_dp_gloo.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""dp 2 x tp 2 gloo: a TP param in FSDP2 ignored_params is averaged over dp; replicas match a single process."""+"""Ignored TP trainables stay synchronized over DP, including empty FSDP2 groups."""import multiprocessingimport os@@ -20,18 +20,24 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from test_tp_native_oracle import LLAMA, _batch, build, tpn # noqa: E402import test_tp_native_gloo as gloo # noqa: E402-_MAX_NORM = 0.05 # small enough that every step clips+_MAX_NORM = 0.05-def _ignored_names(model):+def _ignored_names(model, ignore_all = False):return [nfor n, p in model.named_parameters()- if p.requires_grad and "layers.0." in n and ("q_proj" in n or "down_proj" in n)+ if p.requires_grad+ and (ignore_all or ("layers.0." in n and ("q_proj" in n or "down_proj" in n)))]-def _case_tp_fsdp2_ignored(rank, world, tmp):+def _case_tp_fsdp2_ignored(+ rank,+ world,+ tmp,+ ignore_all = False,+):import torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.tensor import DTensor@@ -47,7 +53,7 @@ def _case_tp_fsdp2_ignored(rank, world, tmp):ids = _batch(ref, bsz = 4)mine = ids[2 * dp : 2 * dp + 2]tpn.apply_tensor_parallel(model, mesh["tp"])- names = _ignored_names(model)+ names = _ignored_names(model, ignore_all)by_name = dict(model.named_parameters())ignored = {by_name[n] for n in names}native.shard_model(@@ -90,15 +96,51 @@ def _case_tp_fsdp2_ignored(rank, world, tmp):gloo.CASES["tp_fsdp2_ignored"] = _case_tp_fsdp2_ignored-def _spawn(world):- """test_tp_native_gloo._spawn with this module's case registered in every spawned rank."""+def _case_tp_fsdp2_ignored_compiled(rank, world, tmp):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.tensor.parallel import ColwiseParallel, parallelize_module+ from torch._dynamo.utils import counters+ from test_fsdp2_native_units import _load_native+ from unsloth.models import fsdp2_save as save++ native = _load_native()+ fully_shard = native._fsdp_api()[2]+ if not native._supports_ignored_params(fully_shard):+ return {"unsupported": True}+ mesh = init_device_mesh("cpu", (2, world // 2), mesh_dim_names = ("dp", "tp"))+ model = torch.nn.Linear(4, 4, bias = False)+ parallelize_module(model, mesh["tp"], ColwiseParallel())+ fully_shard(model, mesh = mesh["dp"], ignored_params = set(model.parameters()))+ model._unsloth_fsdp2_mesh = mesh["dp"]+ names = save.reduce_unsharded_trainable_grads(model)+ compiled = torch.compile(model, backend = "eager", dynamic = True)+ counters.clear()+ for batch in (2, 3, 2):+ x = torch.full((batch, 4), float(mesh["dp"].get_local_rank() + 1))+ compiled(x).sum().backward()+ return {+ "names": names,+ "grad": model.weight.grad.to_local().detach().clone(),+ "graphs": counters["stats"]["unique_graphs"],+ "breaks": list(counters["graph_break"]),+ }+++gloo.CASES["tp_fsdp2_ignored_compiled"] = _case_tp_fsdp2_ignored_compiled+++def _spawn(+ world,+ case = "tp_fsdp2_ignored",+ **kwargs,+):import tempfilectx = multiprocessing.get_context("spawn")port = gloo._free_port()with tempfile.TemporaryDirectory() as tmp:procs = [- ctx.Process(target = _worker, args = (r, world, port, "tp_fsdp2_ignored", tmp, {}))+ ctx.Process(target = _worker, args = (r, world, port, case, tmp, kwargs))for r in range(world)]for p in procs:@@ -117,8 +159,9 @@ def _worker(*args):gloo._worker(*args)-def test_tp_param_in_ignored_params_is_averaged_over_dp():- results = _spawn(4)[email protected]("ignore_all", [False, True], ids = ["some_ignored", "all_ignored"])+def test_tp_param_in_ignored_params_is_averaged_over_dp(ignore_all):+ results = _spawn(4, ignore_all = ignore_all)if results[0].get("unsupported"):pytest.skip("torch < 2.7: no fully_shard(ignored_params)")for res in results:@@ -136,3 +179,16 @@ def test_tp_param_in_ignored_params_is_averaged_over_dp():)for n, ref in res["ref"].items():torch.testing.assert_close(res["full"][n], ref, rtol = 1e-4, atol = 1e-6, msg = n)+++def test_all_ignored_compiled_grad_sync_does_not_add_a_graph_break():+ results = _spawn(4, case = "tp_fsdp2_ignored_compiled")+ if results[0].get("unsupported"):+ pytest.skip("torch < 2.7: no fully_shard(ignored_params)")+ for res in results:+ assert res["names"] == ["weight"]+ assert res["graphs"] > 0+ assert not any("_current_graph_task_id" in reason for reason in res["breaks"]), res[+ "breaks"+ ]+ torch.testing.assert_close(res["grad"], torch.full_like(res["grad"], 1.5 * sum((2, 3, 2))))diff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex d2f45bca1db..6232ad40158 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -1196,6 +1196,8 @@ def _without_quant_state_entries(name, args, kwargs):def _in_backward():+ if torch.compiler.is_compiling():+ return Falsetry:return torch._C._current_graph_task_id() != -1except Exception:@@ -1301,7 +1303,8 @@ def _like_param(p, local):def _fsdp_managed_param_ids(model):- """ids of FSDP2-managed params, or None when no FSDP2 state is readable (treat all DTensors as FSDP2's)."""+ """ids of FSDP2-managed params, or None when no FSDP2 state is readable (treat all DTensors as FSDP2's).+ A readable state managing no params (every trainable param ignored) gives an empty set."""ids = set()found = Falsefor unit in fsdp2_units(model):@@ -1311,11 +1314,13 @@ def _fsdp_managed_param_ids(model):continuegroups = getattr(st, "_fsdp_param_groups", None)if groups is None:- group = getattr(st, "_fsdp_param_group", None)+ if not hasattr(st, "_fsdp_param_group"):+ continue+ group = st._fsdp_param_groupgroups = [group] if group is not None else []+ found = Truefor group in groups:for fp in getattr(group, "fsdp_params", None) or ():- found = Truefor attr in ("sharded_param", "_unsharded_param"):t = getattr(fp, attr, None)if t is not None: