Skip to content

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.

FSDP2: keep the use_cpu reclaim reachable when only `import unsloth` wrapped the Trainer (#15427)

Daniel Han91e6a827dd76
diff --git a/tests/test_fsdp2_native_trainer_args_gloo.py b/tests/test_fsdp2_native_trainer_args_gloo.py
index cfbdf3a2aee..e6bf8bfc885 100644
--- a/tests/test_fsdp2_native_trainer_args_gloo.py
+++ b/tests/test_fsdp2_native_trainer_args_gloo.py
@@ -145,7 +145,13 @@ def _worker(rank, world, port, out, case, tmp, env):
try:
native = _load_native()
_stub_unsloth_save()
- _install_wrapped_trainer_init()
+ if case == "xpu_install_use_cpu_import_time":
+ # Only `import unsloth` ran: no loader has wrapped the Trainer yet.
+ utils = types.ModuleType("unsloth.models._utils")
+ utils.patch_gradient_accumulation_fix = lambda cls: _install_wrapped_trainer_init()
+ sys.modules["unsloth.models._utils"] = utils
+ else:
+ _install_wrapped_trainer_init()
from transformers import Trainer
res = {}
@@ -196,6 +202,19 @@ def _worker(rank, world, port, out, case, tmp, env):
res["sharded"] = native.is_native_fsdp2(trainer.model)
res["accelerate_fsdp"] = os.environ.get("ACCELERATE_USE_FSDP")
res["distributed_type"] = str(trainer.accelerator.distributed_type)
+ elif case == "xpu_install_use_cpu_import_time":
+ torch.version.cuda = None
+ torch.version.hip = None
+ torch.version.xpu = "20250101"
+ launch = sys.modules["unsloth.fsdp2_launch"]
+ # The two import-time steps of unsloth/__init__.py, in its order.
+ res["routed"] = launch.apply_unsloth_fsdp2_launch_env()
+ launch.install_native_fsdp2_trainer_init()
+ trainer = Trainer(model = _lora(1), args = _targs(os.path.join(tmp, "out")))
+ res["wrapped"] = bool(getattr(Trainer, "_test_wrapped", False))
+ res["sharded"] = native.is_native_fsdp2(trainer.model)
+ res["accelerate_fsdp"] = os.environ.get("ACCELERATE_USE_FSDP")
+ res["distributed_type"] = str(trainer.accelerator.distributed_type)
elif case == "named_adapter":
cfg = native.FSDP2Config(param_dtype = torch.float32)
ckpt = os.path.join(tmp, "ckpt")
@@ -292,6 +311,17 @@ def test_xpu_install_cpu_trainer_shards_natively(tmp_path):
assert "MULTI_CPU" in r["distributed_type"], (rank, r)
+def test_xpu_install_cpu_trainer_shards_natively_without_a_loader(tmp_path):
+ # The import-time installer used to skip the wrapper (and its CPU reclaim) on non-CUDA installs.
+ pytest.importorskip("transformers")
+ pytest.importorskip("peft")
+ for rank, r in _run("xpu_install_use_cpu_import_time", tmp_path).items():
+ assert r["routed"] is True, (rank, r)
+ assert r["wrapped"] is True, (rank, r)
+ assert r["sharded"] is True and r["accelerate_fsdp"] is None, (rank, r)
+ assert "MULTI_CPU" in r["distributed_type"], (rank, r)
+
+
# ---- launcher env (no process group) ----------------------------------------------------------
diff --git a/unsloth/fsdp2_launch.py b/unsloth/fsdp2_launch.py
index e9f3a9567b6..43eec3ccce7 100644
--- a/unsloth/fsdp2_launch.py
+++ b/unsloth/fsdp2_launch.py
@@ -612,8 +612,16 @@ def install_native_fsdp2_trainer_init():
(installed by `_utils.patch_gradient_accumulation_fix`). FastLanguageModel / FastModel loads and
DecisionTrainer install it; a model built without them (a FastSentenceTransformer encoder) left the
Trainer unwrapped, so it trained under DDP with nothing sharded and no message. Installs the wrapper
- once the flag selects native FSDP2. Returns whether it applies."""
+ once the flag selects native FSDP2, or while a non-CUDA accelerate route is pending (a use_cpu
+ Trainer reclaims native FSDP2 inside the wrapper). Returns whether it applies."""
if not unsloth_fsdp2_native_requested():
+ if _NON_CUDA_EXPORT is None:
+ return False
+ from transformers import Trainer
+
+ from .models._utils import patch_gradient_accumulation_fix
+
+ patch_gradient_accumulation_fix(Trainer)
return False
from transformers import Trainer