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
Native FSDP2: write sub-mesh saves from the mesh's own first rank (#14761)
Daniel Han8e64f1a8a157
diff --git a/tests/test_fsdp2_native_submesh_gloo.py b/tests/test_fsdp2_native_submesh_gloo.pyindex 0abdab3c7ce..a6e2045cae5 100644--- a/tests/test_fsdp2_native_submesh_gloo.py+++ b/tests/test_fsdp2_native_submesh_gloo.py@@ -10,7 +10,9 @@ sharding its own model replica on its own data):* the per-input media agreement counts only the mesh's ranks: a mixed batch in one pair raisesthere, while the other pair, whose ranks agree, trains;* the one-time layout agreement in shard_model runs over the mesh too: pairs whose GPUs differ pick- their own fit layout, and one pair shards while the other never calls shard_model."""+ their own fit layout, and one pair shards while the other never calls shard_model;+* collective and Trainer saves write from the mesh's own first rank (pair [2, 3] has no rank 0),+ also with every parameter left unsharded by a forward, both pairs saving at once."""import multiprocessingimport os@@ -30,7 +32,12 @@ import torch # noqa: E402sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from test_fsdp2_native_units import _load_native # noqa: E402-from test_fsdp2_native_trainer_ckpt_gloo import _free_port # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import ( # noqa: E402+ _free_port,+ _model,+ _stub_unsloth_save,+ _trainer,+)from test_fsdp2_native_trainer_args_gloo import _lora # noqa: E402from test_fsdp2_native_per_input_gloo import _MoshiLike # noqa: E402@@ -128,6 +135,75 @@ def _case_subgroup(native, rank):return res+def _case_save(native, rank):+ from torch.distributed.fsdp import fully_shard++ save = sys.modules["unsloth.models.fsdp2_save"]+ mesh = _submesh(rank)+ torch.manual_seed(rank // 2)+ model = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 4))+ for block in model:+ fully_shard(block, mesh = mesh)+ fully_shard(model, mesh = mesh)+ res = {}+ with save.fsdp2_gathered(model) as writer:+ res["writer"] = writer+ res["gathered_shape"] = tuple(model[0].weight.shape) if writer else None+ res["full_keys"] = sorted(native.native_full_state_dict(model))+ for unit in save.fsdp2_units(model):+ unit.set_reshard_after_forward(False)+ with torch.no_grad():+ model(torch.randn(2, 8))+ DTensor = save._dtensor_class()+ res["unsharded_plain"] = not any(isinstance(p, DTensor) for p in model.parameters())+ res["unsharded_writer_rank"] = save.mesh_writer_rank(model)+ with save.fsdp2_gathered(model) as writer:+ res["unsharded_writer"] = writer+ for unit in save.fsdp2_units(model):+ unit.set_reshard_after_forward(True)+ optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-3)+ model(torch.randn(2, 8)).sum().backward()+ optimizer.step()+ path = os.path.join(os.environ["UNSLOTH_TEST_SAVE_DIR"], f"optimizer_pair{rank // 2}.pt")+ native.native_save_optimizer(model, optimizer, path)+ state = torch.load(path, weights_only = False)+ res["optimizer_entries"] = len(state.get("state", {}))+ # Full (gathered) moments: 8 * 8 + 8 + 4 * 8 + 4 elements, not one rank's shards.+ res["exp_avg_numel"] = sum(v["exp_avg"].numel() for v in state["state"].values())+ import torch.distributed as dist++ dist.barrier() # rank 0 hosts the store the other pair still waits on+ return res+++def _case_trainer_save(native, rank):+ """Each pair saves its LoRA model, a full model and the optimizer + scheduler through the+ Trainer hooks at the same time. Pair [2, 3]'s should_save is False on both ranks."""+ import torch.distributed as dist++ _stub_unsloth_save()+ mesh = _submesh(rank)+ root = os.path.join(os.environ["UNSLOTH_TEST_SAVE_DIR"], f"pair{rank // 2}")+ cfg = native.FSDP2Config(param_dtype = torch.float32, mesh = mesh)+ res = {}+ lora = native.shard_model(_lora(1), cfg)+ trainer = _trainer(lora, root)+ res["should_save"] = bool(trainer.args.should_save)+ trainer.save_model(os.path.join(root, "lora"))+ res["lora_written"] = os.path.isfile(os.path.join(root, "lora", "adapter_model.safetensors"))+ trainer.create_optimizer_and_scheduler(num_training_steps = 2)+ os.makedirs(os.path.join(root, "ckpt"), exist_ok = True) # Trainer._save_checkpoint does this+ trainer._save_optimizer_and_scheduler(os.path.join(root, "ckpt"))+ res["optimizer_written"] = os.path.isfile(os.path.join(root, "ckpt", "optimizer.pt"))+ full = native.shard_model(_model(False, 1, root), cfg)+ _trainer(full, root).save_model(os.path.join(root, "full"))+ res["full_written"] = os.path.isfile(os.path.join(root, "full", "model.safetensors"))+ dist.barrier() # rank 0 hosts the store the other pair still waits on+ # The scheduler is written after the optimizer wait, so only after the barrier on every rank.+ res["scheduler_written"] = os.path.isfile(os.path.join(root, "ckpt", "scheduler.pt"))+ return res++def _worker(rank, world, port, out, case):os.environ.update(MASTER_ADDR = "127.0.0.1",@@ -154,6 +230,14 @@ def _worker(rank, world, port, out, case):res = _case_fit(native, rank)elif case == "subgroup":res = _case_subgroup(native, rank)+ elif case == "save":+ os.environ["UNSLOTH_FSDP2_SAVE_TIMEOUT"] = "60"+ importlib.import_module("unsloth.models.fsdp2_save")+ res = _case_save(native, rank)+ elif case == "trainer_save":+ os.environ["UNSLOTH_FSDP2_SAVE_TIMEOUT"] = "30"+ importlib.import_module("unsloth.models.fsdp2_save")+ res = _case_trainer_save(native, rank)else:res = _case_grads(native, rank, hsdp = case == "hsdp")out.put((rank, res))@@ -234,3 +318,32 @@ def test_a_sub_mesh_shards_without_the_other_ranks():pytest.importorskip("peft")results = _run("subgroup")assert [results[r]["sharded"] for r in range(WORLD)] == [True, True, False, False], results+++def test_sub_mesh_saves_write_from_the_mesh_first_rank(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_TEST_SAVE_DIR", str(tmp_path))+ results = _run("save")+ assert [results[r]["writer"] for r in range(WORLD)] == [True, False, True, False], results+ assert results[0]["gathered_shape"] == results[2]["gathered_shape"] == (8, 8), results+ for rank in (0, 2):+ assert results[rank]["full_keys"] == ["0.bias", "0.weight", "1.bias", "1.weight"], results+ for rank in (1, 3):+ assert results[rank]["full_keys"] == [], results+ for rank in range(WORLD):+ assert results[rank]["unsharded_plain"], results+ assert results[rank]["unsharded_writer_rank"] == (0 if rank < 2 else 2), results+ assert [results[r]["unsharded_writer"] for r in range(WORLD)] == [True, False, True, False]+ for rank in range(WORLD):+ assert results[rank]["optimizer_entries"] == 4, results+ assert results[rank]["exp_avg_numel"] == 108, results+++def test_sub_mesh_trainer_saves_write_from_the_mesh_first_rank(tmp_path, monkeypatch):+ pytest.importorskip("peft")+ monkeypatch.setenv("UNSLOTH_TEST_SAVE_DIR", str(tmp_path))+ results = _run("trainer_save", timeout = 240)+ assert [results[r]["should_save"] for r in range(WORLD)] == [True, False, False, False]+ for rank in range(WORLD):+ # Every rank returns after its pair's writer wrote (the store wait), so all see the files.+ for key in ("lora_written", "optimizer_written", "scheduler_written", "full_written"):+ assert results[rank][key], (rank, key, results)diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex c36d250e002..425f3bfd932 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -1769,15 +1769,27 @@ def native_full_state_dict(trainable_only = False,cpu_offload = True,):- """Collective: every rank must call. Full (unsharded) state dict on rank 0, {} on the others."""+ """Collective over the model's mesh. Full state dict on the writer (fsdp2_save.mesh_writer_rank),+ {} on the others."""from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict+ from .fsdp2_save import mesh_writer_rank++ writer_rank = mesh_writer_rank(model) if cpu_offload else 0options = StateDictOptions(- full_state_dict = True,- cpu_offload = cpu_offload,+ full_state_dict = writer_rank == 0,+ cpu_offload = cpu_offload and writer_rank == 0,ignore_frozen_params = bool(trainable_only),)- return get_model_state_dict(model, options = options)+ state = get_model_state_dict(model, options = options)+ return state if writer_rank == 0 else _gather_to_writer(state, writer_rank)+++def _gather_to_writer(state, writer_rank):+ """StateDictOptions(full_state_dict, cpu_offload) for `writer_rank` instead of rank 0, which a+ sub-mesh may not contain."""+ from torch.distributed._state_dict_utils import _gather_state_dict+ return _gather_state_dict(state, cpu_offload = True, ranks_only = (writer_rank,))def _reshard_after_forward_off(unit):@@ -2176,24 +2188,29 @@ def native_save_optimizer(should_save = None,):"""Collective (every rank must call): the full, unsharded optimizer state keyed by parameter FQN- (`get_optimizer_state_dict(full_state_dict, cpu_offload)`), written to `path` on rank 0. A plain- `optimizer.state_dict()` on rank 0 holds only rank 0's DTensor shards, so a resume from it is wrong."""+ (`get_optimizer_state_dict(full_state_dict, cpu_offload)`), written to `path` by+ fsdp2_save.mesh_writer_rank. A plain `optimizer.state_dict()` on rank 0 holds only rank 0's+ DTensor shards, so a resume from it is wrong."""from torch.distributed.checkpoint.state_dict import StateDictOptions, get_optimizer_state_dictmodel = _native_root(model)optimizer = _inner_optimizer(optimizer)+ from .fsdp2_save import _dist, _wait_for_writer, mesh_writer_rank++ writer_rank = mesh_writer_rank(model)state = get_optimizer_state_dict(model,optimizer,- options = StateDictOptions(full_state_dict = True, cpu_offload = True),+ options = StateDictOptions(full_state_dict = writer_rank == 0, cpu_offload = writer_rank == 0),)- if should_save is None:- should_save = _rank0()+ if writer_rank != 0:+ state = _gather_to_writer(state, writer_rank)+ dist = _dist()+ if should_save is None or writer_rank != 0:+ # Only the sub-mesh writer holds the state; a global-rank-0 should_save would write nothing.+ should_save = dist is None or dist.get_rank() == writer_rankif path is None:return state- from .fsdp2_save import _dist, _wait_for_writer-- dist = _dist()writer = bool(should_save)try:if writer:@@ -2203,7 +2220,7 @@ def native_save_optimizer(# The other ranks wait for the write, so no later collective overtakes it. A store key,# not a barrier: a large full-finetuning state can take longer to write than the# collective timeout. Every rank passes the same path (the Trainer does).- _wait_for_writer(dist, writer)+ _wait_for_writer(dist, writer, writer_rank)return state@@ -2871,6 +2888,18 @@ def _save_unwrapped(trainer.model = held+def _trainer_save_writer(trainer, root):+ """(writes, writer_rank) for a Trainer save of `root`: should_save, unless the mesh leaves out+ rank 0, then its own first rank (else nobody writes and the mesh waits forever)."""+ from .fsdp2_save import _dist, mesh_writer_rank++ writer_rank = mesh_writer_rank(root)+ if writer_rank == 0:+ return bool(trainer.args.should_save), 0+ dist = _dist()+ return dist is not None and dist.get_rank() == writer_rank, writer_rank++def _install_trainer_hooks():try:from transformers import Trainer@@ -2903,23 +2932,24 @@ def _install_trainer_hooks():include = _fsdp2_peft_saved_frozen(root, {})with fsdp2_gathered(root, trainable_only = True, include = include) as writer:- if writer is not False and self.args.should_save:+ if writer is not False and _trainer_save_writer(self, root)[0]:_save_unwrapped(self, root, output_dir)else:- from .fsdp2_save import _dist, _wait_for_writer+ from .fsdp2_save import _dist, _wait_for_writer, writes_off_rank0state_dict = native_full_state_dict(root)- writer = bool(self.args.should_save)+ writer, writer_rank = _trainer_save_writer(self, root)try:if writer:- _save_unwrapped(self, root, output_dir, state_dict = state_dict)+ with writes_off_rank0(root, writer_rank):+ _save_unwrapped(self, root, output_dir, state_dict = state_dict)finally:# As in fsdp2_gathered: the other ranks wait for the (possibly multi-GB) write# through the store, so they cannot run ahead into the optimizer save's or the next# step's collectives and hit their timeout while rank 0 is still writing.dist = _dist()if dist is not None:- _wait_for_writer(dist, writer)+ _wait_for_writer(dist, writer, writer_rank)if getattr(self.args, "push_to_hub", False) and not _internal_call:self.push_to_hub(commit_message = "Model save", revision = self.args.hub_revision)@@ -2993,10 +3023,11 @@ def _install_trainer_hooks():# other format in a reused directory is removed, so a resume cannot read it.# The flag is read per rank: every rank writes the format they all asked for (a mixed# choice would pair dcp.save's collectives with the full gather's), before any cleanup.+ should_save = _trainer_save_writer(self, _native_root(model))[0]group, usable = _dcp_group(_native_root(model))sharded = usable and _all_ranks_agree(_env_on("UNSLOTH_FSDP2_DCP_OPTIM", False), group)stale = os.path.join(output_dir, _OPTIMIZER_NAME if sharded else _OPTIMIZER_DCP_DIR)- if self.args.should_save and os.path.lexists(stale):+ if should_save and os.path.lexists(stale):if os.path.isdir(stale) and not os.path.islink(stale):import shutilshutil.rmtree(stale)@@ -3011,10 +3042,10 @@ def _install_trainer_hooks():model,self.optimizer,os.path.join(output_dir, _OPTIMIZER_NAME),- should_save = self.args.should_save,+ should_save = should_save,)scheduler = getattr(self, "lr_scheduler", None)- if self.args.should_save and scheduler is not None:+ if should_save and scheduler is not None:torch.save(scheduler.state_dict(), os.path.join(output_dir, _SCHEDULER_NAME))original_load_optimizer = Trainer._load_optimizer_and_schedulerdiff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex 794adc303f5..a212ee41953 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -11,6 +11,8 @@ __all__ = ["fsdp2_units","fsdp2_gathered","fsdp2_gather_active",+ "mesh_writer_rank",+ "writes_off_rank0","install_dcp_bnb_state_dict","reduce_unsharded_trainable_grads",]@@ -71,7 +73,7 @@ def _dist():return None-_SAVE_COUNTER = [0]+_SAVE_COUNTER = {}def _save_timeout():@@ -83,12 +85,70 @@ def _save_timeout():return datetime.timedelta(days = 7)-def _wait_for_writer(dist, writer):- """The other ranks wait for rank 0's write, so no later collective overtakes it. A store key, not- a barrier: a merged or quantized export (and a Hub upload) can outlast the process group's- collective timeout, and NCCL ranks blocked in a barrier would abort before rank 0 arrives."""- _SAVE_COUNTER[0] += 1- key = f"unsloth_fsdp2_save_{_SAVE_COUNTER[0]}"+def _unit_mesh(unit):+ try:+ group = unit._get_fsdp_state()._fsdp_param_group+ return group.mesh_info.mesh if group is not None else None+ except Exception:+ return None+++def mesh_writer_rank(model):+ """Lowest global rank of the model's FSDP2 mesh: a sub-mesh without rank 0 never gathers there."""+ dist = _dist()+ if dist is None:+ return 0+ DTensor = _dtensor_class()+ mesh = None+ if isinstance(model, torch.nn.Module):+ if DTensor is not None:+ mesh = next((p.device_mesh for p in model.parameters() if isinstance(p, DTensor)), None)+ if mesh is None:+ # Unsharded parameters (eval forward, no reshard) carry no mesh; the units still do.+ mesh = next(filter(None, map(_unit_mesh, fsdp2_units(model))), None)+ if mesh is None:+ mesh = model.__dict__.get("_unsloth_fsdp2_mesh", None)+ try:+ return int(mesh.mesh.min()) if mesh is not None else 0+ except Exception:+ return 0+++def writes_off_rank0(model, writer_rank):+ """transformers 5 save_pretrained writes only on global rank 0 (should_save_on_this_rank,+ transformers/distributed/mixin.py); let a sub-mesh writer write for the block."""+ patched = []+ if writer_rank != 0 and isinstance(model, torch.nn.Module):+ for module in model.modules():+ if callable(getattr(module, "should_save_on_this_rank", None)) and (+ "should_save_on_this_rank" not in module.__dict__+ ):+ module.should_save_on_this_rank = lambda is_main_process: bool(is_main_process)+ patched.append(module)+ try:+ yield+ finally:+ for module in patched:+ module.__dict__.pop("should_save_on_this_rank", None)+++def _wait_for_writer(+ dist,+ writer,+ writer_rank = 0,+):+ """The other ranks wait for the writer's write, so no later collective overtakes it. A store key,+ not a barrier: a merged or quantized export (and a Hub upload) can outlast the process group's+ collective timeout, and NCCL ranks blocked in a barrier would abort before the writer arrives.+ Keyed per writer rank so disjoint sub-meshes do not release each other."""+ _SAVE_COUNTER[writer_rank] = _SAVE_COUNTER.get(writer_rank, 0) + 1+ count = _SAVE_COUNTER[writer_rank]+ key = (+ f"unsloth_fsdp2_save_{count}"+ if writer_rank == 0+ else f"unsloth_fsdp2_save_r{writer_rank}_{count}"+ )try:store = dist.distributed_c10d._get_default_store()except Exception:@@ -221,14 +281,15 @@ def fsdp2_gathered(if not units or DTensor is None:yield Nonereturn- dist = _dist()- rank = dist.get_rank() if dist is not None else 0- writer = rank == 0for unit in units:# An eval forward leaves the last block and the lm_head unit gathered; make every# parameter a DTensor again so all ranks gather the same list.if hasattr(unit, "reshard"):unit.reshard()+ dist = _dist()+ rank = dist.get_rank() if dist is not None else 0+ writer_rank = mesh_writer_rank(model)+ writer = rank == writer_rankowners = {}for module in model.modules():for name, param in module._parameters.items():@@ -278,7 +339,8 @@ def fsdp2_gathered(_ACTIVE.append(writer)_STAGED_4BIT.append(staged)pushed = True- yield writer+ with writes_off_rank0(model, writer_rank if writer else 0):+ yield writerfinally:if pushed:_ACTIVE.pop()@@ -289,7 +351,7 @@ def fsdp2_gathered(module._parameters[name] = oldreplaced.clear()if dist is not None:- _wait_for_writer(dist, writer)+ _wait_for_writer(dist, writer, writer_rank)def _is_4bit_base(base_layer):