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.

Tensor parallel: generate, adapter / tokenizer saves, merged and GGUF exports, and reload cells under UNSLOTH_TP_SIZE (#15368)

Daniel Han78b2f82b3ad8
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.json
index f70a419c3cb..30ca4d0c922 100644
--- a/scripts/risky_loaders_baseline.json
+++ b/scripts/risky_loaders_baseline.json
@@ -698,6 +698,14 @@
"count": 1,
"reason": "Reached only after the trust_remote_code gate in _resolve_module_class raises for an untrusted non sentence_transformers class."
},
+ {
+ "file": "unsloth/models/tp_replica.py",
+ "rule": "unsafe-deserialize",
+ "sink": "pickle.loads",
+ "digest": "bf2d3c412d57fd50",
+ "count": 1,
+ "reason": "Reads the result rank 0 published to this job's own torch.distributed c10d store (the same trust boundary as broadcast_object_list); no file or network payload from outside the process group."
+ },
{
"file": "unsloth/save.py",
"rule": "trust-remote-code",
diff --git a/tests/test_parallel_general_gloo.py b/tests/test_parallel_general_gloo.py
index fb7628d8293..633d1577926 100644
--- a/tests/test_parallel_general_gloo.py
+++ b/tests/test_parallel_general_gloo.py
@@ -712,19 +712,37 @@ def test_tp_clip_coefficient_is_not_narrowed_to_fp16():
assert p.grad.float() == pytest.approx(torch.full((4,), 1e-3), rel = 1e-2), p.grad
[email protected]("kind", ["tp", "pp"])
@pytest.mark.parametrize("name", EXPORTS)
-def test_exports_refuse_model_parallel_before_writing(kind, name):
+def test_exports_refuse_pipeline_parallel_before_writing(name):
results = _spawn_cached("export")
if "skip" in results[0]:
pytest.skip(f"import unsloth failed on this host: {results[0]['skip']}")
- want = "tensor parallel model" if kind == "tp" else "pipeline parallel model"
for res in results:
- r = res[f"{kind}:{name}"]
- assert r["error"] and "RuntimeError" in r["error"] and want in r["error"], r
+ r = res[f"pp:{name}"]
+ assert (
+ r["error"] and "RuntimeError" in r["error"] and "pipeline parallel model" in r["error"]
+ ), r
assert not r["wrote"], r
[email protected]("name", EXPORTS)
+def test_exports_of_a_tensor_parallel_model_run_on_rank0_only(name):
+ """tp_replica.py: rank 0 runs the one-process export on the gathered model, the other ranks wait and
+ share its outcome (here a merged save with no base checkpoint fails the same way one process does)."""
+ results = _spawn_cached("export")
+ if "skip" in results[0]:
+ pytest.skip(f"import unsloth failed on this host: {results[0]['skip']}")
+ rank0, rank1 = results[0][f"tp:{name}"], results[1][f"tp:{name}"]
+ assert not rank1["wrote"], rank1 # rank 1's own directory: only rank 0 writes
+ if rank0["error"] is None:
+ assert rank0["wrote"] and rank1["error"] is None, (rank0, rank1)
+ else:
+ assert (
+ "tensor parallel" not in rank0["error"]
+ ), rank0 # the export's own error, not a refusal
+ assert rank1["error"] and "failed on rank 0" in rank1["error"], rank1
+
+
def test_every_whole_model_export_is_guarded():
"""Static: every export patch_saving_functions binds, and every writer behind them, refuses TP / PP first."""
import ast
diff --git a/tests/test_return_logits_survives_for_training.py b/tests/test_return_logits_survives_for_training.py
index 9fe4a34dd51..7ab1098835f 100644
--- a/tests/test_return_logits_survives_for_training.py
+++ b/tests/test_return_logits_survives_for_training.py
@@ -151,8 +151,8 @@ def test_flag_set_after_for_inference_is_kept(fbm):
def test_lifted_for_inference_runs_its_real_helpers(fbm):
# The lifted for_inference calls the real _utils.py guards, not a None the namespace made up.
model = _Model()
- model._unsloth_tp = True
- with pytest.raises(RuntimeError, match = "tensor parallel"):
+ model._unsloth_pp = True
+ with pytest.raises(RuntimeError, match = "pipeline parallel"):
fbm.for_inference(model)
@@ -168,6 +168,7 @@ def _fast_llama_for_training():
resolve_training_gradient_checkpointing = lambda model, flag, checkpointing = None: False,
arm_gradient_checkpointing = lambda model, checkpointing = None: False,
set_module_gradient_checkpointing = lambda module, flag: None,
+ _tensor_parallel_for_training = lambda model: None, # tp_replica.py: no tp model here
)
module = ast.fix_missing_locations(ast.Module(body = [fn], type_ignores = []))
exec(compile(module, str(MODELS / "llama.py"), "exec"), namespace)
diff --git a/tests/test_tp_env_gloo.py b/tests/test_tp_env_gloo.py
index 05c0fc03909..8ecb8414731 100644
--- a/tests/test_tp_env_gloo.py
+++ b/tests/test_tp_env_gloo.py
@@ -323,7 +323,9 @@ def _case_env(
train_dataset = data,
)
)
- res["generate"] = _raised(lambda: model.generate(input_ids = ids[:1, :3]))
+ res["generate"] = _raised(
+ lambda: model.generate(input_ids = ids[:1, :3], max_new_tokens = 2, pad_token_id = 0)
+ )
if dist.is_initialized():
dist.barrier()
return res
@@ -516,9 +518,7 @@ def test_env_tp2_trainer_matches_one_process(four_bit):
assert "evaluation during training" in res["eval"] and hint in res["eval"], res["eval"]
assert "Trainer.evaluate is not supported" in res["evaluate"] and hint in res["evaluate"]
assert "lion_8bit" in res["lion"], res["lion"]
- assert "generation is not supported" in res["generate"], res[
- "generate"
- ] # A3: still refused
+ assert res["generate"] is None, res["generate"] # a whole replica per rank (tp_replica.py)
assert results[0]["seen"] == results[1]["seen"] # both tp ranks read the same batches
diff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.py
index 9500d4c2f03..9716f4c5afc 100644
--- a/tests/test_tp_native_gloo.py
+++ b/tests/test_tp_native_gloo.py
@@ -116,8 +116,11 @@ def _case_parity(
tpn.apply_tensor_parallel(model, mesh["tp"], plan = plan)
assert tpn.is_tensor_parallel(model)
assert tpn.apply_tensor_parallel(model, mesh["tp"]) is model # idempotent
- with pytest.raises(RuntimeError, match = "generation is not supported"):
- model.generate(input_ids = torch.zeros(1, 2, dtype = torch.long))
+ # The training forward below releases the generate replica, so parity also covers that release.
+ generated = model.generate(
+ input_ids = torch.zeros(1, 2, dtype = torch.long), max_new_tokens = 2, pad_token_id = 0
+ )
+ assert generated.shape == (1, 4), generated.shape
from test_fsdp2_native_units import _load_native
try:
@@ -189,7 +192,7 @@ def _case_guards(rank, world, tmp):
import transformers
from torch.distributed.device_mesh import init_device_mesh
from unsloth import FastLanguageModel, FastModel
- from unsloth.models import fsdp2_native, tp_native
+ from unsloth.models import fsdp2_native, tp_native, tp_replica
from unsloth.models._utils import patch_gradient_accumulation_fix
patch_gradient_accumulation_fix(transformers.Trainer)
@@ -217,9 +220,14 @@ def _case_guards(rank, world, tmp):
lambda: fsdp2_native._refuse_tensor_parallel_model(level)
)
res[f"for_inference:{name}"] = _raised(lambda: FastLanguageModel.for_inference(level))
+ res[f"replica_released:{name}"] = tp_replica.release_replica(level)
res[f"FastModel.for_inference:{name}"] = _raised(lambda: FastModel.for_inference(level))
+ tp_replica.release_replica(level)
if name != "decoder":
- res[f"generate:{name}"] = _raised(lambda: level.generate(input_ids = ids))
+ res[f"generate:{name}"] = _raised(
+ lambda: level.generate(input_ids = ids, max_new_tokens = 2, pad_token_id = 0)
+ )
+ tp_replica.release_replica(level)
res[f"trainer:{name}"] = _raised(
lambda: transformers.Trainer(model = level, args = args)
)
@@ -970,7 +978,7 @@ def test_tp2_tied_norm_weight_is_summed_once():
_check_parity(_spawn("parity", 2, arch = "qwen3", tie_norms = True), 2)
-def test_tp2_entry_points_outside_the_regions_are_refused():
+def test_tp2_entry_points_outside_the_regions_are_refused_or_gather():
results = _spawn("guards", 2)
if "skip" in results[0]:
pytest.skip(f"import unsloth failed on this host: {results[0]['skip']}")
@@ -986,14 +994,14 @@ def test_tp2_entry_points_outside_the_regions_are_refused():
key,
value,
)
- elif "for_inference" in key:
- assert value and "for_inference is not supported" in value, (
+ elif "for_inference" in key or key.startswith("generate:"):
+ assert value is None, (
applied,
key,
value,
- )
- elif key.startswith("generate:"):
- assert value and "generation is not supported" in value, (applied, key, value)
+ ) # gathered a replica (tp_replica.py)
+ elif key.startswith("replica_released:"):
+ assert value is True, (applied, key, value)
elif key.startswith("model_init:"):
assert value and "cannot be trained by the Trainer" in value, (
applied,
diff --git a/tests/test_tp_replica_cpu_stage_cuda.py b/tests/test_tp_replica_cpu_stage_cuda.py
new file mode 100644
index 00000000000..2dde81da894
--- /dev/null
+++ b/tests/test_tp_replica_cpu_stage_cuda.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A tensor parallel export replica that does not fit the writer's GPU is gathered to the CPU
+(models/tp_replica.py). A merged_16bit export of a 4-bit model then merges each projection with
+save.py _merge_lora, whose dequantizer is CUDA only: every CPU-staged 4-bit weight is dequantized and merged
+on the GPU it came from, one projection at a time, and the merged weight comes back on the CPU, equal to
+the merge of the same weight left on the GPU. Needs a real CUDA GPU (one process, a 1-rank NCCL group)."""
+
+import os
+import sys
+
+import pytest
+import torch
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "_shared"))
+from real_accelerator import has_real_cuda # noqa: E402
+
+pytestmark = pytest.mark.skipif(not has_real_cuda(), reason = "needs a real CUDA GPU")
+
+
+def _qlora(nested):
+ import bitsandbytes as bnb
+ from peft import LoraConfig, get_peft_model
+
+ class Tiny(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = torch.nn.Linear(256, 192, bias = False)
+
+ def forward(self, x):
+ return self.proj(x)
+
+ torch.manual_seed(0)
+ model = Tiny()
+ dense = model.proj.weight.data.clone()
+ q = bnb.nn.Linear4bit(
+ 256,
+ 192,
+ bias = False,
+ compute_dtype = torch.bfloat16,
+ compress_statistics = nested,
+ quant_type = "nf4",
+ )
+ q.weight = bnb.nn.Params4bit(
+ dense, requires_grad = False, compress_statistics = nested, quant_type = "nf4"
+ )
+ model.proj = q
+ model = model.cuda() # quantizes on the GPU
+ torch.manual_seed(1)
+ return get_peft_model(
+ model, LoraConfig(r = 8, lora_alpha = 16, target_modules = ["proj"], init_lora_weights = False)
+ )
+
+
[email protected]("nested", [True, False])
[email protected]("triton_nf4", [True, False], ids = ["triton", "ctypes"])
+def test_cpu_staged_4bit_replica_merges_on_its_gpu(nested, triton_nf4, monkeypatch):
+ import torch.distributed as dist
+
+ from unsloth import save
+ from unsloth.models import tp_native, tp_replica
+ from unsloth.kernels import utils as kernel_utils
+ from unsloth.save import _merge_lora
+
+ # HMM hosts can dequantize CPU tensors correctly, so assert the device directly.
+ real = save.fast_dequantize
+ devices = []
+
+ def cuda_only(
+ W,
+ quant_state = None,
+ *args,
+ **kwargs,
+ ):
+ devices.append((W.device.type, quant_state.absmax.device.type))
+ assert W.is_cuda and quant_state.absmax.is_cuda, devices[-1]
+ return real(W, quant_state, *args, **kwargs)
+
+ monkeypatch.setattr(save, "fast_dequantize", cuda_only)
+ if not triton_nf4:
+ # Only the bitsandbytes ctypes path fails deterministically without staging (Triton may read via HMM).
+ monkeypatch.setattr(kernel_utils, "_USE_NF4_KERNELS", False)
+
+ if not dist.is_initialized():
+ os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
+ os.environ.setdefault("MASTER_PORT", "29617")
+ dist.init_process_group("nccl", rank = 0, world_size = 1)
+ group = dist.new_group([0])
+ model = _qlora(nested)
+ proj = model.base_model.model.proj
+ base = proj.base_layer
+ want, _ = _merge_lora(proj, "proj") # the GPU replica's merge
+ want = want.cpu()
+ tp_native._shard_params4bit("proj", base, base.weight, tp_native.COLWISE, (192,), 0, 1)
+ staged = tp_replica._full_params4bit(base.weight, base, group, torch.device("cpu"), True)
+ base._parameters["weight"] = staged
+ for factor in (proj.lora_A, proj.lora_B):
+ factor["default"].weight.data = factor["default"].weight.data.cpu()
+ assert staged.device.type == "cpu" and staged.quant_state.absmax.device.type == "cpu"
+ got, _ = _merge_lora(proj, "proj")
+ assert got.device.type == "cpu", got.device
+ assert got.dtype == want.dtype and torch.equal(got, want)
+ # The staged weight itself stays on the CPU.
+ assert base.weight.device.type == "cpu"
diff --git a/tests/test_tp_replica_gloo.py b/tests/test_tp_replica_gloo.py
new file mode 100644
index 00000000000..c50554a38fc
--- /dev/null
+++ b/tests/test_tp_replica_gloo.py
@@ -0,0 +1,704 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Post-training cells on a tensor parallel model (models/tp_replica.py), on a gloo CPU world vs one process:
+for_inference / generate on a gathered replica, adapter / tokenizer saves written by rank 0 while the others wait,
+merged exports on rank 0, and the sharded model put back for more training."""
+
+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 sys # noqa: E402
+import tempfile # 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_tp_native_gloo import ( # noqa: E402
+ _free_port,
+ _import_checkout_unsloth,
+ _qlora_model,
+ _raised,
+ _save_checkpoint,
+ _train,
+)
+from test_tp_native_oracle import ARCHS, LLAMA, _batch, build, skip_unsupported # noqa: E402
+
+
+def _mesh(world, tp = None):
+ from torch.distributed.device_mesh import init_device_mesh
+ tp = tp or world
+ return init_device_mesh("cpu", (world // tp, tp), mesh_dim_names = ("dp", "tp"))["tp"]
+
+
+def _generate(model, prompt, **kwargs):
+ kwargs.setdefault("max_new_tokens", 16)
+ kwargs.setdefault("pad_token_id", 0)
+ return model.generate(input_ids = prompt, **kwargs).tolist()
+
+
+def _all_plain(model):
+ from torch.distributed.tensor import DTensor
+ return not any(isinstance(p, DTensor) for p in model.parameters())
+
+
+def _case_generate(
+ rank,
+ world,
+ tmp,
+ arch,
+ tp = None,
+):
+ """Train 2 steps under tp, then for_inference + greedy / sampled generate on the replica vs one process with
+ the same (gathered) weights; for_training (and a training forward) puts the shards back."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ from unsloth import FastLanguageModel
+ from unsloth.models import tp_native, tp_replica
+
+ repo, overrides = ARCHS[arch]
+ model, ref = build(repo, overrides), build(repo, overrides)
+ ids = _batch(model)
+ tp_native.apply_tensor_parallel(model, _mesh(world, tp))
+ _train(model, ids, 2, tp_native.tp_clip_grad_norm_)
+ sharded = dict(model.named_parameters())
+ with torch.no_grad():
+ loss_before = float(model(input_ids = ids, labels = ids, use_cache = False).loss)
+ ref.load_state_dict(tp_native.tp_full_state_dict(model))
+ out = {}
+ prompt = ids[:1, :5]
+ FastLanguageModel.for_inference(model)
+ FastLanguageModel.for_inference(ref)
+ out["gathered_plain"] = _all_plain(model)
+ with torch.no_grad():
+ out["logits_err"] = float(
+ (model(input_ids = ids).logits - ref(input_ids = ids).logits).abs().max()
+ )
+ out["greedy_tp"] = _generate(model, prompt, do_sample = False)
+ out["greedy_ref"] = _generate(ref, prompt, do_sample = False)
+ out["greedy_batch_tp"] = _generate(model, ids[:, :4], do_sample = False, max_new_tokens = 8)
+ out["greedy_batch_ref"] = _generate(ref, ids[:, :4], do_sample = False, max_new_tokens = 8)
+ torch.manual_seed(100 + rank) # different on every rank: generate copies tp rank 0's RNG state
+ out["sample_tp"] = _generate(model, prompt, do_sample = True, top_k = 0, temperature = 1.5)
+ tp_rank0 = rank - rank % (tp or world) # this tp group's first global rank
+ torch.manual_seed(100 + tp_rank0)
+ out["sample_ref"] = _generate(ref, prompt, do_sample = True, top_k = 0, temperature = 1.5)
+ FastLanguageModel.for_training(model)
+ out["restored"] = all(p is sharded[n] for n, p in model.named_parameters())
+ out["is_tp"] = tp_native.is_tensor_parallel(model)
+ with torch.no_grad():
+ out["loss_err"] = abs(
+ float(model(input_ids = ids, labels = ids, use_cache = False).loss) - loss_before
+ )
+ # A bare generate (no for_inference) releases the replica it gathered when it returns.
+ _generate(model, prompt, do_sample = False, max_new_tokens = 2)
+ out["bare_generate_released"] = not tp_replica.replica_active(model)
+ # for_inference keeps it; a forward that records gradients releases it before it runs.
+ FastLanguageModel.for_inference(model)
+ _generate(model, prompt, do_sample = False, max_new_tokens = 2)
+ out["replica_after_generate"] = tp_replica.replica_active(model)
+ model.train()
+ loss = model(input_ids = ids, labels = ids, use_cache = False).loss
+ loss.backward()
+ out["released_by_forward"] = not tp_replica.replica_active(model)
+ out["restored_2"] = all(p is sharded[n] for n, p in model.named_parameters())
+ out["loss_err_2"] = abs(float(loss) - loss_before)
+ out["dtensor_grads"] = all(
+ p.grad is not None for n, p in model.named_parameters() if p.requires_grad
+ )
+ return out
+
+
+def _case_qlora(rank, world, tmp, nested):
+ """4-bit: the gathered weight is the one-process codes bitwise, its dequantized weight equal, same greedy text."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ import bitsandbytes as bnb
+ from unsloth.models import tp_native, tp_replica
+
+ ref, model = _qlora_model(nested), _qlora_model(nested)
+ ref_w = {
+ n: (
+ m.weight.data.reshape(-1).view(torch.uint8).clone(),
+ bnb.functional.dequantize_4bit(m.weight.data, m.weight.quant_state),
+ )
+ for n, m in ref.named_modules()
+ if type(m).__name__ == "Linear4bit"
+ }
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ ids = _batch(ref)
+ prompt = ids[:1, :5]
+ with torch.no_grad():
+ sharded_logits = model(input_ids = ids).logits
+ tp_replica.gather_replica(model)
+ codes_equal, deq_equal, shapes = True, True, True
+ for n, m in model.named_modules():
+ if type(m).__name__ != "Linear4bit":
+ continue
+ codes, deq = ref_w[n]
+ got = m.weight.data.reshape(-1).view(torch.uint8)
+ codes_equal &= torch.equal(got, codes)
+ deq_equal &= torch.equal(
+ bnb.functional.dequantize_4bit(m.weight.data, m.weight.quant_state), deq
+ )
+ shapes &= tuple(m.weight.quant_state.shape) == tuple(deq.shape)
+ shapes &= (
+ m.weight.quant_state.nested == nested
+ ) # the 1-GPU QuantState, double quantized or not
+ with torch.no_grad():
+ logits = model(input_ids = ids).logits
+ ref_logits = ref(input_ids = ids).logits
+ out = {
+ "codes_equal": codes_equal,
+ "deq_equal": deq_equal,
+ "shapes": shapes,
+ "logits_err": float((logits - ref_logits).abs().max()),
+ "sharded_logits_err": float((sharded_logits - ref_logits).abs().max()),
+ "greedy_tp": _generate(model, prompt, do_sample = False),
+ "greedy_ref": _generate(ref, prompt, do_sample = False),
+ }
+ tp_replica.release_replica(model)
+ with torch.no_grad():
+ out["released_logits_err"] = float(
+ (model(input_ids = ids).logits - sharded_logits).abs().max()
+ )
+ return out
+
+
+def _files(directory):
+ out = {}
+ for name in sorted(os.listdir(directory)):
+ path = os.path.join(directory, name)
+ if os.path.isfile(path):
+ out[name] = open(path, "rb").read()
+ return out
+
+
+def _slow_rank0(
+ obj,
+ attr,
+ seconds = 1.5,
+):
+ """Rank 0's writer sleeps first: a rank that returned before rank 0 wrote would see no files."""
+ import torch.distributed as dist
+
+ original = getattr(obj, attr)
+ if dist.get_rank() != 0:
+ return
+
+ def slow(*args, **kwargs):
+ time.sleep(seconds)
+ return original(*args, **kwargs)
+
+ setattr(obj, attr, slow)
+
+
+def _case_save(rank, world, tmp):
+ """model.save_pretrained / tokenizer.save_pretrained on every rank: rank 0 writes the one-process files,
+ the others return after it did, with its return value. Errors on rank 0 reach every rank."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ import torch.distributed as dist
+ from transformers import AutoTokenizer
+ from unsloth.models import tp_native, tp_replica
+ from unsloth.save import patch_saving_functions
+
+ model, ref = build(LLAMA), build(LLAMA)
+ ids = _batch(model)
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ _train(model, ids, 2, tp_native.tp_clip_grad_norm_)
+ ref.load_state_dict(tp_native.tp_full_state_dict(model))
+ tokenizer = AutoTokenizer.from_pretrained(LLAMA)
+ patch_saving_functions(model)
+ patch_saving_functions(tokenizer)
+ tokenizer.__dict__["_unsloth_tp_world_save"] = True # what tp_env / apply_tensor_parallel mark
+ out = {}
+ tp_dir, ref_dir = os.path.join(tmp, "tp"), os.path.join(tmp, "ref")
+ _slow_rank0(model, "original_model_save_pretrained")
+ out["return"] = model.save_pretrained(tp_dir)
+ out["files_on_return"] = os.path.isfile(os.path.join(tp_dir, "adapter_model.safetensors"))
+ _slow_rank0(tokenizer, "original_save_pretrained")
+ out["tok_return"] = tokenizer.save_pretrained(tp_dir)
+ out["tok_files_on_return"] = os.path.isfile(os.path.join(tp_dir, "tokenizer_config.json"))
+ out["still_sharded"] = not _all_plain(model) and not tp_replica.replica_active(model)
+ if rank == 0:
+ ref_tok = AutoTokenizer.from_pretrained(LLAMA)
+ patch_saving_functions(ref)
+ patch_saving_functions(ref_tok)
+ ref.save_pretrained(ref_dir)
+ ref_tok.save_pretrained(ref_dir)
+ dist.barrier()
+ out["files_tp"], out["files_ref"] = _files(tp_dir), _files(ref_dir)
+ # Same return on every rank, rank 0's error on every rank.
+ out["collective_return"] = tp_replica.tp_collective(
+ model, "probe", lambda: {"written_by": dist.get_rank()}, "adapters"
+ )
+
+ def fail():
+ raise ValueError("disk full")
+
+ out["collective_error"] = _raised(
+ lambda: tp_replica.tp_collective(model, "probe", fail, "adapters")
+ )
+ # Reload: every rank loads what rank 0 wrote (the adapter matches the trained tp model).
+ from peft import PeftModel
+
+ base = build(LLAMA, lora = False)
+ reloaded = PeftModel.from_pretrained(base, tp_dir)
+ with torch.no_grad():
+ out["reload_err"] = float(
+ (reloaded(input_ids = ids).logits - ref(input_ids = ids).logits).abs().max()
+ )
+ return out
+
+
+def _case_merged(rank, world, tmp, ckpt):
+ """save_pretrained_merged (merged_16bit) on every rank: rank 0 writes what one process writes."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ import torch.distributed as dist
+ from peft import LoraConfig, get_peft_model
+ from safetensors.torch import load_file
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+ import unsloth_zoo.saving_utils as zoo_saving
+ from unsloth.models import tp_native
+ from unsloth.save import patch_saving_functions
+
+ zoo_saving._active_merge_device = (
+ lambda: "cpu"
+ ) # the device spoof says cuda; these ranks have none
+ zoo_saving.DEVICE_TYPE = "cpu"
+
+ def load():
+ torch.manual_seed(0)
+ base = AutoModelForCausalLM.from_pretrained(ckpt, torch_dtype = torch.float32)
+ torch.manual_seed(1)
+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False)
+ return get_peft_model(base, config)
+
+ model, ref = load(), load()
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ tokenizer = AutoTokenizer.from_pretrained(LLAMA)
+ patch_saving_functions(model)
+ tp_dir, ref_dir = os.path.join(tmp, "merged_tp"), os.path.join(tmp, "merged_ref")
+ out = {}
+ out["error"] = _raised(
+ lambda: model.save_pretrained_merged(tp_dir, tokenizer, save_method = "merged_16bit")
+ )
+ out["files_on_return"] = os.path.isdir(tp_dir) and any(
+ f.endswith(".safetensors") for f in os.listdir(tp_dir)
+ )
+ out["still_sharded"] = not _all_plain(model)
+ if rank == 0:
+ patch_saving_functions(ref)
+ out["ref_error"] = _raised(
+ lambda: ref.save_pretrained_merged(ref_dir, tokenizer, save_method = "merged_16bit")
+ )
+ dist.barrier()
+
+ def tensors(directory):
+ state = {}
+ for name in sorted(os.listdir(directory)):
+ if name.endswith(".safetensors"):
+ state.update(load_file(os.path.join(directory, name)))
+ return state
+
+ if out["error"] is None:
+ out["tp"], out["ref"] = tensors(tp_dir), tensors(ref_dir)
+ return out
+
+
+def _case_refuse(rank, world, tmp):
+ """A replica that does not fit one rank's memory is refused on every rank, with the numbers; PP still is."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ from unsloth import FastLanguageModel
+ from unsloth.models import pp_native, tp_native, tp_replica
+
+ model = build(LLAMA)
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ sharded = dict(model.named_parameters())
+ real = tp_replica._free_bytes
+ if rank == 1:
+ tp_replica._free_bytes = lambda device: (1 << 10, "free on its GPU")
+ out = {"for_inference": _raised(lambda: FastLanguageModel.for_inference(model))}
+ out["generate"] = _raised(
+ lambda: model.generate(input_ids = _batch(model)[:1, :4], max_new_tokens = 2)
+ )
+ tp_replica._free_bytes = real
+ out["untouched"] = all(p is sharded[n] for n, p in model.named_parameters())
+ out["replica"] = tp_replica.replica_active(model)
+ pp = build(LLAMA)
+ pp_native.apply_pipeline_parallel(pp, _mesh(world), n_microbatches = 2)
+ out["pp_for_inference"] = _raised(lambda: FastLanguageModel.for_inference(pp))
+ return out
+
+
+def _tree(model):
+ return [(n, type(m).__name__) for n, m in model.named_modules()]
+
+
+def _case_destructive(rank, world, tmp):
+ """merged_4bit(_forced) merges LoRA into the base in place (merge_and_unload) on the writer: refused under
+ tensor parallel on every rank; and whatever an export does to rank 0's module tree is undone."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ from unsloth import save
+ from unsloth.models import tp_native, tp_replica
+
+ model = build(LLAMA)
+ ids = _batch(model)
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ before = _tree(model)
+ with torch.no_grad():
+ logits = model(input_ids = ids).logits
+ out = {}
+ for method in ("merged_4bit_forced", "merged_4bit"):
+ out[method] = _raised(
+ lambda: save.unsloth_save_model(
+ model, None, os.path.join(tmp, f"m4_{rank}"), save_method = method
+ )
+ )
+ out["tree_after_refusal"] = _tree(model) == before
+ # A writer that changes the module tree anyway (merge_and_unload) leaves rank 0 as it found it.
+ out["probe"] = _raised(
+ lambda: tp_replica.tp_collective(model, "probe", lambda: model.merge_and_unload() and None)
+ )
+ out["tree_after_merge"] = _tree(model) == before
+ out["merged_flags"] = [
+ m.merged_adapters
+ for m in model.modules()
+ if hasattr(m, "merged_adapters") and m.merged_adapters
+ ]
+ with torch.no_grad():
+ out["logits_err"] = float((model(input_ids = ids).logits - logits).abs().max())
+ out["still_sharded"] = not _all_plain(model)
+ return out
+
+
+class _Processor:
+ """A processor-like object (ProcessorMixin is not a tokenizer: Unsloth does not wrap its save_pretrained)."""
+
+ def __init__(self):
+ self.writers = []
+
+ def save_pretrained(self, directory, **kwargs):
+ import torch.distributed as dist
+
+ if dist.get_rank() == 0:
+ time.sleep(1.5)
+ self.writers.append(dist.get_rank())
+ os.makedirs(directory, exist_ok = True)
+ with open(os.path.join(directory, f"processor_config_{dist.get_rank()}.json"), "w") as f:
+ f.write("{}")
+ open(os.path.join(directory, "processor_config.json"), "w").write("{}")
+ return [os.path.join(directory, "processor_config.json")]
+
+
+def _case_processor(rank, world, tmp):
+ """A processor marked for a tensor parallel run (tp_env loader, apply_tensor_parallel) is written once, by
+ rank 0, the others wait for it; same for one kept on the model as _saved_temp_tokenizer."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ from unsloth.models import tp_env, tp_native
+
+ out = {}
+ env_proc = _Processor()
+ tp_env._mark_world_save((None, env_proc))
+ model = build(LLAMA)
+ kept = _Processor()
+ model.base_model.model.__dict__["_saved_temp_tokenizer"] = kept
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ for label, proc in (("env", env_proc), ("kept", kept)):
+ directory = os.path.join(tmp, label)
+ out[f"{label}_return"] = proc.save_pretrained(directory)
+ out[f"{label}_writers"] = list(proc.writers)
+ out[f"{label}_written_on_return"] = os.path.isfile(
+ os.path.join(directory, "processor_config.json")
+ )
+ return out
+
+
+def _case_workspace(rank, world, tmp):
+ """An export gathers to rank 0 only, but every rank all-gathers each whole tensor: a non-writing rank without
+ room for that workspace makes every rank refuse together, before anything is gathered or written; with room
+ for the workspace (not for a whole replica) the export runs."""
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ from unsloth import save
+ from unsloth.models import tp_native, tp_replica
+
+ model = build(LLAMA)
+ tp_native.apply_tensor_parallel(model, _mesh(world))
+ sharded = dict(model.named_parameters())
+ items = tp_replica._items(model, "all")
+ workspace = 3 * max(tp_replica._bytes(p) for p, _ in items) # tp_replica._workspace
+ replica = sum(tp_replica._bytes(p) for p, _ in items)
+ real = tp_replica._free_bytes
+ out = {"workspace": workspace, "replica": replica}
+
+ def export(directory):
+ return _raised(lambda: save.unsloth_save_model(model, None, directory, save_method = "lora"))
+
+ if rank == 1: # the non-writer: room for less than one tensor's gather
+ tp_replica._free_bytes = lambda device: (
+ tp_replica._margin(workspace) + workspace // 2,
+ "free on its GPU",
+ )
+ out["short"] = export(os.path.join(tmp, "short"))
+ out["short_wrote"] = os.path.isdir(os.path.join(tmp, "short"))
+ out["untouched"] = all(p is sharded[n] for n, p in model.named_parameters())
+ if (
+ rank == 1
+ ): # room for the workspace, not for a whole replica (the writer keeps it, not this rank)
+ tp_replica._free_bytes = lambda device: (
+ tp_replica._margin(workspace) + workspace,
+ "free on its GPU",
+ )
+ out["enough"] = export(os.path.join(tmp, "enough"))
+ tp_replica._free_bytes = real
+ out["enough_wrote"] = os.path.isfile(os.path.join(tmp, "enough", "adapter_config.json"))
+ return out
+
+
+CASES = {
+ "workspace": _case_workspace,
+ "destructive": _case_destructive,
+ "processor": _case_processor,
+ "generate": _case_generate,
+ "qlora": _case_qlora,
+ "save": _case_save,
+ "merged": _case_merged,
+ "refuse": _case_refuse,
+}
+
+
+def _worker(rank, world, port, case, tmp, kwargs):
+ 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),
+ )
+ import datetime
+
+ import torch.distributed as dist
+
+ torch.set_num_threads(2)
+ dist.init_process_group(
+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)
+ )
+ try:
+ res = CASES[case](rank, world, tmp, **kwargs)
+ torch.save(res, os.path.join(tmp, f"result_{rank}.pt"))
+ finally:
+ dist.destroy_process_group()
+
+
+def _spawn(
+ case,
+ world = 2,
+ **kwargs,
+):
+ ctx = multiprocessing.get_context("spawn")
+ port = _free_port()
+ with tempfile.TemporaryDirectory() as tmp:
+ if case == "merged":
+ kwargs["ckpt"] = _save_checkpoint("llama", os.path.join(tmp, "ckpt"))
+ procs = [
+ ctx.Process(target = _worker, args = (r, world, port, case, tmp, kwargs))
+ for r in range(world)
+ ]
+ for p in procs:
+ p.start()
+ for p in procs:
+ p.join(600)
+ codes = [p.exitcode for p in procs]
+ assert codes == [0] * world, f"rank exit codes {codes}"
+ results = [
+ torch.load(os.path.join(tmp, f"result_{r}.pt"), weights_only = False)
+ for r in range(world)
+ ]
+ if "skip" in results[0]:
+ pytest.skip(f"import unsloth failed on this host: {results[0]['skip']}")
+ return results
+
+
[email protected]("arch", ["llama", "llama_bias", "qwen3", "phi3", "gemma2"])
+def test_tp2_generate_on_replica_equals_one_process(arch):
+ skip_unsupported(arch)
+ for rank, res in enumerate(_spawn("generate", 2, arch = arch)):
+ assert res["gathered_plain"], rank
+ assert res["logits_err"] == 0.0, (rank, res["logits_err"])
+ assert res["greedy_tp"] == res["greedy_ref"], (rank, res["greedy_tp"], res["greedy_ref"])
+ assert res["greedy_batch_tp"] == res["greedy_batch_ref"], rank
+ # tp rank 0's RNG state on every tp rank: the sampled text is rank 0's, which is one process's.
+ assert res["sample_tp"] == res["sample_ref"], (rank, res["sample_tp"], res["sample_ref"])
+ assert res["restored"] and res["is_tp"] and res["loss_err"] == 0.0, res
+ assert res["bare_generate_released"], res
+ assert (
+ res["replica_after_generate"] and res["released_by_forward"] and res["restored_2"]
+ ), res
+ assert res["loss_err_2"] == 0.0 and res["dtensor_grads"], res
+
+
+def test_tp2_x_dp2_generate_per_tp_group():
+ """dp 2 x tp 2 (DDP-style dp): each tp group gathers its replica and copies its own tp rank 0's RNG."""
+ results = _spawn("generate", 4, arch = "llama", tp = 2)
+ for rank, res in enumerate(results):
+ assert res["logits_err"] == 0.0 and res["greedy_tp"] == res["greedy_ref"], rank
+ assert res["sample_tp"] == res["sample_ref"], rank
+ assert res["restored"] and res["restored_2"] and res["loss_err_2"] == 0.0, res
+ assert results[0]["sample_tp"] == results[1]["sample_tp"] != results[2]["sample_tp"]
+ assert results[2]["sample_tp"] == results[3]["sample_tp"]
+
+
+def test_env_reload_of_an_adapter_directory_loads_in_full(tmp_path):
+ """tp_env: a reload cell (adapter directory) is not sharded-loaded; a base checkpoint still is."""
+ import importlib.util
+
+ # By path, next to the tp_native the oracle loaded: no `import unsloth` in the pytest process.
+ path = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ "unsloth",
+ "models",
+ "tp_env.py",
+ )
+ spec = importlib.util.spec_from_file_location("unsloth.models.tp_env", path)
+ tp_env = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(tp_env)
+
+ adapter, base = tmp_path / "lora_model", tmp_path / "base"
+ adapter.mkdir()
+ base.mkdir()
+ (adapter / "adapter_config.json").write_text("{}")
+ (base / "config.json").write_text("{}")
+ assert tp_env._is_adapter({"model_name": str(adapter)})
+ assert not tp_env._is_adapter({"model_name": str(base)})
+ assert not tp_env._is_adapter({"model_name": None})
+ out = tp_env._mark_world_save((object(), type("Tok", (), {})()))
+ assert out[1].__dict__.get("_unsloth_tp_world_save") is True
+
+
[email protected]("nested", [False, True])
+def test_tp2_qlora_replica_is_the_one_process_weight(nested):
+ try:
+ import bitsandbytes # noqa: F401
+ except ImportError:
+ pytest.skip("bitsandbytes not installed")
+ for rank, res in enumerate(_spawn("qlora", 2, nested = nested)):
+ assert res["codes_equal"] and res["deq_equal"] and res["shapes"], (rank, res)
+ assert res["logits_err"] <= 1e-5, (rank, res["logits_err"], res["sharded_logits_err"])
+ assert res["greedy_tp"] == res["greedy_ref"], (rank, res)
+ assert res["released_logits_err"] == 0.0, res
+
+
+def test_tp2_adapter_and_tokenizer_saves_equal_one_process():
+ results = _spawn("save", 2)
+ for rank, res in enumerate(results):
+ assert res["return"] is None, res["return"]
+ assert res["files_on_return"] and res["tok_files_on_return"], (rank, res)
+ assert res["still_sharded"], rank
+ assert res["files_tp"].keys() == res["files_ref"].keys(), (
+ sorted(res["files_tp"]),
+ sorted(res["files_ref"]),
+ )
+ for name in res["files_ref"]:
+ assert res["files_tp"][name] == res["files_ref"][name], name
+ assert res["collective_return"] == {"written_by": 0}, (rank, res["collective_return"])
+ assert res["collective_error"] and "disk full" in res["collective_error"], res
+ assert res["reload_err"] == 0.0, res["reload_err"]
+ assert results[0]["tok_return"] == results[1]["tok_return"]
+ assert "adapter_model.safetensors" in results[0]["files_ref"]
+
+
+def test_tp2_merged_save_equals_one_process():
+ results = _spawn("merged", 2)
+ ref = results[0]
+ assert ref["ref_error"] is None, ref["ref_error"]
+ for rank, res in enumerate(results):
+ assert res["error"] is None, (rank, res["error"])
+ assert res["files_on_return"] and res["still_sharded"], (rank, res)
+ assert ref["tp"].keys() == ref["ref"].keys(), sorted(set(ref["tp"]) ^ set(ref["ref"]))
+ for key, value in ref["ref"].items():
+ assert ref["tp"][key].dtype == value.dtype, key
+ assert torch.equal(ref["tp"][key], value), key
+
+
+def test_tp2_replica_that_does_not_fit_is_refused_on_every_rank():
+ for rank, res in enumerate(_spawn("refuse", 2)):
+ for key in ("for_inference", "generate"):
+ assert res[key] and "gathers a whole single-GPU replica" in res[key], (
+ rank,
+ key,
+ res[key],
+ )
+ assert (
+ "rank 1 needs" in res[key]
+ and "MiB on its device" in res[key]
+ and "has 0.0 MiB" in res[key]
+ ), res[key]
+ assert res["untouched"] and not res["replica"], res
+ assert res["pp_for_inference"] and "pipeline parallel" in res["pp_for_inference"], res
+
+
+def test_tp2_destructive_merges_are_refused_and_rank0_tree_is_kept():
+ for rank, res in enumerate(_spawn("destructive", 2)):
+ for method in ("merged_4bit_forced", "merged_4bit"):
+ assert (
+ res[method]
+ and "merges the LoRA weights into the 4-bit base in place" in res[method]
+ ), (
+ rank,
+ method,
+ res[method],
+ )
+ assert res["tree_after_refusal"], rank
+ assert res["probe"] is None, res["probe"]
+ assert res["tree_after_merge"] and not res["merged_flags"], (rank, res["merged_flags"])
+ assert res["logits_err"] == 0.0 and res["still_sharded"], res
+
+
+def test_tp2_processor_saves_atomically_on_every_rank():
+ for rank, res in enumerate(_spawn("processor", 2)):
+ for label in ("env", "kept"):
+ # Every rank writes its own private copy (moved in with os.replace), no rank waits for another.
+ assert res[f"{label}_writers"] == [rank], (rank, label, res)
+ assert res[f"{label}_written_on_return"], (rank, label)
+ assert res[f"{label}_return"] and res[f"{label}_return"][0].endswith(
+ "processor_config.json"
+ ), res
+
+
+def test_tp2_non_writer_without_gather_workspace_refuses_with_every_rank():
+ results = _spawn("workspace", 2)
+ for rank, res in enumerate(results):
+ assert (
+ res["replica"] > res["workspace"] // 3
+ ), res # the room given below is less than a replica
+ assert (
+ res["short"] and "rank 1 needs" in res["short"] and "gather workspace" in res["short"]
+ ), (
+ rank,
+ res["short"],
+ )
+ assert not res["short_wrote"] and res["untouched"], (rank, res)
+ assert res["enough"] is None, (rank, res["enough"])
+ assert results[0]["enough_wrote"]
diff --git a/tests/test_tp_world_save_dirs_gloo.py b/tests/test_tp_world_save_dirs_gloo.py
new file mode 100644
index 00000000000..44e821ad427
--- /dev/null
+++ b/tests/test_tp_world_save_dirs_gloo.py
@@ -0,0 +1,174 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A tokenizer kept on a tensor parallel model saves once per world (rank 0 writes, the others wait), but only
+when every rank saves to the same place: a rank saving to its own directory, or after a save rank 0 made alone
+(`if rank == 0: tokenizer.save_pretrained(...)`), still ends with complete files of its own."""
+
+import multiprocessing
+import os
+
+if multiprocessing.parent_process() is not None or getattr(
+ multiprocessing.current_process(), "_inheriting", False
+):
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
+
+import sys # noqa: E402
+import tempfile # 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_tp_native_gloo import _free_port, _import_checkout_unsloth, _raised # noqa: E402
+from test_tp_native_oracle import LLAMA, build # noqa: E402
+
+
+def _case(rank, world, tmp):
+ error = _import_checkout_unsloth()
+ if error is not None:
+ return {"skip": error}
+ import torch.distributed as dist
+ from torch.distributed.device_mesh import init_device_mesh
+ from transformers import AutoTokenizer
+ from unsloth.models import tp_native
+ from unsloth.save import patch_saving_functions
+
+ tok = AutoTokenizer.from_pretrained(LLAMA)
+ patch_saving_functions(tok)
+ model = build(LLAMA)
+ model.base_model.model.__dict__["_saved_temp_tokenizer"] = tok
+ tp_native.apply_tensor_parallel(
+ model, init_device_mesh("cpu", (world,), mesh_dim_names = ("tp",))["tp"]
+ )
+ writers = []
+ original = tok.original_save_pretrained
+
+ def recording(*args, **kwargs):
+ if dist.get_rank() == 0:
+ time.sleep(2) # a rank that returns before rank 0 wrote sees no files
+ writers.append(dist.get_rank())
+ return original(*args, **kwargs)
+
+ tok.original_save_pretrained = recording
+ out = {"marked": bool(tok.__dict__.get("_unsloth_tp_world_save"))}
+
+ def config(directory):
+ import json
+ with open(os.path.join(directory, "tokenizer_config.json")) as f:
+ return json.load(f).get("model_max_length")
+
+ def leftovers():
+ return sorted(n for n in os.listdir(tmp) if ".unsloth_tp_rank" in n)
+
+ # 1. one shared directory, every rank at once: complete files on every rank when it returns
+ shared = os.path.join(tmp, "shared")
+ out["shared_err"] = _raised(lambda: tok.save_pretrained(shared))
+ out["shared_on_return"] = os.path.isfile(os.path.join(shared, "tokenizer_config.json"))
+ out["shared_writers"] = list(writers)
+ dist.barrier()
+ # 2. every rank its own directory: every directory written
+ own = os.path.join(tmp, f"own_{rank}")
+ out["own_err"] = _raised(lambda: tok.save_pretrained(own))
+ out["own_on_return"] = os.path.isfile(os.path.join(own, "tokenizer_config.json"))
+ dist.barrier()
+ # 3. rank 0 saves alone, then every rank saves new state to the SAME directory
+ same = os.path.join(tmp, "same")
+ tok.model_max_length = 111
+ if rank == 0:
+ out["alone_err"] = _raised(lambda: tok.save_pretrained(same))
+ dist.barrier()
+ tok.model_max_length = 222
+ out["after_return"] = tok.save_pretrained(same)
+ out["after_on_return"] = config(same)
+ dist.barrier()
+ out["after_final"] = config(same)
+ out["leftovers"] = leftovers()
+ return out
+
+
+def _worker(rank, world, port, 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),
+ )
+ import datetime
+
+ import torch.distributed as dist
+
+ torch.set_num_threads(2)
+ dist.init_process_group(
+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)
+ )
+ try:
+ torch.save(_case(rank, world, tmp), os.path.join(tmp, f"result_{rank}.pt"))
+ finally:
+ dist.destroy_process_group()
+
+
+def _spawn(world = 2):
+ ctx = multiprocessing.get_context("spawn")
+ port = _free_port()
+ with tempfile.TemporaryDirectory() as tmp:
+ procs = [ctx.Process(target = _worker, args = (r, world, port, tmp)) for r in range(world)]
+ for p in procs:
+ p.start()
+ for p in procs:
+ p.join(600)
+ assert [p.exitcode for p in procs] == [0] * world
+ results = [
+ torch.load(os.path.join(tmp, f"result_{r}.pt"), weights_only = False)
+ for r in range(world)
+ ]
+ if "skip" in results[0]:
+ pytest.skip(f"import unsloth failed on this host: {results[0]['skip']}")
+ return results
+
+
+def test_tp2_kept_tokenizer_saves_complete_files_on_every_rank():
+ for rank, res in enumerate(_spawn(2)):
+ assert res["marked"], rank
+ for key in ("shared_err", "own_err", "after_err"):
+ assert res.get(key) is None, (rank, key, res.get(key))
+ assert res["after_on_return"] == 222 and res["after_final"] == 222, (rank, res)
+ assert res["shared_on_return"], (rank, res)
+ assert res["own_on_return"], (rank, res) # its own directory, written
+ assert res["shared_writers"] == [
+ rank
+ ], res # its own private copy, moved in with os.replace
+ paths = [p for p in res["after_return"] if str(p).endswith("tokenizer_config.json")]
+ assert paths and os.path.basename(os.path.dirname(paths[0])) == "same", res["after_return"]
+ assert res["leftovers"] == [], res["leftovers"] # private directories removed
+
+
+class _PicklableProcessor:
+ """A processor stand-in with its own save_pretrained (mark_world_save wraps it)."""
+
+ def __init__(self):
+ self.saved = []
+
+ def save_pretrained(self, save_directory, **kwargs):
+ self.saved.append(save_directory)
+ return (save_directory,)
+
+
+def test_marked_processor_stays_picklable(tmp_path):
+ """Spawn-based DataLoader workers pickle the processor (and any collator holding it)."""
+ import pickle
+
+ from unsloth.models.tp_replica import mark_world_save
+
+ processor = mark_world_save(_PicklableProcessor())
+ assert processor.__dict__["save_pretrained"].__name__ == "unsloth_tp_world_save_pretrained"
+ clone = pickle.loads(pickle.dumps(processor))
+ # Unpickled in a worker, it is the plain class method again.
+ assert clone.save_pretrained.__name__ == "save_pretrained"
+ assert clone.save_pretrained(str(tmp_path)) == (str(tmp_path),)
+ # Outside torch.distributed the wrapped save still writes through the object's own save.
+ assert processor.save_pretrained(str(tmp_path / "out"))
+ assert processor.saved
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 413be5b0d9c..18939cd37ab 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -6220,13 +6220,22 @@ def _refuse_model_parallel_export(model, method):
)
-def _refuse_tensor_parallel_for_inference(model):
+def _tensor_parallel_for_inference(model):
+ """for_inference on a tensor parallel model gathers a whole replica on every rank (tp_replica.py)."""
if _is_unsloth_tensor_parallel(model):
- raise RuntimeError(
- "Unsloth: for_inference is not supported on a tensor parallel model in v1 (the fast decode "
- "paths run outside the tensor parallel regions); use model.eval() for forward evaluation, or "
- "save the adapter (save_tp_adapter) and generate on one GPU."
- )
+ from .tp_replica import tp_for_inference
+ return tp_for_inference(model)
+ _refuse_tensor_parallel_for_inference(model)
+
+
+def _tensor_parallel_for_training(model):
+ """for_training puts the sharded parameters back after a for_inference replica."""
+ if _is_unsloth_tensor_parallel(model):
+ from .tp_replica import tp_for_training
+ tp_for_training(model)
+
+
+def _refuse_tensor_parallel_for_inference(model):
if _is_unsloth_pipeline_parallel(model):
raise RuntimeError(
"Unsloth: for_inference is not supported on a pipeline parallel model in v1 (each rank holds "
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 243d763f93f..030343fb856 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -22,7 +22,7 @@ from typing import Optional, Tuple, List, Union
from ._utils import *
from ._utils import apply_unsloth_gradient_checkpointing
from ._utils import _ignore_block_swap_params_for_ddp
-from ._utils import _refuse_tensor_parallel_for_inference
+from ._utils import _tensor_parallel_for_inference, _tensor_parallel_for_training
from ._utils import __version__, importlib_version
from ._utils import move_to_device
from ._utils import per_layer_device
@@ -5480,7 +5480,7 @@ class FastLlamaModel:
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_inference!"
)
- _refuse_tensor_parallel_for_inference(model)
+ _tensor_parallel_for_inference(model)
def _for_inference(m):
if hasattr(m, "gradient_checkpointing"):
@@ -5523,6 +5523,7 @@ class FastLlamaModel:
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_training!"
)
+ _tensor_parallel_for_training(model)
# Mode last, as model.train() was: a custom train() keeps the final say over the chain below.
checkpointing, apply_training_mode = switch_training_mode(model, True, defer = True)
use_gradient_checkpointing = resolve_training_gradient_checkpointing(
diff --git a/unsloth/models/tp_env.py b/unsloth/models/tp_env.py
index 1a33b932442..2d0c7d02d46 100644
--- a/unsloth/models/tp_env.py
+++ b/unsloth/models/tp_env.py
@@ -258,7 +258,7 @@ def tensor_parallel_env_load(fn):
mesh = layout.tp_mesh
_DEPTH["load"] += 1
try:
- if _four_bit(values, fn) or not layout.sharded_loading:
+ if _four_bit(values, fn) or not layout.sharded_loading or _is_adapter(values):
return fn(
*args, **kwargs
) # full load; get_peft_model shards it (Params4bit included)
@@ -283,7 +283,43 @@ def tensor_parallel_env_load(fn):
_DEPTH["load"] -= 1
from_pretrained._unsloth_tp_env = True
- return from_pretrained
+ return _marks_world_save(from_pretrained)
+
+
+def _marks_world_save(from_pretrained):
+ @functools.wraps(from_pretrained)
+ def wrapper(*args, **kwargs):
+ out = from_pretrained(*args, **kwargs)
+ return out if env_layout() is None else _mark_world_save(out)
+
+ return wrapper
+
+
+def _mark_world_save(out):
+ """The tokenizer / processor of a tensor parallel run saves once per world (rank 0 writes, save.py)."""
+ if isinstance(out, (tuple, list)) and len(out) > 1 and hasattr(out[1], "__dict__"):
+ from .tp_replica import mark_world_save
+ try:
+ mark_world_save(out[1])
+ except Exception:
+ pass
+ return out
+
+
+def _is_adapter(values):
+ """A LoRA adapter directory / repo (a reload cell): loaded in full on every rank, nothing to shard."""
+ name = values.get("model_name", values.get("pretrained_model_name_or_path"))
+ if not isinstance(name, str):
+ return False
+ if os.path.isdir(name):
+ return os.path.isfile(os.path.join(name, "adapter_config.json"))
+ if os.path.exists(name) or name.count("/") != 1:
+ return False
+ try:
+ from huggingface_hub import file_exists
+ return bool(file_exists(name, "adapter_config.json", token = values.get("token")))
+ except Exception:
+ return False
def _model_of(out):
diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.py
index 24976505b57..c16088ce52d 100644
--- a/unsloth/models/tp_native.py
+++ b/unsloth/models/tp_native.py
@@ -943,6 +943,15 @@ def _check_params4bit(path, weight, style, tp):
)
+def quant_state_copy(state, device):
+ """A bitsandbytes QuantState on `device`; `state` itself (QuantState.to moves in place) is left as is."""
+ out = copy.copy(state)
+ if getattr(state, "state2", None) is not None:
+ out.state2 = copy.copy(state.state2)
+ out.to(device)
+ return out
+
+
def _shard_params4bit(path, base, weight, style, parts, rank, tp):
"""This rank's 4-bit shard (bitwise slice of the 1-GPU weight); double-quant absmax kept as float32."""
import bitsandbytes as bnb
@@ -986,6 +995,8 @@ def _shard_params4bit(path, base, weight, style, parts, rank, tp):
bnb_quantized = True,
)
new._unsloth_tp_layout = (style, tuple(parts), rank, tp)
+ # The 1-GPU QuantState (absmax still double quantized), on the CPU: tp_replica rebuilds the 1-GPU weight.
+ new._unsloth_tp_quant_state = quant_state_copy(state, "cpu")
base._parameters["weight"] = new
if "quant_state" in base.__dict__:
base.quant_state = local_state
@@ -1044,6 +1055,8 @@ def _input_name(module):
def _region_pre_hook(module, args, kwargs):
+ if module.__dict__.get("_unsloth_tp_gathered"):
+ return None # tp_replica: whole weights in place, the region runs as on one GPU
group = module._unsloth_tp_group
for name in (module.__dict__.get("_unsloth_tp_input", "hidden_states"), "hidden_states"):
if isinstance(kwargs.get(name), torch.Tensor):
@@ -1068,6 +1081,8 @@ def _region_finish(module, y):
def _region_post_hook(module, args, output):
+ if module.__dict__.get("_unsloth_tp_gathered"):
+ return None
if isinstance(output, torch.Tensor):
return _region_finish(module, output)
if isinstance(output, (tuple, list)) and output and isinstance(output[0], torch.Tensor):
@@ -1121,6 +1136,9 @@ def _decoder_of(inner):
return decoder if isinstance(decoder, nn.Module) else None
+_MISSING = object()
+
+
def _tp_chain(model):
"""`model` and every wrapper level below it (PeftModel -> LoraModel -> CausalLM -> decoder)."""
chain, m = [], model
@@ -1160,11 +1178,15 @@ def _default_mesh(model):
return init_device_mesh(device.type, (dist.get_world_size(),), mesh_dim_names = ("tp",))
-def _refuse_generate(*args, **kwargs):
- raise RuntimeError(
- "Unsloth: generation is not supported on a tensor parallel model in v1; save the adapter "
- "(save_tp_adapter) and generate on one GPU."
- )
+def _replica_generate(level, prior):
+ """generate on a tensor parallel level: every rank gathers a whole replica first (tp_replica)."""
+
+ def generate(*args, **kwargs):
+ from .tp_replica import tp_generate
+ return tp_generate(level, prior, args, kwargs)
+
+ generate._unsloth_tp_generate = True
+ return generate
def _cache_in_use(past):
@@ -1206,6 +1228,15 @@ def _refuse_cached_forward(module):
module.__dict__["forward"] = forward_without_cache
+def _mark_tokenizers(chain):
+ """The tokenizer Unsloth keeps on the model saves once per tensor parallel world (save.py)."""
+ for level in chain:
+ tokenizer = level.__dict__.get("_saved_temp_tokenizer")
+ if tokenizer is not None and hasattr(tokenizer, "__dict__"):
+ from .tp_replica import mark_world_save
+ mark_world_save(tokenizer)
+
+
def _sync_trainable(model, group, src):
import torch.distributed as dist
with torch.no_grad():
@@ -1217,6 +1248,17 @@ def _sync_trainable(model, group, src):
def _set_local_heads(module, region, tp):
heads, kv_heads = region.heads // tp, region.kv_heads // tp
+ # What tp_replica puts back while a whole replica is gathered.
+ module.__dict__["_unsloth_tp_saved_attrs"] = {
+ name: module.__dict__.get(name, _MISSING)
+ for name in (
+ "num_heads",
+ "num_key_value_heads",
+ "num_attention_heads",
+ "num_kv_heads",
+ "config",
+ )
+ }
module._unsloth_tp_heads = heads
module._unsloth_tp_kv_heads = kv_heads
for name, value, always in (
@@ -1339,10 +1381,12 @@ def apply_tensor_parallel(
level.__dict__[_TP_FLAG] = info
level.__dict__["_unsloth_tp_mesh"] = tp_mesh
level.__dict__["_unsloth_tp_plan"] = tp_plan
+ level.__dict__["_unsloth_tp_root"] = model
if callable(getattr(level, "generate", None)):
- level.__dict__["generate"] = _refuse_generate
+ level.__dict__["generate"] = _replica_generate(level, level.__dict__.get("generate"))
if level is inner or level is decoder:
_refuse_cached_forward(level)
+ _mark_tokenizers(chain)
if rank == 0:
print(
f"Unsloth: tensor parallel over {tp} ranks: {len(tp_plan.regions)} attention / MLP regions "
@@ -1401,6 +1445,7 @@ def _shard_projection(region, proj, mesh, rank, tp):
else:
_set_dtensor(A, "weight", A.weight, mesh, "shard", in_parts, 1, rank, tp)
_set_dtensor(B, "weight", B.weight, mesh, "replicate")
+ module.__dict__["_unsloth_tp_prior_forward"] = module.__dict__.get("forward", _MISSING)
module._unsloth_tp_style = proj.style
module._unsloth_tp_local = (
_tp_lora_parameters # read by kernels/utils.py get_lora_parameters(_bias)
diff --git a/unsloth/models/tp_replica.py b/unsloth/models/tp_replica.py
new file mode 100644
index 00000000000..74776442ebd
--- /dev/null
+++ b/unsloth/models/tp_replica.py
@@ -0,0 +1,737 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Post-training cells on a tensor parallel model; every rank must make these calls.
+
+- for_inference / generate: every rank gathers a whole one-GPU replica in place; the sharded parameters come
+ back on for_training or the next training forward. tp rank 0's RNG is copied so all ranks sample alike.
+- saves / exports: weights are gathered to global rank 0, which runs the single-process save; the other ranks
+ wait on the rendezvous store (no collective timeout, no NCCL watchdog) and return rank 0's result.
+"""
+
+from __future__ import annotations
+
+import datetime
+import gc
+import os
+import pickle
+import types
+
+import torch
+import torch.nn as nn
+
+from . import tp_native as tpn
+
+__all__ = [
+ "tp_root",
+ "gather_replica",
+ "release_replica",
+ "replica_active",
+ "tp_for_inference",
+ "tp_for_training",
+ "tp_generate",
+ "tp_collective",
+ "tp_world_save",
+ "mark_world_save",
+ "tp_world_push",
+]
+
+_REPLICA = "_unsloth_tp_replica"
+_ACTIVE = [] # rank 0 inside a collective save: nested saves write directly
+_GENERATE_DEPTH = [0]
+_COUNTERS = {}
+_MiB = 1 << 20
+
+
+def _dist():
+ import torch.distributed as dist
+ return dist if dist.is_available() and dist.is_initialized() else None
+
+
+def _rank():
+ dist = _dist()
+ return dist.get_rank() if dist is not None else 0
+
+
+def tp_root(model):
+ """The module apply_tensor_parallel was called on (any wrapper level of it resolves there)."""
+ for level in tpn._tp_chain(model):
+ root = level.__dict__.get("_unsloth_tp_root")
+ if root is not None:
+ return root
+ return model
+
+
+def replica_active(model):
+ return tp_root(model).__dict__.get(_REPLICA) is not None
+
+
+def _device(root):
+ for param in root.parameters():
+ if tpn._is_dtensor(param):
+ return param.to_local().device
+ return param.device
+ return torch.device("cpu")
+
+
+def _gib(n):
+ return f"{n / (1 << 30):.2f} GiB" if n >= (1 << 30) // 10 else f"{n / _MiB:.1f} MiB"
+
+
+def _marked(model, flag):
+ return any(level.__dict__.get(flag) is not None for level in tpn._tp_chain(model))
+
+
+def _fsdp2_units(model):
+ try:
+ from torch.distributed.fsdp import FSDPModule
+ except ImportError:
+ try:
+ from torch.distributed._composable.fsdp import FSDPModule
+ except ImportError:
+ return []
+ return [m for m in model.modules() if isinstance(m, FSDPModule)]
+
+
+def _refusal(root, what):
+ """None when `what` can run on this model, else why not."""
+ if _marked(root, "_unsloth_pp"):
+ return (
+ f"Unsloth: `{what}` is not supported on a pipeline parallel model (each rank holds one stage); save "
+ "the adapter (PipelineParallel.save_adapter) and run it on one GPU."
+ )
+ if _fsdp2_units(root):
+ return (
+ f"Unsloth: `{what}` is not supported on a tensor parallel x native FSDP2 model yet; save the adapter "
+ "(model.save_pretrained or save_tp_adapter, on every rank) and run it on one GPU."
+ )
+ if any(tpn._is_dtensor(p) and p.device_mesh.ndim != 1 for p in root.parameters()):
+ return f"Unsloth: `{what}` supports 1-D tensor parallel meshes only."
+ return None
+
+
+def collective_applies(model):
+ """True when the save / generate of `model` goes through this module (tensor parallel, tp x DDP)."""
+ return _marked(model, tpn._TP_FLAG) and _refusal(tp_root(model), "save") is None
+
+
+def _items(root, select):
+ """(module, name, param) of the sharded parameters a replica replaces, in the same order on every rank."""
+ owners, order, seen = {}, [], set()
+ for module in root.modules():
+ for name, param in module._parameters.items():
+ if param is None:
+ continue
+ owners.setdefault(id(param), []).append((module, name))
+ if id(param) not in seen:
+ seen.add(id(param))
+ order.append(param)
+ names = {id(p): n for n, p in root.named_parameters(remove_duplicate = False)}
+ out = []
+ for param in order:
+ name = names.get(id(param), "")
+ four_bit = getattr(param, "_unsloth_tp_layout", None) is not None
+ if not (tpn._is_dtensor(param) or four_bit):
+ continue
+ if select != "all" and (four_bit or not (param.requires_grad or "lora_" in name)):
+ continue
+ out.append((param, owners[id(param)]))
+ return out
+
+
+def _bytes(param):
+ if tpn._is_dtensor(param):
+ return param.numel() * param.element_size() # global shape
+ tp = param._unsloth_tp_layout[3]
+ full_state = getattr(param, "_unsloth_tp_quant_state", None)
+ absmax = (full_state or param.quant_state).absmax
+ extra = absmax.numel() * absmax.element_size() * (1 if full_state is not None else tp)
+ return param.data.numel() * param.data.element_size() * tp + extra
+
+
+def _workspace(items):
+ """Peak transient gather bytes: pieces, concatenation and reorder of the largest tensor."""
+ return 3 * max((_bytes(p) for p, _ in items), default = 0)
+
+
+def _merge_workspace(items):
+ """Peak GPU bytes to merge one CPU-staged 4-bit projection (save.py _merge_lora)."""
+ peak = 0
+ for p, _ in items:
+ if not tpn._is_dtensor(p):
+ numel = p.data.numel() * p.data.element_size() * 2 * p._unsloth_tp_layout[3]
+ peak = max(peak, _bytes(p) + numel * (2 + 4 + 4))
+ return max(_workspace(items), peak)
+
+
+def _free_bytes(device):
+ if device.type == "cuda":
+ gc.collect()
+ torch.cuda.empty_cache()
+ free, _ = torch.cuda.mem_get_info(device)
+ return free, "free on its GPU"
+ return _host_free(), "of available host RAM"
+
+
+def _host_free():
+ try:
+ import psutil
+ return psutil.virtual_memory().available
+ except Exception:
+ pages = os.sysconf("SC_AVPHYS_PAGES") if hasattr(os, "sysconf") else 0
+ return pages * os.sysconf("SC_PAGE_SIZE") if pages else 1 << 62
+
+
+def _margin(need):
+ return max(512 * _MiB, need // 10)
+
+
+def _comm_device(group, device):
+ dist = _dist()
+ backend = str(dist.get_backend(group)) if dist is not None else "gloo"
+ if "nccl" in backend or "xccl" in backend or "hccl" in backend:
+ return device
+ return torch.device("cpu")
+
+
+def _gather_cat(local, dim, group, tp):
+ import torch.distributed as dist
+
+ local = local.contiguous()
+ pieces = [torch.empty_like(local) for _ in range(tp)]
+ dist.all_gather(pieces, local, group = group)
+ return torch.cat(pieces, dim = dim)
+
+
+def _full_params4bit(weight, base, group, device, keep):
+ """The whole 4-bit weight: the shards' packed codes concatenated back in the 1-GPU order (bitwise the 1-GPU
+ codes) with the 1-GPU QuantState apply_tensor_parallel kept on the CPU (double quantized absmax included)."""
+ import bitsandbytes as bnb
+
+ style, parts, rank, tp = weight._unsloth_tp_layout
+ state = weight.quant_state
+ blocksize = state.blocksize
+ out_local, in_local = state.shape
+ codes = weight.data.reshape(-1).view(torch.uint8).view(out_local, in_local // 2)
+ col = style == tpn.COLWISE
+ dim = 0 if col else 1
+ codes = _gather_cat(codes, dim, group, tp)
+ full_state = getattr(weight, "_unsloth_tp_quant_state", None)
+ absmax = None
+ if full_state is None: # no 1-GPU state kept: the shards' float32 absmax, gathered the same way
+ absmax = _gather_cat(
+ state.absmax.float().view(out_local, in_local // blocksize), dim, group, tp
+ )
+ if not keep:
+ return None
+ if col:
+ codes = tpn._unpermute(codes, 0, parts, tp)
+ absmax = None if absmax is None else tpn._unpermute(absmax, 0, parts, tp)
+ shape = (sum(parts), in_local)
+ else:
+ shape = (out_local, in_local * tp)
+ storage = weight.data.dtype
+ packed = codes.contiguous().view(storage).reshape(-1, 1).to(device)
+ if full_state is not None:
+ full_state = tpn.quant_state_copy(full_state, device)
+ else:
+ full_state = bnb.functional.QuantState(
+ absmax = absmax.contiguous().to(device),
+ shape = torch.Size(shape),
+ code = state.code.to(device),
+ blocksize = blocksize,
+ quant_type = state.quant_type,
+ dtype = state.dtype,
+ )
+ full = bnb.nn.Params4bit(
+ packed,
+ requires_grad = False,
+ quant_state = full_state,
+ blocksize = blocksize,
+ compress_statistics = full_state.nested,
+ quant_type = state.quant_type,
+ quant_storage = storage,
+ module = base,
+ bnb_quantized = True,
+ )
+ if device.type == "cpu" and weight.device.type != "cpu":
+ # CPU-staged export replica: save.py _merge_lora dequantizes it on its original GPU.
+ full._unsloth_tp_stage_device = weight.device
+ return full
+
+
+class _Replica:
+ def __init__(self, select, device):
+ self.select = select
+ self.device = device
+ self.persistent = False # for_inference: kept until for_training / a gradient forward
+ self.swaps = [] # (module, name, sharded parameter)
+ self.attrs = [] # (module __dict__, key, previous value or _MISSING)
+ self.hooks = []
+
+ def set(self, obj, key, value):
+ d = obj.__dict__
+ self.attrs.append((d, key, d.get(key, tpn._MISSING)))
+ if value is tpn._MISSING:
+ d.pop(key, None)
+ else:
+ d[key] = value
+
+
+def _room(need, free, device):
+ """Every rank's (need, free) in bytes, rank order (all ranks run the gather or none does)."""
+ dist = _dist()
+ mine = torch.tensor(
+ [float(need), float(free)], dtype = torch.float64, device = _comm_device(None, device)
+ )
+ if dist is None:
+ return [(need, free)]
+ rows = [torch.empty_like(mine) for _ in range(dist.get_world_size())]
+ dist.all_gather(rows, mine)
+ return [(int(r[0].item()), int(r[1].item())) for r in rows]
+
+
+def _short(room):
+ """The first rank without room, or None."""
+ return next(
+ (r for r, (need, free) in enumerate(room) if need and need + _margin(need) > free), None
+ )
+
+
+def _plan(root, select, keep, what, allow_cpu):
+ """(items, device) once every rank agreed the gather fits; raises with the numbers otherwise."""
+ items = _items(root, select)
+ kept = sum(_bytes(p) for p, _ in items) if keep else 0
+ workspace = _workspace(items)
+ device = _device(root)
+ free, where = _free_bytes(device)
+ room = _room(kept + workspace, free, device)
+ short = _short(room)
+ if short is None:
+ return items, device
+ if allow_cpu and device.type != "cpu":
+ staging = _room(_merge_workspace(items), free, device)
+ cpu_room = _room(kept, _host_free(), device)
+ if _short(staging) is None and _short(cpu_room) is None:
+ if keep:
+ print(
+ f"Unsloth: tensor parallel `{what}`: the whole model ({_gib(kept)}) does not fit "
+ f"{device} ({_gib(free)} free); gathering it to the CPU instead."
+ )
+ return items, torch.device("cpu")
+ where = f"{where}, {_gib(cpu_room[short][1])} of available host RAM"
+ need_s, free_s = room[short]
+ detail = (
+ f"{_gib(need_s)} on its device for it ({_gib(need_s - workspace)} for the replica it keeps, "
+ f"{_gib(workspace)} of gather workspace)"
+ )
+ raise RuntimeError(
+ f"Unsloth: tensor parallel `{what}` gathers a whole single-GPU replica of the model, but rank {short} "
+ f"needs {detail} (+ {_gib(_margin(need_s))} headroom) and has {_gib(free_s)} {where}. "
+ "Free memory (e.g. del trainer; gc.collect(); torch.cuda.empty_cache()), or save the adapter with "
+ "model.save_pretrained(...) and run this on one GPU."
+ )
+
+
+def gather_replica(
+ model,
+ select = "all",
+ keep = True,
+ what = "generate",
+ allow_cpu = False,
+):
+ """Collective: replace the sharded parameters by whole tensors. select "all" or "adapters"; keep = False
+ joins the gather without keeping anything. Idempotent; release_replica undoes it."""
+ root = tp_root(model)
+ current = root.__dict__.get(_REPLICA)
+ if current is not None and (current.select == "all" or current.select == select):
+ return current
+ if current is not None:
+ release_replica(root)
+ refusal = _refusal(root, what)
+ if refusal is not None:
+ raise RuntimeError(refusal)
+ mesh = tpn._tp_meshes(root)[0]
+ if mesh is None:
+ raise RuntimeError("Unsloth: this tensor parallel model has no tp mesh.")
+ group, tp = mesh.get_group(), mesh.size()
+ items, device = _plan(root, select, keep, what, allow_cpu)
+ layouts = tpn._param_layouts(root)
+ replica = _Replica(select, device) if keep else None
+ with torch.no_grad():
+ for param, owners in items:
+ module = owners[0][0]
+ if tpn._is_dtensor(param):
+ full = tpn._full(param, param, layouts.get(id(param)))
+ if not keep:
+ del full
+ continue
+ new = nn.Parameter(full.detach().to(device), requires_grad = param.requires_grad)
+ else:
+ new = _full_params4bit(param, module, group, device, keep)
+ if not keep:
+ continue
+ if "quant_state" in module.__dict__:
+ replica.set(module, "quant_state", new.quant_state)
+ for owner, name in owners:
+ replica.swaps.append((owner, name, param))
+ owner._parameters[name] = new
+ if not keep:
+ return None
+ if select == "all":
+ _switch_to_one_gpu(root, replica)
+ root.__dict__[_REPLICA] = replica
+ return replica
+
+
+def _switch_to_one_gpu(root, replica):
+ """The module state apply_tensor_parallel changed, back to the one-GPU model while the replica is in."""
+ plan = root.__dict__.get("_unsloth_tp_plan")
+ for region in plan.regions if plan is not None else ():
+ module = region.module
+ replica.set(module, "_unsloth_tp_gathered", True) # the region hooks pass through
+ saved = module.__dict__.get("_unsloth_tp_saved_attrs")
+ if saved is not None:
+ for key, value in saved.items():
+ replica.set(module, key, value)
+ for key in ("_unsloth_tp_heads", "_unsloth_tp_kv_heads"):
+ if key in module.__dict__:
+ replica.set(module, key, tpn._MISSING)
+ for proj in region.projs:
+ p = proj.module
+ if "_unsloth_tp_prior_forward" in p.__dict__:
+ replica.set(p, "forward", p.__dict__["_unsloth_tp_prior_forward"])
+ if "_unsloth_tp_local" in p.__dict__:
+ replica.set(p, "_unsloth_tp_local", tpn._MISSING)
+ for level in tpn._tp_chain(root):
+ forward = level.__dict__.get("forward")
+ original = getattr(forward, "__wrapped__", None)
+ if getattr(forward, "__name__", "") != "forward_without_cache" or original is None:
+ continue
+ bound_class = getattr(original, "__func__", None) is getattr(type(level), "forward", None)
+ same = getattr(original, "__self__", None) is level
+ replica.set(level, "forward", tpn._MISSING if bound_class and same else original)
+ replica.hooks.append(root.register_forward_pre_hook(_release_before_training))
+
+
+def _release_before_training(module, args):
+ # A grad-recording forward (also in eval mode) must run on the optimizer's shards, never the replica.
+ if torch.is_grad_enabled() and not torch.is_inference_mode_enabled():
+ release_replica(module)
+
+
+def release_replica(model):
+ """Put the sharded parameters back (local, no collective). True when a replica was in."""
+ root = tp_root(model)
+ replica = root.__dict__.pop(_REPLICA, None)
+ if replica is None:
+ return False
+ for owner, name, param in reversed(replica.swaps):
+ owner._parameters[name] = param
+ for d, key, value in reversed(replica.attrs):
+ if value is tpn._MISSING:
+ d.pop(key, None)
+ else:
+ d[key] = value
+ for hook in replica.hooks:
+ hook.remove()
+ replica.swaps.clear()
+ replica.attrs.clear()
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ return True
+
+
+def tp_for_inference(model):
+ if _marked(model, tpn._TP_FLAG):
+ replica = gather_replica(model, "all", keep = True, what = "for_inference")
+ if (
+ _GENERATE_DEPTH[0] == 0
+ ): # the user's call (generate's own for_inference does not keep it)
+ replica.persistent = True
+ elif _marked(model, "_unsloth_pp"):
+ raise RuntimeError(_refusal(model, "for_inference"))
+
+
+def tp_for_training(model):
+ if _marked(model, tpn._TP_FLAG):
+ release_replica(model)
+
+
+def sync_generation_rng(model):
+ """tp rank 0's CPU and accelerator RNG states to its tp group: sampled tokens agree across tp ranks."""
+ dist = _dist()
+ root = tp_root(model)
+ mesh = tpn._tp_meshes(root)[0]
+ if dist is None or mesh is None or mesh.size() == 1:
+ return
+ group = mesh.get_group()
+ src = dist.get_global_rank(group, 0)
+ device = _device(root)
+ comm = _comm_device(group, device)
+ cpu = torch.get_rng_state().to(comm)
+ dist.broadcast(cpu, src = src, group = group)
+ torch.set_rng_state(cpu.cpu())
+ if device.type == "cuda":
+ state = torch.cuda.get_rng_state(device).to(comm)
+ dist.broadcast(state, src = src, group = group)
+ torch.cuda.set_rng_state(state.cpu(), device)
+
+
+def tp_generate(level, prior, args, kwargs):
+ """Gather the replica (collective), sync sampling, generate; a replica gathered here is released after."""
+ transient = False
+ if _GENERATE_DEPTH[0] == 0:
+ transient = not replica_active(level)
+ gather_replica(level, "all", keep = True, what = "generate")
+ sync_generation_rng(level)
+ if prior is not None:
+ fn = prior
+ elif hasattr(type(level), "generate"):
+ fn = types.MethodType(type(level).generate, level)
+ else: # a forwarding wrapper (PEFT LoraModel): what its __getattr__ resolves, the level below
+ fn = type(level).__getattr__(level, "generate")
+ _GENERATE_DEPTH[0] += 1
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ _GENERATE_DEPTH[0] -= 1
+ replica = tp_root(level).__dict__.get(_REPLICA)
+ if transient and replica is not None and not replica.persistent:
+ release_replica(level)
+
+
+def _timeout():
+ try:
+ return datetime.timedelta(
+ seconds = float(os.environ.get("UNSLOTH_TP_SAVE_TIMEOUT", 7 * 86400))
+ )
+ except ValueError:
+ return datetime.timedelta(days = 7)
+
+
+def _key(namespace):
+ _COUNTERS[namespace] = _COUNTERS.get(namespace, 0) + 1
+ return f"unsloth_tp_{namespace}_{_COUNTERS[namespace]}"
+
+
+def _store():
+ dist = _dist()
+ try:
+ return dist.distributed_c10d._get_default_store()
+ except Exception:
+ return None
+
+
+def _publish(key, payload):
+ store = _store()
+ if store is None:
+ _dist().barrier()
+ return
+ try:
+ data = pickle.dumps(payload)
+ except Exception:
+ data = pickle.dumps((payload[0], None) + tuple(payload[2:]))
+ store.set(key, data)
+
+
+def _wait(key):
+ store = _store()
+ if store is None:
+ _dist().barrier()
+ return ("ok", None)
+ store.wait([key], _timeout())
+ return pickle.loads(store.get(key))
+
+
+def _keep_tree(root):
+ """Every module's children, parameters and PEFT merge flags: a writer that unloads or merges in place
+ (merge_and_unload) must leave rank 0 with the module tree the other ranks still have."""
+ if not isinstance(root, nn.Module):
+ return []
+ kept = []
+ for module in root.modules():
+ merged = getattr(module, "merged_adapters", None)
+ kept.append(
+ (
+ module,
+ list(module._modules.items()),
+ list(module._parameters.items()),
+ list(merged) if isinstance(merged, list) else None,
+ )
+ )
+ return kept
+
+
+def _restore_tree(kept):
+ for module, children, params, merged in kept:
+ if list(module._modules.items()) != children:
+ module._modules.clear()
+ module._modules.update(children)
+ if list(module._parameters.items()) != params:
+ module._parameters.clear()
+ module._parameters.update(params)
+ if merged is not None and getattr(module, "merged_adapters", None) is not None:
+ module.merged_adapters[:] = merged
+
+
+def _on_rank0(
+ key,
+ what,
+ call,
+ model = None,
+):
+ """Rank 0 runs `call`; the others wait for it on the store and return its result or raise its error."""
+ if _rank() == 0:
+ _ACTIVE.append(what)
+ payload = ("error", "rank 0 did not finish")
+ kept = _keep_tree(model)
+ try:
+ result = call()
+ payload = ("ok", result)
+ return result
+ except BaseException as exc:
+ payload = ("error", f"{type(exc).__name__}: {exc}")
+ raise
+ finally:
+ _restore_tree(kept)
+ _ACTIVE.pop()
+ _publish(key, payload)
+ status, value = _wait(key)[:2]
+ if status != "ok":
+ raise RuntimeError(f"Unsloth: tensor parallel `{what}` failed on rank 0: {value}")
+ return value
+
+
+def tp_collective(
+ model,
+ what,
+ call,
+ select = "all",
+):
+ """Every rank calls; the tensors `select` needs are gathered to rank 0, which runs `call` (the unchanged
+ single-process save) on the one-GPU-looking model; the other ranks wait and return rank 0's result."""
+ if _ACTIVE or _dist() is None:
+ return call()
+ root = tp_root(model)
+ refusal = _refusal(root, what)
+ if refusal is not None:
+ raise RuntimeError(refusal)
+ key = _key("save")
+ writer = _rank() == 0
+ current = root.__dict__.get(_REPLICA)
+ gathered = False
+ if current is None or (current.select != "all" and select == "all"):
+ if _rank() == 0 and select == "all":
+ print(
+ f"Unsloth: tensor parallel `{what}`: gathering the whole model to rank 0, which saves."
+ )
+ gather_replica(root, select, keep = writer, what = what, allow_cpu = select == "all")
+ gathered = writer
+ try:
+ return _on_rank0(key, what, call, root)
+ finally:
+ if gathered:
+ release_replica(root)
+
+
+def mark_world_save(obj):
+ """Route a tokenizer / processor's save_pretrained through tp_world_save (nested tokenizer included)."""
+ d = getattr(obj, "__dict__", None)
+ if not isinstance(d, dict) or d.get("_unsloth_tp_world_save"):
+ return obj
+ d["_unsloth_tp_world_save"] = True
+ save = getattr(obj, "save_pretrained", None)
+ if callable(save) and getattr(save, "__name__", "") != "unsloth_tokenizer_save_pretrained":
+ from ..save import _TokenizerBoundMethod
+ if "save_pretrained" in d:
+ d["_unsloth_tp_inner_save"] = d["save_pretrained"]
+ # A picklable bound wrapper, not a closure: spawn-based DataLoader workers pickle the processor.
+ d["save_pretrained"] = _TokenizerBoundMethod(
+ unsloth_tp_world_save_pretrained, obj, "save_pretrained"
+ )
+ nested = d.get("tokenizer")
+ if nested is not None and nested is not obj:
+ mark_world_save(nested)
+ return obj
+
+
+def unsloth_tp_world_save_pretrained(
+ obj,
+ save_directory,
+ *args,
+ push_to_hub = False,
+ **kwargs,
+):
+ """mark_world_save's save_pretrained: the object's own save, through tp_world_save."""
+ save = obj.__dict__.get("_unsloth_tp_inner_save") or type(obj).save_pretrained.__get__(obj)
+ what = f"{type(obj).__name__}.save_pretrained"
+ result = tp_world_save(what, lambda path: save(path, *args, **kwargs), save_directory)
+ if push_to_hub:
+ repo_id = kwargs.pop(
+ "repo_id", os.path.basename(os.path.normpath(os.fspath(save_directory)))
+ )
+ push = {
+ k: kwargs[k] for k in ("commit_message", "token", "private", "revision") if k in kwargs
+ }
+ tp_world_push(f"{type(obj).__name__}.push_to_hub", lambda: obj.push_to_hub(repo_id, **push))
+ return result
+
+
+def _relocated(value, private, target):
+ """The save's return value with paths under `private` pointing into `target` instead."""
+ if isinstance(value, (tuple, list)):
+ return type(value)(_relocated(v, private, target) for v in value)
+ if isinstance(value, (str, os.PathLike)):
+ path = os.fspath(value)
+ if os.path.abspath(path).startswith(private):
+ moved = os.path.join(target, os.path.relpath(os.path.abspath(path), private))
+ return type(value)(moved) if not isinstance(value, str) else moved
+ return value
+
+
+def tp_world_save(what, write, directory):
+ """Each rank writes a private copy and os.replace's every file in; no rank waits, so nothing can desync."""
+ dist = _dist()
+ try:
+ target = os.fspath(directory)
+ except TypeError:
+ target = None
+ if _ACTIVE or dist is None or dist.get_world_size() == 1 or not target:
+ return write(directory)
+ import shutil
+ import tempfile
+
+ absolute = os.path.abspath(target)
+ parent = os.path.dirname(absolute)
+ os.makedirs(absolute, exist_ok = True)
+ private = tempfile.mkdtemp(
+ prefix = f".{os.path.basename(absolute)}.unsloth_tp_rank{_rank()}_", dir = parent
+ )
+ try:
+ result = write(private)
+ for root, _, files in os.walk(private):
+ rel = os.path.relpath(root, private)
+ destination = absolute if rel == "." else os.path.join(absolute, rel)
+ os.makedirs(destination, exist_ok = True)
+ for name in files:
+ os.replace(os.path.join(root, name), os.path.join(destination, name))
+ finally:
+ shutil.rmtree(private, ignore_errors = True)
+ return _relocated(result, private, target)
+
+
+def tp_world_push(what, call):
+ """A Hub upload of a tokenizer / processor: global rank 0 uploads, the other ranks return None (no
+ rendezvous, so an upload rank 0 makes alone desyncs nothing)."""
+ dist = _dist()
+ if _ACTIVE or dist is None or dist.get_world_size() == 1:
+ return call()
+ if _rank() != 0:
+ return None
+ _ACTIVE.append(what)
+ try:
+ return call()
+ finally:
+ _ACTIVE.pop()
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 51a10e99f9e..6651734b174 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -268,7 +268,7 @@ from ._utils import (
)
from ._utils import *
from ._utils import _ignore_block_swap_params_for_ddp
-from ._utils import _refuse_tensor_parallel_for_inference
+from ._utils import _tensor_parallel_for_inference, _tensor_parallel_for_training
from ._uma_safetensors import is_integrated_unified_memory_gpu
from ._utils import estimate_training_reserve_bytes as _zoo_reserve_estimate
from ._remote_code_buffers import restore_remote_code_non_persistent_buffers
@@ -5599,7 +5599,7 @@ class FastBaseModel:
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_inference!"
)
- _refuse_tensor_parallel_for_inference(model)
+ _tensor_parallel_for_inference(model)
def _for_inference(m):
if hasattr(m, "gradient_checkpointing"):
@@ -5645,6 +5645,7 @@ class FastBaseModel:
raise TypeError(
"Unsloth: I think you're passing a tokenizer, not the model to for_training!"
)
+ _tensor_parallel_for_training(model)
# Mode last, as model.train() was: a custom train() keeps the final say over the chain below.
checkpointing, apply_training_mode = switch_training_mode(model, True, defer = True)
use_gradient_checkpointing = resolve_training_gradient_checkpointing(
diff --git a/unsloth/save.py b/unsloth/save.py
index 41b577501e9..57145b170a5 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -70,6 +70,7 @@ from .models.loader_utils import (
_tokenizer_wants_local_only,
)
from .models._utils import (
+ _is_unsloth_tensor_parallel,
_refuse_model_parallel_export,
_convert_torchao_model,
_merged_torchao_config_for_peft_qat,
@@ -865,12 +866,21 @@ def _merge_lora(
bias = getattr(layer, "bias", None)
if isinstance(layer, (Bnb_Linear4bit, Peft_Linear4bit, Peft_Linear)):
W, quant_state, A, B, s, bias = get_lora_parameters_bias(layer)
+ stage = None
if quant_state is not None and W.dtype == torch.float8_e4m3fn:
# FP8 quant_state is the fp32 scale, not the model dtype: dequant in fp32, save in model dtype.
W = fast_dequantize(W, quant_state, dtype = torch.float32)
dtype = dtype if isinstance(dtype, torch.dtype) else torch.bfloat16
elif quant_state is not None:
dtype = quant_state.dtype if type(quant_state) is not list else quant_state[2]
+ # CPU-staged tp export replica: merge on its GPU, return the result on the CPU.
+ stage = getattr(W, "_unsloth_tp_stage_device", None)
+ if stage is not None:
+ from .models.tp_native import quant_state_copy
+
+ W, quant_state = W.data.to(stage), quant_state_copy(quant_state, stage)
+ A = None if A is None else A.to(stage)
+ B = None if B is None else B.to(stage)
W = fast_dequantize(W, quant_state)
else:
dtype = W.dtype
@@ -882,6 +892,8 @@ def _merge_lora(
if not torch.isfinite(maximum_element).item():
raise ValueError(f"Unsloth: Merge failed.\n{name} has some elements = infinity.")
W = W.t().to(dtype)
+ if stage is not None:
+ W = W.cpu()
else:
W = layer.weight
return W, bias
@@ -1285,14 +1297,45 @@ def _restore_tied_weights_keys(originals):
pass
+_TP_IN_PLACE_MERGES = ("merged_4bit", "merged_4bit_forced", "forced_merged_4bit")
+
+
+def _refuse_tp_in_place_merge(fn, method, args, kwargs):
+ """merged_4bit merges the LoRA weights into the loaded 4-bit base (merge_and_unload): under tensor parallel
+ only rank 0 would hold that merged model. Refused on every rank (every rank makes the same call)."""
+ import inspect
+
+ try:
+ save_method = (
+ inspect.signature(fn).bind_partial(*args, **kwargs).arguments.get("save_method")
+ )
+ except (TypeError, ValueError):
+ save_method = kwargs.get("save_method")
+ if isinstance(save_method, str) and save_method.lower().strip() in _TP_IN_PLACE_MERGES:
+ raise RuntimeError(
+ f'Unsloth: `{method}(save_method = "{save_method}")` merges the LoRA weights into the 4-bit base in '
+ "place (merge_and_unload). On a tensor parallel model only rank 0 would end up with that merged "
+ "model, so it is not supported there. Save the adapter (model.save_pretrained) or use "
+ 'save_method = "merged_16bit", or load the adapter on one GPU and run merged_4bit there.'
+ )
+
+
def _model_parallel_refuses_save(method):
- """Every whole-model export refuses an apply_tensor_parallel / apply_pipeline_parallel model before it
- writes anything (see _refuse_model_parallel_export)."""
+ """Every whole-model export refuses an apply_pipeline_parallel model before it writes anything (see
+ _refuse_model_parallel_export). A tensor parallel model (tp, or tp x DDP-style dp) is gathered to rank 0,
+ which runs the export; the other ranks wait for it (models/tp_replica.py)."""
def decorate(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
model = args[0] if args else kwargs.get("model", kwargs.get("self"))
+ if model is not None and _is_unsloth_tensor_parallel(model):
+ from .models.tp_replica import collective_applies, tp_collective
+ if collective_applies(model):
+ _refuse_tp_in_place_merge(fn, method, args, kwargs)
+ # The whole model, also for LoRA-only writers: they run under inference_mode, where
+ # state_dict() cannot detach the frozen DTensor shards.
+ return tp_collective(model, method, lambda: fn(*args, **kwargs), "all")
if model is not None:
_refuse_model_parallel_export(model, method)
return fn(*args, **kwargs)
@@ -6724,6 +6767,32 @@ def _fsdp2_collective_save(
return decorate
+def _tp_collective_save(method):
+ """save_pretrained / push_to_hub under tensor parallel: every rank calls, rank 0 writes the one-GPU files
+ (the LoRA tensors gathered for an adapter, the whole model otherwise) and the others wait for it. A
+ tokenizer of a tensor parallel run is written once, by rank 0. A call that brings its own `state_dict`
+ (save_tp_adapter's rank 0 write) is passed through."""
+
+ def decorate(fn):
+ @functools.wraps(fn)
+ def wrapper(self, *args, **kwargs):
+ if isinstance(self, torch.nn.Module) and _is_unsloth_tensor_parallel(self):
+ from .models.tp_replica import collective_applies, tp_collective
+ arguments = _fsdp2_save_arguments(fn, self, args, kwargs)
+ if arguments.get("state_dict") is None and collective_applies(self):
+ adapter = isinstance(self, PeftModel) and not torch.is_inference_mode_enabled()
+ select = "adapters" if adapter else "all"
+ return tp_collective(self, method, lambda: fn(self, *args, **kwargs), select)
+ elif getattr(self, "__dict__", {}).get("_unsloth_tp_world_save"):
+ from .models.tp_replica import tp_world_push
+ return tp_world_push(method, lambda: fn(self, *args, **kwargs))
+ return fn(self, *args, **kwargs)
+
+ return wrapper
+
+ return decorate
+
+
def _fsdp2_rank():
import torch.distributed as dist
return dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
@@ -8590,6 +8659,34 @@ def unsloth_tokenizer_save_pretrained(
filename_prefix = None,
push_to_hub = False,
**kwargs,
+):
+ if self.__dict__.get("_unsloth_tp_world_save"):
+ from .models.tp_replica import tp_world_save
+
+ push_kwargs = dict(kwargs)
+ repo_id = push_kwargs.pop("repo_id", save_directory)
+ result = tp_world_save(
+ "tokenizer.save_pretrained",
+ lambda path: _unsloth_tokenizer_save_pretrained(
+ self, path, legacy_format, filename_prefix, False, **kwargs
+ ),
+ save_directory,
+ )
+ if push_to_hub:
+ self.push_to_hub(repo_id, **push_kwargs)
+ return result
+ return _unsloth_tokenizer_save_pretrained(
+ self, save_directory, legacy_format, filename_prefix, push_to_hub, **kwargs
+ )
+
+
+def _unsloth_tokenizer_save_pretrained(
+ self,
+ save_directory,
+ legacy_format = None,
+ filename_prefix = None,
+ push_to_hub = False,
+ **kwargs,
):
# Forward only what the caller set: MistralCommonBackend (Voxtral, tekken checkpoints) rejects these even as None.
save_kwargs = dict(kwargs)
@@ -8699,11 +8796,14 @@ def patch_saving_functions(model, vision = False):
exec(push_to_hub_text, globals())
# Under FSDP2 every rank calls push_to_hub: the shards are gathered and rank 0 uploads. Inside,
# the wrapped save_pretrained sees the gather already active and writes directly.
- globals()["unsloth_push_to_hub"] = _fsdp2_collective_save(
- lambda self, args, kwargs: isinstance(self, PeftModel),
- offload_4bit = True,
- )(globals()["unsloth_push_to_hub"])
+ globals()["unsloth_push_to_hub"] = _tp_collective_save("push_to_hub")(
+ _fsdp2_collective_save(
+ lambda self, args, kwargs: isinstance(self, PeftModel),
+ offload_4bit = True,
+ )(globals()["unsloth_push_to_hub"])
+ )
+ @_tp_collective_save("save_pretrained")
@_fsdp2_collective_save(
lambda self, args, kwargs: isinstance(self, PeftModel), offload_4bit = True
)