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
Keep frozen load_in_fp8 weights out of FSDP2 sharding and the DDP broadcast (#15001)
Daniel Han888c51b23b80
diff --git a/tests/test_fp8_torchao_distributed_gloo.py b/tests/test_fp8_torchao_distributed_gloo.pynew file mode 100644index 00000000000..3133f4945ab--- /dev/null+++ b/tests/test_fp8_torchao_distributed_gloo.py@@ -0,0 +1,297 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""load_in_fp8 weights (torchao Float8Tensor) under native FSDP2 and DDP, gloo world of 2, CPU only.++Float8Tensor reports bfloat16 / float32 as its dtype and implements only the ops its linear needs:+fully_shard fails on it (aten.new_zeros) and DDP's start-up broadcast fails on it (reshape to [-1]).+The frozen FP8 base is loaded identically on every rank, so it stays replicated: out of fully_shard+(ignored_params) in every layout, and out of DDP (_ddp_params_and_buffers_to_ignore), both via the load+time hook and via the trainer hook. The trainable parameters still shard / all-reduce, and the gradients+match one process run over the same rows. A trainable Float8Tensor is refused under both."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None or getattr(+ multiprocessing.current_process(), "_inheriting", False+):+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import ast # noqa: E402+import copy # noqa: E402+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_guards_gloo import _tiny_llama # noqa: E402++MODELS = os.path.join(+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "unsloth", "models"+)+_FAKE_PKG = "_fp8_torchao_ddp_pkg"+++def _extract(path, names):+ src = open(path, encoding = "utf-8").read()+ out = []+ for node in ast.parse(src).body:+ if isinstance(node, ast.FunctionDef) and node.name in names:+ out.append(ast.get_source_segment(src, node))+ elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in names:+ out.append(ast.get_source_segment(src, node))+ return "\n\n".join(out)+++def _ddp_helpers():+ """The DDP ignore-list helpers of loader_utils.py / _utils.py, without importing unsloth (GPU)."""+ lu = types.ModuleType(f"{_FAKE_PKG}.loader_utils")+ lu.__dict__.update(torch = torch, is_distributed = lambda: True)+ exec(+ _extract(+ os.path.join(MODELS, "loader_utils.py"),+ {+ "_ROTARY_INV_FREQ_BUFFER_NAMES",+ "_is_tensor_subclass_weight",+ "_frozen_tensor_subclass_names_for_ddp",+ "_exclude_rope_inv_freq_from_ddp",+ },+ ),+ lu.__dict__,+ )+ pkg = types.ModuleType(_FAKE_PKG)+ pkg.__path__ = []+ sys.modules[_FAKE_PKG] = pkg+ sys.modules[lu.__name__] = lu+ ut = {"__name__": f"{_FAKE_PKG}._utils", "__package__": _FAKE_PKG, "torch": torch, "os": os}+ exec(_extract(os.path.join(MODELS, "_utils.py"), {"_tensor_subclass_weights_for_ddp"}), ut)+ return lu, ut+++def _fp8_llama(trainable_fp8 = False):+ from torchao.quantization import Float8Tensor, PerRow++ torch.manual_seed(0)+ model = _tiny_llama()+ for name, p in model.named_parameters():+ p.requires_grad_("norm" in name) # the trainable set beside the frozen FP8 base+ for layer in model.model.layers:+ for mod in (layer.self_attn.q_proj, layer.mlp.up_proj, layer.mlp.down_proj):+ mod.weight = torch.nn.Parameter(+ Float8Tensor.from_hp(mod.weight.detach().clone(), granularity = PerRow()),+ requires_grad = trainable_fp8,+ )+ return model+++def _fp8_weights(model):+ return [p for p in model.parameters() if type(p).__name__ == "Float8Tensor"]+++def _rows(rank):+ return torch.randint(1, 100, (1, 8), generator = torch.Generator().manual_seed(100 + rank))+++def _reference_grads(model):+ """Gradients of one process over both ranks' rows (mean of the two per-row losses)."""+ ref = copy.deepcopy(model)+ for rank in (0, 1):+ ids = _rows(rank)+ (ref(input_ids = ids, labels = ids).loss / 2).backward()+ return {n: p.grad.clone() for n, p in ref.named_parameters() if p.requires_grad}+++def _grad_diff(+ model,+ want,+ canon = lambda n: n,+):+ from torch.distributed.tensor import DTensor++ worst = 0.0+ for n, p in model.named_parameters():+ if not p.requires_grad:+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ worst = max(worst, (g - want[canon(n)]).abs().max().item())+ return worst+++def _fsdp_case(native, rank, shard_frozen):+ from torch.distributed.tensor import DTensor++ model = _fp8_llama()+ want = _reference_grads(model)+ cfg = native.FSDP2Config(param_dtype = torch.float32, shard_frozen = shard_frozen)+ try:+ model = native.shard_model(model, cfg)+ except Exception as exc:+ return {"wrap": f"{type(exc).__name__}: {str(exc)[:300]}"}+ weights = _fp8_weights(model)+ res = {+ "wrap": "ok",+ "fp8": len(weights),+ "fp8_dtensor": sum(isinstance(w, DTensor) for w in weights),+ "other_dtensor": sum(isinstance(p, DTensor) for p in model.parameters()),+ }+ ids = _rows(rank)+ model(input_ids = ids, labels = ids).loss.backward()+ res["grad_diff"] = _grad_diff(model, want)+ return res+++def _ddp_case(lu, ut, rank, via):+ from torch.nn.parallel import DistributedDataParallel as DDP++ model = _fp8_llama(trainable_fp8 = via == "trainable")+ want = None if via == "trainable" else _reference_grads(model)+ try:+ if via == "load":+ lu._exclude_rope_inv_freq_from_ddp(model) # from_pretrained / get_peft_model+ elif via in ("trainer", "trainable"):+ ut["_tensor_subclass_weights_for_ddp"](types.SimpleNamespace(model = model))+ elif via == "model_init": # Trainer.call_model_init marks the rebuilt model it returns+ ut["_tensor_subclass_weights_for_ddp"](types.SimpleNamespace(model = None), model)+ ddp = DDP(model)+ except Exception as exc:+ return {"wrap": f"{type(exc).__name__}: {str(exc)[:300]}"}+ ids = _rows(rank)+ ddp(input_ids = ids, labels = ids).loss.backward()+ return {+ "wrap": "ok",+ "fp8": len(_fp8_weights(model)),+ "ignored": len(getattr(model, "_ddp_params_and_buffers_to_ignore", ())),+ "grad_diff": _grad_diff(model, want),+ }+++def _worker(rank, world, port, out, kind, arg):+ 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),+ )+ if kind == "fsdp":+ os.environ["UNSLOTH_FSDP2"] = "1"+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 30)+ )+ try:+ if kind == "fsdp":+ res = _fsdp_case(_load_native(), rank, arg)+ else:+ res = _ddp_case(*_ddp_helpers(), rank, arg)+ 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(+ kind,+ arg,+ timeout = 150,+):+ import torch.multiprocessing as mp++ out = mp.get_context("spawn").Queue()+ procs = mp.start_processes(+ _worker, args = (2, _free_port(), out, kind, arg), nprocs = 2, join = False, start_method = "spawn"+ )+ deadline = time.time() + timeout+ results = {}+ try:+ while not procs.join(timeout = 2):+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ if time.time() > deadline:+ for p in procs.processes:+ p.kill()+ pytest.fail(+ f"fp8 {kind} {arg}: the ranks did not finish (hung collective) {results}"+ )+ except mp.ProcessExitedException as exc:+ pytest.fail(f"fp8 {kind} {arg}: 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("FP8_RESULT", kind, arg, rank, r)+ assert "crash" not in r, r["crash"]+ return results++[email protected](autouse = True)+def _needs_torchao():+ pytest.importorskip("transformers")+ pytest.importorskip("torchao.quantization").Float8Tensor # noqa: B018++[email protected]("shard_frozen", [True, None], ids = ["sharded", "auto_fit"])+def test_fsdp2_keeps_float8tensor_replicated_and_matches_one_process(shard_frozen):+ for rank, r in _run("fsdp", shard_frozen).items():+ assert r["wrap"] == "ok", (rank, r)+ assert r["fp8"] > 0 and r["fp8_dtensor"] == 0, (rank, r)+ assert r["other_dtensor"] > 0, (rank, r) # the trainable norms are still sharded+ assert r["grad_diff"] < 1e-5, (rank, r)++[email protected]("via", ["load", "trainer", "model_init"])+def test_ddp_skips_float8tensor_broadcast_and_matches_one_process(via):+ for rank, r in _run("ddp", via).items():+ assert r["wrap"] == "ok", (rank, r)+ assert r["ignored"] >= r["fp8"] > 0, (rank, r)+ assert r["grad_diff"] < 1e-5, (rank, r)+++def test_trainable_float8tensor_is_refused():+ for rank, r in _run("ddp", "trainable").items():+ assert r["wrap"].startswith("NotImplementedError") and "Float8Tensor" in r["wrap"], (+ rank,+ r,+ )+ native = _load_native()+ with pytest.raises(NotImplementedError, match = "trainable float8"):+ native._float8_params(_fp8_llama(trainable_fp8 = True))+++def test_float8_training_weights_stay_with_ddp():+ # torchao.float8's training weight implements the flatten DDP's broadcast needs, and plain DDP+ # trains it: neither left out of DDP nor refused, as fsdp2_native leaves it to fully_shard.+ fsdp_utils = pytest.importorskip("torchao.float8.fsdp_utils")+ from torchao.float8.float8_training_tensor import LinearMMConfig++ lu, _ = _ddp_helpers()+ lin = torch.nn.Linear(8, 8, bias = False)+ lin.weight = torch.nn.Parameter(+ fsdp_utils.WeightWithDynamicFloat8CastTensor(+ lin.weight.detach().clone(), LinearMMConfig(), torch.float8_e4m3fn+ )+ )+ assert lu._is_tensor_subclass_weight(lin.weight) is False+ assert lu._frozen_tensor_subclass_names_for_ddp(lin, refuse_trainable = True) == []+ from torchao.quantization import Float8Tensor, PerRow++ frozen = torch.nn.Parameter(+ Float8Tensor.from_hp(torch.randn(8, 8), granularity = PerRow()), requires_grad = False+ )+ assert lu._is_tensor_subclass_weight(frozen) is Truediff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 944be100c7c..764e3508653 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -5713,6 +5713,7 @@ def patch_gradient_accumulation_fix(Trainer):_replan_auto_offload_safely(self)_size_auto_checkpoint_skip_for_trainer(self)_block_swap_for_trainer_backend(self)+ _tensor_subclass_weights_for_ddp(self)_enable_ddp_batched_grad_copy(self)from ._ddp_defaults import install_unsloth_ddp_comm_defaults@@ -5725,6 +5726,22 @@ def patch_gradient_accumulation_fix(Trainer):Trainer.__init__ = _unsloth_trainer_initTrainer._unsloth_init_wrapped_for_accelerate_gas = True+ _original_call_model_init = getattr(Trainer, "call_model_init", None)+ if _original_call_model_init is not None and not getattr(+ _original_call_model_init, "_unsloth_marks_ddp_ignores", False+ ):++ @functools.wraps(_original_call_model_init)+ def _unsloth_call_model_init(self, *args, **kwargs):+ # model_init rebuilds the model when training starts: the new instance needs the same+ # DDP exclusions as the one __init__ marked.+ model = _original_call_model_init(self, *args, **kwargs)+ _tensor_subclass_weights_for_ddp(self, model)+ return model++ _unsloth_call_model_init._unsloth_marks_ddp_ignores = True+ Trainer.call_model_init = _unsloth_call_model_init+# Idempotent: already installed at import unless Trainer was reloaded since._patch_trainer_train_gc_scope(Trainer)@@ -10003,6 +10020,43 @@ def _block_swap_for_trainer_backend(trainer):return []+def _tensor_subclass_weights_for_ddp(trainer, model = None):+ """DDP (torchrun without FSDP / DeepSpeed): keep frozen tensor subclass weights (load_in_fp8's torchao+ Float8Tensor) out of DDP's start-up broadcast, which flattens each parameter and fails on them; every+ rank loads them identically. Trainable ones are refused on every rank alike. Returns the names added."""+ from .loader_utils import is_distributed, _frozen_tensor_subclass_names_for_ddp++ if model is None:+ model = getattr(trainer, "model", None)+ if model is None or not is_distributed():+ return []+ if (+ 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+ )+ or getattr(trainer, "is_fsdp_enabled", False)+ or getattr(trainer, "is_deepspeed_enabled", False)+ ):+ return []+ names = _frozen_tensor_subclass_names_for_ddp(model, refuse_trainable = True)+ ignored = list(getattr(model, "_ddp_params_and_buffers_to_ignore", None) or [])+ seen = set(ignored)+ added = [name for name in names if name not in seen]+ if not added:+ return []+ from torch.nn.parallel import DistributedDataParallel++ DistributedDataParallel._set_params_and_buffers_to_ignore_for_model(model, ignored + added)+ if int(os.environ.get("RANK", "0") or 0) == 0:+ print(+ f"Unsloth: DDP leaves {len(added)} frozen {type(model.get_parameter(added[0])).__name__} weights "+ "out of its start-up broadcast (every rank loads them identically)."+ )+ return added++def _trainer_offload_replan_skip(trainer):"""Why the trainer must keep the attach-time plan, or None."""args = getattr(trainer, "args", None)diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 5df2e14e847..b2055663bec 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -1160,10 +1160,25 @@ _FLOAT8 = tuple()+def _is_torchao_weight(t):+ """A torchao tensor subclass weight (load_in_fp8's Float8Tensor, other torchao quantized tensors). It+ reports the high precision dtype (bfloat16), not float8, and implements only the ops its linear needs:+ fully_shard's sharding (aten.new_zeros) and DDP's flattening broadcast (reshape to [-1]) fail on it."""+ return any(c.__module__.split(".")[0] == "torchao" for c in type(t).__mro__)++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]+ the scale semantics, and a torchao Float8Tensor (load_in_fp8) cannot be sharded at all. Frozen ones stay+ replicated (every rank loads the same weights); trainable ones are refused."""+ found = [+ (n, p)+ for n, p in model.named_parameters()+ # torchao's Float8 training weights (torchao.float8, enable_fsdp_float8_all_gather) implement+ # FSDP2's all-gather hooks, so fully_shard keeps them.+ if p.dtype in _FLOAT8+ or (_is_torchao_weight(p) and not type(p).__module__.startswith("torchao.float8"))+ ]trainable = [n for n, p in found if p.requires_grad]if trainable:raise NotImplementedError(@@ -1173,7 +1188,7 @@ def _float8_params(model):if found:_print_rank0(f"Unsloth: native FSDP2 keeps {len(found)} frozen float8 weights replicated (FSDP2 would cast them "- "to the gather dtype)."+ "to the gather dtype, or cannot shard torchao's Float8Tensor).")return {p for _, p in found}diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex 6c8a88d961c..a547b4fc806 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -4479,6 +4479,45 @@ def _get_fp8_mode_and_check_settings(_ROTARY_INV_FREQ_BUFFER_NAMES = ("inv_freq", "short_inv_freq", "long_inv_freq")+def _is_tensor_subclass_weight(t):+ """A wrapper tensor subclass weight such as torchao's Float8Tensor (load_in_fp8). DDP's start-up+ broadcast flattens every parameter (reshape to [-1]), which Float8Tensor does not implement.+ torchao.float8's training weights (WeightWithDynamicFloat8CastTensor) implement it and DDP trains+ them, so they are not counted, as in fsdp2_native's _float8_params."""+ if type(t).__module__.startswith("torchao.float8"):+ return False+ if any(c.__module__.split(".")[0] == "torchao" for c in type(t).__mro__):+ return True+ try:+ from torch.distributed.tensor import DTensor+ if isinstance(t, DTensor):+ return False+ except Exception:+ pass+ try:+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass+ return is_traceable_wrapper_subclass(t)+ except Exception:+ return False+++def _frozen_tensor_subclass_names_for_ddp(model, refuse_trainable = False):+ """Frozen tensor subclass weights (load_in_fp8's Float8Tensor) stay out of DDP: every rank loads and+ quantizes the same checkpoint, so there is nothing to broadcast, and a frozen weight has no gradient to+ reduce. A trainable one would need both, which DDP cannot do for it: refused when asked."""+ frozen, trainable = [], []+ for name, p in model.named_parameters():+ if _is_tensor_subclass_weight(p):+ (trainable if p.requires_grad else frozen).append(name)+ if trainable and refuse_trainable:+ raise NotImplementedError(+ f"Unsloth: DDP cannot train the {type(model.get_parameter(trainable[0])).__name__} weight "+ f"{trainable[0]} ({len(trainable)} such weights are trainable); it cannot be broadcast or have "+ "its gradient all-reduced. Train LoRA on the frozen FP8 base (get_peft_model), or load in 16-bit."+ )+ return frozen++def _exclude_rope_inv_freq_from_ddp(model):ignored = list(getattr(model, "_ddp_params_and_buffers_to_ignore", None) or [])for module_name, module in model.named_modules():@@ -4487,6 +4526,12 @@ def _exclude_rope_inv_freq_from_ddp(model):fqn = f"{module_name}.{buffer_name}" if module_name else buffer_nameif fqn not in ignored:ignored.append(fqn)+ try:+ for fqn in _frozen_tensor_subclass_names_for_ddp(model):+ if fqn not in ignored:+ ignored.append(fqn)+ except Exception:+ passif ignored:try:from torch.nn.parallel import DistributedDataParallel