Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Tensor parallelism v2: sharded loading, data parallel x tensor parallel, and the Trainer (#15174)
Daniel Han957adb359e82
diff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.pyindex 396c142ce10..e1f3f857407 100644--- a/tests/test_tp_native_gloo.py+++ b/tests/test_tp_native_gloo.py@@ -404,6 +404,373 @@ def _case_save_subgroup(rank, world, tmp):return {"error": _raised(lambda: tpn.save_tp_adapter(model, os.path.join(tmp, "out")))}+def _save_checkpoint(+ arch,+ directory,+ overrides = None,+):+ """A tiny random model saved as several safetensors files (index + shards), like a Hub checkpoint."""+ repo, base_overrides = ARCHS[arch]+ model = build(repo, {**base_overrides, **(overrides or {})}, lora = False)+ model.generation_config.pad_token_id = None # tiny repos ship -1, which save_pretrained rejects+ model.save_pretrained(directory, max_shard_size = "1MB", safe_serialization = True)+ return directory+++def _case_sharded_load(+ rank,+ world,+ tmp,+ arch,+ ckpt,+ lora_kwargs = None,+):+ """sharded_loading + get_peft_model + apply_tensor_parallel vs a full load (1 process, and v1 TP)."""+ from peft import LoraConfig, get_peft_model+ from safetensors.torch import load_file+ from torch.distributed.device_mesh import init_device_mesh+ from transformers import AutoModelForCausalLM++ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("tp",))+ kw = dict(torch_dtype = torch.float32, attn_implementation = "eager")++ def peft(model):+ torch.manual_seed(1)+ config = dict(r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False)+ config.update(lora_kwargs or {})+ return get_peft_model(model, LoraConfig(**config)).eval()++ ref = peft(AutoModelForCausalLM.from_pretrained(ckpt, **kw))+ full_tp = peft(AutoModelForCausalLM.from_pretrained(ckpt, **kw))+ tpn.apply_tensor_parallel(full_tp, mesh["tp"])+ model = tpn.load_tensor_parallel(+ ckpt, mesh["tp"], loader = AutoModelForCausalLM.from_pretrained, **kw+ )+ stats = dict(model._unsloth_tp_load_stats)+ ids = _batch(ref)+ unapplied = _raised(lambda: model(input_ids = ids))+ model = peft(model)+ tpn.apply_tensor_parallel(model, mesh["tp"])+ # Every local tensor equals the v1 shard bitwise (weights, biases, LoRA, buffers).+ a, b = full_tp.state_dict(), model.state_dict()+ local = lambda t: t.to_local() if tpn._is_dtensor(t) else t # noqa: E731+ diffs = sorted(set(a) ^ set(b)) + [+ k for k in a if k in b and not torch.equal(local(a[k]), local(b[k]))+ ]+ full_local = sum(local(p).numel() for p in full_tp.parameters())+ sharded_local = sum(local(p).numel() for p in model.parameters())+ from test_fsdp2_native_units import _load_native++ try:+ _load_native()._refuse_tensor_parallel_model(model)+ fsdp2_refused = None+ except RuntimeError as e:+ fsdp2_refused = str(e)+ ref_out = _train(ref, ids, 3, torch.nn.utils.clip_grad_norm_)+ v1_out = _train(full_tp, ids, 3, tpn.tp_clip_grad_norm_)+ tp_out = _train(model, ids, 3, tpn.tp_clip_grad_norm_)+ ref_dir, tp_dir = os.path.join(tmp, f"ref{rank}"), os.path.join(tmp, "tp")+ ref.save_pretrained(ref_dir)+ tpn.save_tp_adapter(model, tp_dir)+ q = tpn._weight(model._unsloth_tp_plan.regions[0].projs[0].module)[0]+ return {+ "ref": ref_out,+ "tp": tp_out,+ "v1": v1_out,+ "diffs": diffs,+ "stats": stats,+ "unapplied": unapplied,+ "local_numel": (full_local, sharded_local),+ "saved_ref": load_file(os.path.join(ref_dir, "adapter_model.safetensors")),+ "saved_tp": load_file(os.path.join(tp_dir, "adapter_model.safetensors"))+ if rank == 0+ else None,+ "local_q": (tuple(q.to_local().shape), tuple(q.shape), q.placements[0].dim),+ "fsdp2_refused": fsdp2_refused,+ }+++def _case_tp_fsdp2(+ rank,+ world,+ tmp,+ arch,+ fit_layout = True,+ lora_kwargs = None,+):+ """dp 2 x tp 2: apply_tensor_parallel over mesh['tp'], native FSDP2 shard_model over mesh['dp'], each dp+ replica on its own half of the batch, vs one process on the whole batch."""+ import torch.distributed as dist+ from safetensors.torch import load_file+ from torch.distributed.device_mesh import init_device_mesh+ from test_fsdp2_native_units import _load_native++ native = _load_native()+ repo, overrides = ARCHS[arch]+ mesh = init_device_mesh("cpu", (2, world // 2), mesh_dim_names = ("dp", "tp"))+ dp = mesh["dp"].get_local_rank()+ ref = build(repo, overrides, **(lora_kwargs or {}))+ model = build(repo, overrides, **(lora_kwargs or {}))+ ids = _batch(ref, bsz = 4)+ mine = ids[2 * dp : 2 * dp + 2]+ tpn.apply_tensor_parallel(model, mesh["tp"])+ if not native._supports_ignored_params(native._fsdp_api()[2]):+ # torch < 2.7: no fully_shard(ignored_params) to keep the frozen tp shards out of FSDP2.+ config = native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"])+ return {"unsupported": _raised(lambda: native.shard_model(model, config))}+ refusals = {+ "no_mesh": _raised(+ lambda: native.shard_model(model, native.FSDP2Config(param_dtype = torch.float32))+ ),+ "tp_mesh": _raised(+ lambda: native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["tp"])+ )+ ),+ "shard_frozen": _raised(+ lambda: native.shard_model(+ model,+ native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"], shard_frozen = True),+ )+ ),+ }+ native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"], fit_layout = fit_layout)+ )+ layouts = tpn._param_layouts(model)+ params = [p for p in model.parameters() if p.requires_grad]+ ref_params = [p for p in ref.parameters() if p.requires_grad]+ opt = torch.optim.AdamW(params, lr = 1e-2, foreach = False)+ ref_opt = torch.optim.AdamW(ref_params, lr = 1e-2, foreach = False)+ losses, ref_losses, norms, native_norms, ref_norms = [], [], [], [], []+ for step in range(3):+ out = model(input_ids = mine, labels = mine, use_cache = False)+ out.loss.backward()+ r = ref(input_ids = ids, labels = ids, use_cache = False)+ r.loss.backward()+ if step == 0:+ grads = {+ n: tpn._full(p.grad, layout = layouts.get(id(p))).detach().clone()+ for n, p in model.named_parameters()+ if p.grad is not None+ }+ ref_grads = {+ n: p.grad.detach().clone() for n, p in ref.named_parameters() if p.grad is not None+ }+ mismatched = [+ n+ for n, p in model.named_parameters()+ if p.grad is not None and tuple(p.grad.placements) != tuple(p.placements)+ ]+ native_norms.append(float(native.native_clip_grad_norm_(params, 1e9)))+ norms.append(float(tpn.tp_clip_grad_norm_(params, 1.0)))+ ref_norms.append(float(_clip_fp64(ref_params, 1.0)))+ opt.step(), opt.zero_grad(set_to_none = True)+ ref_opt.step(), ref_opt.zero_grad(set_to_none = True)+ loss = out.loss.detach().clone()+ dist.all_reduce(loss) # mean over the 4 ranks = mean over the 2 dp halves (tp ranks agree)+ losses.append(float(loss) / world)+ ref_losses.append(float(r.loss))+ ref_dir, tp_dir = os.path.join(tmp, f"ref{rank}"), os.path.join(tmp, "tp")+ ref.save_pretrained(ref_dir)+ tpn.save_tp_adapter(model, tp_dir)+ dist.barrier()+ return {+ "grads": grads,+ "ref_grads": ref_grads,+ "mismatched": mismatched,+ "losses": losses,+ "ref_losses": ref_losses,+ "norms": norms,+ "native_norms": native_norms,+ "ref_norms": ref_norms,+ "refusals": refusals,+ "placements": {+ n: tuple(p.placements) for n, p in model.named_parameters() if p.requires_grad+ },+ "saved_ref": load_file(os.path.join(ref_dir, "adapter_model.safetensors")),+ "saved_tp": load_file(os.path.join(tp_dir, "adapter_model.safetensors"))+ if rank == 0+ else None,+ }+++def _case_tp_fsdp2_trainable_norms(rank, world, tmp):+ from torch.distributed.device_mesh import init_device_mesh+ from test_fsdp2_native_units import _load_native++ native = _load_native()+ mesh = init_device_mesh("cpu", (2, 2), mesh_dim_names = ("dp", "tp"))+ model = build(QWEN3, train_norms = True)+ tpn.apply_tensor_parallel(model, mesh["tp"])+ return {+ "error": _raised(+ lambda: native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"])+ )+ )+ }+++class _Rows(torch.utils.data.Dataset):+ def __init__(self, ids):+ self.ids = ids++ def __len__(self):+ return len(self.ids)++ def __getitem__(self, i):+ return {"input_ids": self.ids[i], "labels": self.ids[i]}+++def _trainer_args(tmp, bs, **overrides):+ import transformers++ kwargs = dict(+ output_dir = tmp,+ per_device_train_batch_size = bs,+ gradient_accumulation_steps = 2,+ max_steps = 3,+ learning_rate = 1e-2,+ optim = "adamw_torch",+ lr_scheduler_type = "constant",+ warmup_steps = 0,+ weight_decay = 0.0,+ max_grad_norm = 1.0,+ logging_steps = 1,+ save_strategy = "no",+ report_to = [],+ use_cpu = True,+ seed = 0,+ dataloader_drop_last = True,+ remove_unused_columns = False,+ disable_tqdm = True,+ )+ kwargs.update(overrides)+ return transformers.TrainingArguments(**kwargs)+++def _case_trainer(+ rank,+ world,+ tmp,+ dp,+ tp,+ lora_kwargs = None,+):+ """The HF Trainer on a tp (dp = 1) or dp x tp (shard_model over mesh['dp']) model; tp = 1: the 1-process+ reference with a dp times larger batch. Sequential batches, so both read the same rows per step."""+ import torch.distributed as dist+ import transformers+ from safetensors.torch import load_file++ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ from torch.distributed.device_mesh import init_device_mesh+ from unsloth.models import fsdp2_native, tp_native+ from unsloth.models._utils import patch_gradient_accumulation_fix++ patch_gradient_accumulation_fix(transformers.Trainer)+ seen = []++ class SequentialTrainer(transformers.Trainer):+ def _get_train_sampler(self, *args, **kwargs):+ return torch.utils.data.SequentialSampler(self.train_dataset)++ def compute_loss(self, model, inputs, *args, **kwargs):+ seen.append(inputs["input_ids"].clone())+ return super().compute_loss(model, inputs, *args, **kwargs)++ model = build(LLAMA, **(lora_kwargs or {}))+ data = _Rows(list(_batch(model, bsz = 12 * dp, seq = 9)))+ refusals = {}+ if tp > 1:+ mesh = init_device_mesh("cpu", (dp, tp), mesh_dim_names = ("dp", "tp"))+ tp_native.apply_tensor_parallel(model, mesh["tp"])+ if dp > 1:+ refusals["no_shard_model"] = _raised(+ lambda: SequentialTrainer(+ model = model, args = _trainer_args(tmp, 2), train_dataset = data+ )+ )+ fsdp2_native.shard_model(+ model, fsdp2_native.FSDP2Config(param_dtype = torch.float32, mesh = mesh["dp"])+ )+ for key, overrides in {+ "checkpoints": {"save_strategy": "steps", "save_steps": 1},+ "eval": {"eval_strategy": "steps", "eval_steps": 1},+ "optim_8bit": {"optim": "adamw_bnb_8bit"},+ }.items():+ refusals[key] = _raised(+ lambda: SequentialTrainer(+ model = model,+ args = _trainer_args(tmp, 2, **overrides),+ train_dataset = data,+ eval_dataset = data,+ )+ )+ if tp > 1 and lora_kwargs:+ # A prebuilt scheduler already recorded the mixed groups: refused, not split under it.+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr = 1e-2)+ sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda step: 1.0)+ refusals["prebuilt_scheduler"] = _raised(+ lambda: SequentialTrainer(+ model = model,+ args = _trainer_args(tmp, 2),+ train_dataset = data,+ optimizers = (opt, sched),+ ).train()+ )+ trainer = SequentialTrainer(+ model = model, args = _trainer_args(tmp, 2 * dp if tp == 1 else 2), train_dataset = data+ )+ trainer.train()+ refusals["evaluate"] = _raised(lambda: trainer.evaluate(data)) if tp > 1 else None+ logs = [h for h in trainer.state.log_history if "loss" in h]+ out_dir = os.path.join(tmp, f"adapter_{world}_{rank}")+ trainer.save_model(out_dir)+ if dist.is_initialized():+ dist.barrier()+ state = (+ tp_native.tp_full_state_dict(trainer.model, adapters_only = True)+ if tp > 1+ else {k: v.detach().clone() for k, v in trainer.model.state_dict().items() if "lora_" in k}+ )+ wrapped = type(trainer.model_wrapped).__name__+ return {+ "losses": [h["loss"] for h in logs],+ "grad_norms": [h.get("grad_norm") for h in logs],+ "seen": [x.sum().item() for x in seen],+ "state": {k: v for k, v in state.items() if "lora_" in k},+ "saved": load_file(os.path.join(out_dir, "adapter_model.safetensors"))+ if rank == 0 or tp == 1+ else None,+ "wrapped": wrapped,+ "refusals": refusals,+ "mixed_groups": fsdp2_native._mixed_param_groups(trainer.optimizer),+ }+++def _case_sharded_lora_init(rank, world, tmp, ckpt):+ """Weight-dependent LoRA init (PiSSA) on sharded_loading slices is refused before any mutation."""+ from peft import LoraConfig, get_peft_model+ from torch.distributed.device_mesh import init_device_mesh+ from transformers import AutoModelForCausalLM++ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("tp",))+ out = {}+ for init in ("pissa", "gaussian"):+ model = tpn.load_tensor_parallel(+ ckpt, mesh["tp"], loader = AutoModelForCausalLM.from_pretrained, torch_dtype = torch.float32+ )+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = init)+ model = get_peft_model(model, config)+ out[init] = _raised(lambda: tpn.apply_tensor_parallel(model, mesh["tp"]))+ out[init + "_tp"] = tpn.is_tensor_parallel(model)+ return out++CASES = {"parity": _case_parity,"save_subgroup": _case_save_subgroup,@@ -411,6 +778,11 @@ CASES = {"guards": _case_guards,"qlora": _case_qlora,"qlora_misaligned": _case_qlora_misaligned,+ "sharded_load": _case_sharded_load,+ "sharded_lora_init": _case_sharded_lora_init,+ "tp_fsdp2": _case_tp_fsdp2,+ "tp_fsdp2_trainable_norms": _case_tp_fsdp2_trainable_norms,+ "trainer": _case_trainer,}@@ -617,12 +989,19 @@ def test_tp2_entry_points_outside_the_regions_are_refused():)elif key.startswith("generate:"):assert value and "generation is not supported" in value, (applied, key, value)- elif key.startswith(("trainer:", "model_init:")):+ elif key.startswith("model_init:"):assert value and "cannot be trained by the Trainer" in value, (applied,key,value,)+ elif key.startswith("trainer:"):+ # The Trainer trains a tensor parallel model, but not with checkpoints (default args).+ assert value and "does not support Trainer checkpoints" in value, (+ applied,+ key,+ value,+ )elif key.startswith("cached:"):assert value and "cached decoding" in value, (applied, key, value)@@ -630,3 +1009,180 @@ def test_tp2_entry_points_outside_the_regions_are_refused():def test_save_refuses_a_tp_mesh_smaller_than_the_world():for res in _spawn("save_subgroup", 2):assert res["error"] and "data parallel > 1 is outside v1" in res["error"], res+++ "arch,world,overrides",+ [+ ("llama", 2, None),+ ("llama_bias", 2, None), # colwise biases sliced on read, row biases whole+ ("phi3", 2, None), # fused qkv [q, kv, kv] and packed gate_up read as per-part slices+ ("gemma2", 2, None), # tied embeddings, softcapping+ ("qwen3", 4, {"num_attention_heads": 8, "num_key_value_heads": 4, "intermediate_size": 64}),+ ],+)+def test_sharded_loading_matches_full_load(arch, world, overrides):+ skip_unsupported(arch)+ with tempfile.TemporaryDirectory() as ckpt:+ _save_checkpoint(arch, ckpt, overrides)+ results = _spawn("sharded_load", world, arch = arch, ckpt = ckpt)+ _check_parity(results, world)+ for res in results:+ assert res["diffs"] == [], res["diffs"][:6]+ # The sharded load trains exactly like v1's full load + apply_tensor_parallel.+ assert res["tp"][2] == res["v1"][2] and res["tp"][3] == res["v1"][3]+ torch.testing.assert_close(res["tp"][0], res["v1"][0], rtol = 0, atol = 0)+ assert res["unapplied"] and "call apply_tensor_parallel" in res["unapplied"], res[+ "unapplied"+ ]+ stats = res["stats"]+ # Only this rank's slices of the sharded projections were read; replicated tensors were read whole.+ assert stats["read_bytes_sliced"] * world == stats["sharded_numel"] * 4, stats+ assert stats["read_bytes_full"] == stats["replicated_numel"] * 4, stats+ assert stats["sharded_numel"] > 0 and stats["regions"] > 0, stats+ full_local, sharded_local = res["local_numel"]+ assert full_local == sharded_local+++def test_sharded_loading_refuses_weight_dependent_lora_init():+ with tempfile.TemporaryDirectory() as ckpt:+ _save_checkpoint("llama", ckpt, None)+ results = _spawn("sharded_lora_init", 2, ckpt = ckpt)+ for res in results:+ assert "depends on the base weight" in (res["pissa"] or ""), res+ assert not res["pissa_tp"]+ assert res["gaussian"] is None and res["gaussian_tp"], res+++def test_sharded_loading_refuses_quantized_loads():+ from transformers import AutoModelForCausalLM+ for key in ("load_in_4bit", "quantization_config"):+ with pytest.raises(ValueError, match = "16-bit safetensors checkpoints only"):+ tpn.load_tensor_parallel(+ LLAMA, None, loader = AutoModelForCausalLM.from_pretrained, **{key: True}+ )+++ "arch,fit_layout,lora_kwargs",+ [+ ("llama", True, None),+ ("llama", None, None), # automatic layout (frozen tp shards still replicated over dp)+ ("phi3", True, None), # packed / fused parts: saved in the 1-GPU order through FSDP2+ (+ "llama_bias",+ True,+ {"bias": "all"},+ ), # trainable column (Shard) and row (Replicate) biases+ (+ "llama",+ True,+ {"modules_to_save": ["lm_head"]},+ ), # a dp-only (1-D) trainable outside the tp regions+ ],+)+def test_tp2_x_fsdp2_dp2_matches_one_process(arch, fit_layout, lora_kwargs):+ skip_unsupported(arch)+ results = _spawn("tp_fsdp2", 4, arch = arch, fit_layout = fit_layout, lora_kwargs = lora_kwargs)+ if "unsupported" in results[0]:+ assert all("torch 2.7+" in (r["unsupported"] or "") for r in results), results+ pytest.skip(+ "torch < 2.7: tensor parallel x FSDP2 is refused (no fully_shard(ignored_params))"+ )+ for rank, res in enumerate(results):+ assert set(res["grads"]) == set(res["ref_grads"]) and res["grads"]+ for name, ref in res["ref_grads"].items():+ torch.testing.assert_close(res["grads"][name], ref, rtol = 1e-4, atol = 1e-6, msg = name)+ assert not res["mismatched"], res["mismatched"][:4]+ assert res["losses"] == pytest.approx(res["ref_losses"], rel = 1e-5), (+ res["losses"],+ res["ref_losses"],+ )+ assert res["norms"] == pytest.approx(res["ref_norms"], rel = 1e-5), (+ res["norms"],+ res["ref_norms"],+ )+ # CPU vector_norm sums fp32 squares sequentially: about 3e-5 relative on the 2M-element lm_head copy.+ native_rel = 1e-4 if "modules_to_save" in (lora_kwargs or {}) else 1e-5+ assert res["native_norms"][0] == pytest.approx(res["ref_norms"][0], rel = native_rel)+ # FSDP2 shards the LoRA DTensors over dp on top of their tp placement.+ assert all(+ len(pl) == (1 if "lm_head" in n else 2) for n, pl in res["placements"].items()+ ), res["placements"]+ assert "the data parallel dimension" not in (res["refusals"]["no_mesh"] or "")+ assert "does not compose with Unsloth tensor parallelism" in (+ res["refusals"]["no_mesh"] or ""+ )+ assert "must be the data parallel dimension" in (res["refusals"]["tp_mesh"] or ""), res[+ "refusals"+ ]+ assert "shard_frozen = True" in (res["refusals"]["shard_frozen"] or ""), res["refusals"]+ saved_tp, saved_ref = results[0]["saved_tp"], results[0]["saved_ref"]+ assert set(saved_tp) == set(saved_ref)+ for key in saved_ref:+ torch.testing.assert_close(saved_tp[key], saved_ref[key], rtol = 1e-4, atol = 1e-5, msg = key)+++def test_tp_x_fsdp2_refuses_trainable_head_norms():+ for res in _spawn("tp_fsdp2_trainable_norms", 4):+ assert res["error"] and "trainable per-head norms" in res["error"], res+++def test_trainer_splits_mixed_optimizer_groups_for_tp_only():+ # modules_to_save lm_head: a plain trainable next to the LoRA DTensors (foreach / fused take one kind).+ kw = {"modules_to_save": ["lm_head"]}+ ref = _spawn("trainer", 1, dp = 1, tp = 1, lora_kwargs = kw)[0]+ if "skip" in ref:+ pytest.skip(f"import unsloth failed on this host: {ref['skip']}")+ for rank, res in enumerate(_spawn("trainer", 2, dp = 1, tp = 2, lora_kwargs = kw)):+ assert res["mixed_groups"] == 0, rank+ assert "already built the scheduler" in (res["refusals"]["prebuilt_scheduler"] or ""), res[+ "refusals"+ ]+ assert res["losses"] == pytest.approx(ref["losses"], rel = 1e-5), (+ rank,+ res["losses"],+ ref["losses"],+ )++[email protected]("dp,tp", [(1, 2), (2, 2)])+def test_trainer_trains_a_tensor_parallel_model_like_one_process(dp, tp):+ ref = _spawn("trainer", 1, dp = dp, tp = 1)[0]+ if "skip" in ref:+ pytest.skip(f"import unsloth failed on this host: {ref['skip']}")+ results = _spawn("trainer", dp * tp, dp = dp, tp = tp)+ if "torch < 2.7" in str(results[0]["refusals"].get("no_shard_model", "")):+ pytest.skip("torch < 2.7: tensor parallel x FSDP2 is refused")+ assert len(ref["losses"]) == 3+ for rank, res in enumerate(results):+ assert "DistributedDataParallel" not in res["wrapped"], res["wrapped"]+ assert res["losses"] == pytest.approx(ref["losses"], rel = 1e-5), (+ rank,+ res["losses"],+ ref["losses"],+ )+ assert res["grad_norms"] == pytest.approx(ref["grad_norms"], rel = 1e-5), (+ res["grad_norms"],+ ref["grad_norms"],+ )+ assert set(res["state"]) == set(ref["state"]) and ref["state"]+ for key, value in ref["state"].items():+ torch.testing.assert_close(res["state"][key], value, rtol = 1e-4, atol = 1e-6, msg = key)+ refusals = res["refusals"]+ assert "does not support Trainer checkpoints" in (refusals["checkpoints"] or ""), refusals+ assert "evaluation during training" in (refusals["eval"] or ""), refusals+ assert "optim = 'adamw_bnb_8bit'" in (refusals["optim_8bit"] or ""), refusals+ assert "Trainer.evaluate is not supported" in (refusals["evaluate"] or ""), refusals+ if dp > 1:+ assert "covers 2 of 4 ranks" in (refusals["no_shard_model"] or ""), refusals+ # The tp ranks of a replica read the same batches; dp replicas read different ones.+ for rank, res in enumerate(results):+ peer = results[rank ^ 1] # same dp replica (tp is the inner mesh dimension)+ assert res["seen"] == peer["seen"]+ if dp > 1:+ assert res["seen"] != results[(rank + tp) % (dp * tp)]["seen"]+ saved, saved_ref = results[0]["saved"], ref["saved"]+ assert set(saved) == set(saved_ref)+ for key in saved_ref:+ torch.testing.assert_close(saved[key], saved_ref[key], rtol = 1e-4, atol = 1e-6, msg = key)diff --git a/tests/test_tp_native_oracle.py b/tests/test_tp_native_oracle.pyindex 8ad9825aa67..865a0c453f0 100644--- a/tests/test_tp_native_oracle.py+++ b/tests/test_tp_native_oracle.py@@ -686,3 +686,54 @@ def test_stub_packages_keep_valid_specs():for name in ("unsloth", "unsloth.models"):assert sys.modules[name].__spec__ is not None, nameimportlib.util.find_spec("unsloth.models")+++def test_generated_trl_trainer_init_skips_for_inference_on_a_tp_model():+ """The generated TRL trainers end __init__ with model.for_inference(); a tensor parallel trainer+ (tp_native.tp_trainer_setup sets _unsloth_tensor_parallel) must skip it, every other trainer keeps it."""+ import re+ import textwrap++ source = open(os.path.join(REPO, "unsloth", "models", "rl.py")).read()+ match = re.search(+ r"super\(\)\.__init__\(\{RLTrainer_call_args\}\{RLTrainer_kwargs\}\)\n(.*?)\n\{RLTrainer_post\}",+ source,+ re.S,+ )+ assert match, "generated trainer __init__ tail not found"+ tail = textwrap.dedent(match.group(1))+ calls = []++ class Model:+ def for_inference(self):+ calls.append(type(self).__name__)++ for tensor_parallel in (False, True):+ trainer = types.SimpleNamespace(+ **({"_unsloth_tensor_parallel": True} if tensor_parallel else {})+ )+ exec(tail, {}, {"self": trainer, "model": Model()})+ assert calls == ["Model"], calls+++def test_trainer_dataloader_workers_are_seeded_by_dp_rank():+ import functools++ pytest.importorskip("accelerate")+ from accelerate import Accelerator+ from transformers.trainer_utils import seed_worker++ tp = _load_tp()+ tp._install_tp_accelerate_hooks()+ accelerator = Accelerator(cpu = True)+ accelerator.__dict__[tp._TP_DATA] = (1, 0) # dp 1: every tp rank is dp rank 0+ try:+ init_fn = functools.partial(seed_worker, num_workers = 2, rank = 3)+ loader = torch.utils.data.DataLoader(+ list(range(8)), batch_size = 2, num_workers = 2, worker_init_fn = init_fn+ )+ prepared = accelerator.prepare_data_loader(loader)+ finally:+ accelerator.__dict__.pop(tp._TP_DATA, None)+ assert prepared.worker_init_fn.func is seed_worker+ assert prepared.worker_init_fn.keywords == {"num_workers": 2, "rank": 0}diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex e65b410e141..46d449572ba 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -5698,7 +5698,10 @@ def patch_gradient_accumulation_fix(Trainer):install_fsdp2_policy_provenance()except Exception:pass- _refuse_tensor_parallel_for_trainer(model)+ # Unsloth tensor parallel model (apply_tensor_parallel): no DDP over the tp ranks, dataloader+ # sharded over dp only, tp-aware clipping (tp_native.tp_trainer_setup). Dict lookups otherwise.+ _refuse_pipeline_parallel_for_trainer(model)+ tensor_parallel = _tensor_parallel_trainer_pre(model)from ..fsdp2_launch import unsloth_fsdp2_native_requested# Env reads only; fsdp2_native (and torch.distributed.fsdp) is imported only under the flag.@@ -5724,6 +5727,9 @@ def patch_gradient_accumulation_fix(Trainer):_original_trainer_init(self, *args, **kwargs)if native_fsdp2:native_fsdp2_trainer_setup(self, phase = "post")+ if tensor_parallel:+ from .tp_native import tp_trainer_setup+ tp_trainer_setup(phase = "post", trainer = self)try:accelerator = getattr(self, "accelerator", None)if (@@ -5804,12 +5810,16 @@ def _is_unsloth_pipeline_parallel(model):def _refuse_tensor_parallel_for_trainer(model):+ """Trainer(model_init = ...): the model it returns is built after the Trainer set up its accelerator."""if _is_unsloth_tensor_parallel(model):raise RuntimeError(- "Unsloth: a tensor parallel model (apply_tensor_parallel) cannot be trained by the "- "Trainer yet: accelerate would wrap the tensor parallel ranks in DDP. Use a custom "- "training loop (unsloth/models/tp_native.py)."+ "Unsloth: a tensor parallel model (apply_tensor_parallel) returned by model_init cannot be "+ "trained by the Trainer; build it first and pass Trainer(model = model).")+ _refuse_pipeline_parallel_for_trainer(model)+++def _refuse_pipeline_parallel_for_trainer(model):if _is_unsloth_pipeline_parallel(model):raise RuntimeError("Unsloth: a pipeline parallel model (apply_pipeline_parallel) cannot be trained by the "@@ -5818,6 +5828,13 @@ def _refuse_tensor_parallel_for_trainer(model):)+def _tensor_parallel_trainer_pre(model):+ if not _is_unsloth_tensor_parallel(model):+ return False+ from .tp_native import tp_trainer_setup+ return tp_trainer_setup(model, phase = "pre")++def _refuse_tensor_parallel_for_inference(model):if _is_unsloth_tensor_parallel(model):raise RuntimeError(diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex d988e394049..9eda3e1af7a 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -1323,6 +1323,18 @@ def _content_fingerprint(p):return out+def _is_strided_shard(placement):+ return any(c.__name__ in ("_StridedShard", "StridedShard") for c in type(placement).__mro__)+++def _tp_local_view(p):+ """The local tensor of an Unsloth tensor parallel DTensor parameter; anything else unchanged."""+ to_local = getattr(p, "to_local", None)+ if to_local is not None and getattr(p, "device_mesh", None) is not None:+ return to_local()+ return p++def _sync_trainable_from_first_rank(model,dist,@@ -1344,6 +1356,9 @@ def _sync_trainable_from_first_rank(return 0from .fsdp2_save import mesh_all_reduce+ # Unsloth tensor parallel DTensors: the ranks of this (data parallel) mesh hold the same tp slice,+ # so their local tensors are compared and broadcast.+ params = [_tp_local_view(p) for p in params]with torch.no_grad():local = torch.stack([_content_fingerprint(p).to(device) for p in params])first = local.clone()@@ -1424,7 +1439,20 @@ def shard_model(model, config: Optional[FSDP2Config] = None):if config.units is not None:# Sharing is checked once the replicated set is known (ignored and, if replicated, frozen params).check_shard_units(model, list(config.units), ignored_params = None)- _refuse_tensor_parallel_model(model)+ if _refuse_tensor_parallel_model(model, config.mesh, compose = True):+ # Unsloth tensor parallel x FSDP2 data parallel: the frozen weights are this rank's tp slices,+ # replicated over the data parallel mesh; FSDP2 shards only the trainable (LoRA) DTensors over it.+ if config.shard_frozen or config.cpu_offload:+ raise RuntimeError(+ "Unsloth: native FSDP2 over a tensor parallel model keeps the frozen tp shards replicated "+ "over the data parallel mesh; shard_frozen = True and cpu_offload are not supported there."+ )+ if not _supports_ignored_params(fully_shard):+ raise RuntimeError(+ "Unsloth: tensor parallel x native FSDP2 data parallel keeps the frozen tp shards out of FSDP2 "+ f"(fully_shard(ignored_params), torch 2.7+); this is torch {torch.__version__}."+ )+ config = dataclasses.replace(config, shard_frozen = False)device = _shard_device(model, config.device)dist = _ensure_process_group(device, config.backend, config.timeout)if device.type == "cuda":@@ -1655,7 +1683,11 @@ def native_clip_grad_norm_(local = getattr(g, "_local_tensor", None)if local is None:local = g.to_local()- dims = tuple(i for i, pl in enumerate(g.placements) if pl.is_shard())+ # FSDP2 over a tensor parallel DTensor shards it as (_)StridedShard, which newer torch does not+ # report as is_shard().+ dims = tuple(+ i for i, pl in enumerate(g.placements) if pl.is_shard() or _is_strided_shard(pl)+ )groups.setdefault((g.device_mesh, dims), []).append(local)sharded.append(local)device = device or local.device@@ -3508,12 +3540,18 @@ def _expert_parallel_requested(model):return False-def _refuse_tensor_parallel_model(model):+def _refuse_tensor_parallel_model(+ model,+ mesh = None,+ compose = False,+):"""A model loaded with tp_plan or expert parallelism already holds DTensor / per-rank expertparameters on its own mesh, and the Trainer would build a ParallelismConfig from its tp_size.- Native FSDP2 cannot shard it again."""+ Native FSDP2 cannot shard it again. An Unsloth tensor parallel model (apply_tensor_parallel) composes+ with shard_model over the data parallel dimension of the same 2-D (dp, tp) mesh (compose = True and+ mesh = that dp mesh): returns True then."""if not isinstance(model, nn.Module) or getattr(model, _NATIVE_FLAG, False):- return+ return Falsetp_size = getattr(model, "tp_size", None)try:tp_size = int(tp_size) if tp_size is not None else None@@ -3538,10 +3576,15 @@ def _refuse_tensor_parallel_model(model):m.__dict__.get("_unsloth_tp") or m.__dict__.get("_unsloth_tp_style")for m in model.modules()):+ if compose and mesh is not None:+ from .tp_native import check_tp_dp_composition+ check_tp_dp_composition(model, mesh)+ return Trueraise RuntimeError("Unsloth: native FSDP2 does not compose with Unsloth tensor parallelism "- "(apply_tensor_parallel) yet; train a tensor parallel model with a custom loop over the tp "- "ranks only (data parallel size 1)."+ "(apply_tensor_parallel) here; for data parallel x tensor parallel call "+ "shard_model(model, FSDP2Config(mesh = mesh['dp'])) on a model sharded with "+ "apply_tensor_parallel(model, mesh['tp']) over the same 2-D (dp, tp) mesh.")if any(m.__dict__.get("_unsloth_pp") for m in model.modules()):raise RuntimeError(diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex bc11ba3fd44..ad24bf68c9c 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -666,7 +666,9 @@ class Unsloth{RLTrainer_name}(_Unsloth{RLTrainer_name}):except Exception:passsuper().__init__({RLTrainer_call_args}{RLTrainer_kwargs})- if "model" in locals() and hasattr(model, "for_inference"):+ # A tensor parallel model (tp_native.tp_trainer_setup) stays on its training path: for_inference would+ # route the decoder layers onto decode paths outside the tensor parallel regions.+ if "model" in locals() and hasattr(model, "for_inference") and not getattr(self, "_unsloth_tensor_parallel", False):model.for_inference(){RLTrainer_post}passdiff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex d5bad8c1c3b..fa015ecab60 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -16,12 +16,35 @@ Custom loop (torchrun --nproc_per_node tp):tp_clip_grad_norm_(params, 1.0)optimizer.step(); optimizer.zero_grad()save_tp_adapter(model, "out") # collective: the standard 1-GPU PEFT adapter, written by rank 0++Sharded loading (16-bit safetensors checkpoints): each rank reads only its slices of the attention / MLP+projections, so the load-time peak per rank is the replicated parts plus 1 / tp of the rest:++ model, tokenizer = load_tensor_parallel("unsloth/Qwen3-8B", mesh["tp"], dtype = torch.float16)+ # = with sharded_loading(mesh["tp"]): FastLanguageModel.from_pretrained(..., load_in_4bit = False)+ model = FastLanguageModel.get_peft_model(model, ...) # full-size LoRA, same init as 1 GPU+ apply_tensor_parallel(model, mesh["tp"]) # required before the first forward++Data parallel x tensor parallel (native FSDP2 over the dp dimension, torch 2.7+): every tp rank of a dp replica+reads the same batch, dp replicas read different ones:++ mesh = init_device_mesh("cuda", (dp, tp), mesh_dim_names = ("dp", "tp"))+ apply_tensor_parallel(model, mesh["tp"])+ shard_model(model, FSDP2Config(mesh = mesh["dp"])) # frozen tp shards replicated over dp, LoRA sharded+ ... tp_clip_grad_norm_(params, 1.0) (or native_clip_grad_norm_); save_tp_adapter(model, "out")++The HF / TRL Trainer trains a tensor parallel model (tp only, or dp x tp after shard_model above): no DDP over+the tp ranks, batches sharded over dp only, tp-aware clipping and float16 scaler. save_strategy = "no" (no+Trainer checkpoints / resume), no evaluation, torch optimizers (no bitsandbytes 8-bit); trainer.save_model()+writes the 1-GPU adapter."""from __future__ import annotations+import contextlibimport copyimport dataclasses+import functoolsimport inspectimport reimport types@@ -35,11 +58,15 @@ __all__ = ["TPConfig","TPPlan","apply_tensor_parallel",+ "check_tp_dp_composition","derive_tp_plan","is_tensor_parallel",+ "load_tensor_parallel",+ "sharded_loading","shard_slice","tp_clip_grad_norm_","tp_full_state_dict",+ "tp_trainer_setup","save_tp_adapter",]@@ -477,6 +504,9 @@ def _region(path, module, kind, compiled, text, tp):def _logical_shape(weight, base):+ full = getattr(weight, "_unsloth_tp_full_shape", None) # a sharded_loading slice+ if full is not None:+ return tuple(full)state = getattr(weight, "quant_state", None)if state is not None and getattr(state, "shape", None) is not None:return tuple(state.shape)@@ -646,7 +676,11 @@ def _refuse_base(path, proj_module, weight, base):f"Unsloth: tensor parallelism v1 does not support QAT fake quantization ({path}: "f"{type(module).__name__}).")- if not _is_params4bit(weight) and type(weight) not in (nn.Parameter, torch.Tensor):+ if (+ not _is_params4bit(weight)+ and _preloaded(weight) is None+ and type(weight) not in (nn.Parameter, torch.Tensor)+ ):raise ValueError(f"Unsloth: tensor parallelism v1 cannot shard '{path}' weights of type {type(weight).__name__}.")@@ -745,6 +779,7 @@ def _set_dtensor(param = _as_param(dt, full)if placement == "shard" and len(parts) > 1:param._unsloth_tp_parts = (shard_dim, tuple(parts))+ _tag_layout(module, name, shard_dim, parts, tp)module._parameters[name] = paramif param.requires_grad and placement != "shard":param.register_hook(_replicate_grad)@@ -1035,7 +1070,8 @@ def _sync_trainable(model, group, src):import torch.distributed as distwith torch.no_grad():for param in model.parameters():- if param.requires_grad:+ # sharded_loading slices differ per rank (read from the same checkpoint)+ if param.requires_grad and _preloaded(param) is None:dist.broadcast(param.data, src = src, group = group)@@ -1100,12 +1136,15 @@ def apply_tensor_parallel("(apply_pipeline_parallel) in v1.")tp_plan = derive_tp_plan(model, tp, plan)+ covered = set()for region in tp_plan.regions:for proj in region.projs:path = f"{region.path}.{proj.name}"weight, base = _weight(proj.module)_refuse_base(path, proj.module, weight, base)_refuse_adapter(path, proj.module)+ _check_preloaded(path, proj, weight, base, tp_mesh)+ covered.update((id(weight), id(base.bias)))if _is_params4bit(weight):_check_params4bit(path, weight, proj.style, tp)for name, norm in region.norms:@@ -1114,6 +1153,16 @@ def apply_tensor_parallel(raise ValueError(f"Unsloth: cannot replicate {region.path}.{name} ({type(p).__name__}).")+ stray = [+ n for n, p in model.named_parameters() if _preloaded(p) is not None and id(p) not in covered+ ]+ if stray:+ raise ValueError(+ f"Unsloth: {stray[:3]} were sharded by sharded_loading but are not in this tensor parallel plan; "+ "pass the same plan to sharded_loading and apply_tensor_parallel."+ )+ if tp > 1 and covered and any(_preloaded(p) is not None for p in model.parameters()):+ _refuse_weight_dependent_lora_init(model)chain = _tp_chain(model)if config.sync_trainable and tp > 1:import torch.distributed as dist@@ -1170,7 +1219,9 @@ def _shard_projection(region, proj, mesh, rank, tp):col = proj.style == COLWISEparts = proj.partsin_parts = (_logical_shape(weight, base)[1],)- if _is_params4bit(weight):+ if _preloaded(weight) is not None:+ _wrap_preloaded(base, "weight", weight, mesh, 0 if col else 1)+ elif _is_params4bit(weight):_shard_params4bit(f"{region.path}.{proj.name}", base, weight, proj.style, parts, rank, tp)else:_set_dtensor(@@ -1186,9 +1237,16 @@ def _shard_projection(region, proj, mesh, rank, tp):)if base.bias is not None:if col:- _set_dtensor(base, "bias", base.bias, mesh, "shard", parts, 0, rank, tp)+ if _preloaded(base.bias) is not None:+ _wrap_preloaded(base, "bias", base.bias, mesh, 0)+ else:+ _set_dtensor(base, "bias", base.bias, mesh, "shard", parts, 0, rank, tp)else:+ # sharded_loading keeps row biases as plain full tensors: replicated here as in v1_set_dtensor(base, "bias", base.bias, mesh, "replicate")+ guard = base.__dict__.pop("_unsloth_tp_load_guard", None)+ if guard is not None:+ guard.remove()lora_A = module._modules.get("lora_A")if lora_A is not None:for adapter in lora_A.keys():@@ -1206,6 +1264,58 @@ def _shard_projection(region, proj, mesh, rank, tp):module.forward = types.MethodType(_tp_projection_forward, module)+def check_tp_dp_composition(model, dp_mesh):+ """shard_model(model, FSDP2Config(mesh = dp_mesh)) on a model sharded by apply_tensor_parallel: valid when+ dp_mesh and the tp mesh are the two dimensions of one (dp, tp) mesh covering the world. Marks the model."""+ import torch.distributed as dist++ chain = _tp_chain(model)+ tp_mesh = next(+ (m.__dict__["_unsloth_tp_mesh"] for m in chain if "_unsloth_tp_mesh" in m.__dict__), None+ )+ if tp_mesh is None:+ raise ValueError(+ "Unsloth: native FSDP2 over a tensor parallel model needs the outermost model (the one "+ "apply_tensor_parallel was given, or a wrapper of it)."+ )+ if dp_mesh.ndim != 1:+ raise ValueError(+ "Unsloth: native FSDP2 over a tensor parallel model takes a 1-D dp mesh (mesh['dp'])."+ )+ dp_ranks, tp_ranks = set(dp_mesh.mesh.tolist()), set(tp_mesh.mesh.tolist())+ me = dist.get_rank()+ if dp_ranks & tp_ranks != {me} or dp_mesh.size() * tp_mesh.size() != dist.get_world_size():+ raise ValueError(+ f"Unsloth: native FSDP2's mesh (ranks {sorted(dp_ranks)}) must be the data parallel dimension of the "+ f"(dp, tp) mesh whose tp dimension (ranks {sorted(tp_ranks)}) apply_tensor_parallel used, covering "+ f"all {dist.get_world_size()} ranks: pass FSDP2Config(mesh = mesh['dp'])."+ )+ try:+ from torch.distributed.device_mesh import _mesh_resources+ same_root = _mesh_resources.get_root_mesh(dp_mesh) is _mesh_resources.get_root_mesh(tp_mesh)+ except Exception:+ same_root = True+ if not same_root:+ raise ValueError(+ "Unsloth: the dp and tp meshes must come from one init_device_mesh(..., (dp, tp), mesh_dim_names = "+ "('dp', 'tp')) (FSDP2 shards the tp DTensors over its dp dimension)."+ )+ plan = next(+ (m.__dict__["_unsloth_tp_plan"] for m in chain if "_unsloth_tp_plan" in m.__dict__), None+ )+ for region in plan.regions if plan is not None else ():+ for name, norm in region.norms:+ if any(p.requires_grad for p in norm.parameters()):+ # Their tp sum is a hook on the Parameter, and FSDP2 replaces the Parameter objects.+ raise ValueError(+ f"Unsloth: trainable per-head norms ({region.path}.{name}) are not supported with tensor "+ "parallel x FSDP2 data parallel; keep them frozen."+ )+ for level in chain:+ level.__dict__["_unsloth_tp_dp_mesh"] = dp_mesh+ return tp_mesh++def tp_clip_grad_norm_(parameters,max_norm,@@ -1220,6 +1330,8 @@ def tp_clip_grad_norm_(params = [p for p in parameters if p.grad is not None]if not params:return torch.tensor(0.0)+ if any(_is_dtensor(p.grad) and p.grad.device_mesh.ndim > 1 for p in params):+ return _clip_over_world(params, max_norm, eps)sharded = replicated = Nonegroup = mesh.get_group() if mesh is not None else Nonefor p in params:@@ -1255,14 +1367,59 @@ def tp_clip_grad_norm_(return total-def _full(tensor, param = None):+def _clip_over_world(params, max_norm, eps):+ """tp_clip_grad_norm_ for gradients on a 2-D (dp, tp) mesh (shard_model over the dp mesh): every+ element's square is counted once, divided by the number of ranks holding a replica of it."""+ import math++ import torch.distributed as dist++ total = None+ world = dist.get_world_size()+ for p in params:+ g = _replicate_grad(p.grad)+ if g is not p.grad:+ p.grad = g+ if _is_dtensor(g):+ mesh = g.device_mesh+ if world % mesh.size():+ raise ValueError(+ f"Unsloth: tp_clip_grad_norm_ got a gradient on {mesh.size()} of {world} ranks."+ )+ # Replicate dims hold copies; Shard and FSDP2's _StridedShard (not is_shard() on newer torch) split.+ # A gradient on the dp mesh only (a parameter outside the tp regions, e.g. modules_to_save) is the+ # same on every tp rank: world / mesh.size() more copies.+ copies = math.prod(+ mesh.size(i) for i, pl in enumerate(g.placements) if pl.is_replicate()+ ) * (world // mesh.size())+ sq = g.to_local().float().square().sum() / copies+ else:+ sq = g.float().square().sum() / world # the same on every rank+ total = sq if total is None else total + sq+ dist.all_reduce(total)+ total = total.sqrt()+ coef = float(max_norm) / (float(total) + eps)+ if coef < 1:+ for p in params:+ p.grad.mul_(coef)+ return total+++def _full(+ tensor,+ param = None,+ layout = None,+):+ """The whole tensor (collective over its mesh), fused / packed parts back in their original order."""if not _is_dtensor(tensor):return tensorfull = tensor.full_tensor()- layout = getattr(param, "_unsloth_tp_parts", None) if param is not None else None+ if layout is None and param is not None:+ layout = getattr(param, "_unsloth_tp_parts", None)+ layout = None if layout is None else (*layout, tensor.device_mesh.size())if layout is not None:- dim, parts = layout- full = _unpermute(full, dim, parts, tensor.device_mesh.size())+ dim, parts, tp = layout+ full = _unpermute(full, dim, parts, tp)return full@@ -1277,6 +1434,7 @@ def tp_full_state_dict(model, adapters_only = False):if weight is not None:embeddings.add(id(weight))out = {}+ layouts = _param_layouts(model)with torch.no_grad():for key, value in state.items():if (@@ -1286,7 +1444,7 @@ def tp_full_state_dict(model, adapters_only = False):and id(value) not in embeddings):continue- out[key] = _full(value, value).detach()+ out[key] = _full(value, value, layouts.get(id(value))).detach()return out@@ -1314,11 +1472,12 @@ def _peft_state_dict(model, **kwargs):"save_tp_adapter cannot gather them.")state = {}+ layouts = _param_layouts(model)with torch.no_grad():for key, value in raw.items():if _is_dtensor(value):if id(value) in wanted:- state[key] = _full(value, value).detach()+ state[key] = _full(value, value, layouts.get(id(value))).detach()else:state[key] = value.detach()return state@@ -1328,10 +1487,15 @@ def save_tp_adapter(model, save_directory, **kwargs):"""Write the standard 1-GPU PEFT adapter. Collective (tp mesh = whole world in v1); rank 0 writes."""import torch.distributed as dist- mesh = None+ mesh = dp_mesh = Nonefor level in _tp_chain(model):mesh = mesh or level.__dict__.get("_unsloth_tp_mesh")- if dist.is_initialized() and mesh is not None and mesh.size() != dist.get_world_size():+ dp_mesh = dp_mesh or level.__dict__.get("_unsloth_tp_dp_mesh")+ # Under shard_model over the dp mesh every trainable DTensor spans the whole (dp, tp) world.+ ranks = (+ mesh.size() * (dp_mesh.size() if dp_mesh is not None else 1) if mesh is not None else None+ )+ if dist.is_initialized() and mesh is not None and ranks != dist.get_world_size():raise ValueError(f"Unsloth: save_tp_adapter writes on global rank 0 behind a world barrier, but the tensor parallel "f"mesh has {mesh.size()} of {dist.get_world_size()} ranks (data parallel > 1 is outside v1). "@@ -1344,3 +1508,694 @@ def save_tp_adapter(model, save_directory, **kwargs):model.save_pretrained(save_directory, state_dict = state, **kwargs)if dist.is_initialized():dist.barrier()+++# Sharded loading (v2): each rank reads only its slices of the sharded projections from the checkpoint, so the+# load-time peak is the replicated parts plus 1 / tp of the attention / MLP weights, never the whole model.++_PRELOADED = "_unsloth_tp_preloaded"+_UNSUPPORTED_LOAD_KWARGS = (+ "load_in_4bit",+ "load_in_8bit",+ "quantization_config",+ "tp_plan",+ "tp_size",+ "device_mesh",+ "distributed_config",+ "gguf_file",+ "variant",+ "from_tf",+ "from_flax",+)+++def _preloaded(t):+ return None if t is None else getattr(t, _PRELOADED, None)+++def _refuse_weight_dependent_lora_init(model):+ """PiSSA / OLoRA / CorDA / EVA / LoftQ build the factors (and residual) from the weight; on a sharded_loading+ slice that is this rank's slice only, so the factors come out shard-sized and differ per rank."""+ configs = {}+ for level in _tp_chain(model):+ configs.update(getattr(level, "peft_config", None) or {})+ bad = {+ name: cfg.init_lora_weights+ for name, cfg in configs.items()+ if getattr(cfg, "init_lora_weights", True) not in (True, False, "gaussian")+ }+ if bad:+ raise ValueError(+ f"Unsloth: init_lora_weights {bad} depends on the base weight, which sharded_loading holds only as "+ "this rank's slice; use init_lora_weights = True / 'gaussian', or load the full model (no "+ "sharded_loading) before get_peft_model and apply_tensor_parallel."+ )+++def _check_preloaded(path, proj, weight, base, mesh):+ """A pre-sharded projection must carry exactly the layout apply_tensor_parallel derives now."""+ want = (proj.style, tuple(proj.parts), mesh.size())+ for what, t in (("weight", weight), ("bias", base.bias)):+ layout = _preloaded(t)+ if layout is None:+ continue+ if tuple(layout) != want:+ raise ValueError(+ f"Unsloth: '{path}.{what}' was sharded by sharded_loading as {layout}, but the tensor parallel "+ f"plan now gives {want}; pass the same plan and tp mesh to both."+ )+ ranks = getattr(t, "_unsloth_tp_preload_ranks", None)+ if ranks != mesh.mesh.tolist():+ raise ValueError(+ f"Unsloth: '{path}.{what}' was sharded by sharded_loading over ranks {ranks}, not this tp "+ f"mesh {mesh.mesh.tolist()}."+ )+++def _wrap_preloaded(module, name, local, mesh, dim):+ """A sharded_loading slice -> the DTensor parameter v1 would have built from the full tensor."""+ DTensor, _, _, Shard = _dtensor_api()+ shape = torch.Size(local._unsloth_tp_full_shape)+ dt = DTensor.from_local(+ local.detach(),+ mesh,+ [Shard(dim)],+ run_check = False,+ shape = shape,+ stride = torch.empty(shape, device = "meta").stride(),+ )+ param = _as_param(dt, local)+ parts = getattr(local, "_unsloth_tp_parts", None)+ if parts is not None:+ param._unsloth_tp_parts = parts+ _tag_layout(module, name, parts[0], parts[1], mesh.size())+ module._parameters[name] = param+ return param+++def _tag_layout(module, name, dim, parts, tp):+ # On the module too: FSDP2 replaces the Parameter objects (and their attributes) when it shards them.+ module.__dict__.setdefault("_unsloth_tp_layouts", {})[name] = (dim, tuple(parts), tp)+++def _param_layouts(model):+ """{id(parameter): (dim, parts, tp)} for the permuted (fused / packed) tp parameters of `model`."""+ out = {}+ for module in model.modules():+ for name, layout in (module.__dict__.get("_unsloth_tp_layouts") or {}).items():+ param = module._parameters.get(name)+ if param is not None:+ out[id(param)] = layout+ return out+++def _refuse_unapplied_forward(module, args):+ raise RuntimeError(+ "Unsloth: this model was loaded with tensor parallel sharded loading (each rank holds slices of the "+ "attention / MLP weights); call apply_tensor_parallel(model, tp_mesh) after get_peft_model and "+ "before running it."+ )+++def _checkpoint_index(name, kwargs):+ """{tensor name: local safetensors path} of a checkpoint directory or Hub repo."""+ import json+ import os++ sub = kwargs.get("subfolder") or ""++ def keys_of(path):+ from safetensors import safe_open+ with safe_open(path, framework = "pt", device = "cpu") as f:+ return {key: path for key in f.keys()}++ if os.path.isdir(name):+ root = os.path.join(name, sub)+ index = os.path.join(root, "model.safetensors.index.json")+ if os.path.isfile(index):+ with open(index) as f:+ weight_map = json.load(f)["weight_map"]+ return {k: os.path.join(root, v) for k, v in weight_map.items()}+ single = os.path.join(root, "model.safetensors")+ if os.path.isfile(single):+ return keys_of(single)+ raise ValueError(+ f"Unsloth: tensor parallel sharded loading needs a safetensors checkpoint; none in {root}."+ )+ from huggingface_hub import hf_hub_download++ hub = dict(+ subfolder = sub or None,+ revision = kwargs.get("revision"),+ token = kwargs.get("token"),+ cache_dir = kwargs.get("cache_dir"),+ local_files_only = bool(kwargs.get("local_files_only", False)),+ )+ try:+ index = hf_hub_download(name, "model.safetensors.index.json", **hub)+ except Exception:+ index = None+ if index is None:+ return keys_of(hf_hub_download(name, "model.safetensors", **hub))+ with open(index) as f:+ weight_map = json.load(f)["weight_map"]+ paths = {v: hf_hub_download(name, v, **hub) for v in sorted(set(weight_map.values()))}+ return {k: paths[v] for k, v in weight_map.items()}+++class _SliceReader:+ """safetensors reads of whole tensors or of this rank's slices (only the slice's bytes are read)."""++ def __init__(self, index):+ self.index, self.handles = index, {}+ self.full_bytes = self.slice_bytes = 0++ def _open(self, key):+ path = self.index[key]+ if path not in self.handles:+ from safetensors import safe_open+ self.handles[path] = safe_open(path, framework = "pt", device = "cpu")+ return self.handles[path]++ def shape(self, key):+ return tuple(self._open(key).get_slice(key).get_shape())++ def full(self, key):+ t = self._open(key).get_tensor(key)+ self.full_bytes += t.numel() * t.element_size()+ return t++ def slice(self, key, dim, parts, rank, tp):+ view = self._open(key).get_slice(key)+ pieces, offset = [], 0+ for size in parts:+ step = size // tp+ start = offset + rank * step+ pieces.append(view[start : start + step] if dim == 0 else view[:, start : start + step])+ offset += size+ t = torch.cat(pieces, dim = dim) if len(pieces) > 1 else pieces[0]+ self.slice_bytes += t.numel() * t.element_size()+ return t+++def _checkpoint_key(names, model, index):+ prefix = getattr(_unwrap(model), "base_model_prefix", "") or ""+ for name in names:+ candidates = [name]+ if prefix and name.startswith(prefix + "."):+ candidates.append(name[len(prefix) + 1 :])+ elif prefix:+ candidates.append(f"{prefix}.{name}")+ for key in candidates:+ if key in index:+ return key+ return None+++def _buffer_skeleton(model):+ """The model rebuilt with meta parameters and real buffers (RoPE tables), as from_pretrained builds them."""+ from accelerate import init_empty_weights++ dtype = next((p.dtype for p in model.parameters() if p.is_floating_point()), torch.float32)+ previous = torch.get_default_dtype()+ with torch.random.fork_rng(devices = []), init_empty_weights(include_buffers = False):+ torch.set_default_dtype(dtype)+ try:+ return type(model)(copy.deepcopy(model.config))+ finally:+ torch.set_default_dtype(previous)+++def _materialize_sharded(model, name, kwargs, mesh, plan, device):+ """Fill a meta model from the checkpoint: replicated tensors whole, sharded projections as local slices."""+ tp, rank = mesh.size(), mesh.get_local_rank()+ tp_plan = derive_tp_plan(model, tp, plan)+ shards = {}+ for region in tp_plan.regions:+ for proj in region.projs:+ weight, base = _weight(proj.module)+ col = proj.style == COLWISE+ shards[id(weight)] = (proj, 0 if col else 1, proj.parts if col else (weight.shape[1],))+ if base.bias is not None and col:+ shards[id(base.bias)] = (proj, 0, proj.parts)+ index = _checkpoint_index(name, kwargs)+ reader = _SliceReader(index)+ slots = {}+ for module_name, module in model.named_modules(remove_duplicate = False):+ for pname, p in module._parameters.items():+ if p is not None:+ entry = slots.setdefault(id(p), (p, [], []))+ entry[1].append((module, pname))+ entry[2].append(f"{module_name}.{pname}" if module_name else pname)+ sharded_numel = full_numel = 0+ for pid, (old, where, names) in slots.items():+ key = _checkpoint_key(names, model, index)+ if key is None:+ raise ValueError(+ f"Unsloth: tensor parallel sharded loading found no checkpoint tensor for '{names[0]}'; load "+ "this model without sharded loading (full load, then apply_tensor_parallel)."+ )+ if reader.shape(key) != tuple(old.shape):+ raise ValueError(+ f"Unsloth: checkpoint tensor '{key}' has shape {reader.shape(key)}, the model expects "+ f"{tuple(old.shape)}."+ )+ shard = shards.get(pid)+ if shard is None:+ value = reader.full(key).to(device = device, dtype = old.dtype)+ new = nn.Parameter(value, requires_grad = old.requires_grad)+ full_numel += old.numel()+ else:+ proj, dim, parts = shard+ local = reader.slice(key, dim, parts, rank, tp).to(device = device, dtype = old.dtype)+ # A plain local tensor tagged with its full shape: nn.Linear keeps the full in / out features, so+ # get_peft_model builds full-size LoRA factors with the 1-GPU init (a DTensor would make PEFT size+ # them from the shard). apply_tensor_parallel wraps it into the DTensor.+ new = nn.Parameter(local.contiguous(), requires_grad = old.requires_grad)+ if len(parts) > 1:+ new._unsloth_tp_parts = (dim, tuple(parts))+ new._unsloth_tp_full_shape = tuple(old.shape)+ new._unsloth_tp_preload_ranks = mesh.mesh.tolist()+ setattr(new, _PRELOADED, (proj.style, tuple(proj.parts), tp))+ sharded_numel += old.numel()+ for module, pname in where:+ module._parameters[pname] = new+ skeleton = None+ for module_name, module in model.named_modules():+ for bname, buf in list(module._buffers.items()):+ if buf is None or not buf.is_meta:+ continue+ key = f"{module_name}.{bname}" if module_name else bname+ if bname not in module._non_persistent_buffers_set and key in index:+ value = reader.full(key)+ else:+ skeleton = skeleton if skeleton is not None else _buffer_skeleton(model)+ value = skeleton.get_buffer(key)+ if value.is_meta:+ raise ValueError(f"Unsloth: sharded loading cannot rebuild the buffer '{key}'.")+ module._buffers[bname] = value.to(device = device, dtype = buf.dtype)+ for region in tp_plan.regions:+ for proj in region.projs:+ base = _weight(proj.module)[1]+ base.__dict__["_unsloth_tp_load_guard"] = base.register_forward_pre_hook(+ _refuse_unapplied_forward+ )+ if isinstance(getattr(model, "hf_device_map", None), dict):+ model.hf_device_map = {"": device.index if device.type == "cuda" else device.type}+ stats = {+ "tp": tp,+ "rank": rank,+ "sharded_numel": sharded_numel,+ "replicated_numel": full_numel,+ "read_bytes_full": reader.full_bytes,+ "read_bytes_sliced": reader.slice_bytes,+ "regions": len(tp_plan.regions),+ "source": tp_plan.source,+ }+ model.__dict__["_unsloth_tp_load_stats"] = stats+ return stats+++def _load_device(device_map, mesh):+ if mesh.device_type != "cuda":+ return torch.device(mesh.device_type)+ if isinstance(device_map, dict) and len(device_map) == 1:+ (value,) = device_map.values()+ if isinstance(value, int) or (isinstance(value, str) and value.startswith("cuda")):+ return torch.device(value if isinstance(value, str) else f"cuda:{value}")+ if isinstance(device_map, (int, torch.device)) or (+ isinstance(device_map, str) and device_map.startswith("cuda")+ ):+ return torch.device(f"cuda:{device_map}" if isinstance(device_map, int) else device_map)+ return torch.device("cuda", torch.cuda.current_device())+++def _from_pretrained_sharded(original, cls, name, args, kwargs, state):+ if state["active"]:+ return original(cls, name, *args, **kwargs) # a nested load inside from_pretrained+ config = kwargs.get("config")+ for key in _UNSUPPORTED_LOAD_KWARGS:+ if kwargs.get(key) or (key == "quantization_config" and getattr(config, key, None)):+ raise ValueError(+ f"Unsloth: tensor parallel sharded loading supports 16-bit safetensors checkpoints only "+ f"(got {key}). Load 4-bit / 8-bit / quantized models in full and call apply_tensor_parallel, "+ "or pass load_in_4bit = False."+ )+ mesh = state["mesh"] if state["mesh"] is not None else _world_mesh()+ if mesh.ndim != 1:+ raise ValueError("Unsloth: sharded_loading takes a 1-D tp mesh (pass mesh['tp']).")+ device = _load_device(kwargs.get("device_map"), mesh)+ kwargs = dict(kwargs, device_map = "meta")+ state["active"] = True+ try:+ with torch.random.fork_rng(devices = []):+ model = original(cls, name, *args, **kwargs)+ finally:+ state["active"] = False+ text = _text_config(model)+ if getattr(text, "quantization_config", None) or getattr(+ model.config, "quantization_config", None+ ):+ raise ValueError(+ "Unsloth: tensor parallel sharded loading supports 16-bit checkpoints only; this checkpoint is "+ "pre-quantized. Load it in full and call apply_tensor_parallel."+ )+ _materialize_sharded(model, name, kwargs, mesh, state["plan"], device)+ state["models"].append(model)+ return model+++def _world_mesh():+ import torch.distributed as dist+ from torch.distributed.device_mesh import init_device_mesh++ if not dist.is_initialized():+ raise RuntimeError(+ "Unsloth: tensor parallel sharded loading needs an initialized process group (torchrun) or a tp_mesh."+ )+ device_type = "cuda" if torch.cuda.is_available() else "cpu"+ return init_device_mesh(device_type, (dist.get_world_size(),), mesh_dim_names = ("tp",))+++def sharded_loading(tp_mesh = None, plan = None):+ """Inside this context every `from_pretrained` of a transformers model (FastLanguageModel's included)+ builds the model on meta, then each rank reads from the safetensors checkpoint the replicated tensors+ whole and only its own slices of the attention / MLP projections (DTensors with the full logical shape,+ so get_peft_model sizes and seeds LoRA exactly as on one GPU). 16-bit checkpoints only.++ with sharded_loading(mesh["tp"]):+ model, tokenizer = FastLanguageModel.from_pretrained(name, load_in_4bit = False, ...)+ model = FastLanguageModel.get_peft_model(model, ...)+ apply_tensor_parallel(model, mesh["tp"]) # required before the first forward+ """+ from transformers import PreTrainedModel++ descriptor = PreTrainedModel.__dict__["from_pretrained"]+ original = descriptor.__func__+ state = {"mesh": tp_mesh, "plan": plan, "models": [], "active": False}++ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):+ return _from_pretrained_sharded(+ original, cls, pretrained_model_name_or_path, args, kwargs, state+ )++ PreTrainedModel.from_pretrained = classmethod(from_pretrained)+ try:+ yield state+ finally:+ PreTrainedModel.from_pretrained = descriptor+++def load_tensor_parallel(+ model_name,+ tp_mesh = None,+ loader = None,+ plan = None,+ **kwargs,+):+ """`loader(model_name, **kwargs)` under sharded_loading (default FastLanguageModel.from_pretrained, 16-bit).+ Returns what the loader returns; raises if no model went through the sharded path."""+ if loader is None:+ from unsloth import FastLanguageModel+ loader = FastLanguageModel.from_pretrained+ kwargs.setdefault("load_in_4bit", False)+ with sharded_loading(tp_mesh, plan) as state:+ out = loader(model_name, **kwargs)+ if not state["models"]:+ raise RuntimeError(+ "Unsloth: load_tensor_parallel's loader did not call transformers from_pretrained; nothing was "+ "loaded sharded."+ )+ return out+++# Trainer (v2): the HF / TRL Trainer trains a tensor parallel model. accelerate must not wrap the tp ranks in+# DDP, every tp rank of a dp replica must read the same batches (the dataloader is sharded over dp only), and+# gradients are clipped with tp_clip_grad_norm_. Data parallel comes from shard_model over mesh["dp"] (native+# FSDP2, which then wraps the model itself). The loss needs no change: the Trainer's token count gathered over+# the world counts each dp replica's tokens tp times and its loss scale multiplies by dp * tp, so per rank the+# loss is (sum over its tokens) * dp / (dp replicas' tokens), which FSDP2's mean over dp (or nothing, dp = 1)+# turns into the token mean over the dp replicas, as for DDP on dp GPUs.++_TP_DATA = "_unsloth_tp_data"+_UNSUPPORTED_OPTIMIZERS = (+ "8bit",+ "bnb",+ "paged",+ "lomo",+ "galore",+ "apollo",+ "torchao",+ "q_galore",+)+++def _tp_meshes(model):+ chain = _tp_chain(model)+ tp = next(+ (m.__dict__["_unsloth_tp_mesh"] for m in chain if "_unsloth_tp_mesh" in m.__dict__), None+ )+ dp = next(+ (m.__dict__["_unsloth_tp_dp_mesh"] for m in chain if "_unsloth_tp_dp_mesh" in m.__dict__),+ None,+ )+ return tp, dp+++def _strategy(value):+ value = getattr(value, "value", value)+ return str(value or "no").lower()+++def _refuse_tp_trainer_args(args):+ problems = []+ if getattr(args, "deepspeed", None):+ problems.append("DeepSpeed")+ if getattr(args, "fsdp", None) or getattr(args, "parallelism_config", None) is not None:+ problems.append(+ "accelerate FSDP / ParallelismConfig (use shard_model over mesh['dp'] for data parallel)"+ )+ if _strategy(getattr(args, "save_strategy", "no")) != "no":+ problems.append(+ "Trainer checkpoints (set save_strategy = 'no'; trainer.save_model() writes the 1-GPU adapter)"+ )+ if (+ _strategy(getattr(args, "eval_strategy", getattr(args, "evaluation_strategy", "no")))+ != "no"+ ):+ problems.append("evaluation during training (set eval_strategy = 'no')")+ for flag in ("load_best_model_at_end", "push_to_hub"):+ if getattr(args, flag, False):+ problems.append(flag)+ optim = str(getattr(getattr(args, "optim", ""), "value", getattr(args, "optim", ""))).lower()+ if any(key in optim for key in _UNSUPPORTED_OPTIMIZERS):+ problems.append(f"optim = '{optim}' (use 'adamw_torch')")+ config = getattr(args, "accelerator_config", None)+ if getattr(config, "dispatch_batches", None):+ problems.append("accelerator_config.dispatch_batches")+ if problems:+ raise RuntimeError(+ "Unsloth: the Trainer on a tensor parallel model does not support "+ + "; ".join(problems)+ + "."+ )+++def tp_trainer_setup(+ model = None,+ phase = "pre",+ trainer = None,+):+ """Called around Trainer.__init__ (models/_utils.py) for a tensor parallel model. Returns True if it is one."""+ import torch.distributed as dist++ if phase == "pre":+ if model is None or not is_tensor_parallel(model):+ return False+ tp_mesh, dp_mesh = _tp_meshes(model)+ if tp_mesh is None:+ raise RuntimeError(+ "Unsloth: pass the Trainer the outermost model (the one apply_tensor_parallel was given, or a "+ "wrapper of it)."+ )+ ranks = tp_mesh.size() * (dp_mesh.size() if dp_mesh is not None else 1)+ if dist.is_initialized() and ranks != dist.get_world_size():+ raise RuntimeError(+ f"Unsloth: the Trainer on a tensor parallel model needs every rank in the tp mesh, or in the (dp, "+ f"tp) mesh after shard_model(model, FSDP2Config(mesh = mesh['dp'])); the tp mesh covers "+ f"{ranks} of {dist.get_world_size()} ranks."+ )+ _install_tp_accelerate_hooks()+ return True+ model = trainer.model+ _refuse_tp_trainer_args(trainer.args)+ tp_mesh, dp_mesh = _tp_meshes(model)+ dp_size, dp_rank = (dp_mesh.size(), dp_mesh.get_local_rank()) if dp_mesh is not None else (1, 0)+ trainer.accelerator.__dict__[_TP_DATA] = (dp_size, dp_rank)+ trainer.__dict__["_unsloth_tensor_parallel"] = (+ True # the generated TRL trainers skip for_inference()+ )+ _tp_scaler(trainer, dp_size)+ trainer.__dict__["save_model"] = types.MethodType(_tp_trainer_save_model, trainer)+ for name in ("evaluate", "predict"):+ trainer.__dict__[name] = _refuse_tp_trainer_call(name)+ create_optimizer = trainer.create_optimizer++ def create_optimizer_tp(*args, **kwargs):+ # A trainable outside the tp regions (modules_to_save) is a plain tensor next to the LoRA DTensors:+ # foreach / fused kernels take one kind per group. Split before create_scheduler records the groups.+ optimizer = create_optimizer(*args, **kwargs)+ from .fsdp2_native import _inner_optimizer, _mixed_param_groups, _split_mixed_param_groups++ inner = _inner_optimizer(optimizer)+ if getattr(trainer, "lr_scheduler", None) is not None and _mixed_param_groups(inner):+ # A prebuilt scheduler keeps one base LR / lambda per original group: split groups would go unscheduled.+ raise ValueError(+ "Unsloth: this tensor parallel model mixes DTensor (tensor parallel) and plain trainable parameters "+ "in one optimizer group, which foreach / fused optimizers cannot step, and Trainer(optimizers = "+ "(optimizer, scheduler)) already built the scheduler over those groups. Build the optimizer over "+ "`unsloth.models.fsdp2_native.split_param_groups(...)` before the scheduler, or pass only the optimizer."+ )+ _split_mixed_param_groups(inner)+ return optimizer++ trainer.__dict__["create_optimizer"] = create_optimizer_tp+ train = trainer.train++ def train_tp(*args, **kwargs):+ resume = kwargs.get("resume_from_checkpoint", args[0] if args else None)+ if resume:+ raise RuntimeError(+ "Unsloth: resuming a tensor parallel model from a Trainer checkpoint is not supported."+ )+ return train(*args, **kwargs)++ trainer.__dict__["train"] = train_tp+ return True+++def _refuse_tp_trainer_call(name):+ def refuse(*args, **kwargs):+ raise RuntimeError(+ f"Unsloth: Trainer.{name} is not supported on a tensor parallel model (its gather would count every "+ "tp rank); run the forward in your own loop, or save the adapter and evaluate on one GPU."+ )++ return refuse+++def _tp_trainer_save_model(+ self,+ output_dir = None,+ _internal_call = False,+):+ """Trainer.save_model for a tensor parallel model: the 1-GPU PEFT adapter (collective, rank 0 writes)."""+ output_dir = output_dir if output_dir is not None else self.args.output_dir+ save_tp_adapter(self.model, output_dir)+ processing = getattr(self, "processing_class", None) or getattr(self, "tokenizer", None)+ if processing is not None and self.args.should_save:+ processing.save_pretrained(output_dir)+++def _tp_scaler(trainer, dp):+ """float16: one GradScaler inf decision for all ranks (each tp rank sees other gradient shards)."""+ from .fsdp2_native import _scaler_for_native++ accelerator = trainer.accelerator+ if not _scaler_for_native(trainer):+ return+ handler = getattr(accelerator, "scaler_handler", None)+ user = handler.to_kwargs() if handler is not None and hasattr(handler, "to_kwargs") else {}+ if "init_scale" not in user:+ # The loss scale grows with dp (the Trainer's token-count scaling), never with tp.+ accelerator.scaler._init_scale = 2.0**16 / dp+++def _install_tp_accelerate_hooks():+ from accelerate import Accelerator++ if getattr(Accelerator, "_unsloth_tp_hooks", False):+ return+ original_prepare_model = Accelerator.prepare_model+ original_data_loader = Accelerator.prepare_data_loader+ original_clip = Accelerator.clip_grad_norm_++ def _tp_model(self, model):+ if self.__dict__.get(_TP_DATA) is None or not is_tensor_parallel(model):+ return False+ try:+ from .fsdp2_native import is_native_fsdp2+ except Exception:+ return True+ return not is_native_fsdp2(model) # native FSDP2 (dp > 1) prepares it itself++ def prepare_model(+ self,+ model,+ device_placement = None,+ evaluation_mode = False,+ ):+ if not _tp_model(self, model):+ return original_prepare_model(+ self, model, device_placement = device_placement, evaluation_mode = evaluation_mode+ )+ # No DDP over the tp ranks and no device move; evaluation_mode keeps only the autocast wrap.+ if getattr(model, "_is_accelerate_prepared", False):+ if model not in self._models:+ self._models.append(model)+ return model+ return original_prepare_model(self, model, device_placement = False, evaluation_mode = True)++ def prepare_data_loader(self, data_loader, *args, **kwargs):+ layout = self.__dict__.get(_TP_DATA)+ if layout is None:+ return original_data_loader(self, data_loader, *args, **kwargs)+ if isinstance(getattr(data_loader, "dataset", None), torch.utils.data.IterableDataset):+ raise RuntimeError(+ "Unsloth: the Trainer on a tensor parallel model needs a map-style dataset (accelerate "+ "dispatches iterable datasets over every rank)."+ )+ dp_size, dp_rank = layout+ # The Trainer seeds workers with partial(seed_worker, rank = process_index): tp peers must draw the+ # same random transforms / collation, so seed them by dp rank too.+ init_fn = getattr(data_loader, "worker_init_fn", None)+ if isinstance(init_fn, functools.partial) and "rank" in (init_fn.keywords or {}):+ data_loader.worker_init_fn = functools.partial(+ init_fn.func, *init_fn.args, **{**init_fn.keywords, "rank": dp_rank}+ )+ cls = type(self)+ # accelerate shards the batches by num_processes / process_index: give it the dp layout, so the tp+ # ranks of a replica read the same batches.+ self.__class__ = type(+ "UnslothTensorParallelDataAccelerator",+ (cls,),+ {+ "num_processes": property(lambda s: dp_size),+ "process_index": property(lambda s: dp_rank),+ },+ )+ try:+ return original_data_loader(self, data_loader, *args, **kwargs)+ finally:+ self.__class__ = cls++ def clip_grad_norm_(+ self,+ parameters,+ max_norm,+ norm_type = 2,+ ):+ if self.__dict__.get(_TP_DATA) is None:+ return original_clip(self, parameters, max_norm, norm_type = norm_type)+ if float(norm_type) != 2.0:+ raise RuntimeError(+ "Unsloth: tensor parallel gradient clipping supports the 2-norm only."+ )+ self.unscale_gradients()+ return tp_clip_grad_norm_(list(parameters), max_norm)++ Accelerator.prepare_model = prepare_model+ Accelerator.prepare_data_loader = prepare_data_loader+ Accelerator.clip_grad_norm_ = clip_grad_norm_+ Accelerator._unsloth_tp_hooks = True