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: run GGUF, torchao, OpenVINO and GGML exports on rank 0 instead of refusing them (#15353)

Daniel Hand08984c7234a
diff --git a/tests/test_fsdp2_exports_gloo.py b/tests/test_fsdp2_exports_gloo.py
new file mode 100644
index 00000000000..30127213fee
--- /dev/null
+++ b/tests/test_fsdp2_exports_gloo.py
@@ -0,0 +1,600 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Whole-model exports of an FSDP2-sharded model, two gloo ranks on CPU, against one process.
+
+Every rank makes the export call, as a notebook script under torchrun does. The shards are gathered to
+rank 0, which runs the single-process export alone; rank 1 writes nothing and returns rank 0's result.
+- save_pretrained_merged (merged_16bit): the files equal a one-process merged save, tensor for tensor.
+- save_pretrained_gguf (the llama.cpp converter stubbed): rank 0 alone converts, from a 16-bit merge
+ equal to the one-process merge; both ranks return the same result.
+- push_to_hub_gguf (converter and Hub stubbed): only rank 0 talks to the Hub.
+- save_pretrained_torchao: a LoRA model with a given torchao config, and a QAT-trained full model
+ (the Qwen3 ExecuTorch notebook), equal to one process; the sharded model still trains afterwards.
+- A gathered model that does not fit rank 0's host RAM is refused on every rank, with the numbers.
+- An export that fails on rank 0 raises on every rank.
+"""
+
+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 importlib.util # noqa: E402
+import json # noqa: E402
+import sys # noqa: E402
+
+import pytest # noqa: E402
+import torch # noqa: E402
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM" # tokenizer only; the weights are built here
+
+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)
+pytest.importorskip("peft")
+HAS_TORCHAO = importlib.util.find_spec("torchao") is not None
+
+
+def _import_checkout_unsloth():
+ """`import unsloth` from this checkout, conftest's device spoof first; None or why it failed."""
+ for name in [n for n in sys.modules if n == "unsloth" or n.startswith("unsloth.")]:
+ del sys.modules[name]
+ sys.path.insert(0, REPO)
+ try:
+ spec = importlib.util.spec_from_file_location(
+ "_exports_conftest", os.path.join(REPO, "tests", "conftest.py")
+ )
+ spec.loader.exec_module(importlib.util.module_from_spec(spec))
+ import unsloth # noqa: F401
+ except Exception as e:
+ return repr(e)
+ # The spoofed device is "cuda"; the merge asks its name (T4 check) on this GPU-less host.
+ torch.cuda.get_device_name = lambda *args, **kwargs: "cpu"
+ return None
+
+
+def _make_base(directory):
+ """A small random Qwen3 checkpoint with real-sized groups (every Linear in_features % 32 == 0)."""
+ from transformers import AutoTokenizer, Qwen3Config, Qwen3ForCausalLM
+
+ tokenizer = AutoTokenizer.from_pretrained(TINY)
+ config = Qwen3Config(
+ vocab_size = len(tokenizer),
+ hidden_size = 64,
+ intermediate_size = 128,
+ num_hidden_layers = 3,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 16,
+ tie_word_embeddings = False,
+ torch_dtype = "bfloat16",
+ )
+ torch.manual_seed(0)
+ model = Qwen3ForCausalLM(config).to(torch.bfloat16)
+ model.save_pretrained(directory)
+ tokenizer.save_pretrained(directory)
+
+
+def _load(
+ base,
+ lora = True,
+ qat = None,
+):
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+ from unsloth.save import patch_saving_functions
+
+ model = AutoModelForCausalLM.from_pretrained(base, dtype = torch.bfloat16)
+ tokenizer = AutoTokenizer.from_pretrained(base)
+ if qat is not None:
+ from unsloth.models._utils import _prepare_model_for_qat
+ _prepare_model_for_qat(model, qat)
+ if lora:
+ from peft import LoraConfig, get_peft_model
+ torch.manual_seed(1)
+ model = get_peft_model(
+ model,
+ LoraConfig(
+ r = 4,
+ lora_alpha = 8,
+ target_modules = ["q_proj", "v_proj", "down_proj"],
+ init_lora_weights = False, # random B: the merge changes the weights
+ ),
+ )
+ return patch_saving_functions(model), patch_saving_functions(tokenizer)
+
+
+def _shard(model, world_size):
+ from torch.distributed.device_mesh import init_device_mesh
+ from torch.distributed.fsdp import fully_shard
+
+ mesh = init_device_mesh("cpu", (world_size,))
+ inner = model.get_base_model() if hasattr(model, "get_base_model") else model
+ for layer in inner.model.layers:
+ fully_shard(layer, mesh = mesh)
+ fully_shard(model, mesh = mesh)
+ return model
+
+
+def _all_dtensor(model):
+ from torch.distributed.tensor import DTensor
+ return all(isinstance(p, DTensor) for p in model.parameters())
+
+
+class _StubGGUF:
+ """Stands in for unsloth.save.save_to_gguf: records the call and writes a fake GGUF that lists
+ the 16-bit checkpoint it was handed."""
+
+ def __init__(
+ self,
+ rank,
+ fail = False,
+ ):
+ self.rank, self.fail, self.calls = rank, fail, []
+
+ def __call__(self, **kwargs):
+ self.calls.append(kwargs["quantization_method"])
+ if self.fail:
+ raise OSError("converter crashed")
+ directory = kwargs["gguf_directory"]
+ os.makedirs(directory, exist_ok = True)
+ path = os.path.join(directory, "model.Q8_0.gguf")
+ with open(path, "w") as f:
+ json.dump(sorted(os.listdir(kwargs["model_directory"])), f)
+ return [path], False, False
+
+
+class _StubHub:
+ """huggingface_hub.HfApi: records every call; uploads nothing."""
+
+ calls = []
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __getattr__(self, name):
+ def call(*args, **kwargs):
+ _StubHub.calls.append(name)
+ return {"name": "user"} if name == "whoami" else None
+
+ return call
+
+
+def _run_cases(rank, world_size, base, out):
+ """Every export once, each case on its own so one refusal does not hide the others. `world_size`
+ 0 is the one-process reference (no process group). A case's exception lands in `<case>_raised`."""
+ import huggingface_hub
+ import unsloth.save as save
+ from unsloth.models import fsdp2_save
+
+ sharded = world_size > 0
+ tag = f"rank{rank}" if sharded else "single"
+ result = {}
+
+ def load(**kwargs):
+ model, tokenizer = _load(base, **kwargs)
+ return (_shard(model, world_size) if sharded else model), tokenizer
+
+ def mine(name):
+ # rank 0 writes where the reference does; rank 1 gets a folder of its own, which must stay absent
+ return os.path.join(out, name if rank == 0 else f"{name}_{tag}")
+
+ def merged():
+ model, tokenizer = load()
+ result["merged_return"] = model.save_pretrained_merged(
+ mine("merged"), tokenizer, save_method = "merged_16bit"
+ )
+ result["merged_wrote"] = os.path.isdir(mine("merged"))
+
+ def gguf():
+ model, tokenizer = load()
+ stub = save.save_to_gguf = _StubGGUF(rank)
+ answer = model.save_pretrained_gguf(mine("gguf"), tokenizer, quantization_method = "q8_0")
+ result["gguf_return"] = {
+ k: answer[k] for k in ("gguf_files", "want_full_precision", "is_vlm")
+ }
+ result["gguf_calls"] = stub.calls
+ result["gguf_wrote"] = os.path.isdir(mine("gguf"))
+ result["all_dtensor_after_gguf"] = _all_dtensor(model) if sharded else None
+
+ def push_gguf():
+ model, tokenizer = load()
+ huggingface_hub.HfApi = _StubHub
+ _StubHub.calls = []
+ stub = save.save_to_gguf = _StubGGUF(rank)
+ os.chdir(out) # the push stages its folders under the working directory
+ model.push_to_hub_gguf("user/repo", tokenizer, quantization_method = "q8_0", token = "hf_x")
+ result["push_hub_calls"] = sorted(set(_StubHub.calls))
+ result["push_gguf_calls"] = stub.calls
+
+ def fail():
+ # A converter that fails on rank 0 raises on every rank.
+ model, tokenizer = load()
+ save.save_to_gguf = _StubGGUF(rank, fail = True)
+ try:
+ model.save_pretrained_gguf(mine("gguf_fail"), tokenizer)
+ result["fail_error"] = None
+ except Exception as e:
+ result["fail_error"] = f"{type(e).__name__}: {e}"
+
+ def ram():
+ # Too big for rank 0's host RAM: refused on every rank before anything is gathered.
+ model, tokenizer = load()
+ save.save_to_gguf = _StubGGUF(rank)
+ real = fsdp2_save._host_available_bytes
+ fsdp2_save._host_available_bytes = lambda: 512 * 1024**2
+ try:
+ model.save_pretrained_gguf(mine("gguf_ram"), tokenizer)
+ result["ram_error"] = None
+ except Exception as e:
+ result["ram_error"] = f"{type(e).__name__}: {e}"
+ finally:
+ fsdp2_save._host_available_bytes = real
+ result["ram_wrote"] = os.path.isdir(mine("gguf_ram"))
+
+ def estimate():
+ # An eval forward leaves the root unit gathered; the RAM and placement estimates must
+ # still count those weights, as the gather (which reshards first) will move them.
+ model, tokenizer = load()
+ full = fsdp2_save._gathered_host_bytes(model, offload_to_cpu = True, offload_4bit = True)
+ model.eval()
+ with torch.no_grad():
+ model(input_ids = torch.arange(16).reshape(2, 8))
+ result["estimate_gathered_after_eval"] = not _all_dtensor(model)
+ after = fsdp2_save._gathered_host_bytes(model, offload_to_cpu = True, offload_4bit = True)
+ result["estimate_bytes"] = (full, after)
+
+ def ptq():
+ # A LoRA model, quantized after a 16-bit merge.
+ from torchao.quantization import Int8WeightOnlyConfig
+
+ model, tokenizer = load()
+ model.save_pretrained_torchao(mine("ptq"), tokenizer, torchao_config = Int8WeightOnlyConfig())
+ result["ptq_wrote"] = os.path.isdir(mine("ptq") + "-torchao")
+
+ def qat():
+ # The ExecuTorch notebook: a full QAT model converted in place, then saved.
+ model, tokenizer = load(lora = False, qat = "phone-deployment")
+ model.save_pretrained_torchao(mine("qat"), tokenizer)
+ result["qat_wrote"] = os.path.isdir(mine("qat"))
+ if sharded:
+ # Rank 0's model is the sharded fake-quantized one again, so training goes on in step.
+ result["qat_all_dtensor_after"] = _all_dtensor(model)
+ ids = torch.arange(16).reshape(2, 8) + 100 * rank
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ result["qat_loss_after"] = float(loss)
+
+ def qat_fallback():
+ # Too big for rank 0's GPU: gathered to the CPU and converted one module at a time on the
+ # accelerator (the CPU stands in here), which must equal the whole-model convert.
+ from unsloth.models import _utils
+
+ calls = []
+ real_convert = _utils._convert_module_by_module
+ real_options = fsdp2_save.gather_on_accelerator_if_it_fits
+
+ def counted(*args, **kwargs):
+ calls.append(1)
+ return real_convert(*args, **kwargs)
+
+ _utils._convert_module_by_module = counted
+ if sharded:
+ fsdp2_save.gather_on_accelerator_if_it_fits = lambda model: dict(
+ offload_to_cpu = True, offload_4bit = True, convert_on = torch.device("cpu")
+ )
+ try:
+ model, tokenizer = load(lora = False, qat = "phone-deployment")
+ model.save_pretrained_torchao(mine("qat_fallback"), tokenizer)
+ finally:
+ _utils._convert_module_by_module = real_convert
+ fsdp2_save.gather_on_accelerator_if_it_fits = real_options
+ result["qat_fallback_wrote"] = os.path.isdir(mine("qat_fallback"))
+ result["qat_fallback_calls"] = len(calls)
+
+ def cgroup():
+ # A container is killed at its cgroup limit, not at host RAM: the check takes the smaller.
+ import builtins
+
+ root = os.path.join(out, f"cgroup_{tag}")
+ os.makedirs(os.path.join(root, "job"), exist_ok = True)
+ for name, value in (("memory.max", 4 * 1024**3), ("memory.current", 1024**3)):
+ with open(os.path.join(root, "job", name), "w") as f:
+ f.write(str(value))
+ with open(os.path.join(root, "self"), "w") as f:
+ f.write("0::/job\n")
+ real_open = builtins.open
+
+ def fake_open(path, *args, **kwargs):
+ path = str(path)
+ if path == "/proc/self/cgroup":
+ path = os.path.join(root, "self")
+ elif path.startswith("/sys/fs/cgroup"):
+ path = root + path[len("/sys/fs/cgroup") :]
+ return real_open(path, *args, **kwargs)
+
+ # cgroup v1: the limit on the parent (/job), the process in /job/worker under no limit of its own.
+ v1 = os.path.join(root, "v1")
+ os.makedirs(os.path.join(v1, "memory", "job", "worker"), exist_ok = True)
+ for where, limit, used in (("job", 2 * 1024**3, 512 * 1024**2), ("job/worker", 1 << 62, 0)):
+ for name, value in (("memory.limit_in_bytes", limit), ("memory.usage_in_bytes", used)):
+ with open(os.path.join(v1, "memory", where, name), "w") as f:
+ f.write(str(value))
+ with open(os.path.join(v1, "self"), "w") as f:
+ f.write("4:memory:/job/worker\n")
+
+ builtins.open = fake_open
+ try:
+ result["cgroup_bytes"] = (
+ fsdp2_save._cgroup_available_bytes(),
+ fsdp2_save._host_available_bytes(),
+ )
+ root = v1
+ result["cgroup_v1_bytes"] = fsdp2_save._cgroup_available_bytes()
+ finally:
+ builtins.open = real_open
+
+ def restore_devices():
+ # A replicated bias on another device than the gathered weight goes back to its own device
+ # (the meta device stands in for the GPU; CPU <-> CUDA keeps the Parameter object via .data,
+ # CPU -> meta cannot, so it gets a new one). A tensor already home is left untouched.
+ from unsloth.models import _utils
+
+ layer = torch.nn.Linear(4, 4)
+ weight = layer.weight
+ homes = {"weight": torch.device("cpu"), "bias": torch.device("meta")}
+ _utils._restore_tensor_devices(layer, homes, torch.device("cpu"))
+ result["restore_devices"] = [
+ str(layer.weight.device),
+ str(layer.bias.device),
+ layer.weight is weight,
+ isinstance(layer.bias, torch.nn.Parameter),
+ ]
+
+ def placement():
+ # 10 GiB gathered converts on a 16 GiB card only with the quantized copy counted too.
+ result["placement_need"] = fsdp2_save._accelerator_convert_bytes(10 * 1024**3)
+
+ cases = [merged, gguf, push_gguf, placement, restore_devices]
+ if sharded:
+ cases += [fail, ram, estimate, cgroup]
+ if HAS_TORCHAO:
+ cases += [ptq, qat, qat_fallback]
+ for case in cases:
+ try:
+ case()
+ except Exception as e:
+ result[f"{case.__name__}_raised"] = f"{type(e).__name__}: {e}"
+ return result
+
+
+def _worker(rank, world_size, port, base, out, queue):
+ try:
+ why = _import_checkout_unsloth()
+ if why is not None:
+ queue.put((rank, {"skip": why}))
+ return
+ if world_size:
+ import torch.distributed as dist
+ os.environ.update(
+ MASTER_ADDR = "127.0.0.1",
+ MASTER_PORT = str(port),
+ RANK = str(rank),
+ WORLD_SIZE = str(world_size),
+ )
+ dist.init_process_group("gloo", rank = rank, world_size = world_size)
+ result = _run_cases(rank, world_size, base, out)
+ queue.put((rank, result))
+ if world_size:
+ dist.destroy_process_group()
+ except BaseException as error:
+ import traceback
+ queue.put((rank, {"error": f"{type(error).__name__}: {error}\n{traceback.format_exc()}"}))
+
+
+def _spawn(world_size, base, out):
+ from tests._rendezvous_port import free_port
+
+ ctx = multiprocessing.get_context("spawn")
+ queue = ctx.Queue()
+ port = free_port()
+ ranks = range(max(world_size, 1))
+ procs = [
+ ctx.Process(target = _worker, args = (r, world_size, port, base, out, queue)) for r in ranks
+ ]
+ for p in procs:
+ p.start()
+ results = {}
+ try:
+ for _ in procs:
+ rank, result = queue.get(timeout = 900)
+ results[rank] = result
+ finally:
+ for p in procs:
+ p.join(timeout = 60)
+ if p.is_alive():
+ p.terminate()
+ for r in results.values():
+ if "skip" in r:
+ pytest.skip(f"import unsloth failed on this host: {r['skip']}")
+ assert "error" not in r, r.get("error")
+ return results
+
+
+def _tensors(directory):
+ """name -> tensor of every weight file in `directory` (safetensors or torch pickles)."""
+ from safetensors.torch import load_file
+
+ tensors = {}
+ for name in sorted(os.listdir(directory)):
+ path = os.path.join(directory, name)
+ if name.endswith(".safetensors"):
+ tensors.update(load_file(path))
+ elif name.endswith(".bin") and "training_args" not in name:
+ tensors.update(torch.load(path, map_location = "cpu", weights_only = False))
+ return tensors
+
+
+def _plain(t):
+ """A comparable plain tensor: a torchao quantized tensor by its inner data (qdata, scales, ...)."""
+ if hasattr(t, "__tensor_flatten__") and type(t) is not torch.Tensor:
+ names, _ = t.__tensor_flatten__()
+ return [_plain(getattr(t, n)) for n in names]
+ return t.detach().cpu()
+
+
+def _same(a, b):
+ if isinstance(a, list):
+ return isinstance(b, list) and len(a) == len(b) and all(map(_same, a, b))
+ return a.dtype == b.dtype and a.shape == b.shape and torch.equal(a, b)
+
+
+def _assert_same_files(single, sharded):
+ a, b = _tensors(single), _tensors(sharded)
+ assert a and sorted(a) == sorted(b), (sorted(a), sorted(b))
+ differ = [k for k in a if not _same(_plain(a[k]), _plain(b[k]))]
+ assert not differ, differ
+
+
+def _no_raise(runs, case):
+ for where, result in [("one process", runs["single"])] + [
+ (f"rank {r}", runs["ranks"][r]) for r in (0, 1)
+ ]:
+ raised = result.get(f"{case}_raised")
+ assert raised is None, f"{case} raised on {where}: {raised}"
+
+
[email protected](scope = "module")
+def runs(tmp_path_factory):
+ root = tmp_path_factory.mktemp("fsdp2_exports")
+ base = str(root / "base")
+ # Built here with transformers alone: `import unsloth` happens only in the spawned processes,
+ # so this one keeps the unsloth modules other test files imported (and monkeypatch).
+ _make_base(base)
+ single, sharded = root / "single", root / "sharded"
+ single.mkdir()
+ sharded.mkdir()
+ saved = os.environ.get("CUDA_VISIBLE_DEVICES")
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
+ try:
+ one = _spawn(0, base, str(single))[0]
+ two = _spawn(2, base, str(sharded))
+ finally:
+ if saved is None:
+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)
+ else:
+ os.environ["CUDA_VISIBLE_DEVICES"] = saved
+ return {"single": one, "ranks": two, "single_dir": single, "sharded_dir": sharded}
+
+
+def test_merged_16bit_equals_one_process(runs):
+ _no_raise(runs, "merged")
+ for rank in (0, 1):
+ assert runs["ranks"][rank]["merged_return"] is None
+ assert not runs["ranks"][1]["merged_wrote"]
+ _assert_same_files(runs["single_dir"] / "merged", runs["sharded_dir"] / "merged")
+
+
+def test_gguf_runs_on_rank0_only_from_the_same_merge(runs):
+ _no_raise(runs, "gguf")
+ r0, r1 = runs["ranks"][0], runs["ranks"][1]
+ assert r0["gguf_calls"] == [["q8_0"]] and r1["gguf_calls"] == [], (r0, r1)
+ assert not r1["gguf_wrote"]
+ assert r0["all_dtensor_after_gguf"] and r1["all_dtensor_after_gguf"]
+ # Every rank returns rank 0's answer.
+ assert r0["gguf_return"] == r1["gguf_return"]
+ single = runs["single"]["gguf_return"]
+ assert [os.path.basename(p) for p in single["gguf_files"]] == [
+ os.path.basename(p) for p in r0["gguf_return"]["gguf_files"]
+ ]
+ # The 16-bit checkpoint the converter was handed equals the one-process one.
+ _assert_same_files(runs["single_dir"] / "gguf", runs["sharded_dir"] / "gguf")
+
+
+def test_push_to_hub_gguf_uploads_from_rank0_only(runs):
+ _no_raise(runs, "push_gguf")
+ r0, r1 = runs["ranks"][0], runs["ranks"][1]
+ assert "create_commit" in r0["push_hub_calls"] or "upload_file" in r0["push_hub_calls"], r0
+ assert r0["push_gguf_calls"] == [["q8_0"]]
+ assert r1["push_hub_calls"] == [] and r1["push_gguf_calls"] == [], r1
+
+
+def test_a_rank0_failure_raises_on_every_rank(runs):
+ _no_raise(runs, "fail")
+ r0, r1 = runs["ranks"][0], runs["ranks"][1]
+ assert r0["fail_error"] and "converter crashed" in r0["fail_error"], r0["fail_error"]
+ assert r1["fail_error"] and "failed on rank 0" in r1["fail_error"], r1["fail_error"]
+ assert "converter crashed" in r1["fail_error"]
+
+
+def test_too_big_for_host_ram_is_refused_on_every_rank(runs):
+ _no_raise(runs, "ram")
+ for rank in (0, 1):
+ error = runs["ranks"][rank]["ram_error"]
+ assert error and "host RAM" in error and "0.5 GiB is available" in error, error
+ assert not runs["ranks"][rank]["ram_wrote"]
+
+
+def test_export_estimate_counts_units_an_eval_forward_left_gathered(runs):
+ _no_raise(runs, "estimate")
+ for rank in (0, 1):
+ res = runs["ranks"][rank]
+ assert res["estimate_gathered_after_eval"], "the eval forward must leave a unit gathered"
+ full, after = res["estimate_bytes"]
+ assert full > 0 and after == full, res["estimate_bytes"]
+
+
[email protected](not HAS_TORCHAO, reason = "torchao not installed")
+def test_torchao_lora_ptq_equals_one_process(runs):
+ _no_raise(runs, "ptq")
+ assert runs["ranks"][0]["ptq_wrote"] and not runs["ranks"][1]["ptq_wrote"]
+ _assert_same_files(runs["single_dir"] / "ptq-torchao", runs["sharded_dir"] / "ptq-torchao")
+
+
[email protected](not HAS_TORCHAO, reason = "torchao not installed")
+def test_torchao_qat_full_model_equals_one_process_and_keeps_training(runs):
+ _no_raise(runs, "qat")
+ r0, r1 = runs["ranks"][0], runs["ranks"][1]
+ assert r0["qat_wrote"] and not r1["qat_wrote"]
+ assert r0["qat_all_dtensor_after"] and r1["qat_all_dtensor_after"]
+ assert r0["qat_loss_after"] == r0["qat_loss_after"] # finite, not NaN
+ _assert_same_files(runs["single_dir"] / "qat", runs["sharded_dir"] / "qat")
+
+
[email protected](not HAS_TORCHAO, reason = "torchao not installed")
+def test_torchao_qat_fallback_converts_module_by_module_and_equals_one_process(runs):
+ _no_raise(runs, "qat_fallback")
+ r0, r1 = runs["ranks"][0], runs["ranks"][1]
+ assert r0["qat_fallback_wrote"] and not r1["qat_fallback_wrote"]
+ assert r0["qat_fallback_calls"] > 0 and r1["qat_fallback_calls"] == 0
+ assert runs["single"]["qat_fallback_calls"] == 0
+ _assert_same_files(runs["single_dir"] / "qat_fallback", runs["sharded_dir"] / "qat_fallback")
+
+
+def test_host_ram_check_honours_the_cgroup_limit(runs):
+ _no_raise(runs, "cgroup")
+ limit, available = runs["ranks"][0]["cgroup_bytes"]
+ assert limit == 3 * 1024**3 and available <= limit, runs["ranks"][0]["cgroup_bytes"]
+ assert runs["ranks"][0]["cgroup_v1_bytes"] == 1536 * 1024**2, runs["ranks"][0][
+ "cgroup_v1_bytes"
+ ]
+
+
+def test_gpu_placement_counts_the_converted_copy(runs):
+ _no_raise(runs, "placement")
+ assert runs["single"]["placement_need"] == 15 * 1024**3
+
+
+def test_module_by_module_convert_restores_each_tensor_device(runs):
+ _no_raise(runs, "restore_devices")
+ assert list(runs["single"]["restore_devices"]) == ["cpu", "meta", True, True]
diff --git a/tests/test_fsdp2_save_coverage.py b/tests/test_fsdp2_save_coverage.py
index f3ada289115..19b6a3ccaf6 100644
--- a/tests/test_fsdp2_save_coverage.py
+++ b/tests/test_fsdp2_save_coverage.py
@@ -3,9 +3,9 @@
"""Which exports run under FSDP2 (unsloth/save.py). save_pretrained and save_pretrained_merged
already gather the shards to rank 0; push_to_hub_merged and push_to_hub did not, so every rank
-merged and uploaded its own shards. They now gather like the saves. GGUF and torchao exports
-rebuild or quantize the whole model in-process and are refused under FSDP2 with a way to get the
-same file. No GPU work: FSDP2 is faked by fsdp2_units, the gather by a recording context manager."""
+merged and uploaded its own shards. They now gather like the saves. GGUF, torchao, OpenVINO and
+GGML exports rebuild or quantize the whole model in-process: rank 0 runs them alone on the
+gathered model (tests/test_fsdp2_exports_gloo.py runs them for real). No GPU work: FSDP2 is faked by fsdp2_units, the gather by a recording context manager."""
import contextlib
@@ -71,27 +71,120 @@ def test_push_to_hub_gathers(fake_fsdp2):
@pytest.mark.parametrize(
- "method, call",
+ "method, call, adapter_only",
[
- ("save_pretrained_gguf", lambda m: unsloth_save.unsloth_save_pretrained_gguf(m, "out")),
- ("push_to_hub_gguf", lambda m: unsloth_save.unsloth_push_to_hub_gguf(m, "user/repo")),
+ (
+ "save_pretrained_gguf",
+ lambda m: unsloth_save.unsloth_save_pretrained_gguf(m, "out"),
+ False,
+ ),
+ (
+ "save_pretrained_gguf",
+ lambda m: unsloth_save.unsloth_save_pretrained_gguf(m, "out", save_method = "lora"),
+ True,
+ ),
+ (
+ "push_to_hub_gguf",
+ lambda m: unsloth_save.unsloth_push_to_hub_gguf(m, "user/repo"),
+ False,
+ ),
(
"save_pretrained_torchao",
lambda m: unsloth_save.unsloth_save_pretrained_torchao(m, "out"),
+ False,
+ ),
+ (
+ "save_pretrained_openvino",
+ lambda m: unsloth_save.unsloth_save_pretrained_openvino(m, "out"),
+ False,
+ ),
+ (
+ "push_to_hub_openvino",
+ lambda m: unsloth_save.unsloth_push_to_hub_openvino(m, "user/repo"),
+ False,
+ ),
+ (
+ "save_pretrained_ggml",
+ lambda m: unsloth_save.unsloth_convert_lora_to_ggml_and_save_locally(m, "out", None),
+ True,
+ ),
+ (
+ "push_to_hub_ggml",
+ lambda m: unsloth_save.unsloth_convert_lora_to_ggml_and_push_to_hub(
+ m, None, "user/repo"
+ ),
+ True,
),
],
)
-def test_gguf_and_torchao_are_refused_under_fsdp2(fake_fsdp2, method, call):
- with pytest.raises(
- RuntimeError, match = rf"`{method}` does not support a model sharded by FSDP2"
+def test_whole_model_exports_run_on_rank0_under_fsdp2(monkeypatch, method, call, adapter_only):
+ """GGUF, torchao, OpenVINO and GGML exports used to be refused (or, for OpenVINO and GGML, ran
+ on every rank over its own shards). Under FSDP2 they now gather and run on rank 0 alone:
+ a non-writer rank gets rank 0's answer without running the export."""
+ from peft import LoraConfig, get_peft_model
+
+ seen = []
+
+ def export(
+ model,
+ run,
+ name,
+ trainable_only = False,
+ **options,
+ ):
+ seen.append((name, trainable_only, sorted(options)))
+ return "rank 0's result"
+
+ monkeypatch.setattr(fsdp2_save, "fsdp2_units", lambda model: [object()])
+ monkeypatch.setattr(fsdp2_save, "fsdp2_gather_active", lambda: False)
+ monkeypatch.setattr(fsdp2_save, "fsdp2_export_on_writer", export)
+ model = get_peft_model(_tiny_llama(), LoraConfig(r = 2, target_modules = ["q_proj"]))
+ assert call(model) == "rank 0's result"
+ assert len(seen) == 1 and seen[0][0] == method and seen[0][1] is adapter_only, seen
+ # A full export stages the packed 4-bit base on the CPU, as save_pretrained_merged does.
+ if not adapter_only:
+ assert "offload_4bit" in seen[0][2], seen
+
+
+def test_qat_torchao_export_converts_where_one_gpu_would(monkeypatch):
+ """A QAT model saved with its own config is converted in place: rank 0 keeps the gathered
+ weights on its GPU when they fit (as one GPU converts them). A given torchao_config quantizes a
+ reload of a 16-bit save, so the weights go to the CPU as for every other export."""
+ seen = []
+
+ def export(
+ model,
+ run,
+ name,
+ trainable_only = False,
+ **options,
):
- call(_tiny_llama())
- assert fake_fsdp2 == []
+ seen.append(options)
+
+ monkeypatch.setattr(fsdp2_save, "fsdp2_units", lambda model: [object()])
+ monkeypatch.setattr(fsdp2_save, "fsdp2_gather_active", lambda: False)
+ monkeypatch.setattr(fsdp2_save, "fsdp2_export_on_writer", export)
+ monkeypatch.setattr(
+ fsdp2_save, "gather_on_accelerator_if_it_fits", lambda model: {"offload_to_cpu": "gpu"}
+ )
+ model = _tiny_llama()
+ model._torchao_config = object()
+ unsloth_save.unsloth_save_pretrained_torchao(model, "out")
+ unsloth_save.unsloth_save_pretrained_torchao(model, "out", torchao_config = object())
+ assert seen == [{"offload_to_cpu": "gpu"}, dict(offload_to_cpu = True, offload_4bit = True)]
-def test_refusal_passes_through_without_fsdp2(monkeypatch):
+def test_rank0_export_passes_through_without_fsdp2(monkeypatch):
monkeypatch.setattr(fsdp2_save, "fsdp2_units", lambda model: [])
- export = unsloth_save._fsdp2_refuses_save("save_pretrained_gguf")(lambda self, x: ("ran", x))
+ export = unsloth_save._fsdp2_export_on_rank0("save_pretrained_gguf")(lambda self, x: ("ran", x))
+ assert export(object(), 1) == ("ran", 1)
+
+
+def test_rank0_export_passes_through_inside_a_gather(monkeypatch):
+ # push_to_hub_gguf -> save_pretrained_gguf: the outer call already gathered.
+ monkeypatch.setattr(fsdp2_save, "fsdp2_units", lambda model: [object()])
+ monkeypatch.setattr(fsdp2_save, "fsdp2_gather_active", lambda: True)
+ export = unsloth_save._fsdp2_export_on_rank0("save_pretrained_gguf")(lambda self, x: ("ran", x))
assert export(object(), 1) == ("ran", 1)
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 43919e3879d..413be5b0d9c 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -8731,6 +8731,72 @@ def _merged_torchao_config_for_peft_qat(model):
return TorchAoConfig(quant_type = ModuleFqnToConfig(module_to_fqn_dict), **kwargs)
+# Set by an FSDP2 export whose gathered weights sit on the CPU (fsdp2_save._torchao_convert_device).
+_TORCHAO_CONVERT_DEVICE = []
+
+
+def _convert_module_by_module(model, base_config, filter_fn, device):
+ """`_convert_torchao_model`'s two quantize_ calls, one selected module at a time on `device`, each
+ converted module moved back to where its weights were. One GPU converts on the GPU, and CUDA and
+ CPU round torchao's scales differently for fp32 weights."""
+ from torchao.quantization import quantize_
+ from torchao.quantization.qat import QATConfig
+ from torchao.quantization.quant_api import _is_linear
+ import itertools
+
+ select = filter_fn or _is_linear
+ unquantized = _unquantized_filter(filter_fn)
+ targets = []
+ for fqn, module in model.named_modules():
+ if fqn and select(module, fqn):
+ home = next(itertools.chain(module.parameters(), module.buffers()), None)
+ # Per tensor: a bias FSDP2 replicates (ignored_params) stays on the GPU while the
+ # gathered weight sits on the CPU, and each must go back where it was.
+ homes = {
+ name: t.device
+ for name, t in itertools.chain(module.named_parameters(), module.named_buffers())
+ }
+ targets.append((fqn, module, home.device if home is not None else None, homes))
+ for fqn, module, home, homes in targets:
+ parent_fqn, _, child = fqn.rpartition(".")
+ parent = model.get_submodule(parent_fqn)
+ if getattr(parent, child, None) is not module:
+ continue
+ module.to(device)
+ quantize_(
+ parent,
+ QATConfig(base_config, step = "convert"),
+ filter_fn = lambda m, _, old = module: m is old and select(m, fqn),
+ )
+ new = getattr(parent, child)
+ quantize_(parent, base_config, filter_fn = lambda m, _, n = new: m is n and unquantized(m, fqn))
+ if home is not None:
+ _restore_tensor_devices(getattr(parent, child), homes, home)
+ # The replaced module may still be referenced (a kept module tree, a tied weight).
+ _restore_tensor_devices(module, homes, home)
+
+
+def _restore_tensor_devices(module, homes, default):
+ """Move each parameter / buffer of `module` to `homes[name]` (else `default`), keeping
+ Parameter objects (optimizer state and FSDP2 hold them)."""
+ for prefix, sub in module.named_modules():
+ for store in (sub._parameters, sub._buffers):
+ for key, tensor in list(store.items()):
+ if tensor is None:
+ continue
+ target = homes.get(f"{prefix}.{key}" if prefix else key, default)
+ if tensor.device == target:
+ continue
+ if not isinstance(tensor, torch.nn.Parameter):
+ store[key] = tensor.to(target)
+ continue
+ moved = tensor.data.to(target)
+ try:
+ tensor.data = moved
+ except RuntimeError: # a tensor subclass that refuses .data swaps
+ store[key] = torch.nn.Parameter(moved, requires_grad = tensor.requires_grad)
+
+
def _convert_torchao_model(model):
from transformers import TorchAoConfig
from torchao.quantization import quantize_, ModuleFqnToConfig
@@ -8739,10 +8805,14 @@ def _convert_torchao_model(model):
_materialize_offloaded_fake_quantized_embeddings(model)
module_to_fqn_dict = {}
+ device = _TORCHAO_CONVERT_DEVICE[-1] if _TORCHAO_CONVERT_DEVICE else None
for base_config, filter_fn in model._torchao_config.base_config_and_filter_fns:
- quantize_(model, QATConfig(base_config, step = "convert"), filter_fn = filter_fn)
- # The QAT notebook's manual QATConfig(step = "convert") leaves plain, unquantized modules.
- quantize_(model, base_config, filter_fn = _unquantized_filter(filter_fn))
+ if device is not None:
+ _convert_module_by_module(model, base_config, filter_fn, device)
+ else:
+ quantize_(model, QATConfig(base_config, step = "convert"), filter_fn = filter_fn)
+ # The QAT notebook's manual QATConfig(step = "convert") leaves plain, unquantized modules.
+ quantize_(model, base_config, filter_fn = _unquantized_filter(filter_fn))
if filter_fn is None:
if "_default" in module_to_fqn_dict:
diff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.py
index a212ee41953..42e25d4eee9 100644
--- a/unsloth/models/fsdp2_save.py
+++ b/unsloth/models/fsdp2_save.py
@@ -11,6 +11,7 @@ __all__ = [
"fsdp2_units",
"fsdp2_gathered",
"fsdp2_gather_active",
+ "fsdp2_export_on_writer",
"mesh_writer_rank",
"writes_off_rank0",
"install_dcp_bnb_state_dict",
@@ -281,11 +282,9 @@ def fsdp2_gathered(
if not units or DTensor is None:
yield None
return
- for unit in units:
- # An eval forward leaves the last block and the lm_head unit gathered; make every
- # parameter a DTensor again so all ranks gather the same list.
- if hasattr(unit, "reshard"):
- unit.reshard()
+ # An eval forward leaves the last block and the lm_head unit gathered; make every
+ # parameter a DTensor again so all ranks gather the same list.
+ _reshard_units(units)
dist = _dist()
rank = dist.get_rank() if dist is not None else 0
writer_rank = mesh_writer_rank(model)
@@ -484,6 +483,338 @@ def fsdp2_gather_active():
return bool(_ACTIVE)
+_EXPORT_COUNTER = {}
+_GIB = 1024**3
+
+
+def _reshard_units(units):
+ for unit in units:
+ if hasattr(unit, "reshard"):
+ unit.reshard()
+
+
+def _gathered_host_bytes(
+ model,
+ trainable_only = False,
+ include = None,
+ offload_to_cpu = True,
+ offload_4bit = False,
+):
+ """Bytes `fsdp2_gathered` with these options leaves in the writer's host RAM: every selected
+ sharded parameter it moves to the CPU, at its full (global) size."""
+ DTensor = _dtensor_class()
+ if DTensor is None:
+ return 0
+ # Counted as the gather will find them: it reshards first, so an eval forward's still
+ # gathered units are DTensors again by then.
+ _reshard_units(fsdp2_units(model))
+ total = 0
+ seen = set()
+ for name, param in model.named_parameters():
+ if id(param) in seen or not isinstance(param, DTensor):
+ continue
+ seen.add(id(param))
+ if trainable_only and not param.requires_grad and not (include and include(name, param)):
+ continue
+ offload = offload_to_cpu(name, param) if callable(offload_to_cpu) else offload_to_cpu
+ if not offload:
+ continue
+ if getattr(param, "quant_state", None) is not None and not offload_4bit:
+ continue
+ total += param.numel() * param.element_size()
+ return total
+
+
+def _cgroup_available_bytes():
+ """Bytes left under this process's cgroup memory limits (v2 memory.max - memory.current over the
+ cgroup and its parents, v1 memory.limit_in_bytes - memory.usage_in_bytes), or None without one.
+ A container (Docker, Kubernetes, Kaggle, Colab) is killed at its limit, not at host RAM."""
+
+ def read(path):
+ try:
+ with open(path, encoding = "utf-8") as f:
+ value = f.read().strip()
+ return None if value == "max" else int(value)
+ except Exception:
+ return None
+
+ left = []
+ try:
+ with open("/proc/self/cgroup", encoding = "utf-8") as f:
+ lines = f.read().splitlines()
+ except Exception:
+ return None
+ for line in lines:
+ hierarchy, controllers, path = (line.split(":", 2) + ["", ""])[:3]
+ if hierarchy == "0" and controllers == "":
+ parts = [p for p in path.split("/") if p]
+ for depth in range(len(parts), -1, -1):
+ base = os.path.join("/sys/fs/cgroup", *parts[:depth])
+ limit, used = (
+ read(os.path.join(base, "memory.max")),
+ read(os.path.join(base, "memory.current")),
+ )
+ if limit is not None and used is not None:
+ left.append(limit - used)
+ elif "memory" in controllers.split(","):
+ # A limit may sit on any ancestor (/job over /job/worker): every level counts, as in v2.
+ parts = [p for p in path.split("/") if p]
+ for depth in range(len(parts), -1, -1):
+ base = os.path.join("/sys/fs/cgroup/memory", *parts[:depth])
+ limit = read(os.path.join(base, "memory.limit_in_bytes"))
+ used = read(os.path.join(base, "memory.usage_in_bytes"))
+ if limit is not None and used is not None and limit < (1 << 60):
+ left.append(limit - used)
+ return max(0, min(left)) if left else None
+
+
+def _host_available_bytes():
+ """Host RAM this process could still allocate, or None when it cannot be read."""
+ available = None
+ try:
+ import psutil
+ available = int(psutil.virtual_memory().available)
+ except Exception:
+ pass
+ if available is None:
+ try:
+ with open("/proc/meminfo", encoding = "utf-8") as f:
+ for line in f:
+ if line.startswith("MemAvailable:"):
+ available = int(line.split()[1]) * 1024
+ break
+ except Exception:
+ pass
+ cgroup = _cgroup_available_bytes()
+ if cgroup is not None:
+ available = cgroup if available is None else min(available, cgroup)
+ return available
+
+
+def _accelerator_convert_bytes(gathered):
+ # The gathered weights stay alive while the convert allocates their quantized copies (int8 of
+ # 16-bit weights is half their size, int4 a quarter), so both must fit at once.
+ return gathered + gathered // 2
+
+
+def gather_on_accelerator_if_it_fits(model):
+ """`fsdp2_gathered` options for an export that quantizes the weights in place, where they sit
+ (torchao's QAT convert). On one GPU they sit on the GPU, so the writer keeps the gathered weights
+ on its accelerator when they fit there (with 1 GiB or 10% of the card spare), and the checkpoint
+ is the one a single GPU writes. Otherwise they go to the CPU as for any other export."""
+ on_cpu = dict(offload_to_cpu = True, offload_4bit = True)
+ if not isinstance(model, torch.nn.Module):
+ return on_cpu
+ DTensor = _dtensor_class()
+ _reshard_units(fsdp2_units(model))
+ param = next(
+ (p for p in model.parameters() if DTensor is not None and isinstance(p, DTensor)),
+ None,
+ )
+ if param is None:
+ return on_cpu
+ device = param.to_local().device
+ mesh_type = param.device_mesh.device_type
+ if device.type == "cpu" and mesh_type != "cpu":
+ # CPUOffloadPolicy keeps the shards on the host; the model still computes on the mesh device.
+ try:
+ device = torch.device(mesh_type, getattr(torch, mesh_type).current_device())
+ except Exception:
+ return on_cpu
+ if device.type == "cpu":
+ return on_cpu
+ try:
+ free, total = getattr(torch, device.type).mem_get_info(device)
+ except Exception:
+ return on_cpu
+ need = _accelerator_convert_bytes(
+ _gathered_host_bytes(model, offload_to_cpu = True, offload_4bit = True)
+ )
+ if need + max(_GIB, total // 10) > free:
+ if mesh_writer_rank(model) == (_dist().get_rank() if _dist() is not None else 0):
+ print(
+ f"Unsloth: FSDP2 export: the gathered model and its converted copy ({need / _GIB:.1f} GiB) do not fit the "
+ f"{free / _GIB:.1f} GiB free on {device}, so it is gathered to the CPU and converted "
+ f"one module at a time on {device}."
+ )
+ # Not on the CPU: CUDA computes torchao's `scale = max / 7.5` as max * (1 / 7.5), the CPU
+ # divides, and for fp32 weights the two differ in the last bit of most scales.
+ return dict(on_cpu, convert_on = device)
+ return dict(offload_to_cpu = False, offload_4bit = False)
+
+
+def _host_ram_refusal(method, need):
+ """None when `need` gathered bytes fit this host's available RAM, else the refusal message."""
+ if os.environ.get("UNSLOTH_FSDP2_EXPORT_SKIP_RAM_CHECK", "0") == "1":
+ return None
+ available = _host_available_bytes()
+ if available is None:
+ return None
+ headroom = max(2 * _GIB, need // 10)
+ if need + headroom <= available:
+ return None
+ return (
+ f"Unsloth: `{method}` under FSDP2 gathers the whole model into the host RAM of the rank that "
+ f"exports: that needs about {(need + headroom) / _GIB:.1f} GiB ({need / _GIB:.1f} GiB of "
+ f"gathered weights + {headroom / _GIB:.1f} GiB headroom), but only {available / _GIB:.1f} GiB "
+ "is available. Save the adapter with `model.save_pretrained(save_directory)` (it gathers only "
+ "the LoRA weights), then in a single process load that folder with "
+ f"`FastLanguageModel.from_pretrained` and call `{method}` there. Set "
+ "UNSLOTH_FSDP2_EXPORT_SKIP_RAM_CHECK=1 to export anyway."
+ )
+
+
+def _share_from_writer(
+ dist,
+ writer,
+ writer_rank,
+ tag,
+ payload = None,
+):
+ """The writer's `payload` on every rank, passed through the default store (not a collective,
+ so a rank may wait for it as long as an export takes). Without a store, None off the writer."""
+ import pickle
+
+ try:
+ store = dist.distributed_c10d._get_default_store()
+ except Exception:
+ store = None
+ if store is None:
+ return payload if writer else None
+ counter = _EXPORT_COUNTER.setdefault(writer_rank, {})
+ counter[tag] = counter.get(tag, 0) + 1
+ key = f"unsloth_fsdp2_export_r{writer_rank}_{tag}_{counter[tag]}"
+ if writer:
+ try:
+ data = pickle.dumps(payload)
+ except Exception:
+ data = pickle.dumps(None)
+ store.set(key, data)
+ return payload
+ store.wait([key], _save_timeout())
+ return pickle.loads(store.get(key))
+
+
+def _module_tree_kept(model):
+ """Puts back every submodule an export swapped out in place (torchao's QAT convert replaces
+ each fake-quantized Linear), and the config's quantization_config, so the writer's model stays
+ the sharded model the other ranks hold. The swapped-in modules only carried gathered weights."""
+ saved = [(module, dict(module._modules)) for module in model.modules()]
+ config = getattr(model, "config", None)
+ missing = object()
+ quantization_config = (
+ config.__dict__.get("quantization_config", missing) if config is not None else missing
+ )
+ try:
+ yield
+ finally:
+ for module, children in saved:
+ current = module._modules
+ if current.keys() != children.keys() or any(
+ current[k] is not v for k, v in children.items()
+ ):
+ current.clear()
+ current.update(children)
+ if config is not None:
+ if quantization_config is missing:
+ config.__dict__.pop("quantization_config", None)
+ else:
+ config.__dict__["quantization_config"] = quantization_config
+
+
+def _torchao_convert_device(device):
+ """While set, unsloth's in-place torchao QAT convert moves each module it converts to `device`,
+ converts it there and moves it back (`_convert_torchao_model`)."""
+ if device is None:
+ yield
+ return
+ from . import _utils
+
+ _utils._TORCHAO_CONVERT_DEVICE.append(device)
+ try:
+ yield
+ finally:
+ _utils._TORCHAO_CONVERT_DEVICE.pop()
+
+
+def fsdp2_export_on_writer(
+ model,
+ run,
+ method,
+ trainable_only = False,
+ include = None,
+ offload_to_cpu = True,
+ offload_4bit = False,
+ convert_on = None,
+):
+ """An export that rebuilds or quantizes the whole model in one process (GGUF, torchao, OpenVINO),
+ on a model FSDP2 shards. Every rank must call it. The writer (global rank 0, or the lowest rank
+ of a sub-mesh) first checks the gathered weights fit its host RAM, and every rank refuses if
+ not. Then the shards are gathered to the writer's CPU, the writer alone calls `run()`, the
+ ordinary single-process export, and the others wait on the store (a GGUF build can outlast any
+ collective timeout). Every rank returns the writer's result, or raises if the writer raised."""
+ dist = _dist()
+ rank = dist.get_rank() if dist is not None else 0
+ writer_rank = mesh_writer_rank(model)
+ writer = rank == writer_rank
+ refusal = None
+ if writer:
+ need = _gathered_host_bytes(model, trainable_only, include, offload_to_cpu, offload_4bit)
+ refusal = _host_ram_refusal(method, need)
+ if dist is not None:
+ refusal = _share_from_writer(dist, writer, writer_rank, "fit", refusal)
+ if refusal:
+ raise RuntimeError(refusal)
+ if writer:
+ print(
+ f"Unsloth: FSDP2 {method}: gathering the "
+ + ("trainable" if trainable_only else "sharded")
+ + f" weights to rank {writer_rank}, which exports alone; the other ranks wait for it."
+ )
+ outcome = None
+ error = None
+ try:
+ with fsdp2_gathered(
+ model,
+ trainable_only = trainable_only,
+ offload_to_cpu = offload_to_cpu,
+ include = include,
+ offload_4bit = offload_4bit,
+ ) as gathered_writer:
+ if gathered_writer is not False:
+ try:
+ with _module_tree_kept(model), _torchao_convert_device(convert_on):
+ outcome = ("ok", run())
+ except BaseException as e:
+ error = e
+ outcome = ("error", f"{type(e).__name__}: {e}")
+ if dist is not None:
+ # Published before the gather's own release, so it is there once the others wake.
+ _share_from_writer(dist, True, writer_rank, "result", outcome)
+ except BaseException as e:
+ if writer and outcome is None and dist is not None:
+ # The gather itself failed on the writer: do not leave the others waiting for a result.
+ _share_from_writer(
+ dist, True, writer_rank, "result", ("error", f"{type(e).__name__}: {e}")
+ )
+ raise
+ if error is not None:
+ raise error
+ if writer or dist is None:
+ return outcome[1] if outcome else None
+ outcome = _share_from_writer(dist, False, writer_rank, "result")
+ if outcome is None:
+ return None
+ if outcome[0] == "error":
+ raise RuntimeError(
+ f"Unsloth: `{method}` failed on rank {writer_rank}, the FSDP2 rank that exports: "
+ + outcome[1]
+ )
+ return outcome[1]
+
+
_DCP_DEPTH = [0]
_ADAPTER_ONLY = [0]
_DCP_FUNCTIONS = (
diff --git a/unsloth/save.py b/unsloth/save.py
index 8fb3dd427be..41b577501e9 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -4481,31 +4481,80 @@ def _assert_export_target_is_not_base_with_lora_layers(self):
)
-def _fsdp2_refuses_save(method):
- """Exports that rebuild or quantize the whole model in this process (GGUF, torchao) cannot run on a
- model FSDP2 shards: each rank would export its own shards, all into the same place. Raise on every
- rank (so none waits on another) and say how to get the same file. Passed through without FSDP2."""
+def _fsdp2_export_on_rank0(
+ method,
+ adapter_only = None,
+ gather_options = None,
+):
+ """Exports that rebuild or quantize the whole model in this process (GGUF, torchao, OpenVINO)
+ on a model FSDP2 shards: every rank makes the call, the shards are gathered to rank 0's CPU,
+ rank 0 alone runs the ordinary single-process export, the other ranks wait for it, and every
+ rank returns rank 0's result (fsdp2_export_on_writer). Refused on every rank when the gathered
+ weights do not fit rank 0's host RAM. `adapter_only(self, arguments)` says the export only
+ reads the LoRA weights (a GGUF LoRA), so only those are gathered. `gather_options(self,
+ arguments)`, when it returns a dict, sets the gather's placement instead. Passed through without
+ FSDP2, and inside a gather already in progress (push_to_hub_gguf -> save_pretrained_gguf)."""
def decorate(fn):
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
- from .models.fsdp2_save import fsdp2_units, fsdp2_gather_active
- if fsdp2_units(self) and not fsdp2_gather_active():
- raise RuntimeError(
- f"Unsloth: `{method}` does not support a model sharded by FSDP2. Save the merged "
- "model on every rank with `model.save_pretrained_merged(save_directory, tokenizer, "
- 'save_method = "merged_16bit")`, then in a single process load that folder with '
- f"`FastLanguageModel.from_pretrained` and call `{method}` there."
- )
- return fn(self, *args, **kwargs)
+ from .models.fsdp2_save import (
+ fsdp2_units,
+ fsdp2_gather_active,
+ fsdp2_export_on_writer,
+ merged_save_gather_options,
+ )
+
+ if fsdp2_gather_active() or not fsdp2_units(self):
+ return fn(self, *args, **kwargs)
+ arguments = _fsdp2_save_arguments(fn, self, args, kwargs)
+ only = bool(
+ adapter_only is not None
+ and isinstance(self, PeftModel)
+ and adapter_only(self, arguments)
+ )
+ custom = gather_options(self, arguments) if gather_options is not None else None
+ if only:
+ options = dict(include = _fsdp2_peft_saved_frozen(self, arguments))
+ elif custom is not None:
+ options = custom
+ elif isinstance(self, PeftModel):
+ # The 16-bit merge every one of these exports starts from (save_pretrained_merged's).
+ options = merged_save_gather_options(self, "merged_16bit")
+ else:
+ # A full model is written as it is, packed 4-bit bytes included (save_pretrained's).
+ options = dict(offload_to_cpu = True, offload_4bit = True)
+ return fsdp2_export_on_writer(
+ self,
+ lambda: fn(self, *args, **kwargs),
+ method,
+ trainable_only = only,
+ **options,
+ )
return wrapper
return decorate
+def _gguf_lora_only(model, arguments):
+ return str(arguments.get("save_method") or "").lower() == "lora"
+
+
+def _torchao_gather_options(model, arguments):
+ """A QAT model saved with its own config and no LoRA is quantized in place, on the device its
+ weights sit on; every other torchao export quantizes a reload of a 16-bit save."""
+ if isinstance(model, PeftModel) or arguments.get("torchao_config") is not None:
+ return None
+ if getattr(model, "_torchao_config", None) is None:
+ return None
+ from .models.fsdp2_save import gather_on_accelerator_if_it_fits
+
+ return gather_on_accelerator_if_it_fits(model)
+
+
@_model_parallel_refuses_save("save_pretrained_gguf")
-@_fsdp2_refuses_save("save_pretrained_gguf")
+@_fsdp2_export_on_rank0("save_pretrained_gguf", adapter_only = _gguf_lora_only)
@_normalize_tied_weights_keys_for_save
def unsloth_save_pretrained_gguf(
self,
@@ -5180,7 +5229,7 @@ def _free_merge_if_disk_is_tight(
@_model_parallel_refuses_save("push_to_hub_gguf")
-@_fsdp2_refuses_save("push_to_hub_gguf")
+@_fsdp2_export_on_rank0("push_to_hub_gguf", adapter_only = _gguf_lora_only)
def unsloth_push_to_hub_gguf(
self,
repo_id: str,
@@ -5822,6 +5871,7 @@ def _unsloth_save_lora_gguf(
@_model_parallel_refuses_save("push_to_hub_ggml")
+@_fsdp2_export_on_rank0("push_to_hub_ggml", adapter_only = lambda model, arguments: True)
def unsloth_convert_lora_to_ggml_and_push_to_hub(
self,
tokenizer,
@@ -5853,6 +5903,7 @@ def unsloth_convert_lora_to_ggml_and_push_to_hub(
@_model_parallel_refuses_save("save_pretrained_ggml")
+@_fsdp2_export_on_rank0("save_pretrained_ggml", adapter_only = lambda model, arguments: True)
def unsloth_convert_lora_to_ggml_and_save_locally(
self,
save_directory: str,
@@ -8090,7 +8141,7 @@ def _write_executorch_export_config(
@_model_parallel_refuses_save("save_pretrained_torchao")
-@_fsdp2_refuses_save("save_pretrained_torchao")
+@_fsdp2_export_on_rank0("save_pretrained_torchao", gather_options = _torchao_gather_options)
def unsloth_save_pretrained_torchao(
self,
save_directory: Union[str, os.PathLike],
@@ -8419,6 +8470,7 @@ def _unsloth_save_openvino(
@_model_parallel_refuses_save("save_pretrained_openvino")
+@_fsdp2_export_on_rank0("save_pretrained_openvino")
def unsloth_save_pretrained_openvino(
self,
save_directory: Union[str, os.PathLike],
@@ -8454,6 +8506,7 @@ def unsloth_save_pretrained_openvino(
@_model_parallel_refuses_save("push_to_hub_openvino")
+@_fsdp2_export_on_rank0("push_to_hub_openvino")
def unsloth_push_to_hub_openvino(
self,
repo_id: str,