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: fully_shard per block and root for every model, LoRA, QLoRA and full finetuning (UNSLOTH_FSDP2=1) (#14273)
Daniel Hanc280b6f7d044
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.ymlindex cc16ad709c0..328e3bbc093 100644--- a/.github/workflows/studio-backend-ci.yml+++ b/.github/workflows/studio-backend-ci.yml@@ -464,8 +464,15 @@ jobs:--ignore=tests/sh--ignore=tests/vllm_compat--ignore=tests/version_compat+ --ignore-glob=tests/test_fsdp2*.py--deselect tests/test_model_registry.py::test_model_registration--deselect tests/test_model_registry.py::test_all_model_registration+ # Native FSDP2's gloo tests spawn 2 to 4 ranks each: about ten minutes of this+ # runner on their own, which pushed the catch-all to the 2100 s step cap. They run+ # beside it instead.+ - shard: fsdp2+ selection: >-+ tests/test_fsdp2*.pysteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:diff --git a/tests/studio/test_backend_ci_parallel_isolation.py b/tests/studio/test_backend_ci_parallel_isolation.pyindex 5d6f7440891..0a064114161 100644--- a/tests/studio/test_backend_ci_parallel_isolation.py+++ b/tests/studio/test_backend_ci_parallel_isolation.py@@ -318,15 +318,15 @@ def test_the_command_scan_sees_the_parallel_run_and_the_serial_steps():"""Pin the parser: a scan that matched nothing would pass both tests above."""commands = _pytest_commands()parallel = [command for command in commands if " -n " in f" {command} "]- assert len(parallel) == 6, (- f"expected six parallel pytest runs, three shards of the backend matrix and three "+ assert len(parallel) == 7, (+ f"expected seven parallel pytest runs, three shards of the backend matrix and four "f"of repo-cpu-tests, got {parallel}. If a job stopped running in parallel, or a "f"shard was added or removed, say so here rather than letting this scan quietly "f"cover fewer runs.")root = [command for command in parallel if _over_the_repo_tests(command)]- assert len(root) == 3, (- f"expected the three repo-root shards, got {root}. The isolation checks above apply "+ assert len(root) == 4, (+ f"expected the four repo-root shards, got {root}. The isolation checks above apply "f"to those, and a scan that matched none of them would pass on nothing.")backend = [command for command in parallel if _over_the_backend(command)]diff --git a/tests/test_block_compile.py b/tests/test_block_compile.pyindex 3eaff4ac76d..a3b09de69ad 100644--- a/tests/test_block_compile.py+++ b/tests/test_block_compile.py@@ -667,12 +667,15 @@ def test_nf4_block_route_matches_both_checkpoint_halves(monkeypatch, linear_env)O._TRACE, O._TRACE_BF16, O._LINEAR = True, True, linear_envO._eligible = lambda self, x, weight, quant_state: TrueO._linear = lambda x, weight, quant_state, bias: torch.full_like(x, 7.0)+ O._float_packed_as_uint8 = lambda weight: weightkernels.bnb_override = Oclass Linear4bit(torch.nn.Module):def __init__(self, dtype, bias):super().__init__()- self.weight = types.SimpleNamespace(quant_state = types.SimpleNamespace(dtype = dtype))+ self.weight = types.SimpleNamespace(+ dtype = torch.uint8, quant_state = types.SimpleNamespace(dtype = dtype)+ )self.bias = torch.nn.Parameter(torch.zeros(8)) if bias else Nonedef forward(self, x):diff --git a/tests/test_bnb_nf4_override.py b/tests/test_bnb_nf4_override.pyindex 33320853d3e..1c2a195e976 100644--- a/tests/test_bnb_nf4_override.py+++ b/tests/test_bnb_nf4_override.py@@ -449,3 +449,66 @@ def test_compiled_dynamic_decode_through_module_no_breaks():assert (y.float() - ref.float()).abs().max().item() <= 4 * torch.finfo(dtype).eps * ref.abs().max().item()+++@needs_override[email protected]("dtype", [torch.bfloat16, torch.float16])[email protected]("rows", [1, 2 * 1025])+def test_float_packed_storage_runs_the_override_bit_exact(dtype, rows, monkeypatch):+ """FSDP2 stores the packed NF4 bytes in the compute dtype (`bnb_4bit_quant_storage`) so it can+ shard them; the all-gathered weight is the same bytes typed as that dtype. The override must still+ run on it (not fall back to bitsandbytes) and give bitsandbytes' result on the uint8 layer."""+ lin = _layer(1000, 576, dtype)+ ref = _layer(1000, 576, dtype)+ # What fsdp2_qlora.params4bit_to_float_storage does: same bytes, float element type.+ lin.weight.data = lin.weight.data.reshape(-1).view(dtype).reshape(-1, 1)+ lin.weight.quant_storage = dtype+ assert torch.equal(lin.weight.data.reshape(-1).view(torch.uint8), ref.weight.data.reshape(-1))+ x0 = torch.randn(rows, 576, device = "cuda", dtype = dtype)+ _call(ref, x0[:8], False)+ _call(lin, x0[:8], False)+ assert O._eligible(lin, x0, O._float_packed_as_uint8(lin.weight), lin.weight.quant_state)+ if rows == 1:+ with torch.no_grad():+ want = _call(ref, x0, True)+ calls, _ = _count_fallback(monkeypatch)+ got = _call(lin, x0, True)+ assert not calls, "the override fell back to bitsandbytes"+ assert _bits(got, want)+ return+ dy = torch.randn(rows, 1000, device = "cuda", dtype = dtype)+ outs, grads = [], []+ for layer, ours in ((ref, False), (lin, True)):+ x = x0.clone().requires_grad_()+ if ours:+ calls, _ = _count_fallback(monkeypatch)+ y = _call(layer, x, ours)+ y.backward(dy)+ outs.append(y.detach())+ grads.append(x.grad)+ assert not calls, "the override fell back to bitsandbytes"+ assert _bits(outs[1], outs[0]), "forward differs from bitsandbytes"+ assert _bits(grads[1], grads[0]), "dX differs from bitsandbytes"+++@needs_override+def test_float_packed_gate_reads_the_weight_not_a_global(monkeypatch):+ """The float-packed route is chosen from the weight itself (float dtype, contiguous (N, 1)), never+ from a process-global flag that Dynamo would guard on. A uint8 weight takes exactly the previous+ path, and a float weight of any other shape is left to bitsandbytes."""+ assert not hasattr(O._U, "_FSDP2_QLORA_PREPARED")+ lin = _layer(1000, 576, torch.bfloat16)+ lin.weight.data = lin.weight.data.reshape(-1).view(torch.bfloat16).reshape(-1, 1)+ lin.weight.quant_storage = torch.bfloat16+ ref = _layer(1000, 576, torch.bfloat16)+ x = torch.randn(4, 576, device = "cuda", dtype = torch.bfloat16)+ _call(ref, x, False)+ _call(lin, x, False)+ with torch.no_grad():+ calls, _ = _count_fallback(monkeypatch)+ _call(ref, x, True)+ assert not calls, "uint8 weight lost the override"+ _call(lin, x, True)+ assert not calls, "float-packed (N, 1) weight fell back to bitsandbytes"+ flat = torch.zeros(4, 8, dtype = torch.bfloat16)+ assert O._float_packed_as_uint8(flat) is flatdiff --git a/tests/test_ci_repo_cpu_shards.py b/tests/test_ci_repo_cpu_shards.pyindex b64509cafb8..1595236c279 100644--- a/tests/test_ci_repo_cpu_shards.py+++ b/tests/test_ci_repo_cpu_shards.py@@ -3,6 +3,7 @@"""Each tests/ directory is claimed by exactly one Repo tests (CPU) shard, the third a catch-all."""+import fnmatchfrom pathlib import Pathimport pytest@@ -39,7 +40,7 @@ def _shards() -> dict:index = 0while index < len(tokens):token = tokens[index]- if token.startswith("--ignore="):+ if token.startswith(("--ignore=", "--ignore-glob=")):ignores.append(token.split("=", 1)[1].rstrip("/"))elif token == "--deselect":index += 1 # a test id, not a path@@ -53,6 +54,8 @@ def _shards() -> dict:def _covers(prefix: str, path: str) -> bool:+ if "*" in prefix: # a shell-expanded root or an --ignore-glob, matched like pytest does+ return fnmatch.fnmatch(path, prefix)prefix = prefix.rstrip("/")return path == prefix or path.startswith(prefix + "/")diff --git a/tests/test_fsdp2_detection.py b/tests/test_fsdp2_detection.pyindex ef6057c8f50..f89952e7e36 100644--- a/tests/test_fsdp2_detection.py+++ b/tests/test_fsdp2_detection.py@@ -42,8 +42,27 @@ def _load_launch():@pytest.fixture(autouse = True)def _clean_env(monkeypatch):+ # apply_unsloth_fsdp2_launch_env writes os.environ directly, which monkeypatch does not undo for+ # keys that were absent; restore the whole environment so nothing leaks into later test files.+ saved = dict(os.environ)for key in _ENV:monkeypatch.delenv(key, raising = False)+ # These tests cover the accelerate FSDP2 launch; UNSLOTH_FSDP2=1 alone now selects Unsloth's native+ # fully_shard wrap (test_native_backend_exports_nothing).+ monkeypatch.setenv("UNSLOTH_FSDP2_BACKEND", "accelerate")+ yield+ os.environ.clear()+ os.environ.update(saved)+++def test_native_backend_exports_nothing(monkeypatch, launch):+ monkeypatch.delenv("UNSLOTH_FSDP2_BACKEND")+ monkeypatch.setenv("UNSLOTH_FSDP2", "1")+ monkeypatch.setenv("WORLD_SIZE", "2")+ assert launch.unsloth_fsdp2_native_requested()+ assert launch.fsdp_version_from_env() == 2+ assert launch.apply_unsloth_fsdp2_launch_env() is False+ assert "ACCELERATE_USE_FSDP" not in os.environ and "FSDP_VERSION" not in os.environ@pytest.fixture@@ -118,7 +137,7 @@ def test_reshard_after_forward_switch(monkeypatch, launch, value, expected):def _fake_accelerate(monkeypatch, launch, tmp_path, source):(tmp_path / "utils").mkdir()- (tmp_path / "utils" / "fsdp_utils.py").write_text(source)+ (tmp_path / "utils" / "fsdp_utils.py").write_text(source, encoding = "utf-8")spec = importlib.util.spec_from_file_location("accelerate", tmp_path / "__init__.py")spec.submodule_search_locations = [str(tmp_path)]monkeypatch.setattr(launch.importlib.util, "find_spec", lambda name: spec)@@ -271,7 +290,7 @@ def _rank_worker(rank, port, out_dir):everyone = [None, None]dist.all_gather_object(everyone, mine)if rank == 0:- with open(os.path.join(out_dir, "ranks.json"), "w") as f:+ with open(os.path.join(out_dir, "ranks.json"), "w", encoding = "utf-8") as f:json.dump(everyone, f)finally:dist.destroy_process_group()@@ -286,7 +305,7 @@ def test_every_rank_reads_the_same_fsdp2_launch(tmp_path):import torch.multiprocessing as mpmp.spawn(_rank_worker, args = (_free_port(), str(tmp_path)), nprocs = 2, join = True)- ranks = json.loads((tmp_path / "ranks.json").read_text())+ ranks = json.loads((tmp_path / "ranks.json").read_text(encoding = "utf-8"))assert ranks[0] == ranks[1] == [2, "true", "TRANSFORMER_BASED_WRAP"]diff --git a/tests/test_fsdp2_native_accel_devices.py b/tests/test_fsdp2_native_accel_devices.pynew file mode 100644index 00000000000..41d98c05ebd--- /dev/null+++ b/tests/test_fsdp2_native_accel_devices.py@@ -0,0 +1,66 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 runs on CUDA / ROCm or the CPU only: a model on XPU (or another non-CUDA+accelerator), an explicit non-CUDA device, or a CPU model on a host whose accelerator is not CUDA+(where the Trainer would run the batches on it) is refused before any process group or mesh."""++import os+import sys++import pytest+import torch++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_pg_tp_media_gloo import ( # noqa: E402,F401+ Params4bit,+ _FakeModel,+ _T,+ native_env,+)+from test_fsdp2_native_guards_gloo import _shard_device_seen, _tiny_llama # noqa: E402+++def test_xpu_model_is_refused(native_env):+ native = native_env+ with pytest.raises(RuntimeError, match = "CUDA / ROCm.*uses xpu"):+ native._shard_device(_FakeModel([_T("xpu:0"), _T("xpu:0")]))+ with pytest.raises(RuntimeError, match = "uses xpu"):+ native._shard_device(_FakeModel([_T("cpu")]), "xpu")+ with pytest.raises(RuntimeError, match = "uses hpu"):+ native._shard_device(_FakeModel([_T("cpu"), _T("hpu")]))+++def test_cpu_model_on_a_non_cuda_accelerator_host_is_refused(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ monkeypatch.setattr(native, "_non_cuda_accelerator", lambda: "xpu", raising = False)+ with pytest.raises(RuntimeError, match = "uses xpu"):+ native.shard_model(_tiny_llama(), native.FSDP2Config(param_dtype = torch.float32))+ # The CPU asked for explicitly (TrainingArguments(use_cpu = True)) still runs.+ assert native._shard_device(_FakeModel([_T("cpu")]), "cpu").type == "cpu"+ monkeypatch.setenv("ACCELERATE_USE_CPU", "true")+ assert native._shard_device(_FakeModel([_T("cpu")])).type == "cpu"+++def test_cpu_only_host_keeps_the_cpu_mesh(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ monkeypatch.setattr(native, "_non_cuda_accelerator", lambda: None, raising = False)+ assert _shard_device_seen(native, monkeypatch, _tiny_llama()).type == "cpu"+++def test_cpu_mesh_refuses_gpu_resident_quantized_weights(native_env, monkeypatch):+ """use_cpu = True with a 4-bit model already on the GPU: the CPU mesh does not replicate frozen+ weights, so fully_shard would move packed storage away from its quantization state."""+ native = native_env+ model = _FakeModel([_T("cuda:0"), Params4bit("cuda:0")])+ with pytest.raises(RuntimeError, match = "CPU mesh .*quantized weights are on the GPU"):+ native._shard_device(model, "cpu")+ monkeypatch.setenv("ACCELERATE_USE_CPU", "true")+ with pytest.raises(RuntimeError, match = "CPU mesh .*quantized weights are on the GPU"):+ native._shard_device(model)+ # Unquantized GPU weights on a CPU mesh still move as before.+ assert native._shard_device(_FakeModel([_T("cuda:0")]), "cpu").type == "cpu"diff --git a/tests/test_fsdp2_native_accelerator_loop_gloo.py b/tests/test_fsdp2_native_accelerator_loop_gloo.pynew file mode 100644index 00000000000..cb079f8f572--- /dev/null+++ b/tests/test_fsdp2_native_accelerator_loop_gloo.py@@ -0,0 +1,343 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 and accelerate, gloo world of 2. A Trainer's own accelerator (marked by+Trainer.create_accelerator_and_postprocess) is the supported accelerate path:++* accelerator.prepare(optimizer, model) (optimizer first) still applies the native optimizer checks:+ a bitsandbytes optimizer is refused, a mixed DTensor / replicated group is split;+* accelerate's plain float16 GradScaler already skips the step on every rank when one rank's shard+ overflows (DTensor reduces the inf check: torch/distributed/tensor/_dispatch.py+ found_inf_reduce_handler), so no ShardedGradScaler swap is needed;+* get_state_dict / save_model return and write the full weights; save_state / load_state refuse,+ also when only the optimizer was prepared;+* FP8 (ACCELERATE_FP8_BACKEND) is refused before accelerate converts any layer.++An accelerator the user built (custom loop) refuses to prepare a native model, optimizer or+scheduler, before any FP8 conversion; non-native objects still prepare."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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, _full, _stub_unsloth_save # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_optim_reentry_gloo import AdamW8bitLike # noqa: E402+++def _trainer_accelerator(native, model, tmp):+ """The accelerator a real Trainer builds for `model` (the supported accelerate path)."""+ _install_wrapped_trainer_init()+ from transformers import Trainer++ trainer = Trainer(model = model, args = _targs(os.path.join(tmp, "out")))+ return trainer.accelerator+++def _mixed_lora(native):+ model = _lora(1)+ first = next(p for n, p in model.named_parameters() if "lora_A" in n)+ cfg = native.FSDP2Config(param_dtype = torch.float32, ignored_params = {first})+ return native.shard_model(model, cfg)+++def _case_order(native, tmp):+ res = {}+ model = _mixed_lora(native)+ trainable = [p for p in model.parameters() if p.requires_grad]+ try:+ _trainer_accelerator(native, model, tmp).prepare(AdamW8bitLike(trainable, lr = 1e-3), model)+ res["bnb"] = ""+ except Exception as exc:+ res["bnb"] = f"{type(exc).__name__}: {str(exc)[:160]}"+ optimizer = torch.optim.AdamW(trainable, lr = 1e-3)+ _trainer_accelerator(native, model, tmp).prepare(optimizer, model)+ res["mixed_groups_left"] = native._mixed_param_groups(optimizer)+ res["groups"] = len(optimizer.param_groups)+ return res+++def _case_scaler(native, rank, tmp):+ from torch.distributed.tensor import DTensor++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ accelerator = _trainer_accelerator(native, model, tmp)+ accelerator.scaler = torch.amp.GradScaler(+ "cpu"+ ) # what mixed_precision = "fp16" builds on a GPU+ params = [p for p in model.parameters() if p.requires_grad]+ optimizer, model = accelerator.prepare(torch.optim.SGD(params, lr = 1.0), model)+ res = {"scaler": type(accelerator.scaler).__name__}+ ids = torch.randint(1, 100, (1, 8), generator = torch.Generator().manual_seed(0))+ accelerator.backward(model(input_ids = ids, labels = ids).loss) # scaled by accelerator.scaler+ target = next(p for p in params if isinstance(p, DTensor) and p.to_local().numel())+ if rank == 0:+ target.grad.to_local().view(-1)[0] = float("inf") # overflow in rank 0's shard only+ before = target.to_local().detach().clone()+ optimizer.step()+ res["stepped"] = not torch.equal(before, target.to_local().detach())+ return res+++def _case_state(native, rank, tmp):+ from safetensors.torch import load_file+ import torch.distributed as dist++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ want = _full(model)+ res = {}+ # Only the optimizer prepared: save_state would still write this rank's DTensor shards.+ accelerator = _trainer_accelerator(native, model, tmp)+ res["marked"] = getattr(accelerator, native._TRAINER_ACCELERATOR, False)+ params = [p for p in model.parameters() if p.requires_grad]+ accelerator.prepare(torch.optim.SGD(params, lr = 1.0))+ try:+ accelerator.save_state(os.path.join(tmp, f"opt_state_{rank}"))+ res["opt_only_save_state"] = ""+ except Exception as exc:+ res["opt_only_save_state"] = f"{type(exc).__name__}: {str(exc)[:160]}"+ accelerator = _trainer_accelerator(native, model, tmp)+ model = accelerator.prepare(model)+ state = accelerator.get_state_dict(model)+ if rank == 0:+ res["n"] = len(state)+ res["plain"] = all(type(v) is torch.Tensor for v in state.values())+ res["diff"] = max(+ (state[k].float() - want[k].float()).abs().max().item() for k in want if k in state+ )+ else:+ res["n"] = len(state)+ out = os.path.join(tmp, "saved")+ accelerator.save_model(model, out)+ dist.barrier()+ if rank == 0:+ saved = {}+ for name in sorted(os.listdir(out)):+ if name.endswith(".safetensors"):+ saved.update(load_file(os.path.join(out, name)))+ res["saved_diff"] = max(+ (saved[k].float() - want[k].float()).abs().max().item() for k in want if k in saved+ )+ res["saved_n"] = sum(k in saved for k in want)+ res["want_n"] = len(want)+ for name in ("save_state", "load_state"):+ try:+ getattr(accelerator, name)(os.path.join(tmp, f"state_{rank}"))+ res[name] = ""+ except Exception as exc:+ res[name] = f"{type(exc).__name__}: {str(exc)[:160]}"+ return res+++def _attempt(fn):+ try:+ fn()+ return ""+ except Exception as exc:+ return f"{type(exc).__name__}: {str(exc)[:600]}"+++def _case_custom(native, rank, tmp):+ """A user-built Accelerator (custom loop): every route that prepares a native object refuses."""+ from accelerate import Accelerator++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ params = [p for p in model.parameters() if p.requires_grad]+ res = {}+ res["prepare_model"] = _attempt(lambda: Accelerator().prepare(model))+ res["prepare_model_direct"] = _attempt(lambda: Accelerator().prepare_model(model))+ accelerator = Accelerator()+ res["prepare_optimizer_only"] = _attempt(+ lambda: accelerator.prepare(torch.optim.SGD(params, lr = 1.0))+ )+ res["optimizer_only_save_state"] = _attempt(+ lambda: accelerator.save_state(os.path.join(tmp, f"custom_state_{rank}"))+ )+ res["prepare_optimizer_direct"] = _attempt(+ lambda: Accelerator().prepare_optimizer(torch.optim.SGD(params, lr = 1.0))+ )+ plain = torch.nn.Linear(4, 4)+ res["plain"] = _attempt(+ lambda: Accelerator().prepare(plain, torch.optim.SGD(plain.parameters(), lr = 1.0))+ )+ return res+++def _case_fp8(native, tmp):+ """accelerate converts to FP8 in prepare before prepare_model: refused before any conversion,+ on a custom accelerator and on a Trainer's."""+ from accelerate import Accelerator++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ res = {}+ for name, accelerator in (+ ("custom", Accelerator()),+ ("trainer", _trainer_accelerator(native, model, tmp)),+ ):+ converted = []++ def record(*args, _converted = converted):+ _converted.append(len(args))+ return args++ accelerator._prepare_te = record+ accelerator._prepare_ao = record+ os.environ["ACCELERATE_FP8_BACKEND"] = "TE"+ try:+ res[name] = _attempt(lambda: accelerator.prepare(model))+ finally:+ os.environ.pop("ACCELERATE_FP8_BACKEND", None)+ res[f"{name}.converted"] = len(converted)+ return res+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "order":+ res = _case_order(native, tmp)+ elif case == "scaler":+ res = _case_scaler(native, rank, tmp)+ elif case == "custom":+ res = _case_custom(native, rank, tmp)+ elif case == "fp8":+ res = _case_fp8(native, tmp)+ elif case == "state":+ res = _case_state(native, rank, tmp)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 150,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND10_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_optimizer_prepared_before_its_model_gets_the_native_checks(tmp_path):+ pytest.importorskip("accelerate")+ pytest.importorskip("peft")+ for rank, r in _run("order", tmp_path).items():+ assert r["bnb"].startswith("ValueError") and "bitsandbytes" in r["bnb"], (rank, r)+ assert r["mixed_groups_left"] == 0 and r["groups"] == 2, (rank, r)+++def test_fp16_plain_scaler_overflow_skips_on_every_rank(tmp_path):+ pytest.importorskip("accelerate")+ pytest.importorskip("peft")+ for rank, r in _run("scaler", tmp_path).items():+ assert r["scaler"] == "GradScaler", (rank, r)+ assert r["stepped"] is False, (rank, r) # rank 0's overflow skips rank 1's step too+++def test_accelerator_state_dict_is_full_and_save_state_refuses(tmp_path):+ pytest.importorskip("accelerate")+ pytest.importorskip("peft")+ results = _run("state", tmp_path)+ r0 = results[0]+ assert r0["plain"] and r0["n"] > 0 and r0["diff"] == 0.0, r0+ assert r0["saved_n"] == r0["want_n"] and r0["saved_diff"] == 0.0, r0+ assert results[1]["n"] == 0, results[1]+ for rank, r in results.items():+ assert r["marked"] is True, (rank, r)+ assert r["opt_only_save_state"].startswith("RuntimeError"), (rank, r)+ for name in ("save_state", "load_state"):+ assert r[name].startswith("RuntimeError") and "native" in r[name], (rank, name, r)+++def test_custom_accelerator_refuses_native_objects(tmp_path):+ pytest.importorskip("accelerate")+ pytest.importorskip("peft")+ for rank, r in _run("custom", tmp_path).items():+ for name in (+ "prepare_model",+ "prepare_model_direct",+ "prepare_optimizer_only",+ "prepare_optimizer_direct",+ ):+ assert r[name].startswith("RuntimeError") and "outside a Trainer" in r[name], (+ rank,+ name,+ r,+ )+ # Nothing native was registered, so save_state has nothing sharded to write.+ assert r["optimizer_only_save_state"] == "", (rank, r)+ assert r["plain"] == "", (rank, r)+++def test_accelerate_fp8_refused_before_conversion(tmp_path):+ pytest.importorskip("accelerate")+ pytest.importorskip("peft")+ for rank, r in _run("fp8", tmp_path).items():+ assert r["custom"].startswith("RuntimeError") and "outside a Trainer" in r["custom"], r+ assert r["trainer"].startswith("RuntimeError") and "FP8" in r["trainer"], r+ assert r["custom.converted"] == 0 and r["trainer.converted"] == 0, (rank, r)diff --git a/tests/test_fsdp2_native_backend_table.py b/tests/test_fsdp2_native_backend_table.pynew file mode 100644index 00000000000..bf28fe0754f--- /dev/null+++ b/tests/test_fsdp2_native_backend_table.py@@ -0,0 +1,139 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 against every accelerate distributed backend (fsdp2_launch.NATIVE_BACKEND_TABLE):+the table names every accelerate DistributedType (accelerate/utils/dataclasses.py DistributedType),+and each "refuse" row, switched on the way accelerate itself would see it (launch env, plugin+TrainingArguments, installed torch_xla, an available vendor device, SageMaker env, ParallelismConfig+env), is refused at the launch step (apply_unsloth_fsdp2_launch_env, env / package / device rows) and+at Trainer setup (every row), before the model is touched."""++import importlib.machinery+import re+import sys+import types++import pytest+import torch++sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))+from test_fsdp2_native_units import _load_native # noqa: E402++_CLEAN = (+ "ACCELERATE_USE_DEEPSPEED",+ "ACCELERATE_USE_MEGATRON_LM",+ "ACCELERATE_USE_FSDP",+ "ACCELERATE_USE_SAGEMAKER",+ "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE",+ "ACCELERATE_USE_PARALLELISM_CONFIG",+ "PARALLELISM_CONFIG_TP_SIZE",+ "ACCELERATE_USE_CPU",+ "ACCELERATE_MIXED_PRECISION",+ "USE_TORCH_XLA",+ "UNSLOTH_FSDP2_BACKEND",+)+++def native(monkeypatch):+ for key in _CLEAN:+ monkeypatch.delenv(key, raising = False)+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ return _load_native()+++def _fake_module(monkeypatch, name):+ module = types.ModuleType(name)+ module.__spec__ = importlib.machinery.ModuleSpec(name, None)+ module.__path__ = []+ monkeypatch.setitem(sys.modules, name, module)+ return module+++def _switch_on(row, monkeypatch):+ """Turn the row's backend on as accelerate would detect it; returns TrainingArguments."""+ args = types.SimpleNamespace(save_on_each_node = False)+ if row.get("env"):+ monkeypatch.setenv(row["env"][0], "true")+ elif row.get("args"):+ setattr(args, row["args"][0], object())+ elif row.get("package"):+ _fake_module(monkeypatch, row["package"])+ elif row.get("device"):+ package, attr, before_cuda = row["device"]+ if package is not None:+ parts = package.split(".")+ for i in range(len(parts)):+ _fake_module(monkeypatch, ".".join(parts[: i + 1]))+ monkeypatch.setattr(+ torch, attr, types.SimpleNamespace(is_available = lambda: True), raising = False+ )+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ elif row.get("env_pair"):+ monkeypatch.setenv(row["env_pair"][0], "true")+ monkeypatch.setenv(row["env_pair"][1], "DATA_PARALLEL")+ elif row.get("sizes"):+ monkeypatch.setenv("ACCELERATE_USE_PARALLELISM_CONFIG", "true")+ monkeypatch.setenv(row["sizes"] + "TP_SIZE", "2")+ else:+ raise AssertionError(f"row {row['type']} has no detector")+ return args+++def test_table_covers_every_accelerate_distributed_type(native):+ dataclasses = pytest.importorskip("accelerate.utils.dataclasses")+ launch = sys.modules["unsloth.fsdp2_launch"]+ names = {row["type"] for row in launch.NATIVE_BACKEND_TABLE}+ missing = {t.name for t in dataclasses.DistributedType} - names+ assert not missing, missing+ for row in launch.NATIVE_BACKEND_TABLE:+ assert row["action"] in ("handle", "refuse"), row+ assert row["action"] == "handle" or row.get("label"), row+++def test_every_refuse_row_is_refused_at_both_entry_points(native, monkeypatch):+ launch = sys.modules["unsloth.fsdp2_launch"]+ rows = [r for r in launch.NATIVE_BACKEND_TABLE if r["action"] == "refuse"]+ assert len(rows) >= 10+ for row in rows:+ with monkeypatch.context() as m:+ args = _switch_on(row, m)+ model = torch.nn.Linear(2, 2)+ weight = model.weight+ with pytest.raises(RuntimeError, match = "native FSDP2") as exc:+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ assert row["label"] in str(exc.value), (row["type"], str(exc.value))+ assert model.weight is weight and not native.is_native_fsdp2(model), row["type"]+ if not row.get("args"): # the launch step sees only the env / installed packages+ with pytest.raises(RuntimeError, match = re.escape(row["label"])):+ launch.apply_unsloth_fsdp2_launch_env()+ # Nothing on: neither entry point refuses.+ assert launch.native_backend_conflicts() == []+ assert launch.apply_unsloth_fsdp2_launch_env() is False+++def test_megatron_lm_launch_is_refused(native, monkeypatch):+ """accelerate launch --use_megatron_lm exports ACCELERATE_USE_MEGATRON_LM+ (accelerate/utils/launch.py), which AcceleratorState turns into DistributedType.MEGATRON_LM."""+ launch = sys.modules["unsloth.fsdp2_launch"]+ monkeypatch.setenv("ACCELERATE_USE_MEGATRON_LM", "true")+ with pytest.raises(RuntimeError, match = "Megatron-LM"):+ launch.apply_unsloth_fsdp2_launch_env()+ with pytest.raises(RuntimeError, match = "Megatron-LM"):+ native.native_fsdp2_trainer_setup(model = torch.nn.Linear(2, 2), phase = "pre")+++def test_xla_off_switch_and_cpu_runs_are_not_refused(native, monkeypatch):+ launch = sys.modules["unsloth.fsdp2_launch"]+ _fake_module(monkeypatch, "torch_xla")+ monkeypatch.setenv("USE_TORCH_XLA", "0") # accelerate's own off switch+ assert launch.native_backend_conflicts() == []+ monkeypatch.setattr(torch, "xpu", types.SimpleNamespace(is_available = lambda: True))+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ assert launch.native_backend_conflicts(uses_cpu = True) == []+ assert [t for t, _, _ in launch.native_backend_conflicts()] == ["MULTI_XPU"]+ # A ParallelismConfig env that is a plain shard over every rank is what native FSDP2 does.+ monkeypatch.setenv("ACCELERATE_USE_PARALLELISM_CONFIG", "true")+ monkeypatch.setenv("PARALLELISM_CONFIG_DP_SHARD_SIZE", "2")+ assert "PARALLELISM_CONFIG" not in [t for t, _, _ in launch.native_backend_conflicts()]diff --git a/tests/test_fsdp2_native_default_path.py b/tests/test_fsdp2_native_default_path.pynew file mode 100644index 00000000000..a8ceeacd557--- /dev/null+++ b/tests/test_fsdp2_native_default_path.py@@ -0,0 +1,74 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""FSDP2 off (no UNSLOTH_FSDP2, one GPU): a real Unsloth load + LoRA + SFTTrainer step in a fresh process+never imports the native FSDP2 modules (fsdp2_native, fsdp2_perf, fsdp2_native_quant, fsdp2_vision), and+patches neither accelerate nor the Trainer. Needs a GPU (import unsloth)."""++import os+import subprocess+import sys++import pytest++torch = pytest.importorskip("torch")++if not torch.cuda.is_available():+ pytest.skip("needs a GPU (import unsloth)", allow_module_level = True)++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))++_CODE = r"""+import os, sys+for k in ("UNSLOTH_FSDP2", "UNSLOTH_FSDP2_BACKEND", "WORLD_SIZE", "RANK", "LOCAL_RANK"):+ os.environ.pop(k, None)+os.environ["UNSLOTH_DISABLE_AUTO_UPDATES"] = "1"+from unsloth import FastLanguageModel+import torch+from datasets import Dataset+from trl import SFTConfig, SFTTrainer++import transformers+# Kernel-friendly tiny Llama (head_dim 64: xformers / SDPA kernels exist on every arch), random weights.+src = "hf-internal-testing/tiny-random-LlamaForCausalLM"+tok = transformers.AutoTokenizer.from_pretrained(src)+config = transformers.LlamaConfig(vocab_size = len(tok), hidden_size = 256, intermediate_size = 512,+ num_hidden_layers = 2, num_attention_heads = 4, num_key_value_heads = 2, head_dim = 64,+ max_position_embeddings = 256)+torch.manual_seed(0)+path = os.path.join(os.environ["OUT_DIR"], "tiny_llama")+transformers.LlamaForCausalLM(config).to(torch.bfloat16).save_pretrained(path)+tok.save_pretrained(path)+model, tok = FastLanguageModel.from_pretrained(path, max_seq_length = 64, load_in_4bit = False,+ dtype = torch.bfloat16)+model = FastLanguageModel.get_peft_model(model, r = 4, lora_alpha = 8, random_state = 0,+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"])+ds = Dataset.from_list([{"input_ids": list(range(5, 37)), "attention_mask": [1] * 32}] * 4)+cfg = SFTConfig(output_dir = os.environ["OUT_DIR"], per_device_train_batch_size = 2, max_steps = 1,+ logging_steps = 1, report_to = "none", save_strategy = "no", bf16 = True, max_length = 64,+ dataset_num_proc = 1)+trainer = SFTTrainer(model = model, processing_class = tok, train_dataset = ds, args = cfg)+trainer.train()+import accelerate, transformers+loaded = sorted(m for m in sys.modules if m.split(".")[-1] in+ ("fsdp2_native", "fsdp2_perf", "fsdp2_native_quant", "fsdp2_vision") and m.startswith("unsloth"))+assert not loaded, f"native FSDP2 modules imported on the default path: {loaded}"+assert not getattr(accelerate.Accelerator, "_unsloth_fsdp2_native_patched", False)+assert not getattr(transformers.Trainer, "_unsloth_fsdp2_native_patched", False)+assert not getattr(trainer.model, "_unsloth_fsdp2_native", False)+print("DEFAULT_PATH_OK", trainer.state.log_history[0].get("loss"))+"""+++def test_default_path_never_imports_native_fsdp2(tmp_path):+ env = dict(os.environ, OUT_DIR = str(tmp_path / "out"))+ env["PYTHONPATH"] = REPO + os.pathsep + env.get("PYTHONPATH", "")+ out = subprocess.run(+ [sys.executable, "-c", _CODE],+ capture_output = True,+ text = True,+ timeout = 900,+ env = env,+ cwd = str(tmp_path),+ )+ assert "DEFAULT_PATH_OK" in out.stdout, out.stdout[-3000:] + out.stderr[-5000:]diff --git a/tests/test_fsdp2_native_dora_resume_gloo.py b/tests/test_fsdp2_native_dora_resume_gloo.pynew file mode 100644index 00000000000..053e73e0adb--- /dev/null+++ b/tests/test_fsdp2_native_dora_resume_gloo.py@@ -0,0 +1,146 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 resume of a DoRA adapter (LoraConfig(use_dora = True)), gloo world of 2. PEFT saves+DoRA's magnitude `lora_magnitude_vector.<adapter>.weight` as `lora_magnitude_vector` (peft+tuners/lora/model.py LoraModel._get_adapter_state_dict, called from get_peft_model_state_dict in+peft/utils/save_and_load.py). The native resume now asks PEFT's own save path for the key of every+parameter, and its fallback rule (no PEFT answer) mirrors the DoRA rename too: both restore every+adapter tensor exactly."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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 ( # noqa: E402+ REPO_ID,+ _free_port,+ _full,+ _stub_unsloth_save,+ _trainer,+)+++def _dora(seed):+ import transformers+ from peft import LoraConfig, get_peft_model++ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ config.pad_token_id = None+ torch.manual_seed(0)+ model = transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None+ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"], use_dora = True)+ model = get_peft_model(model, cfg)+ g = torch.Generator().manual_seed(seed)+ with torch.no_grad():+ for n, p in model.named_parameters():+ if "lora_" in n:+ p.normal_(0, 0.02, generator = g)+ return model+++def _worker(rank, world, port, out, tmp, fallback):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 60)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if fallback:+ native._peft_save_keys = lambda root, adapter: {} # no PEFT answer: the rule alone+ cfg = native.FSDP2Config(param_dtype = torch.float32)+ ckpt = os.path.join(tmp, "ckpt")+ src = native.shard_model(_dora(1), cfg)+ _trainer(src, tmp).save_model(ckpt)+ dist.barrier()+ want = _full(src, trainable_only = True)+ dst = native.shard_model(_dora(2), cfg)+ res = {"magnitudes": sum("lora_magnitude_vector" in n for n in want)}+ keys = native._peft_save_keys(native._native_root(dst), "default")+ res["peft_magnitude_keys"] = sum(+ v.endswith(".lora_magnitude_vector") for k, v in keys.items() if "magnitude" in k+ )+ try:+ native.native_load_model_checkpoint(dst, ckpt)+ got = _full(dst, trainable_only = True)+ res["max_diff"] = max((got[n] - want[n]).abs().max().item() for n in want)+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ tmp_path,+ fallback,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, str(tmp_path), fallback),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail("dora: the ranks did not finish (hung collective)")+ except mp.ProcessExitedException as exc:+ pytest.fail(f"dora: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND14_RESULT dora", fallback, rank, r)+ assert "crash" not in r, r["crash"]+ return results++[email protected]("fallback", [False, True], ids = ["peft_keys", "rule_only"])+def test_dora_adapter_resumes_exactly(tmp_path, fallback):+ pytest.importorskip("peft")+ for rank, r in _run(tmp_path, fallback).items():+ assert r["magnitudes"] > 0, (rank, r)+ # PEFT answers on its own (DoRA's key without ".weight"), unless switched off for the rule.+ assert r["peft_magnitude_keys"] == (0 if fallback else r["magnitudes"]), (rank, r)+ assert "load_error" not in r and r["max_diff"] == 0.0, (rank, r)diff --git a/tests/test_fsdp2_native_generic_media_gloo.py b/tests/test_fsdp2_native_generic_media_gloo.pynew file mode 100644index 00000000000..0c19f03c370--- /dev/null+++ b/tests/test_fsdp2_native_generic_media_gloo.py@@ -0,0 +1,276 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 generic media agreement (gloo world of 2): a multimodal model with trainable or+FSDP-managed parameters outside its language model gets one agreement on its outermost forward+over every non-text forward input, whatever the encoder is called.++* Fuyu (transformers/models/fuyu/modeling_fuyu.py: FuyuModel.forward takes `image_patches` and runs+ `vision_embed_tokens` only when it is given, :147-181) with a trainable `vision_embed_tokens`;+* MusicFlamingo / VoxtralRealtime (transformers/models/musicflamingo/modeling_musicflamingo.py+ get_audio_features :223-247, voxtral_realtime/modeling_voxtral_realtime.py :897-928): a frozen,+ replicated audio tower and a sharded `multi_modal_projector` reached only inside+ get_audio_features;++a mixed batch raises on every rank, naming the inputs; uniform batches train; a text-only model+installs nothing."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import importlib # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402+import torch.nn as nn # noqa: E402++sys.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+++class _Decoder(nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = nn.ModuleList(nn.Linear(8, 8) for _ in range(2))++ def forward(self, h):+ for layer in self.layers:+ h = h + layer(h)+ return h+++class _FuyuLike(nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed_tokens = nn.Embedding(16, 8).requires_grad_(False)+ self.vision_embed_tokens = nn.Linear(12, 8) # trainable+ self.language_model = _Decoder()+ self.lm_head = nn.Linear(8, 4)++ def get_input_embeddings(self):+ return self.embed_tokens++ def forward(+ self,+ input_ids,+ image_patches = None,+ image_patches_indices = None,+ attention_mask = None,+ labels = None,+ ):+ h = self.embed_tokens(input_ids)+ if image_patches is not None:+ h = h + self.vision_embed_tokens(image_patches).mean(1, keepdim = True)+ return self.lm_head(self.language_model(h)).square().mean()+++class _AudioTower(nn.Module):+ def __init__(self):+ super().__init__()+ self.conv = nn.Linear(3, 8)++ def forward(+ self,+ input_features,+ input_features_mask = None,+ ):+ return self.conv(input_features)+++class _MusicFlamingoLike(nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.audio_tower = _AudioTower().requires_grad_(False) # frozen, replicated+ self.multi_modal_projector = nn.Sequential(nn.Linear(8, 8), nn.GELU(), nn.Linear(8, 8))+ self.embed_tokens = nn.Embedding(16, 8).requires_grad_(False)+ self.language_model = _Decoder()+ self.lm_head = nn.Linear(8, 4)++ def get_input_embeddings(self):+ return self.embed_tokens++ def get_audio_features(self, input_features, input_features_mask):+ return self.multi_modal_projector(self.audio_tower(input_features, input_features_mask))++ def forward(+ self,+ input_ids,+ input_features = None,+ input_features_mask = None,+ attention_mask = None,+ ):+ h = self.embed_tokens(input_ids)+ if input_features is not None:+ h = h + self.get_audio_features(input_features, input_features_mask).mean(+ 1, keepdim = True+ )+ return self.lm_head(self.language_model(h)).square().mean()+++class _TextOnly(nn.Module):+ def __init__(self):+ super().__init__()+ self.embed_tokens = nn.Embedding(16, 8)+ self.layers = nn.ModuleList(nn.Linear(8, 8) for _ in range(2))++ def forward(+ self,+ input_ids,+ attention_mask = None,+ labels = None,+ num_items_in_batch = None,+ ):+ h = self.embed_tokens(input_ids)+ for layer in self.layers:+ h = layer(h)+ return h.square().mean()+++def _shard(+ model,+ mesh,+ extra = (),+):+ from torch.distributed.fsdp import fully_shard++ for layer in model.language_model.layers:+ fully_shard(layer, mesh = mesh)+ for module in extra:+ fully_shard(module, mesh = mesh)+ ignored = set(model.audio_tower.parameters()) if hasattr(model, "audio_tower") else None+ fully_shard(model, mesh = mesh, ignored_params = ignored)+ return model+++def _steps(model, rank, media):+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ res = {}+ for step, given in (("all_text", False), ("all_media", True), ("mixed", rank == 0)):+ kwargs = media() if given else {}+ try:+ model(ids, **kwargs).backward()+ res[step] = "ok"+ except Exception as exc:+ res[step] = f"{type(exc).__name__}: {str(exc)[:400]}"+ return res+++def _case(rank, case):+ from torch.distributed.device_mesh import init_device_mesh++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ if case == "fuyu":+ model = _shard(_FuyuLike(), mesh)+ media = lambda: { # noqa: E731+ "image_patches": torch.randn(1, 3, 12),+ "image_patches_indices": torch.arange(3).view(1, 3),+ }+ elif case == "flamingo":+ model = _MusicFlamingoLike()+ model = _shard(model, mesh, extra = [model.multi_modal_projector])+ media = lambda: { # noqa: E731+ "input_features": torch.randn(1, 6, 3),+ "input_features_mask": torch.ones(1, 6, dtype = torch.long),+ }+ else:+ from torch.distributed.fsdp import fully_shard++ model = _TextOnly()+ for layer in model.layers:+ fully_shard(layer, mesh = mesh)+ fully_shard(model, mesh = mesh)+ host = vision.install_vision_dummy(model)+ return {"host": None if host is None else type(host).__name__}+ host = vision.install_vision_dummy(model)+ res = {"host": None if host is None else type(host).__name__}+ res.update(_steps(model, rank, media))+ return res+++def _worker(rank, world, port, out, case):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ _load_native()+ out.put((rank, _case(rank, case)))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(case, timeout = 150):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker, args = (2, _free_port(), out, case), nprocs = 2, join = False, start_method = "spawn"+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND14_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++ "case, names",+ [+ ("fuyu", ("image_patches", "image_patches_indices")),+ ("flamingo", ("input_features", "input_features_mask")),+ ],+)+def test_mixed_media_raises_on_every_rank(case, names):+ for rank, r in _run(case).items():+ assert r["host"] is not None, (rank, r)+ assert r["all_text"] == "ok" and r["all_media"] == "ok", (rank, r)+ assert r["mixed"].startswith("RuntimeError") and "on 1 of 2 ranks" in r["mixed"], (rank, r)+ for name in names:+ assert name in r["mixed"], (rank, name, r)+++def test_text_only_model_installs_nothing():+ for rank, r in _run("text").items():+ assert r["host"] is None, (rank, r)diff --git a/tests/test_fsdp2_native_guards_gloo.py b/tests/test_fsdp2_native_guards_gloo.pynew file mode 100644index 00000000000..49b509c20e2--- /dev/null+++ b/tests/test_fsdp2_native_guards_gloo.py@@ -0,0 +1,289 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 guards, on a gloo CPU world of 2 where a process group is needed:++* a resume restores every adapter PEFT saved (inactive ones under <ckpt>/<name>/ too);+* TrainingArguments(deepspeed = ...) / a DeepSpeed plugin is refused before the model is sharded;+* a model still on the CPU is sharded onto the local rank's GPU when CUDA is used (a deliberate+ CPU / disk device_map and CPU 4-bit weights are refused);+* replicated trainable parameters average their gradients once per backward on every rank, also+ when one rank did not use a parameter (a per-parameter hook all_reduce hangs or mismatches)."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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 ( # noqa: E402+ REPO_ID,+ _free_port,+ _full,+ _stub_unsloth_save,+)+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+++class _Replicated(torch.nn.Module):+ """A sharded body plus three replicated (ignored_params) parameters: `rep` used by every rank,+ `extra` used only where the forward says so, `never` used by no rank."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.body = torch.nn.Linear(8, 8)+ self.rep = torch.nn.Parameter(torch.zeros(3))+ self.extra = torch.nn.Parameter(torch.zeros(5))+ self.never = torch.nn.Parameter(torch.zeros(2))++ def forward(self, x, k, c):+ out = self.body(x).sum() + k * self.rep.sum()+ if c:+ out = out + c * self.extra.sum()+ return out+++def _case_replicated_unused(rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ _load_native()+ save = sys.modules.get("unsloth.models.fsdp2_save")+ if save is None:+ import importlib+ save = importlib.import_module("unsloth.models.fsdp2_save")+ model = _Replicated()+ mesh = init_device_mesh("cpu", (2,))+ fully_shard(model.body, mesh = mesh)+ fully_shard(model, mesh = mesh, ignored_params = {model.rep, model.extra, model.never})+ names = save.reduce_unsharded_trainable_grads(model)+ x = torch.randn(4, 8, generator = torch.Generator().manual_seed(rank))+ # Two accumulated micro-steps: `extra` is used by rank 0 in the first, by rank 1 in the second.+ model(x, k = float(rank + 1), c = 3.0 if rank == 0 else 0.0).backward()+ model(x, k = float(10 * (rank + 1)), c = 5.0 if rank == 1 else 0.0).backward()+ return {+ "names": sorted(names),+ "rep": model.rep.grad.tolist(),+ "extra": model.extra.grad.tolist() if model.extra.grad is not None else None,+ "never": None if model.never.grad is None else model.never.grad.tolist(),+ }+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ res = {}+ if case == "all_adapters":+ from transformers import Trainer++ cfg = native.FSDP2Config(param_dtype = torch.float32)+ ckpt = os.path.join(tmp, "ckpt")+ src = native.shard_model(_lora(1, same_config_adapter = True), cfg)+ Trainer(model = src, args = _targs(os.path.join(tmp, "out"))).save_model(ckpt)+ dist.barrier()+ want = _full(src)+ dst = native.shard_model(_lora(2, same_config_adapter = True), cfg)+ try:+ native.native_load_model_checkpoint(dst, ckpt)+ got = _full(dst)+ for adapter in ("default", "other"):+ keys = [n for n in want if f".{adapter}." in n]+ res[f"n_{adapter}"] = len(keys)+ res[f"{adapter}_diff"] = max(+ (got[n] - want[n]).abs().max().item() for n in keys+ )+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ elif case == "deepspeed":+ _install_wrapped_trainer_init()+ from transformers import Trainer++ model = _lora(1)+ targs = _targs(os.path.join(tmp, "out"))+ targs.deepspeed = {"train_micro_batch_size_per_gpu": 1} # deepspeed is not installed+ try:+ Trainer(model = model, args = targs)+ res["error"] = ""+ except Exception as exc:+ res["error"] = f"{type(exc).__name__}: {exc}"+ res["sharded"] = native.is_native_fsdp2(model)+ elif case == "replicated_unused":+ res = _case_replicated_unused(rank)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 240,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(f"{case}: the ranks did not finish within {timeout} s (hung collective)")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("GUARD_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_resume_restores_inactive_adapters(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("all_adapters", tmp_path).items():+ assert "load_error" not in r, (rank, r)+ assert r["n_default"] > 0 and r["default_diff"] == 0.0, (rank, r)+ assert r["n_other"] > 0 and r["other_diff"] == 0.0, (rank, r)+++def test_deepspeed_training_args_are_refused_before_sharding(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("deepspeed", tmp_path).items():+ assert r["error"].startswith("RuntimeError") and "DeepSpeed" in r["error"], (rank, r)+ assert r["sharded"] is False, (rank, r)+++def test_replicated_grads_sync_when_one_rank_skips_a_parameter(tmp_path):+ results = _run("replicated_unused", tmp_path, timeout = 120)+ for rank, r in results.items():+ assert r["names"] == ["extra", "never", "rep"], (rank, r)+ # (1 + 2) / 2 + (10 + 20) / 2, and (3 + 5) / 2 (each rank used `extra` in one micro-step).+ assert r["rep"] == [16.5] * 3, (rank, r)+ assert r["extra"] == [4.0] * 5, (rank, r)+ assert r["never"] is None, (rank, r)+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def native_env(monkeypatch):+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ monkeypatch.delenv("ACCELERATE_USE_DEEPSPEED", raising = False)+ return _load_native()+++def test_deepspeed_plugin_and_env_are_refused(native_env, monkeypatch):+ native = native_env+ model = torch.nn.Linear(2, 2)+ args = types.SimpleNamespace(deepspeed = None, deepspeed_plugin = object(), save_on_each_node = False)+ with pytest.raises(RuntimeError, match = "DeepSpeed"):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ monkeypatch.setenv("ACCELERATE_USE_DEEPSPEED", "true")+ with pytest.raises(RuntimeError, match = "DeepSpeed"):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = None)+++class _Stop(Exception):+ pass+++def _tiny_llama():+ import transformers+ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ return transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+++def _shard_device_seen(native, monkeypatch, model):+ seen = {}++ def _record(device, *_):+ seen["device"] = device+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _record)+ with pytest.raises(_Stop):+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ return seen["device"]+++def test_cpu_model_is_sharded_onto_the_local_gpu(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ monkeypatch.setenv("LOCAL_RANK", "1")+ assert _shard_device_seen(native, monkeypatch, _tiny_llama()) == torch.device("cuda", 1)+++def test_cpu_offloaded_or_4bit_model_is_refused(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ monkeypatch.setenv("LOCAL_RANK", "1")+ model = _tiny_llama()+ model.hf_device_map = {"model.embed_tokens": 0, "model.layers": "cpu", "lm_head": "disk"}+ with pytest.raises(RuntimeError, match = "offloads weights"):+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))++ class Params4bit(torch.nn.Parameter):+ pass++ model = _tiny_llama()+ proj = model.model.layers[0].self_attn.q_proj+ proj.weight = Params4bit(proj.weight.detach().clone(), requires_grad = False)+ with pytest.raises(RuntimeError, match = "4-bit model on the CPU"):+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ # No GPU in use (CUDA unavailable): the CPU run keeps its CPU mesh.+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ assert _shard_device_seen(native, monkeypatch, _tiny_llama()).type == "cpu"diff --git a/tests/test_fsdp2_native_infer_embed_audio_gloo.py b/tests/test_fsdp2_native_infer_embed_audio_gloo.pynew file mode 100644index 00000000000..d8688ade7fd--- /dev/null+++ b/tests/test_fsdp2_native_infer_embed_audio_gloo.py@@ -0,0 +1,397 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 (gloo CPU world of 2 where a process group is needed):++* `_get_inference_mode_context_manager` picks no_grad (not inference_mode) under native FSDP2, whose+ launch exports no accelerate FSDP variable: a unit gathered under inference mode breaks the next+ training step;+* a resume restores LoRA on an nn.Embedding (`lora_embedding_A.<adapter>`, saved without the name);+* `input_values` audio (PeAudioVideo-style, run by a submodule only some ranks reach) is agreed on a+ host every rank runs, and a mixed batch raises on every rank;+* q_galore_config is refused before sharding;+* native_clip_grad_norm_ with a negative norm type and an empty local shard matches torch."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import importlib # noqa: E402+import math # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import ( # noqa: E402+ REPO_ID,+ _free_port,+ _full,+ _stub_unsloth_save,+)+from test_fsdp2_native_trainer_args_gloo import _targs # noqa: E402+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402++NEGATIVE_NORMS = (-1.0, -2.0, -0.5, -math.inf)+++def _inference_helper():+ """`_get_inference_mode_context_manager` from _utils.py (self-contained: GRPO's compiled trainer+ copies its source too)."""+ path = os.path.join(REPO, "unsloth", "models", "_utils.py")+ src = open(path, encoding = "utf-8").read()+ fn = next(+ n+ for n in ast.parse(src).body+ if isinstance(n, ast.FunctionDef) and n.name == "_get_inference_mode_context_manager"+ )+ ns = {"torch": torch}+ exec(compile(ast.Module(body = [fn], type_ignores = []), path, "exec"), ns)+ return ns["_get_inference_mode_context_manager"]+++def _case_inference(native):+ helper = _inference_helper()+ model = native.shard_model(_tiny_llama(), native.FSDP2Config(param_dtype = torch.float32))+ inner = model.model # what generate() / GRPO log-prob code pass: often not the sharded root+ ids = torch.randint(1, 100, (1, 8), generator = torch.Generator().manual_seed(0))+ res = {"kind": type(helper(inner)).__name__}+ try:+ with helper(inner):+ model(input_ids = ids)+ model(input_ids = ids, labels = ids).loss.backward()+ res["train_after"] = "ok"+ except Exception as exc:+ res["train_after"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++def _embedding_lora(seed):+ import transformers+ from peft import LoraConfig, get_peft_model++ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ config.pad_token_id = None+ torch.manual_seed(0)+ model = transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None+ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["embed_tokens", "q_proj"])+ model = get_peft_model(model, cfg)+ g = torch.Generator().manual_seed(seed)+ with torch.no_grad():+ for n, p in model.named_parameters():+ if "lora_" in n:+ p.normal_(0, 0.02, generator = g)+ return model+++def _case_embedding(native, tmp):+ from transformers import Trainer+ import torch.distributed as dist++ cfg = native.FSDP2Config(param_dtype = torch.float32)+ ckpt = os.path.join(tmp, "ckpt")+ src = native.shard_model(_embedding_lora(1), cfg)+ Trainer(model = src, args = _targs(os.path.join(tmp, "out"))).save_model(ckpt)+ dist.barrier()+ want = _full(src, trainable_only = True)+ dst = native.shard_model(_embedding_lora(2), cfg)+ res = {"embedding_keys": sorted(n for n in want if "lora_embedding" in n)}+ try:+ native.native_load_model_checkpoint(dst, ckpt)+ got = _full(dst, trainable_only = True)+ res["diff"] = max((got[n] - want[n]).abs().max().item() for n in want)+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ return res+++class _AudioModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.audio_encoder = torch.nn.Linear(3, 8)+ self.embed = torch.nn.Embedding(16, 8)++ def forward(self, input_ids, input_values):+ return self.embed(input_ids) + self.audio_encoder(input_values).mean(1, keepdim = True)+++class _AudioText(torch.nn.Module):+ """PeAudioVideoModel-like: `audio_model` (with its own forward taking input_values) runs only+ when audio is given; the text path otherwise."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.audio_model = _AudioModel()+ self.text = torch.nn.Embedding(16, 8)+ self.head = torch.nn.Linear(8, 4)++ def forward(+ self,+ input_ids,+ input_values = None,+ ):+ h = (+ self.audio_model(input_ids, input_values)+ if input_values is not None+ else self.text(input_ids)+ )+ return self.head(h).square().mean()+++def _case_audio(native, rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ model = _AudioText()+ fully_shard(model.audio_model.audio_encoder, mesh = mesh)+ fully_shard(model, mesh = mesh)+ host = vision.install_vision_dummy(model)+ res = {"host": type(host).__name__ if host is not None else None}+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ for step, audio in (("all_text", False), ("all_audio", True), ("mixed", rank == 0)):+ kwargs = {"input_values": torch.randn(1, 6, 3)} if audio else {}+ try:+ model(ids, **kwargs).backward()+ res[step] = "ok"+ except Exception as exc:+ res[step] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++class _Uneven(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.a = torch.nn.Linear(5, 6)+ self.small = torch.nn.Linear(+ 6, 1+ ) # weight (1, 6), bias (1,): dim 0 < world, rank 1 holds nothing++ def forward(self, x):+ return self.small(torch.tanh(self.a(x))).square().sum()+++def _case_negative_norm(native):+ import copy++ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ reference = _Uneven()+ model = copy.deepcopy(reference)+ mesh = init_device_mesh("cpu", (2,))+ fully_shard(model.a, mesh = mesh)+ fully_shard(model.small, mesh = mesh)+ fully_shard(model, mesh = mesh)+ x = torch.randn(3, 5, generator = torch.Generator().manual_seed(2))+ res = {"local_numel": model.small.weight.to_local().numel()}+ for norm_type in NEGATIVE_NORMS:+ for m in (model, reference):+ m.zero_grad(set_to_none = True)+ m(x).backward()+ want = torch.nn.utils.clip_grad_norm_(+ list(reference.parameters()), 1e6, norm_type = norm_type+ )+ got = native.native_clip_grad_norm_(list(model.parameters()), 1e6, norm_type = norm_type)+ res[str(norm_type)] = {"got": float(got), "want": float(want)}+ return res+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "inference":+ res = _case_inference(native)+ elif case == "embedding":+ res = _case_embedding(native, tmp)+ elif case == "audio":+ res = _case_audio(native, rank)+ elif case == "negative_norm":+ res = _case_negative_norm(native)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND6_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_native_fsdp2_inference_context_is_no_grad(tmp_path):+ pytest.importorskip("transformers")+ for rank, r in _run("inference", tmp_path).items():+ assert r["kind"] == "no_grad", (rank, r)+ assert r["train_after"] == "ok", (rank, r)+++def test_resume_restores_embedding_lora(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("embedding", tmp_path).items():+ assert r["embedding_keys"], (rank, r)+ assert "load_error" not in r and r["diff"] == 0.0, (rank, r)+++def test_input_values_audio_is_agreed_on_a_host_every_rank_runs(tmp_path):+ for rank, r in _run("audio", tmp_path).items():+ assert r["host"] in ("_AudioText", "FSDP_AudioText"), (rank, r) # not the inner _AudioModel+ assert r["all_text"] == "ok" and r["all_audio"] == "ok", (rank, r)+ assert r["mixed"].startswith("RuntimeError") and "audio on 1 of 2 ranks" in r["mixed"], (+ rank,+ r,+ )+++def test_negative_norm_with_an_empty_shard_matches_torch(tmp_path):+ results = _run("negative_norm", tmp_path)+ assert results[1]["local_numel"] == 0, results+ for rank, r in results.items():+ for norm_type in NEGATIVE_NORMS:+ v = r[str(norm_type)]+ assert v["want"] > 0, (rank, norm_type, v)+ assert math.isclose(v["got"], v["want"], rel_tol = 1e-5), (rank, norm_type, v)+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def test_inference_helper_env_and_marker(monkeypatch):+ helper = _inference_helper()+ for key in ("ACCELERATE_USE_FSDP", "FSDP_VERSION", "UNSLOTH_FSDP2", "WORLD_SIZE"):+ monkeypatch.delenv(key, raising = False)+ plain = torch.nn.Linear(2, 2)+ assert isinstance(helper(plain), torch.inference_mode)+ marked = torch.nn.Linear(2, 2)+ marked._unsloth_fsdp2_native = True+ assert isinstance(helper(marked), torch.no_grad)+ assert isinstance(helper(types.SimpleNamespace(module = marked)), torch.no_grad)+ monkeypatch.setenv("UNSLOTH_FSDP2", "1")+ monkeypatch.setenv("WORLD_SIZE", "2")+ assert isinstance(helper(plain), torch.no_grad)+ monkeypatch.setenv("WORLD_SIZE", "1") # single process: no sharding, inference mode is fine+ assert isinstance(helper(plain), torch.inference_mode)+++def test_q_galore_is_refused_before_sharding(monkeypatch):+ pytest.importorskip("transformers")+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ for key in ("ACCELERATE_USE_DEEPSPEED", "ACCELERATE_MIXED_PRECISION"):+ monkeypatch.delenv(key, raising = False)+ native = _load_native()++ def _stop(device, *_):+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _stop)+ base = dict(optim = "adamw_torch", save_on_each_node = False, fsdp = None)+ args = types.SimpleNamespace(q_galore_config = object(), **base)+ model = _tiny_llama()+ with pytest.raises(ValueError, match = "q_galore_config"):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ assert not native.is_native_fsdp2(model)+ with pytest.raises(_Stop): # q_galore_config = None: sharding proceeds+ args = types.SimpleNamespace(q_galore_config = None, **base)+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+++ "optim",+ [+ "galore_adamw_layerwise",+ "galore_adamw_8bit_layerwise",+ "galore_adafactor_layerwise",+ "apollo_adamw_layerwise",+ "galore_adamw",+ ],+)+def test_galore_and_apollo_are_refused_before_sharding(monkeypatch, optim):+ pytest.importorskip("transformers")+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ for key in ("ACCELERATE_USE_DEEPSPEED", "ACCELERATE_MIXED_PRECISION"):+ monkeypatch.delenv(key, raising = False)+ native = _load_native()++ def _stop(device, *_):+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _stop)+ base = dict(save_on_each_node = False, fsdp = None, q_galore_config = None)+ model = _tiny_llama()+ with pytest.raises(ValueError, match = optim):+ args = types.SimpleNamespace(optim = optim, **base)+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ assert not native.is_native_fsdp2(model)+ with pytest.raises(_Stop): # a torch optimizer: sharding proceeds+ args = types.SimpleNamespace(optim = "adamw_torch", **base)+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)diff --git a/tests/test_fsdp2_native_int8_gloo.py b/tests/test_fsdp2_native_int8_gloo.pynew file mode 100644index 00000000000..a9850315625--- /dev/null+++ b/tests/test_fsdp2_native_int8_gloo.py@@ -0,0 +1,168 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 with bitsandbytes 8-bit (LLM.int8, Linear8bitLt) weights, gloo world of 2. Int8Params+keeps its quantization state in CB / SCB attributes beside the int8 data+(bitsandbytes/nn/modules.py Int8Params.__new__ / _quantize); a DTensor shard and FSDP2's gathered+plain tensor carry neither. So 8-bit weights stay replicated (ignored_params) in every layout, also+when frozen weights are sharded (shard_frozen = True), and the sharded model's forward matches the+unsharded one; a torch without fully_shard(ignored_params) refuses."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import copy # noqa: E402+import datetime # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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_guards_gloo import _tiny_llama # noqa: E402+++def _int8_llama():+ import bitsandbytes as bnb++ torch.manual_seed(0)+ model = _tiny_llama()+ for layer in model.model.layers:+ old = layer.mlp.down_proj+ new = bnb.nn.Linear8bitLt(+ old.in_features, old.out_features, bias = False, has_fp16_weights = False+ )+ new.weight = bnb.nn.Int8Params(+ old.weight.detach().clone(), requires_grad = False, has_fp16_weights = False+ )+ layer.mlp.down_proj = new.to("cpu") # quantizes: int8 data + CB / SCB+ for name, p in model.named_parameters():+ p.requires_grad_("norm" in name) # a trainable float set next to the frozen int8 weights+ return model+++def _case(native, rank, refuse):+ from torch.distributed.tensor import DTensor++ model = _int8_llama()+ reference = copy.deepcopy(model)+ if refuse:+ native._supports_ignored_params = lambda fully_shard: False+ cfg = native.FSDP2Config(param_dtype = torch.float32, shard_frozen = True)+ try:+ model = native.shard_model(model, cfg)+ except Exception as exc:+ return {"shard": f"{type(exc).__name__}: {str(exc)[:300]}"}+ weights = [layer.mlp.down_proj.weight for layer in model.model.layers]+ res = {+ "shard": "ok",+ "int8_dtensor": sum(isinstance(w, DTensor) for w in weights),+ "int8_scb": sum(getattr(w, "SCB", None) is not None for w in weights),+ "int8": len(weights),+ "other_dtensor": sum(isinstance(p, DTensor) for p in model.parameters()),+ }+ ids = torch.randint(1, 100, (1, 8), generator = torch.Generator().manual_seed(rank))+ try:+ got = model(input_ids = ids, labels = ids)+ got.loss.backward()+ want = reference(input_ids = ids, labels = ids)+ res["logits_diff"] = (got.logits - want.logits).abs().max().item()+ except Exception as exc:+ res["forward"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ return res+++def _worker(rank, world, port, out, refuse):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ out.put((rank, _case(_load_native(), rank, refuse)))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(refuse, timeout = 150):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, refuse),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail("int8: the ranks did not finish (hung collective)")+ except mp.ProcessExitedException as exc:+ pytest.fail(f"int8: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND11_RESULT int8", refuse, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_int8_weights_stay_replicated_when_frozen_weights_are_sharded():+ pytest.importorskip("bitsandbytes")+ pytest.importorskip("transformers")+ for rank, r in _run(False).items():+ assert r["shard"] == "ok" and "forward" not in r, (rank, r)+ assert r["int8_dtensor"] == 0 and r["int8_scb"] == r["int8"] > 0, (rank, r)+ assert r["other_dtensor"] > 0, (rank, r) # the rest is still sharded+ assert r["logits_diff"] < 1e-4, (rank, r)+++def test_int8_weights_refused_without_ignored_params():+ pytest.importorskip("bitsandbytes")+ pytest.importorskip("transformers")+ for rank, r in _run(True).items():+ assert r["shard"].startswith("RuntimeError") and "8-bit" in r["shard"], (rank, r)+++def test_cpu_int8_model_with_a_gpu_is_refused(monkeypatch):+ """Moving the int8 data to the GPU would leave CB / SCB on the CPU."""+ pytest.importorskip("bitsandbytes")+ pytest.importorskip("transformers")+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0", LOCAL_RANK = "1").items():+ monkeypatch.setenv(key, value)+ monkeypatch.delenv("ACCELERATE_USE_CPU", raising = False)+ native = _load_native()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ with pytest.raises(RuntimeError, match = "8-bit model on the CPU"):+ native._shard_device(_int8_llama())diff --git a/tests/test_fsdp2_native_layout_agree_gloo.py b/tests/test_fsdp2_native_layout_agree_gloo.pynew file mode 100644index 00000000000..e28059af2af--- /dev/null+++ b/tests/test_fsdp2_native_layout_agree_gloo.py@@ -0,0 +1,195 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 layout decisions every rank must share, on a gloo CPU world of 2.++* Unequal device memory: rank 0 "fits", rank 1 does not. The ranks agree on fits = False, and the+ reshard_after_forward derived from it must be the same on both (a rank keeping its blocks gathered+ while the other reshards issues different backward collectives: a hang on GPUs).+* torch without fully_shard(ignored_params) (2.6): the automatic fit layout falls back to sharding the+ frozen weights; an explicit replication request keeps the capability error."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib # noqa: E402+import socket # noqa: E402+import sys # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import _build, _load_native # noqa: E402++REPO_ID = "hf-internal-testing/tiny-random-LlamaForCausalLM"+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _init(+ rank,+ world,+ port,+ extra_env = None,+):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ **(extra_env or {}),+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)+ )+ return dist+++def _ids(seed):+ return torch.randint(3, 1000, (2, 16), generator = torch.Generator().manual_seed(seed))+++def _unequal_worker(rank, world, port, out):+ dist = _init(rank, world, port)+ try:+ native = _load_native()+ perf = importlib.import_module("unsloth.models.fsdp2_perf")+ # Rank 0 sees a huge device (the model fits), rank 1 a tiny one (it does not).+ big = 1 << 40 if rank == 0 else 1 << 10+ perf._device_bytes = lambda device = None: big+ local = perf.plan_fsdp2_layout(_build(REPO_ID, "AutoModelForCausalLM")).as_dict()+ model = _build(REPO_ID, "AutoModelForCausalLM") # full fine-tuning+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ layout = model._unsloth_fsdp2_layout+ reshards = [u._unsloth_reshard_after_forward for u in model._unsloth_fsdp2_units]+ mine = {+ "local_fits": local["fits"],+ "fits": layout["fits"],+ "reshard_after_forward": layout["reshard_after_forward"],+ "prefetch": layout["prefetch"],+ "unit_reshards": reshards,+ }+ everyone = [None] * world+ dist.all_gather_object(everyone, mine)+ consistent = all(e == {**everyone[0], "local_fits": e["local_fits"]} for e in everyone)+ step = None+ if consistent: # mismatched layouts would hang the backward: only run it when they agree+ ids = _ids(rank)+ model(input_ids = ids, labels = ids, use_cache = False).loss.backward()+ step = "ok"+ if rank == 0:+ out.put({"ranks": everyone, "consistent": consistent, "step": step})+ except Exception as exc:+ import traceback+ out.put({"error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"})+ finally:+ dist.destroy_process_group()+++def _spawn(worker, *args):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ mp.start_processes(+ worker, args = (2, _free_port(), out, *args), nprocs = 2, join = True, start_method = "spawn"+ )+ results = []+ while not out.empty():+ results.append(out.get(timeout = 5))+ return results+++def test_unequal_capacity_ranks_agree_on_reshard():+ pytest.importorskip("transformers")+ (r,) = _spawn(_unequal_worker)+ assert "error" not in r, r["error"]+ print("AGREE_RESULT", r)+ ranks = r["ranks"]+ assert [x["local_fits"] for x in ranks] == [True, False], r # the setup really differs per rank+ assert all(x["fits"] is False for x in ranks), r+ assert r["consistent"], r+ # Not fitting everywhere: blocks reshard after forward (all but the last, which never does).+ assert all(x["reshard_after_forward"] is True for x in ranks), r+ assert all(x["prefetch"] is False for x in ranks), r+ assert r["step"] == "ok", r+++def _no_ignored_worker(rank, world, port, out, mode):+ extra = {"UNSLOTH_FSDP2_REPLICATE_FROZEN": "1"} if mode == "env" else {}+ dist = _init(rank, world, port, extra)+ try:+ native = _load_native()+ from peft import LoraConfig, get_peft_model+ from torch.distributed.tensor import DTensor++ native._supports_ignored_params = lambda fully_shard: False # torch 2.6's fully_shard+ model = get_peft_model(+ _build(REPO_ID, "AutoModelForCausalLM"),+ LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear"),+ )+ cfg = native.FSDP2Config(+ param_dtype = torch.float32,+ fit_layout = True,+ shard_frozen = False if mode == "config" else None,+ )+ try:+ native.shard_model(model, cfg)+ except RuntimeError as exc:+ out.put((rank, {"raised": str(exc)}))+ return+ layout = model._unsloth_fsdp2_layout+ ids = _ids(rank)+ model(input_ids = ids, labels = ids, use_cache = False).loss.backward()+ out.put(+ (+ rank,+ {+ "layout": layout,+ "frozen_sharded": all(+ isinstance(p, DTensor) for p in model.parameters() if not p.requires_grad+ ),+ "lora_grads": all(+ p.grad is not None for p in model.parameters() if p.requires_grad+ ),+ },+ )+ )+ except Exception as exc:+ import traceback+ out.put((rank, {"error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ dist.destroy_process_group()++[email protected]("mode", ["auto", "config", "env"])+def test_fit_layout_without_ignored_params(mode):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ results = dict(_spawn(_no_ignored_worker, mode))+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("NO_IGNORED_RESULT", mode, rank, r)+ assert "error" not in r, r["error"]+ if mode == "auto":+ assert "raised" not in r, r+ assert r["layout"]["fits"] is True, r+ assert r["layout"]["replicate_frozen"] is False, r+ assert r["layout"]["root_only"] is False, r+ assert r["frozen_sharded"] and r["lora_grads"], r+ else: # explicit replication: the capability error stays+ assert "ignored_params" in r.get("raised", ""), rdiff --git a/tests/test_fsdp2_native_layout_cpu_split_gloo.py b/tests/test_fsdp2_native_layout_cpu_split_gloo.pynew file mode 100644index 00000000000..e26ddd09a65--- /dev/null+++ b/tests/test_fsdp2_native_layout_cpu_split_gloo.py@@ -0,0 +1,159 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 shard layout (gloo world of 2):++* a large root embedding table split into its own unit (Gemma4 `embed_tokens_per_layer`,+ _large_root_embeddings) is its own dtype group: a 16-bit table next to float32 root parameters+ leaves both homogeneous, with nothing replicated or upcast;+* a CPU mesh (TrainingArguments(use_cpu = True) -> FSDP2Config(device = "cpu")) on a CUDA host plans+ without the GPU's capacity: the per-block sharded layout, as on a CPU-only host."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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_args_gloo import _lora # noqa: E402+from test_fsdp2_native_guards_gloo import _tiny_llama # noqa: E402+++def _case_split(native):+ torch.manual_seed(0)+ model = _tiny_llama() # float32 root: embed_tokens, norm, lm_head+ for layer in model.model.layers:+ layer.to(torch.bfloat16)+ hidden = model.config.hidden_size+ model.model.embed_tokens_per_layer = torch.nn.Embedding(4096, hidden).to(torch.bfloat16)+ table = model.model.embed_tokens_per_layer.weight+ root = [model.model.embed_tokens.weight, model.model.norm.weight, model.lm_head.weight]+ cfg = native.FSDP2Config(param_dtype = torch.float32, split_large_root_embeddings = 0.01)+ model = native.shard_model(model, cfg)+ return {+ "extra_units": len(model._unsloth_fsdp2_extra_units),+ "replicated": model._unsloth_fsdp2_replicated,+ "table_dtype": str(model.model.embed_tokens_per_layer.weight.dtype),+ "table_dtensor": type(model.model.embed_tokens_per_layer.weight).__name__,+ "root_dtypes": sorted({str(p.dtype) for p in root}),+ "table_was": str(table.dtype),+ }+++def _case_cpu_mesh(native):+ from torch.distributed.device_mesh import init_device_mesh++ model = _lora(1)+ # Built before CUDA is faked below: on a CPU-only torch build a faked CUDA makes new_group ask+ # for NCCL. shard_model's own default mesh is the same CPU mesh (device = "cpu").+ mesh = init_device_mesh("cpu", (2,))+ # A CUDA host whose GPU would fit the model, but the Trainer runs on the CPU.+ torch.cuda.is_available = lambda: True+ torch.cuda.current_device = lambda: 0+ torch.cuda.get_device_properties = lambda device = None: types.SimpleNamespace(+ total_memory = 80 << 30+ )+ agreed = {}+ original = native._agree_over_ranks++ def record(*args, **kwargs):+ agreed["flags"] = original(*args, **kwargs)+ return agreed["flags"]++ native._agree_over_ranks = record+ cfg = native.FSDP2Config(param_dtype = torch.float32, device = "cpu", mesh = mesh)+ model = native.shard_model(model, cfg)+ fits, replicate_frozen, root_only, prefetch = agreed["flags"]+ return {+ "fits": fits,+ "replicate_frozen": replicate_frozen,+ "root_only": root_only,+ "blocks": model._unsloth_fsdp2_blocks,+ "replicated": model._unsloth_fsdp2_replicated,+ }+++def _worker(rank, world, port, out, case):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ res = _case_split(native) if case == "split" else _case_cpu_mesh(native)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(case, timeout = 150):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker, args = (2, _free_port(), out, case), nprocs = 2, join = False, start_method = "spawn"+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND13_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_split_root_table_is_its_own_dtype_group():+ pytest.importorskip("transformers")+ for rank, r in _run("split").items():+ assert r["extra_units"] == 1 and r["table_was"] == "torch.bfloat16", (rank, r)+ assert r["replicated"] == 0, (rank, r) # neither the table nor the float32 root+ assert r["table_dtype"] == "torch.bfloat16" and r["table_dtensor"] == "DTensor", (rank, r)+ assert r["root_dtypes"] == ["torch.float32"], (rank, r)+++def test_cpu_mesh_on_a_cuda_host_plans_the_sharded_layout():+ pytest.importorskip("peft")+ for rank, r in _run("cpu_mesh").items():+ assert r["fits"] is False and r["replicate_frozen"] is False, (rank, r)+ assert r["root_only"] is False and r["blocks"] > 0 and r["replicated"] == 0, (rank, r)diff --git a/tests/test_fsdp2_native_modality_mesh_gloo.py b/tests/test_fsdp2_native_modality_mesh_gloo.pynew file mode 100644index 00000000000..3234d85a7c5--- /dev/null+++ b/tests/test_fsdp2_native_modality_mesh_gloo.py@@ -0,0 +1,373 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2, gloo CPU worlds of 2 (and 4 for the 2-D mesh):++* per-modality presence agreement (fsdp2_vision): a vision `get_image_features` with a required+ argument no dummy supplies, and an audio tower, raise on every rank when present on some ranks+ only (instead of one rank raising or skipping collectives); a buildable image dummy still runs+ on the ranks without images; all-present / all-absent batches train;+* native_clip_grad_norm_ on an HSDP (2 replicate x 2 shard) mesh matches torch on an unsharded copy;+* a prebuilt optimizer + LR scheduler over mixed DTensor / replicated groups is refused, and one+ built from split_param_groups is accepted with its groups intact;+* Unsloth block swap is refused before sharding, and the post-init check recognises native FSDP2."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib # noqa: E402+import math # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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, _stub_unsloth_save # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402+from test_fsdp2_native_trainer_fsdp_clip_gloo import NORM_TYPES, _Net # noqa: E402++H = 8+SIZE = 4+++class _Tower(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(SIZE * SIZE, H)++ def forward(self, pixel_values):+ return self.proj(pixel_values.flatten(1))+++class _LM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(16, H)+ self.layers = torch.nn.ModuleList([torch.nn.Linear(H, H) for _ in range(2)])++ def forward(self, inputs_embeds):+ h = inputs_embeds+ for layer in self.layers:+ h = torch.tanh(layer(h))+ return h+++class _MM(torch.nn.Module):+ """Llava-like: vision tower + projector via get_image_features, an audio tower run inline."""++ def __init__(self, high_res):+ super().__init__()+ torch.manual_seed(0)+ self.high_res = high_res+ self.config = types.SimpleNamespace(+ vision_config = types.SimpleNamespace(image_size = SIZE, patch_size = 2, num_channels = 1)+ )+ self.vision_tower = _Tower()+ self.multi_modal_projector = torch.nn.Linear(H, H)+ self.audio_tower = torch.nn.Linear(3, H)+ self.language_model = _LM()++ def get_input_embeddings(self):+ return self.language_model.embed++ def _image(self, pixel_values):+ return self.multi_modal_projector(self.vision_tower(pixel_values))++ def forward(+ self,+ input_ids,+ pixel_values = None,+ high_res_pixel_values = None,+ input_features = None,+ ):+ embeds = self.language_model.embed(input_ids)+ if pixel_values is not None:+ if self.high_res:+ feats = self.get_image_features(pixel_values, high_res_pixel_values)+ else:+ feats = self.get_image_features(pixel_values)+ embeds = embeds + feats.mean(0)+ if input_features is not None:+ embeds = embeds + self.audio_tower(input_features).mean(1, keepdim = True)+ return self.language_model(inputs_embeds = embeds).square().mean()+++class _MMHighRes(_MM):+ def get_image_features(self, pixel_values, high_res_pixel_values):+ return self._image(pixel_values) + 0.0 * high_res_pixel_values.sum()+++class _MMPlain(_MM):+ def get_image_features(self, pixel_values):+ return self._image(pixel_values)+++def _modality_step(model, rank, image, audio):+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ kwargs = {}+ if image:+ kwargs["pixel_values"] = torch.randn(1, 1, SIZE, SIZE)+ kwargs["high_res_pixel_values"] = torch.randn(1, 1, 2 * SIZE, 2 * SIZE)+ if audio:+ kwargs["input_features"] = torch.randn(1, 6, 3)+ model(ids, **kwargs).backward()+++def _case_modality(native, rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ res = {}+ for name, cls in (("plain", _MMPlain), ("high_res", _MMHighRes)):+ model = cls(high_res = cls is _MMHighRes)+ for module in (model.vision_tower, model.audio_tower, *model.language_model.layers):+ fully_shard(module, mesh = mesh)+ fully_shard(model, mesh = mesh)+ vision.install_vision_dummy(model)+ steps = [("all_text", False, False), ("all_image", True, False), ("all_audio", False, True)]+ steps += [("mixed_image", rank == 0, False), ("mixed_audio", False, rank == 1)]+ for step, image, audio in steps:+ try:+ _modality_step(model, rank, image, audio)+ res[f"{name}.{step}"] = "ok"+ except Exception as exc:+ res[f"{name}.{step}"] = f"{type(exc).__name__}: {str(exc)[:240]}"+ return res+++def _case_clip_hsdp(native):+ import copy++ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard+ from torch.distributed.tensor import DTensor++ reference = _Net()+ model = copy.deepcopy(reference)+ mesh = init_device_mesh("cpu", (2, 2), mesh_dim_names = ("replicate", "shard"))+ for name in ("a", "b", "dead"):+ fully_shard(getattr(model, name), mesh = mesh)+ fully_shard(model, mesh = mesh, ignored_params = {model.rep})+ x = torch.randn(4, 7, generator = torch.Generator().manual_seed(1)) # same batch everywhere+ res = {"placements": str(model.a.weight.placements)}+ for norm_type in NORM_TYPES:+ for m in (model, reference):+ m.zero_grad(set_to_none = True)+ m(x).backward()+ want = torch.nn.utils.clip_grad_norm_(+ list(reference.parameters()), 0.5, norm_type = norm_type+ )+ got = native.native_clip_grad_norm_(list(model.parameters()), 0.5, norm_type = norm_type)+ diff = 0.0+ for p, q in zip(model.parameters(), reference.parameters()):+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ diff = max(diff, (g - q.grad).abs().max().item())+ res[str(norm_type)] = {"got": float(got), "want": float(want), "grad_diff": diff}+ return res+++def _case_prebuilt_optimizer(native, tmp):+ _install_wrapped_trainer_init()+ from transformers import Trainer++ model = _lora(1)+ first = next(p for n, p in model.named_parameters() if "lora_A" in n)+ cfg = native.FSDP2Config(param_dtype = torch.float32, ignored_params = {first})+ model = native.shard_model(model, cfg)+ trainable = [p for p in model.parameters() if p.requires_grad]+ res = {}+ optimizer = torch.optim.AdamW(trainable, lr = 1e-3)+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda step: 1.0)+ try:+ trainer = Trainer(+ model = model, args = _targs(os.path.join(tmp, "out")), optimizers = (optimizer, scheduler)+ )+ trainer.create_optimizer()+ res["mixed"] = {"groups": len(optimizer.param_groups), "base_lrs": len(scheduler.base_lrs)}+ except RuntimeError as exc:+ res["mixed"] = {"error": str(exc)}+ if not hasattr(native, "split_param_groups"):+ return res # (before the helper existed)+ optimizer = torch.optim.AdamW(native.split_param_groups(trainable), lr = 1e-3)+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda step: 1.0)+ trainer = Trainer(+ model = model, args = _targs(os.path.join(tmp, "out")), optimizers = (optimizer, scheduler)+ )+ trainer.create_optimizer()+ res["split"] = {"groups": len(optimizer.param_groups), "base_lrs": len(scheduler.base_lrs)}+ return res+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "modality":+ res = _case_modality(native, rank)+ elif case == "clip_hsdp":+ res = _case_clip_hsdp(native)+ elif case == "prebuilt_optimizer":+ res = _case_prebuilt_optimizer(native, tmp)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ world = 2,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (world, _free_port(), out, case, str(tmp_path)),+ nprocs = world,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == list(range(world)), results+ for rank, r in results.items():+ print("ROUND4_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_modality_presence_is_agreed_over_ranks(tmp_path):+ for rank, r in _run("modality", tmp_path).items():+ for name in ("plain", "high_res"):+ for step in ("all_text", "all_image", "all_audio"):+ assert r[f"{name}.{step}"] == "ok", (rank, name, step, r)+ # Audio has no dummy: a mixed audio batch raises on every rank.+ assert r[f"{name}.mixed_audio"].startswith("RuntimeError"), (rank, r)+ assert "audio on 1 of 2 ranks" in r[f"{name}.mixed_audio"], (rank, r)+ # A buildable image dummy runs on the rank without images.+ assert r["plain.mixed_image"] == "ok", (rank, r)+ # get_image_features needs high_res_pixel_values, which no dummy supplies: raise everywhere.+ assert r["high_res.mixed_image"].startswith("RuntimeError"), (rank, r)+ assert "high_res_pixel_values" in r["high_res.mixed_image"], (rank, r)+++def test_native_clip_on_an_hsdp_mesh_matches_torch(tmp_path):+ for rank, r in _run("clip_hsdp", tmp_path, world = 4, timeout = 240).items():+ assert "Replicate" in r["placements"] and "Shard" in r["placements"], (rank, r)+ for norm_type in NORM_TYPES:+ v = r[str(norm_type)]+ assert math.isclose(v["got"], v["want"], rel_tol = 1e-5, abs_tol = 1e-6), (+ rank,+ norm_type,+ v,+ )+ assert v["grad_diff"] < 1e-6, (rank, norm_type, v)+++def test_prebuilt_mixed_optimizer_with_scheduler_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("prebuilt_optimizer", tmp_path).items():+ assert "split_param_groups" in r["mixed"].get("error", ""), (rank, r)+ assert r["split"]["groups"] == r["split"]["base_lrs"] == 2, (+ rank,+ r,+ ) # split before the scheduler+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def native_env(monkeypatch):+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ return _load_native()+++def test_block_swap_is_refused_before_sharding(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env++ def _stop(device, *_):+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _stop)+ model = _tiny_llama()+ model.model.layers._unsloth_block_swap = types.SimpleNamespace(indices = [1])+ model._unsloth_block_swap = model.model.layers._unsloth_block_swap+ with pytest.raises(ValueError, match = r"offload_layers = 1 .*native FSDP2"):+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ assert not native.is_native_fsdp2(model)+ # An "auto" rank that swapped nothing refuses too (no rank shards alone).+ model = _tiny_llama()+ model._unsloth_offload_layers_auto = 1+ with pytest.raises(ValueError, match = r"offload_layers = 'auto' \(this rank swapped 0"):+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ with pytest.raises(_Stop): # no block swap: sharding proceeds+ native.shard_model(_tiny_llama(), native.FSDP2Config(param_dtype = torch.float32))+++def test_post_init_block_swap_check_recognises_native_fsdp2(monkeypatch):+ pytest.importorskip("unsloth_zoo")+ from test_block_swap_auto_ddp import _ignore_helpers++ check = _ignore_helpers(monkeypatch)["_block_swap_for_trainer_backend"]+ model = types.SimpleNamespace(+ _unsloth_fsdp2_native = True, _unsloth_block_swap = types.SimpleNamespace(indices = [2])+ )+ trainer = types.SimpleNamespace(model = model, is_fsdp_enabled = False, is_deepspeed_enabled = False)+ with pytest.raises(ValueError, match = "native FSDP2"):+ check(trainer)diff --git a/tests/test_fsdp2_native_optim_reentry_gloo.py b/tests/test_fsdp2_native_optim_reentry_gloo.pynew file mode 100644index 00000000000..1bbfe8442fa--- /dev/null+++ b/tests/test_fsdp2_native_optim_reentry_gloo.py@@ -0,0 +1,289 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 (gloo CPU world of 2 where a process group is needed):++* a prebuilt optimizer over mixed DTensor / replicated groups that already holds state is refused+ (its groups cannot be split), also without an LR scheduler;+* Trainer(optimizer_cls_and_kwargs = (bitsandbytes class, ...)), by keyword or position, is refused+ before sharding; a torch optimizer class passes;+* native_fsdp2_unsharded is re-entrant: generate() inside an outer block leaves the weights gathered+ until the outer block exits, also when an inner block raises;+* accelerate's FP8 mixed precision is refused before any model change."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import _free_port, _stub_unsloth_save # noqa: E402+++class AdamW8bitLike(torch.optim.AdamW):+ """Stands for a bitsandbytes optimizer class (only its module is read)."""+++AdamW8bitLike.__module__ = "bitsandbytes.optim.adamw"+++def _sharded_lora(native):+ model = _lora(1)+ first = next(p for n, p in model.named_parameters() if "lora_A" in n)+ cfg = native.FSDP2Config(param_dtype = torch.float32, ignored_params = {first})+ return native.shard_model(model, cfg)+++def _case_stateful(native, tmp):+ _install_wrapped_trainer_init()+ from transformers import Trainer++ model = _sharded_lora(native)+ trainable = [p for p in model.parameters() if p.requires_grad]+ optimizer = torch.optim.AdamW(trainable, lr = 1e-3, foreach = False)+ ids = torch.randint(1, 100, (1, 8))+ model(input_ids = ids, labels = ids).loss.backward()+ optimizer.step() # the optimizer now holds state (as after load_state_dict)+ res = {"state": len(optimizer.state)}+ try:+ trainer = Trainer(+ model = model, args = _targs(os.path.join(tmp, "out")), optimizers = (optimizer, None)+ )+ trainer.create_optimizer()+ res["mixed_groups_left"] = native._mixed_param_groups(optimizer)+ except RuntimeError as exc:+ res["error"] = str(exc)+ return res+++def _case_optimizer_cls(native, tmp):+ _install_wrapped_trainer_init()+ from transformers import Trainer++ classes = [("like", AdamW8bitLike)]+ try:+ import bitsandbytes as bnb+ classes.append(("bnb", bnb.optim.AdamW8bit))+ except Exception:+ pass+ res = {}+ for name, cls in classes + [("torch", torch.optim.AdamW)]:+ for how in ("keyword", "positional"):+ model = _lora(1)+ targs = _targs(os.path.join(tmp, "out"))+ try:+ if how == "keyword":+ Trainer(model = model, args = targs, optimizer_cls_and_kwargs = (cls, {"lr": 1e-3}))+ else:+ # model, args, data_collator, train_dataset, eval_dataset, processing_class,+ # model_init, compute_loss_func, compute_metrics, callbacks, optimizers,+ # optimizer_cls_and_kwargs.+ Trainer(+ model,+ targs,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ (None, None),+ (cls, {"lr": 1e-3}),+ )+ err = ""+ except Exception as exc:+ err = f"{type(exc).__name__}: {str(exc)[:200]}"+ res[f"{name}.{how}"] = {"error": err, "sharded": native.is_native_fsdp2(model)}+ return res+++def _case_reentry(native):+ from torch.distributed.tensor import DTensor++ model = native.shard_model(_tiny_llama(), native.FSDP2Config(param_dtype = torch.float32))+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None++ def n_sharded():+ return sum(isinstance(p, DTensor) for p in model.parameters())++ res = {"before": n_sharded()}+ ids = torch.randint(1, 100, (1, 4), generator = torch.Generator().manual_seed(0))+ with native.native_fsdp2_unsharded(model):+ res["outer"] = n_sharded()+ model.generate(input_ids = ids, max_new_tokens = 2, do_sample = False)+ res["after_generate"] = n_sharded()+ try:+ with native.native_fsdp2_unsharded(model):+ raise KeyError("inner")+ except KeyError:+ pass+ res["after_inner_raise"] = n_sharded()+ res["after_outer"] = n_sharded()+ res["depth"] = model.__dict__.get("_unsloth_unsharded_depth", 0)+ return res+++def _worker_case(case, native, rank, tmp):+ if case == "stateful":+ return _case_stateful(native, tmp)+ if case == "optimizer_cls":+ return _case_optimizer_cls(native, tmp)+ if case == "reentry":+ return _case_reentry(native)+ raise KeyError(case)+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ out.put((rank, _worker_case(case, native, rank, tmp)))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND5_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_stateful_mixed_optimizer_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("stateful", tmp_path).items():+ assert r["state"] > 0, (rank, r)+ assert "split_param_groups" in r.get("error", ""), (rank, r)+++def test_bnb_optimizer_cls_and_kwargs_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("optimizer_cls", tmp_path).items():+ for key, v in r.items():+ if key.startswith("torch."):+ assert v["error"] == "" and v["sharded"], (rank, key, v)+ else:+ assert v["error"].startswith("ValueError") and "bitsandbytes" in v["error"], (+ rank,+ key,+ v,+ )+ assert not v["sharded"], (rank, key, v)+++def test_unsharded_context_is_reentrant(tmp_path):+ pytest.importorskip("transformers")+ for rank, r in _run("reentry", tmp_path).items():+ assert r["before"] > 0 and r["outer"] == 0, (rank, r)+ assert r["after_generate"] == 0 and r["after_inner_raise"] == 0, (rank, r)+ assert r["after_outer"] == r["before"] and r["depth"] == 0, (rank, r)+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def test_accelerate_fp8_is_refused_before_sharding(monkeypatch, tmp_path):+ pytest.importorskip("transformers")+ # transformers 5: TrainingArguments reads ACCELERATE_MIXED_PRECISION into args.mixed_precision.+ # Built before the distributed env below (a WORLD_SIZE without MASTER_ADDR fails its setup).+ for key in ("WORLD_SIZE", "RANK", "LOCAL_RANK", "MASTER_ADDR"):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setenv("ACCELERATE_MIXED_PRECISION", "fp8")+ from transformers import TrainingArguments++ real = TrainingArguments(output_dir = str(tmp_path / "out"), report_to = [], use_cpu = True)+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0").items():+ monkeypatch.setenv(key, value)+ monkeypatch.delenv("ACCELERATE_USE_DEEPSPEED", raising = False)+ native = _load_native()++ def _stop(device, *_):+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _stop)+ base = dict(optim = "adamw_torch", save_on_each_node = False, fsdp = None)+ model = torch.nn.Linear(2, 2)+ for args in (+ real,+ types.SimpleNamespace(mixed_precision = "fp8", **base),+ types.SimpleNamespace(fp16 = False, bf16 = False, **base), # 4.x: only the env+ ):+ with pytest.raises(RuntimeError, match = "FP8"):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ # bf16 overrides the env (both transformers lines): not FP8, sharding proceeds.+ args = types.SimpleNamespace(fp16 = False, bf16 = True, **base)+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)diff --git a/tests/test_fsdp2_native_optim_save_wait_gloo.py b/tests/test_fsdp2_native_optim_save_wait_gloo.pynew file mode 100644index 00000000000..c6fc3593cc5--- /dev/null+++ b/tests/test_fsdp2_native_optim_save_wait_gloo.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""native_save_optimizer (gloo CPU world of 2): only rank 0 writes the full optimizer state, and the+other rank must not leave before that write finishes, or its next collective (the next step's+all-gather) waits on rank 0 for as long as a large torch.save takes and can hit the collective+timeout. Rank 0's write is slowed down; rank 1 must find the file complete when the call returns."""++import datetime+import os+import sys+import time++import pytest+import torch++if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import _load_native # noqa: E402+from test_fsdp2_native_guards_gloo import _tiny_llama # noqa: E402++DELAY_S = 3.0+++def _worker(rank, world, init_file, path, out):+ os.environ.update(RANK = str(rank), WORLD_SIZE = str(world), LOCAL_RANK = str(rank))+ import torch.distributed as dist++ dist.init_process_group(+ "gloo",+ init_method = f"file://{init_file}",+ rank = rank,+ world_size = world,+ timeout = datetime.timedelta(seconds = 60),+ )+ try:+ native = _load_native()+ model = native.shard_model(_tiny_llama(), native.FSDP2Config(param_dtype = torch.float32))+ opt = torch.optim.AdamW(model.parameters(), lr = 1e-3, foreach = False)+ model(torch.tensor([[1, 2, 3]])).logits.float().mean().backward()+ opt.step()+ if rank == 0:+ save = torch.save++ def slow_save(*args, **kwargs):+ time.sleep(DELAY_S) # a large state still being written+ return save(*args, **kwargs)++ torch.save = slow_save+ native.native_save_optimizer(model, opt, path, should_save = rank == 0)+ out.put((rank, {"file_complete_on_return": os.path.exists(path)}))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def test_non_writers_wait_for_the_optimizer_write(tmp_path):+ pytest.importorskip("transformers")+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ args = (2, str(tmp_path / "store"), str(tmp_path / "optimizer.pt"), out)+ procs = mp.start_processes(_worker, args = args, nprocs = 2, join = False, start_method = "spawn")+ deadline = time.time() + 180+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail("the ranks did not finish within 180 s")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ assert "crash" not in r, r["crash"]+ assert r["file_complete_on_return"], (rank, results)diff --git a/tests/test_fsdp2_native_per_input_gloo.py b/tests/test_fsdp2_native_per_input_gloo.pynew file mode 100644index 00000000000..a6e1773f569--- /dev/null+++ b/tests/test_fsdp2_native_per_input_gloo.py@@ -0,0 +1,214 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 media agreement is per input, not per modality: each input is encoded by its own+call, so a rank with two inputs of one modality runs the encoder twice while a rank with one runs it+once.++* Moshi (transformers/models/moshi/modeling_moshi.py MoshiForConditionalGeneration.forward) takes+ `user_input_values` and `moshi_input_values` and runs `audio_encoder.encode` once per given input:+ both names are recognised as audio, and a rank with both next to a rank with one raises on every+ rank (gloo world of 2) instead of desynchronising the encoder's collectives;+* Qwen-VL runs `visual` once for pixel_values and again for pixel_values_videos+ (transformers/models/qwen2_vl/modeling_qwen2_vl.py Qwen2VLModel.forward): mixed videos raise (no+ video dummy), mixed images still run the image dummy."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib # noqa: E402+import inspect # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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+++class _Codec(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(3, 8)++ def encode(self, values):+ return (self.proj(values).mean(1, keepdim = True),)+++class _MoshiLike(torch.nn.Module):+ """MoshiForConditionalGeneration-like: `audio_encoder.encode` once per given audio input."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.audio_encoder = _Codec()+ self.embed = torch.nn.Embedding(16, 8)+ self.head = torch.nn.Linear(8, 4)++ def forward(+ self,+ input_ids,+ user_input_values = None,+ moshi_input_values = None,+ ):+ h = self.embed(input_ids)+ if user_input_values is not None:+ h = h + self.audio_encoder.encode(user_input_values)[0]+ if moshi_input_values is not None:+ h = h + self.audio_encoder.encode(moshi_input_values)[0]+ return self.head(h).square().mean()+++def _case_moshi(rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ model = _MoshiLike()+ fully_shard(+ model.audio_encoder.proj, mesh = mesh+ ) # a unit inside the codec (encode is no forward)+ fully_shard(model, mesh = mesh)+ host = vision.install_vision_dummy(model)+ res = {"host": type(host).__name__ if host is not None else None}+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ audio = lambda: torch.randn(1, 6, 3) # noqa: E731+ steps = (+ ("both_everywhere", {"user_input_values": audio(), "moshi_input_values": audio()}),+ ("user_everywhere", {"user_input_values": audio()}),+ # rank 0 encodes twice, rank 1 once+ (+ "both_vs_user",+ {"user_input_values": audio(), "moshi_input_values": audio()}+ if rank == 0+ else {"user_input_values": audio()},+ ),+ )+ for step, kwargs in steps:+ try:+ model(ids, **kwargs).backward()+ res[step] = "ok"+ except Exception as exc:+ res[step] = f"{type(exc).__name__}: {str(exc)[:300]}"+ return res+++def _worker(rank, world, port, out):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ _load_native()+ out.put((rank, _case_moshi(rank)))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def test_moshi_inputs_are_agreed_per_input():+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker, args = (2, _free_port(), out), nprocs = 2, join = False, start_method = "spawn"+ )+ deadline = time.time() + 150+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail("moshi: the ranks did not finish (hung collective)")+ except mp.ProcessExitedException as exc:+ pytest.fail(f"moshi: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND11_RESULT moshi", rank, r)+ assert "crash" not in r, r["crash"]+ assert r["host"] in ("_MoshiLike", "FSDP_MoshiLike"), (rank, r)+ assert r["both_everywhere"] == "ok" and r["user_everywhere"] == "ok", (rank, r)+ assert r["both_vs_user"].startswith("RuntimeError"), (rank, r)+ assert "audio on 1 of 2 ranks (input `moshi_input_values`)" in r["both_vs_user"], (rank, r)+++def test_real_moshi_signature_inputs_are_audio():+ transformers = pytest.importorskip("transformers")+ _load_native()+ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ moshi = transformers.MoshiForConditionalGeneration+ names = vision._audio_inputs(inspect.signature(moshi.forward))+ assert "user_input_values" in names and "moshi_input_values" in names, names+++class _QwenVLHost(torch.nn.Module):+ def forward(+ self,+ input_ids = None,+ pixel_values = None,+ pixel_values_videos = None,+ ):+ return input_ids+++def _simulated(vision, monkeypatch, other):+ """One process: the other rank's flags are added to this rank's (world of 2)."""+ monkeypatch.setattr(+ vision,+ "_agree_counts",+ lambda flags, device, *_: ([int(f) + o for f, o in zip(flags, other)], 2),+ )+++def test_qwen_vl_videos_are_agreed_apart_from_images(monkeypatch):+ _load_native()+ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ modality = vision._Modality("images", vision._VISION_INPUTS, "", lambda: True)+ host = _QwenVLHost()+ vision._install_presence_agreement(host, [modality], lambda: torch.device("cpu"))+ x = torch.zeros(1)+ # Flags: [image group, pixel_values_videos, unready]. The other rank has images and a video.+ _simulated(vision, monkeypatch, [1, 1, 0])+ with pytest.raises(+ RuntimeError, match = r"images on 1 of 2 ranks \(input `pixel_values_videos`\)"+ ):+ host(pixel_values = x) # this rank: images only, so `visual` runs once here, twice there+ # The other rank has images only: this rank, with a video only, runs the image dummy.+ _simulated(vision, monkeypatch, [1, 0, 0])+ with pytest.raises(RuntimeError, match = "pixel_values_videos"):+ host(pixel_values_videos = x)+ _simulated(vision, monkeypatch, [1, 0, 0])+ host(input_ids = x)+ assert modality.run_dummy is True+ _simulated(vision, monkeypatch, [1, 1, 0])+ host(pixel_values = x, pixel_values_videos = x)+ assert modality.run_dummy is Falsediff --git a/tests/test_fsdp2_native_pg_tp_media_gloo.py b/tests/test_fsdp2_native_pg_tp_media_gloo.pynew file mode 100644index 00000000000..d1379025e56--- /dev/null+++ b/tests/test_fsdp2_native_pg_tp_media_gloo.py@@ -0,0 +1,453 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2:++* the process group native setup creates uses TrainingArguments.ddp_backend / ddp_timeout (or the+ arguments' own device setup), with the NCCL-or-gloo default only when none is given;+* a model already on CUDA shards onto cuda:LOCAL_RANK, not its first weight's GPU; quantized weights on+ another GPU, or a model split over GPUs, are refused;+* transformers 5 parallelism_config (TP / CP / SP / replicate) and tp_plan models are refused;+* FSDP2 names resolve on torch 2.4 / 2.5's `torch.distributed._composable.fsdp` too;+* Phi-4-multimodal-style `image_embed` / `audio_embed` towers (and an unrecognised encoder, through+ the fallback) get the per-modality agreement (gloo world of 2)."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import datetime # noqa: E402+import functools # noqa: E402+import importlib # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import _free_port # noqa: E402+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402++BASE_ARGS = dict(optim = "adamw_torch", save_on_each_node = False, fsdp = None)+++def native_env(monkeypatch):+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0", LOCAL_RANK = "1").items():+ monkeypatch.setenv(key, value)+ for key in ("ACCELERATE_USE_DEEPSPEED", "ACCELERATE_MIXED_PRECISION", "ACCELERATE_USE_CPU"):+ monkeypatch.delenv(key, raising = False)+ return _load_native()+++def _fake_cuda(monkeypatch):+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ monkeypatch.setattr(torch.cuda, "set_device", lambda device: None)+++# ---- 1. backend / timeout ---------------------------------------------------------------------+++def test_process_group_uses_trainer_backend_and_timeout(native_env, monkeypatch):+ pytest.importorskip("transformers")+ import torch.distributed as dist++ native = native_env+ _fake_cuda(monkeypatch)+ monkeypatch.setattr(dist, "is_initialized", lambda: False)+ calls = []++ def _init(**kwargs):+ calls.append(kwargs)+ raise _Stop++ monkeypatch.setattr(dist, "init_process_group", _init)+ args = types.SimpleNamespace(ddp_backend = "gloo", ddp_timeout = 123, **BASE_ARGS)+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)+ assert calls[-1].get("backend") == "gloo", calls+ assert calls[-1].get("timeout") == datetime.timedelta(seconds = 123), calls+ # No ddp_backend: the default (NCCL for CUDA when available, else gloo), still with the timeout.+ args = types.SimpleNamespace(ddp_backend = None, ddp_timeout = 77, **BASE_ARGS)+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)+ assert calls[-1]["backend"] == ("nccl" if dist.is_nccl_available() else "gloo"), calls+ assert calls[-1].get("timeout") == datetime.timedelta(seconds = 77), calls++ # Real TrainingArguments: their own device setup (PartialState with backend / timeout) runs first.+ class Args(types.SimpleNamespace):+ @functools.cached_property+ def _setup_devices(self):+ calls.append({"setup_devices": True})+ raise _Stop++ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(+ model = _tiny_llama(), phase = "pre", training_args = Args(**BASE_ARGS)+ )+ assert calls[-1] == {"setup_devices": True}, calls+++# ---- 2. cuda:LOCAL_RANK -----------------------------------------------------------------------+++class _T:+ def __init__(self, device):+ self.device = torch.device(device)+++class Params4bit(_T):+ pass+++class _FakeModel:+ def __init__(+ self,+ tensors,+ device_map = None,+ ):+ self._tensors = tensors+ if device_map is not None:+ self.hf_device_map = device_map++ def parameters(self):+ return iter(self._tensors)++ def buffers(self):+ return iter(())++ def modules(self):+ return iter((self,))+++def test_placed_model_shards_onto_the_local_rank_gpu(native_env, monkeypatch):+ native = native_env+ _fake_cuda(monkeypatch)+ # device_map = {"": 0} on every rank: rank 1 must still use cuda:1.+ model = _FakeModel([_T("cuda:0"), _T("cuda:0")], device_map = {"": 0})+ assert native._shard_device(model) == torch.device("cuda", 1)+ with pytest.raises(RuntimeError, match = "quantized weights are on cuda:0"):+ native._shard_device(_FakeModel([_T("cuda:0"), Params4bit("cuda:0")]))+ with pytest.raises(RuntimeError, match = "split over several GPUs"):+ native._shard_device(_FakeModel([_T("cuda:0"), _T("cuda:1")], device_map = {"a": 0, "b": 1}))+ # Quantized weights already on this rank's GPU are fine.+ assert native._shard_device(_FakeModel([Params4bit("cuda:1"), _T("cuda:0")])) == torch.device(+ "cuda", 1+ )+++# ---- 3. parallelism_config / tp_plan ----------------------------------------------------------+++def test_parallelism_config_and_tp_models_are_refused(native_env, monkeypatch):+ pytest.importorskip("transformers")+ native = native_env+ monkeypatch.setattr(+ native, "_ensure_process_group", lambda device, *_: (_ for _ in ()).throw(_Stop())+ )++ def pc(**sizes):+ base = dict(tp_size = 1, cp_size = 1, sp_size = 1, dp_replicate_size = 1, dp_shard_size = 1)+ return types.SimpleNamespace(**{**base, **sizes})++ for sizes in (dict(tp_size = 2), dict(cp_size = 2), dict(sp_size = 2), dict(dp_replicate_size = 2)):+ args = types.SimpleNamespace(parallelism_config = pc(**sizes), **BASE_ARGS)+ model = _tiny_llama()+ with pytest.raises(RuntimeError, match = "parallelism_config"):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ assert not native.is_native_fsdp2(model)+ try:+ from accelerate import ParallelismConfig+ real = ParallelismConfig(tp_size = 2)+ except Exception:+ real = None+ if real is not None:+ args = types.SimpleNamespace(parallelism_config = real, **BASE_ARGS)+ with pytest.raises(RuntimeError, match = "parallelism_config"):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)+ # A plain shard over every rank is what native FSDP2 does: sharding proceeds.+ args = types.SimpleNamespace(parallelism_config = pc(dp_shard_size = 2), **BASE_ARGS)+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)+ # A tensor-parallel model (from_pretrained(tp_plan = ...) sets tp_size).+ model = _tiny_llama()+ model._tp_size = 2+ with pytest.raises(RuntimeError, match = "already distributed"):+ native.native_fsdp2_trainer_setup(+ model = model, phase = "pre", training_args = types.SimpleNamespace(**BASE_ARGS)+ )+++# ---- 4. torch 2.4 / 2.5 layout ----------------------------------------------------------------+++def test_fsdp_names_resolve_on_the_composable_layout(native_env, monkeypatch):+ native = native_env+ sentinel = object()+ public = types.ModuleType("torch.distributed.fsdp") # 2.4 / 2.5: no FSDP2 names promoted here+ composable = types.ModuleType("torch.distributed._composable.fsdp")+ composable.CPUOffloadPolicy = sentinel+ monkeypatch.setitem(sys.modules, "torch.distributed.fsdp", public)+ monkeypatch.setitem(sys.modules, "torch.distributed._composable.fsdp", composable)+ assert native._fsdp_attr("CPUOffloadPolicy") is sentinel+++_FSDP_FILES = (+ "fsdp2_native.py",+ "fsdp2_perf.py",+ "fsdp2_vision.py",+ "fsdp2_native_quant.py",+ "fsdp2_save.py",+ "fsdp2_qlora.py",+)+++def test_no_unguarded_public_fsdp2_import():+ """Every `from torch.distributed.fsdp import <FSDP2 name>` sits in a try with an ImportError (or+ Exception) handler, so torch 2.4 / 2.5 falls back to `_composable.fsdp`."""+ names = {+ "fully_shard",+ "FSDPModule",+ "MixedPrecisionPolicy",+ "OffloadPolicy",+ "CPUOffloadPolicy",+ "register_fsdp_forward_method",+ }+ bad = []+ for name in _FSDP_FILES:+ path = os.path.join(REPO, "unsloth", "models", name)+ tree = ast.parse(open(path, encoding = "utf-8").read())+ guarded = set()+ fallback = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Try) and any(+ any(+ isinstance(n, (ast.Import, ast.ImportFrom))+ and "torch.distributed._composable.fsdp"+ in (getattr(n, "module", None) or " ".join(a.name for a in n.names))+ for n in ast.walk(h)+ )+ for h in node.handlers+ ):+ for inner in node.body:+ fallback.update(id(n) for n in ast.walk(inner))+ for node in ast.walk(tree):+ if isinstance(node, ast.Try) and any(+ h.type is None or getattr(h.type, "id", "") in ("ImportError", "Exception")+ for h in node.handlers+ ):+ for inner in node.body:+ guarded.update(id(n) for n in ast.walk(inner))+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.ImportFrom)+ and node.module == "torch.distributed.fsdp"+ and names.intersection(a.name for a in node.names)+ and id(node) not in guarded+ ):+ bad.append(f"{name}:{node.lineno}")+ # FSDP2's private modules move with the layout (`_composable.fsdp.<name>` on 2.4 / 2.5):+ # a direct import must sit in a try whose ImportError handler imports the same module+ # from `torch.distributed._composable.fsdp` (the _fsdp_private loaders).+ if (+ isinstance(node, ast.ImportFrom)+ and (node.module or "").startswith("torch.distributed.fsdp._fully_shard")+ and id(node) not in fallback+ ):+ bad.append(f"{name}:{node.lineno} (private)")+ assert not bad, bad+++# ---- 5. Phi-4 multimodal-style towers (gloo) --------------------------------------------------+++class _ImageEmbed(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.img_processor = torch.nn.Linear(16, 8)++ def forward(self, image_pixel_values):+ return self.img_processor(image_pixel_values.flatten(1))+++class _AudioEmbed(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.encoder = torch.nn.Linear(3, 8)++ def forward(self, audio_input_features):+ return self.encoder(audio_input_features).mean(1)+++class _FeatureEmbedding(torch.nn.Module):+ """Phi4MultimodalFeatureEmbedding's shape: image_embed / audio_embed run only for their input."""++ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(16, 8)+ self.image_embed = _ImageEmbed()+ self.audio_embed = _AudioEmbed()++ def forward(+ self,+ input_ids,+ image_pixel_values = None,+ audio_input_features = None,+ ):+ h = self.embed(input_ids)+ if image_pixel_values is not None:+ h = h + self.image_embed(image_pixel_values).mean(0)+ if audio_input_features is not None:+ h = h + self.audio_embed(audio_input_features).mean(0)+ return h+++class _Phi4Like(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed_tokens_extend = _FeatureEmbedding()+ self.head = torch.nn.Linear(8, 4)++ def forward(+ self,+ input_ids,+ image_pixel_values = None,+ audio_input_features = None,+ ):+ h = self.embed_tokens_extend(input_ids, image_pixel_values, audio_input_features)+ return self.head(h).square().mean()+++class _Unknown(torch.nn.Module):+ """Takes pixel_values, runs an encoder no name rule recognises, only for images."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed = torch.nn.Embedding(16, 8)+ self.patch_net = torch.nn.Linear(16, 8)+ self.head = torch.nn.Linear(8, 4)++ def forward(+ self,+ input_ids,+ pixel_values = None,+ ):+ h = self.embed(input_ids)+ if pixel_values is not None:+ h = h + self.patch_net(pixel_values.flatten(1)).mean(0)+ return self.head(h).square().mean()+++def _case_media(rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ _load_native()+ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ res = {}+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ image = {"image_pixel_values": torch.randn(1, 1, 4, 4)}+ audio = {"audio_input_features": torch.randn(1, 6, 3)}+ model = _Phi4Like()+ fully_shard(model.embed_tokens_extend.image_embed, mesh = mesh)+ fully_shard(model.embed_tokens_extend.audio_embed.encoder, mesh = mesh)+ fully_shard(model, mesh = mesh)+ host = vision.install_vision_dummy(model)+ res["phi4.host"] = type(host).__name__ if host is not None else None+ steps = [+ ("text", {}),+ ("image", image),+ ("audio", audio),+ ("mixed_image", image if rank == 0 else {}),+ ("mixed_audio", audio if rank == 1 else {}),+ ]+ for step, kwargs in steps:+ try:+ model(ids, **kwargs).backward()+ res[f"phi4.{step}"] = "ok"+ except Exception as exc:+ res[f"phi4.{step}"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ model = _Unknown()+ fully_shard(model.patch_net, mesh = mesh)+ fully_shard(model, mesh = mesh)+ vision.install_vision_dummy(model)+ for step, kwargs in (+ ("text", {}),+ ("mixed", {"pixel_values": torch.randn(1, 1, 4, 4)} if rank == 0 else {}),+ ):+ try:+ model(ids, **kwargs).backward()+ res[f"unknown.{step}"] = "ok"+ except Exception as exc:+ res[f"unknown.{step}"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++def _worker(rank, world, port, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ out.put((rank, _case_media(rank)))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def test_phi4_style_and_unknown_encoders_are_agreed():+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker, args = (2, _free_port(), out), nprocs = 2, join = False, start_method = "spawn"+ )+ deadline = time.time() + 180+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail("the ranks did not finish within 180 s (hung collective)")+ except mp.ProcessExitedException as exc:+ pytest.fail(f"a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND8_RESULT", rank, r)+ assert "crash" not in r, r["crash"]+ assert r["phi4.host"] in ("_Phi4Like", "FSDP_Phi4Like"), (rank, r)+ for step in ("text", "image", "audio"):+ assert r[f"phi4.{step}"] == "ok", (rank, step, r)+ assert "images on 1 of 2 ranks" in r["phi4.mixed_image"], (rank, r)+ assert "audio on 1 of 2 ranks" in r["phi4.mixed_audio"], (rank, r)+ assert r["unknown.text"] == "ok", (rank, r)+ assert "images on 1 of 2 ranks" in r["unknown.mixed"], (rank, r)diff --git a/tests/test_fsdp2_native_qlora_clef_place_gloo.py b/tests/test_fsdp2_native_qlora_clef_place_gloo.pynew file mode 100644index 00000000000..abd33e4a3db--- /dev/null+++ b/tests/test_fsdp2_native_qlora_clef_place_gloo.py@@ -0,0 +1,202 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2:++* fsdp2_qlora's FSDP2 checks find FSDP2's private modules on torch 2.4 / 2.5's `_composable.fsdp`+ layout too (the new layout hidden in sys.modules);+* a Clef model (DecisionTrainer) is refused at Trainer setup: its `_save` is not collective, and a+ rank-0-only save that enters a collective hangs (gloo world of 2);+* Trainer.__init__ does not `.to(device)` a natively sharded model (CPU offload keeps shards on the+ CPU; everything else is already on the mesh device)."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import importlib # noqa: E402+import importlib.util # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import _free_port, _stub_unsloth_save # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_guards_gloo import _tiny_llama # noqa: E402+++def _load_qlora():+ path = os.path.join(REPO, "unsloth", "models", "fsdp2_qlora.py")+ spec = importlib.util.spec_from_file_location("_fsdp2_qlora_under_test", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_qlora_checks_find_fsdp2_on_the_composable_layout(monkeypatch):+ qlora = _load_qlora()+ assert qlora._missing_fsdp2_anchors() == [] # this torch: the new layout+ real = {+ name: importlib.import_module("torch.distributed.fsdp._fully_shard." + name)+ for name in ("_fsdp_param", "_fsdp_collectives", "_fsdp_param_group", "_fsdp_init")+ }+ # torch 2.4 / 2.5: no torch.distributed.fsdp._fully_shard; the same modules under _composable.fsdp.+ monkeypatch.setitem(sys.modules, "torch.distributed.fsdp._fully_shard", None)+ for name, module in real.items():+ monkeypatch.setitem(sys.modules, "torch.distributed.fsdp._fully_shard." + name, None)+ monkeypatch.setitem(sys.modules, "torch.distributed._composable.fsdp." + name, module)+ assert qlora._missing_fsdp2_anchors() == []+ assert qlora._fsdp_private("_fsdp_init") is real["_fsdp_init"]+++class _CollectiveSave:+ """Stands for DecisionTrainer: `_save` runs a collective (the encoder's gathered save_pretrained)."""++ def _save(+ self,+ output_dir = None,+ state_dict = None,+ ):+ import torch.distributed as dist+ dist.all_reduce(torch.ones(1))+++def _case_clef(native, rank, tmp):+ _install_wrapped_trainer_init()+ from transformers import Trainer++ class DecisionLike(_CollectiveSave, Trainer):+ pass++ model = _tiny_llama()+ model.is_clef = True+ res = {}+ try:+ trainer = DecisionLike(model = model, args = _targs(os.path.join(tmp, "out")))+ res["init"] = "ok"+ except Exception as exc:+ res["init"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ res["sharded"] = native.is_native_fsdp2(model)+ return res+ try:+ trainer.save_model(os.path.join(tmp, "ckpt"))+ res["save"] = "ok"+ except Exception as exc:+ res["save"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++def _case_placement(native, tmp):+ from transformers import Trainer++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ calls = []+ original = torch.nn.Module.to++ def spy(self, *args, **kwargs):+ if self is model:+ calls.append(str(args or kwargs))+ return original(self, *args, **kwargs)++ torch.nn.Module.to = spy+ try:+ Trainer(model = model, args = _targs(os.path.join(tmp, "out")))+ finally:+ torch.nn.Module.to = original+ return {"to_calls": len(calls)}+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 20)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "clef":+ res = _case_clef(native, rank, tmp)+ elif case == "placement":+ res = _case_placement(native, tmp)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 150,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND9_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_clef_models_are_refused_before_a_non_collective_save(tmp_path):+ pytest.importorskip("transformers")+ for rank, r in _run("clef", tmp_path).items():+ assert r["init"].startswith("RuntimeError") and "Clef" in r["init"], (rank, r)+ assert r["sharded"] is False, (rank, r)+++def test_trainer_does_not_move_a_natively_sharded_model(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("placement", tmp_path).items():+ assert r["to_calls"] == 0, (rank, r)diff --git a/tests/test_fsdp2_native_quant_gloo.py b/tests/test_fsdp2_native_quant_gloo.pynew file mode 100644index 00000000000..3219ec79d5b--- /dev/null+++ b/tests/test_fsdp2_native_quant_gloo.py@@ -0,0 +1,298 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""bitsandbytes 4-bit weights under Unsloth's native FSDP2 wrap (fully_shard per block, then the root,+MixedPrecisionPolicy(param_dtype = compute dtype, reduce_dtype = float32)), two gloo ranks on CPU.++`fsdp2_native_quant.native_quant_context` around the fully_shard calls: a pre-quantized (uint8) 4-bit+weight is repacked as the compute dtype and sharded, the all-gathered weight is a Params4bit with its+QuantState and exact packed bytes inside the block's forward, the forward equals the unsharded model and+the trainable gradients equal the full-batch reference. Without it (control) the all-gathered weight is a+plain Parameter with no quant_state. A 16-bit model is left untouched. The modules are loaded from their files.+"""++import importlib.util+import os+import socket+import sys+import types+from pathlib import Path++import pytest+import torch++# Spawned gloo ranks re-import this module: keep them on the CPU (deterministic on GPU hosts; CUDA+# reads the mask at its lazy first use, after this).+if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++_ROOT = Path(__file__).resolve().parents[1]++fsdp_mod = pytest.importorskip("torch.distributed.fsdp")+if not hasattr(fsdp_mod, "fully_shard"):+ pytest.skip("torch has no FSDP2 fully_shard", allow_module_level = True)+if (+ sys.platform == "win32"+ or not torch.distributed.is_available()+ or not torch.distributed.is_gloo_available()+):+ pytest.skip("needs torch.distributed with gloo", allow_module_level = True)+++def _load_models_package():+ """unsloth.models.fsdp2_native_quant and its relative imports, without importing unsloth."""+ pkg = types.ModuleType("_b_models")+ pkg.__path__ = [str(_ROOT / "unsloth" / "models")]+ sys.modules["_b_models"] = pkg+ out = {}+ for name in ("fsdp2_qlora", "fsdp2_save", "fsdp2_native_quant"):+ path = _ROOT / "unsloth" / "models" / f"{name}.py"+ spec = importlib.util.spec_from_file_location(f"_b_models.{name}", path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[f"_b_models.{name}"] = module+ spec.loader.exec_module(module)+ out[name] = module+ return out+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++N_BLOCKS = 3+HIDDEN = 128+++def _linear4bit(bnb, seed, storage):+ torch.manual_seed(seed)+ layer = bnb.nn.Linear4bit(+ HIDDEN,+ HIDDEN,+ bias = False,+ compute_dtype = torch.bfloat16,+ quant_type = "nf4",+ quant_storage = storage,+ )+ layer.weight = bnb.nn.Params4bit(+ torch.randn(HIDDEN, HIDDEN) * 0.05,+ requires_grad = False,+ quant_type = "nf4",+ quant_storage = storage,+ blocksize = 64,+ module = layer,+ )+ return layer.to("cpu")+++def _model(bnb, quantized = True):+ class Block(torch.nn.Module):+ def __init__(self, i):+ super().__init__()+ if quantized:+ # uint8: what a pre-quantized checkpoint loads as.+ self.base = _linear4bit(bnb, 10 + i, torch.uint8)+ else:+ torch.manual_seed(10 + i)+ self.base = torch.nn.Linear(HIDDEN, HIDDEN, bias = False, dtype = torch.bfloat16)+ self.base.requires_grad_(False)+ torch.manual_seed(100 + i)+ self.lora_A = torch.nn.Linear(HIDDEN, 8, bias = False, dtype = torch.bfloat16)+ self.lora_B = torch.nn.Linear(8, HIDDEN, bias = False, dtype = torch.bfloat16)+ torch.nn.init.normal_(self.lora_B.weight, std = 0.05)+ self.seen = []++ def forward(self, x):+ w = self.base.weight+ self.seen.append((type(w).__name__, getattr(w, "quant_state", None) is not None))+ return x + torch.tanh(self.base(x) + self.lora_B(self.lora_A(x)))++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = torch.nn.ModuleList([Block(i) for i in range(N_BLOCKS)])+ torch.manual_seed(7)+ self.norm = torch.nn.LayerNorm(HIDDEN, dtype = torch.bfloat16)++ def forward(self, x):+ for layer in self.layers:+ x = layer(x)+ return self.norm(x)++ return Model()+++def _shard(+ model,+ world_size,+ native_quant_context = None,+):+ import contextlib++ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard++ mesh = init_device_mesh("cpu", (world_size,))+ mp = MixedPrecisionPolicy(param_dtype = torch.bfloat16, reduce_dtype = torch.float32)+ ctx = (+ native_quant_context(model, dtype = torch.bfloat16)+ if native_quant_context+ else contextlib.nullcontext()+ )+ with ctx as info:+ for layer in model.layers:+ fully_shard(layer, mesh = mesh, mp_policy = mp)+ fully_shard(model, mesh = mesh, mp_policy = mp)+ return info+++def _case(rank, world_size, mods, case):+ bnb = pytest.importorskip("bitsandbytes")+ import torch.distributed as dist+ from torch.distributed.tensor import DTensor++ nq = mods["fsdp2_native_quant"]+ quantized = case != "dense"+ model = _model(bnb, quantized)+ reference = _model(bnb, quantized)+ raw = [l.base.weight.data.view(torch.uint8).clone() for l in model.layers]+ xs = [+ torch.randn(4, HIDDEN, generator = torch.Generator().manual_seed(50 + r)).to(torch.bfloat16)+ for r in range(world_size)+ ]+ with torch.no_grad():+ ref_out = reference(xs[rank])+ ref_loss = sum(reference(x).float().square().mean() for x in xs) / world_size+ ref_loss.backward()+ before_ids = {id(p) for p in model.parameters()}++ out = {}+ if case == "control":+ try:+ _shard(model, world_size)+ with torch.no_grad():+ got = model(xs[rank])+ out["forward_equal"] = torch.equal(got, ref_out)+ out["seen"] = sorted({s for l in model.layers for s in l.seen})+ except Exception as error:+ out["forward_equal"] = f"{type(error).__name__}: {error}"[:300]+ return out++ info = _shard(model, world_size, nq.native_quant_context)+ report = nq.after_native_shard(model)+ out["info"] = (+ None if info is None else {k: info[k] for k in ("params4bit", "converted", "patched")}+ )+ out["storage"] = None if info is None else info["storage"]+ out["unsharded"] = report["unsharded"]+ out["params4bit_sharded"] = report["params4bit_sharded"]+ out["same_objects_dense"] = case == "dense" and all(+ isinstance(p, DTensor) for p in model.parameters()+ )+ for l in model.layers:+ l.seen.clear()+ with torch.no_grad():+ got = model(xs[rank])+ out["forward_equal"] = torch.equal(got, ref_out)+ out["seen"] = sorted({s for l in model.layers for s in l.seen})+ # Exact packed bytes on the all-gathered weight, inside the block's unshard.+ exact = []+ for l, r in zip(model.layers, raw):+ l.unshard()+ exact.append(torch.equal(l.base.weight.data.reshape(-1).view(torch.uint8), r.reshape(-1)))+ l.reshard()+ out["bytes_exact"] = all(exact)+ model(xs[rank]).float().square().mean().backward()+ diffs = []+ ref_named = dict(reference.named_parameters())+ for name, p in model.named_parameters():+ if not p.requires_grad:+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ diffs.append(float((g.float() - ref_named[name].grad.float()).abs().max()))+ out["grad_max_diff"] = max(diffs)+ out["all_dtensor_after"] = all(isinstance(p, DTensor) for p in model.parameters())+ return out+++def _worker(rank, world_size, port, case, queue):+ try:+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world_size),+ )+ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world_size)+ mods = _load_models_package()+ result = _case(rank, world_size, mods, case)+ queue.put((rank, result))+ dist.destroy_process_group()+ except BaseException as error:+ import traceback+ queue.put((rank, {"error": f"{type(error).__name__}: {error}\n{traceback.format_exc()}"}))+++def _run(case, world_size = 2):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ queue = ctx.Queue()+ port = _free_port()+ procs = [+ ctx.Process(target = _worker, args = (r, world_size, port, case, queue))+ for r in range(world_size)+ ]+ for p in procs:+ p.start()+ results = {}+ for _ in procs:+ rank, result = queue.get(timeout = 300)+ results[rank] = result+ for p in procs:+ p.join(timeout = 60)+ for r in results.values():+ assert "error" not in r, r.get("error")+ return results+++def test_native_fsdp2_shards_4bit_and_keeps_quant_state():+ pytest.importorskip("bitsandbytes")+ results = _run("native")+ for r in results.values():+ assert r["info"] == {"params4bit": N_BLOCKS, "converted": N_BLOCKS, "patched": True}, r+ assert r["storage"] == ["bfloat16"], r+ assert r["unsharded"] == [], r+ assert r["params4bit_sharded"] == N_BLOCKS, r+ assert r["seen"] == [("Params4bit", True)], r+ assert r["bytes_exact"], r+ assert r["forward_equal"] is True, r+ assert r["grad_max_diff"] < 2e-2, r+ assert r["all_dtensor_after"], r+++def test_without_native_quant_context_the_gathered_weight_is_not_4bit():+ # Control: the same fully_shard calls with no 4-bit handling. bitsandbytes' own Linear4bit forward+ # recovers (it re-reads the module's copy of the QuantState), but the all-gathered weight the block+ # sees is a plain Parameter without quant_state: what Unsloth's fused LoRA kernels and the zoo MoE+ # 4-bit paths read (they take it for a dense weight, or crash).+ pytest.importorskip("bitsandbytes")+ # torch < 2.12 cannot shard the uint8 weight at all ("only Tensors of floating point dtype can+ # require gradients"); later torch shards it but gathers a plain Parameter.+ results = _run("control")+ for r in results.values():+ raised = isinstance(r["forward_equal"], str) and "floating point" in r["forward_equal"]+ assert raised or r.get("seen") == [("Parameter", False)], r+++def test_native_fsdp2_leaves_16bit_untouched():+ pytest.importorskip("bitsandbytes")+ results = _run("dense")+ for r in results.values():+ assert r["info"] is None, r+ assert r["unsharded"] == [] and r["params4bit_sharded"] == 0, r+ assert r["forward_equal"] is True and r["all_dtensor_after"], r+ assert r["grad_max_diff"] < 2e-2, rdiff --git a/tests/test_fsdp2_native_resume_gloo.py b/tests/test_fsdp2_native_resume_gloo.pynew file mode 100644index 00000000000..d054cd603a2--- /dev/null+++ b/tests/test_fsdp2_native_resume_gloo.py@@ -0,0 +1,184 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 checkpoint resume on a gloo CPU world of 2 (fsdp2_native.py loaded on its own, no GPU):+train 2 steps, save the model (as Trainer.save_model writes it) and the optimizer with+native_save_optimizer, resume a freshly built and sharded copy with native_load_model_checkpoint ++native_load_optimizer, then 2 more steps on both: losses and parameters must be identical. Negative+control: rank 0's plain `optimizer.state_dict()` (the Trainer's own save) holds only rank 0's shards."""++import os+import socket+import sys++import pytest+import torch++# Spawned gloo ranks re-import this module: keep them on the CPU (deterministic on GPU hosts; CUDA+# reads the mask at its lazy first use, after this).+if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import _load_native # noqa: E402++REPO_ID = "hf-internal-testing/tiny-random-LlamaForCausalLM"+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _model(lora, seed):+ import transformers++ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ config.pad_token_id = None # tiny repo's -1 fails save_pretrained's config check+ torch.manual_seed(0) # identical base weights on every build+ model = transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None+ if lora:+ from peft import LoraConfig, get_peft_model++ torch.manual_seed(seed)+ model = get_peft_model(model, LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear"))+ with torch.no_grad():+ g = torch.Generator().manual_seed(seed)+ for n, p in model.named_parameters():+ if "lora_B" in n:+ p.normal_(0, 0.02, generator = g)+ elif seed:+ with torch.no_grad():+ g = torch.Generator().manual_seed(seed)+ for p in model.parameters():+ p.add_(torch.randn(p.shape, generator = g) * 0.01)+ return model+++def _batch(step, rank):+ g = torch.Generator().manual_seed(100 * step + rank)+ ids = torch.randint(3, 1000, (2, 16), generator = g)+ return {"input_ids": ids, "labels": ids.clone(), "use_cache": False}+++def _step(model, opt, step, rank):+ loss = model(**_batch(step, rank)).loss+ loss.backward()+ opt.step()+ opt.zero_grad(set_to_none = True)+ return loss.detach().clone()+++def _full_params(model):+ from torch.distributed.tensor import DTensor+ return {+ n: (p.full_tensor() if isinstance(p, DTensor) else p).detach().clone()+ for n, p in model.named_parameters()+ if p.requires_grad+ }+++def _worker(rank, world, port, lora, tmp, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ cfg = native.FSDP2Config(param_dtype = torch.float32)++ def _new(seed):+ m = native.shard_model(_model(lora, seed), cfg)+ o = torch.optim.AdamW(+ [p for p in m.parameters() if p.requires_grad], lr = 1e-2, foreach = False+ )+ return m, o++ model, opt = _new(1)+ for step in (1, 2):+ _step(model, opt, step, rank)+ ckpt = os.path.join(tmp, "ckpt")+ state = native.native_full_state_dict(model, trainable_only = lora)+ opt_path = os.path.join(ckpt, "optimizer.pt")+ plain_path = os.path.join(ckpt, "optimizer_rank0_plain.pt")+ if rank == 0:+ os.makedirs(ckpt, exist_ok = True)+ model.save_pretrained(ckpt, state_dict = state, safe_serialization = True)+ torch.save(opt.state_dict(), plain_path) # what Trainer saves without the hook+ native.native_save_optimizer(model, opt, opt_path, should_save = rank == 0)+ dist.barrier()+ want = [_step(model, opt, step, rank).item() for step in (3, 4)]+ want_params = _full_params(model)++ resumed, ropt = _new(2) # different fresh trainable values: the load must replace them+ native.native_load_model_checkpoint(resumed, ckpt)+ native.native_load_optimizer(resumed, ropt, opt_path)+ got = [_step(resumed, ropt, step, rank).item() for step in (3, 4)]+ got_params = _full_params(resumed)+ param_diff = max((got_params[n] - want_params[n]).abs().max().item() for n in want_params)++ control, copt = _new(2)+ native.native_load_model_checkpoint(control, ckpt)+ try:+ copt.load_state_dict(torch.load(plain_path, weights_only = False))+ ctrl = [_step(control, copt, step, rank).item() for step in (3, 4)]+ ctrl_error = None+ except Exception as exc:+ ctrl, ctrl_error = None, f"{type(exc).__name__}: {str(exc)[:200]}"+ ctrl_flag = torch.tensor([0 if ctrl is None else int(ctrl != want)], dtype = torch.int64)+ dist.all_reduce(ctrl_flag)+ out.put(+ (+ rank,+ {+ "want": want,+ "got": got,+ "param_diff": param_diff,+ "ctrl": ctrl,+ "ctrl_error": ctrl_error,+ "ctrl_differs_any_rank": int(ctrl_flag.item()),+ },+ )+ )+ except Exception as exc:+ import traceback+ out.put((rank, {"error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ dist.destroy_process_group()++[email protected]("lora", [True, False], ids = ["lora", "full"])+def test_native_resume_replays_exactly(lora, tmp_path):+ pytest.importorskip("transformers")+ if lora:+ pytest.importorskip("peft")+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ port = _free_port()+ procs = [+ ctx.Process(target = _worker, args = (r, 2, port, lora, str(tmp_path), out)) for r in range(2)+ ]+ for p in procs:+ p.start()+ results = dict(out.get(timeout = 600) for _ in procs)+ for p in procs:+ p.join(timeout = 60)+ for rank, r in results.items():+ print("RESUME_RESULT", rank, r)+ assert "error" not in r, r["error"]+ assert r["got"] == r["want"], (rank, r)+ assert r["param_diff"] == 0.0, (rank, r)+ # Rank 0's plain optimizer.state_dict() is not a valid resume for a sharded model.+ assert r["ctrl_error"] is not None or r["ctrl_differs_any_rank"] > 0, (rank, r)diff --git a/tests/test_fsdp2_native_subclass_optimizer_gloo.py b/tests/test_fsdp2_native_subclass_optimizer_gloo.pynew file mode 100644index 00000000000..093462be393--- /dev/null+++ b/tests/test_fsdp2_native_subclass_optimizer_gloo.py@@ -0,0 +1,216 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 with a Trainer subclass that builds its own optimizer (gloo world of 2):+UnslothTrainer's create_optimizer with `embedding_learning_rate` (unsloth/trainer.py, run here from+its source) never calls the base Trainer.create_optimizer, so a group mixing a replicated trainable+parameter with sharded ones reached the LR scheduler unsplit (transformers 4.x+create_optimizer_and_scheduler builds the scheduler before Accelerator.prepare). The groups are now+split before the scheduler is built: one base LR per final group, and every group follows the+schedule during training."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import datetime # noqa: E402+import functools # noqa: E402+import inspect # noqa: E402+import logging # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import _free_port # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)++_HELPERS = (+ "_create_unsloth_optimizer",+ "_embedding_weight_ids",+ "_install_legacy_resume",+ "_migrate_legacy_optimizer_state",+ "_migrate_previous_layout_state",+ "_super_create_optimizer_takes_model",+)+_CONSTANTS = (+ "_LEGACY_ROLE_ORDER",+ "_EMBEDDING_SPLIT_MARKER",+ "_SUPER_CREATE_OPTIMIZER_TAKES_MODEL",+)+++def _unsloth_trainer_class():+ """UnslothTrainer with its real create_optimizer and the optimizer builder it calls, from+ unsloth/trainer.py (importing unsloth needs a GPU); SFTTrainer stands as transformers' Trainer."""+ from transformers import Trainer++ path = os.path.join(REPO, "unsloth", "trainer.py")+ tree = ast.parse(open(path, encoding = "utf-8").read())+ body = []+ for node in tree.body:+ if isinstance(node, ast.FunctionDef) and node.name in _HELPERS:+ body.append(node)+ elif isinstance(node, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id in _CONSTANTS for t in node.targets+ ):+ body.append(node)+ elif isinstance(node, ast.ClassDef) and node.name == "UnslothTrainer":+ method = next(+ n+ for n in node.body+ if isinstance(n, ast.FunctionDef) and n.name == "create_optimizer"+ )+ node.body = [method]+ node.decorator_list = []+ body.append(node)+ ns = {+ "torch": torch,+ "inspect": inspect,+ "wraps": functools.wraps,+ "functools": functools,+ "logger": logging.getLogger("unsloth_test"),+ "SFTTrainer": Trainer,+ "__name__": "unsloth_trainer_source",+ }+ exec(compile(ast.Module(body = body, type_ignores = []), path, "exec"), ns)+ return ns["UnslothTrainer"]+++def _mixed_model(native):+ model = _lora(1)+ first = next(p for n, p in model.named_parameters() if "lora_A" in n)+ cfg = native.FSDP2Config(param_dtype = torch.float32, ignored_params = {first})+ return native.shard_model(model, cfg)+++def _case_scheduler(native, tmp):+ _install_wrapped_trainer_init()+ trainer = _unsloth_trainer_class()(model = _mixed_model(native), args = _targs(tmp))+ trainer.args.embedding_learning_rate = 1e-4+ trainer.create_optimizer_and_scheduler(num_training_steps = 10)+ optimizer = trainer.optimizer+ return {+ "mixed_left": native._mixed_param_groups(optimizer),+ "groups": len(optimizer.param_groups),+ "base_lrs": len(trainer.lr_scheduler.base_lrs),+ "lambdas": len(getattr(trainer.lr_scheduler, "lr_lambdas", [])),+ }+++def _case_train(native, tmp):+ from datasets import Dataset++ _install_wrapped_trainer_init()+ ds = Dataset.from_list([{"input_ids": list(range(5, 21)), "labels": list(range(5, 21))}] * 4)+ args = _targs(+ tmp,+ max_steps = 3,+ learning_rate = 1e-3,+ per_device_train_batch_size = 1,+ lr_scheduler_type = "linear",+ save_strategy = "no",+ logging_steps = 1,+ )+ args.embedding_learning_rate = 1e-4+ trainer = _unsloth_trainer_class()(model = _mixed_model(native), args = args, train_dataset = ds)+ trainer.train()+ groups = trainer.optimizer.param_groups+ # Linear decay to 0 over 3 steps: after the last step every group sits at lr 0; a group the+ # scheduler never saw keeps its initial LR.+ return {+ "mixed_left": native._mixed_param_groups(trainer.optimizer),+ "lrs": [float(g["lr"]) for g in groups],+ }+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ res = _case_scheduler(native, tmp) if case == "scheduler" else _case_train(native, tmp)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 240,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND12_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_subclass_optimizer_groups_are_split_before_the_scheduler(tmp_path):+ pytest.importorskip("peft")+ for rank, r in _run("scheduler", tmp_path).items():+ assert r["mixed_left"] == 0, (rank, r)+ assert r["base_lrs"] == r["groups"] and r["lambdas"] == r["groups"], (rank, r)+++def test_subclass_optimizer_every_group_follows_the_schedule(tmp_path):+ pytest.importorskip("peft")+ pytest.importorskip("datasets")+ for rank, r in _run("train", tmp_path).items():+ assert r["mixed_left"] == 0, (rank, r)+ assert all(lr == 0.0 for lr in r["lrs"]), (rank, r)diff --git a/tests/test_fsdp2_native_submesh_gloo.py b/tests/test_fsdp2_native_submesh_gloo.pynew file mode 100644index 00000000000..8a17f247eae--- /dev/null+++ b/tests/test_fsdp2_native_submesh_gloo.py@@ -0,0 +1,234 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 on a sub-mesh (gloo world of 4, two disjoint 2-rank meshes [0, 1] and [2, 3], each+sharding its own model replica on its own data):++* a trainable parameter left replicated (ignored_params) gets its gradient averaged over its own+ mesh's two ranks, not over all four (the other pair's data would leak in); on a 2 x 2 HSDP mesh+ over all four ranks, over all four;+* the per-input media agreement counts only the mesh's ranks: a mixed batch in one pair raises+ there, 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."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import importlib # noqa: E402+import sys # noqa: E402+import time # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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_args_gloo import _lora # noqa: E402+from test_fsdp2_native_per_input_gloo import _MoshiLike # noqa: E402++WORLD = 4+++def _submesh(rank, whole = False):+ from torch.distributed.device_mesh import DeviceMesh+ mesh = DeviceMesh("cpu", [[0, 1], [2, 3]], mesh_dim_names = ("pair", "shard"))+ return mesh if whole else mesh["shard"]+++def _case_grads(+ native,+ rank,+ hsdp = False,+):+ import torch.distributed as dist++ mesh = _submesh(rank, whole = hsdp)+ model = _lora(1)+ reference = _lora(1)+ name, first = next((n, p) for n, p in model.named_parameters() if "lora_A" in n)+ cfg = native.FSDP2Config(param_dtype = torch.float32, ignored_params = {first}, mesh = mesh)+ model = native.shard_model(model, cfg)+ ids = torch.randint(1, 100, (1, 8), generator = torch.Generator().manual_seed(rank))+ model(input_ids = ids, labels = ids).loss.backward()+ reference(input_ids = ids, labels = ids).loss.backward()+ local = dict(reference.named_parameters())[name].grad.detach().clone()+ every = [torch.zeros_like(local) for _ in range(WORLD)]+ dist.all_gather(every, local) # the test's own view of every rank's unreduced gradient+ pair = [0, 1] if rank < 2 else [2, 3]+ want_pair = sum(every[r] for r in pair) / 2+ want_world = sum(every) / WORLD+ got = dict(model.named_parameters())[name].grad+ return {+ "mesh_ranks": mesh.mesh.tolist(),+ "pair_diff": (got - want_pair).abs().max().item(),+ "world_diff": (got - want_world).abs().max().item(),+ }+++def _case_media(rank):+ from torch.distributed.fsdp import fully_shard++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = _submesh(rank)+ model = _MoshiLike()+ fully_shard(model.audio_encoder.proj, mesh = mesh)+ fully_shard(model, mesh = mesh)+ vision.install_vision_dummy(model)+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ audio = lambda: torch.randn(1, 6, 3) # noqa: E731+ # Pair [0, 1]: both ranks user audio only. Pair [2, 3]: rank 2 has both inputs, rank 3 one.+ kwargs = {"user_input_values": audio()}+ if rank == 2:+ kwargs["moshi_input_values"] = audio()+ try:+ model(ids, **kwargs).backward()+ return {"step": "ok"}+ except Exception as exc:+ return {"step": f"{type(exc).__name__}: {str(exc)[:300]}"}+++def _case_fit(native, rank):+ """Rank 3's GPU is too small for the fit layout, the others' are not: only pair [2, 3] falls back+ to the sharded layout."""+ perf = sys.modules["unsloth.models.fsdp2_perf"]+ perf._device_bytes = lambda device = None: 0 if rank == 3 else 1 << 40+ agreed = {}+ original = native._agree_over_ranks++ def record(*args, **kwargs):+ agreed["flags"] = original(*args, **kwargs)+ return agreed["flags"]++ native._agree_over_ranks = record+ mesh = _submesh(rank)+ native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32, mesh = mesh))+ return {"fits": agreed["flags"][0]}+++def _case_subgroup(native, rank):+ """Only pair [0, 1] shards a model; ranks 2 and 3 never call shard_model."""+ import torch.distributed as dist++ mesh = _submesh(rank)+ res = {"sharded": False}+ if rank < 2:+ model = native.shard_model(+ _lora(1), native.FSDP2Config(param_dtype = torch.float32, mesh = mesh)+ )+ res["sharded"] = native.is_native_fsdp2(model)+ dist.barrier()+ return res+++def _worker(rank, world, port, out, case):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ # Ranks 2 and 3 can wait at a world barrier while the other pair shards a model, which takes+ # more than 30 s on a loaded CI runner; _run's deadline still catches a real hang.+ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 150)+ )+ try:+ native = _load_native()+ if case == "media":+ res = _case_media(rank)+ elif case == "fit":+ importlib.import_module("unsloth.models.fsdp2_perf")+ res = _case_fit(native, rank)+ elif case == "subgroup":+ res = _case_subgroup(native, rank)+ else:+ res = _case_grads(native, rank, hsdp = case == "hsdp")+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(case, timeout = 180):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (WORLD, _free_port(), out, case),+ nprocs = WORLD,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == list(range(WORLD)), results+ for rank, r in results.items():+ print("ROUND11_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_replicated_grads_average_over_the_model_mesh_only():+ pytest.importorskip("peft")+ for rank, r in _run("grads").items():+ assert r["mesh_ranks"] == ([0, 1] if rank < 2 else [2, 3]), (rank, r)+ # The two pairs' data differ, so the world average is measurably another value.+ assert r["world_diff"] > 1e-6 and r["pair_diff"] < r["world_diff"] / 100, (rank, r)+++def test_media_agreement_counts_only_the_model_mesh():+ results = _run("media")+ assert results[0]["step"] == "ok" and results[1]["step"] == "ok", results+ for rank in (2, 3):+ r = results[rank]+ assert r["step"].startswith("RuntimeError") and "on 1 of 2 ranks" in r["step"], (rank, r)+++def test_replicated_grads_average_over_a_whole_hsdp_mesh():+ pytest.importorskip("peft")+ for rank, r in _run("hsdp").items():+ assert r["mesh_ranks"] == [[0, 1], [2, 3]], (rank, r)+ assert r["pair_diff"] > 1e-6 and r["world_diff"] < r["pair_diff"] / 100, (rank, r)+++def test_layout_agreement_is_per_mesh():+ pytest.importorskip("peft")+ results = _run("fit")+ assert [results[r]["fits"] for r in range(WORLD)] == [True, True, False, False], results+++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], resultsdiff --git a/tests/test_fsdp2_native_trainer_args_gloo.py b/tests/test_fsdp2_native_trainer_args_gloo.pynew file mode 100644index 00000000000..71e76e7da78--- /dev/null+++ b/tests/test_fsdp2_native_trainer_args_gloo.py@@ -0,0 +1,298 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 and the Trainer's constructor arguments, on a gloo CPU world of 2. The real+`_unsloth_trainer_init` (taken from unsloth/models/_utils.py) wraps transformers' Trainer.__init__:++* an optimizer passed positionally (Trainer's own order) is refused like a keyword one;+* `model_init` (and with it hyperparameter_search) is refused instead of training unsharded;+* `save_on_each_node=True` across nodes is refused (only global rank 0 holds the gathered state);+* a resume of a non-default active PEFT adapter reads `<ckpt>/<adapter>/`, never the root adapter.+Plus the launcher env: an explicit native backend turns accelerate's FSDP launch env off."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import importlib.util # noqa: E402+import sys # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import ( # noqa: E402+ REPO_ID,+ _free_port,+ _full,+ _stub_unsloth_save,+)+++def _install_wrapped_trainer_init():+ """Trainer.__init__ wrapped by the `_unsloth_trainer_init` source in _utils.py, with the+ unrelated helpers it calls stubbed (they need the whole unsloth package)."""+ from transformers import Trainer++ if getattr(Trainer, "_test_wrapped", False):+ return+ path = os.path.join(REPO, "unsloth", "models", "_utils.py")+ tree = ast.parse(open(path, encoding = "utf-8").read())+ fn = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_trainer_init"+ )+ fsdp2 = types.ModuleType("unsloth.models.fsdp2")+ fsdp2.install_fsdp2_policy_provenance = lambda: None+ sys.modules["unsloth.models.fsdp2"] = fsdp2+ noop = lambda *a, **k: None # noqa: E731+ ns = {+ "__name__": "unsloth.models._utils",+ "__package__": "unsloth.models",+ "os": os,+ "_original_trainer_init": Trainer.__init__,+ "apply_accepts_loss_kwargs_fix": noop,+ "_replan_auto_offload_safely": noop,+ "_block_swap_for_trainer_backend": noop,+ "_enable_ddp_batched_grad_copy": noop,+ }+ exec(compile(ast.Module(body = [fn], type_ignores = []), path, "exec"), ns)+ Trainer.__init__ = ns["_unsloth_trainer_init"]+ Trainer._test_wrapped = True+++def _lora(+ seed,+ same_config_adapter = False,+ active = "default",+):+ import transformers+ from peft import LoraConfig, get_peft_model++ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ config.pad_token_id = None+ torch.manual_seed(0)+ model = transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None+ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"])+ model = get_peft_model(model, cfg)+ if same_config_adapter:+ model.add_adapter(+ "other", LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"])+ )+ g = torch.Generator().manual_seed(seed)+ with torch.no_grad():+ for n, p in model.named_parameters():+ if "lora_" in n:+ p.normal_(0, 0.02, generator = g)+ if active != "default":+ model.set_adapter(active)+ return model+++def _targs(out, **kw):+ from transformers import TrainingArguments+ return TrainingArguments(output_dir = out, report_to = [], use_cpu = True, **kw)+++def _worker(rank, world, port, out, case, tmp, env):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ os.environ.update(env)+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ _install_wrapped_trainer_init()+ from transformers import Trainer++ res = {}+ if case == "positional_optimizer":+ model = _lora(1)+ optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad])+ targs = _targs(os.path.join(tmp, "out"))+ try:+ # Trainer's positional order: model, args, data_collator, train_dataset, eval_dataset,+ # processing_class, model_init, compute_loss_func, compute_metrics, callbacks, optimizers.+ trainer = Trainer(+ model, targs, None, None, None, None, None, None, None, None, (optimizer, None)+ )+ params = {id(p) for p in trainer.model.parameters()}+ res["stale"] = sum(+ id(p) not in params for g in optimizer.param_groups for p in g["params"]+ )+ except RuntimeError as exc:+ res["error"] = str(exc)+ elif case == "model_init":+ targs = _targs(os.path.join(tmp, "out"))+ try:+ trainer = Trainer(args = targs, model_init = lambda: _lora(1))+ res["sharded"] = native.is_native_fsdp2(trainer.model)+ except RuntimeError as exc:+ res["error"] = str(exc)+ elif case == "save_on_each_node":+ # Two nodes of one process each: both ranks are local rank 0, so both `should_save`.+ node_dir = os.path.join(tmp, f"node{rank}")+ targs = _targs(node_dir, save_on_each_node = True)+ try:+ trainer = Trainer(model = _lora(1), args = targs)+ trainer.create_optimizer()+ trainer._save_optimizer_and_scheduler(node_dir)+ state = torch.load(os.path.join(node_dir, "optimizer.pt"), weights_only = True)+ res["optimizer_keys"] = sorted(state)+ except RuntimeError as exc:+ res["error"] = str(exc)+ elif case == "named_adapter":+ cfg = native.FSDP2Config(param_dtype = torch.float32)+ ckpt = os.path.join(tmp, "ckpt")+ src = native.shard_model(_lora(1, same_config_adapter = True, active = "other"), cfg)+ Trainer(model = src, args = _targs(os.path.join(tmp, "out"))).save_model(ckpt)+ dist.barrier()+ want = _full(src)+ dst = native.shard_model(_lora(2, same_config_adapter = True, active = "other"), cfg)+ try:+ native.native_load_model_checkpoint(dst, ckpt)+ got = _full(dst)+ other = [n for n in want if ".other." in n]+ res["n_other"] = len(other)+ res["other_diff"] = max((got[n] - want[n]).abs().max().item() for n in other)+ res["files"] = sorted(+ os.path.relpath(os.path.join(d, f), ckpt)+ for d, _, fs in os.walk(ckpt)+ for f in fs+ if f.startswith("adapter_model")+ )+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ dist.destroy_process_group()+++def _run(+ case,+ tmp_path,+ env = None,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path), dict(env or {})),+ nprocs = 2,+ join = True,+ start_method = "spawn",+ )+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ARGS_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_positional_optimizer_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("positional_optimizer", tmp_path).items():+ assert "optimizer built before the Trainer" in r.get("error", ""), (rank, r)+++def test_model_init_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("model_init", tmp_path).items():+ assert "model_init" in r.get("error", ""), (rank, r)+++def test_save_on_each_node_across_nodes_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ env = {"LOCAL_RANK": "0", "LOCAL_WORLD_SIZE": "1"}+ for rank, r in _run("save_on_each_node", tmp_path, env).items():+ assert "save_on_each_node" in r.get("error", ""), (rank, r)+++def test_resume_reads_named_adapter_from_its_subdirectory(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("named_adapter", tmp_path).items():+ assert "load_error" not in r, (rank, r)+ assert r["n_other"] > 0 and r["other_diff"] == 0.0, (rank, r)+++# ---- launcher env (no process group) ----------------------------------------------------------+++def _load_launch():+ path = os.path.join(REPO, "unsloth", "fsdp2_launch.py")+ spec = importlib.util.spec_from_file_location("_unsloth_fsdp2_launch_args", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def clean_env(monkeypatch):+ saved = dict(os.environ)+ for key in ("ACCELERATE_USE_FSDP", "FSDP_VERSION", "UNSLOTH_FSDP2_BACKEND", "RANK"):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setenv("UNSLOTH_FSDP2", "1")+ monkeypatch.setenv("WORLD_SIZE", "2")+ yield+ os.environ.clear()+ os.environ.update(saved)+++def test_explicit_native_backend_turns_accelerate_fsdp_env_off(clean_env, monkeypatch, capsys):+ launch = _load_launch()+ # What `accelerate launch` exports for an FSDP config (accelerate/utils/launch.py).+ monkeypatch.setenv("ACCELERATE_USE_FSDP", "true")+ monkeypatch.setenv("FSDP_VERSION", "2")+ monkeypatch.setenv("UNSLOTH_FSDP2_BACKEND", "native")+ monkeypatch.setenv("RANK", "0")+ assert launch.unsloth_fsdp2_native_requested()+ assert launch.apply_unsloth_fsdp2_launch_env() is False+ assert os.environ.get("ACCELERATE_USE_FSDP", "false").lower() != "true"+ assert "FSDP_VERSION" not in os.environ+ # Still native once the accelerate variables are gone, and the second call is a no-op.+ assert launch.unsloth_fsdp2_native_requested()+ assert launch.apply_unsloth_fsdp2_launch_env() is False+ assert capsys.readouterr().out.count("UNSLOTH_FSDP2_BACKEND") == 1+++def test_accelerate_fsdp_launch_without_backend_is_left_alone(clean_env, monkeypatch):+ launch = _load_launch()+ monkeypatch.setenv("ACCELERATE_USE_FSDP", "true")+ monkeypatch.setenv("FSDP_VERSION", "2")+ assert not launch.unsloth_fsdp2_native_requested()+ launch.apply_unsloth_fsdp2_launch_env()+ assert os.environ["ACCELERATE_USE_FSDP"] == "true" and os.environ["FSDP_VERSION"] == "2"diff --git a/tests/test_fsdp2_native_trainer_ckpt_gloo.py b/tests/test_fsdp2_native_trainer_ckpt_gloo.pynew file mode 100644index 00000000000..788b7521df5--- /dev/null+++ b/tests/test_fsdp2_native_trainer_ckpt_gloo.py@@ -0,0 +1,340 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 Trainer checkpoints on a gloo CPU world of 2 (fsdp2_native.py loaded on its own):++* `Trainer._load_best_model` (load_best_model_at_end) goes through the native loader, LoRA and full;+* a resume restores persistent buffers (a routing bias), not only parameters;+* `Trainer.save_model` of a LoRA model writes the frozen tensors PEFT saves: the resized embedding+ tables and an inactive adapter, with their full values.+Plus the CPU-only unit checks of the process-group bootstrap and the bitsandbytes optimizer swap."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import socket # noqa: E402+import sys # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import REPO, _load_native # noqa: E402++REPO_ID = "hf-internal-testing/tiny-random-LlamaForCausalLM"+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _stub_unsloth_save():+ """unsloth/save.py needs the whole package (GPU); the hook only needs its PEFT selector, taken+ verbatim from the source."""+ if "unsloth.save" in sys.modules:+ return+ path = os.path.join(REPO, "unsloth", "save.py")+ tree = ast.parse(open(path, encoding = "utf-8").read())+ fn = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_fsdp2_peft_saved_frozen"+ )+ module = types.ModuleType("unsloth.save")+ exec(compile(ast.Module(body = [fn], type_ignores = []), path, "exec"), module.__dict__)+ sys.modules["unsloth.save"] = module+++def _model(+ lora,+ seed,+ tmp,+ resize = False,+ other_adapter = False,+ buffers = False,+):+ import transformers++ config = transformers.AutoConfig.from_pretrained(REPO_ID)+ config.pad_token_id = None # tiny repo's -1 fails save_pretrained's config check+ base_dir = os.path.join(tmp, "base_config")+ if resize and not os.path.isdir(base_dir):+ config.save_pretrained(base_dir) # PEFT compares the vocab with the base config's+ torch.manual_seed(0)+ model = transformers.AutoModelForCausalLM.from_config(config, torch_dtype = torch.float32)+ if getattr(model, "generation_config", None) is not None:+ model.generation_config.pad_token_id = None+ g = torch.Generator().manual_seed(seed)+ if resize:+ model.resize_token_embeddings(config.vocab_size + 8)+ model.config._name_or_path = base_dir+ model.name_or_path = base_dir+ with torch.no_grad():+ for module in (model.get_input_embeddings(), model.get_output_embeddings()):+ module.weight.normal_(0, 0.02, generator = g)+ if buffers:+ # Persistent buffers outside and inside a block (DeepSeek-like routing correction bias).+ model.model.register_buffer("running_scale", torch.full((4,), float(seed)))+ model.model.layers[0].mlp.register_buffer("route_bias", torch.arange(4.0) * seed)+ if lora:+ from peft import LoraConfig, get_peft_model++ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj"])+ model = get_peft_model(model, cfg)+ if other_adapter:+ model.add_adapter("other", LoraConfig(r = 2, lora_alpha = 4, target_modules = ["k_proj"]))+ with torch.no_grad():+ for n, p in model.named_parameters():+ if "lora_" in n:+ p.normal_(0, 0.02, generator = g)+ elif not resize:+ with torch.no_grad():+ for p in model.parameters():+ p.add_(torch.randn(p.shape, generator = g) * 0.01)+ return model+++def _full(model, trainable_only = False):+ from torch.distributed.tensor import DTensor+ return {+ n: (p.full_tensor() if isinstance(p, DTensor) else p).detach().clone()+ for n, p in model.named_parameters()+ if p.requires_grad or not trainable_only+ }+++def _trainer(model, tmp):+ from transformers import Trainer, TrainingArguments+ args = TrainingArguments(output_dir = os.path.join(tmp, "out"), report_to = [], use_cpu = True)+ return Trainer(model = model, args = args)+++def _worker(rank, world, port, out, case, tmp):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ cfg = native.FSDP2Config(param_dtype = torch.float32)+ ckpt = os.path.join(tmp, "ckpt")+ res = {}+ if case in ("best_lora", "best_full"):+ lora = case == "best_lora"+ src = native.shard_model(_model(lora, 1, tmp), cfg)+ _trainer(src, tmp).save_model(ckpt)+ dist.barrier()+ want = _full(src, trainable_only = lora)+ dst = native.shard_model(_model(lora, 2, tmp), cfg)+ trainer = _trainer(dst, tmp)+ trainer.state.best_model_checkpoint = ckpt+ try:+ trainer._load_best_model()+ got = _full(dst, trainable_only = lora)+ res["max_diff"] = max((got[n] - want[n]).abs().max().item() for n in want)+ res["n"] = len(want)+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ elif case == "full_save_wait":+ # Full finetuning: only rank 0 writes the gathered model. Slow its write down; rank 1+ # must not return from save_model before the files exist.+ import time++ src = native.shard_model(_model(False, 1, tmp), cfg)+ if rank == 0:+ save = native._save_unwrapped++ def slow_save(*args, **kwargs):+ time.sleep(3.0)+ return save(*args, **kwargs)++ native._save_unwrapped = slow_save+ _trainer(src, tmp).save_model(ckpt)+ res["written_on_return"] = os.path.isfile(os.path.join(ckpt, "model.safetensors"))+ elif case == "buffers":+ src = native.shard_model(_model(False, 1, tmp, buffers = True), cfg)+ state = native.native_full_state_dict(src)+ if rank == 0:+ src.save_pretrained(ckpt, state_dict = state, safe_serialization = True)+ dist.barrier()+ dst = native.shard_model(_model(False, 3, tmp, buffers = True), cfg)+ native.native_load_model_checkpoint(dst, ckpt)+ res["running_scale"] = dst.model.running_scale.tolist()+ res["route_bias"] = dst.model.layers[0].mlp.route_bias.tolist()+ elif case == "save_frozen":+ from safetensors.torch import load_file++ model = native.shard_model(_model(True, 1, tmp, resize = True, other_adapter = True), cfg)+ want = _full(model)+ _trainer(model, tmp).save_model(ckpt)+ dist.barrier()+ if rank == 0:+ saved = load_file(os.path.join(ckpt, "adapter_model.safetensors"))+ other_path = os.path.join(ckpt, "other", "adapter_model.safetensors")+ other = load_file(other_path) if os.path.isfile(other_path) else {}+ res["keys"] = sorted(saved)+ res["other_keys"] = sorted(other)++ def _match(saved_dict, adapter):+ worst = 0.0+ for k, v in saved_dict.items():+ name = k+ if "lora_" in k:+ name = k.replace(".weight", f".{adapter}.weight")+ if name not in want:+ return f"no model tensor for {k}"+ worst = max(worst, (v - want[name]).abs().max().item())+ return worst++ res["diff"] = _match(saved, "default")+ res["other_diff"] = _match(other, "other")+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ dist.destroy_process_group()+++def _run(case, tmp_path):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = True,+ start_method = "spawn",+ )+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("CKPT_RESULT", case, rank, r)+ assert "error" not in r, r["error"]+ return results++[email protected]("case", ["best_lora", "best_full"])+def test_load_best_model_uses_native_loader(case, tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run(case, tmp_path).items():+ assert "load_error" not in r, (rank, r)+ assert r["n"] > 0 and r["max_diff"] == 0.0, (rank, r)+++def test_full_save_non_writers_wait_for_the_write(tmp_path):+ pytest.importorskip("transformers")+ for rank, r in _run("full_save_wait", tmp_path).items():+ assert r["written_on_return"], (rank, r)+++def test_resume_restores_persistent_buffers(tmp_path):+ pytest.importorskip("transformers")+ for rank, r in _run("buffers", tmp_path).items():+ assert r["running_scale"] == [1.0] * 4, (rank, r)+ assert r["route_bias"] == [0.0, 1.0, 2.0, 3.0], (rank, r)+++def test_trainer_save_writes_frozen_peft_tensors(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ r = _run("save_frozen", tmp_path)[0]+ assert any("embed_tokens" in k for k in r["keys"]), r+ assert any("lm_head" in k for k in r["keys"]), r+ assert any("lora_A" in k for k in r["other_keys"]), r+ assert r["diff"] == 0.0 and r["other_diff"] == 0.0, r+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def test_bootstrap_uses_gloo_without_nccl(monkeypatch):+ import torch.distributed as dist++ native = _load_native()+ calls = {}+ monkeypatch.setattr(dist, "is_initialized", lambda: False)+ monkeypatch.setattr(dist, "is_nccl_available", lambda: False)+ monkeypatch.setattr(+ dist, "init_process_group", lambda backend = None, **kw: calls.update(b = backend)+ )+ monkeypatch.setattr(torch.cuda, "set_device", lambda device: None)+ native._ensure_process_group(torch.device("cuda", 0))+ assert calls["b"] == "gloo"+ monkeypatch.setattr(dist, "is_nccl_available", lambda: True)+ native._ensure_process_group(torch.device("cuda", 0))+ assert calls["b"] == "nccl"+ native._ensure_process_group(torch.device("cpu"))+ assert calls["b"] == "gloo"+++ "optim",+ [+ "lion_8bit",+ "lion_32bit",+ "paged_lion_8bit",+ "paged_lion_32bit",+ "ademamix",+ "ademamix_8bit",+ "paged_ademamix_32bit",+ "paged_ademamix_8bit",+ ],+)+def test_bnb_optimizers_without_torch_equivalent_are_refused(optim):+ native = _load_native()+ args = types.SimpleNamespace(optim = optim)+ with pytest.raises(ValueError, match = "adamw_torch"):+ native._swap_bnb_optimizer(args)+ assert args.optim == optim+++ "optim,target",+ [+ ("adamw_8bit", "adamw_torch"),+ ("paged_adamw_32bit", "adamw_torch"),+ ("rmsprop_bnb", "rmsprop"),+ ("rmsprop_bnb_8bit", "rmsprop"),+ ("rmsprop_bnb_32bit", "rmsprop"),+ ("adamw_torch", "adamw_torch"),+ ],+)+def test_bnb_optimizers_switch_to_torch(optim, target):+ native = _load_native()+ args = types.SimpleNamespace(optim = optim)+ native._swap_bnb_optimizer(args)+ value = str(getattr(args.optim, "value", args.optim))+ assert value in (target, target + "_fused"), value # fused only when CUDA is visible+ # Every bitsandbytes optimizer transformers knows is either switched or refused.+ try:+ from transformers.trainer_optimizer import _BITSANDBYTES_OPTIMIZERS+ except ImportError:+ return+ known = set(native._BNB_OPTIMS) | set(native._BNB_UNSUPPORTED)+ assert {str(o.value) for o in _BITSANDBYTES_OPTIMIZERS} <= knowndiff --git a/tests/test_fsdp2_native_trainer_fsdp_clip_gloo.py b/tests/test_fsdp2_native_trainer_fsdp_clip_gloo.pynew file mode 100644index 00000000000..0943116e0a0--- /dev/null+++ b/tests/test_fsdp2_native_trainer_fsdp_clip_gloo.py@@ -0,0 +1,316 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2, on a gloo CPU world of 2 where a process group is needed:++* TrainingArguments(fsdp = ...) is refused under an explicit UNSLOTH_FSDP2_BACKEND=native and wins+ (nothing sharded natively) without one;+* native_clip_grad_norm_ matches torch.nn.utils.clip_grad_norm_ for norm types 0, 1, 2 and inf;+* Mllama (vision tower run inline, cross-attention layers skipped without images) raises on every+ rank when images are on some ranks only, instead of hanging; all-image and all-text batches train;+* TrainingArguments(use_cpu = True) keeps a CPU mesh on a CUDA host."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import math # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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, _stub_unsloth_save # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402++NORM_TYPES = (0.0, 1.0, 2.0, math.inf)+++def _case_trainer_fsdp(native, tmp):+ _install_wrapped_trainer_init()+ from transformers import Trainer++ res = {}+ for backend in ("", "native"):+ os.environ["UNSLOTH_FSDP2_BACKEND"] = backend+ # Accelerator(fsdp_plugin = ...) exports ACCELERATE_USE_FSDP=true for the process+ # (accelerate/accelerator.py): each case starts from a plain torchrun env.+ os.environ.pop("ACCELERATE_USE_FSDP", None)+ model = _lora(1)+ try:+ targs = _targs(os.path.join(tmp, "out"), fsdp = "full_shard")+ trainer = Trainer(model = model, args = targs)+ # On CPU accelerate builds no FSDP state (MULTI_CPU), so is_fsdp_enabled stays False+ # here; the plugin arguments show the Trainer took the FSDP request.+ res[backend or "none"] = {+ "error": "",+ "fsdp_plugin": getattr(trainer.args, "fsdp_plugin_args", None) is not None+ or bool(getattr(trainer.args, "fsdp", None)),+ }+ except Exception as exc:+ res[backend or "none"] = {"error": f"{type(exc).__name__}: {str(exc)[:300]}"}+ res[backend or "none"]["sharded"] = native.is_native_fsdp2(model)+ os.environ.pop("UNSLOTH_FSDP2_BACKEND", None)+ return res+++class _Net(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.a = torch.nn.Linear(7, 9)+ self.b = torch.nn.Linear(9, 5)+ self.dead = torch.nn.Linear(9, 3) # its gradient is exactly zero+ self.rep = torch.nn.Parameter(torch.randn(5)) # replicated (ignored_params)++ def forward(self, x):+ h = torch.tanh(self.a(x))+ return (self.b(h) * self.rep).square().sum() + 0.0 * self.dead(h).sum()+++def _case_clip(native):+ import copy++ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard+ from torch.distributed.tensor import DTensor++ reference = _Net()+ model = copy.deepcopy(reference)+ mesh = init_device_mesh("cpu", (2,))+ for name in ("a", "b", "dead"):+ fully_shard(getattr(model, name), mesh = mesh)+ fully_shard(model, mesh = mesh, ignored_params = {model.rep})+ x = torch.randn(4, 7, generator = torch.Generator().manual_seed(1)) # same batch on both ranks+ res = {}+ for norm_type in NORM_TYPES:+ for m in (model, reference):+ m.zero_grad(set_to_none = True)+ m(x).backward()+ want = torch.nn.utils.clip_grad_norm_(+ list(reference.parameters()), 0.5, norm_type = norm_type+ )+ try:+ got = native.native_clip_grad_norm_(list(model.parameters()), 0.5, norm_type = norm_type)+ except Exception as exc:+ res[str(norm_type)] = {"error": f"{type(exc).__name__}: {exc}"}+ continue+ grad_diff = 0.0+ for (n, p), (_, q) in zip(model.named_parameters(), reference.named_parameters()):+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ grad_diff = max(grad_diff, (g - q.grad).abs().max().item())+ res[str(norm_type)] = {"got": float(got), "want": float(want), "grad_diff": grad_diff}+ return res+++def _mllama():+ from transformers import MllamaConfig, MllamaForConditionalGeneration++ config = MllamaConfig(+ vision_config = dict(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_global_layers = 1,+ attention_heads = 2,+ image_size = 28,+ patch_size = 14,+ max_num_tiles = 1,+ intermediate_layers_indices = [0],+ vision_output_dim = 32,+ supported_aspect_ratios = [[1, 1]],+ ),+ text_config = dict(+ vocab_size = 64,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ cross_attention_layers = [1],+ pad_token_id = 0,+ ),+ image_token_index = 63,+ )+ torch.manual_seed(0)+ return MllamaForConditionalGeneration(config)+++def _mllama_step(model, image):+ ids = torch.randint(1, 60, (1, 6), generator = torch.Generator().manual_seed(3))+ kwargs = dict(input_ids = ids, labels = ids)+ if image:+ kwargs.update(+ pixel_values = torch.randn(1, 1, 1, 3, 28, 28),+ aspect_ratio_ids = torch.tensor([[1]]),+ aspect_ratio_mask = torch.tensor([[[1]]]),+ cross_attention_mask = torch.ones(1, 6, 1, 1, dtype = torch.long),+ )+ model(**kwargs).loss.backward()+++def _case_mllama(native, rank):+ model = native.shard_model(_mllama(), native.FSDP2Config(param_dtype = torch.float32))+ res = {}+ for name, image in (("all_image", True), ("all_text", False), ("mixed", rank == 0)):+ try:+ _mllama_step(model, image)+ res[name] = "ok"+ except Exception as exc:+ res[name] = f"{type(exc).__name__}: {str(exc)[:300]}"+ return res+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "trainer_fsdp":+ res = _case_trainer_fsdp(native, tmp)+ elif case == "clip":+ res = _case_clip(native)+ elif case == "mllama":+ res = _case_mllama(native, rank)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("FSDP_CLIP_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_trainer_fsdp_args_refused_with_native_backend_and_win_without(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ for rank, r in _run("trainer_fsdp", tmp_path).items():+ native = r["native"]+ assert native["error"].startswith("RuntimeError"), (rank, r)+ assert "UNSLOTH_FSDP2_BACKEND=accelerate" in native["error"], (rank, r)+ assert native["sharded"] is False, (rank, r)+ # No explicit backend: the Trainer's FSDP request wins, the model is left to accelerate.+ assert r["none"]["sharded"] is False, (rank, r)+ assert r["none"]["error"] == "" and r["none"]["fsdp_plugin"], (rank, r)+++def test_native_clip_matches_torch_for_every_norm_type(tmp_path):+ for rank, r in _run("clip", tmp_path).items():+ for norm_type in NORM_TYPES:+ v = r[str(norm_type)]+ assert "error" not in v, (rank, norm_type, v)+ assert math.isclose(v["got"], v["want"], rel_tol = 1e-5, abs_tol = 1e-6), (+ rank,+ norm_type,+ v,+ )+ assert v["grad_diff"] < 1e-6, (rank, norm_type, v)+++def test_mllama_mixed_image_batch_raises_instead_of_hanging(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("transformers.models.mllama")+ for rank, r in _run("mllama", tmp_path, timeout = 150).items():+ assert r["all_image"] == "ok" and r["all_text"] == "ok", (rank, r)+ assert r["mixed"].startswith("RuntimeError") and "1 of 2 ranks" in r["mixed"], (rank, r)+++# ---- CPU unit checks (no process group) -------------------------------------------------------++[email protected]("flag", ["use_cpu", "no_cuda"])+def test_use_cpu_keeps_a_cpu_mesh_on_a_cuda_host(flag, monkeypatch):+ pytest.importorskip("transformers")+ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0", LOCAL_RANK = "1").items():+ monkeypatch.setenv(key, value)+ for key in ("ACCELERATE_USE_DEEPSPEED", "ACCELERATE_USE_CPU", "UNSLOTH_FSDP2_BACKEND"):+ monkeypatch.delenv(key, raising = False)+ native = _load_native()+ model = _tiny_llama()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ seen = {}++ def _record(device, *_):+ seen["device"] = device+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _record)+ # 4.57's `no_cuda` alone (its __post_init__ copies it to use_cpu; a namespace does not).+ args = types.SimpleNamespace(+ **{flag: True}, optim = "adamw_torch", save_on_each_node = False, fsdp = None+ )+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = args)+ assert seen["device"] == torch.device("cpu"), seen+ # Without it, the CUDA host shards onto the local GPU.+ args = types.SimpleNamespace(optim = "adamw_torch", save_on_each_node = False, fsdp = None)+ with pytest.raises(_Stop):+ native.native_fsdp2_trainer_setup(model = _tiny_llama(), phase = "pre", training_args = args)+ assert seen["device"] == torch.device("cuda", 1), seendiff --git a/tests/test_fsdp2_native_units.py b/tests/test_fsdp2_native_units.pynew file mode 100644index 00000000000..801d6391734--- /dev/null+++ b/tests/test_fsdp2_native_units.py@@ -0,0 +1,1004 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 (unsloth/models/fsdp2_native.py) on a gloo CPU world of 2: unit discovery for many+tiny architectures, then fully_shard per unit + root, and a forward / backward whose loss and+gradients match the unsharded model. Loads `fsdp2_native.py` on its own (no `import unsloth`), so+it runs without a GPU."""++import importlib.util+import os+import socket+import sys+import types++import pytest+import torch++# Spawned gloo ranks re-import this module: keep them on the CPU (deterministic on GPU hosts; CUDA+# reads the mask at its lazy first use, after this).+if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))++# (architecture, tiny repo, loader class, LoRA target modules or None)+ARCHS = [+ ("Llama", "hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM"),+ ("Qwen3", "trl-internal-testing/tiny-Qwen3ForCausalLM", "AutoModelForCausalLM"),+ ("Mistral", "hf-internal-testing/tiny-random-MistralForCausalLM", "AutoModelForCausalLM"),+ ("Gemma2", "trl-internal-testing/tiny-Gemma2ForCausalLM", "AutoModelForCausalLM"),+ ("Qwen3Moe", "trl-internal-testing/tiny-Qwen3MoeForCausalLM", "AutoModelForCausalLM"),+ ("GptOss", "trl-internal-testing/tiny-GptOssForCausalLM", "AutoModelForCausalLM"),+ ("Qwen3Next", "hf-internal-testing/tiny-random-Qwen3NextForCausalLM", "AutoModelForCausalLM"),+ (+ "Gemma3VL",+ "trl-internal-testing/tiny-Gemma3ForConditionalGeneration",+ "AutoModelForImageTextToText",+ ),+ (+ "Qwen2_5_VL",+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",+ "AutoModelForImageTextToText",+ ),+ (+ "Qwen3VL",+ "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",+ "AutoModelForImageTextToText",+ ),+ (+ "Gemma4",+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",+ "AutoModelForImageTextToText",+ ),+ (+ "Qwen3_5",+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration",+ "AutoModelForImageTextToText",+ ),+]+++def _load_native():+ """fsdp2_native.py without importing the unsloth package (which needs a GPU)."""+ pkg = types.ModuleType("unsloth")+ pkg.__path__ = [os.path.join(REPO, "unsloth")]+ models = types.ModuleType("unsloth.models")+ models.__path__ = [os.path.join(REPO, "unsloth", "models")]+ sys.modules.setdefault("unsloth", pkg)+ sys.modules.setdefault("unsloth.models", models)+ for name, path in (+ ("unsloth.fsdp2_launch", os.path.join(REPO, "unsloth", "fsdp2_launch.py")),+ ("unsloth.models.fsdp2_native", os.path.join(REPO, "unsloth", "models", "fsdp2_native.py")),+ ):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return sys.modules["unsloth.models.fsdp2_native"]+++def _build(repo, loader):+ import transformers++ config = transformers.AutoConfig.from_pretrained(repo)+ torch.manual_seed(0)+ cls = getattr(transformers, loader)+ model = cls.from_config(config, torch_dtype = torch.float32)+ return model.eval()+++def _expected_blocks(model):+ """Every ModuleList child whose class is a decoder / encoder block by name."""+ n = 0+ for module in model.modules():+ if isinstance(module, torch.nn.ModuleList):+ kids = list(module.children())+ if kids and all(+ any(k in type(c).__name__ for k in ("Layer", "Block"))+ and "Expert" not in type(c).__name__+ for c in kids+ ):+ n += len(kids)+ return n+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _batch(model, seed = 1):+ config = getattr(model.config, "text_config", None) or model.config+ vocab = config.vocab_size+ g = torch.Generator().manual_seed(seed)+ ids = torch.randint(3, min(vocab, 1000), (2, 16), generator = g)+ return {"input_ids": ids, "labels": ids.clone(), "use_cache": False}+++def _worker(rank, world, port, repo, loader, lora, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ assert native.native_fsdp2_requested()+ ref = _build(repo, loader)+ model = _build(repo, loader)+ if lora:+ from peft import LoraConfig, get_peft_model++ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear")+ torch.manual_seed(2)+ ref = get_peft_model(ref, cfg)+ torch.manual_seed(2)+ model = get_peft_model(model, cfg)+ # lora_B starts at zero, which would hide a wrong base weight gather in the gradients.+ with torch.no_grad():+ for (n1, p1), (n2, p2) in zip(ref.named_parameters(), model.named_parameters()):+ if "lora_B" in n1:+ p1.normal_(0, 0.02, generator = torch.Generator().manual_seed(len(n1)))+ p2.copy_(p1)+ units = native.find_shard_units(model)+ expected = _expected_blocks(model)+ names = {type(u).__name__ for u in units}+ batch = _batch(model)+ ref_loss = ref(**batch).loss+ ref_loss.backward()+ ref_grads = {n: p.grad.clone() for n, p in ref.named_parameters() if p.grad is not None}++ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ assert native.is_native_fsdp2(model)+ assert native.shard_model(model) is model # idempotent+ loss = model(**batch).loss+ loss.backward()+ from torch.distributed.tensor import DTensor++ worst = 0.0+ missing = []+ n_dtensor = 0+ zero_grads = 0+ for n, p in model.named_parameters():+ if isinstance(p, DTensor):+ n_dtensor += 1+ if p.grad is None:+ if n in ref_grads:+ missing.append(n)+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ if n not in ref_grads:+ # Only fsdp2_vision's dummy image (output times 0) gives a text-only batch vision grads.+ assert float(g.abs().max()) == 0.0, n+ zero_grads += 1+ continue+ r = ref_grads[n]+ worst = max(worst, (g - r).abs().max().item() / (r.abs().max().item() + 1e-8))+ n_params = sum(1 for _ in model.named_parameters())+ result = {+ "units": len(units),+ "expected": expected,+ "unit_classes": sorted(names),+ "loss": loss.item(),+ "ref_loss": ref_loss.item(),+ "worst_rel_grad": worst,+ "missing": missing,+ "dtensor_params": n_dtensor,+ "params": n_params,+ "n_grads": len(ref_grads),+ "extra_units": len(getattr(model, "_unsloth_fsdp2_extra_units", [])),+ "zero_grads": zero_grads,+ }+ if loader == "AutoModelForImageTextToText":+ import importlib++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ plan = vision._vision_plan(model)+ # A dummy image this family can run (every required get_image_features argument given).+ result["dummy_viable"] = plan is not None and plan[2] is not None+ # generate after a backward: root-held weights must be gathered (PeftModel.generate skips root hooks).+ if loader == "AutoModelForCausalLM":+ prompt = batch["input_ids"][:1, :6]+ try:+ with torch.no_grad():+ ref_tokens = ref.generate(input_ids = prompt, max_new_tokens = 4, do_sample = False)+ except (+ Exception+ ): # transformers cannot generate this tiny model at all (Qwen3-Next cache)+ ref_tokens = None+ if ref_tokens is not None:+ with torch.no_grad():+ tokens = model.generate(input_ids = prompt, max_new_tokens = 4, do_sample = False)+ result["generate_equal"] = bool(torch.equal(ref_tokens, tokens))+ result["after_generate_sharded"] = all(+ isinstance(p, DTensor) for p in model.parameters()+ )+ if rank == 0:+ import json+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()+++def _run(repo, loader, lora, tmp_path):+ import torch.multiprocessing as mp++ out = str(tmp_path / "result.json")+ mp.spawn(_worker, args = (2, _free_port(), repo, loader, lora, out), nprocs = 2, join = True)+ import json++ with open(out, encoding = "utf-8") as f:+ return json.load(f)++[email protected]("lora", [False, True], ids = ["full", "lora"])[email protected]("arch,repo,loader", ARCHS, ids = [a[0] for a in ARCHS])+def test_native_fsdp2_units_and_grads(arch, repo, loader, lora, tmp_path):+ try:+ import transformers+ transformers.AutoConfig.from_pretrained(repo)+ except Exception as exc: # unknown architecture in this transformers+ pytest.skip(f"{repo}: {type(exc).__name__}: {exc}")+ r = _run(repo, loader, lora, tmp_path)+ assert r["units"] >= max(1, r["expected"]), r+ assert r["dtensor_params"] == r["params"], r # root covers every leftover parameter+ assert not r["missing"], r+ assert abs(r["loss"] - r["ref_loss"]) <= 1e-5 * max(1.0, abs(r["ref_loss"])), r+ assert r["worst_rel_grad"] < 1e-4, r+ if "generate_equal" in r:+ assert r["generate_equal"] and r["after_generate_sharded"], r+ if arch == "Gemma4":+ assert r["extra_units"] >= 1, r # embed_tokens_per_layer gets its own unit+ if loader == "AutoModelForImageTextToText":+ # Text-only on every rank: the presence agreement sees no mixed batch, so no dummy runs and+ # the vision tower gets no gradient anywhere (matching collectives). The dummy for this family+ # can be built (it runs when another rank has images: test_fsdp2_native_vision_gloo).+ assert r["zero_grads"] == 0, r+ assert r["dummy_viable"], r+++def test_native_selection_env(monkeypatch):+ native = _load_native()+ monkeypatch.setenv("WORLD_SIZE", "2")+ monkeypatch.delenv("ACCELERATE_USE_FSDP", raising = False)+ monkeypatch.delenv("UNSLOTH_FSDP2_BACKEND", raising = False)+ monkeypatch.setenv("UNSLOTH_FSDP2", "0")+ assert not native.native_fsdp2_requested()+ monkeypatch.setenv("UNSLOTH_FSDP2", "1")+ assert native.native_fsdp2_requested()+ monkeypatch.setenv("UNSLOTH_FSDP2", "native")+ assert native.native_fsdp2_requested()+ monkeypatch.setenv("UNSLOTH_FSDP2_BACKEND", "accelerate")+ assert not native.native_fsdp2_requested()+ monkeypatch.delenv("UNSLOTH_FSDP2_BACKEND")+ monkeypatch.setenv("ACCELERATE_USE_FSDP", "true")+ assert not native.native_fsdp2_requested()+ monkeypatch.setenv("UNSLOTH_FSDP2_BACKEND", "native")+ assert native.native_fsdp2_requested()+ monkeypatch.setenv("WORLD_SIZE", "1")+ assert not native.native_fsdp2_requested()+ launch = sys.modules["unsloth.fsdp2_launch"]+ monkeypatch.setenv("WORLD_SIZE", "2")+ monkeypatch.delenv("ACCELERATE_USE_FSDP")+ assert launch.apply_unsloth_fsdp2_launch_env() is False+ assert "ACCELERATE_USE_FSDP" not in os.environ+++def test_find_units_jamba_like_hybrid():+ native = _load_native()++ class Attn(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(4, 4)++ class Mamba(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(4, 4)++ class M(torch.nn.Module):+ _no_split_modules = ["Attn", "Mamba"]++ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(10, 4)+ self.layers = torch.nn.ModuleList([Attn(), Mamba(), Attn()])+ self.heads = torch.nn.ModuleList([torch.nn.Linear(4, 4), torch.nn.Linear(4, 4)])++ m = M()+ units = native.find_shard_units(m)+ assert [type(u).__name__ for u in units] == ["Attn", "Mamba", "Attn"]+++def _mixed_worker(+ rank,+ world,+ port,+ out,+ lora = False,+ average = True,+):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import json++ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ from torch.distributed.tensor import DTensor++ def build():+ m = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ m = m.to(torch.bfloat16)+ for name, p in m.named_parameters():+ if "norm" in name: # Unsloth full finetuning: float32 norms, 16-bit linears+ p.data = p.data.float()+ if lora: # frozen float32 norms next to frozen bf16 linears and bf16 adapters+ from peft import LoraConfig, get_peft_model++ torch.manual_seed(2)+ m = get_peft_model(m, LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear"))+ with torch.no_grad():+ for n, p in m.named_parameters():+ if "lora_" in n:+ p.data = p.data.to(torch.bfloat16)+ if "lora_B" in n:+ p.normal_(0, 0.02, generator = torch.Generator().manual_seed(len(n)))+ return m.train()++ ref, model = build(), build()+ batch = _batch(model)+ # float32 norm outputs meet bf16 linears: autocast, as the Trainer runs one GPU.+ amp = lambda: torch.autocast("cpu", dtype = torch.bfloat16)+ with amp():+ ref_loss = ref(**batch).loss+ ref_loss.backward()+ ref_grads = {+ n: p.grad.float().clone() for n, p in ref.named_parameters() if p.grad is not None+ }+ if not average: # negative control: no gradient averaging for replicated parameters+ import importlib+ importlib.import_module(+ "unsloth.models.fsdp2_save"+ ).reduce_unsharded_trainable_grads = lambda m: []+ native.shard_model(model, native.FSDP2Config())+ norms_plain = all(+ not isinstance(p, DTensor) and p.dtype == torch.float32+ for n, p in model.named_parameters()+ if "norm" in n+ )+ linears_sharded = all(+ isinstance(p, DTensor) and p.dtype == torch.bfloat16+ for n, p in model.named_parameters()+ if "norm" not in n+ )+ with amp():+ loss = model(**batch).loss+ loss.backward()+ worst = {}+ for n, p in model.named_parameters():+ if p.grad is None:+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ r = ref_grads[n]+ worst[n] = (g.float() - r).abs().max().item() / (r.abs().max().item() + 1e-8)+ # Weights read outside the blocks' forwards (decode loops, generate): gathered while inside.+ inner = model.get_base_model() if lora else model+ ref_inner = ref.get_base_model() if lora else ref+ with native.native_fsdp2_unsharded(model):+ inside_plain = not any(isinstance(p, DTensor) for p in model.parameters())+ with torch.no_grad(), amp():+ logits = inner.model.layers[0].mlp.down_proj.weight.float().sum().item()+ with torch.no_grad(), amp():+ ref_w = ref_inner.model.layers[0].mlp.down_proj.weight.float().sum().item()+ after_sharded = isinstance(inner.model.layers[0].mlp.down_proj.weight, DTensor)+ opt = torch.optim.AdamW(+ [p for p in model.parameters() if p.requires_grad], lr = 1e-3, foreach = True+ )+ splits = native._split_mixed_param_groups(opt)+ opt.step()+ clip = native.native_clip_grad_norm_(list(model.parameters()), 1e9)+ ref_norm = torch.sqrt(sum((g**2).sum() for g in ref_grads.values())).item()+ # Replicated parameters must not drift across ranks: different data per rank, then a step.+ rep = [p for p in model.parameters() if p.requires_grad and not isinstance(p, DTensor)]+ before = [p.detach().clone() for p in rep]+ opt.zero_grad()+ with amp():+ loss2 = model(**_batch(model, seed = 10 + rank)).loss+ loss2.backward()+ opt.step()+ flat = torch.cat([p.detach().float().flatten() for p in rep]) if rep else torch.zeros(1)+ gathered = [torch.zeros_like(flat) for _ in range(world)]+ dist.all_gather(gathered, flat)+ drift = (gathered[0] - gathered[1]).abs().max().item()+ moved = any((p.detach() != b).any().item() for p, b in zip(rep, before))+ result = {+ "norms_plain": norms_plain,+ "linears_sharded": linears_sharded,+ "worst": max(worst.values()),+ "worst_name": max(worst, key = worst.get),+ "splits": splits,+ "clip": float(clip),+ "ref_norm": ref_norm,+ "replicated": getattr(model, "_unsloth_fsdp2_replicated", None),+ "drift": drift,+ "moved": moved,+ "inside_plain": inside_plain,+ "after_sharded": after_sharded,+ "direct_read_diff": abs(logits - ref_w),+ }+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()+++def test_mixed_dtype_full_ft_keeps_norms_replicated(tmp_path):+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "mixed.json")+ mp.spawn(_mixed_worker, args = (2, _free_port(), out), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r["norms_plain"] and r["linears_sharded"], r+ assert r["replicated"] and r["replicated"] > 0, r+ assert r["splits"] == 1, r+ assert r["moved"] and r["drift"] == 0.0, r # averaged gradients: replicas stay identical+ _check_unsharded(r)+++def _check_unsharded(r):+ assert r["inside_plain"] and r["after_sharded"], r+ assert r["direct_read_diff"] < 1e-3, r+ assert r["worst"] < 2e-2, r # bf16 compute, float32 reduce+ assert abs(r["clip"] - r["ref_norm"]) <= 2e-2 * r["ref_norm"], r+++def test_lora_frozen_fp32_norms_stay_replicated(tmp_path):+ """LoRA: frozen float32 norms next to bf16 weights are not cast to bf16 by the gather (1-GPU numerics)."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "lora_mixed.json")+ mp.spawn(_mixed_worker, args = (2, _free_port(), out, True), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r["norms_plain"] and r["linears_sharded"], r+ assert r["splits"] == 0, r # trainable adapters are all sharded+ _check_unsharded(r)+++def test_default_path_untouched():+ """No flag: no torch.distributed.fsdp import, no accelerate / Trainer patch, the model is returned as is."""+ import subprocess++ code = f"""+import os, sys+os.environ.pop("UNSLOTH_FSDP2", None)+os.environ["WORLD_SIZE"] = "2"+sys.path.insert(0, {os.path.dirname(os.path.abspath(__file__))!r})+import test_fsdp2_native_units as t+native = t._load_native()+import torch+m = torch.nn.Linear(2, 2)+assert native.native_fsdp2_trainer_setup(model = m, phase = "pre") is m+assert native.native_fsdp2_trainer_setup(trainer = object(), phase = "post") is None+assert "torch.distributed.fsdp" not in sys.modules, "fsdp imported on the default path"+import accelerate, transformers+assert not getattr(accelerate.Accelerator, native._PATCHED, False)+assert not getattr(transformers.Trainer, native._PATCHED, False)+assert not native.is_native_fsdp2(m)+print("DEFAULT_OK")+"""+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 300)+ assert "DEFAULT_OK" in out.stdout, out.stdout[-2000:] + out.stderr[-3000:]+++def _knobs_worker(rank, world, port, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import json++ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ from peft import LoraConfig, get_peft_model+ from torch.distributed.tensor import DTensor++ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear")+ models = []+ for _ in range(2):+ m = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ torch.manual_seed(2)+ m = get_peft_model(m, cfg)+ with torch.no_grad():+ for n, p in m.named_parameters():+ if "lora_B" in n:+ p.normal_(0, 0.02, generator = torch.Generator().manual_seed(len(n)))+ models.append(m)+ ref, model = models+ batch = _batch(model)+ ref(**batch).loss.backward()+ ref_grads = {n: p.grad.clone() for n, p in ref.named_parameters() if p.grad is not None}+ calls = []+ config = native.FSDP2Config(+ param_dtype = torch.float32,+ shard_frozen = False,+ forward_prefetch = 1,+ backward_prefetch = 2,+ reshard_last_block = True,+ unit_reshard_after_forward = lambda i, u: calls.append(i) or (False if i == 0 else None),+ )+ native.shard_model(model, config)+ frozen_plain = all(+ not isinstance(p, DTensor) for p in model.parameters() if not p.requires_grad+ )+ lora_sharded = all(isinstance(p, DTensor) for p in model.parameters() if p.requires_grad)+ units = model._unsloth_fsdp2_units+ reshards = [u._unsloth_reshard_after_forward for u in units]+ model(**batch).loss.backward()+ worst = 0.0+ for n, p in model.named_parameters():+ if p.grad is None:+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ worst = max(+ worst,+ (g - ref_grads[n]).abs().max().item() / (ref_grads[n].abs().max().item() + 1e-8),+ )+ result = {+ "frozen_plain": frozen_plain,+ "lora_sharded": lora_sharded,+ "calls": calls,+ "reshards": reshards,+ "worst": worst,+ "n_units": len(units),+ }+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()+++def test_perf_knobs_shard_frozen_prefetch(tmp_path):+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "knobs.json")+ mp.spawn(_knobs_worker, args = (2, _free_port(), out), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r["frozen_plain"] and r["lora_sharded"], r+ assert r["calls"] == list(range(r["n_units"])), r+ assert r["reshards"][0] is False and r["reshards"][-1] is True, r+ assert r["worst"] < 1e-4, r+++def _skip_worker(rank, world, port, out, guard):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import json++ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ if not guard:+ native._patch_accumulated_grad_guard = lambda: False++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(8, 8)++ def forward(self, x):+ return self.proj(x)++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = torch.nn.ModuleList([Block(), Block()])+ self.tower = torch.nn.ModuleList([Block()]) # skipped on "text" batches+ self.head = torch.nn.Linear(8, 1)++ def forward(self, x, use_tower):+ if use_tower:+ x = self.tower[0](x)+ for layer in self.layers:+ x = layer(x)+ return self.head(x).sum()++ torch.manual_seed(0)+ model = Model().to(torch.bfloat16)+ native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.bfloat16, reduce_dtype = torch.float32)+ )+ x = torch.randn(4, 8, dtype = torch.bfloat16)+ error = None+ try:+ model.set_requires_gradient_sync(False)+ model(x, use_tower = False).backward() # micro-step 1: tower never unsharded+ model.set_requires_gradient_sync(True)+ model(x, use_tower = True).backward()+ except AttributeError as exc:+ error = str(exc)+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump({"error": error}, f)+ finally:+ dist.destroy_process_group()++[email protected]("guard", [False, True], ids = ["unguarded", "guarded"])+def test_accumulation_with_skipped_unit(guard, tmp_path):+ """float32 reduce + no-sync accumulation + a unit skipped in a micro-step: torch raises without the guard."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "skip.json")+ mp.spawn(_skip_worker, args = (2, _free_port(), out, guard), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ if guard:+ assert r["error"] is None, r+ else:+ # Documents the torch bug the guard covers (fixed upstream with a getattr; then both pass).+ if r["error"] is None:+ pytest.skip("this torch already guards _unsharded_param")+ assert "_unsharded_param" in r["error"], r+++def test_replicated_params_drift_without_averaging(tmp_path):+ """Negative control for the drift check: without the gradient averaging hook the replicas diverge."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "noavg.json")+ mp.spawn(_mixed_worker, args = (2, _free_port(), out, False, False), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r["moved"] and r["drift"] > 0.0, r+++def test_find_units_real_jamba_and_peft_linear_lists():+ """R5: mixed-class decoder lists (real Jamba) are units without `_no_split_modules` help; R6: a list of+ PEFT-wrapped Linear layers (Gemma3n altup-like) is not."""+ import transformers+ from peft import LoraConfig, get_peft_model++ native = _load_native()+ cfg = transformers.JambaConfig(+ num_hidden_layers = 4,+ hidden_size = 64,+ intermediate_size = 128,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ vocab_size = 256,+ attn_layer_period = 2,+ attn_layer_offset = 1,+ expert_layer_period = 2,+ expert_layer_offset = 1,+ num_experts = 2,+ mamba_d_state = 8,+ mamba_dt_rank = 8,+ use_mamba_kernels = False,+ )+ m = transformers.JambaForCausalLM(cfg)+ m._no_split_modules = []+ for module in m.modules():+ module._no_split_modules = []+ units = native.find_shard_units(m)+ assert [type(u).__name__ for u in units] == [+ "JambaMambaDecoderLayer",+ "JambaAttentionDecoderLayer",+ ] * 2++ base = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ base.extra_proj = torch.nn.ModuleList([torch.nn.Linear(4, 4) for _ in range(3)])+ peft_model = get_peft_model(base, LoraConfig(r = 4, target_modules = "all-linear"))+ names = {id(mod): n for n, mod in peft_model.named_modules()}+ found = [names[id(u)] for u in native.find_shard_units(peft_model)]+ assert found == ["base_model.model.model.layers.0", "base_model.model.model.layers.1"], found+++def test_no_unit_inside_a_compiled_block():+ """torch.compile rule: no FSDP unit nested in a (compiled) decoder block. find_shard_units only picks+ whole blocks; an explicit unit inside a block (an MLP, an expert, a LoRA Linear) is refused before any+ fully_shard or process group."""+ native = _load_native()+ model = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ layers = model.model.layers+ cls = type(layers[0])+ original = cls.forward++ def compiled_forward(self, *args, **kwargs):+ return original(self, *args, **kwargs)++ compiled_forward._unsloth_block_compiled = True # what _block_compile marks+ cls.forward = compiled_forward+ try:+ units = native.find_shard_units(model)+ assert [id(u) for u in units] == [id(layer) for layer in layers]+ assert native.check_shard_units(model, units)+ for bad in ([layers[0].mlp], [layers[0], layers[0].self_attn.q_proj]):+ with pytest.raises(RuntimeError, match = "inside the"):+ native.check_shard_units(model, bad)+ with pytest.raises(RuntimeError, match = "inside the"):+ native.shard_model(model, native.FSDP2Config(units = [layers[1].mlp]))+ assert not getattr(model, "_unsloth_fsdp2_native", False)+ finally:+ cls.forward = original+ # Without the compile marker a block is still a block (ModuleList of repeated blocks).+ with pytest.raises(RuntimeError, match = "decoder block"):+ native.check_shard_units(model, [layers[0].mlp])+++def _fit_worker(rank, world, port, out, units_mode):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ UNSLOTH_FSDP2_TRAINABLE_UNITS = units_mode,+ )+ import json++ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ from peft import LoraConfig, get_peft_model+ from torch.distributed.tensor import DTensor++ cfg = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear")+ models = []+ for _ in range(2):+ m = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ torch.manual_seed(2)+ m = get_peft_model(m, cfg)+ with torch.no_grad():+ for n, p in m.named_parameters():+ if "lora_B" in n:+ p.normal_(0, 0.02, generator = torch.Generator().manual_seed(len(n)))+ models.append(m)+ ref, model = models+ # Each rank its own micro batch; the reference averages both (what the reduce-scatter gives).+ batches = [_batch(model, seed = 1 + r) for r in range(world)]+ for b in batches:+ (ref(**b).loss / world).backward()+ ref_grads = {n: p.grad.clone() for n, p in ref.named_parameters() if p.grad is not None}+ # Default config, forced fit layout (CPU has no device memory to size it).+ native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32, fit_layout = True))+ layout = model._unsloth_fsdp2_layout+ frozen_plain = all(+ not isinstance(p, DTensor) for p in model.parameters() if not p.requires_grad+ )+ lora_sharded = all(isinstance(p, DTensor) for p in model.parameters() if p.requires_grad)+ model(**batches[rank]).loss.backward()+ worst = 0.0+ for n, p in model.named_parameters():+ if not p.requires_grad:+ assert p.grad is None, n+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ worst = max(+ worst,+ (g - ref_grads[n]).abs().max().item() / (ref_grads[n].abs().max().item() + 1e-8),+ )+ result = {+ "layout": layout,+ "frozen_plain": frozen_plain,+ "lora_sharded": lora_sharded,+ "n_units": len(model._unsloth_fsdp2_units),+ "root_only": model._unsloth_fsdp2_root_only,+ "reshards": [u._unsloth_reshard_after_forward for u in model._unsloth_fsdp2_units],+ "worst": worst,+ }+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()++[email protected]("units_mode", ["root", "blocks"])+def test_fit_layout_through_shard_model(units_mode, tmp_path):+ """shard_model with the fit layout (fsdp2_perf): frozen base weights replicated (plain tensors, no+ grad), LoRA sharded, one root unit or per-block units kept gathered (last block too), gradients equal+ the averaged unsharded reference."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "fit.json")+ mp.spawn(_fit_worker, args = (2, _free_port(), out, units_mode), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r["layout"]["fits"] and r["layout"]["replicate_frozen"], r+ assert r["layout"]["reshard_after_forward"] is False, r+ assert r["frozen_plain"] and r["lora_sharded"], r+ if units_mode == "root":+ assert r["root_only"] and r["n_units"] == 0, r+ else:+ assert not r["root_only"] and r["n_units"] > 1, r+ assert all(x is False for x in r["reshards"]), r+ assert r["worst"] < 1e-4, r+++def _gather_dtype_worker(rank, world, port, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ UNSLOTH_FSDP2_TRAINABLE_UNITS = "root",+ )+ import json++ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ from peft import LoraConfig, get_peft_model++ result = {}+ for name, fit in (("fit", True), ("sharded", False)):+ m = _build("hf-internal-testing/tiny-random-LlamaForCausalLM", "AutoModelForCausalLM")+ m = m.to(torch.bfloat16)+ # PEFT keeps the adapters in float32 (autocast_adapter_dtype), as Unsloth's LoRA does.+ m = get_peft_model(m, LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear"))+ assert {p.dtype for p in m.parameters() if p.requires_grad} == {torch.float32}+ native.shard_model(m, native.FSDP2Config(fit_layout = fit))+ result[name] = str(m._unsloth_fsdp2_mp_policy.param_dtype)+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()+++def test_fit_layout_gathers_float32_masters_as_stored(tmp_path):+ """bf16 base + float32 LoRA: the fit layout (FSDP2 manages only trainable params) gathers the float32+ masters as they are (one GPU keeps them float32 and autocast casts per op); the per-block layout keeps+ the contract's bf16 gather."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / "gather.json")+ mp.spawn(_gather_dtype_worker, args = (2, _free_port(), out), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ assert r == {"fit": "None", "sharded": "torch.bfloat16"}, r+++def _recompute_cast_worker(rank, world, init_file, out, patched):+ os.environ.update(+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import json++ import torch.distributed as dist+ from torch.distributed.fsdp._fully_shard._fsdp_common import TrainingState+ from torch.distributed.fsdp._fully_shard._fsdp_state import FSDPState++ # A file store, not a TCP port: parallel test workers cannot race for the same port.+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = world)+ try:+ native = _load_native()+ current = FSDPState._pre_forward+ if not native._recompute_skips_input_cast(current):+ # Emulate torch < 2.13 on a newer torch: the recompute branch returns the inputs uncast.+ def old_pre_forward(self, module, args, kwargs):+ if self._training_state == TrainingState.PRE_BACKWARD:+ current(self, module, args, kwargs)+ return args, kwargs+ return current(self, module, args, kwargs)++ FSDPState._pre_forward = old_pre_forward+ if not patched:+ native._patch_recompute_input_cast = lambda: False++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.lin = torch.nn.Linear(8, 8, bias = False)++ def forward(self, x):+ # Like Unsloth's LoRA / 4-bit matmul: the weight is cast to the input dtype and saved.+ return x + torch.tanh(x @ self.lin.weight.t().to(x.dtype))++ class Toy(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = torch.nn.ModuleList(Block() for _ in range(2))++ def forward(self, x):+ x = (+ x.float()+ ) # float32 activations inside the model (the root's pre-forward cast them)+ for layer in self.layers:+ x = torch.utils.checkpoint.checkpoint(layer, x, use_reentrant = False)+ return x.float().pow(2).mean()++ torch.manual_seed(0)+ model = Toy()+ native.shard_model(+ model,+ native.FSDP2Config(+ param_dtype = torch.bfloat16, units = list(model.layers), fit_layout = False+ ),+ )+ x = torch.randn(4, 8, generator = torch.Generator().manual_seed(rank)) # float32 inputs+ error = None+ try:+ model(x).backward()+ except Exception as exc: # CheckpointError: bf16 saved, float32 recomputed+ error = f"{type(exc).__name__}: {str(exc)[:200]}"+ if rank == 0:+ with open(out, "w", encoding = "utf-8") as f:+ json.dump({"error": error}, f)+ finally:+ dist.destroy_process_group()++[email protected]("patched", [False, True])+def test_recompute_sees_the_cast_inputs(patched, tmp_path):+ """torch < 2.13 skipped FSDP2's forward-input cast on activation-checkpoint recompute, so a unit fed+ float32 inputs with bf16 gathered weights saved bf16 tensors in forward and float32 ones in the+ recompute: CheckpointError (Kaggle T4, torch 2.10). The backport casts there too."""+ import json++ import torch.multiprocessing as mp++ out = str(tmp_path / f"recompute_{patched}.json")+ init_file = str(tmp_path / f"recompute_{patched}.store")+ mp.spawn(_recompute_cast_worker, args = (2, init_file, out, patched), nprocs = 2, join = True)+ r = json.load(open(out, encoding = "utf-8"))+ if patched:+ assert r["error"] is None, r+ else:+ assert r["error"] and "Checkpoint" in r["error"], rdiff --git a/tests/test_fsdp2_native_vision_gloo.py b/tests/test_fsdp2_native_vision_gloo.pynew file mode 100644index 00000000000..80da3f6fcd5--- /dev/null+++ b/tests/test_fsdp2_native_vision_gloo.py@@ -0,0 +1,245 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2, mixed image / text micro-batches (gloo CPU world of 2): rank 0 trains on an image ++text batch, rank 1 on text only. Without the dummy vision pass (fsdp2_vision) the vision units+all-gather on rank 0 only and the run fails or times out, and with the vision LoRA held by the root+(frozen base replicated) the reduce-scatter sets differ. With it, two steps complete and the gradients+equal the unsharded model's on both micro-batches, averaged. Loads fsdp2_native.py on its own (no+`import unsloth`), so it runs without a GPU."""++import datetime+import importlib.util+import json+import os+import socket+import sys+import types++import pytest+import torch++# Spawned gloo ranks re-import this module: keep them on the CPU (deterministic on GPU hosts; CUDA+# reads the mask at its lazy first use, after this).+if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+TINY = "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration"+++def _load_native():+ pkg = types.ModuleType("unsloth")+ pkg.__path__ = [os.path.join(REPO, "unsloth")]+ models = types.ModuleType("unsloth.models")+ models.__path__ = [os.path.join(REPO, "unsloth", "models")]+ sys.modules.setdefault("unsloth", pkg)+ sys.modules.setdefault("unsloth.models", models)+ for name, path in (+ ("unsloth.fsdp2_launch", os.path.join(REPO, "unsloth", "fsdp2_launch.py")),+ ("unsloth.models.fsdp2_native", os.path.join(REPO, "unsloth", "models", "fsdp2_native.py")),+ ("unsloth.models.fsdp2_vision", os.path.join(REPO, "unsloth", "models", "fsdp2_vision.py")),+ ):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return sys.modules["unsloth.models.fsdp2_native"], sys.modules["unsloth.models.fsdp2_vision"]+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _build(lora):+ import transformers++ config = transformers.AutoConfig.from_pretrained(TINY)+ torch.manual_seed(0)+ model = transformers.AutoModelForImageTextToText.from_config(config, torch_dtype = torch.float32)+ if lora:+ from peft import LoraConfig, get_peft_model++ torch.manual_seed(2)+ model = get_peft_model(model, LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear"))+ with torch.no_grad():+ for n, p in model.named_parameters():+ if "lora_B" in n:+ p.normal_(0, 0.02, generator = torch.Generator().manual_seed(len(n)))+ return model.train()+++def _batches(model):+ config = model.config+ vision = config.vision_config+ m = vision.spatial_merge_size+ grid = torch.tensor([[1, 2 * m, 2 * m]])+ n_patches = int(grid.prod())+ n_tokens = n_patches // (m * m)+ patch_dim = vision.in_channels * vision.temporal_patch_size * vision.patch_size**2+ g = torch.Generator().manual_seed(1)+ text = lambda n: torch.randint(3, 1000, (n,), generator = g) # noqa: E731+ image_ids = torch.cat(+ [+ text(4),+ torch.tensor([config.vision_start_token_id]),+ torch.full((n_tokens,), config.image_token_id),+ torch.tensor([config.vision_end_token_id]),+ text(10 - n_tokens),+ ]+ )[None]+ image = {+ "input_ids": image_ids,+ "labels": image_ids.clone(),+ "pixel_values": torch.randn(n_patches, patch_dim, generator = g),+ "image_grid_thw": grid,+ "use_cache": False,+ }+ text_ids = text(image_ids.shape[1])[None]+ plain = {"input_ids": text_ids, "labels": text_ids.clone(), "use_cache": False}+ return [image, plain]+++def _worker(rank, world, port, lora, root_only, dummy, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ result = {"rank": rank}+ try:+ native, vision = _load_native()+ if not dummy:+ vision.install_vision_dummy = lambda model: None+ ref = _build(lora)+ model = _build(lora)+ batches = _batches(model)+ config = native.FSDP2Config(param_dtype = torch.float32)+ if root_only:+ # The fit layout with LoRA: no block units, frozen base replicated, adapters in the root.+ config = native.FSDP2Config(param_dtype = torch.float32, units = [], shard_frozen = False)+ native.shard_model(model, config)+ result["installed"] = any(getattr(m, vision._INSTALLED, False) for m in model.modules())+ from torch.distributed.tensor import DTensor++ ref_opt = torch.optim.SGD([p for p in ref.parameters() if p.requires_grad], lr = 0.5)+ opt = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr = 0.5)+ worst = 0.0+ compared = 0+ losses = []+ for step in range(2):+ ref_opt.zero_grad(set_to_none = True)+ for b in batches:+ (ref(**b).loss / len(batches)).backward()+ ref_grads = {n: p.grad for n, p in ref.named_parameters() if p.grad is not None}+ ref_opt.step()+ opt.zero_grad(set_to_none = True)+ loss = model(**batches[rank]).loss+ loss.backward()+ losses.append(loss.item())+ for n, p in model.named_parameters():+ if n not in ref_grads:+ continue+ if p.grad is None:+ worst = float("inf")+ result.setdefault("missing", []).append(n)+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ r = ref_grads[n]+ compared += 1+ worst = max(worst, (g - r).abs().max().item() / (r.abs().max().item() + 1e-8))+ opt.step()+ result.update(ok = True, worst_rel_grad = worst, compared = compared, losses = losses)+ except Exception as exc:+ result.update(ok = False, error = f"{type(exc).__name__}: {str(exc)[:300]}")+ with open(f"{out}.{rank}", "w", encoding = "utf-8") as f:+ json.dump(result, f)+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(lora, root_only, dummy, tmp_path):+ import torch.multiprocessing as mp++ out = str(tmp_path / "result.json")+ # CPU only: the spawned children inherit this environment before they import torch.+ saved = os.environ.get("CUDA_VISIBLE_DEVICES")+ os.environ["CUDA_VISIBLE_DEVICES"] = ""+ try:+ ctx = mp.start_processes(+ _worker,+ args = (2, _free_port(), lora, root_only, dummy, out),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ finally:+ if saved is None:+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)+ else:+ os.environ["CUDA_VISIBLE_DEVICES"] = saved+ import time++ deadline = time.time() + 300+ while True:+ try:+ if ctx.join(timeout = 5):+ break+ except Exception: # a rank died (gloo aborted the collective): the expected failure mode+ break+ if time.time() > deadline:+ break+ for p in ctx.processes:+ if p.is_alive():+ p.kill()+ results = []+ for rank in range(2):+ try:+ with open(f"{out}.{rank}", encoding = "utf-8") as f:+ results.append(json.load(f))+ except FileNotFoundError:+ results.append({"rank": rank, "ok": False, "error": "no result (hung or killed)"})+ return results+++def _skip_without_tiny():+ try:+ import transformers+ transformers.AutoConfig.from_pretrained(TINY)+ except Exception as exc:+ pytest.skip(f"{TINY}: {type(exc).__name__}: {exc}")+++LAYOUTS = [(False, False), (True, False), (True, True)]+LAYOUT_IDS = ["full-blocks", "lora-blocks", "lora-root-only"]++[email protected]("lora,root_only", LAYOUTS, ids = LAYOUT_IDS)+def test_text_only_rank_runs_dummy_vision(lora, root_only, tmp_path):+ _skip_without_tiny()+ results = _run(lora, root_only, True, tmp_path)+ for r in results:+ assert r["ok"], results+ assert r["installed"], results+ assert r["worst_rel_grad"] < 1e-4, results+ assert r["compared"] > 0, results++[email protected]("lora,root_only", LAYOUTS, ids = LAYOUT_IDS)+def test_without_dummy_vision_desyncs(lora, root_only, tmp_path):+ """Negative control: the same run without the dummy pass fails, times out or gets wrong grads."""+ _skip_without_tiny()+ results = _run(lora, root_only, False, tmp_path)+ assert not all(r["ok"] and r["worst_rel_grad"] < 1e-4 for r in results), resultsdiff --git a/tests/test_fsdp2_native_wrappers_video_gloo.py b/tests/test_fsdp2_native_wrappers_video_gloo.pynew file mode 100644index 00000000000..106730e0a59--- /dev/null+++ b/tests/test_fsdp2_native_wrappers_video_gloo.py@@ -0,0 +1,346 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 (gloo CPU world of 2 where a process group is needed):++* Trainer.save_model of a LoRA model the Trainer holds wrapped by torch.compile (`_orig_mod`) still+ writes the adapter checkpoint;+* a model on the CPU is sharded onto the local GPU under a gloo-only process group (CUDA without+ NCCL), unless the CPU is asked for explicitly;+* VideoLlava-style separate image / video towers (`pixel_values_images` / `pixel_values_videos`) get+ the per-modality agreement: image on one rank and video on the other raises on both;+* a prebuilt bitsandbytes optimizer instance is refused (Trainer and accelerate prepare)."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib # noqa: E402+import sys # noqa: E402+import time # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.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, _full, _stub_unsloth_save # noqa: E402+from test_fsdp2_native_trainer_args_gloo import ( # noqa: E402+ _install_wrapped_trainer_init,+ _lora,+ _targs,+)+from test_fsdp2_native_guards_gloo import _Stop, _tiny_llama # noqa: E402+from test_fsdp2_native_optim_reentry_gloo import AdamW8bitLike # noqa: E402+++def _case_compiled_save(native, tmp):+ from safetensors.torch import load_file+ from transformers import Trainer+ import torch.distributed as dist++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ want = _full(model, trainable_only = True)+ trainer = Trainer(model = model, args = _targs(os.path.join(tmp, "out")))+ trainer.model = torch.compile(model) # what accelerate hands back with torch_compile = True+ ckpt = os.path.join(tmp, "ckpt")+ res = {"full_gathers": 0}+ full = native.native_full_state_dict++ def counting(*args, **kwargs): # the whole-model gather a LoRA save must not take+ res["full_gathers"] += 1+ return full(*args, **kwargs)++ native.native_full_state_dict = counting+ try:+ trainer.save_model(ckpt)+ except Exception as exc:+ res["error"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ finally:+ native.native_full_state_dict = full+ dist.barrier()+ res["files"] = sorted(os.listdir(ckpt)) if os.path.isdir(ckpt) else []+ path = os.path.join(ckpt, "adapter_model.safetensors")+ if os.path.isfile(path):+ saved = load_file(path)+ worst = 0.0+ for k, v in saved.items():+ name = k.replace(".weight", ".default.weight")+ worst = (+ max(worst, (v - want[name]).abs().max().item()) if name in want else float("inf")+ )+ res["n"] = len(saved)+ res["diff"] = worst+ # Resume / load_best_model through the same wrapper.+ dst = native.shard_model(_lora(2), native.FSDP2Config(param_dtype = torch.float32))+ try:+ native.native_load_model_checkpoint(torch.compile(dst), ckpt)+ got = _full(dst, trainable_only = True)+ res["load_diff"] = max((got[n] - want[n]).abs().max().item() for n in want)+ except Exception as exc:+ res["load_error"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++class _Tower(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(16, 8)++ def forward(self, pixels):+ return self.proj(pixels.flatten(1))+++class _LM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(16, 8)+ self.layer = torch.nn.Linear(8, 8)++ def forward(self, inputs_embeds):+ return torch.tanh(self.layer(inputs_embeds))+++class _VideoLlavaLike(torch.nn.Module):+ """transformers VideoLlavaModel's layout: image_tower, video_tower, multi_modal_projector,+ language_model; get_image_features(pixel_values_images), get_video_features(pixel_values_videos)."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.config = types.SimpleNamespace(+ vision_config = types.SimpleNamespace(image_size = 4, patch_size = 2, num_channels = 1)+ )+ self.image_tower = _Tower()+ self.video_tower = _Tower()+ self.multi_modal_projector = torch.nn.Linear(8, 8)+ self.language_model = _LM()++ def get_input_embeddings(self):+ return self.language_model.embed++ def get_image_features(self, pixel_values_images):+ return self.multi_modal_projector(self.image_tower(pixel_values_images))++ def get_video_features(self, pixel_values_videos):+ return self.multi_modal_projector(self.video_tower(pixel_values_videos))++ def forward(+ self,+ input_ids,+ pixel_values_images = None,+ pixel_values_videos = None,+ ):+ embeds = self.language_model.embed(input_ids)+ if pixel_values_images is not None:+ embeds = embeds + self.get_image_features(pixel_values_images).mean(0)+ if pixel_values_videos is not None:+ embeds = embeds + self.get_video_features(pixel_values_videos).mean(0)+ return self.language_model(inputs_embeds = embeds).square().mean()+++def _case_video(native, rank):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard++ vision = importlib.import_module("unsloth.models.fsdp2_vision")+ mesh = init_device_mesh("cpu", (2,))+ model = _VideoLlavaLike()+ for module in (model.image_tower, model.video_tower, model.language_model.layer):+ fully_shard(module, mesh = mesh)+ fully_shard(model, mesh = mesh)+ host = vision.install_vision_dummy(model)+ res = {"host": type(host).__name__ if host is not None else None}+ ids = torch.randint(0, 16, (1, 5), generator = torch.Generator().manual_seed(rank))+ image = {"pixel_values_images": torch.randn(1, 1, 4, 4)}+ video = {"pixel_values_videos": torch.randn(2, 1, 4, 4)}+ steps = [+ ("text", {}),+ ("both", {**image, **video}),+ ("image_vs_video", image if rank == 0 else video),+ ]+ for step, kwargs in steps:+ try:+ model(ids, **kwargs).backward()+ res[step] = "ok"+ except Exception as exc:+ res[step] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++def _case_bnb_instance(native, tmp):+ _install_wrapped_trainer_init()+ from accelerate import Accelerator+ from transformers import Trainer++ model = native.shard_model(_lora(1), native.FSDP2Config(param_dtype = torch.float32))+ trainable = [p for p in model.parameters() if p.requires_grad]+ res = {}+ for name, cls in (("bnb_like", AdamW8bitLike), ("torch", torch.optim.AdamW)):+ optimizer = cls(trainable, lr = 1e-3)+ try:+ Trainer(+ model = model, args = _targs(os.path.join(tmp, "out")), optimizers = (optimizer, None)+ )+ res[f"{name}.trainer"] = ""+ except Exception as exc:+ res[f"{name}.trainer"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ # A Trainer's accelerator (marked) with the sharded model registered.+ fake_accelerator = types.SimpleNamespace(_models = [model])+ setattr(fake_accelerator, native._TRAINER_ACCELERATOR, True)+ try:+ Accelerator.prepare_optimizer(fake_accelerator, AdamW8bitLike(trainable, lr = 1e-3))+ res["prepare"] = ""+ except Exception as exc:+ res["prepare"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ return res+++def _worker(rank, world, port, out, case, tmp):+ 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),+ UNSLOTH_FSDP2 = "1",+ )+ import datetime++ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ native = _load_native()+ _stub_unsloth_save()+ if case == "compiled_save":+ res = _case_compiled_save(native, tmp)+ elif case == "video":+ res = _case_video(native, rank)+ elif case == "bnb_instance":+ res = _case_bnb_instance(native, tmp)+ out.put((rank, res))+ except Exception as exc:+ import traceback+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))+ finally:+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(+ case,+ tmp_path,+ timeout = 180,+):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ procs = mp.start_processes(+ _worker,+ args = (2, _free_port(), out, case, str(tmp_path)),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ deadline = time.time() + timeout+ try:+ while not procs.join(timeout = 5):+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"{case}: a rank died ({exc})")+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, r in results.items():+ print("ROUND7_RESULT", case, rank, r)+ assert "crash" not in r, r["crash"]+ return results+++def test_compiled_peft_model_saves_an_adapter_checkpoint(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ r = _run("compiled_save", tmp_path)[0]+ assert "error" not in r, r+ assert "adapter_model.safetensors" in r["files"] and "model.safetensors" not in r["files"], r+ assert r["n"] > 0 and r["diff"] == 0.0, r+ assert r["full_gathers"] == 0, r # adapter-only gather, not the whole model+ assert "load_error" not in r and r["load_diff"] == 0.0, r+++def test_separate_image_and_video_towers_are_agreed(tmp_path):+ for rank, r in _run("video", tmp_path).items():+ assert r["host"] in ("_VideoLlavaLike", "FSDP_VideoLlavaLike"), (rank, r)+ assert r["text"] == "ok" and r["both"] == "ok", (rank, r)+ assert r["image_vs_video"].startswith("RuntimeError"), (rank, r)+ assert "on 1 of 2 ranks" in r["image_vs_video"], (rank, r)+++def test_prebuilt_bnb_optimizer_instance_is_refused(tmp_path):+ pytest.importorskip("transformers")+ pytest.importorskip("peft")+ pytest.importorskip("accelerate")+ for rank, r in _run("bnb_instance", tmp_path).items():+ assert (+ r["bnb_like.trainer"].startswith("ValueError")+ and "bitsandbytes" in r["bnb_like.trainer"]+ ), (rank, r)+ assert r["torch.trainer"] == "", (rank, r)+ assert r["prepare"].startswith("ValueError") and "bitsandbytes" in r["prepare"], (rank, r)+++# ---- CPU unit checks (no process group) -------------------------------------------------------+++def test_gloo_process_group_on_a_cuda_host_shards_onto_the_gpu(monkeypatch):+ pytest.importorskip("transformers")+ import torch.distributed as dist++ for key, value in dict(UNSLOTH_FSDP2 = "1", WORLD_SIZE = "2", RANK = "0", LOCAL_RANK = "1").items():+ monkeypatch.setenv(key, value)+ monkeypatch.delenv("ACCELERATE_USE_CPU", raising = False)+ native = _load_native()+ model = _tiny_llama()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)+ monkeypatch.setattr(dist, "is_initialized", lambda: True)+ monkeypatch.setattr(dist, "get_backend", lambda *a, **k: "gloo") # CUDA build without NCCL+ seen = {}++ def _record(device, *_):+ seen["device"] = device+ raise _Stop++ monkeypatch.setattr(native, "_ensure_process_group", _record)+ cfg = native.FSDP2Config(param_dtype = torch.float32)+ with pytest.raises(_Stop):+ native.shard_model(model, cfg)+ assert seen["device"] == torch.device("cuda", 1), seen+ # Explicit CPU requests still keep the CPU: ACCELERATE_USE_CPU, or config.device (use_cpu).+ monkeypatch.setenv("ACCELERATE_USE_CPU", "true")+ with pytest.raises(_Stop):+ native.shard_model(_tiny_llama(), cfg)+ assert seen["device"] == torch.device("cpu"), seen+ monkeypatch.delenv("ACCELERATE_USE_CPU")+ with pytest.raises(_Stop):+ native.shard_model(+ _tiny_llama(), native.FSDP2Config(param_dtype = torch.float32, device = "cpu")+ )+ assert seen["device"] == torch.device("cpu"), seendiff --git a/tests/test_fsdp2_perf_layout_gloo.py b/tests/test_fsdp2_perf_layout_gloo.pynew file mode 100644index 00000000000..cce2a15d458--- /dev/null+++ b/tests/test_fsdp2_perf_layout_gloo.py@@ -0,0 +1,186 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 fit layout (unsloth/models/fsdp2_perf.py), two gloo ranks on CPU.++When the model fits: frozen weights stay plain replicated tensors (never DTensor, never gathered),+trainable weights are sharded DTensors, and loss + reduced gradients match an unsharded copy. Both the+single root unit (small trainable set) and per-block units are checked. The planner falls back to the+plain sharded layout when the model does not fit or CPU offload is asked for.+"""++from __future__ import annotations++import os+import socket++import pytest++# Spawned gloo ranks re-import this module: keep them on the CPU (deterministic on GPU hosts; CUDA+# reads the mask at its lazy first use, after this).+if __import__("multiprocessing").parent_process() is not None:+ os.environ["CUDA_VISIBLE_DEVICES"] = ""++torch = pytest.importorskip("torch")+dist = pytest.importorskip("torch.distributed")+pytest.importorskip("torch.distributed.fsdp")++if not dist.is_available() or not dist.is_gloo_available():+ pytest.skip("gloo backend unavailable", allow_module_level = True)++import importlib.util # noqa: E402++# Load the module by path: it imports nothing from unsloth, and the spawned ranks skip unsloth's import.+_spec = importlib.util.spec_from_file_location(+ "unsloth_fsdp2_perf_under_test",+ os.path.join(os.path.dirname(__file__), "..", "unsloth", "models", "fsdp2_perf.py"),+)+fsdp2_perf = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(fsdp2_perf)+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++D = 16+++class Adapter(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.base = torch.nn.Linear(D, D, bias = False)+ self.A = torch.nn.Linear(D, 4, bias = False)+ self.B = torch.nn.Linear(4, D, bias = False)+ self.base.weight.requires_grad_(False)++ def forward(self, x):+ return self.base(x) + self.B(self.A(x))+++class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.q = Adapter()+ self.o = Adapter()++ def forward(self, x):+ return x + torch.tanh(self.o(self.q(x)))+++class Toy(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(32, D)+ self.layers = torch.nn.ModuleList(Block() for _ in range(3))+ self.head = torch.nn.Linear(D, 32, bias = False)+ self.embed.weight.requires_grad_(False)+ self.head.weight.requires_grad_(False)++ def forward(self, ids):+ x = self.embed(ids)+ for layer in self.layers:+ x = layer(x)+ return torch.nn.functional.cross_entropy(self.head(x).flatten(0, 1), ids.flatten())+++def _worker(rank, world, port, units_mode, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1", MASTER_PORT = str(port), UNSLOTH_FSDP2_TRAINABLE_UNITS = units_mode+ )+ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ from torch.distributed.fsdp import MixedPrecisionPolicy+ from torch.distributed.tensor import DTensor++ fsdp2_perf._device_bytes = lambda device = None: 1 << 40 # pretend a big GPU: the model fits+ torch.manual_seed(0)+ ref = Toy()+ torch.manual_seed(0)+ model = Toy()+ ids = torch.randint(0, 32, (2, 8), generator = torch.Generator().manual_seed(1))+ ref_loss = ref(ids)+ ref_loss.backward()++ layout = fsdp2_perf.plan_fsdp2_layout(model, param_dtype = torch.float32)+ wrapped = fsdp2_perf.shard_model_layout(+ model, list(model.layers), MixedPrecisionPolicy(), layout, mesh = None+ )+ loss = model(ids)+ loss.backward()+ res = {+ "layout": layout.as_dict(),+ "n_wrapped": len(wrapped),+ "loss": float(loss),+ "ref_loss": float(ref_loss),+ "frozen_plain": all(+ not isinstance(p, DTensor) for p in model.parameters() if not p.requires_grad+ ),+ "trainable_dtensor": all(+ isinstance(p, DTensor) for p in model.parameters() if p.requires_grad+ ),+ "frozen_no_grad": all(+ p.grad is None for p in model.parameters() if not p.requires_grad+ ),+ }+ ref_grads = {n: p.grad for n, p in ref.named_parameters() if p.requires_grad}+ diffs = []+ for n, p in model.named_parameters():+ if p.requires_grad:+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ diffs.append(float((g - ref_grads[n]).abs().max()))+ res["max_grad_diff"] = max(diffs)+ if rank == 0:+ out.put(res)+ finally:+ dist.destroy_process_group()++[email protected]("units_mode", ["auto", "blocks"])+def test_fit_layout_matches_unsharded(units_mode):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ q = ctx.Queue()+ mp.start_processes(+ _worker, args = (2, _free_port(), units_mode, q), nprocs = 2, join = True, start_method = "spawn"+ )+ res = q.get(timeout = 60)+ assert res["layout"]["replicate_frozen"] is True+ assert res["layout"]["reshard_after_forward"] is False+ assert res["layout"]["root_only"] is (units_mode == "auto")+ assert res["n_wrapped"] == (0 if units_mode == "auto" else 3)+ assert res["frozen_plain"] and res["trainable_dtensor"] and res["frozen_no_grad"]+ assert abs(res["loss"] - res["ref_loss"]) < 1e-6+ assert res["max_grad_diff"] < 1e-6+++def test_planner_falls_back_when_not_fitting(monkeypatch):+ model = Toy()+ monkeypatch.setattr(fsdp2_perf, "_device_bytes", lambda device = None: 1024)+ layout = fsdp2_perf.plan_fsdp2_layout(model)+ assert not layout.fits and not layout.replicate_frozen and layout.reshard_after_forward is True+ assert not layout.root_only+++def test_planner_cpu_offload_and_overrides(monkeypatch):+ model = Toy()+ monkeypatch.setattr(fsdp2_perf, "_device_bytes", lambda device = None: 1 << 40)+ assert not fsdp2_perf.plan_fsdp2_layout(model, cpu_offload = True).replicate_frozen+ assert (+ fsdp2_perf.plan_fsdp2_layout(model, reshard_after_forward = True).reshard_after_forward+ is True+ )+ monkeypatch.setenv("UNSLOTH_FSDP2_REPLICATE_FROZEN", "0")+ assert not fsdp2_perf.plan_fsdp2_layout(model).replicate_frozen+ monkeypatch.setenv("UNSLOTH_FSDP2_REPLICATE_FROZEN", "auto")+ monkeypatch.setenv("UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD", "1")+ assert fsdp2_perf.plan_fsdp2_layout(model).reshard_after_forward is True+ # Full fine-tuning (nothing frozen): nothing to replicate.+ for p in model.parameters():+ p.requires_grad_(True)+ monkeypatch.delenv("UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD")+ layout = fsdp2_perf.plan_fsdp2_layout(model)+ assert not layout.replicate_frozen and layout.reshard_after_forward is Falsediff --git a/tests/test_fsdp2_save_args.py b/tests/test_fsdp2_save_args.pyindex 4640c4f18c6..5e1f9c45612 100644--- a/tests/test_fsdp2_save_args.py+++ b/tests/test_fsdp2_save_args.py@@ -98,6 +98,33 @@ def test_peft_saves_gather_the_frozen_tensors_peft_writes():assert arguments["save_embedding_layers"] is False+def test_peft_embedding_membership_survives_a_reshard():+ """The gather reshards before it walks the parameters, and a parameter an eval forward left+ unsharded is a different object from the DTensor the gather then sees: the embeddings must still be+ selected (by module, not by parameter identity), or they stay sharded in the saved adapter."""+ from peft import LoraConfig, get_peft_model+ from transformers import LlamaConfig, LlamaForCausalLM++ cfg = LlamaConfig(+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ vocab_size = 64,+ )+ model = get_peft_model(LlamaForCausalLM(cfg), LoraConfig(r = 2, target_modules = ["q_proj"]))+ include = unsloth_save._fsdp2_peft_saved_frozen(model, {})+ for getter in ("get_input_embeddings", "get_output_embeddings"):+ module = getattr(model, getter)()+ # What FSDPModule.reshard does: the module's parameter becomes a new object.+ module.weight = torch.nn.Parameter(module.weight.detach().clone(), requires_grad = False)+ names = {n for n, p in model.named_parameters() if include(n, p)}+ assert any("embed_tokens" in n for n in names), names+ assert any("lm_head" in n for n in names), names+ assert not any("q_proj.base_layer" in n for n in names), names++@pytest.mark.parametrize("method,offload",[diff --git a/tests/test_fsdp2_save_gloo.py b/tests/test_fsdp2_save_gloo.pyindex abce71b0d51..a22c479fe62 100644--- a/tests/test_fsdp2_save_gloo.py+++ b/tests/test_fsdp2_save_gloo.py@@ -221,7 +221,12 @@ def _case_gather_4bit(rank, world_size, m):dict(params4bit = type(w).__name__ == "Params4bit",quant_state = w.quant_state is not None,- bytes_equal = torch.equal(w.data.view(torch.uint8), raw),+ bytes_equal = torch.equal(+ w.data.reshape(-1).view(torch.uint8), raw.reshape(-1)+ ),+ # Saved as the uint8 bitsandbytes writes without FSDP2 (merged_4bit requantizes+ # with the weight's own quant_storage).+ uint8_storage = w.dtype == torch.uint8 and w.quant_storage == torch.uint8,dequant_equal = torch.equal(bnb.functional.dequantize_4bit(w.data, w.quant_state), deq),@@ -235,6 +240,64 @@ def _case_gather_4bit(rank, world_size, m):return out+class Linear4bit(torch.nn.Linear):+ """Stands in for bitsandbytes' Linear4bit (matched by class name)."""+++class _LoraLayer(torch.nn.Module):+ """PEFT's LoraLayer shape: `base_layer` + `lora_A` / `lora_B` ModuleDicts."""++ def __init__(self, seed, quantized):+ super().__init__()+ torch.manual_seed(seed)+ base = Linear4bit if quantized else torch.nn.Linear+ self.base_layer = base(37, 37, bias = False).requires_grad_(False)+ self.lora_A = torch.nn.ModuleDict({"default": torch.nn.Linear(37, 4, bias = False)})+ self.lora_B = torch.nn.ModuleDict({"default": torch.nn.Linear(4, 37, bias = False)})++ def forward(self, x):+ return x + torch.tanh(+ self.base_layer(x) + self.lora_B["default"](self.lora_A["default"](x))+ )+++class _LoraModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.layers = torch.nn.ModuleList(+ [_LoraLayer(10 * i, quantized = i != 1) for i in range(N_LAYERS)]+ )++ def forward(self, x):+ for layer in self.layers:+ x = layer(x)+ return x+++def _case_merge_offload(rank, world_size, m):+ """merged_4bit after an eval forward: the filter is built while the last unit is unsharded, the+ gather reshards it first. Every adapter of a 4-bit layer must stay put (False), everything else+ moves to the CPU (True)."""+ model = _shard(_LoraModel(), world_size)+ with torch.no_grad():+ model(torch.randn(6, 37))+ out = {"unsharded_after_eval": sum(not _is_dtensor(p) for p in model.parameters())}+ for layer in model.layers:+ if isinstance(layer.base_layer, Linear4bit):+ layer.base_layer.weight.quant_state = object() # what the filter reads today+ offload = m.offload_all_but_4bit_merge_operands(model)+ decisions = {}++ def record(name, param):+ decisions[name] = offload(name, param)+ return decisions[name]++ with m.fsdp2_gathered(model, offload_to_cpu = record):+ pass+ out["decisions"] = decisions+ return out++def _case_replicated(rank, world_size, m, hooked):import torch.distributed as dist@@ -293,6 +356,9 @@ def _case_dcp_bnb(rank, world_size, m):module = layer,)model = torch.nn.Sequential(layer.to("cpu"), torch.nn.Linear(64, 8))+ reference_dequant = bnb.functional.dequantize_4bit(+ model[0].weight.data, model[0].weight.quant_state+ )q.prepare_fsdp2_qlora(model)fully_shard(model, mesh = init_device_mesh("cpu", (world_size,)))# What accelerate's save_fsdp_model / load_fsdp_model ask for on an adapter checkpoint.@@ -313,6 +379,33 @@ def _case_dcp_bnb(rank, world_size, m):out["full_sharded_keys"] = sorted(full)except AttributeError as error:out["full_sharded_keys"] = f"AttributeError: {error}"+ full = None+ if rank == 0 and full is not None:+ # The full checkpoint rebuilds the 4-bit weight on its own (what transformers does with a+ # pre-quantized checkpoint) and dequantizes to the same values. The packed bytes keep the+ # sharded storage dtype; they are the same bytes as uint8.+ try:+ stats = {k[len("0.weight.") :]: v for k, v in full.items() if k.startswith("0.weight.")}+ packed = full["0.weight"].reshape(-1).view(torch.uint8).reshape(-1, 1)+ fresh = bnb.nn.Params4bit.from_prequantized(+ data = packed, quantized_stats = stats, requires_grad = False, device = "cpu"+ )+ out["full_reload"] = torch.equal(+ bnb.functional.dequantize_4bit(fresh.data, fresh.quant_state), reference_dequant+ )+ except Exception as error:+ out["full_reload"] = f"{type(error).__name__}: {error}"+ if full is not None:+ # ... and loads back into the sharded model (the entries it added are dropped again).+ try:+ dcp.set_model_state_dict(+ model,+ full if rank == 0 else {},+ options = StateDictOptions(full_state_dict = True, broadcast_from_rank0 = True),+ )+ out["full_set"] = "ok"+ except Exception as error:+ out["full_set"] = f"{type(error).__name__}: {error}"sd = dcp.get_model_state_dict(model, options = options)out["after_keys"] = sorted(sd)expected = {k: v.clone() for k, v in sd.items()}@@ -380,6 +473,20 @@ def _case_dcp_bnb(rank, world_size, m):return out+def _case_fp16_reduce(rank, world_size, m):+ """An fp16 trainable parameter FSDP2 does not manage: its gradient mean must not overflow."""++ class _Half(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.bias = torch.nn.Parameter(torch.zeros(4, dtype = torch.float16))++ model = _Half()+ m.reduce_unsharded_trainable_grads(model)+ (model.bias * 40000).sum().backward()+ return {"grad": model.bias.grad.float().tolist(), "dtype": str(model.bias.grad.dtype)}++def _case_slow_writer(rank, world_size, m):"""rank 0's write (a merged or quantized export, a Hub upload) outlasts the collective timeout."""import time@@ -415,6 +522,10 @@ def _worker(rank, world_size, port, case, queue):result = _case_slow_writer(rank, world_size, m)elif case == "gather":result = _case_gather(rank, world_size, m)+ elif case == "fp16_reduce":+ result = _case_fp16_reduce(rank, world_size, m)+ elif case == "merge_offload":+ result = _case_merge_offload(rank, world_size, m)elif case == "gather_4bit":result = _case_gather_4bit(rank, world_size, m)elif case.startswith("replicated"):@@ -438,8 +549,17 @@ def _run(case, world_size = 2):ctx.Process(target = _worker, args = (r, world_size, port, case, queue))for r in range(world_size)]- for p in procs:- p.start()+ # CPU only: a spawned child inherits this environment before it imports torch.+ saved = os.environ.get("CUDA_VISIBLE_DEVICES")+ os.environ["CUDA_VISIBLE_DEVICES"] = ""+ try:+ for p in procs:+ p.start()+ finally:+ if saved is None:+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)+ else:+ os.environ["CUDA_VISIBLE_DEVICES"] = savedresults = {}for _ in procs:rank, result = queue.get(timeout = 240)@@ -506,7 +626,14 @@ def test_dcp_state_dict_of_bitsandbytes_4bit():assert r["before"].startswith("AttributeError") and "absmax" in r["before"], rassert r["installed"], rassert r["after_keys"] == ["1.bias", "1.weight"], r- assert r["full_sharded_keys"] == ["0.weight", "1.bias", "1.weight"], r["full_sharded_keys"]+ # A full checkpoint of the sharded 4-bit model keeps what dequantizes it, reloads, and loads back.+ assert "0.weight" in r["full_sharded_keys"], r["full_sharded_keys"]+ assert "0.weight.absmax" in r["full_sharded_keys"], r["full_sharded_keys"]+ assert "0.weight.quant_state.bitsandbytes__nf4" in r["full_sharded_keys"], r[+ "full_sharded_keys"+ ]+ assert r["full_reload"] is True, r["full_reload"]+ assert all(x["full_set"] == "ok" for x in results.values()), resultsassert all(x["roundtrip"] for x in results.values()), resultsassert "0.weight.absmax" in r["full_keys"], r["full_keys"]assert r["adapter_keys"] == ["lora_A.default.weight", "lora_B.default.weight"], r[@@ -517,3 +644,26 @@ def test_dcp_state_dict_of_bitsandbytes_4bit():def test_a_slow_writer_does_not_time_out_the_other_ranks():results = _run("slow_writer")assert all(r["ok"] for r in results.values()), results+++def test_unsharded_fp16_grads_are_averaged_without_overflow():+ # Each rank's fp16 gradient is 40000; their fp16 sum (80000) overflows, their mean does not.+ results = _run("fp16_reduce")+ for r in results.values():+ assert r["grad"] == [40000.0] * 4, r+ assert r["dtype"] == "torch.float16", r+++def test_merge_offload_keeps_4bit_adapters_after_an_eval_forward():+ """The merged_4bit offload filter is built by name: after an eval forward the last unit's+ parameters are unsharded objects the gather replaces with DTensors before asking the filter, so an+ identity based filter moved that layer's adapters to the CPU while its 4-bit base stayed put."""+ r0 = _run("merge_offload")[0]+ assert r0["unsharded_after_eval"] > 0, r0+ decisions = r0["decisions"]+ expected = {}+ for i in range(N_LAYERS):+ for part in ("lora_A", "lora_B"):+ expected[f"layers.{i}.{part}.default.weight"] = i == 1 # layer 1 is not 4-bit+ expected[f"layers.{i}.base_layer.weight"] = True+ assert decisions == expected, decisionsdiff --git a/tests/test_fsdp2_vision_gate_gloo.py b/tests/test_fsdp2_vision_gate_gloo.pynew file mode 100644index 00000000000..cfcec2d91a9--- /dev/null+++ b/tests/test_fsdp2_vision_gate_gloo.py@@ -0,0 +1,267 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 dummy vision pass (fsdp2_vision) on a tiny random Llava, gloo CPU world of 2: rank 0+trains on an image + text batch, rank 1 on text only.++- frozen tower, trainable FSDP2-managed `multi_modal_projector`: the projector's reduce-scatter sets+ differ unless the gate counts the projector.+- frozen tower except replicated trainable norms (gradients averaged by the all-reduce hook): the+ all-reduce runs on the image rank only unless the gate counts those hooked parameters.+- `get_image_features(..., image_sizes = None)` (Llava on transformers >= 5.19): a CLIP tower needs+ `vision_config.image_size`, not a patch-sized dummy.+Each case must finish on both ranks with gradients equal to the unsharded model's on both batches.+Loads fsdp2_native.py on its own (no `import unsloth`), so it runs without a GPU."""++import datetime+import importlib.util+import inspect+import json+import os+import socket+import sys+import types++import pytest+import torch++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+IMAGE_SIZE = 8+PATCH = 4+IMAGE_TOKEN = 999+++def _load_native():+ pkg = types.ModuleType("unsloth")+ pkg.__path__ = [os.path.join(REPO, "unsloth")]+ models = types.ModuleType("unsloth.models")+ models.__path__ = [os.path.join(REPO, "unsloth", "models")]+ sys.modules.setdefault("unsloth", pkg)+ sys.modules.setdefault("unsloth.models", models)+ for name in ("fsdp2_launch", "models.fsdp2_native", "models.fsdp2_vision", "models.fsdp2_save"):+ path = os.path.join(REPO, "unsloth", *name.split(".")) + ".py"+ spec = importlib.util.spec_from_file_location(f"unsloth.{name}", path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[f"unsloth.{name}"] = module+ spec.loader.exec_module(module)+ return sys.modules["unsloth.models.fsdp2_native"], sys.modules["unsloth.models.fsdp2_vision"]+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _config():+ import transformers++ vision = transformers.CLIPVisionConfig(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ image_size = IMAGE_SIZE,+ patch_size = PATCH,+ num_channels = 3,+ )+ text = transformers.LlamaConfig(+ vocab_size = 1000,+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ max_position_embeddings = 64,+ )+ return transformers.LlavaConfig(+ vision_config = vision,+ text_config = text,+ image_token_index = IMAGE_TOKEN,+ vision_feature_layer = -1,+ vision_feature_select_strategy = "default",+ )+++def _build(case):+ import transformers++ torch.manual_seed(0)+ model = transformers.LlavaForConditionalGeneration(_config()).float().train()+ if case in ("projector", "norms"):+ for name, p in model.named_parameters():+ if "vision_tower" in name:+ p.requires_grad_(case == "norms" and "layer_norm" in name)+ elif "multi_modal_projector" in name:+ p.requires_grad_(case == "projector")+ return model+++def _batches():+ g = torch.Generator().manual_seed(1)+ n_tokens = (IMAGE_SIZE // PATCH) ** 2+ text = lambda n: torch.randint(3, 900, (n,), generator = g) # noqa: E731+ image_ids = torch.cat([text(4), torch.full((n_tokens,), IMAGE_TOKEN), text(6)])[None]+ image = {+ "input_ids": image_ids,+ "labels": image_ids.clone(),+ "pixel_values": torch.randn(1, 3, IMAGE_SIZE, IMAGE_SIZE, generator = g),+ "use_cache": False,+ }+ text_ids = text(image_ids.shape[1])[None]+ return [image, {"input_ids": text_ids, "labels": text_ids.clone(), "use_cache": False}]+++def _explicit_image_sizes():+ """transformers >= 5.19 Llava: `get_image_features(..., image_sizes = None, **kwargs)`, passed on+ to the backbone only when given. Older versions take it through **kwargs only."""+ from transformers.models.llava import modeling_llava++ cls = modeling_llava.LlavaModel+ if "image_sizes" in inspect.signature(cls.get_image_features).parameters:+ return+ original = cls.get_image_features++ def get_image_features(+ self,+ pixel_values,+ vision_feature_layer = None,+ vision_feature_select_strategy = None,+ image_sizes = None,+ **kwargs,+ ):+ return original(+ self,+ pixel_values = pixel_values,+ vision_feature_layer = vision_feature_layer,+ vision_feature_select_strategy = vision_feature_select_strategy,+ **kwargs,+ )++ cls.get_image_features = get_image_features+++def _worker(rank, world, port, case, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ result = {"rank": rank}+ try:+ native, vision = _load_native()+ if case == "image_sizes":+ _explicit_image_sizes()+ ref = _build(case)+ model = _build(case)+ ignored = None+ if case == "norms":+ # Replicated trainable vision norms: their gradients are all-reduced by a hook.+ ignored = {+ p for n, p in model.named_parameters() if "vision_tower" in n and p.requires_grad+ }+ config = native.FSDP2Config(+ param_dtype = torch.float32, units = [], shard_frozen = False, ignored_params = ignored+ )+ native.shard_model(model, config)+ result["installed"] = any(getattr(m, vision._INSTALLED, False) for m in model.modules())+ from torch.distributed.tensor import DTensor++ batches = _batches()+ ref_opt = torch.optim.SGD([p for p in ref.parameters() if p.requires_grad], lr = 0.5)+ opt = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr = 0.5)+ worst, compared = 0.0, 0+ for step in range(2):+ ref_opt.zero_grad(set_to_none = True)+ for b in batches:+ (ref(**b).loss / len(batches)).backward()+ ref_grads = {n: p.grad for n, p in ref.named_parameters() if p.grad is not None}+ ref_opt.step()+ opt.zero_grad(set_to_none = True)+ model(**batches[rank]).loss.backward()+ for n, p in model.named_parameters():+ if n not in ref_grads:+ continue+ if p.grad is None:+ worst = float("inf")+ result.setdefault("missing", []).append(n)+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ r = ref_grads[n]+ compared += 1+ worst = max(worst, (g - r).abs().max().item() / (r.abs().max().item() + 1e-8))+ opt.step()+ result.update(ok = True, worst_rel_grad = worst, compared = compared)+ except Exception as exc:+ result.update(ok = False, error = f"{type(exc).__name__}: {str(exc)[:300]}")+ with open(f"{out}.{rank}", "w", encoding = "utf-8") as f:+ json.dump(result, f)+ try:+ dist.destroy_process_group()+ except Exception:+ pass+++def _run(case, tmp_path):+ import time++ import torch.multiprocessing as mp++ out = str(tmp_path / "result.json")+ # CPU only: the spawned children inherit this environment before they import torch.+ saved = os.environ.get("CUDA_VISIBLE_DEVICES")+ os.environ["CUDA_VISIBLE_DEVICES"] = ""+ try:+ ctx = mp.start_processes(+ _worker,+ args = (2, _free_port(), case, out),+ nprocs = 2,+ join = False,+ start_method = "spawn",+ )+ finally:+ if saved is None:+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)+ else:+ os.environ["CUDA_VISIBLE_DEVICES"] = saved+ deadline = time.time() + 300+ while True:+ try:+ if ctx.join(timeout = 5):+ break+ except Exception: # a rank died (gloo aborted the collective)+ break+ if time.time() > deadline:+ break+ for p in ctx.processes:+ if p.is_alive():+ p.kill()+ results = []+ for rank in range(2):+ try:+ with open(f"{out}.{rank}", encoding = "utf-8") as f:+ results.append(json.load(f))+ except FileNotFoundError:+ results.append({"rank": rank, "ok": False, "error": "no result (hung or killed)"})+ return results++[email protected]("case", ["projector", "norms", "image_sizes"])+def test_text_only_rank_matches_image_rank_collectives(case, tmp_path):+ pytest.importorskip("transformers.models.llava")+ if sys.platform == "win32" or not torch.distributed.is_gloo_available():+ pytest.skip("needs torch.distributed with gloo")+ results = _run(case, tmp_path)+ for r in results:+ assert r["ok"], results+ assert r["installed"], results+ assert r["compared"] > 0, results+ assert r["worst_rel_grad"] < 1e-4, resultsdiff --git a/unsloth/fsdp2_launch.py b/unsloth/fsdp2_launch.pyindex 4265d167b27..5d2b39e8d41 100644--- a/unsloth/fsdp2_launch.py+++ b/unsloth/fsdp2_launch.py@@ -5,11 +5,16 @@import importlib.utilimport os+import sys__all__ = ["unsloth_fsdp2_requested",+ "unsloth_fsdp2_native_requested","fsdp_version_from_env","apply_unsloth_fsdp2_launch_env",+ "NATIVE_BACKEND_TABLE",+ "native_backend_conflicts",+ "refuse_native_backend_conflicts",]_TRUTHY = ("1", "true", "yes", "on")@@ -28,7 +33,30 @@ def _env_world_size():def unsloth_fsdp2_requested():- return _env_flag("UNSLOTH_FSDP2")+ return _env_flag("UNSLOTH_FSDP2") or _env_value("UNSLOTH_FSDP2") == "native"+++def _env_value(name):+ return str(os.environ.get(name, "")).strip().lower()+++def unsloth_fsdp2_native_requested():+ """UNSLOTH_FSDP2=1 / native under WORLD_SIZE > 1 selects Unsloth's own fully_shard wrap+ (`unsloth.models.fsdp2_native`). UNSLOTH_FSDP2_BACKEND=accelerate, or an `accelerate launch`+ FSDP config (ACCELERATE_USE_FSDP) without an explicit backend, keeps accelerate's wrap."""+ if not unsloth_fsdp2_requested() or _env_world_size() <= 1:+ return False+ backend = _env_value("UNSLOTH_FSDP2_BACKEND")+ if backend in ("accelerate", "hf", "transformers"):+ return False+ if backend not in ("", "native", "unsloth", "torch"):+ raise ValueError(+ f"Unsloth: UNSLOTH_FSDP2_BACKEND={os.environ.get('UNSLOTH_FSDP2_BACKEND')} is not one "+ "of 'native' (default) or 'accelerate'."+ )+ if backend == "" and _env_flag("ACCELERATE_USE_FSDP"):+ return False+ return Truedef fsdp_version_from_env():@@ -64,11 +92,239 @@ def _accelerate_fsdp2_support():return None+# Every distributed backend accelerate 1.15 can select (accelerate/utils/dataclasses.py:602-638+# DistributedType, chosen in accelerate/state.py PartialState._prepare_backend :755-816 and+# AcceleratorState.__init__ :960-1023), plus the launcher-only layouts beside it, and what native FSDP2+# does with each. "handle" rows are supported or turned off elsewhere (named in `how`); "refuse" rows+# are detected from+# env: a flag `accelerate launch` / an Accelerator plugin exports (true / 1 / yes / on),+# args: a TrainingArguments attribute that is set,+# package: an installed package accelerate switches on by itself (find_spec, no import),+# device: (vendor package or None, torch attribute, checked before CUDA like accelerate): an+# available device of that kind; needs torch, so the launch step checks it only once torch+# is imported, Trainer setup and shard_model always,+# sizes: accelerate's ParallelismConfig env (accelerate/parallelism_config.py:277-289).+# The launch step (apply_unsloth_fsdp2_launch_env) and Trainer setup both run every row, before any+# model change.+NATIVE_BACKEND_TABLE = (+ {"type": "NO", "action": "handle", "how": "native FSDP2 needs WORLD_SIZE > 1"},+ {+ "type": "MULTI_CPU",+ "action": "handle",+ "how": "gloo CPU mesh (use_cpu / ACCELERATE_USE_CPU)",+ },+ {"type": "MULTI_GPU", "action": "handle", "how": "the supported CUDA / ROCm launch"},+ {+ "type": "FSDP",+ "action": "handle",+ "how": "accelerate's FSDP wins unless UNSLOTH_FSDP2_BACKEND=native, which turns it off "+ "(ACCELERATE_USE_FSDP here, TrainingArguments(fsdp) in native_fsdp2_defers_to_trainer_fsdp)",+ },+ {+ "type": "DEEPSPEED",+ "action": "refuse",+ "label": "DeepSpeed",+ # accelerate/utils/launch.py:566, state.py:974, accelerator.py:368 (a DeepSpeedPlugin sets it)+ "env": ("ACCELERATE_USE_DEEPSPEED",),+ "args": ("deepspeed", "deepspeed_plugin", "hf_deepspeed_config"),+ },+ {+ "type": "MEGATRON_LM",+ "action": "refuse",+ "label": "Megatron-LM",+ # accelerate/utils/launch.py:337, state.py:1017-1023, accelerator.py:405-410 (MegatronLMPlugin)+ "env": ("ACCELERATE_USE_MEGATRON_LM",),+ "args": ("megatron_lm_plugin",),+ },+ {+ "type": "XLA",+ "action": "refuse",+ "label": "torch_xla (TPU / XLA)",+ # accelerate/utils/imports.py:30-41 (USE_TORCH_XLA, default on), state.py:766-767: XLA wins+ # whenever torch_xla imports.+ "package": "torch_xla",+ "unless_env_false": "USE_TORCH_XLA",+ },+ {"type": "MULTI_MLU", "action": "refuse", "label": "MLU", "device": ("torch_mlu", "mlu", True)},+ {+ "type": "MULTI_SDAA",+ "action": "refuse",+ "label": "SDAA",+ "device": ("torch_sdaa", "sdaa", True),+ },+ {+ "type": "MULTI_MUSA",+ "action": "refuse",+ "label": "MUSA",+ "device": ("torch_musa", "musa", True),+ },+ {+ "type": "MULTI_NPU",+ "action": "refuse",+ "label": "Ascend NPU",+ "device": ("torch_npu", "npu", True),+ },+ {+ "type": "MULTI_HPU",+ "action": "refuse",+ "label": "Gaudi HPU",+ "device": ("habana_frameworks.torch", "hpu", True),+ },+ {"type": "MULTI_XPU", "action": "refuse", "label": "Intel XPU", "device": (None, "xpu", False)},+ {+ "type": "MULTI_NEURON",+ "action": "refuse",+ "label": "AWS Neuron",+ "device": ("torch_neuronx", "neuron", False),+ },+ {+ "type": "SAGEMAKER_DP",+ "action": "refuse",+ "label": "SageMaker data parallel",+ # accelerate/state.py:186-191: smddp backend+ "env_pair": ("ACCELERATE_USE_SAGEMAKER", "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE"),+ },+ {+ "type": "PARALLELISM_CONFIG",+ "action": "refuse",+ "label": "an accelerate ParallelismConfig (TP / CP / SP / replicate)",+ # accelerate/utils/launch.py:403-420, accelerator.py:455-460; TrainingArguments(+ # parallelism_config) and tp_plan models are refused in fsdp2_native (_refuse_parallelism_config,+ # _refuse_tensor_parallel_model).+ "sizes": "PARALLELISM_CONFIG_",+ },+)+++def _set_arg(training_args, name):+ value = getattr(training_args, name, None)+ return value is not None and value is not False and value != "" and value != {}+++def _import_vendor(package):+ """The vendor extension that registers its device with torch, as accelerate imports it+ (accelerate/utils/imports.py is_*_available). Written-out names only."""+ if package == "torch_mlu":+ import torch_mlu # noqa: F401+ elif package == "torch_sdaa":+ import torch_sdaa # noqa: F401+ elif package == "torch_musa":+ import torch_musa # noqa: F401+ elif package == "torch_npu":+ import torch_npu # noqa: F401+ elif package == "habana_frameworks.torch":+ import habana_frameworks.torch # noqa: F401+ elif package == "torch_neuronx":+ import torch_neuronx # noqa: F401+ else:+ raise ValueError(package)+++def _device_available(spec):+ package, attr, before_cuda = spec+ torch = sys.modules.get("torch")+ if torch is None:+ return False # launch step before torch: Trainer setup / shard_model check it+ try:+ if not before_cuda and torch.cuda.is_available():+ return False # accelerate prefers CUDA over this one+ if package is not None:+ if importlib.util.find_spec(package.split(".")[0]) is None:+ return False+ _import_vendor(package)+ backend = getattr(torch, attr, None)+ return bool(backend is not None and backend.is_available())+ except Exception:+ return False+++def _parallelism_sizes(prefix):+ if not _env_flag("ACCELERATE_USE_PARALLELISM_CONFIG"):+ return None+ sizes = {}+ for name in ("DP_REPLICATE_SIZE", "DP_SHARD_SIZE", "TP_SIZE", "CP_SIZE", "SP_SIZE"):+ try:+ sizes[name.lower()] = int(os.environ.get(prefix + name, "1") or 1)+ except ValueError:+ sizes[name.lower()] = 1+ world = _env_world_size()+ extra = {k: v for k, v in sizes.items() if k != "dp_shard_size" and v > 1}+ if extra or sizes["dp_shard_size"] not in (1, world):+ return sizes+ return None+++def native_backend_conflicts(training_args = None, uses_cpu = None):+ """[(DistributedType, label, reason)] for every NATIVE_BACKEND_TABLE refuse row this launch or+ these TrainingArguments select. `uses_cpu` (the Trainer's use_cpu) skips the device rows."""+ if uses_cpu is None:+ uses_cpu = _env_flag("ACCELERATE_USE_CPU")+ found = []+ for row in NATIVE_BACKEND_TABLE:+ if row["action"] != "refuse":+ continue+ reasons = [name for name in row.get("env", ()) if _env_flag(name)]+ if training_args is not None:+ reasons += [+ f"TrainingArguments.{name}"+ for name in row.get("args", ())+ if _set_arg(training_args, name)+ ]+ package = row.get("package")+ if package and importlib.util.find_spec(package) is not None:+ off = os.environ.get(row.get("unless_env_false", ""), "")+ if str(off).strip().lower() not in _FALSY:+ reasons.append(f"{package} installed")+ if "device" in row and not uses_cpu and _device_available(row["device"]):+ reasons.append(f"a {row['label']} device")+ pair = row.get("env_pair")+ if pair and _env_flag(pair[0]) and _env_value(pair[1]) not in ("", "no"):+ reasons.append(f"{pair[0]} / {pair[1]}={os.environ.get(pair[1])}")+ if "sizes" in row:+ sizes = _parallelism_sizes(row["sizes"])+ if sizes:+ reasons.append(+ "ACCELERATE_USE_PARALLELISM_CONFIG with "+ + ", ".join(f"{k}={v}" for k, v in sizes.items())+ )+ if reasons:+ found.append((row["type"], row["label"], reasons))+ return found+++def refuse_native_backend_conflicts(training_args = None, uses_cpu = None):+ """Raise, before any model change, when native FSDP2 meets a backend it cannot run under."""+ found = native_backend_conflicts(training_args, uses_cpu)+ if found:+ what = "; ".join(f"{label} ({', '.join(reasons)})" for _, label, reasons in found)+ raise RuntimeError(+ "Unsloth: UNSLOTH_FSDP2=1 shards the model with native FSDP2 (CUDA / ROCm, or the CPU), "+ f"which cannot run under {what}. Drop that backend, or unset UNSLOTH_FSDP2."+ )++def apply_unsloth_fsdp2_launch_env():"""UNSLOTH_FSDP2=1 with WORLD_SIZE > 1: export what `accelerate launch` exports for an FSDP2config (explicit FSDP_* values win). Must run before transformers / accelerate read the env."""if not unsloth_fsdp2_requested() or _env_world_size() <= 1:return False+ if unsloth_fsdp2_native_requested():+ # Unsloth shards the model itself; accelerate must see a plain multi-GPU launch.+ refuse_native_backend_conflicts()+ if _env_flag("ACCELERATE_USE_FSDP"):+ # `accelerate launch` with an FSDP config and an explicit UNSLOTH_FSDP2_BACKEND=native:+ # accelerate would build its own FSDP plugin from this env and wrap the sharded model+ # again (and with FSDP_CPU_RAM_EFFICIENT_LOADING, from_pretrained leaves the weights+ # unloaded off local rank 0). Same env on every rank, so every rank drops it alike.+ os.environ.pop("ACCELERATE_USE_FSDP", None)+ os.environ.pop("FSDP_VERSION", None)+ if str(os.environ.get("RANK", "0")).strip() in ("", "0"):+ print(+ "Unsloth: UNSLOTH_FSDP2_BACKEND=native on an `accelerate launch` FSDP config: "+ "Unsloth shards the model itself, so accelerate's FSDP is turned off "+ "(ACCELERATE_USE_FSDP and FSDP_VERSION unset)."+ )+ return Falseif _env_flag("ACCELERATE_USE_DEEPSPEED"):raise RuntimeError("Unsloth: UNSLOTH_FSDP2=1 was set on a DeepSpeed launch. Unset one of them."diff --git a/unsloth/kernels/bnb_override.py b/unsloth/kernels/bnb_override.pyindex e626593fb91..4c7c6e3e760 100644--- a/unsloth/kernels/bnb_override.py+++ b/unsloth/kernels/bnb_override.py@@ -205,9 +205,30 @@ def _bnb_fused_takes(self, x, quant_state):return take+def _float_packed_as_uint8(weight):+ """FSDP2 QLoRA stores the packed NF4 bytes as the compute dtype (`bnb_4bit_quant_storage`) so they+ can be sharded; the all-gathered weight is those bytes as a contiguous (N, 1) float buffer. Return+ the uint8 view the kernels read, else the weight unchanged (bitsandbytes then handles it)."""+ if (+ weight.dtype in _FLOAT_PACKED+ and weight.dim() == 2+ and weight.shape[-1] == 1+ and weight.is_contiguous()+ ):+ return weight.view(torch.uint8)+ return weight+++_FLOAT_PACKED = (torch.float16, torch.bfloat16, torch.float32)++def _forward(self, x):weight = self.weightquant_state = getattr(weight, "quant_state", None)+ if weight.dtype is not torch.uint8:+ # FSDP2 QLoRA packs NF4 bytes as floats; gated on the weight itself (a process-global flag would+ # become a Dynamo guard). A uint8 weight, the default, never reaches the check.+ weight = _float_packed_as_uint8(weight)if (_BNB_FUSEDand quant_state is not Nonediff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.pyindex 53f2f621ed0..aaadba0dd87 100644--- a/unsloth/models/_block_compile.py+++ b/unsloth/models/_block_compile.py@@ -593,6 +593,9 @@ def _nf4_in_blocks():):weight = self.weightquant_state = getattr(weight, "quant_state", None)+ if weight.dtype is not torch.uint8:+ # FSDP2 QLoRA packs the NF4 bytes as floats; the kernels read the uint8 view.+ weight = O._float_packed_as_uint8(weight)if (O._eligible(self, x, weight, quant_state)and (quant_state.dtype is not torch.bfloat16 or O._TRACE_BF16)diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 9bc93477aae..d611b52fce8 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -5560,7 +5560,31 @@ def patch_gradient_accumulation_fix(Trainer):install_fsdp2_policy_provenance()except Exception:pass+ from ..fsdp2_launch import unsloth_fsdp2_native_requested++ # Env reads only; fsdp2_native (and torch.distributed.fsdp) is imported only under the flag.+ native_fsdp2 = unsloth_fsdp2_native_requested()+ if native_fsdp2:+ from .fsdp2_native import (+ native_fsdp2_trainer_init_arguments,+ native_fsdp2_trainer_setup,+ )++ # UNSLOTH_FSDP2=1 under torchrun: Unsloth shards the model itself (fully_shard per block+ # + root) before the optimizer and accelerate exist; accelerate then skips its wrap.+ # Arguments by keyword or position, so a positional optimizer is refused too.+ bound = native_fsdp2_trainer_init_arguments(_original_trainer_init, args, kwargs)+ native_fsdp2_trainer_setup(+ model = bound["model"],+ phase = "pre",+ optimizers = bound["optimizers"],+ training_args = bound["args"],+ model_init = bound["model_init"],+ optimizer_cls_and_kwargs = bound["optimizer_cls_and_kwargs"],+ )_original_trainer_init(self, *args, **kwargs)+ if native_fsdp2:+ native_fsdp2_trainer_setup(self, phase = "post")try:accelerator = getattr(self, "accelerator", None)if (@@ -7951,6 +7975,18 @@ def _get_inference_mode_context_manager(model: torch.nn.Module):return torch.no_grad()if os.environ.get("FSDP_VERSION", "").strip() not in ("", "0"):return torch.no_grad()+ # Unsloth's native FSDP2 (UNSLOTH_FSDP2=1 under torchrun) exports neither variable, so accelerate+ # does not wrap the model again: read its launch flag, and the mark shard_model leaves on the root.+ _fsdp2 = os.environ.get("UNSLOTH_FSDP2", "").strip().lower()+ if _fsdp2 in ("1", "true", "yes", "on", "native"):+ try:+ if int(os.environ.get("WORLD_SIZE", "1")) > 1:+ return torch.no_grad()+ except ValueError:+ pass+ for _m in (model, getattr(model, "module", None), getattr(model, "_orig_mod", None)):+ if _m is not None and getattr(_m, "_unsloth_fsdp2_native", False) is True:+ return torch.no_grad()accelerate_state = sys.modules.get("accelerate.state", None)shared_state = getattr(getattr(accelerate_state, "AcceleratorState", None), "_shared_state", None@@ -8571,8 +8607,16 @@ def _block_swap_for_trainer_backend(trainer):"""DDP: ignore swapped weights. FSDP / DeepSpeed (invisible at load): refuse any block swap, sincesharding flattens the 0-element placeholders the swap later rebinds."""model = getattr(trainer, "model", None)+ # Native FSDP2 (UNSLOTH_FSDP2=1) shards in Trainer.__init__ but leaves is_fsdp_enabled False.+ native = model is not None and any(+ getattr(m, "_unsloth_fsdp2_native", False) is True+ for m in (model, getattr(model, "module", None), getattr(model, "_orig_mod", None))+ if m is not None+ )backend = (- "FSDP"+ "native FSDP2"+ if native+ else "FSDP"if getattr(trainer, "is_fsdp_enabled", False)else "DeepSpeed"if getattr(trainer, "is_deepspeed_enabled", False)diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pynew file mode 100644index 00000000000..76b7cbeea3b--- /dev/null+++ b/unsloth/models/fsdp2_native.py@@ -0,0 +1,2806 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 for every Unsloth model, built directly on `torch.distributed.fsdp.fully_shard`.++ for unit in find_shard_units(model): fully_shard(unit, mp_policy = mp)+ fully_shard(model, mp_policy = mp)++with `MixedPrecisionPolicy(param_dtype = compute dtype, reduce_dtype = float32)`. Neither accelerate's+nor transformers' FSDP code wraps the model: Unsloth shards it before the optimizer exists and the+Trainer / accelerate only see an already sharded `FSDPModule` (no second wrap, no DDP).++Opt in with `UNSLOTH_FSDP2=1` (or `native`) under torchrun (WORLD_SIZE > 1).+`UNSLOTH_FSDP2_BACKEND=accelerate` (or an `accelerate launch` FSDP config) keeps the accelerate+path in `unsloth/models/fsdp2.py`. Nothing changes without the flag.+"""++from __future__ import annotations++import contextlib+import dataclasses+import functools+import math+import os+import sys+from typing import Callable, Optional, Union++import torch+import torch.nn as nn++__all__ = [+ "FSDP2Config",+ "STORAGE_DTYPE",+ "find_shard_units",+ "shard_model",+ "native_fsdp2_requested",+ "is_native_fsdp2",+ "install_native_fsdp2_hooks",+ "native_fsdp2_trainer_setup",+ "native_clip_grad_norm_",+ "native_full_state_dict",+ "native_fsdp2_unsharded",+ "register_shard_context",+ "check_shard_units",+ "native_save_optimizer",+ "native_load_optimizer",+ "native_load_model_checkpoint",+]++_PATCHED = "_unsloth_fsdp2_native_patched"+_NATIVE_FLAG = "_unsloth_fsdp2_native"+# Leaf module types that are never a shard unit on their own, even when repeated in a ModuleList.+_LEAF_TYPES = (+ nn.Linear,+ nn.Embedding,+ nn.LayerNorm,+ nn.Conv1d,+ nn.Conv2d,+ nn.Conv3d,+ nn.Dropout,+ nn.Identity,+)+++class FSDP2Config:+ param_dtype: Optional[torch.dtype] = None # None = model compute dtype (bf16; fp16 on T4)+ reduce_dtype: torch.dtype = torch.float32+ # None = auto: when the whole model fits on one GPU (fsdp2_perf.plan_fsdp2_layout), frozen weights stay+ # replicated (never gathered), only trainable ones are sharded, kept gathered from forward to backward+ # (False) with next-block prefetch, and a small trainable set (LoRA) is one root unit; otherwise every+ # block reshards after forward (True). An explicit bool / int is used as is. Last block always False.+ reshard_after_forward: Optional[Union[bool, int]] = None+ cpu_offload: bool = False # CPUOffloadPolicy+ mesh: Optional[object] = None # DeviceMesh; None = 1-D over WORLD_SIZE+ # "cpu": shard on a CPU mesh (gloo) even with CUDA present (TrainingArguments(use_cpu = True)).+ device: Optional[Union[str, torch.device]] = None+ # Process group backend / timeout when shard_model has to create the group (Trainer setup passes+ # TrainingArguments.ddp_backend / ddp_timeout). None = NCCL for CUDA (gloo without NCCL), default.+ backend: Optional[str] = None+ timeout: Optional[object] = None # datetime.timedelta+ # Knobs for perf tuning (defaults = the plan's contract behaviour).+ # The last unit's reshard_after_forward (backward re-gathers it first).+ reshard_last_block: bool = False+ # unit_reshard_after_forward(index, unit) -> bool | int | None (None = the default), per unit.+ unit_reshard_after_forward: Optional[Callable] = None+ # False: frozen weights (LoRA / QLoRA base) stay replicated and are never gathered. True: sharded.+ # None = auto (replicated when the model fits, see reshard_after_forward).+ shard_frozen: Optional[bool] = None+ # None = auto by device memory; True / False forces the fit / sharded layout (env UNSLOTH_FSDP2_LAYOUT).+ fit_layout: Optional[bool] = None+ # Extra parameters to leave replicated (trainable ones get their gradients averaged).+ ignored_params: Optional[set] = None+ # Explicit shard units instead of find_shard_units(model).+ units: Optional[list] = None+ # All-gather the next N units during a unit's forward (0 = FSDP2's implicit prefetch).+ forward_prefetch: int = 0+ # Prefetch the previous N units in backward (0 = FSDP2 default of 1).+ backward_prefetch: int = 0+ # Passed to fully_shard (per-parameter Shard(dim) placement).+ shard_placement_fn: Optional[Callable] = None+ # True: a small minority-dtype trainable group (Unsloth full FT's fp32 norms next to bf16 linears) stays+ # replicated in its own dtype with DDP-style gradient averaging (matches 1 GPU). False: every parameter+ # becomes a DTensor and mixed units get float32 masters (measured 0.25 loss drift vs 1 GPU by step 10).+ replicate_minority_dtype: bool = True+ # Root-level embedding tables (not the input / output embeddings) holding at least this fraction of all+ # parameters get their own unit (Gemma4 / Gemma3n `embed_tokens_per_layer`: ~40% of an E-model would sit+ # gathered in the root for the whole step). 0 disables.+ split_large_root_embeddings: float = 0.05+ # Wrap `generate` so it runs inside native_fsdp2_unsharded (Unsloth's decode loops read layer weights+ # without calling the blocks; PeftModel.generate skips the root's hooks). Collective: every rank generates.+ wrap_generate: bool = True++ @classmethod+ def from_env(cls):+ """Defaults, overridden by UNSLOTH_FSDP2_PARAM_DTYPE (bfloat16 / float16 / float32 / storage =+ gather each weight in its own dtype / auto = the default), UNSLOTH_FSDP2_REDUCE_DTYPE, UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD+ (0 / 1) and UNSLOTH_FSDP2_CPU_OFFLOAD (0 / 1)."""+ config = cls()+ dtypes = {+ "bfloat16": torch.bfloat16,+ "bf16": torch.bfloat16,+ "float16": torch.float16,+ "fp16": torch.float16,+ "float32": torch.float32,+ "fp32": torch.float32,+ "storage": STORAGE_DTYPE,+ "none": STORAGE_DTYPE,+ }+ value = os.environ.get("UNSLOTH_FSDP2_PARAM_DTYPE", "").strip().lower()+ if value and value != "auto":+ if value not in dtypes:+ raise ValueError(+ f"Unsloth: UNSLOTH_FSDP2_PARAM_DTYPE={value} is not one of {sorted(dtypes)}."+ )+ config.param_dtype = dtypes[value]+ value = os.environ.get("UNSLOTH_FSDP2_REDUCE_DTYPE", "").strip().lower()+ if value:+ if value not in dtypes or dtypes[value] is STORAGE_DTYPE:+ raise ValueError(f"Unsloth: UNSLOTH_FSDP2_REDUCE_DTYPE={value} is not a dtype.")+ config.reduce_dtype = dtypes[value]+ value = os.environ.get("UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD", "").strip().lower()+ if value and value != "auto":+ config.reshard_after_forward = value not in ("0", "false", "no", "off")+ value = os.environ.get("UNSLOTH_FSDP2_CPU_OFFLOAD", "").strip().lower()+ if value:+ config.cpu_offload = value in ("1", "true", "yes", "on")+ value = os.environ.get("UNSLOTH_FSDP2_SHARD_FROZEN", "").strip().lower()+ if value and value != "auto":+ config.shard_frozen = value not in ("0", "false", "no", "off")+ value = os.environ.get("UNSLOTH_FSDP2_LAYOUT", "").strip().lower()+ if value in ("fit", "sharded"):+ config.fit_layout = value == "fit"+ for name in ("forward_prefetch", "backward_prefetch"):+ value = os.environ.get(f"UNSLOTH_FSDP2_{name.upper()}", "").strip()+ if value:+ setattr(config, name, int(value))+ return config+++# `FSDP2Config(param_dtype = STORAGE_DTYPE)`: no gather cast, each weight computes in its own dtype.+STORAGE_DTYPE = "storage"+++def native_fsdp2_requested() -> bool:+ """UNSLOTH_FSDP2=1 (or "native") under WORLD_SIZE > 1. UNSLOTH_FSDP2_BACKEND=accelerate, or an+ `accelerate launch` FSDP config (ACCELERATE_USE_FSDP) with no explicit backend, keeps the+ accelerate path. Read from the launcher env only, so every rank agrees."""+ from ..fsdp2_launch import unsloth_fsdp2_native_requested+ return unsloth_fsdp2_native_requested()+++def _fsdp_api():+ try:+ from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, fully_shard+ except ImportError:+ from torch.distributed._composable.fsdp import ( # torch 2.4 / 2.5+ FSDPModule,+ MixedPrecisionPolicy,+ fully_shard,+ )+ return FSDPModule, MixedPrecisionPolicy, fully_shard+++def _fsdp_attr(name):+ """A public FSDP2 name (fully_shard, CPUOffloadPolicy, OffloadPolicy, MixedPrecisionPolicy,+ FSDPModule, register_fsdp_forward_method, ...): `torch.distributed.fsdp` on torch >= 2.6,+ `torch.distributed._composable.fsdp` on 2.4 / 2.5."""+ import importlib++ try:+ public = importlib.import_module("torch.distributed.fsdp")+ if hasattr(public, name):+ return getattr(public, name)+ except ImportError:+ pass+ composable = importlib.import_module("torch.distributed._composable.fsdp") # torch 2.4 / 2.5+ return getattr(composable, name)+++# FSDP2's private modules, by static import on either layout: torch.distributed.fsdp._fully_shard.<name>+# (torch >= 2.6) or torch.distributed._composable.fsdp.<name> (2.4 / 2.5).+++def _load_fsdp_param():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_param as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_param as module+ return module+++def _load_fsdp_state():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_state as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_state as module+ return module+++def _load_fsdp_common():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_common as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_common as module+ return module+++def _load_fsdp_param_group():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_param_group as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_param_group as module+ return module+++def _load_fsdp_init():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_init as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_init as module+ return module+++def _load_fsdp_collectives():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_collectives as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_collectives as module+ return module+++def _load_fully_shard():+ try:+ from torch.distributed.fsdp._fully_shard import _fully_shard as module+ except (+ ImportError+ ): # torch 2.4 / 2.5: the module is `fully_shard` (the package attribute is the function)+ import torch.distributed._composable.fsdp.fully_shard # noqa: F401+ module = sys.modules["torch.distributed._composable.fsdp.fully_shard"]+ return module+++_FSDP_PRIVATE_LOADERS = {+ "_fsdp_param": _load_fsdp_param,+ "_fsdp_state": _load_fsdp_state,+ "_fsdp_common": _load_fsdp_common,+ "_fsdp_param_group": _load_fsdp_param_group,+ "_fsdp_init": _load_fsdp_init,+ "_fsdp_collectives": _load_fsdp_collectives,+ "_fully_shard": _load_fully_shard,+}+++def _fsdp_private(submodule):+ """FSDP2's private module `submodule` (_fsdp_param, _fsdp_state, _fsdp_common, _fsdp_param_group,+ _fsdp_init, _fsdp_collectives, _fully_shard) on either layout (see _FSDP_PRIVATE_LOADERS)."""+ loader = _FSDP_PRIVATE_LOADERS.get(submodule)+ if loader is None:+ raise ImportError(f"no FSDP2 module {submodule}")+ return loader()+++def _fsdp_module_class():+ try:+ return _fsdp_api()[0]+ except ImportError:+ return None+++def is_native_fsdp2(model) -> bool:+ if model is None:+ return False+ if getattr(model, _NATIVE_FLAG, False):+ return True+ for attr in ("module", "_orig_mod"):+ inner = getattr(model, attr, None)+ if isinstance(inner, nn.Module) and getattr(inner, _NATIVE_FLAG, False):+ return True+ return False+++def _rank0():+ try:+ import torch.distributed as dist+ return not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0+ except Exception:+ return True+++def _print_rank0(message):+ if _rank0():+ print(message, flush = True)+++# --------------------------------------------------------------------------------------------------+# Unit discovery+# --------------------------------------------------------------------------------------------------+++def _no_split_names(model):+ names = set()+ for module in model.modules():+ for name in getattr(module, "_no_split_modules", None) or ():+ if isinstance(name, str):+ names.add(name)+ return names+++def _mro_names(module):+ return {c.__name__ for c in type(module).__mro__}+++def _has_params(module):+ return next(module.parameters(), None) is not None+++def _leafish(module):+ """A Linear / norm / Embedding-like module, also when PEFT wrapped it (lora.Linear keeps `base_layer`)."""+ if isinstance(module, _LEAF_TYPES) or not any(True for _ in module.children()):+ return True+ base = getattr(module, "base_layer", None)+ return isinstance(base, nn.Module) and _leafish(base)+++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 altup+ projections, also after PEFT wraps them) are not blocks."""+ children = list(container.children())+ if not children:+ return False+ for child in children:+ if _leafish(child) or not _has_params(child):+ return False+ return True+++def find_shard_units(model) -> list:+ """Repeated decoder / vision / audio blocks in module order: every child of the outermost+ nn.ModuleLists of blocks (model.layers, language_model.layers, vision_tower.*.layers, ...); never a+ unit inside a unit (MoE experts, fused-LoRA Linears stay in their block's unit). Only when no such list+ exists, the existing `_no_split_modules` instances."""+ no_split = _no_split_names(model)+ units = []+ unit_ids = set()+ inside = set() # ids of modules inside a chosen unit++ def _take(module):+ units.append(module)+ unit_ids.add(id(module))+ for sub in module.modules():+ inside.add(id(sub))++ for _, module in model.named_modules():+ if id(module) in inside:+ continue+ if isinstance(module, nn.ModuleList) and _is_block_list(module, no_split):+ for child in module.children():+ if id(child) not in inside:+ _take(child)+ if no_split and not units:+ # Fallback only when no block list exists: the existing `_no_split_modules` classes (transformers 5.x+ # merges children's names into the parent, so absent names are simply never matched).+ for _, module in model.named_modules():+ if id(module) in inside or module is model:+ continue+ if _mro_names(module) & no_split and _has_params(module):+ _take(module)+ # Module (pre-)order = forward order for the usual layouts; the fallback units are re-sorted in.+ order = {id(m): i for i, m in enumerate(model.modules())}+ units.sort(key = lambda m: order.get(id(m), 0))+ check_shard_units(model, units)+ return units+++def _block_compiled(module):+ """Unsloth's block compile installs a compiled `forward` on the decoder-layer class (_block_compile)."""+ return bool(getattr(getattr(type(module), "forward", None), "_unsloth_block_compiled", False))+++def check_shard_units(model, units):+ """The one hard torch.compile rule: no FSDP unit inside a (compiled) decoder block or inside another+ unit. Unsloth compiles each decoder block's forward (fullgraph=False); FSDP2's hooks are dynamo+ disabled, so a unit nested inside the block (an expert, a router, a LoRA / norm submodule) is a silent+ graph break per block (an error under fullgraph). Experts, routers and LoRA stay inside their block's+ unit. Raises RuntimeError naming the offending unit."""+ blocks = set()+ for module in model.modules():+ if isinstance(module, nn.ModuleList) and _is_block_list(module, ()):+ blocks.update(id(child) for child in module.children())+ elif _block_compiled(module):+ blocks.add(id(module))+ parents = {}+ names = {}+ for name, module in model.named_modules(remove_duplicate = False):+ names.setdefault(id(module), name)+ for child in module.children():+ parents.setdefault(id(child), module)+ unit_ids = {id(u) for u in units}+ for unit in units:+ if unit is model:+ raise RuntimeError(+ "Unsloth: native FSDP2 shard units must not include the root module."+ )+ ancestor = parents.get(id(unit))+ while ancestor is not None and ancestor is not model:+ if id(ancestor) in unit_ids or id(ancestor) in blocks:+ kind = "shard unit" if id(ancestor) in unit_ids else "decoder block"+ raise RuntimeError(+ f"Unsloth: native FSDP2 would make `{names.get(id(unit), type(unit).__name__)}` its own "+ f"unit inside the {kind} `{names.get(id(ancestor), type(ancestor).__name__)}`. Units nested "+ "in a compiled block break its graph (FSDP2 hooks are dynamo disabled); keep experts, "+ "routers and LoRA inside their block's unit."+ )+ ancestor = parents.get(id(ancestor))+ return True+++# --------------------------------------------------------------------------------------------------+# Sharding+# --------------------------------------------------------------------------------------------------+++def _device_of(model):+ for p in model.parameters():+ if p.device.type != "meta":+ return p.device+ for b in model.buffers():+ if b.device.type != "meta":+ return b.device+ return torch.device("cpu")+++def _offloaded_device_map(model):+ """cpu / disk entries of an accelerate device map (from_pretrained(device_map = ...)) anywhere+ in the model: the user placed those weights off the GPU on purpose."""+ found = []+ for module in model.modules():+ device_map = module.__dict__.get("hf_device_map", None)+ if isinstance(device_map, dict):+ found.extend(+ f"{k}: {v}" for k, v in device_map.items() if str(v).lower() in ("cpu", "disk")+ )+ return found+++def _refuse_gpu_quantized_on_cpu_mesh(model):+ """A CPU mesh (use_cpu) does not replicate frozen weights, so fully_shard would move packed+ bitsandbytes storage off the GPU it was quantized on, away from its quantization state."""+ if any(p.device.type == "cuda" and _is_quantized_param(p) for p in model.parameters()):+ raise RuntimeError(+ "Unsloth: native FSDP2 was asked for a CPU mesh (use_cpu = True), but the model's "+ "bitsandbytes quantized weights are on the GPU; moving them would separate them from "+ "their quantization state. Train on the GPU (use_cpu = False), or load the model "+ "without load_in_4bit / load_in_8bit."+ )+++def _shard_device(model, requested = None):+ """The device FSDP2 shards onto: the model's own, except that a model still entirely on the CPU+ (loaded with device_map = None; meta tensors stay meta) goes to this rank's GPU when CUDA is used,+ like the Trainer would have placed it: fully_shard moves each unit's states to the mesh device as+ it shards it, _place_replicated the replicated ones. A deliberate CPU / disk offload (any+ device_map entry on cpu / disk) and CPU 4-bit weights are refused instead. requested = "cpu" (the+ Trainer's use_cpu) keeps the CPU mesh."""+ if requested is not None and torch.device(requested).type == "cpu":+ _refuse_gpu_quantized_on_cpu_mesh(model)+ return torch.device("cpu")+ if requested is not None and torch.device(requested).type != "cuda":+ _refuse_non_cuda(torch.device(requested).type)+ if str(os.environ.get("ACCELERATE_USE_CPU", "")).strip().lower() in ("1", "true", "yes", "on"):+ _refuse_gpu_quantized_on_cpu_mesh(model)+ return torch.device("cpu")+ elsewhere = sorted(+ {+ t.device.type+ for t in list(model.parameters()) + list(model.buffers())+ if t.device.type not in ("cpu", "cuda", "meta")+ }+ )+ if elsewhere:+ _refuse_non_cuda(elsewhere[0])+ offloaded = _offloaded_device_map(model)+ if offloaded:+ raise RuntimeError(+ "Unsloth: native FSDP2 got a model whose device_map offloads weights to the CPU or disk "+ f"(e.g. {offloaded[0]}). FSDP2 shards the whole model over the GPUs; load it without "+ "CPU / disk offload (device_map = None or each rank's GPU)."+ )+ device = _device_of(model)+ if not torch.cuda.is_available():+ accelerator = _non_cuda_accelerator()+ if accelerator is not None:+ # The Trainer / accelerate would run the batches on it while the mesh stays on the CPU.+ _refuse_non_cuda(accelerator)+ return device+ if device.type not in ("cpu", "cuda"):+ return device # meta+ # Only an explicit CPU request keeps the CPU (above). A gloo process group alone does not: CUDA+ # builds without NCCL (Windows) and _ensure_process_group's fallback run gloo over CUDA tensors.+ tensors = [+ t for t in list(model.parameters()) + list(model.buffers()) if t.device.type != "meta"+ ]+ if any(t.device.type == "cuda" for t in tensors):+ return _placed_cuda_device(model, tensors, device)+ if any(_is_params4bit(p) for p in model.parameters()):+ raise RuntimeError(+ "Unsloth: native FSDP2 got a 4-bit model on the CPU; moving bitsandbytes weights would "+ "re-quantize them. Load it onto each rank's GPU (device_map = {'': local_rank})."+ )+ if any(_is_int8_param(p) for p in model.parameters()):+ raise RuntimeError(+ "Unsloth: native FSDP2 got an 8-bit model on the CPU; moving bitsandbytes Int8Params "+ "would leave their CB / SCB quantization state behind. Load it onto each rank's GPU "+ "(device_map = {'': local_rank})."+ )+ index = _local_cuda_index()+ if index is None:+ index = torch.cuda.current_device()+ _print_rank0(+ "Unsloth: native FSDP2 got a model on the CPU; it is sharded onto each rank's GPU "+ "(cuda:LOCAL_RANK)."+ )+ return torch.device("cuda", index)+++def _non_cuda_accelerator():+ """The device type of an available accelerator other than CUDA / ROCm (xpu, mps, npu, hpu, ...),+ else None."""+ accelerator = getattr(torch, "accelerator", None)+ if accelerator is not None and hasattr(accelerator, "current_accelerator"): # torch 2.6++ try:+ device = accelerator.current_accelerator(check_available = True)+ except Exception:+ device = None+ return None if device is None or device.type == "cuda" else device.type+ for name in ("xpu", "npu", "hpu", "mlu", "musa"):+ try:+ if getattr(torch, name).is_available():+ return name+ except Exception:+ pass+ try:+ if torch.backends.mps.is_available():+ return "mps"+ except Exception:+ pass+ return None+++def _refuse_non_cuda(device_type):+ raise RuntimeError(+ f"Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) supports NVIDIA / AMD GPUs (CUDA / ROCm) and the CPU "+ f"only; this model or host uses {device_type}, which Unsloth's sharding, process group and "+ "memory planning do not handle. Unset UNSLOTH_FSDP2, or train on the CPU with "+ "TrainingArguments(use_cpu = True)."+ )+++def _local_cuda_index():+ try:+ index = int(os.environ.get("LOCAL_RANK", ""))+ except ValueError:+ return None+ return index if 0 <= index < torch.cuda.device_count() else None+++def _is_quantized_param(t):+ """bitsandbytes 4-bit / 8-bit weights: moving them re-quantizes (or loses their state)."""+ return any(c.__name__ in ("Params4bit", "Int8Params") for c in type(t).__mro__) or (+ getattr(t, "quant_state", None) is not None+ )+++def _is_int8_param(t):+ """bitsandbytes LLM.int8() weight (Linear8bitLt): int8 data plus CB / SCB attributes."""+ return any(c.__name__ == "Int8Params" for c in type(t).__mro__)+++def _int8_params(model):+ """bitsandbytes 8-bit weights stay replicated, never sharded: FSDP2 turns a parameter into a+ DTensor shard and gathers it back as a plain tensor, which drops the Int8Params CB / SCB state+ Linear8bitLt's forward reads. They are frozen (int8), so no gradient needs reducing."""+ found = {p for p in model.parameters() if _is_int8_param(p)}+ if found:+ _print_rank0(+ f"Unsloth: native FSDP2 keeps {len(found)} bitsandbytes 8-bit weights replicated (FSDP2 "+ "would drop their CB / SCB quantization state)."+ )+ return found+++def _placed_cuda_device(model, tensors, device):+ """A model already (partly) on CUDA shards onto this rank's GPU, cuda:LOCAL_RANK, not wherever its+ first weight sits: device_map = {"": 0} on every rank would put every rank's mesh on GPU 0 (NCCL+ duplicate device). Plain tensors elsewhere are moved by fully_shard / _place_replicated as they are+ sharded; quantized weights on another device, or a model split over several GPUs, are refused."""+ index = _local_cuda_index()+ if index is None:+ return device # no launcher local rank: keep the model's own device+ target = torch.device("cuda", index)+ gpus = set()+ for module in model.modules():+ device_map = module.__dict__.get("hf_device_map", None)+ if isinstance(device_map, dict):+ gpus.update(+ str(torch.device(v) if not isinstance(v, int) else torch.device("cuda", v))+ for v in device_map.values()+ )+ if len(gpus) > 1:+ raise RuntimeError(+ f"Unsloth: native FSDP2 got a model split over several GPUs ({', '.join(sorted(gpus))}). "+ "FSDP2 shards a whole model per rank; load it onto each rank's own GPU "+ "(device_map = {'': local_rank})."+ )+ misplaced = [t for t in tensors if _is_quantized_param(t) and t.device != target]+ if misplaced:+ raise RuntimeError(+ f"Unsloth: native FSDP2 runs this rank on {target}, but the model's quantized weights are on "+ f"{misplaced[0].device}; moving them would re-quantize. Load it with device_map = "+ "{'': local_rank} so each rank's weights start on its own GPU."+ )+ if any(t.device != target for t in tensors):+ _print_rank0(+ "Unsloth: native FSDP2 shards onto each rank's GPU (cuda:LOCAL_RANK); weights loaded on "+ "another device are moved there as they are sharded."+ )+ return target+++def _ensure_process_group(+ device,+ backend = None,+ timeout = None,+):+ """The default process group, created here only when nothing created it yet (transformers 4.x sets+ it up lazily; Trainer setup first runs TrainingArguments' own device setup). An explicit `backend`+ (TrainingArguments.ddp_backend) and `timeout` (ddp_timeout) are used as given; only the default+ picks NCCL for CUDA and falls back to gloo when NCCL is missing (Windows CUDA builds)."""+ import torch.distributed as dist++ if dist.is_initialized():+ return dist+ if backend is None:+ backend = "nccl" if device.type == "cuda" and dist.is_nccl_available() else "gloo"+ if device.type == "cuda":+ torch.cuda.set_device(device)+ kwargs = {"backend": backend}+ if timeout is not None:+ kwargs["timeout"] = timeout+ dist.init_process_group(**kwargs)+ return dist+++def _default_mesh(device, dist):+ from torch.distributed.device_mesh import init_device_mesh+ return init_device_mesh(device.type, (dist.get_world_size(),))+++def _floating(p):+ return p.is_floating_point() and p.dtype not in _FLOAT8 and not _is_params4bit(p)+++def _is_params4bit(p):+ return any(c.__name__ == "Params4bit" for c in type(p).__mro__)+++def _compute_dtype(model):+ """bfloat16 / float16 the model computes in (its config / most common 16-bit weight)."""+ for attr in ("config",):+ cfg = getattr(model, attr, None)+ for key in ("torch_dtype", "dtype"):+ value = getattr(cfg, key, None) if cfg is not None else None+ if isinstance(value, str):+ value = getattr(torch, value, None)+ if value in (torch.bfloat16, torch.float16):+ return value+ counts = {}+ for p in model.parameters():+ if p.dtype in (torch.bfloat16, torch.float16) and not _is_params4bit(p):+ counts[p.dtype] = counts.get(p.dtype, 0) + p.numel()+ for p in model.parameters():+ quant_state = getattr(p, "quant_state", None)+ dtype = getattr(quant_state, "dtype", None)+ if dtype in (torch.bfloat16, torch.float16):+ counts[dtype] = counts.get(dtype, 0) + p.numel()+ if counts:+ return max(counts, key = counts.get)+ return None+++def _resolve_param_dtype(model, config):+ if config.param_dtype == STORAGE_DTYPE:+ return None+ if config.param_dtype is not None:+ return config.param_dtype+ compute = _compute_dtype(model)+ if compute == torch.float16 and any(+ p.requires_grad and p.dtype == torch.float32 for p in model.parameters()+ ):+ # float16 gathers of float32 masters move the embedding / norm / lm_head backward into+ # float16, where scaled gradients overflow and the GradScaler skips steps one GPU takes;+ # gather the masters as they are and let autocast cast like one GPU does.+ return None+ return compute+++def _fsdp2_checks_frozen_dtypes():+ """torch < 2.8 asserts one original dtype over every parameter of a unit, frozen ones included."""+ try:+ import inspect+ FSDPParamGroup = _fsdp_private("_fsdp_param_group").FSDPParamGroup+ return "requires_grad" not in inspect.getsource(FSDPParamGroup._init_mp_dtypes)+ except Exception:+ pass+ try:+ major, minor = (int(x) for x in torch.__version__.split(".")[:2])+ return (major, minor) < (2, 8)+ except Exception:+ return False+++def _supports_ignored_params(fully_shard):+ import inspect+ try:+ return "ignored_params" in inspect.signature(fully_shard).parameters+ except (TypeError, ValueError):+ return False+++# A minority dtype group up to this fraction of a unit's trainable elements stays replicated.+_REPLICATE_MINORITY_FRACTION = 0.10+++def _unify_dtypes(+ model,+ units,+ param_dtype,+ can_ignore = True,+):+ """FSDP2 wants one original dtype over a unit's trainable parameters (all of them on torch < 2.8).+ Unsloth's full finetuning keeps 16-bit linears next to float32 norms; one GPU updates each in its own+ dtype. To keep that, a small minority dtype group (norms) is left out of the unit: replicated, its+ gradient averaged over ranks like DDP. A large one, or a torch without `ignored_params`, gets float32+ masters instead (gathered in `param_dtype`). Returns (ignored parameter set, number upcast)."""+ frozen_too = _fsdp2_checks_frozen_dtypes()+ groups = [list(u.parameters()) for u in units]+ inside = set()+ for u in units:+ for p in u.parameters():+ inside.add(id(p))+ groups.append([p for p in model.parameters() if id(p) not in inside])+ ignored = set()+ frozen_kept = []+ n = 0+ seen = set()+ for params in groups:+ params = [p for p in params if id(p) not in seen and not seen.add(id(p))]+ trainable = [p for p in params if _floating(p) and p.requires_grad]+ by_dtype = {}+ for p in trainable:+ by_dtype[p.dtype] = by_dtype.get(p.dtype, 0) + p.numel()+ if len(by_dtype) > 1:+ majority = max(by_dtype, key = by_dtype.get)+ total = sum(by_dtype.values())+ minority = total - by_dtype[majority]+ if can_ignore and minority <= _REPLICATE_MINORITY_FRACTION * total:+ ignored.update(p for p in trainable if p.dtype != majority)+ else:+ for p in trainable:+ if p.dtype != torch.float32 and type(p) is nn.Parameter:+ p.data = p.data.to(torch.float32)+ n += 1+ if can_ignore and param_dtype in (torch.bfloat16, torch.float16):+ # Frozen float32 weights next to 16-bit ones (GDN A_log / dt_bias, fp32 norms, routers): the+ # gather would cast them to 16-bit, which one GPU never does. Keep small ones replicated.+ floats = [p for p in params if _floating(p)]+ frozen32 = [+ p+ for p in floats+ if not p.requires_grad and p.dtype == torch.float32 and p not in ignored+ ]+ total = sum(p.numel() for p in floats)+ if frozen32 and len(frozen32) < len(floats):+ if sum(p.numel() for p in frozen32) <= _REPLICATE_MINORITY_FRACTION * total:+ ignored.update(frozen32)+ frozen_kept.extend(frozen32)+ if frozen_too:+ checked = [p for p in params if _floating(p) and p not in ignored]+ if len({p.dtype for p in checked}) > 1:+ for p in checked:+ if p.dtype != torch.float32 and type(p) is nn.Parameter:+ p.data = p.data.to(torch.float32)+ n += 1+ if n:+ _print_rank0(+ f"Unsloth: native FSDP2 needs one dtype per unit, so {n} 16-bit parameters are kept in "+ f"float32 and gathered in {str(param_dtype).replace('torch.', '')} for compute."+ )+ if frozen_kept:+ _print_rank0(+ f"Unsloth: native FSDP2 keeps {len(frozen_kept)} frozen float32 parameters "+ f"({sum(p.numel() for p in frozen_kept)} elements) replicated, so they are not cast to "+ f"{str(param_dtype).replace('torch.', '')} as one GPU never does."+ )+ trainable_kept = [p for p in ignored if p.requires_grad]+ if trainable_kept:+ ignored_trainable = trainable_kept+ _print_rank0(+ f"Unsloth: native FSDP2 keeps {len(ignored_trainable)} trainable "+ f"{'/'.join(sorted({str(p.dtype).replace('torch.', '') for p in ignored_trainable}))} parameters "+ f"({sum(p.numel() for p in ignored_trainable)} elements, e.g. norms) replicated in their own dtype, as one "+ "GPU trains them; their gradients are averaged over ranks."+ )+ return ignored, n+++# Context-manager factories entered around the fully_shard calls, in order:+# factory(model, param_dtype = None) -> context manager yielding an info dict or None. The default is the+# bitsandbytes 4-bit context (fsdp2_native_quant: Params4bit FSDPParam patches, packed storage dtype).+_SHARD_CONTEXTS = {}+++def register_shard_context(name, factory):+ """Register (or replace, same `name`) a context entered around every native fully_shard pass."""+ _SHARD_CONTEXTS[name] = factory+ return factory+++def _qlora_context(model, param_dtype = None):+ """bitsandbytes 4-bit weights through the fully_shard calls (fsdp2_native_quant): packed bytes+ stored as `param_dtype`, QuantState and Params4bit class kept on the all-gathered weight, no+ accelerate source check (this wrap never upcasts the model)."""+ try:+ from .fsdp2_native_quant import native_quant_context+ except Exception:+ return contextlib.nullcontext(None)+ return native_quant_context(model, dtype = param_dtype)+++register_shard_context("bnb_qlora", _qlora_context)+++def _fully_shard(fully_shard, module, **kwargs):+ """fully_shard, retrying with an ABC-compatible FSDPModule for ABC-derived models on torch builds where the+ dynamic `FSDP<cls>` subclass hits a metaclass conflict (verl `maybe_patch_fsdp_module`)."""+ try:+ return fully_shard(module, **kwargs)+ except TypeError as exc:+ if "metaclass" not in str(exc):+ raise+ import abc++ # The module defining fully_shard (and FSDPModule) on this torch's layout: already imported.+ fully_shard_module = sys.modules.get(getattr(fully_shard, "__module__", ""), None)+ if fully_shard_module is None or not hasattr(fully_shard_module, "FSDPModule"):+ fully_shard_module = _fsdp_private("_fully_shard")++ original = fully_shard_module.FSDPModule++ class FSDPModuleABC(abc.ABC, original):+ pass++ fully_shard_module.FSDPModule = FSDPModuleABC+ try:+ return fully_shard(module, **kwargs)+ finally:+ fully_shard_module.FSDPModule = original+++def _post_shard(+ model,+ units,+ device,+ root_only = False,+):+ """Unsloth-side bookkeeping shared with the accelerate path: fused LoRA gate, direct-read units,+ gradient averaging for anything FSDP2 left unmanaged."""+ FSDPModule = _fsdp_module_class()+ try:+ from . import fsdp2 as _acc++ parents = _acc._parents(model)+ shim = type("_Shim", (), {"device": device})()+ # Fused LoRA kernels exist only once llama.py patched the model; never import it here.+ if __package__ and f"{__package__}.llama" in sys.modules:+ if root_only:+ # One root unit = the outermost module the loop calls: its pre-forward gathers every+ # adapter before any block runs and keeps them gathered through backward.+ from .llama import _fused_lora_modules+ model._unsloth_fsdp2_fused_lora = len(_fused_lora_modules(model))+ else:+ _acc._gate_fused_lora(shim, model, parents, FSDPModule, units)+ model._unsloth_fsdp2_direct_read_units = _acc._gather_units_read_directly(+ model, units, parents, FSDPModule+ )+ except Exception as exc: # pragma: no cover - diagnostics only+ _print_rank0(+ f"Unsloth: native FSDP2 post-shard step skipped ({type(exc).__name__}: {exc})."+ )+ try:+ from .fsdp2_save import reduce_unsharded_trainable_grads+ replicated = reduce_unsharded_trainable_grads(model)+ except Exception:+ replicated = []+ if replicated:+ _print_rank0(+ f"Unsloth: native FSDP2 leaves {len(replicated)} trainable parameters unsharded (e.g. "+ f"{replicated[0]}); their gradients are averaged over ranks like DDP."+ )+++def _patch_accumulated_grad_guard():+ """torch's FSDPParam.to_accumulated_grad_if_needed reads `_unsharded_param`, which a unit never+ unsharded in this step lacks (a tower skipped on a text batch, a block an MoE route skipped), so float32+ reduce_dtype + accumulation without sync raises AttributeError. Same guard as upstream torch nightly,+ miles and NeMo Automodel; a wrapper, so torch's own logic runs otherwise. Native FSDP2 only."""+ try:+ import inspect+ FSDPParam = _fsdp_private("_fsdp_param").FSDPParam+ except Exception:+ return False+ original = getattr(FSDPParam, "to_accumulated_grad_if_needed", None)+ if original is None or getattr(original, _PATCHED, False):+ return original is not None+ try:+ if "getattr" in inspect.getsource(original):+ return True+ except (OSError, TypeError):+ pass++ @functools.wraps(original)+ def to_accumulated_grad_if_needed(self):+ if getattr(self, "_unsharded_param", None) is None:+ return None+ return original(self)++ setattr(to_accumulated_grad_if_needed, _PATCHED, True)+ FSDPParam.to_accumulated_grad_if_needed = to_accumulated_grad_if_needed+ return True+++def _recompute_skips_input_cast(original):+ """torch < 2.13: FSDPState._pre_forward returns early for an activation-checkpoint recompute (training+ state PRE_BACKWARD) without the mixed precision cast of the forward inputs."""+ import inspect++ try:+ source = inspect.getsource(original)+ except (OSError, TypeError):+ return False+ branch = source.split("TrainingState.PRE_BACKWARD:", 1)+ if len(branch) < 2:+ return False+ first_return = branch[1].split("return", 1)+ return len(first_return) == 2 and first_return[1].lstrip().startswith("args, kwargs")+++def _patch_recompute_input_cast():+ """torch < 2.13 skips FSDP2's forward-input cast when a checkpointed unit is recomputed in backward, so+ the recompute sees the uncast (e.g. float32) inputs while the forward saw param_dtype ones: anything+ cast to the input dtype (LoRA A / B, a dequantized 4-bit weight) is saved in another dtype and+ non-reentrant checkpointing raises CheckpointError (Kaggle T4, torch 2.10, fp16 MoE / VLM 4-bit).+ torch 2.13 casts there (`return self._cast_forward_inputs(args, kwargs)`); do the same on older+ builds. Must run before fully_shard registers the hook. Native FSDP2 only;+ UNSLOTH_FSDP2_RECOMPUTE_CAST=0 turns it off (diagnostics)."""+ if os.environ.get("UNSLOTH_FSDP2_RECOMPUTE_CAST", "1").strip().lower() in (+ "0",+ "false",+ "no",+ "off",+ ):+ return False+ try:+ _common = _fsdp_private("_fsdp_common")+ TrainingState, _cast_fp_tensor = _common.TrainingState, _common._cast_fp_tensor+ FSDPState = _fsdp_private("_fsdp_state").FSDPState+ from torch.distributed.utils import _apply_to_tensors+ except Exception:+ return False+ original = getattr(FSDPState, "_pre_forward", None)+ if original is None or getattr(original, _PATCHED, False):+ return original is not None+ if not _recompute_skips_input_cast(original):+ return False++ @functools.wraps(original)+ def _pre_forward(self, module, args, kwargs):+ recompute = self._training_state == TrainingState.PRE_BACKWARD+ args, kwargs = original(self, module, args, kwargs)+ mp = getattr(self, "_mp_policy", None)+ if recompute and mp is not None and mp.cast_forward_inputs and mp.param_dtype:+ cast = functools.partial(_cast_fp_tensor, mp.param_dtype)+ args, kwargs = _apply_to_tensors(cast, args), _apply_to_tensors(cast, kwargs)+ return args, kwargs++ disable = getattr(torch, "_disable_dynamo", None)+ if callable(disable):+ _pre_forward = functools.wraps(original)(disable(_pre_forward))+ setattr(_pre_forward, _PATCHED, True)+ FSDPState._pre_forward = _pre_forward+ return True+++def _large_root_embeddings(model, units, fraction):+ """nn.Embedding tables outside every unit, other than the input / output embeddings (the fused CE reads+ lm_head.weight directly; tied tables must share one unit), holding >= `fraction` of all parameters. They+ are called as modules, so their own unit's hooks gather them."""+ if not fraction or fraction <= 0:+ return []+ total = sum(p.numel() for p in model.parameters())+ if total == 0:+ return []+ inside = set()+ for u in units:+ for p in u.parameters():+ inside.add(id(p))+ skip = set()+ for getter in ("get_input_embeddings", "get_output_embeddings"):+ try:+ module = getattr(model, getter)()+ except Exception:+ module = None+ if isinstance(module, nn.Module):+ skip.update(id(p) for p in module.parameters())+ owners = {}+ for module in model.modules():+ for p in module.parameters(recurse = False):+ owners.setdefault(id(p), set()).add(id(module))+ extra = []+ for _, module in model.named_modules():+ if not isinstance(module, nn.Embedding):+ continue+ params = list(module.parameters())+ if not params or any(id(p) in inside or id(p) in skip for p in params):+ continue+ if any(len(owners.get(id(p), ())) > 1 for p in params): # tied elsewhere+ continue+ if sum(p.numel() for p in params) >= fraction * total:+ extra.append(module)+ return extra+++_FLOAT8 = tuple(+ getattr(torch, name)+ for name in (+ "float8_e4m3fn",+ "float8_e5m2",+ "float8_e4m3fnuz",+ "float8_e5m2fnuz",+ "float8_e8m0fnu",+ )+ if hasattr(torch, name)+)+++def _float8_params(model):+ """FP8 weights: FSDP2's mixed precision would cast them to the gather dtype (a floating dtype), dropping+ the scale semantics. Frozen ones stay replicated in float8; trainable ones are refused."""+ found = [(n, p) for n, p in model.named_parameters() if p.dtype in _FLOAT8]+ trainable = [n for n, p in found if p.requires_grad]+ if trainable:+ raise NotImplementedError(+ f"Unsloth: native FSDP2 cannot shard trainable float8 parameters (e.g. {trainable[0]}); FSDP2's "+ "gather would cast them. Train LoRA on a frozen FP8 base, or load in 16-bit."+ )+ if found:+ _print_rank0(+ f"Unsloth: native FSDP2 keeps {len(found)} frozen float8 weights replicated (FSDP2 would cast them "+ "to the gather dtype)."+ )+ return {p for _, p in found}+++_GENERATE_DEPTH = [0]+++def _wrap_generate(model):+ """Run `generate` (the root's and every inner module's that has one) inside native_fsdp2_unsharded."""+ import weakref++ root = weakref.ref(model)+ for module in model.modules():+ generate = getattr(module, "generate", None)+ if not callable(generate) or getattr(generate, _PATCHED, False):+ continue+ if not hasattr(type(module), "generate"):+ continue++ def wrapped(+ *args,+ _generate = generate,+ **kwargs,+ ):+ target = root()+ if target is None or _GENERATE_DEPTH[0] > 0:+ return _generate(*args, **kwargs)+ _GENERATE_DEPTH[0] += 1+ try:+ with native_fsdp2_unsharded(target), torch.no_grad():+ return _generate(*args, **kwargs)+ finally:+ _GENERATE_DEPTH[0] -= 1++ functools.update_wrapper(wrapped, generate)+ setattr(wrapped, _PATCHED, True)+ module.generate = wrapped+++def _all_trainable_float32(model):+ """Every trainable floating parameter is float32 (LoRA masters), none 16-bit (full FT, embeddings)."""+ trainable = [p for p in model.parameters() if p.requires_grad and _floating(p)]+ return bool(trainable) and all(p.dtype == torch.float32 for p in trainable)+++def _agree_over_ranks(+ dist,+ device,+ flags,+ mesh = None,+):+ """Every rank must pick the same layout (a per-rank memory heuristic could differ on mixed GPUs):+ elementwise AND of the boolean flags over the ranks of `mesh` (FSDP2Config.mesh; the world for+ the default mesh), so disjoint sub-meshes decide on their own and a sub-group shards without the+ other ranks calling in. At shard time only."""+ if not flags:+ return flags+ from .fsdp2_save import mesh_all_reduce++ t = torch.tensor([1 if f else 0 for f in flags], dtype = torch.int32, device = device)+ ranks = mesh_all_reduce(t, mesh, dist)+ return [int(v) == ranks for v in t.tolist()]+++def _place_replicated(params, device):+ """Parameters left out of FSDP (ignored_params) are never moved by it: they must already sit on this+ rank's device. Moves plain ones that do not; refuses meta (a meta / broadcast load must materialise+ them first) and bitsandbytes 4-bit weights (moving them would re-quantize)."""+ moved = 0+ for p in params:+ if p.device == device:+ continue+ if p.device.type == "meta" or _is_quantized_param(p):+ raise RuntimeError(+ f"Unsloth: native FSDP2 keeps this {tuple(p.shape)} parameter replicated, but it is on "+ f"{p.device}, not {device}. Load the model onto each rank's device first."+ )+ p.data = p.data.to(device)+ moved += 1+ return moved+++def _refuse_block_swap(model):+ """Unsloth block swap (offload_layers = N or "auto", `_unsloth_block_swap`) keeps decoder layers in+ host RAM behind 0-element placeholders it rebinds each step; fully_shard would turn those into+ DTensors. Refused before any change. Every "auto" rank refuses, also one that swapped nothing, so+ no rank shards alone (the peers would hang)."""+ swapped = 0+ auto = False+ for module in model.modules():+ d = module.__dict__+ swapper = d.get("_unsloth_block_swap", None)+ if swapper is not None:+ swapped = max(swapped, len(getattr(swapper, "indices", None) or ()))+ auto = auto or bool(d.get("_unsloth_offload_layers_auto_ddp", False))+ auto = auto or d.get("_unsloth_offload_layers_auto", None) is not None+ if auto or swapped:+ what = "'auto'" if auto else str(swapped)+ raise ValueError(+ f"Unsloth: offload_layers = {what} (this rank swapped {swapped} decoder layers to host "+ "RAM) cannot be combined with native FSDP2 (UNSLOTH_FSDP2=1), which shards the weights "+ "itself and cannot wrap swapped layers. Load with offload_layers = 0 (and "+ "get_peft_model(offload_layers = 0)), or launch without UNSLOTH_FSDP2."+ )+++def shard_model(model, config: Optional[FSDP2Config] = None):+ """fully_shard(unit) for each unit of `find_shard_units`, then fully_shard(model): the root holds+ embeddings, final norm, lm_head and any leftover parameters, so Unsloth's direct lm_head.weight+ read in the fused CE runs while the root is unsharded. Pass the outermost module the training+ loop calls (the PeftModel for LoRA): peft calls the inner model's `.forward` directly, which+ would skip an inner root's hooks. Idempotent.++ Layout (fsdp2_perf.plan_fsdp2_layout): when the model fits on one GPU and reshard_after_forward is+ auto, frozen weights stay replicated (never gathered, like DDP), only trainable ones are sharded and+ kept gathered from forward to backward with next-block prefetch, and a small trainable set (LoRA) is+ one root unit. Otherwise each block reshards after forward."""+ if getattr(model, _NATIVE_FLAG, False):+ return model+ _refuse_block_swap(model)+ FSDPModule, MixedPrecisionPolicy, fully_shard = _fsdp_api()+ if isinstance(model, FSDPModule):+ raise RuntimeError(+ "Unsloth: this model is already wrapped by FSDP2 outside Unsloth; native FSDP2 will not "+ "wrap it again."+ )+ config = config or FSDP2Config.from_env()+ units = list(config.units) if config.units is not None else find_shard_units(model)+ extra_units = (+ _large_root_embeddings(model, units, config.split_large_root_embeddings)+ if config.units is None+ else []+ )+ check_shard_units(model, units + extra_units)+ _refuse_tensor_parallel_model(model)+ device = _shard_device(model, config.device)+ dist = _ensure_process_group(device, config.backend, config.timeout)+ if device.type == "cuda":+ torch.cuda.set_device(device)+ mesh = config.mesh if config.mesh is not None else _default_mesh(device, dist)+ param_dtype = _resolve_param_dtype(model, config)+ mp_policy = MixedPrecisionPolicy(param_dtype = param_dtype, reduce_dtype = config.reduce_dtype)+ _patch_recompute_input_cast() # before any fully_shard registers FSDPState._pre_forward+ offload_policy = None+ if config.cpu_offload:+ CPUOffloadPolicy = _fsdp_attr("CPUOffloadPolicy")+ offload_policy = CPUOffloadPolicy(pin_memory = device.type == "cuda")+ from .fsdp2_perf import (+ _env_tristate,+ plan_fsdp2_layout,+ resolve_reshard_after_forward,+ shard_model_layout,+ )++ layout = plan_fsdp2_layout(+ model,+ param_dtype = param_dtype,+ reshard_after_forward = config.reshard_after_forward,+ device = device, # a CPU mesh has no GPU capacity: the per-block sharded layout+ cpu_offload = config.cpu_offload,+ fits = config.fit_layout,+ replicate_frozen = None if config.shard_frozen is None else not config.shard_frozen,+ allow_root_only = config.units is None,+ )+ if (+ layout.replicate_frozen+ and config.shard_frozen is None+ and _env_tristate("UNSLOTH_FSDP2_REPLICATE_FROZEN") is not True+ and not _supports_ignored_params(fully_shard)+ ):+ # Automatic fit layout on a torch whose fully_shard has no ignored_params (2.6): shard the+ # frozen weights too. An explicit replication request still fails below. Before the agreement,+ # which every rank then reaches with the same answer.+ layout.replicate_frozen = False+ layout.root_only = False+ layout.reasons.append("replicate_frozen=False (fully_shard has no ignored_params)")+ layout.fits, layout.replicate_frozen, layout.root_only, layout.prefetch = _agree_over_ranks(+ dist,+ device,+ [layout.fits, layout.replicate_frozen, layout.root_only, layout.prefetch],+ config.mesh,+ )+ # reshard_after_forward is derived from `fits` (when not set by config / env): derive it again from+ # the agreed value, or a rank that fit alone keeps its blocks gathered while the others reshard, and+ # their backward collectives no longer match.+ resolve_reshard_after_forward(layout, config.reshard_after_forward, note = False)+ gather_dtype = param_dtype+ if (+ config.param_dtype is None+ and layout.replicate_frozen+ and param_dtype in (torch.bfloat16, torch.float16)+ and _all_trainable_float32(model)+ ):+ # Fit layout: FSDP2 manages only trainable parameters. One GPU keeps float32 masters (LoRA) and+ # lets autocast cast them at each op; a 16-bit gather casts them first, which moved Gemma4's step-0+ # grad norm 0.2% off 1 GPU (A/A 0.01%). Gather them as they are; the 4-bit storage stays 16-bit.+ gather_dtype = None+ mp_policy = MixedPrecisionPolicy(param_dtype = None, reduce_dtype = config.reduce_dtype)+ if not units and not layout.root_only:+ _print_rank0(+ "Unsloth: native FSDP2 found no repeated blocks in this model; only the root is sharded "+ "(every forward gathers all weights)."+ )+ with contextlib.ExitStack() as stack:+ infos = {+ name: stack.enter_context(factory(model, param_dtype = param_dtype))+ for name, factory in _SHARD_CONTEXTS.items()+ }+ qlora = infos.get("bnb_qlora")+ ignored, _ = _unify_dtypes(+ model,+ # Root only: every trainable param is in the root group. Otherwise the split root+ # embedding tables are units of their own, not part of the root's dtype group.+ [] if layout.root_only else units + list(extra_units),+ param_dtype,+ can_ignore = config.replicate_minority_dtype and _supports_ignored_params(fully_shard),+ )+ ignored = set(ignored)+ ignored.update(_float8_params(model))+ int8 = _int8_params(model)+ if int8 and not _supports_ignored_params(fully_shard):+ raise RuntimeError(+ "Unsloth: native FSDP2 keeps bitsandbytes 8-bit (load_in_8bit) weights replicated, which "+ f"needs torch with fully_shard(ignored_params) (2.7+); this is torch {torch.__version__}. "+ "Upgrade torch, or load the model in 4-bit or 16-bit."+ )+ ignored.update(int8)+ if config.ignored_params:+ ignored.update(config.ignored_params)+ replicated = set(ignored)+ if layout.replicate_frozen:+ replicated.update(p for p in model.parameters() if not p.requires_grad)+ if replicated:+ if not _supports_ignored_params(fully_shard):+ raise RuntimeError(+ f"Unsloth: native FSDP2 needs torch with fully_shard(ignored_params) (2.7+) to keep "+ f"parameters replicated; this is torch {torch.__version__}."+ )+ _place_replicated(replicated, device)+ wrapped = shard_model_layout(+ model,+ units,+ mp_policy,+ layout,+ mesh = mesh,+ offload_policy = offload_policy,+ ignored_params = ignored,+ extra_units = extra_units,+ fully_shard_fn = functools.partial(_fully_shard, fully_shard),+ reshard_last_block = config.reshard_last_block,+ unit_reshard_after_forward = config.unit_reshard_after_forward,+ forward_prefetch = config.forward_prefetch,+ backward_prefetch = config.backward_prefetch,+ shard_kwargs = (+ {"shard_placement_fn": config.shard_placement_fn}+ if config.shard_placement_fn is not None+ else None+ ),+ )+ model._unsloth_reshard_after_forward = False+ setattr(model, _NATIVE_FLAG, True)+ for param in model.parameters():+ # An optimizer over these is a native one even before (or without) its model is prepared.+ try:+ param._unsloth_fsdp2_native_param = True+ except Exception:+ pass+ model._unsloth_fsdp2_blocks = len(wrapped)+ model._unsloth_fsdp2_units = wrapped+ model._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:+ _wrap_generate(model)+ model._unsloth_fsdp2_mp_policy = mp_policy+ model._unsloth_fsdp2_replicated = sum(1 for p in model.parameters() if p in replicated)+ # The replicated-gradient average and the media agreement run over this mesh's ranks only.+ model.__dict__["_unsloth_fsdp2_mesh"] = mesh+ _post_shard(model, units, device, root_only = layout.root_only)+ from .fsdp2_vision import install_vision_dummy++ install_vision_dummy(model) # mixed image / text ranks+ _patch_accumulated_grad_guard()+ if qlora is not None:+ # Trainer / DCP checkpoints of the sharded 4-bit weights (fsdp2_save).+ from .fsdp2_save import install_dcp_bnb_state_dict+ install_dcp_bnb_state_dict()+ install_native_fsdp2_hooks()+ classes = sorted({type(u).__name__.removeprefix("FSDP") for u in wrapped})+ note = ""+ if qlora is not None:+ note = f", {qlora.get('params4bit', 0)} 4-bit weights packed as {'/'.join(qlora.get('storage', []))}"+ if layout.fits:+ shape = (+ "trainable params in one root unit"+ if layout.root_only+ else f"{len(wrapped)} blocks ({', '.join(classes) or 'none'}) + root, kept gathered"+ )+ frozen = "frozen weights replicated (never gathered)" if layout.replicate_frozen else ""+ what = f"(the model fits one GPU) {shape}{', ' + frozen if frozen else ''}"+ else:+ what = f"{len(wrapped)} blocks ({', '.join(classes) or 'none'}) + root"+ _print_rank0(+ f"Unsloth: native FSDP2 sharded {what}, over {dist.get_world_size()} ranks; gather dtype "+ f"{str(gather_dtype).replace('torch.', '') if gather_dtype is not None else 'as stored'}, reduce dtype "+ f"{str(config.reduce_dtype).replace('torch.', '')}{note}."+ )+ return model+++# --------------------------------------------------------------------------------------------------+# Training-loop pieces: grad clipping, grad accumulation, full state dict+# --------------------------------------------------------------------------------------------------+++def native_clip_grad_norm_(+ parameters,+ max_norm,+ norm_type = 2.0,+):+ """Global gradient norm over DTensor (sharded) and plain gradients; clips in place and returns a+ plain float32 tensor (the same value on every rank)."""+ import torch.distributed as dist++ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ from torch.distributed._tensor import DTensor+ if isinstance(parameters, torch.Tensor):+ parameters = [parameters]+ params = [p for p in parameters if p is not None and p.grad is not None]+ norm_type = float(norm_type)+ device = None+ sharded, replicated = [], []+ # Per (mesh, mesh dims the gradient is sharded over): a user mesh may be 2-D (HSDP: replicate x+ # shard) or a submesh, and a local shard repeats along Replicate dims, so its partial norm reduces+ # over the Shard dims' groups only (what DTensor's own norm does, _NormPartial).+ groups = {}+ for p in params:+ g = p.grad+ if isinstance(g, DTensor):+ local = g.to_local()+ dims = tuple(i for i, pl in enumerate(g.placements) if pl.is_shard())+ groups.setdefault((g.device_mesh, dims), []).append(local)+ sharded.append(local)+ device = device or local.device+ else:+ replicated.append(g)+ device = device or g.device+ if device is None:+ return torch.tensor(0.0)+ if device.type == "cpu" and torch.cuda.is_available() and dist.is_initialized():+ if dist.get_backend() == "nccl":+ device = torch.device("cuda", torch.cuda.current_device())+ initialized = dist.is_available() and dist.is_initialized()+ p = norm_type++ def _per_tensor(grads):+ """One float64 norm per tensor (torch.linalg.vector_norm semantics); an empty local shard+ (uneven sharding: dim 0 smaller than the world) is the identity of the combine. 0 for p >= 0;+ +inf for every negative p (its p-th power is 0, and -inf takes the min), where vector_norm+ itself refuses an empty tensor."""+ if not grads:+ return torch.zeros(0, device = device, dtype = torch.float64)+ empty = math.inf if p < 0 else 0.0+ live = [g.detach() for g in grads if g.numel()]+ try:+ norms = list(torch._foreach_norm(live, p)) if live else []+ except Exception:+ norms = [torch.linalg.vector_norm(g, p) for g in live]+ it = iter(norms)+ return torch.stack(+ [+ next(it).double().to(device)+ if g.numel()+ else torch.tensor(empty, device = device, dtype = torch.float64)+ for g in grads+ ]+ )++ # torch.nn.utils.clip_grad_norm_ is vector_norm(stack(per-tensor norms), p): for p = 0 the number+ # of tensors with a nonzero element, for +-inf the max / min, else the p-th root of the sum of+ # p-th powers. A sharded tensor's norm combines over ranks first (counts and powers add up).+ replicated_norms = _per_tensor(replicated)++ def _over_shards(value, op, mesh, dims):+ if initialized:+ for dim in dims:+ dist.all_reduce(value, op = op, group = mesh.get_group(dim))+ return value++ if p == 0:+ total = (replicated_norms > 0).sum().double()+ for (mesh, dims), grads in groups.items():+ counts = _over_shards(_per_tensor(grads), dist.ReduceOp.SUM, mesh, dims)+ total = total + (counts > 0).sum().double()+ elif p in (math.inf, -math.inf):+ pick, op = (torch.max, dist.ReduceOp.MAX) if p > 0 else (torch.min, dist.ReduceOp.MIN)+ total = torch.tensor(0.0 if p > 0 else math.inf, device = device, dtype = torch.float64)+ parts = [pick(replicated_norms)] if replicated_norms.numel() else []+ for (mesh, dims), grads in groups.items():+ parts.append(_over_shards(pick(_per_tensor(grads)), op, mesh, dims))+ if parts:+ total = pick(torch.stack(parts))+ else:+ total = replicated_norms.pow(p).sum()+ for (mesh, dims), grads in groups.items():+ powers = _per_tensor(grads).pow(p).sum()+ total = total + _over_shards(powers, dist.ReduceOp.SUM, mesh, dims)+ total = total.pow(1.0 / p)+ clip_coef = float(max_norm) / (total + 1e-6)+ clip_coef = torch.clamp(clip_coef, max = 1.0).float()+ total = total.float()+ grads = sharded + replicated+ if grads:+ by_device = {}+ for g in grads:+ by_device.setdefault((g.device, g.dtype), []).append(g)+ for (dev, _), group in by_device.items():+ torch._foreach_mul_(group, clip_coef.to(dev))+ return total+++def native_full_state_dict(+ model,+ trainable_only = False,+ cpu_offload = True,+):+ """Collective: every rank must call. Full (unsharded) state dict on rank 0, {} on the others."""+ from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict++ options = StateDictOptions(+ full_state_dict = True,+ cpu_offload = cpu_offload,+ ignore_frozen_params = bool(trainable_only),+ )+ return get_model_state_dict(model, options = options)+++def native_fsdp2_unsharded(model):+ """Collective (every rank must enter): gather every unit's whole weights and keep them gathered,+ for code that reads weights without calling the blocks (Unsloth's decode loop, `PeftModel.generate`,+ which skips the root's hooks, merges). Resharded on exit. A no-op for a model not sharded natively."""+ FSDPModule = _fsdp_module_class()+ if FSDPModule is None or not is_native_fsdp2(model):+ yield model+ return+ # Re-entrant: the wrapped generate() enters again inside an outer block. Only the outermost+ # enter gathers and only the outermost exit reshards (per sharded root).+ root = _native_root(model)+ depth = root.__dict__.get("_unsloth_unsharded_depth", 0)+ root.__dict__["_unsloth_unsharded_depth"] = depth + 1+ if depth > 0:+ try:+ yield model+ finally:+ root.__dict__["_unsloth_unsharded_depth"] -= 1+ return+ units = [m for m in model.modules() if isinstance(m, FSDPModule)]+ try:+ for unit in units:+ unit.set_reshard_after_forward(False, recurse = False)+ for unit in units:+ unit.unshard()+ yield model+ finally:+ root.__dict__["_unsloth_unsharded_depth"] = 0+ for unit in units:+ unit.reshard()+ unit.set_reshard_after_forward(+ getattr(unit, "_unsloth_reshard_after_forward", True), recurse = False+ )+++def _no_grad_sync(model):+ model.set_requires_gradient_sync(False)+ try:+ yield+ finally:+ model.set_requires_gradient_sync(True)+++def _native_models(accelerator):+ return [m for m in getattr(accelerator, "_models", []) if is_native_fsdp2(m)]+++# Set by Trainer.create_accelerator_and_postprocess on the accelerator a Trainer owns.+_TRAINER_ACCELERATOR = "_unsloth_fsdp2_trainer_accelerator"++_CUSTOM_LOOP_REFUSAL = (+ "Unsloth: native FSDP2 (UNSLOTH_FSDP2=1 / shard_model) supports the Hugging Face / TRL Trainer, "+ "and plain PyTorch loops over shard_model(model) with the native helpers "+ "(unsloth.models.fsdp2_native: native_clip_grad_norm_, native_full_state_dict, "+ "native_save_optimizer, native_load_model_checkpoint, native_load_optimizer). "+ "accelerator.prepare() of a natively sharded model or its optimizer outside a Trainer is not "+ "supported: accelerate would treat the sharded model as unsharded (FP8 conversion, save_state / "+ "load_state, device placement). Drop accelerator.prepare for the model and optimizer, or use "+ "UNSLOTH_FSDP2_BACKEND=accelerate for an accelerate-managed FSDP2 loop."+)+++def _native_object(obj):+ """A natively sharded model (or a wrapper of one), an optimizer over its parameters, or an LR+ scheduler over such an optimizer."""+ if isinstance(obj, nn.Module):+ return is_native_fsdp2(obj)+ if isinstance(obj, torch.optim.Optimizer) or hasattr(obj, "param_groups"):+ return _native_optimizer(obj)+ inner = getattr(obj, "optimizer", None)+ return inner is not None and hasattr(inner, "param_groups") and _native_optimizer(inner)+++def _accelerator_fp8(accelerator):+ """accelerate converts Linear layers to FP8 (Transformer Engine / torchao / MS-AMP) inside+ Accelerator.prepare, before prepare_model."""+ if str(getattr(accelerator, "mixed_precision", "no") or "no").lower() == "fp8":+ return True+ try:+ backend = accelerator.fp8_backend+ except Exception:+ return False+ backend = getattr(backend, "value", backend)+ return backend is not None and str(backend).strip().upper() not in ("", "NO", "NONE")+++def _refuse_untrusted_accelerator(accelerator, objects):+ """Native objects are prepared only by a Trainer's accelerator, never with FP8 conversion."""+ if not any(_native_object(obj) for obj in objects):+ return+ if not getattr(accelerator, _TRAINER_ACCELERATOR, False):+ raise RuntimeError(_CUSTOM_LOOP_REFUSAL)+ if _accelerator_fp8(accelerator):+ raise RuntimeError(+ "Unsloth: native FSDP2 cannot train with accelerate's FP8 (mixed_precision = 'fp8' or "+ "ACCELERATE_FP8_BACKEND): accelerate converts the layers after Unsloth sharded them. Use "+ "bf16 / fp16, or UNSLOTH_FSDP2_BACKEND=accelerate."+ )+++def split_param_groups(params_or_groups):+ """Optimizer parameter groups for a natively sharded model: foreach / fused optimizer kernels cannot+ take DTensor (sharded) and plain (replicated) tensors in one list, so each group comes back as one+ group per kind with the same hyperparameters. Takes `model.parameters()` (or any iterable of+ tensors) or a list of group dicts. Build the optimizer from this before an LR scheduler:+ `torch.optim.AdamW(split_param_groups(p for p in model.parameters() if p.requires_grad), lr = ...)`."""+ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ from torch.distributed._tensor import DTensor+ items = list(params_or_groups)+ if items and not isinstance(items[0], dict):+ items = [{"params": items}]+ out = []+ for group in items:+ params = list(group["params"])+ sharded = [p for p in params if isinstance(p, DTensor)]+ plain = [p for p in params if not isinstance(p, DTensor)]+ rest = {k: v for k, v in group.items() if k != "params"}+ out.extend({**rest, "params": kind} for kind in (sharded, plain) if kind)+ if not params:+ out.append({**rest, "params": []})+ return out+++def _mixed_param_groups(optimizer):+ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ from torch.distributed._tensor import DTensor+ groups = getattr(_inner_optimizer(optimizer), "param_groups", None) or []+ return sum(+ 1+ for g in groups+ if any(isinstance(p, DTensor) for p in g["params"])+ and any(not isinstance(p, DTensor) for p in g["params"])+ )+++def _split_mixed_param_groups(optimizer):+ """Split mixed DTensor / plain groups in place (split_param_groups). Before the first step only,+ and only where no LR scheduler was built yet (the Trainer refuses a prebuilt pair)."""+ groups = getattr(optimizer, "param_groups", None)+ if not groups or getattr(optimizer, "state", None):+ return 0+ splits = _mixed_param_groups(optimizer)+ if splits:+ optimizer.param_groups[:] = split_param_groups(groups)+ return splits+++def _install_accelerate_hooks():+ try:+ from accelerate import Accelerator+ except Exception:+ return False+ if getattr(Accelerator, _PATCHED, False):+ return True++ original_prepare = Accelerator.prepare++ @functools.wraps(original_prepare)+ def prepare(self, *args, **kwargs):+ # Before accelerate's FP8 conversion, which runs here ahead of prepare_model.+ _refuse_untrusted_accelerator(self, args)+ return original_prepare(self, *args, **kwargs)++ original_prepare_model = Accelerator.prepare_model++ @functools.wraps(original_prepare_model)+ def prepare_model(+ self,+ model,+ device_placement = None,+ evaluation_mode = False,+ ):+ if not is_native_fsdp2(model):+ return original_prepare_model(+ self, model, device_placement = device_placement, evaluation_mode = evaluation_mode+ )+ _refuse_untrusted_accelerator(self, [model])+ # Already sharded by Unsloth: keep accelerate's autocast wrap of forward (as one GPU gets),+ # skip device placement and the DDP / FSDP wrap (evaluation_mode skips exactly those).+ if getattr(model, "_is_accelerate_prepared", False):+ if model not in self._models:+ self._models.append(model)+ return model+ return original_prepare_model(self, model, device_placement = False, evaluation_mode = True)++ original_no_sync = Accelerator.no_sync++ @contextlib.contextmanager+ def no_sync(self, model):+ target = model+ if not is_native_fsdp2(target):+ with original_no_sync(self, model):+ yield+ return+ root = (+ getattr(target, "module", None) if not getattr(target, _NATIVE_FLAG, False) else target+ )+ root = root if root is not None else target+ with _no_grad_sync(root):+ yield++ no_sync.__doc__ = original_no_sync.__doc__++ original_clip = Accelerator.clip_grad_norm_++ @functools.wraps(original_clip)+ def clip_grad_norm_(+ self,+ parameters,+ max_norm,+ norm_type = 2,+ ):+ if not _native_models(self):+ return original_clip(self, parameters, max_norm, norm_type = norm_type)+ self.unscale_gradients()+ return native_clip_grad_norm_(list(parameters), max_norm, norm_type)++ original_prepare_optimizer = Accelerator.prepare_optimizer++ @functools.wraps(original_prepare_optimizer)+ def prepare_optimizer(self, optimizer, *args, **kwargs):+ # From the optimizer's own parameters too: prepare(optimizer, model) prepares in the order+ # given, so the native model may not be registered in `_models` yet.+ native = bool(_native_models(self)) or _native_optimizer(optimizer)+ if native:+ _refuse_untrusted_accelerator(self, [optimizer] if _native_optimizer(optimizer) else [])+ _refuse_bnb_optimizer_instance(optimizer)+ if native and _mixed_param_groups(optimizer):+ if getattr(_inner_optimizer(optimizer), "state", None):+ # The split carries no per-parameter state over; a mixed group stepping a foreach /+ # fused kernel over DTensor and plain tensors fails.+ raise RuntimeError(_MIXED_GROUPS_REFUSAL)+ if native and _split_mixed_param_groups(getattr(optimizer, "optimizer", optimizer)):+ _print_rank0(+ "Unsloth: native FSDP2 split optimizer groups mixing sharded and replicated parameters "+ "after the optimizer was built; an LR scheduler built before this keeps the old groups."+ )+ return original_prepare_optimizer(self, optimizer, *args, **kwargs)++ original_get_state_dict = Accelerator.get_state_dict++ @functools.wraps(original_get_state_dict)+ def get_state_dict(+ self,+ model,+ unwrap = True,+ ):+ if not is_native_fsdp2(model):+ return original_get_state_dict(self, model, unwrap = unwrap)+ # accelerate's non-FSDP branch would return this rank's DTensor shards. Collective: the full+ # state dict on rank 0, {} elsewhere (save_model writes from the main process only).+ return native_full_state_dict(_native_root(model))++ def _refuse_state(name, original):+ @functools.wraps(original)+ def wrapped(self, *args, **kwargs):+ if _native_models(self) or any(+ _native_optimizer(o) for o in getattr(self, "_optimizers", [])+ ):+ raise RuntimeError(+ f"Unsloth: accelerator.{name}() would save / load each natively sharded model and "+ "optimizer as this rank's DTensor shards (accelerate treats the model as unsharded). "+ "Use unsloth.models.fsdp2_native.native_full_state_dict / native_save_optimizer and "+ "native_load_model_checkpoint / native_load_optimizer (collective), "+ "accelerator.save_model / get_state_dict (full weights), or Trainer checkpoints."+ )+ return original(self, *args, **kwargs)++ return wrapped++ Accelerator.get_state_dict = get_state_dict+ Accelerator.save_state = _refuse_state("save_state", Accelerator.save_state)+ Accelerator.load_state = _refuse_state("load_state", Accelerator.load_state)+ Accelerator.prepare = prepare+ Accelerator.prepare_model = prepare_model+ Accelerator.prepare_optimizer = prepare_optimizer+ Accelerator.no_sync = no_sync+ Accelerator.clip_grad_norm_ = clip_grad_norm_+ setattr(Accelerator, _PATCHED, True)+ return True+++# --------------------------------------------------------------------------------------------------+# Checkpoint resume: optimizer state and model weights of a sharded model+# --------------------------------------------------------------------------------------------------++_OPTIMIZER_NAME = "optimizer.pt"+_SCHEDULER_NAME = "scheduler.pt"+++def _native_root(model):+ """The module shard_model wrapped (the Trainer may hold it directly, under `.module`, or under+ torch.compile's `_orig_mod`). Wrappers are peeled by their registered child, not by attribute+ lookup: OptimizedModule (and PeftModel) forward unknown attributes, so the wrapper itself would+ answer the native flag."""+ current = model+ for _ in range(8):+ children = getattr(current, "_modules", None) or {}+ inner = next(+ (+ children[attr]+ for attr in ("_orig_mod", "module")+ if isinstance(children.get(attr), nn.Module)+ and getattr(children[attr], _NATIVE_FLAG, False)+ ),+ None,+ )+ if inner is None:+ break+ current = inner+ return current+++def _inner_optimizer(optimizer):+ """accelerate's AcceleratedOptimizer wraps the torch optimizer as `.optimizer`."""+ while isinstance(getattr(optimizer, "optimizer", None), torch.optim.Optimizer):+ optimizer = optimizer.optimizer+ return optimizer+++def native_save_optimizer(+ model,+ optimizer,+ path = None,+ 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."""+ from torch.distributed.checkpoint.state_dict import StateDictOptions, get_optimizer_state_dict++ model = _native_root(model)+ optimizer = _inner_optimizer(optimizer)+ state = get_optimizer_state_dict(+ model,+ optimizer,+ options = StateDictOptions(full_state_dict = True, cpu_offload = True),+ )+ if should_save is None:+ should_save = _rank0()+ if path is None:+ return state+ from .fsdp2_save import _dist, _wait_for_writer++ dist = _dist()+ writer = bool(should_save)+ try:+ if writer:+ torch.save(state, path)+ finally:+ if dist is not None:+ # 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)+ return state+++def native_load_optimizer(model, optimizer, path_or_state):+ """Collective: every rank reads the full optimizer state (CPU) and keeps only its own shards."""+ from torch.distributed.checkpoint.state_dict import StateDictOptions, set_optimizer_state_dict++ state = path_or_state+ if not isinstance(state, dict):+ state = torch.load(state, map_location = "cpu", weights_only = True)+ set_optimizer_state_dict(+ _native_root(model),+ _inner_optimizer(optimizer),+ state,+ options = StateDictOptions(full_state_dict = True),+ )+ return state+++_WEIGHT_FILES = (+ "adapter_model.safetensors",+ "adapter_model.bin",+ "model.safetensors",+ "pytorch_model.bin",+)+_WEIGHT_INDEXES = ("model.safetensors.index.json", "pytorch_model.bin.index.json")+++def _read_checkpoint_weights(checkpoint):+ import json++ def _read(path):+ if path.endswith(".safetensors"):+ from safetensors.torch import load_file+ return load_file(path, device = "cpu")+ return torch.load(path, map_location = "cpu", weights_only = True)++ for name in _WEIGHT_FILES:+ path = os.path.join(checkpoint, name)+ if os.path.isfile(path):+ return _read(path), name.startswith("adapter_")+ for name in _WEIGHT_INDEXES:+ path = os.path.join(checkpoint, name)+ if os.path.isfile(path):+ with open(path, encoding = "utf-8") as f:+ files = sorted(set(json.load(f)["weight_map"].values()))+ state = {}+ for shard in files:+ state.update(_read(os.path.join(checkpoint, shard)))+ return state, False+ raise ValueError(f"Unsloth: native FSDP2 found no model or adapter weights in {checkpoint}.")+++def _peft_saved_key(key, adapter):+ """PEFT's own model-key -> checkpoint-key rule (_remove_adapter_name_from_state_dict_key): a+ ParameterDict entry (lora_embedding_A.<adapter>) drops the terminal `.<adapter>`, a module-backed+ one (lora_A.<adapter>.weight) the `.<adapter>` before the last segment, never one mid-path."""+ if "." not in key:+ return key+ if key.endswith(f".{adapter}"):+ return key[: -len(adapter) - 1]+ head, _, suffix = key.rpartition(".")+ if head.endswith(f".{adapter}"):+ head = head[: -len(adapter) - 1]+ key = f"{head}.{suffix}"+ if key.endswith(".lora_magnitude_vector.weight"):+ # LoraModel._get_adapter_state_dict: DoRA's magnitude (a DoraLinearLayer's weight since the+ # ParameterDict -> ModuleDict refactor) is still saved without ".weight".+ key = key[: -len(".weight")]+ return key+++def _peft_save_keys(root, adapter):+ """model key -> checkpoint key for `adapter`, from PEFT's own save path+ (peft.utils.get_peft_model_state_dict, peft/utils/save_and_load.py): every key rule the installed+ PEFT applies on save (adapter name removal, DoRA's lora_magnitude_vector, modules_to_save, later+ ones) is inverted here. PEFT is handed empty placeholder tensors (no collective, no copy) and the+ returned keys are matched back by tensor identity; {} when PEFT cannot be asked, and the rule above+ stands in."""+ try:+ from peft.utils import get_peft_model_state_dict+ except Exception:+ return {}+ import warnings++ names = [n for n, _ in root.named_parameters()] + [n for n, _ in _persistent_buffers(root)]+ placeholders = {n: torch.empty(0) for n in names}+ by_id = {id(t): n for n, t in placeholders.items()}+ try:+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ out = get_peft_model_state_dict(+ root,+ state_dict = dict(placeholders),+ adapter_name = adapter,+ save_embedding_layers = False,+ )+ except Exception:+ return {}+ return {by_id[id(v)]: k for k, v in out.items() if id(v) in by_id}+++def _has_checkpoint_weights(directory):+ return any(+ os.path.isfile(os.path.join(directory, name)) for name in _WEIGHT_FILES + _WEIGHT_INDEXES+ )+++def _adapter_owner(root, adapters):+ """name -> the adapter a parameter belongs to, or None: PEFT keys adapter weights by name under+ a tuner layer's `adapter_layer_names` (lora_A.<adapter>.weight, lora_embedding_A.<adapter>) and+ under modules_to_save.<adapter>. Matching only those segments keeps a module path that merely+ equals an adapter name (layers.0, mlp) from counting."""+ containers = {"modules_to_save"}+ for module in root.modules():+ names = getattr(module, "adapter_layer_names", None)+ if isinstance(names, (list, tuple)):+ containers.update(n for n in names if isinstance(n, str))+ adapters = set(adapters)++ def owner(name):+ parts = name.split(".")+ for i in range(len(parts) - 1):+ if parts[i] in containers and parts[i + 1] in adapters:+ return parts[i + 1]+ return None++ return owner+++def _persistent_buffers(root):+ out = []+ for module_name, module in root.named_modules():+ skip = getattr(module, "_non_persistent_buffers_set", ())+ for name, buf in module.named_buffers(recurse = False):+ if buf is not None and name not in skip:+ out.append((f"{module_name}.{name}" if module_name else name, buf))+ return out+++def native_load_model_checkpoint(model, checkpoint):+ """Collective: load a Trainer checkpoint's weights (PEFT adapter or full model, as save_model wrote+ them) into a natively sharded model with `set_model_state_dict(full_state_dict)`. PEFT's saved keys+ drop the adapter name; it is put back for each trainable parameter. Raises if a trainable parameter+ has no saved tensor (the resume would silently keep the fresh value)."""+ from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict++ root = _native_root(model)+ adapters = []+ active = getattr(root, "active_adapters", None)+ if isinstance(active, (list, tuple)):+ adapters = [a for a in active if isinstance(a, str)]+ elif isinstance(getattr(root, "active_adapter", None), str):+ adapters = [root.active_adapter]+ peft_config = getattr(root, "peft_config", None) if _is_peft(root) else None+ absent = []+ if isinstance(peft_config, dict) and peft_config:+ # PeftModel.save_pretrained writes every adapter in peft_config: "default" at the checkpoint+ # root, every other one under <checkpoint>/<adapter>/; each file drops its adapter's name from+ # the keys. Active adapters first, so shared tensors (resized embeddings) come from them.+ active_names = [a for a in adapters if a in peft_config]+ adapters = active_names + [a for a in peft_config if a not in active_names]+ sources = []+ for adapter in adapters:+ directory = checkpoint if adapter == "default" else os.path.join(checkpoint, adapter)+ if adapter not in active_names and not _has_checkpoint_weights(directory):+ absent.append(adapter) # an inactive adapter this checkpoint did not save+ continue+ sources.append((adapter, _read_checkpoint_weights(directory)[0]))+ is_adapter = True+ else:+ saved, is_adapter = _read_checkpoint_weights(checkpoint)+ sources = [(adapter, saved) for adapter in adapters] or [(None, saved)]+ owner_of = _adapter_owner(root, adapters)+ loaded = {adapter for adapter, _ in sources}+ save_keys = (+ {adapter: _peft_save_keys(root, adapter) for adapter, _ in sources if adapter is not None}+ if _is_peft(root)+ else {}+ )++ mapped = {}+ missing = []+ # Persistent buffers too (e.g. DeepSeek's routing correction bias): the state dict holds them.+ tensors = list(root.named_parameters()) + _persistent_buffers(root)+ for name, param in tensors:+ owner = owner_of(name)+ if owner in absent:+ continue+ key = None+ # An adapter's own tensors come only from that adapter's file; shared ones (resized+ # embeddings, buffers) from the first file holding them.+ for adapter, saved in sources:+ if owner is not None and adapter != owner:+ continue+ candidates = [name]+ if save_keys.get(adapter, {}).get(name) is not None:+ candidates.insert(0, save_keys[adapter][name])+ if adapter is not None:+ candidates.append(name.replace(f".modules_to_save.{adapter}.", "."))+ candidates.append(_peft_saved_key(name, adapter))+ key = next((c for c in candidates if c in saved), None)+ if key is not None:+ mapped[name] = saved[key]+ break+ # A saved adapter must restore all its tensors, frozen (inactive) ones included.+ if key is None and (param.requires_grad or (owner is not None and owner in loaded)):+ missing.append(name)+ if absent:+ _print_rank0(+ f"Unsloth: native FSDP2 resume: {checkpoint} holds no weights for the inactive adapters "+ f"{absent}; they keep their current values."+ )+ if missing:+ raise RuntimeError(+ f"Unsloth: native FSDP2 resume found no saved tensor for {len(missing)} parameters "+ f"(e.g. {missing[0]}) in {checkpoint}."+ )+ n_loaded = len(mapped) # set_model_state_dict may add entries to the dict it is given+ set_model_state_dict(+ root,+ mapped,+ options = StateDictOptions(full_state_dict = True, strict = False),+ )+ _print_rank0(+ f"Unsloth: native FSDP2 resumed {n_loaded} {'adapter ' if is_adapter else ''}tensors from "+ f"{checkpoint}."+ )+ return n_loaded+++def _save_unwrapped(+ trainer,+ root,+ output_dir,+ state_dict = None,+):+ """Trainer._save with `trainer.model` set to the sharded root for the call: on a wrapper (a+ torch.compile OptimizedModule) _save would take `self.model.state_dict()`, whose `_orig_mod.`+ keys PEFT's adapter selection does not match, and write an empty adapter."""+ held = trainer.model+ trainer.model = root+ try:+ if state_dict is None:+ trainer._save(output_dir)+ else:+ trainer._save(output_dir, state_dict = state_dict)+ finally:+ trainer.model = held+++def _install_trainer_hooks():+ try:+ from transformers import Trainer+ except Exception:+ return False+ if getattr(Trainer, _PATCHED, False):+ return True+ original_save_model = Trainer.save_model++ @functools.wraps(original_save_model)+ def save_model(+ self,+ output_dir = None,+ _internal_call = False,+ ):+ model = getattr(self, "model", None)+ if not is_native_fsdp2(model) or getattr(self, "is_fsdp_enabled", False):+ return original_save_model(self, output_dir, _internal_call = _internal_call)+ if output_dir is None:+ output_dir = self.args.output_dir+ # Collective gather on every rank (the Trainer would only call _save on rank 0). The sharded+ # root, not a torch.compile (`_orig_mod`) / DDP-style (`.module`) wrapper around it: a+ # compiled PeftModel is still an adapter checkpoint, and its state dict keys carry no prefix.+ root = _native_root(model)+ if _is_peft(root):+ # The adapter save also writes frozen tensors (resized embeddings, inactive adapters,+ # modules_to_save): gather those with the trainable ones, PEFT picks what it writes.+ from .fsdp2_save import fsdp2_gathered+ from ..save import _fsdp2_peft_saved_frozen++ 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:+ _save_unwrapped(self, root, output_dir)+ else:+ from .fsdp2_save import _dist, _wait_for_writer++ state_dict = native_full_state_dict(root)+ writer = bool(self.args.should_save)+ try:+ if writer:+ _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)+ 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)++ original_move = getattr(Trainer, "_move_model_to_device", None)++ if original_move is not None:++ @functools.wraps(original_move)+ def _move_model_to_device(self, model, device):+ # shard_model already put every shard and replicated tensor on the mesh device (or keeps+ # the shards on the CPU under CPUOffloadPolicy); Trainer.__init__ only skips this placement+ # for is_fsdp_enabled, which native FSDP2 leaves False. `.to(device)` would move offloaded+ # shards to the GPU.+ if is_native_fsdp2(model):+ return None+ return original_move(self, model, device)++ Trainer._move_model_to_device = _move_model_to_device++ original_create_optimizer = Trainer.create_optimizer++ @functools.wraps(original_create_optimizer)+ def create_optimizer(self, *args, **kwargs):+ optimizer = original_create_optimizer(self, *args, **kwargs)+ if is_native_fsdp2(getattr(self, "model", None)):+ # Before the LR scheduler records one base LR per group.+ _split_mixed_param_groups(getattr(optimizer, "optimizer", optimizer))+ return optimizer++ original_create_scheduler = Trainer.create_scheduler++ @functools.wraps(original_create_scheduler)+ def create_scheduler(+ self,+ num_training_steps,+ optimizer = None,+ *args,+ **kwargs,+ ):+ # A subclass create_optimizer that builds its own optimizer (UnslothTrainer with+ # embedding_learning_rate / loraplus_lr_ratio, DecisionTrainer) never reaches the base hook+ # above, and transformers 4.x builds the scheduler before Accelerator.prepare splits the+ # groups. Split here, before the scheduler records one base LR (and lambda) per group.+ target = optimizer if optimizer is not None else getattr(self, "optimizer", None)+ if (+ target is not None+ and getattr(self, "lr_scheduler", None) is None+ and is_native_fsdp2(getattr(self, "model", None))+ and _split_mixed_param_groups(_inner_optimizer(target))+ ):+ _print_rank0(+ "Unsloth: native FSDP2 split optimizer groups mixing sharded and replicated "+ "parameters (each kind needs its own foreach / fused group) before the LR scheduler."+ )+ return original_create_scheduler(self, num_training_steps, optimizer, *args, **kwargs)++ original_save_optimizer = Trainer._save_optimizer_and_scheduler++ @functools.wraps(original_save_optimizer)+ def _save_optimizer_and_scheduler(self, output_dir):+ model = getattr(self, "model", None)+ if not is_native_fsdp2(model) or getattr(self, "is_fsdp_enabled", False):+ return original_save_optimizer(self, output_dir)+ # Collective full optimizer state (the original saves rank 0's shards only), then the scheduler.+ native_save_optimizer(+ model,+ self.optimizer,+ os.path.join(output_dir, _OPTIMIZER_NAME),+ should_save = self.args.should_save,+ )+ scheduler = getattr(self, "lr_scheduler", None)+ if self.args.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_scheduler++ @functools.wraps(original_load_optimizer)+ def _load_optimizer_and_scheduler(self, checkpoint, *args, **kwargs):+ model = getattr(self, "model", None)+ if (+ checkpoint is None+ or not is_native_fsdp2(model)+ or getattr(self, "is_fsdp_enabled", False)+ or not os.path.isfile(os.path.join(checkpoint, _OPTIMIZER_NAME))+ or not os.path.isfile(os.path.join(checkpoint, _SCHEDULER_NAME))+ ):+ return original_load_optimizer(self, checkpoint, *args, **kwargs)+ native_load_optimizer(model, self.optimizer, os.path.join(checkpoint, _OPTIMIZER_NAME))+ self.lr_scheduler.load_state_dict(+ torch.load(os.path.join(checkpoint, _SCHEDULER_NAME), weights_only = True)+ )++ original_load_from_checkpoint = Trainer._load_from_checkpoint++ @functools.wraps(original_load_from_checkpoint)+ def _load_from_checkpoint(+ self,+ resume_from_checkpoint,+ model = None,+ ):+ target = model if model is not None else getattr(self, "model", None)+ if not is_native_fsdp2(target) or getattr(self, "is_fsdp_enabled", False):+ return original_load_from_checkpoint(self, resume_from_checkpoint, model)+ # Copying full tensors into DTensor parameters (load_state_dict / PEFT load_adapter) cannot work.+ native_load_model_checkpoint(target, resume_from_checkpoint)++ original_load_best_model = getattr(Trainer, "_load_best_model", None)++ if original_load_best_model is not None:++ @functools.wraps(original_load_best_model)+ def _load_best_model(self, *args, **kwargs):+ model = getattr(self, "model", None)+ if not is_native_fsdp2(model) or getattr(self, "is_fsdp_enabled", False):+ return original_load_best_model(self, *args, **kwargs)+ # load_best_model_at_end: the same native load as a resume (collective, every rank).+ native_load_model_checkpoint(model, self.state.best_model_checkpoint)++ Trainer._load_best_model = _load_best_model++ original_create_accelerator = getattr(Trainer, "create_accelerator_and_postprocess", None)+ if original_create_accelerator is not None:++ @functools.wraps(original_create_accelerator)+ def create_accelerator_and_postprocess(self, *args, **kwargs):+ out = original_create_accelerator(self, *args, **kwargs)+ accelerator = getattr(self, "accelerator", None)+ if accelerator is not None:+ # The Trainer owns this accelerator: its prepare / save paths are the supported ones.+ setattr(accelerator, _TRAINER_ACCELERATOR, True)+ return out++ Trainer.create_accelerator_and_postprocess = create_accelerator_and_postprocess+ Trainer.save_model = save_model+ Trainer.create_optimizer = create_optimizer+ Trainer.create_scheduler = create_scheduler+ Trainer._save_optimizer_and_scheduler = _save_optimizer_and_scheduler+ Trainer._load_optimizer_and_scheduler = _load_optimizer_and_scheduler+ Trainer._load_from_checkpoint = _load_from_checkpoint+ setattr(Trainer, _PATCHED, True)+ return True+++def _is_peft(model):+ model = _native_root(model)+ try:+ from peft import PeftModel+ return isinstance(model, PeftModel)+ except Exception:+ return False+++def install_native_fsdp2_hooks():+ """Idempotent: accelerate treats a native FSDP2 model as prepared (no DDP / FSDP wrap), no_sync+ turns gradient reduction off for accumulation, clip_grad_norm_ handles DTensor gradients, and+ Trainer.save_model gathers collectively."""+ a = _install_accelerate_hooks()+ t = _install_trainer_hooks()+ return a and t+++def _scaler_for_native(trainer):+ """float16: the GradScaler's inf check must agree over ranks, or one rank skips a step the+ others take. ShardedGradScaler all-reduces it."""+ accelerator = getattr(trainer, "accelerator", None)+ scaler = getattr(accelerator, "scaler", None)+ if scaler is None:+ return False+ try:+ from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler+ except ImportError:+ return False+ if isinstance(scaler, ShardedGradScaler):+ return False+ kwargs = {}+ handler = getattr(accelerator, "scaler_handler", None)+ if handler is not None and hasattr(handler, "to_kwargs"):+ kwargs = handler.to_kwargs()+ accelerator.scaler = ShardedGradScaler(**kwargs)+ return True+++def _native_optimizer(optimizer):+ """Whether an optimizer steps parameters shard_model produced (marked on each of them)."""+ groups = getattr(_inner_optimizer(optimizer), "param_groups", None) or []+ return any(+ getattr(p, "_unsloth_fsdp2_native_param", False) is True+ for g in groups+ for p in g["params"]+ )+++# bitsandbytes optimizers (transformers' OptimizerNames) step plain tensors through custom ops with no+# DTensor sharding strategy. Those with a torch equivalent are switched to it; the others are refused.+_BNB_OPTIMS = {+ "adamw_8bit": "adamw_torch_fused",+ "adamw_bnb_8bit": "adamw_torch_fused",+ "paged_adamw_8bit": "adamw_torch_fused",+ "paged_adamw_32bit": "adamw_torch_fused",+ "rmsprop_bnb": "rmsprop",+ "rmsprop_bnb_8bit": "rmsprop",+ "rmsprop_bnb_32bit": "rmsprop",+}+_BNB_UNSUPPORTED = (+ "lion_8bit",+ "lion_32bit",+ "paged_lion_8bit",+ "paged_lion_32bit",+ "ademamix",+ "ademamix_8bit",+ "paged_ademamix_32bit",+ "paged_ademamix_8bit",+)+++def _swap_bnb_optimizer(training_args):+ """bitsandbytes' optimizers step plain CUDA tensors; native FSDP2 parameters are DTensors."""+ optim = getattr(training_args, "optim", None)+ if optim is None:+ return False+ name = str(getattr(optim, "value", optim)).strip().lower()+ if name in _BNB_UNSUPPORTED:+ raise ValueError(+ f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "+ f"step (optim = '{name}'), and torch has no equivalent to switch to. Use optim = "+ f"'adamw_torch' (or 'adamw_torch_fused'), or build a DTensor-compatible optimizer after "+ f"`unsloth.models.fsdp2_native.shard_model(model)` and pass it to the Trainer."+ )+ target = _BNB_OPTIMS.get(name)+ if target is None:+ return False+ if target == "adamw_torch_fused" and not torch.cuda.is_available():+ target = "adamw_torch"+ _print_rank0(+ f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "+ f"step. Switching optim = '{name}' to '{target}'."+ )+ try:+ from transformers.training_args import OptimizerNames+ training_args.optim = OptimizerNames(target)+ except Exception:+ training_args.optim = target+ return True+++# Trainer.__init__'s positional order (the same in transformers 4.57 and 5.x), for an __init__ whose+# signature cannot be read (a wrapper without functools.wraps).+_TRAINER_INIT_ORDER = (+ "model",+ "args",+ "data_collator",+ "train_dataset",+ "eval_dataset",+ "processing_class",+ "model_init",+ "compute_loss_func",+ "compute_metrics",+ "callbacks",+ "optimizers",+)+++def native_fsdp2_trainer_init_arguments(init, args, kwargs):+ """`model`, `args`, `model_init` and `optimizers` of a Trainer.__init__(self, *args, **kwargs)+ call, passed by keyword or by position (read from the signature of `init`)."""+ import inspect++ names = ()+ try:+ params = list(inspect.signature(init).parameters.values())+ kinds = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)+ names = tuple(p.name for p in params if p.kind in kinds)+ if names and names[0] == "self":+ names = names[1:]+ except (TypeError, ValueError):+ pass+ if "model" not in names:+ names = _TRAINER_INIT_ORDER+ wanted = ("model", "args", "model_init", "optimizers", "optimizer_cls_and_kwargs")+ out = {name: kwargs.get(name) for name in wanted}+ for name, value in zip(names, args):+ if name in out and name not in kwargs:+ out[name] = value+ return out+++def _trainer_fsdp_requested(training_args):+ """TrainingArguments(fsdp = ...): transformers 5 keeps it on the arguments (`fsdp`,+ `fsdp_plugin_args`) and the Trainer builds accelerate's FSDP plugin from them; 4.x also exports+ ACCELERATE_USE_FSDP from __post_init__."""+ if training_args is None:+ return False+ return bool(getattr(training_args, "fsdp", None)) or (+ getattr(training_args, "fsdp_plugin_args", None) is not None+ )+++def native_fsdp2_defers_to_trainer_fsdp(training_args):+ """TrainingArguments(fsdp = ...) asks for accelerate's FSDP. With no UNSLOTH_FSDP2_BACKEND that+ request wins, as an `accelerate launch` FSDP config does (fsdp2_launch): True, nothing is sharded+ natively. With UNSLOTH_FSDP2_BACKEND=native the two requests conflict: refused before any model+ change (accelerate would wrap the natively sharded model again)."""+ if not _trainer_fsdp_requested(training_args):+ return False+ backend = os.environ.get("UNSLOTH_FSDP2_BACKEND", "").strip().lower()+ if backend in ("native", "unsloth", "torch"):+ raise RuntimeError(+ "Unsloth: UNSLOTH_FSDP2_BACKEND=native shards the model with Unsloth's own FSDP2, but "+ "TrainingArguments(fsdp = ...) also asks accelerate to wrap it. Pick one: drop `fsdp` "+ "(and `fsdp_config`) from the TrainingArguments, or set UNSLOTH_FSDP2_BACKEND=accelerate."+ )+ _print_rank0(+ "Unsloth: TrainingArguments(fsdp = ...) selects accelerate's FSDP, so Unsloth's native FSDP2 "+ "sharding is skipped (set UNSLOTH_FSDP2_BACKEND=native and drop `fsdp` to use it)."+ )+ return True+++def _trainer_uses_cpu(training_args):+ """TrainingArguments(use_cpu = True) (4.x `no_cuda`, copied to use_cpu in __post_init__) or+ ACCELERATE_USE_CPU: the Trainer's accelerator runs on the CPU. Read without `args.device`, whose+ first access sets up the distributed state."""+ if getattr(training_args, "use_cpu", False) or getattr(training_args, "no_cuda", False):+ return True+ return str(os.environ.get("ACCELERATE_USE_CPU", "")).strip().lower() in (+ "1",+ "true",+ "yes",+ "on",+ )+++_MIXED_GROUPS_REFUSAL = (+ "Unsloth: native FSDP2 got an optimizer whose parameter groups mix sharded (DTensor) and "+ "replicated parameters, together with an LR scheduler built on those groups or with optimizer state "+ "already loaded, so the groups cannot be split. Build the optimizer from "+ "`unsloth.models.fsdp2_native.split_param_groups(...)` (before the scheduler and before loading "+ "state), or let the Trainer build both (optimizers = (None, None))."+)+++def _is_bnb_optimizer_class(cls):+ """A bitsandbytes optimizer class, or a subclass of one (Optimizer8bit / Optimizer2State /+ Optimizer1State), read from the MRO's modules so bitsandbytes is not imported."""+ for klass in getattr(cls, "__mro__", None) or (cls,):+ module = str(getattr(klass, "__module__", "") or "")+ if module == "bitsandbytes" or module.startswith("bitsandbytes."):+ return True+ return False+++def _refuse_bnb_optimizer_instance(optimizer):+ """A prebuilt optimizer passed as Trainer(optimizers = (opt, ...)) or to accelerator.prepare:+ _swap_bnb_optimizer only edits args.optim, so a bitsandbytes instance would be kept and step+ DTensor shards it cannot handle. Torch optimizers pass."""+ if optimizer is None:+ return+ inner = _inner_optimizer(optimizer)+ if _is_bnb_optimizer_class(type(inner)):+ raise ValueError(+ f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "+ f"step (got a {type(inner).__name__}). Build a torch optimizer (torch.optim.AdamW over "+ "`unsloth.models.fsdp2_native.split_param_groups(...)`), or let the Trainer build it with "+ "optim = 'adamw_8bit', which native FSDP2 switches to torch's AdamW."+ )+++def _refuse_bnb_optimizer_cls(optimizer_cls_and_kwargs):+ """Trainer(optimizer_cls_and_kwargs = (cls, kwargs)) overrides args.optim, so the bitsandbytes+ switch in _swap_bnb_optimizer never sees it; bitsandbytes' optimizers step plain CUDA tensors, not+ DTensors. Torch optimizer classes pass. Refused rather than switched: the kwargs are the class's."""+ if not isinstance(optimizer_cls_and_kwargs, (tuple, list)) or not optimizer_cls_and_kwargs:+ return+ cls = optimizer_cls_and_kwargs[0]+ if _is_bnb_optimizer_class(cls):+ raise ValueError(+ f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "+ f"step (optimizer_cls_and_kwargs = ({getattr(cls, '__name__', cls)}, ...)). Pass a torch "+ "optimizer class (torch.optim.AdamW), or drop optimizer_cls_and_kwargs and set optim = "+ "'adamw_8bit' / 'paged_adamw_8bit', which native FSDP2 switches to torch's AdamW."+ )+++def _trainer_process_group(training_args, config):+ """Create the process group the way the Trainer would, before sharding needs it: TrainingArguments'+ own device setup (PartialState with ddp_backend, ddp_timeout and use_cpu), which the Trainer runs+ first thing in __init__ anyway. Without it (a namespace), pass ddp_backend / ddp_timeout on."""+ import datetime++ import torch.distributed as dist++ if training_args is None or (dist.is_available() and dist.is_initialized()):+ return+ if isinstance(getattr(type(training_args), "_setup_devices", None), functools.cached_property):+ training_args._setup_devices+ return+ backend = getattr(training_args, "ddp_backend", None)+ if backend:+ config.backend = backend+ timeout = getattr(training_args, "ddp_timeout", None)+ if timeout:+ config.timeout = datetime.timedelta(seconds = int(timeout))+++def _refuse_parallelism_config(training_args):+ """transformers 5 TrainingArguments(parallelism_config = accelerate.ParallelismConfig(...)) is+ separate from `fsdp`: accelerate would prepare tensor / context / sequence parallelism or a+ replicate x shard mesh over the natively sharded model. Only a plain shard over every rank (what+ native FSDP2 does) passes. Absent on 4.x."""+ pc = getattr(training_args, "parallelism_config", None)+ if pc is None:+ return+ sizes = {+ name: int(getattr(pc, name, None) or 1)+ for name in ("tp_size", "cp_size", "sp_size", "dp_replicate_size", "dp_shard_size")+ }+ try:+ world = int(os.environ.get("WORLD_SIZE", "1"))+ except ValueError:+ world = 1+ extra = {k: v for k, v in sizes.items() if k != "dp_shard_size" and v > 1}+ if extra or sizes["dp_shard_size"] not in (1, world):+ raise RuntimeError(+ f"Unsloth: native FSDP2 shards over all {world} ranks itself, but TrainingArguments("+ f"parallelism_config = ...) asks accelerate for {', '.join(f'{k}={v}' for k, v in sizes.items())}"+ ". Drop parallelism_config, or set UNSLOTH_FSDP2_BACKEND=accelerate to let accelerate "+ "build that layout."+ )+++def _refuse_tensor_parallel_model(model):+ """A model loaded with a tensor-parallel plan (from_pretrained(tp_plan = ...)) already holds+ DTensor parameters on its own mesh; the Trainer would also build a ParallelismConfig from its+ tp_size. Native FSDP2 cannot shard it again."""+ if not isinstance(model, nn.Module) or getattr(model, _NATIVE_FLAG, False):+ return+ tp_size = getattr(model, "tp_size", None)+ try:+ tp_size = int(tp_size) if tp_size is not None else None+ except (TypeError, ValueError):+ tp_size = None+ DTensor = None+ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ pass+ dtensor = DTensor is not None and any(isinstance(p, DTensor) for p in model.parameters())+ if (tp_size or 1) > 1 or dtensor:+ raise RuntimeError(+ "Unsloth: native FSDP2 got a model that is already distributed (tensor-parallel tp_plan, "+ f"tp_size = {tp_size}, or DTensor parameters). Load it without tp_plan for native FSDP2, or "+ "use UNSLOTH_FSDP2_BACKEND=accelerate with a ParallelismConfig."+ )+++def _refuse_clef(model):+ """DecisionTrainer's Clef models save (adapters + head through staging folders, written by+ `_save` on the rank that calls it) and resume (`_load_clef_checkpoint`, plain tensor copies) outside+ the native collective hooks: rank 0's `_save` would wait in the encoder's gathered save_pretrained+ the other ranks never enter."""+ if getattr(model, "is_clef", False) is True:+ raise RuntimeError(+ "Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) does not support Clef / DecisionTrainer models: "+ "their checkpoint save and resume are not collective, so a multi-rank save would hang. "+ "Train them without UNSLOTH_FSDP2 (DDP or a single GPU)."+ )+++def _refuse_q_galore(training_args):+ """UnslothTrainer builds QGaLoreAdamW8bit in its own create_optimizer when q_galore_config is set,+ bypassing args.optim (so _swap_bnb_optimizer never sees it). Its 8-bit states and 2-D projections+ expect plain tensors, not DTensor shards."""+ if getattr(training_args, "q_galore_config", None) is not None:+ raise ValueError(+ "Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) cannot train with q_galore_config: Q-GaLore's "+ "8-bit optimizer projects whole 2-D weights, and native FSDP2 hands it DTensor shards. Set "+ "q_galore_config = None, or launch without UNSLOTH_FSDP2."+ )+++def _refuse_projection_optim(training_args):+ """GaLore and APOLLO (optim = 'galore_*' / 'apollo_*', layerwise or not) project whole 2-D weights,+ like Q-GaLore, and the layerwise variants register per-parameter post-gradient hooks that+ transformers documents as single-GPU only. Native FSDP2 hands them DTensor shards."""+ optim = getattr(training_args, "optim", None) if training_args is not None else None+ if optim is None:+ return+ name = str(getattr(optim, "value", optim)).strip().lower()+ if name.startswith(("galore_", "apollo_")):+ raise ValueError(+ f"Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) cannot train with optim = '{name}': GaLore and "+ "APOLLO project whole 2-D weights (the layerwise variants are single-GPU only), and native "+ "FSDP2 hands the optimizer DTensor shards. Use optim = 'adamw_torch', or launch without "+ "UNSLOTH_FSDP2."+ )+++def _refuse_accelerate_fp8(training_args):+ """accelerate's FP8 training (mixed_precision = "fp8": Transformer Engine, torchao or MS-AMP)+ converts the model's Linear layers in Accelerator.prepare, after native sharding captured the+ DTensors, so the optimizer would target replacement parameters FSDP2 does not manage. The Trainer+ gets it from ACCELERATE_MIXED_PRECISION (accelerate launch / config) unless fp16 / bf16 is set:+ transformers 5 stores the result as args.mixed_precision, 4.x leaves it in the env. Unsloth's own+ float8 weights are not affected (kept replicated, never converted by accelerate)."""+ mode = getattr(training_args, "mixed_precision", None) if training_args is not None else None+ if mode is None:+ mode = os.environ.get("ACCELERATE_MIXED_PRECISION", "no")+ if training_args is not None and (+ getattr(training_args, "fp16", False) or getattr(training_args, "bf16", False)+ ):+ mode = "fp16"+ if str(mode).strip().lower() == "fp8":+ raise RuntimeError(+ "Unsloth: native FSDP2 cannot train with accelerate's FP8 mixed precision (mixed_precision = "+ "'fp8', from ACCELERATE_MIXED_PRECISION or the accelerate config): accelerate converts the "+ "layers after Unsloth sharded them. Use bf16 / fp16 (TrainingArguments(bf16 = True)), or "+ "UNSLOTH_FSDP2_BACKEND=accelerate."+ )+++def _refuse_accelerate_backends(training_args):+ """Every accelerate backend native FSDP2 cannot run under (fsdp2_launch.NATIVE_BACKEND_TABLE:+ DeepSpeed, Megatron-LM, XLA, NPU / MLU / SDAA / MUSA / HPU / XPU / Neuron devices, SageMaker DP, a+ ParallelismConfig env), from the env and the TrainingArguments (`deepspeed`, `deepspeed_plugin`,+ `hf_deepspeed_config`, ...): the import-time check only sees the launch env, and accelerate would+ otherwise build that backend over the DTensor model. Before any model change."""+ from ..fsdp2_launch import refuse_native_backend_conflicts+ refuse_native_backend_conflicts(training_args, _trainer_uses_cpu(training_args))+++def _refuse_save_on_each_node(training_args):+ """save_on_each_node makes every node's local rank 0 a writer, but the collective gathers+ (native_full_state_dict, native_save_optimizer, fsdp2_gathered) leave the full state on global+ rank 0 only: the other nodes would write empty model and optimizer files. One node is fine."""+ if not getattr(training_args, "save_on_each_node", False):+ return+ try:+ multi_node = int(os.environ.get("WORLD_SIZE", "1")) > int(os.environ["LOCAL_WORLD_SIZE"])+ except (KeyError, ValueError):+ multi_node = True # cannot tell: assume the launch spans nodes+ if multi_node:+ raise RuntimeError(+ "Unsloth: native FSDP2 gathers the full model and optimizer state on global rank 0 only, "+ "so `save_on_each_node = True` would make the other nodes write empty checkpoints. Set "+ "`save_on_each_node = False` and save to storage every node can read."+ )+++def native_fsdp2_trainer_setup(+ trainer = None,+ model = None,+ phase = "pre",+ optimizers = None,+ training_args = None,+ model_init = None,+ optimizer_cls_and_kwargs = None,+):+ """Called around Trainer.__init__. pre: shard `model` (LoRA or full finetuning) before the+ optimizer and accelerate exist. post: float16 scaler. Returns the (sharded) model."""+ if not native_fsdp2_requested():+ return model+ install_native_fsdp2_hooks()+ if phase == "pre":+ if native_fsdp2_defers_to_trainer_fsdp(training_args):+ return model+ _refuse_accelerate_backends(training_args)+ _refuse_accelerate_fp8(training_args)+ _refuse_save_on_each_node(training_args)+ _refuse_bnb_optimizer_cls(optimizer_cls_and_kwargs)+ _refuse_q_galore(training_args)+ _refuse_projection_optim(training_args)+ _refuse_clef(model)+ _refuse_parallelism_config(training_args)+ _refuse_tensor_parallel_model(model)+ if model_init is not None:+ # Trainer.train / hyperparameter_search call model_init again for a fresh model (and+ # rebuild the accelerator per trial), which would train unsharded.+ raise RuntimeError(+ "Unsloth: native FSDP2 does not support `Trainer(model_init = ...)` or "+ "`hyperparameter_search`: the model model_init returns would not be sharded. Build "+ "the model first and pass it as `Trainer(model = model)`."+ )+ optimizer = optimizers[0] if isinstance(optimizers, (tuple, list)) and optimizers else None+ scheduler = (+ optimizers[1] if isinstance(optimizers, (tuple, list)) and len(optimizers) > 1 else None+ )+ _refuse_bnb_optimizer_instance(optimizer)+ if is_native_fsdp2(model) and optimizer is not None and _mixed_param_groups(optimizer):+ # The Trainer would split the groups after a scheduler recorded one base LR (and lambda)+ # per group (the new groups keep their initial LR; a resumed scheduler state no longer+ # matches), and a split cannot carry loaded per-parameter state, so it is skipped and the+ # mixed group reaches a foreach / fused kernel. Only a fresh optimizer alone is split.+ if scheduler is not None or getattr(_inner_optimizer(optimizer), "state", None):+ raise RuntimeError(_MIXED_GROUPS_REFUSAL)+ if is_native_fsdp2(model):+ _swap_bnb_optimizer(+ training_args+ ) # the Trainer still builds the optimizer from args.optim+ if model is None or not isinstance(model, nn.Module) or is_native_fsdp2(model):+ return model+ if optimizer is not None:+ raise RuntimeError(+ "Unsloth: native FSDP2 shards the model inside Trainer.__init__, which replaces its "+ "parameters, so an optimizer built before the Trainer would update stale tensors. Call "+ "`unsloth.models.fsdp2_native.shard_model(model)` before building the optimizer, or "+ "let the Trainer build it (optimizers = (None, None))."+ )+ _swap_bnb_optimizer(training_args)+ config = FSDP2Config.from_env()+ if _trainer_uses_cpu(training_args):+ config.device = "cpu" # the Trainer will run on the CPU: no GPU mesh+ _trainer_process_group(training_args, config)+ return shard_model(model, config)+ if trainer is not None and is_native_fsdp2(getattr(trainer, "model", None)):+ _scaler_for_native(trainer)+ return modeldiff --git a/unsloth/models/fsdp2_native_quant.py b/unsloth/models/fsdp2_native_quant.pynew file mode 100644index 00000000000..505e82bf770--- /dev/null+++ b/unsloth/models/fsdp2_native_quant.py@@ -0,0 +1,94 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Quantized and exotic parameters under Unsloth's native FSDP2 wrap (`fsdp2_native.shard_model`).++`shard_model` calls `fully_shard` on every repeated block and then on the root; around those calls+`native_quant_context` makes bitsandbytes 4-bit weights shardable (packed bytes stored in the compute+dtype, QuantState and the Params4bit class kept on the all-gathered weight, no mixed precision cast of+packed bytes: `fsdp2_qlora.py`), and `after_native_shard` installs what saving and checkpointing need+and checks that no trainable parameter was left out of FSDP2 (its gradient would not be reduced).++ with native_quant_context(model) as quant:+ for unit in units: fully_shard(unit, mp_policy = ...)+ fully_shard(model, mp_policy = ...)+ report = after_native_shard(model)+"""++__all__ = [+ "native_quant_context",+ "after_native_shard",+ "sharding_report",+]++import contextlib++import torch++from .fsdp2_qlora import fsdp2_qlora_wrap, is_params4bit+++def _dtensor_class():+ try:+ from torch.distributed.tensor import DTensor+ return DTensor+ except ImportError:+ try:+ from torch.distributed._tensor import DTensor+ return DTensor+ except ImportError:+ return None+++def native_quant_context(model, dtype = None):+ """Enter around the fully_shard calls. Yields None for a model without bitsandbytes 4-bit weights+ (nothing is touched), else the `prepare_fsdp2_qlora` info (`params4bit`, `converted`, `patched`,+ `storage`, `reverted`). `dtype`: the float storage of the packed bytes, the mixed precision+ param_dtype (default: the weights' compute dtype). load_in_4bit = False models are left exactly+ as they are."""+ with fsdp2_qlora_wrap(model, native = True, dtype = dtype) as info:+ yield info+++def sharding_report(model):+ """What FSDP2 manages after the wrap: counts of DTensor parameters, bitsandbytes 4-bit weights+ sharded, and the names of parameters FSDP2 does not manage (trainable ones get no reduction)."""+ DTensor = _dtensor_class()+ report = {+ "dtensor": 0,+ "params4bit_sharded": 0,+ "unsharded": [],+ "unsharded_trainable": [],+ }+ seen = set()+ for name, param in model.named_parameters():+ if id(param) in seen:+ continue+ seen.add(id(param))+ if DTensor is not None and isinstance(param, DTensor):+ report["dtensor"] += 1+ if getattr(param, "quant_state", None) is not None:+ report["params4bit_sharded"] += 1+ continue+ report["unsharded"].append(name)+ if param.requires_grad:+ report["unsharded_trainable"].append(name)+ return report+++def after_native_shard(model):+ """After `fully_shard(model)`: install the DCP state dict handling of bitsandbytes 4-bit weights,+ and average the gradient of any trainable parameter FSDP2 does not manage over ranks (like DDP),+ so no replica drifts. Returns `sharding_report(model)` plus `reduced` (those parameter names)."""+ from .fsdp2_save import install_dcp_bnb_state_dict, reduce_unsharded_trainable_grads++ if any(+ is_params4bit(p) or getattr(p, "quant_state", None) is not None for p in model.parameters()+ ):+ install_dcp_bnb_state_dict()+ report = sharding_report(model)+ report["reduced"] = (+ reduce_unsharded_trainable_grads(model) if report["unsharded_trainable"] else []+ )+ return reportdiff --git a/unsloth/models/fsdp2_perf.py b/unsloth/models/fsdp2_perf.pynew file mode 100644index 00000000000..5fbbb2f6bc2--- /dev/null+++ b/unsloth/models/fsdp2_perf.py@@ -0,0 +1,324 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Throughput layout for native FSDP2 when the model fits on one GPU.++Plain FSDP2 is slower than DDP for a model that fits on each GPU because it moves weights DDP never+moves: every block's frozen LoRA base weights are all-gathered in forward and again for the backward+(or gradient checkpointing) recompute, and full fine-tuning all-gathers each block twice per step.+When the model fits, the layout here keeps:++ * frozen parameters replicated (passed as ``ignored_params``): never gathered, never reduced, exactly+ like DDP, and bitsandbytes 4-bit base weights stay plain ``Params4bit``;+ * trainable parameters, their gradients and optimizer state sharded as usual;+ * the gathered trainable weights resident from forward to backward (``reshard_after_forward=False``),+ one all-gather per step instead of two;+ * explicit next-block prefetch in forward and backward;+ * when only small trainable params are left (LoRA adapters), a single root unit: one all-gather and+ one reduce-scatter per step, no per-block hooks.++Units holding no trainable parameter are not wrapped (no hooks, no empty collectives). Peak memory stays+at or below DDP: frozen weights are what DDP holds, trainable weights are held once gathered plus one+shard, and gradients plus optimizer state are sharded.++Env overrides (read only when native FSDP2 is used): ``UNSLOTH_FSDP2_REPLICATE_FROZEN`` = auto | 1 | 0,+``UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD`` = auto | 1 | 0, ``UNSLOTH_FSDP2_PREFETCH`` = 1 | 0,+``UNSLOTH_FSDP2_FIT_FRACTION`` (default 0.4 of one device's memory).+"""++from dataclasses import dataclass, field+import os++import torch++__all__ = [+ "FSDP2Layout",+ "plan_fsdp2_layout",+ "unit_ignored_params",+ "resolve_reshard_after_forward",+ "apply_fsdp2_prefetch",+ "shard_model_layout",+]++_TRUE = ("1", "true", "yes", "on")+_FALSE = ("0", "false", "no", "off")+++def _env_tristate(name):+ value = os.environ.get(name, "auto").strip().lower()+ if value in _TRUE:+ return True+ if value in _FALSE:+ return False+ return None+++def _param_bytes(params, dtype = None):+ total = 0+ seen = set()+ for p in params:+ if id(p) in seen:+ continue+ seen.add(id(p))+ # bitsandbytes Params4bit keeps its packed storage: count what is really resident.+ size = dtype.itemsize if dtype is not None and p.is_floating_point() else p.element_size()+ total += p.numel() * size+ return total+++def _device_bytes(device = None):+ """Total memory of the GPU the model trains on; 0 for a CPU (or other non-CUDA) mesh, which plans+ the per-block sharded layout as a CPU-only host does."""+ if device is not None and torch.device(device).type != "cuda":+ return 0+ try:+ if device is None:+ device = torch.cuda.current_device()+ return torch.cuda.get_device_properties(device).total_memory+ except Exception:+ return 0+++@dataclass+class FSDP2Layout:+ replicate_frozen: bool = False+ reshard_after_forward: bool = True+ prefetch: bool = False+ root_only: bool = False+ fits: bool = False+ frozen_bytes: int = 0+ trainable_bytes: int = 0+ device_bytes: int = 0+ reasons: list = field(default_factory = list)++ def as_dict(self):+ return {+ "replicate_frozen": self.replicate_frozen,+ "reshard_after_forward": self.reshard_after_forward,+ "prefetch": self.prefetch,+ "root_only": self.root_only,+ "fits": self.fits,+ "frozen_gib": round(self.frozen_bytes / 2**30, 3),+ "trainable_gib": round(self.trainable_bytes / 2**30, 3),+ "device_gib": round(self.device_bytes / 2**30, 1),+ "reasons": list(self.reasons),+ }+++def plan_fsdp2_layout(+ model,+ param_dtype = None,+ reshard_after_forward = None,+ device = None,+ cpu_offload = False,+ fits = None,+ replicate_frozen = None,+ allow_root_only = True,+):+ """Decide the layout. ``reshard_after_forward`` None = auto; an explicit bool / int is kept.+ ``fits`` None = by device memory (``UNSLOTH_FSDP2_LAYOUT`` = fit / sharded forces it), True / False+ forces it. ``replicate_frozen`` None = auto (``UNSLOTH_FSDP2_REPLICATE_FROZEN``), else forced.+ ``allow_root_only`` False keeps per-unit wrapping (explicit units)."""+ params = list(model.parameters())+ frozen = [p for p in params if not p.requires_grad]+ trainable = [p for p in params if p.requires_grad]+ layout = FSDP2Layout(+ frozen_bytes = _param_bytes(frozen),+ trainable_bytes = _param_bytes(trainable, param_dtype),+ device_bytes = _device_bytes(device),+ )+ try:+ fraction = float(os.environ.get("UNSLOTH_FSDP2_FIT_FRACTION", "0.4"))+ except ValueError:+ fraction = 0.4+ # "Fits" = the whole model (what DDP keeps on every GPU) uses at most `fraction` of one device,+ # leaving the rest for activations, gradients and optimizer state.+ # CPU offload asks for memory, not speed: keep the plain sharded layout.+ forced = os.environ.get("UNSLOTH_FSDP2_LAYOUT", "auto").strip().lower()+ if fits is None and forced in ("fit", "sharded"):+ fits = forced == "fit"+ if fits is not None:+ layout.fits = bool(fits) and not cpu_offload+ else:+ layout.fits = (+ not cpu_offload+ and layout.device_bytes > 0+ and (layout.frozen_bytes + layout.trainable_bytes) <= fraction * layout.device_bytes+ )+ layout.reasons.append(+ f"fits={layout.fits} (model {(layout.frozen_bytes + layout.trainable_bytes) / 2**30:.2f} GiB vs {fraction} x {layout.device_bytes / 2**30:.1f} GiB)"+ )++ replicate = replicate_frozen+ if replicate is None:+ replicate = _env_tristate("UNSLOTH_FSDP2_REPLICATE_FROZEN")+ if replicate is None:+ replicate = layout.fits and len(frozen) > 0 and len(trainable) > 0+ layout.replicate_frozen = bool(replicate and frozen and trainable)++ resolve_reshard_after_forward(layout, reshard_after_forward)+ # Explicit prefetch is part of the fit layout; the sharded layout keeps the caller's prefetch knobs.+ layout.prefetch = (+ layout.fits and os.environ.get("UNSLOTH_FSDP2_PREFETCH", "1").strip().lower() not in _FALSE+ )+ # With the frozen weights replicated, what is left to shard (LoRA adapters) is small: one root+ # unit = one all-gather + one reduce-scatter per step instead of a hook pair and two collectives+ # per block, and the per-block saving it gives up is a few MB.+ units = os.environ.get("UNSLOTH_FSDP2_TRAINABLE_UNITS", "auto").strip().lower()+ small = layout.trainable_bytes <= min(1 << 30, 0.01 * layout.device_bytes)+ layout.root_only = (+ allow_root_only+ and layout.replicate_frozen+ and (units == "root" or (units == "auto" and small))+ )+ layout.reasons.append(+ f"root_only={layout.root_only} (trainable {layout.trainable_bytes / 2**20:.1f} MiB)"+ )+ return layout+++def resolve_reshard_after_forward(+ layout,+ reshard_after_forward = None,+ note = True,+):+ """Set ``layout.reshard_after_forward``: the explicit config value, else the env override, else+ derived from ``layout.fits`` (kept gathered when it fits). Call again after ``fits`` changes (the+ ranks agreeing on one layout) so every rank derives the same value."""+ env_reshard = _env_tristate("UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD")+ if reshard_after_forward is not None:+ layout.reshard_after_forward = reshard_after_forward+ source = "config"+ elif env_reshard is not None:+ layout.reshard_after_forward = env_reshard+ source = "env"+ else:+ layout.reshard_after_forward = not layout.fits+ source = None+ if note and source is not None:+ layout.reasons.append(f"reshard_after_forward from {source}")+ return layout.reshard_after_forward+++def unit_ignored_params(module, layout):+ """Frozen params of `module` to pass as fully_shard(ignored_params = ...), or None."""+ if not layout.replicate_frozen:+ return None+ ignored = {p for p in module.parameters() if not p.requires_grad}+ return ignored or None+++def _has_managed_params(module, ignored):+ return any(ignored is None or p not in ignored for p in module.parameters())+++def apply_fsdp2_prefetch(+ units,+ forward_depth = 1,+ backward_depth = 1,+):+ """Explicit prefetch: forward gathers blocks i+1..i+forward_depth while i runs, backward gathers+ i-1..i-backward_depth (NeMo Automodel defaults to forward 1 / backward 2)."""+ units = [u for u in units if hasattr(u, "set_modules_to_forward_prefetch")]+ for i, unit in enumerate(units):+ ahead = units[i + 1 : i + 1 + forward_depth]+ behind = units[max(0, i - backward_depth) : i][::-1]+ if ahead:+ unit.set_modules_to_forward_prefetch(ahead)+ if behind:+ unit.set_modules_to_backward_prefetch(behind)+ return len(units)+++def _env_int(name, default):+ try:+ return max(1, int(os.environ.get(name, default)))+ except ValueError:+ return default+++def shard_model_layout(+ model,+ units,+ mp_policy,+ layout,+ mesh = None,+ offload_policy = None,+ ignored_params = None,+ extra_units = (),+ fully_shard_fn = None,+ reshard_last_block = False,+ unit_reshard_after_forward = None,+ forward_prefetch = 0,+ backward_prefetch = 0,+ shard_kwargs = None,+):+ """fully_shard each unit then the root following `layout`. Returns the units that were wrapped.++ The last unit never reshards after forward (backward starts there) unless `reshard_last_block`.+ Units with no parameter left to manage (all frozen and replicated) are not wrapped.+ `ignored_params`: extra parameters every fully_shard call leaves replicated (minority dtype norms,+ float8 weights, ...). `extra_units` (large root embedding tables) are wrapped after the blocks with+ the layout's reshard_after_forward. `unit_reshard_after_forward(i, unit)` -> bool | int | None+ overrides one block. `forward_prefetch` / `backward_prefetch` > 0 set explicit prefetch depths;+ 0 / 0 uses the layout's (one ahead, env UNSLOTH_FSDP2_PREFETCH_FWD / _BWD) when it prefetches.+ """+ if fully_shard_fn is None:+ try:+ from torch.distributed.fsdp import fully_shard as fully_shard_fn+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import fully_shard as fully_shard_fn++ kwargs = {"mp_policy": mp_policy}+ if mesh is not None:+ kwargs["mesh"] = mesh+ if offload_policy is not None:+ kwargs["offload_policy"] = offload_policy+ if shard_kwargs:+ kwargs.update(shard_kwargs)+ extra_ignored = set(ignored_params or ())++ def _ignored(module):+ own = unit_ignored_params(module, layout) or set()+ if extra_ignored:+ own = own | {p for p in module.parameters() if p in extra_ignored}+ return own or None++ def _wrap(module, reshard, ignored):+ kw = dict(kwargs)+ if ignored:+ kw["ignored_params"] = ignored+ fully_shard_fn(module, reshard_after_forward = reshard, **kw)+ module._unsloth_reshard_after_forward = reshard++ targets = []+ for unit in [] if layout.root_only else units:+ ignored = _ignored(unit)+ if _has_managed_params(unit, ignored):+ targets.append((unit, ignored))+ wrapped = []+ last = len(targets) - 1+ for i, (unit, ignored) in enumerate(targets):+ reshard = reshard_last_block if i == last else layout.reshard_after_forward+ if unit_reshard_after_forward is not None:+ chosen = unit_reshard_after_forward(i, unit)+ reshard = reshard if chosen is None else chosen+ _wrap(unit, reshard, ignored)+ wrapped.append(unit)+ for unit in [] if layout.root_only else extra_units:+ ignored = _ignored(unit)+ if _has_managed_params(unit, ignored):+ _wrap(unit, layout.reshard_after_forward, ignored)+ # The root holds embeddings / final norm / lm_head; it is used again first in backward.+ _wrap(model, False, _ignored(model))+ if len(wrapped) > 1:+ if forward_prefetch > 0 or backward_prefetch > 0:+ apply_fsdp2_prefetch(wrapped, forward_prefetch, backward_prefetch)+ elif layout.prefetch:+ apply_fsdp2_prefetch(+ wrapped,+ forward_depth = _env_int("UNSLOTH_FSDP2_PREFETCH_FWD", 1),+ backward_depth = _env_int("UNSLOTH_FSDP2_PREFETCH_BWD", 1),+ )+ model._unsloth_fsdp2_layout = layout.as_dict()+ return wrappeddiff --git a/unsloth/models/fsdp2_qlora.py b/unsloth/models/fsdp2_qlora.pyindex c24ea0a3214..947042f9a78 100644--- a/unsloth/models/fsdp2_qlora.py+++ b/unsloth/models/fsdp2_qlora.py@@ -36,6 +36,7 @@ __all__ = [import contextlibimport inspect+import sysimport torch@@ -60,12 +61,15 @@ def is_params4bit(tensor):return any(cls.__name__ == "Params4bit" for cls in type(tensor).__mro__)-def float_storage_survives_wrap(prepare_fn = None):+def float_storage_survives_wrap(prepare_fn = None, native = False):"""Whether 4-bit weights may be packed in a float dtype for FSDP2. False when this torch's FSDP2cannot be patched (`patch_fsdp2_params4bit`), checks frozen dtypes per unit (torch < 2.8), or when accelerate's FSDP2 wrap ends with`model.to(torch.float32)` (accelerate < 1.13 with mixed precision), which converts float-storedpacked bytes as if they were weights. uint8 storage is safe from both, so 4-bit weights then stay- uint8 (left replicated by accelerate, but correct)."""+ uint8 (left replicated by accelerate, but correct). `native` is Unsloth's own fully_shard wrap+ (`fsdp2_native`), which never upcasts the model: only the two FSDP2 conditions apply."""+ if native:+ return not _missing_fsdp2_anchors() and not _fsdp2_checks_frozen_dtypes()if prepare_fn is None:try:from accelerate.utils.fsdp_utils import fsdp2_prepare_model as prepare_fn@@ -88,9 +92,92 @@ def float_storage_survives_wrap(prepare_fn = None):return "model.to(torch.float32)" not in source+# FSDP2's private modules, by static import on either layout: torch.distributed.fsdp._fully_shard.<name>+# (torch >= 2.6) or torch.distributed._composable.fsdp.<name> (2.4 / 2.5).+++def _load_fsdp_param():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_param as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_param as module+ return module+++def _load_fsdp_state():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_state as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_state as module+ return module+++def _load_fsdp_common():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_common as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_common as module+ return module+++def _load_fsdp_param_group():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_param_group as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_param_group as module+ return module+++def _load_fsdp_init():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_init as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_init as module+ return module+++def _load_fsdp_collectives():+ try:+ from torch.distributed.fsdp._fully_shard import _fsdp_collectives as module+ except ImportError: # torch 2.4 / 2.5+ from torch.distributed._composable.fsdp import _fsdp_collectives as module+ return module+++def _load_fully_shard():+ try:+ from torch.distributed.fsdp._fully_shard import _fully_shard as module+ except (+ ImportError+ ): # torch 2.4 / 2.5: the module is `fully_shard` (the package attribute is the function)+ import torch.distributed._composable.fsdp.fully_shard # noqa: F401+ module = sys.modules["torch.distributed._composable.fsdp.fully_shard"]+ return module+++_FSDP_PRIVATE_LOADERS = {+ "_fsdp_param": _load_fsdp_param,+ "_fsdp_state": _load_fsdp_state,+ "_fsdp_common": _load_fsdp_common,+ "_fsdp_param_group": _load_fsdp_param_group,+ "_fsdp_init": _load_fsdp_init,+ "_fsdp_collectives": _load_fsdp_collectives,+ "_fully_shard": _load_fully_shard,+}+++def _fsdp_private(submodule):+ """FSDP2's private module `submodule` (_fsdp_param, _fsdp_state, _fsdp_common, _fsdp_param_group,+ _fsdp_init, _fsdp_collectives, _fully_shard) on either layout (see _FSDP_PRIVATE_LOADERS)."""+ loader = _FSDP_PRIVATE_LOADERS.get(submodule)+ if loader is None:+ raise ImportError(f"no FSDP2 module {submodule}")+ return loader()++def _fsdp2_checks_frozen_dtypes():try:- from torch.distributed.fsdp._fully_shard._fsdp_param_group import FSDPParamGroup+ FSDPParamGroup = _fsdp_private("_fsdp_param_group").FSDPParamGroupreturn "requires_grad" not in inspect.getsource(FSDPParamGroup._init_mp_dtypes)except Exception:return True@@ -255,16 +342,11 @@ def nonfloat_frozen_unmanaged():every unit, as accelerate >= 1.14 does with `ignored_params` on torch >= 2.7. torch < 2.8 asserts oneoriginal dtype over all of a unit's parameters, so uint8 next to float LoRA weights cannot be sharded."""modules = []- try:- from torch.distributed.fsdp._fully_shard import _fully_shard as _fully_shard_module- modules.append(_fully_shard_module)- except Exception:- pass- try:- from torch.distributed.fsdp._fully_shard import _fsdp_init as _fsdp_init_module- modules.append(_fsdp_init_module)- except Exception:- pass+ for name in ("_fully_shard", "_fsdp_init"):+ try:+ modules.append(_fsdp_private(name))+ except Exception:+ passpatched = []for module in modules:@@ -389,8 +471,8 @@ def _check_collectives_anchors(collectives):def _missing_fsdp2_anchors():try:- from torch.distributed.fsdp._fully_shard import _fsdp_collectives- from torch.distributed.fsdp._fully_shard._fsdp_param import FSDPParam+ _fsdp_collectives = _fsdp_private("_fsdp_collectives")+ FSDPParam = _fsdp_private("_fsdp_param").FSDPParamexcept Exception as error:return [f"FSDP2 ({type(error).__name__})"]return _check_fsdp_param_anchors(FSDPParam) + _check_collectives_anchors(_fsdp_collectives)@@ -415,8 +497,8 @@ def patch_fsdp2_params4bit():missing = _missing_fsdp2_anchors()if missing:return False, f"torch {torch.__version__} FSDP2 lacks " + ", ".join(missing)- from torch.distributed.fsdp._fully_shard import _fsdp_collectives- from torch.distributed.fsdp._fully_shard._fsdp_param import FSDPParam+ _fsdp_collectives = _fsdp_private("_fsdp_collectives")+ FSDPParam = _fsdp_private("_fsdp_param").FSDPParamif getattr(FSDPParam.init_dtype_attrs, "_unsloth_original", None) is not None:_PATCH_STATE["patched"] = True@@ -576,15 +658,22 @@ def prepare_fsdp2_qlora(@contextlib.contextmanager-def fsdp2_qlora_wrap(model, prepare_fn = None):- """Around an FSDP2 wrap (accelerate's `fsdp2_prepare_model` is `prepare_fn`): prepare the 4-bit- weights, and let uint8 ones still left shard on torch < 2.12. Yields the `prepare_fsdp2_qlora`- info, or None for a model without bitsandbytes 4-bit weights (nothing is touched then)."""+def fsdp2_qlora_wrap(+ model,+ prepare_fn = None,+ native = False,+ dtype = None,+):+ """Around an FSDP2 wrap (accelerate's `fsdp2_prepare_model` is `prepare_fn`, or Unsloth's own+ fully_shard calls with `native = True`): prepare the 4-bit weights, and let uint8 ones still left+ shard on torch < 2.12. Yields the `prepare_fsdp2_qlora` info, or None for a model without+ bitsandbytes 4-bit weights (nothing is touched then). `dtype` is the float storage (default: the+ weights' compute dtype)."""if not any(is_params4bit(p) for p in model.parameters()):yield Nonereturn- survives = float_storage_survives_wrap(prepare_fn)- info = prepare_fsdp2_qlora(model, float_storage = survives)+ survives = float_storage_survives_wrap(prepare_fn, native = native)+ info = prepare_fsdp2_qlora(model, dtype = dtype, float_storage = survives)info["reverted"] = 0if not survives or not info["patched"]:# Float storage here comes only from the caller's own BitsAndBytesConfig. An unpatched FSDP2diff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex 7229a8803f8..50790dd42b9 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -137,6 +137,17 @@ def _rebuild(param, full, module):return torch.nn.Parameter(full, requires_grad = param.requires_grad)from bitsandbytes.nn import Params4bit+ as_uint8 = (+ full.is_floating_point()+ and full.dim() == 2+ and full.shape[-1] == 1+ and full.is_contiguous()+ )+ if as_uint8:+ # FSDP2 packs the 4-bit bytes in the compute dtype only to shard them. Saved (merged_4bit+ # requantizes with the weight's own quant_storage) they are the uint8 bitsandbytes writes+ # without FSDP2, so the checkpoint matches a single-GPU one and its quantization_config.+ full = full.reshape(-1).view(torch.uint8).reshape(-1, 1)new = torch.Tensor._make_subclass(Params4bit, full, False)for key in ("quant_state",@@ -145,9 +156,12 @@ def _rebuild(param, full, module):"quant_type","quant_storage","bnb_quantized",+ "_original_shape",):if hasattr(param, key):setattr(new, key, getattr(param, key))+ if as_uint8:+ new.quant_storage = torch.uint8new.module = modulereturn new@@ -229,15 +243,27 @@ def fsdp2_gathered(_wait_for_writer(dist, writer)+def _is_4bit_base(base_layer):+ weight = getattr(base_layer, "weight", None)+ if weight is not None and getattr(weight, "quant_state", None) is not None:+ return True+ # The weight object an eval forward left unsharded need not carry the QuantState attribute.+ return any(c.__name__ == "Linear4bit" for c in type(base_layer).__mro__)++def offload_all_but_4bit_merge_operands(model):"""`offload_to_cpu` for a merged 4-bit save: PEFT merges a LoRA layer where its packed 4-bit baseweight stays (its GPU), so only the adapter weights of those layers stay there too. Everything- else (embeddings, unquantized towers, LoRA on unquantized layers with their base) goes to the CPU."""- keep = set()- for module in model.modules() if isinstance(model, torch.nn.Module) else ():- weight = getattr(getattr(module, "base_layer", None), "weight", None)- if weight is None or getattr(weight, "quant_state", None) is None:+ else (embeddings, unquantized towers, LoRA on unquantized layers with their base) goes to the CPU.+ Selected by parameter name, not identity: `fsdp2_gathered` reshards first, and a parameter an eval+ forward left unsharded is a different object from the DTensor the gather then sees."""+ prefixes = []+ modules = model.named_modules() if isinstance(model, torch.nn.Module) else ()+ for module_name, module in modules:+ base_layer = getattr(module, "base_layer", None)+ if not isinstance(base_layer, torch.nn.Module) or not _is_4bit_base(base_layer):continue+ prefix = f"{module_name}." if module_name else ""for attr in ("lora_A","lora_B",@@ -245,10 +271,10 @@ def offload_all_but_4bit_merge_operands(model):"lora_embedding_B","lora_magnitude_vector",):- sub = getattr(module, attr, None)- if isinstance(sub, torch.nn.Module):- keep.update(id(param) for param in sub.parameters())- return lambda name, param: id(param) not in keep+ if isinstance(getattr(module, attr, None), torch.nn.Module):+ prefixes.append(f"{prefix}{attr}.")+ prefixes = tuple(prefixes)+ return lambda name, param: not name.startswith(prefixes)def fsdp2_gather_active():@@ -293,6 +319,25 @@ def _has_sharded_4bit(args, kwargs):)+def _has_native_replicated_4bit(args, kwargs):+ """A natively sharded model (fsdp2_native, fit layout) whose Linear4bit weights FSDP2 left replicated:+ they keep bitsandbytes' own `weight.absmax` / `quant_state` entries, which a strict DCP load rejects+ as unexpected keys although the in-memory QuantState already equals them."""+ model = args[0] if args else kwargs.get("model", None)+ if not isinstance(model, torch.nn.Module) or not getattr(model, "_unsloth_fsdp2_native", False):+ return False+ DTensor = _dtensor_class()+ try:+ from bitsandbytes.nn import Linear4bit+ except Exception:+ return False+ return any(+ isinstance(m, Linear4bit)+ and not (DTensor is not None and isinstance(getattr(m, "weight", None), DTensor))+ for m in model.modules()+ )++def _wrap_accelerate_adapter_only():try:import accelerate.utils.fsdp_utils as fsdp_utils@@ -326,7 +371,9 @@ def install_dcp_bnb_state_dict():bitsandbytes' `weight.absmax` / `weight.quant_state.bitsandbytes__nf4` entries are not one(AttributeError in `_get_fqns`). That breaks every FSDP2 Trainer adapter checkpoint of a 4-bitmodel. Inside adapter-only DCP calls (`_drops_frozen_weights`) Linear4bit reports just its weight- and bias; the QuantState is unchanged in memory. Other DCP calls keep bitsandbytes' entries."""+ and bias; the QuantState is unchanged in memory. A full DCP state dict of a sharded 4-bit model is+ built the same way and then gets bitsandbytes' entries back under their usual keys+ (`_add_quant_state_entries`), which loading drops again. Other DCP calls are untouched."""try:import torch.distributed.checkpoint.state_dict as dcp_state_dictfrom bitsandbytes.nn import Linear4bit@@ -346,16 +393,27 @@ def install_dcp_bnb_state_dict():_save_to_state_dict._unsloth_fsdp2_patched = TrueLinear4bit._save_to_state_dict = _save_to_state_dict- def _wrap(fn):+ def _wrap(fn, name):@functools.wraps(fn)def wrapper(*args, **kwargs):- if not (_drops_frozen_weights(kwargs) or _has_sharded_4bit(args, kwargs)):+ adapter_only = _drops_frozen_weights(kwargs)+ full_4bit = not adapter_only and _has_sharded_4bit(args, kwargs)+ if not (adapter_only or full_4bit):+ if name.startswith("set_") and _has_native_replicated_4bit(args, kwargs):+ args, kwargs = _without_quant_state_entries(name, args, kwargs)return fn(*args, **kwargs)+ if full_4bit and name.startswith("set_"):+ args, kwargs = _without_quant_state_entries(name, args, kwargs)_DCP_DEPTH[0] += 1try:- return fn(*args, **kwargs)+ out = fn(*args, **kwargs)finally:_DCP_DEPTH[0] -= 1+ if full_4bit and name in ("get_model_state_dict", "get_state_dict"):+ model = args[0] if args else kwargs.get("model")+ state_dict = out[0] if name == "get_state_dict" else out+ _add_quant_state_entries(model, state_dict, kwargs.get("options", None))+ return outwrapper._unsloth_fsdp2_patched = Truereturn wrapper@@ -363,34 +421,206 @@ def install_dcp_bnb_state_dict():for name in _DCP_FUNCTIONS:fn = getattr(dcp_state_dict, name, None)if fn is not None and not getattr(fn, "_unsloth_fsdp2_patched", False):- setattr(dcp_state_dict, name, _wrap(fn))+ setattr(dcp_state_dict, name, _wrap(fn, name))return True+def _linear4bit_entries(model):+ """(state dict key prefix, module) of every bitsandbytes Linear4bit with a QuantState, keyed the way+ torch.distributed.checkpoint names them (no torch.compile `_orig_mod.` segment)."""+ try:+ from bitsandbytes.nn import Linear4bit+ except Exception:+ return []+ entries = []+ for name, module in model.named_modules():+ if not isinstance(module, Linear4bit):+ continue+ if getattr(getattr(module, "weight", None), "quant_state", None) is None:+ continue+ prefix = name.replace("_orig_mod.", "")+ entries.append((prefix + "." if prefix else "", module))+ return entries+++def _add_quant_state_entries(model, state_dict, options):+ """A full (not adapter-only) DCP state dict of a sharded 4-bit model: DCP cannot name bitsandbytes'+ `weight.absmax` / `weight.quant_state.*` entries (they are not attribute paths of a DTensor), so+ they are built without them and added here, next to each packed weight the dict holds. Without them+ the packed bytes cannot be dequantized after a reload. The QuantState is replicated on every rank."""+ if not isinstance(state_dict, dict) or not isinstance(model, torch.nn.Module):+ return+ cpu = bool(getattr(options, "cpu_offload", False))+ for prefix, module in _linear4bit_entries(model):+ if prefix + "weight" not in state_dict:+ continue+ for key, value in module.weight.quant_state.as_dict(packed = True).items():+ value = value.detach()+ state_dict[prefix + "weight." + key] = value.cpu() if cpu else value+++def _without_quant_state_entries(name, args, kwargs):+ """Loading: drop the entries `_add_quant_state_entries` wrote (DCP would reject them as unexpected+ keys); the QuantState is rebuilt identically when the 4-bit model is loaded again."""+ model = args[0] if args else kwargs.get("model")+ if not isinstance(model, torch.nn.Module):+ return args, kwargs+ drop = set()+ for prefix, module in _linear4bit_entries(model):+ drop.update(+ prefix + "weight." + key for key in module.weight.quant_state.as_dict(packed = True)+ )+ if not drop:+ return args, kwargs++ def strip(state_dict):+ if not isinstance(state_dict, dict) or not drop.intersection(state_dict):+ return state_dict+ return {k: v for k, v in state_dict.items() if k not in drop}++ if name == "set_model_state_dict":+ if len(args) > 1:+ args = (args[0], strip(args[1])) + tuple(args[2:])+ elif "model_state_dict" in kwargs:+ kwargs = dict(kwargs, model_state_dict = strip(kwargs["model_state_dict"]))+ elif "model_state_dict" in kwargs:+ kwargs = dict(kwargs, model_state_dict = strip(kwargs["model_state_dict"]))+ return args, kwargs+++def _in_backward():+ try:+ return torch._C._current_graph_task_id() != -1+ except Exception:+ return False+++def model_mesh(model):+ """The device mesh `model` is sharded over: the one shard_model recorded, else its first DTensor+ parameter's; None when neither exists (the default world group applies)."""+ mesh = model.__dict__.get("_unsloth_fsdp2_mesh", None)+ if mesh is not None:+ return mesh+ DTensor = _dtensor_class()+ if DTensor is None:+ return None+ for p in model.parameters():+ if isinstance(p, DTensor):+ return p.device_mesh+ return None+++def mesh_all_reduce(tensor, mesh, dist):+ """Sum `tensor` in place over every rank of `mesh` (the world when None), one all_reduce per mesh+ dimension (the groups of each dimension partition the mesh, so an HSDP mesh is summed whole).+ Returns the number of ranks summed. A sub-mesh (several models or replicas on disjoint ranks)+ reduces only over its own ranks."""+ if mesh is None:+ dist.all_reduce(tensor)+ return dist.get_world_size()+ for dim in range(mesh.ndim):+ dist.all_reduce(tensor, group = mesh.get_group(dim))+ return mesh.size()+++def _sync_replicated_grads(+ params,+ dist,+ mesh = None,+):+ """One all_reduce per (device, reduce dtype) over the fixed parameter list, in its order, issued+ by every rank: a gradient this rank did not produce counts as zeros, and a per-parameter+ "has a gradient" flag rides along so a parameter no rank used keeps grad None (as with DDP).+ Sums in float32 (float64 stays float64), as FSDP2's reduce_dtype does: two fp16 gradients of+ 40000 overflow an fp16 sum although their mean is finite. Linear, so averaging the running+ accumulation after each micro-step equals averaging the accumulated sum once. Over the ranks of+ `mesh`, the model's own (mesh_all_reduce), not the whole world."""+ groups = {}+ for p in params:+ dtype = torch.float64 if p.dtype == torch.float64 else torch.float32+ groups.setdefault((str(p.device), dtype), []).append(p)+ for (device, dtype), group in groups.items():+ sizes = [p.numel() for p in group]+ total = sum(sizes)+ flat = torch.zeros(total + len(group), dtype = dtype, device = group[0].device)+ offset = 0+ for i, (p, n) in enumerate(zip(group, sizes)):+ if p.grad is not None:+ flat[offset : offset + n].copy_(p.grad.detach().reshape(-1))+ flat[total + i] = 1+ offset += n+ world = mesh_all_reduce(flat, mesh, dist)+ flat[:total].div_(world)+ used = flat[total:].tolist() # one device sync, not one per parameter+ offset = 0+ for i, (p, n) in enumerate(zip(group, sizes)):+ if used[i] > 0:+ value = flat[offset : offset + n].view(p.shape)+ if p.grad is None:+ p.grad = value.to(p.dtype).clone()+ else:+ p.grad.copy_(value)+ offset += n++def reduce_unsharded_trainable_grads(model):"""Trainable parameters FSDP2 does not manage (e.g. in `ignored_modules`) get no gradientreduction, so every rank would step on its own gradient and the replicas drift apart. Average- their gradient over ranks as it is produced, like DDP. Returns the parameter names."""+ their gradients over the model's mesh ranks like DDP, once per backward, at its end, on every rank: a per-parameter+ hook would make a rank that did not use the parameter (a branch, a routed MoE expert) skip the+ collective the others enter, and hang. The sync is queued as an autograd engine callback from a+ hook on `model`'s forward outputs (and, as a fallback, on each of these parameters), so it runs+ after all gradients are accumulated and before the optimizer step / clip. Returns the names."""dist = _dist()DTensor = _dtensor_class()- if dist is None or DTensor is None or dist.get_world_size() == 1:+ if dist is None or DTensor is None:+ return []+ mesh = model_mesh(model)+ if (mesh.size() if mesh is not None else dist.get_world_size()) == 1:return []names = []seen = set()+ params = model.__dict__.setdefault("_unsloth_replicated_grad_params", [])+ state = model.__dict__.setdefault("_unsloth_replicated_grad_state", {"queued": False})++ def _sync():+ state["queued"] = False+ _sync_replicated_grads(params, dist, mesh)++ def _queue(*_):+ if not state["queued"]:+ state["queued"] = True+ torch.autograd.Variable._execution_engine.queue_callback(_sync)+for name, param in model.named_parameters():if id(param) in seen or not param.requires_grad or isinstance(param, DTensor):continueseen.add(id(param))if getattr(param, "_unsloth_grad_all_reduce", False):continue- world = dist.get_world_size()-- def _average(grad, world = world):- grad = grad.clone()- dist.all_reduce(grad)- return grad.div_(world)-- param.register_hook(_average)+ param.register_hook(_queue)param._unsloth_grad_all_reduce = True+ params.append(param)names.append(name)+ if params and not getattr(model, "_unsloth_replicated_grad_hooked", False):++ def _pre_forward(module, args):+ if not _in_backward():+ state["queued"] = False # a backward that raised never ran its callback++ def _post_forward(module, args, output):+ if not torch.is_grad_enabled():+ return+ from torch.utils._pytree import tree_flatten++ leaves = tree_flatten(output)[0]+ if not any(isinstance(t, torch.Tensor) for t in leaves) and isinstance(output, dict):+ leaves = list(output.values())+ for t in leaves:+ if isinstance(t, torch.Tensor) and t.requires_grad:+ t.register_hook(_queue)++ model.register_forward_pre_hook(_pre_forward)+ model.register_forward_hook(_post_forward)+ model.__dict__["_unsloth_replicated_grad_hooked"] = Truereturn namesdiff --git a/unsloth/models/fsdp2_vision.py b/unsloth/models/fsdp2_vision.pynew file mode 100644index 00000000000..f1237d7de31--- /dev/null+++ b/unsloth/models/fsdp2_vision.py@@ -0,0 +1,958 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Mixed image / text micro-batches under native FSDP2.++When one rank's micro-batch has images and another's does not, only the image rank runs the vision+tower: its units all-gather on that rank alone and NCCL pairs the collectives wrongly (hang), and+FSDP2 reduce-scatters only parameters whose gradient is not None, so even a vision tower held in the+root unit (fit layout) desyncs at the reduce-scatter. Here a rank without images runs the vision+encoder on a minimal dummy input before the language model (same collective order as an image rank)+and adds `0.0 * sum(outputs)` to the multimodal model's output, so every vision parameter gets a zero+gradient on that rank. No collective and no host sync is added (the decision is local: is+`pixel_values` given). Installed only by `fsdp2_native.shard_model`, and only when some vision tower+or projector parameter issues a gradient collective (FSDP2-managed, or replicated with an all-reduce+hook). `UNSLOTH_FSDP2_VISION_DUMMY=0` turns it off (then every rank's micro-batch must carry an image).+"""++import inspect+import os+import re++import torch++__all__ = ["install_vision_dummy"]++_INSTALLED = "_unsloth_fsdp2_vision_dummy"+_VISION_INPUTS = (+ "pixel_values",+ "pixel_values_videos",+ "pixel_values_images",+ "image_pixel_values",+)+# Audio encoders (Gemma3n / Gemma4 `input_features`, Qwen2.5-Omni / Qwen3-Omni `input_features` with+# `feature_attention_mask`, PE Audio / PeAudioVideo `input_values`, others `audio_values`): no dummy+# is built, a mixed batch raises. The media keys unsloth/trainer.py and utils/token_budget.py batch.+_AUDIO_INPUTS = (+ "input_features",+ "input_values",+ "audio_values",+ "input_audio_embeds",+ "audio_input_features",+)+# Named per speaker / stream: Moshi's `user_input_values` / `moshi_input_values`+# (transformers/models/moshi/modeling_moshi.py MoshiForConditionalGeneration.forward), each encoded by+# its own audio_encoder.encode call.+_AUDIO_INPUT_RE = re.compile(r"^\w+_(input_values|audio_values)$")+++def _audio_inputs(signature):+ """The audio inputs a forward takes: the known names, then any `*_input_values` /+ `*_audio_values` parameter. All known names for a signature that cannot be read."""+ if signature is None:+ return ()+ names = [n for n in _AUDIO_INPUTS if n in signature.parameters]+ names += [n for n in signature.parameters if _AUDIO_INPUT_RE.match(n) and n not in names]+ return tuple(names)+++_AUDIO_TOWER_NAMES = ("audio_tower", "audio_model", "audio_encoder", "audio")+_AUDIO_PROJECTOR_NAMES = (+ "embed_audio",+ "audio_projector",+ "audio_projection",+ "audio_multi_modal_projector",+)+# `visual` (Qwen-VL) also runs the video path; VideoLlava has separate `image_tower` / `video_tower`.+_TOWER_NAMES = ("visual", "vision_tower", "vision_model", "vision_encoder", "vision", "image_tower")+_VIDEO_TOWER_NAMES = ("video_tower",)+# Generic encoder attribute names (Phi-4 multimodal `image_embed` / `audio_embed`, `*_encoder`,+# `*_model`), matched on registered children after the known names above.+_SUFFIXES = r"(_(embed|embedding|embeddings|encoder|tower|model|processor))?"+_VISION_TOWER_RE = re.compile(r"^(image|vision|visual|img)" + _SUFFIXES + "$")+_AUDIO_TOWER_RE = re.compile(r"^(audio|speech)" + _SUFFIXES + "$")+_VIDEO_TOWER_RE = re.compile(r"^video_(embed|embedding|encoder|tower|model)$")+_PROJECTOR_NAMES = (+ "multi_modal_projector",+ "mm_projector",+ "embed_vision",+ "connector",+ "vision_projection",+ "visual_projection",+)+++def _rank0():+ try:+ import torch.distributed as dist+ return not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0+ except Exception:+ return True+++def _print_rank0(message):+ if _rank0():+ print(message, flush = True)+++def _takes(fn, name):+ try:+ return name in inspect.signature(fn).parameters+ except (TypeError, ValueError):+ return False+++def _forward_signature(module):+ """The forward's signature; a `(*args, **kwargs)` wrapper (zoo temporary patches wrap Gemma4Model's)+ is looked through to the function it wraps when that one names `pixel_values`."""+ forward = type(module).forward+ try:+ unwrapped = inspect.unwrap(forward)+ if unwrapped is not forward and _takes(unwrapped, "pixel_values"):+ return inspect.signature(unwrapped)+ return inspect.signature(forward)+ except (TypeError, ValueError):+ return None+++def _takes_any_kwargs(signature):+ return signature is not None and any(+ p.kind is inspect.Parameter.VAR_KEYWORD for p in signature.parameters.values()+ )+++def _multimodal_module(model):+ """The innermost module with `get_image_features` and a vision tower whose forward takes+ `pixel_values` (or `**kwargs`, a wrapped forward)."""+ found = None+ for module in model.modules():+ if not callable(getattr(module, "get_image_features", None)):+ continue+ signature = _forward_signature(module)+ takes = signature is not None and any(n in signature.parameters for n in _VISION_INPUTS)+ if takes or (_takes_any_kwargs(signature) and _vision_tower(module) is not None):+ found = module # pre-order: a later match is nested deeper (CG -> Model)+ return found+++def _inline_multimodal_module(model):+ """The outermost module whose forward takes a vision input (pixel_values, image_pixel_values, ...)+ with no `get_image_features`: its encoder runs inline and conditionally (Mllama's vision_model ++ multi_modal_projector, then cross-attention layers skipped without images; Phi-4 multimodal's+ `image_embed` inside its feature embedding). Outermost, because an inner module taking the input may+ run only on ranks that have it, and the agreement must be on a forward every rank runs."""+ for module in model.modules():+ if callable(getattr(module, "get_image_features", None)):+ continue+ signature = _forward_signature(module)+ if signature is None or not any(n in signature.parameters for n in _VISION_INPUTS):+ continue+ return module+ return None+++def _video_modality(host, image_tower):+ """A video tower separate from the image tower (VideoLlava `video_tower`) is its own modality+ (`pixel_values_videos`), with no dummy. Returns (image inputs, [video modality]) or the shared+ form (all vision inputs, []) when video runs through the image tower (Qwen-VL `visual`)."""+ children = host.__dict__.get("_modules", {})+ names = list(_VIDEO_TOWER_NAMES) + [n for n in children if _VIDEO_TOWER_RE.match(n)]+ for name in names:+ video = children.get(name, None)+ if isinstance(video, torch.nn.Module) and video is not image_tower:+ inputs = tuple(n for n in _VISION_INPUTS if n != "pixel_values_videos")+ if not _managed_by_fsdp(video):+ return inputs, []+ why = "runs a separate video tower Unsloth has no dummy for"+ return inputs, [_Modality("videos", ("pixel_values_videos",), why)]+ return _VISION_INPUTS, []+++def _image_only_modules(mm, tower = None):+ """Modules only run with an image (Mllama's cross-attention layers), outside the vision tower."""+ skip = {id(m) for m in tower.modules()} if isinstance(tower, torch.nn.Module) else set()+ return [m for m in mm.modules() if "CrossAttention" in type(m).__name__ and id(m) not in skip]+++def _is_media_value(value):+ """A tensor, or a non-empty list / tuple holding one (batched per-sample images)."""+ if isinstance(value, torch.Tensor):+ return True+ if isinstance(value, (list, tuple)):+ return any(_is_media_value(v) for v in value)+ return False+++def _given(+ signature,+ module,+ args,+ kwargs,+ names,+ tensors_only = False,+):+ """Whether this forward call passes a non-None value (a tensor value with `tensors_only`) for any+ of `names`."""+ check = _is_media_value if tensors_only else (lambda v: v is not None)+ if any(check(kwargs.get(name)) for name in names):+ return True+ if not args or signature is None:+ return False+ try:+ bound = signature.bind_partial(module, *args, **kwargs).arguments+ except TypeError:+ return False+ return any(check(bound.get(name)) for name in names)+++def _agree_counts(+ flags,+ device,+ mesh = None,+):+ """Elementwise sum of `flags` over the ranks of `mesh` (the model's; the world when None), and+ their number: one small all-reduce per mesh dimension."""+ import torch.distributed as dist++ if not (dist.is_available() and dist.is_initialized()):+ return [int(f) for f in flags], 1+ if "nccl" in str(dist.get_backend()).lower() and torch.cuda.is_available():+ device = torch.device("cuda", torch.cuda.current_device())+ vector = torch.tensor([float(f) for f in flags], device = device)+ from .fsdp2_save import mesh_all_reduce++ world = mesh_all_reduce(vector, mesh, dist)+ return [int(round(v)) for v in vector.tolist()], world+++def _missing_required(fn, inputs):+ """Parameters of `fn` with no default (not *args / **kwargs) that `inputs` does not supply. A+ signature that cannot be read counts as unknown: ["?"]."""+ try:+ signature = inspect.signature(inspect.unwrap(fn))+ except (TypeError, ValueError):+ return ["?"]+ missing = []+ for name, param in signature.parameters.items():+ if name == "self" or param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):+ continue+ if param.default is param.empty and name not in inputs:+ missing.append(name)+ return missing+++# A forward that takes a media input but no recognised encoder under it: the conservative fallback.+_NO_ENCODER = (+ "takes this input but Unsloth found no encoder it could run on a dummy (whatever runs only for it "+ "would leave the ranks without it out of its collectives)"+)+++class _Modality:+ """One encoder input kind on a host module: which forward arguments carry it, and how a rank+ without it can still run the encoder's collectives (`ready()` -> bool), or None (it cannot)."""++ def __init__(+ self,+ label,+ inputs,+ why,+ ready = None,+ ):+ self.label = label+ self.inputs = inputs+ self.why = why+ self.ready = ready+ self.run_dummy = False+ self.tensors_only = False++ def groups(self, signature):+ """The inputs, one group per encoder call: each input the host takes is encoded on its own+ (Qwen-VL runs `visual` once for pixel_values and once more for pixel_values_videos; Moshi+ encodes user_input_values and moshi_input_values separately), so presence is agreed per input.+ The image inputs a dummy stands in for (`ready`) are one group, the first."""+ taken = [+ n+ for n in self.inputs+ if signature is None or n in signature.parameters or _takes_any_kwargs(signature)+ ] or list(self.inputs)+ if self.ready is None:+ return [(n,) for n in taken]+ covered = tuple(n for n in taken if n != "pixel_values_videos")+ return ([covered] if covered else []) + [(n,) for n in taken if n not in covered]+++def _install_presence_agreement(+ host,+ modalities,+ device_of,+ mesh = None,+):+ """Every forward of `host`, before any encoder runs: one all-reduce over [present per input,+ cannot-run-a-dummy per modality]. Each input is encoded by its own call, so an input present on+ some ranks only makes the ranks without it run the modality's dummy (`run_dummy`, the image inputs+ a dummy stands in for), or, when there is no dummy for that input or it cannot be built on some+ rank lacking it, raises on every rank alike (the ranks with it would otherwise wait in+ collectives the others never enter). A dummy that cannot be built is found before the+ collective, so that failure is agreed too."""+ signature = _forward_signature(host)+ plan = [(m, m.groups(signature)) for m in modalities]+ slots = [+ (m, g, j == 0 and m.ready is not None and "pixel_values_videos" not in g)+ for m, groups in plan+ for j, g in enumerate(groups)+ ]+ pairs = [+ (l, c)+ for l, (ml, _, _) in enumerate(slots)+ if ml.tensors_only+ for c, (_, _, covered) in enumerate(slots)+ if covered+ ]++ def agree(module, args, kwargs):+ for m in modalities:+ m.run_dummy = False+ if _in_generate():+ return None+ present = [_given(signature, host, args, kwargs, g, m.tensors_only) for m, g, _ in slots]+ unready = []+ for m, groups in plan:+ ok = True+ if m.ready is not None and groups:+ ok = _given(signature, host, args, kwargs, groups[0])+ if not ok:+ try:+ ok = bool(m.ready())+ except Exception:+ ok = False+ unready.append(not ok)+ # A generic input arriving with a dummy-covered group on exactly the same ranks is that+ # group's companion (image_grid_thw with pixel_values): the dummy stands in for both.+ xor = [present[l] != present[c] for l, c in pairs]+ counts, world = _agree_counts(present + unready + xor, device_of(), mesh)+ n = len(slots)+ mismatched = []+ for i, (m, group, covered) in enumerate(slots):+ if not 0 < counts[i] < world:+ continue # every rank has it, or none does: the collectives already match+ if covered and not counts[n + modalities.index(m)]:+ m.run_dummy = not present[i]+ continue+ companion = any(+ l == i+ and 0 < counts[c] < world+ and not counts[n + modalities.index(slots[c][0])]+ and counts[n + len(plan) + k] == 0+ for k, (l, c) in enumerate(pairs)+ )+ if not companion:+ mismatched.append((i, m, group, covered))+ if mismatched:+ i, m, group, covered = mismatched[0]+ why = (+ m.why+ if covered or m.ready is None+ else (f"encodes `{group[0]}` in a call of its own, which Unsloth has no dummy for")+ )+ single = len(plan[modalities.index(m)][1]) == 1 and not m.tensors_only+ which = "" if single else f" (input `{group[0]}`)"+ names = sorted({g[0] for _, _, g, _ in mismatched})+ raise RuntimeError(+ f"Unsloth: native FSDP2 got a micro-batch with {m.label} on {counts[i]} of {world} "+ f"ranks{which}. {type(host).__name__} {why or 'cannot build a dummy input here'}, "+ f"so the ranks without it would skip collectives the others run and the job would "+ f"hang. Mismatched inputs: {', '.join(names)}. Give every rank's micro-batch "+ f"{m.label} (or none), for example by grouping samples by modality into batches."+ )+ return None++ host.register_forward_pre_hook(agree, with_kwargs = True)+ setattr(host, _INSTALLED, True)+ for m in modalities:+ if m.ready is None:+ _print_rank0(+ f"Unsloth: native FSDP2 cannot run {type(host).__name__}'s {m.label} path on a dummy "+ f"input ({m.why}); every rank's micro-batch must carry {m.label} or none must (checked "+ "each forward, mixed raises on every rank)."+ )+ return host+++def _audio_tower(module):+ return _named_tower(module, _AUDIO_TOWER_NAMES, _AUDIO_TOWER_RE)+++def _audio_host(model, vision_host = None):+ """The module whose forward receives the audio input on every rank: the outermost one taking an+ audio input with an audio tower in its subtree. An inner module taking it too may run only on some+ ranks (PeAudioVideoModel calls `audio_model` only when no video is given), and an agreement hook+ there would leave the other ranks out of its collective. The vision host is reused when it takes an+ audio input and holds the tower (Gemma3n / Gemma4), so one collective covers both."""+ candidates = [vision_host] if vision_host is not None else []+ candidates += list(model.modules())+ for module in candidates:+ signature = _forward_signature(module)+ if not _audio_inputs(signature):+ continue+ if any(_audio_tower(m) is not None for m in module.modules()):+ return module+ return None+++def _audio_modules(host):+ """Every audio tower and audio projector in the host's subtree (they may sit below the host)."""+ modules = []+ for owner in host.modules():+ children = owner.__dict__.get("_modules", {})+ names = list(_AUDIO_TOWER_NAMES + _AUDIO_PROJECTOR_NAMES)+ names += [n for n in children if _AUDIO_TOWER_RE.match(n) and n not in names]+ for name in names:+ module = children.get(name, None)+ if isinstance(module, torch.nn.Module) and all(module is not m for m in modules):+ modules.append(module)+ return modules+++def _named_tower(module, names, pattern):+ """A known encoder attribute (properties included), else a registered child whose name matches."""+ for name in names:+ tower = getattr(module, name, None)+ if isinstance(tower, torch.nn.Module):+ return tower+ for name, child in (getattr(module, "_modules", None) or {}).items():+ if isinstance(child, torch.nn.Module) and pattern.match(name):+ return child+ return None+++def _vision_tower(mm):+ return _named_tower(mm, _TOWER_NAMES, _VISION_TOWER_RE)+++def _subtree_tower(host, find):+ """The first encoder `find` recognises anywhere under `host` (pre-order)."""+ for module in host.modules():+ tower = find(module)+ if tower is not None:+ return tower+ return None+++def _is_params4bit(p):+ return any(c.__name__ == "Params4bit" for c in type(p).__mro__)+++def _tower_dtype(tower, mm):+ for p in tower.parameters():+ if p.is_floating_point() and not _is_params4bit(p):+ try:+ return p.to_local().dtype if hasattr(p, "to_local") else p.dtype+ except Exception:+ return p.dtype+ return getattr(mm, "dtype", torch.float32)+++def _tower_device(tower):+ for p in tower.parameters():+ try:+ local = p.to_local() if hasattr(p, "to_local") else p+ except Exception:+ local = p+ if local.device.type != "meta":+ return local.device+ return torch.device("cpu")+++def _fixed_resolution(get, tower):+ """`get_image_features` takes `image_sizes` only optionally (Llava on recent transformers forwards+ it to backbones that need it) and the tower's forward does not take it (CLIP / SigLIP): the encoder+ expects `vision_config.image_size`, so a patch-sized dummy raises there. A tower that takes+ `image_sizes` (Pixtral) or a `get_image_features` that requires it (LlavaNext) is variable+ resolution."""+ try:+ param = inspect.signature(get).parameters["image_sizes"]+ except (TypeError, ValueError, KeyError):+ return False+ if param.default is inspect.Parameter.empty:+ return False+ tower_signature = _forward_signature(tower)+ return tower_signature is not None and "image_sizes" not in tower_signature.parameters+++def _dummy_inputs(mm, tower):+ """Smallest valid image input for this family, or None when it cannot be built."""+ config = getattr(mm, "config", None)+ vision = getattr(config, "vision_config", None) or getattr(tower, "config", None)+ if vision is None:+ return None+ dtype = _tower_dtype(tower, mm)+ device = _tower_device(tower)+ get = mm.get_image_features+ patch = getattr(vision, "patch_size", None) or getattr(vision, "spatial_patch_size", None)+ channels = getattr(vision, "in_channels", None) or getattr(vision, "num_channels", None) or 3+ if _takes(get, "image_grid_thw"):+ m = getattr(vision, "spatial_merge_size", None) or 1+ temporal = getattr(vision, "temporal_patch_size", None) or 1+ if not patch:+ return None+ pixel = torch.zeros(m * m, channels * temporal * patch * patch, dtype = dtype, device = device)+ grid = torch.tensor([[1, m, m]], dtype = torch.long, device = device)+ return {"pixel_values": pixel, "image_grid_thw": grid}+ if _takes(get, "image_position_ids"):+ # Gemma4: flattened patches + (x, y) patch positions; one pooling window = one soft token.+ k = getattr(vision, "pooling_kernel_size", None) or 1+ if not patch:+ return None+ n = k * k+ pixel = torch.zeros(1, n, channels * patch * patch, dtype = dtype, device = device)+ ys, xs = torch.meshgrid(torch.arange(k), torch.arange(k), indexing = "ij")+ pos = torch.stack([xs.reshape(-1), ys.reshape(-1)], dim = -1)[None].to(device)+ return {"pixel_values": pixel, "image_position_ids": pos}+ size = getattr(vision, "image_size", None)+ if isinstance(size, (tuple, list)):+ size = size[0]+ if _takes(get, "image_sizes") and not (size and _fixed_resolution(get, tower)):+ merge = (+ getattr(config, "spatial_merge_size", None)+ or getattr(vision, "spatial_merge_size", None)+ or 1+ )+ if not patch:+ return None+ s = patch * merge+ pixel = torch.zeros(1, channels, s, s, dtype = dtype, device = device)+ return {"pixel_values": pixel, "image_sizes": torch.tensor([[s, s]], device = device)}+ if not size:+ return None+ return {"pixel_values": torch.zeros(1, channels, size, size, dtype = dtype, device = device)}+++def _float_sum(obj, acc = None):+ """Sum of every floating tensor in a (nested) output, as one scalar kept in the autograd graph."""+ if isinstance(obj, torch.Tensor):+ if obj.is_floating_point() and obj.numel():+ s = obj.float().sum()+ return s if acc is None else acc + s+ return acc+ fields = getattr(obj, "__dataclass_fields__", None)+ if fields or isinstance(obj, dict):+ # ModelOutput: Gemma4 assigns pooler_output (the embed_vision projection) to a+ # BaseModelOutputWithPast after building it, so it is neither a field nor a dict item, only an+ # instance attribute. Read the dict items, the fields and the instance attributes (a tensor+ # counted twice only adds another 0 times it).+ values = list(obj.values()) if isinstance(obj, dict) else []+ values += [getattr(obj, name, None) for name in fields or ()]+ values += list(getattr(obj, "__dict__", {}).values())+ elif isinstance(obj, (list, tuple)):+ values = obj+ elif hasattr(obj, "to_tuple"):+ values = obj.to_tuple()+ else:+ return acc+ for value in values:+ acc = _float_sum(value, acc)+ return acc+++def _vision_modules(mm, tower):+ """The tower plus the connectors `get_image_features` runs after it (Llava / Gemma3 / Mllama+ `multi_modal_projector`, Gemma4 `embed_vision`, Idefics3 `connector`, ...); Qwen-VL's merger is+ inside the tower."""+ modules = [tower]+ for name in _PROJECTOR_NAMES:+ module = getattr(mm, name, None)+ if isinstance(module, torch.nn.Module) and all(module is not m for m in modules):+ modules.append(module)+ return modules+++def _managed_by_fsdp(*modules):+ """Some parameter of `modules` issues a gradient collective: a DTensor (FSDP2 reduce-scatters it,+ but only where its gradient is not None), or a replicated trainable one whose gradient is averaged+ by the all-reduce hook `fsdp2_save.reduce_unsharded_trainable_grads` installed."""+ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ try:+ from torch.distributed._tensor import DTensor+ except ImportError:+ DTensor = None+ for module in modules:+ for p in module.parameters():+ if DTensor is not None and isinstance(p, DTensor):+ return True+ if getattr(p, "_unsloth_grad_all_reduce", False):+ return True+ return False+++def _in_generate():+ try:+ from .fsdp2_native import _GENERATE_DEPTH+ return _GENERATE_DEPTH[0] > 0+ except Exception:+ return False+++def _vision_plan(model):+ """(host, image modality or None, dummy tower or None, [separate video modality]) for the vision+ encoders, or None when none issues collectives."""+ mm = _multimodal_module(model)+ if mm is None:+ inline = _inline_multimodal_module(model)+ if inline is None:+ return None+ tower = _subtree_tower(inline, _vision_tower)+ if tower is None:+ return inline, _Modality("images", _VISION_INPUTS, _NO_ENCODER), None, []+ managed = _managed_by_fsdp(*_vision_modules(inline, tower))+ if not (managed or _managed_by_fsdp(*_image_only_modules(inline, tower))):+ return None # nothing image-only issues a collective+ why = (+ "runs its vision tower inline (no get_image_features)"+ if managed+ else "skips its cross-attention layers without images"+ )+ inputs, extra = _video_modality(inline, tower)+ return inline, _Modality("images", inputs, why), None, extra+ tower = _vision_tower(mm)+ if tower is None:+ return mm, _Modality("images", _VISION_INPUTS, _NO_ENCODER), None, []+ inputs, extra = _video_modality(mm, tower)+ if not _managed_by_fsdp(*_vision_modules(mm, tower)):+ if extra: # only the separate video tower issues collectives+ return mm, None, None, extra+ return None # replicated / ignored tower and projector: no collectives to desync+ dummy = _dummy_inputs(mm, tower)+ missing = _missing_required(mm.get_image_features, dummy or {})+ if dummy is None or missing:+ why = (+ "has no dummy image input Unsloth can build"+ if dummy is None+ else f"needs {', '.join(missing)} for get_image_features, which no dummy supplies"+ )+ return mm, _Modality("images", inputs, why), None, extra++ def ready():+ inputs = _dummy_inputs(mm, tower)+ return inputs is not None and not _missing_required(mm.get_image_features, inputs)++ return mm, _Modality("images", inputs, "", ready), tower, extra+++def _audio_plan(model, vision_host = None):+ host = _audio_host(model, vision_host)+ if host is None:+ # Takes an audio input but no encoder is recognised: agree anyway, raise on mixed batches.+ for module in (+ [vision_host] + list(model.modules()) if vision_host is not None else model.modules()+ ):+ names = _audio_inputs(_forward_signature(module))+ if names:+ return module, _Modality("audio", names, _NO_ENCODER)+ return None+ if not _managed_by_fsdp(*_audio_modules(host)):+ return None+ names = _audio_inputs(_forward_signature(host))+ return host, _Modality("audio", names, "runs an audio tower Unsloth has no dummy for")+++# Forward arguments that are text (or control) inputs, never a media encoder's: everything else a+# multimodal model's forward takes is a candidate media input of the generic agreement.+_TEXT_KWARGS = frozenset(+ (+ "input_ids",+ "attention_mask",+ "labels",+ "position_ids",+ "past_key_values",+ "inputs_embeds",+ "token_type_ids",+ "cache_position",+ "use_cache",+ "logits_to_keep",+ "num_logits_to_keep",+ "num_items_in_batch",+ "output_attentions",+ "output_hidden_states",+ "output_router_logits",+ "return_dict",+ "return_loss",+ "head_mask",+ "decoder_input_ids",+ "decoder_attention_mask",+ "decoder_inputs_embeds",+ "decoder_head_mask",+ "cross_attn_head_mask",+ "encoder_outputs",+ "encoder_hidden_states",+ "encoder_attention_mask",+ "task_ids",+ "kwargs",+ "args",+ )+)+# Media inputs by name (the ones above in this module, Fuyu's image_patches, ...) or by shape of the+# name, for models whose config carries no media sub-config.+_MEDIA_KWARG_RE = re.compile(+ r"(pixel|image|img|video|audio|speech|patch|wave|mel|spectrogram|_features$|_values$)"+)+_MEDIA_CONFIG_RE = re.compile(r"(vision|visual|image|video|audio|speech)\w*_config$")+_BACKBONE_NAMES = ("language_model", "text_model", "text_decoder")+++def _forward_chain(model):+ """The outermost module and the wrapped models its forward hands kwargs to (PeftModel ->+ LoraModel -> the transformers model), outermost first."""+ chain = [model]+ for _ in range(6):+ current = chain[-1]+ inner = None+ children = current.__dict__.get("_modules", {})+ for attr in ("base_model", "model", "module", "_orig_mod"):+ child = children.get(attr) # registered children only (PeftModel forwards attributes)+ if isinstance(child, torch.nn.Module) and all(child is not c for c in chain):+ if attr == "model" and getattr(child, "config", None) is None:+ continue # a decoder stack, not a wrapped model+ inner = child+ break+ if inner is None:+ break+ chain.append(inner)+ return chain+++def _media_candidates(chain):+ """Sorted forward argument names, over the wrapper chain, that may carry a media input."""+ names = set()+ for module in chain:+ signature = _forward_signature(module)+ if signature is None:+ continue+ for name, param in signature.parameters.items():+ if name == "self" or name in _TEXT_KWARGS:+ continue+ if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):+ continue+ names.add(name)+ return sorted(names)+++def _is_multimodal(chain, candidates):+ """A media sub-config (vision_config, audio_config, audio_encoder_config, ...) on the model's+ config, or a media-looking input in its forward."""+ for module in chain:+ config = getattr(module, "config", None)+ if config is None:+ continue+ for name in list(getattr(config, "__dict__", {})):+ if _MEDIA_CONFIG_RE.search(name) and getattr(config, name, None) is not None:+ return True+ known = set(_VISION_INPUTS) | set(_AUDIO_INPUTS)+ return any(n in known or _MEDIA_KWARG_RE.search(n) for n in candidates)+++def _outside_backbone(model, chain):+ """Parameters outside the language model that are trainable or FSDP-managed (a DTensor): the+ ones a media input alone reaches. The text backbone (`language_model` / `text_model`, else the+ decoder) and the input / output embeddings do not count."""+ try:+ from torch.distributed.tensor import DTensor+ except ImportError:+ try:+ from torch.distributed._tensor import DTensor+ except ImportError:+ DTensor = None+ inside = set()+ backbones = [m for n, m in model.named_modules() if n.rsplit(".", 1)[-1] in _BACKBONE_NAMES]+ if not backbones:+ for module in chain:+ get = getattr(module, "get_decoder", None)+ try:+ decoder = get() if callable(get) else None+ except Exception:+ decoder = None+ if isinstance(decoder, torch.nn.Module) and decoder is not module:+ backbones.append(decoder)+ break+ for module in chain:+ for getter in ("get_input_embeddings", "get_output_embeddings"):+ try:+ embedding = getattr(module, getter)()+ except Exception:+ embedding = None+ if isinstance(embedding, torch.nn.Module):+ backbones.append(embedding)+ for module in backbones:+ inside.update(id(p) for p in module.parameters())+ return [+ n+ for n, p in model.named_parameters()+ if id(p) not in inside+ and (p.requires_grad or (DTensor is not None and isinstance(p, DTensor)))+ ]+++def _generic_media_plan(model, named):+ """The outermost forward agrees on every media input whenever a multimodal model has trainable+ or FSDP-managed parameters outside its language model: one bit per candidate input (a fixed,+ sorted list of forward argument names read now). Inputs a named modality covers keep its dummy;+ the others have none, so a mismatch raises on every rank. Returns (host, leftover modality or+ None), or None (text-only model, or nothing outside the backbone)."""+ chain = _forward_chain(model)+ candidates = _media_candidates(chain)+ if not candidates or not _is_multimodal(chain, candidates):+ return None+ outside = _outside_backbone(model, chain)+ if not outside:+ return None+ covered = {n for m in named for n in m.inputs}+ leftover = tuple(n for n in candidates if n not in covered)+ modality = None+ if leftover:+ modality = _Modality(+ "media",+ leftover,+ f"runs parameters outside its language model for this input (e.g. {outside[0]}) and "+ "Unsloth has no dummy for it",+ )+ modality.tensors_only = True+ return model, modality+++def install_vision_dummy(model):+ """Per-modality presence agreement on a natively sharded `model` (vision and audio encoders that+ issue gradient / gather collectives). Every forward agrees over ranks, with one small all-reduce,+ which encoder inputs each rank has; a modality present on some ranks only runs a dummy on the+ others (images, when a dummy input with every required argument can be built) or raises on every+ rank. Models with no such encoder get no hook and pay nothing. Returns the host module (the vision+ one when there is one), or None."""+ if os.environ.get("UNSLOTH_FSDP2_VISION_DUMMY", "1").strip().lower() in (+ "0",+ "false",+ "no",+ "off",+ ):+ return None+ vision = _vision_plan(model)+ audio = _audio_plan(model, vision[0] if vision is not None else None)+ hosts = {}+ for plan in (vision, audio):+ if plan is not None and not getattr(plan[0], _INSTALLED, False):+ modalities = [plan[1]] if plan[1] is not None else []+ modalities += list(plan[3]) if len(plan) > 3 else []+ hosts.setdefault(id(plan[0]), (plan[0], []))[1].extend(modalities)+ generic = (+ None+ if getattr(model, _INSTALLED, False)+ else _generic_media_plan(model, [m for _, ms in hosts.values() for m in ms])+ )+ if generic is not None:+ # One agreement, on the outermost forward (every rank runs it, and the media kwargs pass+ # through it by name): the named modalities (and their dummies) plus every other media input.+ named = [m for _, ms in hosts.values() for m in ms]+ hosts = {id(generic[0]): (generic[0], named + ([generic[1]] if generic[1] else []))}+ if not hosts:+ return None+ from .fsdp2_save import model_mesh++ for host, modalities in hosts.values():+ encoders = [_subtree_tower(host, _vision_tower)] + _audio_modules(host)+ encoders += [host.__dict__.get("_modules", {}).get(n) for n in _VIDEO_TOWER_NAMES]+ ref = next((e for e in encoders if e is not None), host)+ _install_presence_agreement(+ host, modalities, lambda ref = ref: _tower_device(ref), model_mesh(model)+ )+ if vision is None or vision[2] is None or getattr(vision[0], _INSTALLED + "_dummy", False):+ return vision[0] if vision is not None else next(iter(hosts.values()))[0]+ mm, modality, tower = vision[:3]+ state = {"pending": None, "armed": False}+ # Run the dummy where an image rank runs its tower: just before the language model (after the input+ # embeddings and Gemma4's per-layer embedding unit), so per-block layouts gather units in the same+ # order on every rank. Without a `language_model` child, before the multimodal forward.+ language_model = getattr(mm, "language_model", None)+ if not isinstance(language_model, torch.nn.Module) or language_model is tower:+ language_model = None++ def _zero_like(total, ref):+ return (0.0 * total).to(ref.dtype)++ def _dummy_total():+ return _float_sum(mm.get_image_features(**_dummy_inputs(mm, tower)))++ def lm_pre_hook(module, args, kwargs):+ if not state["armed"]:+ return None+ state["armed"] = False+ total = _dummy_total()+ if total is None:+ return None+ embeds = kwargs.get("inputs_embeds")+ if isinstance(embeds, torch.Tensor):+ # Into the decoder input, like an image rank's masked_scatter (see embed_hook).+ kwargs["inputs_embeds"] = embeds + _zero_like(total, embeds)+ return args, kwargs+ state["pending"] = total # added to the multimodal output by post_hook+ return None++ def pre_hook(module, args, kwargs):+ # After the agreement hook (registered first): run only when images are mixed and absent here.+ state["pending"] = None+ state["armed"] = False+ if not modality.run_dummy:+ return None+ if language_model is not None:+ state["armed"] = True+ return None+ total = _dummy_total()+ if total is None:+ return None+ embeds = kwargs.get("inputs_embeds")+ if isinstance(embeds, torch.Tensor):+ kwargs["inputs_embeds"] = embeds + _zero_like(total, embeds)+ return args, kwargs+ state["pending"] = total+ return None++ def embed_hook(module, args, output):+ # Into the language model's input, like an image rank's masked_scatter: the decoder units' inputs+ # then require grad on every rank, so FSDP2 runs their post-backward (reduce-scatter) at the same+ # point of the backward everywhere instead of deferring it to the final callback on this rank.+ total = state["pending"]+ if total is None or not isinstance(output, torch.Tensor):+ return None+ state["pending"] = None+ return output + _zero_like(total, output)++ def post_hook(module, args, kwargs, output):+ total = state["pending"]+ state["pending"] = None+ state["armed"] = False+ if total is None:+ return None+ zero = 0.0 * total # inputs_embeds was not built from the input embeddings: add here+ hidden = getattr(output, "last_hidden_state", None)+ if isinstance(hidden, torch.Tensor):+ output.last_hidden_state = hidden + zero.to(hidden.dtype)+ return output+ if isinstance(output, tuple) and output and isinstance(output[0], torch.Tensor):+ return (output[0] + zero.to(output[0].dtype),) + tuple(output[1:])+ if isinstance(output, torch.Tensor):+ return output + zero.to(output.dtype)+ return None++ embeddings = mm.get_input_embeddings() if hasattr(mm, "get_input_embeddings") else None+ mm.register_forward_pre_hook(pre_hook, with_kwargs = True)+ if language_model is not None:+ language_model.register_forward_pre_hook(lm_pre_hook, with_kwargs = True)+ elif isinstance(embeddings, torch.nn.Module):+ embeddings.register_forward_hook(embed_hook)+ mm.register_forward_hook(post_hook, with_kwargs = True)+ setattr(mm, _INSTALLED + "_dummy", True)+ _print_rank0(+ f"Unsloth: native FSDP2 runs {type(mm).__name__}'s vision tower on a dummy image for micro-batches "+ "when another rank has images, so every rank issues the same vision collectives (output added "+ "times 0)."+ )+ return mmdiff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex c7bfed88d5e..5112ab62505 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -5079,7 +5079,9 @@ class FastBaseModel:float32_mixed_precision = False# VLMs can hit DDP "marked ready twice" with re-entrant checkpointing (#3713), so under DDP skip the offloaded/re-entrant checkpoint patch and default native checkpoint to non-reentrant, offloading via saved-tensor hooks instead.- use_reentrant = not is_distributed()+ # FSDP2 has no DDP reducer to mark twice: each unit reduce-scatters in its own post-backward hook,+ # recompute included, so it keeps Unsloth's offloaded checkpointing (and unsloth_stream) as 1 GPU does.+ use_reentrant = not is_distributed() or fsdp2_requested()# DeepSeek-V4.1 layers consume tensors from earlier layers; reentrant GC's no_grad pass drops those grads._gc_model_type = (getattr(getattr(model, "config", None), "model_type", "") or "").lower()_force_non_reentrant = _gc_model_type.startswith(_NON_REENTRANT_GC_MODEL_TYPES)diff --git a/unsloth/save.py b/unsloth/save.pyindex 6e8aa5310f3..2a5ec462436 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -6206,21 +6206,24 @@ def _fsdp2_peft_saved_frozen(model, arguments):`selected_adapters` defaults to all), `modules_to_save` copies, and the embeddings unless`save_embedding_layers = False`."""adapters = set(getattr(model, "peft_config", None) or {})- embeddings = set()+ # By module name, not parameter identity: the gather reshards first, and a parameter an eval+ # forward left unsharded is a different object from the DTensor the gather then sees.+ embeddings = []if arguments.get("save_embedding_layers", "auto") is not False:+ names = {id(m): n for n, m in model.named_modules()}for getter in ("get_input_embeddings", "get_output_embeddings"):try:module = getattr(model, getter)()except Exception:module = None# PEFT copies every entry under the embedding module (a decoder bias too), not just weight.- if module is not None:- embeddings.update(id(p) for p in module.parameters())+ if module is not None and id(module) in names:+ embeddings.append(names[id(module)] + ".")def include(name, param):parts = name.split(".")return (- id(param) in embeddings+ any(name.startswith(prefix) for prefix in embeddings)or "modules_to_save" in partsor any(a in parts for a in adapters))