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 parallel from UNSLOTH_TP_SIZE for unmodified training scripts, with Trainer checkpoints and 8-bit AdamW (#15326)
Daniel Han97a1732d47b6
diff --git a/tests/test_tp_env_gloo.py b/tests/test_tp_env_gloo.pynew file mode 100644index 00000000000..a517186ea88--- /dev/null+++ b/tests/test_tp_env_gloo.py@@ -0,0 +1,622 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""UNSLOTH_TP_SIZE (models/tp_env.py): tensor parallel from the environment, on a gloo CPU world, vs one process.++The workers set the torchrun environment and let tp_env create the process group and the mesh. The loader /+get_peft_model hooks wrap AutoModelForCausalLM / PEFT the way they wrap FastLanguageModel / FastModel."""++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 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+ _Rows,+ _free_port,+ _import_checkout_unsloth,+ _raised,+ _save_checkpoint,+ _trainer_args,+)++_ENV_KEYS = (+ "UNSLOTH_TP_SIZE",+ "UNSLOTH_PP_SIZE",+ "UNSLOTH_FSDP2",+ "UNSLOTH_FSDP2_BACKEND",+ "ACCELERATE_USE_FSDP",+)+++def _checkpoint(tmp):+ """A tiny random Llama saved as sharded safetensors (index + shards), like a Hub checkpoint."""+ return _save_checkpoint("llama", os.path.join(tmp, "ckpt"))+++def _patch_bnb_8bit_everywhere():+ # bitsandbytes keeps 32-bit state below min_8bit_size (4096) elements: every tiny LoRA factor would.+ # transformers builds optim = "adamw_8bit" as bitsandbytes.optim.AdamW(optim_bits = 8).+ import bitsandbytes as bnb+ for cls in (bnb.optim.AdamW, bnb.optim.AdamW8bit):+ init = cls.__init__++ def patched(+ self,+ *args,+ __init = init,+ **kwargs,+ ):+ kwargs["min_8bit_size"] = 0+ __init(self, *args, **kwargs)++ cls.__init__ = patched+++def _case_units(rank, world, tmp):+ """Layout parsing and refusals (no process group)."""+ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ from unsloth.models import tp_env++ out = {}++ def layout(**env):+ for key in _ENV_KEYS + ("WORLD_SIZE",):+ os.environ.pop(key, None)+ os.environ.update({k: str(v) for k, v in env.items()})+ tp_env._reset_env_layout()+ try:+ got = tp_env.env_layout()+ except Exception as e:+ return f"{type(e).__name__}: {e}"+ return None if got is None else (got.tp, got.dp, got.world, got.fsdp2)++ out["unset"] = layout(WORLD_SIZE = 4)+ out["one"] = layout(UNSLOTH_TP_SIZE = 1, WORLD_SIZE = 4)+ out["zero"] = layout(UNSLOTH_TP_SIZE = 0, WORLD_SIZE = 4)+ out["text"] = layout(UNSLOTH_TP_SIZE = "two", WORLD_SIZE = 4)+ out["no_divide"] = layout(UNSLOTH_TP_SIZE = 3, WORLD_SIZE = 4)+ out["no_torchrun"] = layout(UNSLOTH_TP_SIZE = 2)+ out["pp"] = layout(UNSLOTH_PP_SIZE = 2, WORLD_SIZE = 4)+ out["pp_with_tp"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 4)+ out["pp_one"] = layout(UNSLOTH_PP_SIZE = 1, UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 4)+ out["tp_world"] = layout(UNSLOTH_TP_SIZE = 4, WORLD_SIZE = 4)+ out["ddp"] = layout(UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 4)+ out["fsdp2"] = layout(UNSLOTH_TP_SIZE = 2, UNSLOTH_FSDP2 = 1, WORLD_SIZE = 4)+ out["accelerate_fsdp"] = layout(+ UNSLOTH_TP_SIZE = 2, UNSLOTH_FSDP2 = 1, UNSLOTH_FSDP2_BACKEND = "accelerate", WORLD_SIZE = 4+ )++ calls = []++ def loader(+ model_name,+ load_in_4bit = True,+ fast_inference = False,+ full_finetuning = False,+ **kw,+ ):+ calls.append(model_name)+ return "loaded"++ layout(UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 2)+ wrapped = tp_env.tensor_parallel_env_load(loader)+ out["refuse_vllm"] = _raised(lambda: wrapped("m", fast_inference = True))+ out["refuse_full_ft"] = _raised(lambda: wrapped("m", False, full_finetuning = True))+ out["refuse_8bit"] = _raised(lambda: wrapped("m", load_in_8bit = True))+ layout(UNSLOTH_TP_SIZE = 2, UNSLOTH_FSDP2 = 1, UNSLOTH_FSDP2_SHARDED_LOAD = 1, WORLD_SIZE = 2)+ out["refuse_fsdp2_sharded_load"] = _raised(lambda: wrapped("m", False))+ os.environ.pop("UNSLOTH_FSDP2_SHARDED_LOAD", None)+ out["refused_before_load"] = calls == []+ layout(WORLD_SIZE = 2)+ out["no_env_passthrough"] = wrapped("m", fast_inference = True)+ out["four_bit_default"] = tp_env._four_bit({}, loader)+ out["four_bit_16"] = tp_env._four_bit({"load_in_16bit": True}, loader)+ out["four_bit_qconfig"] = tp_env._four_bit(+ {"load_in_4bit": False, "quantization_config": {}}, loader+ )+ # The hooks sit on the real loaders.+ from unsloth import FastLanguageModel, FastModel, FastVisionModel++ out["hooked"] = {}+ for label, cls in (+ ("lm", FastLanguageModel),+ ("model", FastModel),+ ("vision", FastVisionModel),+ ):+ for attr in ("from_pretrained", "get_peft_model"):+ out["hooked"][f"{label}.{attr}"] = getattr(getattr(cls, attr), "_unsloth_tp_env", False)+ return out+++def _case_env(+ rank,+ world,+ tmp,+ ckpt,+ bs,+ optim = "adamw_torch",+ four_bit = False,+ resume = False,+ bnb_8bit = False,+ refusals = False,+):+ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ import torch.distributed as dist+ import transformers+ from peft import LoraConfig, get_peft_model+ from transformers import AutoModelForCausalLM++ from unsloth.models import tp_env, tp_native+ from unsloth.models._utils import patch_gradient_accumulation_fix++ patch_gradient_accumulation_fix(transformers.Trainer)+ if bnb_8bit:+ _patch_bnb_8bit_everywhere()+ layout = tp_env.env_layout()+ 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"].sum().item())+ return super().compute_loss(model, inputs, *args, **kwargs)++ def load(+ model_name,+ load_in_4bit = True,+ **kwargs,+ ): # FastLanguageModel.from_pretrained's flags+ return AutoModelForCausalLM.from_pretrained(+ model_name, torch_dtype = torch.float32, attn_implementation = "eager"+ )++ def peft(model):+ torch.manual_seed(1)+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False)+ return get_peft_model(model, config)++ load = tp_env.tensor_parallel_env_load(load)+ peft = tp_env.tensor_parallel_env_peft(peft)++ def fresh():+ model = load(ckpt, load_in_4bit = four_bit)+ sharded = "_unsloth_tp_load_stats" in model.__dict__+ return peft(model), sharded++ dp = layout.dp if layout is not None else 1+ steps = 4 if resume else 3+ g = torch.Generator().manual_seed(1)+ ids = torch.randint(0, 1000, (steps * 4 * max(dp, bs // 2), 9), generator = g)+ data = _Rows(list(ids))++ def run(out_dir, **overrides):+ model, sharded = fresh()+ args = _trainer_args(out_dir, bs, optim = optim, max_steps = steps, **overrides)+ trainer = SequentialTrainer(model = model, args = args, train_dataset = data)+ return trainer, sharded++ save = dict(save_strategy = "steps", save_steps = 2) if resume else {}+ out_a = os.path.join(tmp, "a")+ trainer, sharded = run(out_a, **save)+ trainer.train()++ def summary(trainer):+ logs = [h for h in trainer.state.log_history if "loss" in h]+ model = trainer.model+ is_tp = tp_native.is_tensor_parallel(model)+ state = (+ tp_native.tp_full_state_dict(model, adapters_only = True)+ if is_tp+ else {k: v.detach().clone() for k, v in model.state_dict().items() if "lora_" in k}+ )+ return {+ "steps": [h["step"] for h in logs],+ "losses": [h["loss"] for h in logs],+ "grad_norms": [h.get("grad_norm") for h in logs],+ "state": {k: v for k, v in state.items() if "lora_" in k},+ }++ from unsloth.models.fsdp2_bnb_optim import is_local_shard_bnb_optimizer+ from unsloth.models.fsdp2_native import _inner_optimizer, is_native_fsdp2++ res = {+ "a": summary(trainer),+ "sharded_load": sharded,+ "is_tp": tp_native.is_tensor_parallel(trainer.model),+ "native_fsdp2": is_native_fsdp2(trainer.model),+ "ddp_mesh": tp_native._ddp_mesh(trainer.model) is not None,+ "wrapped": type(trainer.model_wrapped).__name__,+ "optimizer": type(_inner_optimizer(trainer.optimizer)).__module__+ + "."+ + type(_inner_optimizer(trainer.optimizer)).__name__,+ "optim_bits": getattr(+ getattr(_inner_optimizer(trainer.optimizer), "args", None), "optim_bits", None+ ),+ "state_dtypes": sorted(+ {+ str(v.dtype)+ for st in _inner_optimizer(trainer.optimizer).state.values()+ for v in st.values()+ if torch.is_tensor(v) and v.ndim > 0+ }+ ),+ "local_shard_bnb": is_local_shard_bnb_optimizer(_inner_optimizer(trainer.optimizer)),+ "optim_arg": str(getattr(trainer.args.optim, "value", trainer.args.optim)),+ "seen": list(seen),+ "layout": None if layout is None else repr(layout),+ }+ if resume:+ ckpt2 = os.path.join(out_a, "checkpoint-2")+ res["ckpt_files"] = sorted(os.listdir(ckpt2)) + sorted(+ os.listdir(os.path.join(ckpt2, "unsloth_tp")) if layout is not None else []+ )+ trainer_b, _ = run(os.path.join(tmp, "b"), **save)+ trainer_b.train(resume_from_checkpoint = ckpt2)+ res["b"] = summary(trainer_b)+ if layout is not None:+ # A checkpoint written on another layout is refused before anything is loaded.+ bad = os.path.join(tmp, "bad")+ if rank == 0:+ import shutil+ shutil.copytree(ckpt2, bad)+ dist.barrier()+ path = os.path.join(bad, "unsloth_tp", f"rank{rank:05d}.pt")+ payload = torch.load(path, weights_only = True)+ payload["layout"]["tp"] = 99+ torch.save(payload, path)+ trainer_c, _ = run(os.path.join(tmp, "c"), **save)+ res["bad_layout"] = _raised(lambda: trainer_c.train(resume_from_checkpoint = bad))+ dist.barrier()+ if refusals:+ model = trainer.model++ class Stream(torch.utils.data.IterableDataset):+ def __iter__(self):+ return iter([data[i] for i in range(len(data))])++ res["iterable"] = _raised(+ lambda: SequentialTrainer(+ model = model, args = _trainer_args(os.path.join(tmp, "it"), bs), train_dataset = Stream()+ ).train()+ )+ res["eval"] = _raised(+ lambda: SequentialTrainer(+ model = model,+ args = _trainer_args(+ os.path.join(tmp, "ev"), bs, eval_strategy = "steps", eval_steps = 1+ ),+ train_dataset = data,+ eval_dataset = data,+ )+ )+ res["evaluate"] = _raised(lambda: trainer.evaluate(data))+ res["lion"] = _raised(+ lambda: SequentialTrainer(+ model = model,+ args = _trainer_args(os.path.join(tmp, "li"), bs, optim = "lion_8bit"),+ train_dataset = data,+ )+ )+ res["generate"] = _raised(lambda: model.generate(input_ids = ids[:1, :3]))+ if dist.is_initialized():+ dist.barrier()+ return res+++def _case_dp_average(rank, world, tmp):+ """DDP-style dp averaging: a gradient on one replica only is averaged with zeros (DDP's behaviour), one on+ none stays None, and both replicas end equal."""+ 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 unsloth.models import tp_native++ dist.init_process_group("gloo")+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("dp",))+ one, both, none, frozen = (torch.nn.Parameter(torch.zeros(3)) for _ in range(4))+ frozen.requires_grad_(False)+ one.grad = torch.full((3,), 4.0) if rank == 0 else None+ both.grad = torch.full((3,), float(rank + 1))+ tp_native._dp_average([one, both, none, frozen], mesh["dp"])+ return {+ "one": one.grad.tolist(),+ "both": both.grad.tolist(),+ "none": none.grad,+ "frozen": frozen.grad,+ }+++def _case_accelerate_fsdp(rank, world, tmp, ckpt):+ """UNSLOTH_FSDP2=1 that resolves to accelerate's FSDP: the dp dimension would be left unsynced."""+ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ import transformers+ from peft import LoraConfig, get_peft_model+ from transformers import AutoModelForCausalLM++ from unsloth.models import tp_env+ from unsloth.models._utils import patch_gradient_accumulation_fix++ patch_gradient_accumulation_fix(transformers.Trainer)+ model = tp_env.tensor_parallel_env_load(+ lambda name, load_in_4bit = True: AutoModelForCausalLM.from_pretrained(+ name, torch_dtype = torch.float32+ )+ )(ckpt, load_in_4bit = False)+ model = get_peft_model(model, LoraConfig(r = 4, target_modules = "all-linear"))+ data = _Rows([torch.arange(9)] * 8)+ return {+ "refused": _raised(+ lambda: transformers.Trainer(+ model = model, args = _trainer_args(tmp, 2), train_dataset = data+ )+ )+ }+++CASES = {+ "units": _case_units,+ "env": _case_env,+ "dp_average": _case_dp_average,+ "accelerate_fsdp": _case_accelerate_fsdp,+}+++def _worker(rank, world, port, case, tmp, env, 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),+ )+ for key in _ENV_KEYS:+ os.environ.pop(key, None)+ os.environ.update(env)+ torch.set_num_threads(2)+ import torch.distributed as dist++ try:+ res = CASES[case](rank, world, tmp, **kwargs)+ torch.save(res, os.path.join(tmp, f"result_{rank}.pt"))+ finally:+ if dist.is_initialized():+ dist.destroy_process_group()+++def _spawn(+ case,+ world = 1,+ env = None,+ **kwargs,+):+ ctx = multiprocessing.get_context("spawn")+ port = _free_port()+ with tempfile.TemporaryDirectory() as tmp:+ if case in ("env", "accelerate_fsdp"):+ kwargs["ckpt"] = _checkpoint(tmp)+ procs = [+ ctx.Process(target = _worker, args = (r, world, port, case, tmp, env or {}, 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]+ for p in procs:+ if p.is_alive():+ p.kill()+ 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+++def _close(+ got,+ want,+ rel = 1e-5,+ what = "",+):+ assert got["steps"] == want["steps"], (what, got["steps"], want["steps"])+ assert got["losses"] == pytest.approx(want["losses"], rel = rel), (+ what,+ got["losses"],+ want["losses"],+ )+ assert got["grad_norms"] == pytest.approx(want["grad_norms"], rel = rel), (+ what,+ got["grad_norms"],+ want["grad_norms"],+ )+ assert set(got["state"]) == set(want["state"]) and want["state"]+ for key, value in want["state"].items():+ torch.testing.assert_close(got["state"][key], value, rtol = rel * 10, atol = 1e-6, msg = key)+++def test_env_layout_parsing_and_refusals():+ (res,) = _spawn("units")+ assert res["unset"] is None and res["one"] is None+ assert "must be >= 1" in res["zero"] and "must be an integer" in res["text"]+ assert "must divide the number of ranks (WORLD_SIZE=4)" in res["no_divide"]+ assert (+ "WORLD_SIZE=1" in res["no_torchrun"] and "torchrun --nproc-per-node 2" in res["no_torchrun"]+ )+ for key in ("pp", "pp_with_tp"):+ assert "UNSLOTH_PP_SIZE=2" in res[key] and "Python API" in res[key], res[key]+ assert res["pp_one"] == (2, 2, 4, False)+ assert res["tp_world"] == (4, 1, 4, False)+ assert res["ddp"] == (2, 2, 4, False)+ assert res["fsdp2"] == (2, 2, 4, True)+ assert "native FSDP2 only" in res["accelerate_fsdp"]+ assert "vLLM" in res["refuse_vllm"] and "UNSLOTH_TP_SIZE=2" in res["refuse_vllm"]+ assert "full finetuning" in res["refuse_full_ft"]+ assert "8-bit weights" in res["refuse_8bit"]+ assert "UNSLOTH_FSDP2_SHARDED_LOAD=1" in (res["refuse_fsdp2_sharded_load"] or ""), res[+ "refuse_fsdp2_sharded_load"+ ]+ assert res["refused_before_load"] and res["no_env_passthrough"] == "loaded"+ assert res["four_bit_default"] and not res["four_bit_16"] and res["four_bit_qconfig"]+ assert all(res["hooked"].values()), res["hooked"]+++def _ref(bs, **kwargs):+ return _spawn("env", 1, bs = bs, **kwargs)[0]++[email protected]("four_bit", [False, True], ids = ["sharded_16bit", "full_load"])+def test_env_tp2_trainer_matches_one_process(four_bit):+ ref = _ref(2, four_bit = four_bit)+ assert ref["layout"] is None and not ref["is_tp"]+ results = _spawn("env", 2, {"UNSLOTH_TP_SIZE": "2"}, bs = 2, four_bit = four_bit, refusals = True)+ for rank, res in enumerate(results):+ assert res["layout"] == "tp 2" and res["is_tp"], res+ assert res["sharded_load"] is (not four_bit), res["sharded_load"]+ assert not res["native_fsdp2"] and not res["ddp_mesh"]+ assert "DistributedDataParallel" not in res["wrapped"]+ _close(res["a"], ref["a"], what = rank)+ hint = "UNSLOTH_TP_SIZE=2: unset it"+ assert "map-style dataset" in res["iterable"] and hint in res["iterable"], res["iterable"]+ 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 results[0]["seen"] == results[1]["seen"] # both tp ranks read the same batches+++def test_env_tp2_with_fsdp2_flag_and_no_dp_dimension():+ ref = _ref(2)+ for res in _spawn("env", 2, {"UNSLOTH_TP_SIZE": "2", "UNSLOTH_FSDP2": "1"}, bs = 2):+ assert res["layout"] == "tp 2" and res["is_tp"] and not res["native_fsdp2"], res+ _close(res["a"], ref["a"])++[email protected]("fsdp2", [True, False], ids = ["fsdp2_dp2", "ddp_dp2"])+def test_env_tp2_x_dp2_trainer_matches_one_process(fsdp2):+ ref = _ref(4)+ env = {"UNSLOTH_TP_SIZE": "2"}+ if fsdp2:+ env["UNSLOTH_FSDP2"] = "1"+ results = _spawn("env", 4, env, bs = 2)+ for rank, res in enumerate(results):+ assert res["layout"] == (+ "dp 2 (native FSDP2) x tp 2" if fsdp2 else "dp 2 (DDP) x tp 2"+ ), res+ assert res["is_tp"] and res["native_fsdp2"] is fsdp2 and res["ddp_mesh"] is (not fsdp2)+ assert "DistributedDataParallel" not in res["wrapped"]+ _close(res["a"], ref["a"], what = rank)+ for rank, res in enumerate(results):+ assert res["seen"] == results[rank ^ 1]["seen"] # tp peers: same rows+ assert res["seen"] != results[(rank + 2) % 4]["seen"] # dp replicas: different rows+++def _bnb_cpu():+ try:+ import bitsandbytes # noqa: F401+ except Exception:+ return False+ return True++[email protected](not _bnb_cpu(), reason = "bitsandbytes not installed")+ "world,env", [(2, {}), (4, {"UNSLOTH_FSDP2": "1"})], ids = ["tp2", "tp2_fsdp2_dp2"]+)+def test_env_tp_adamw_8bit_steps_local_shards(world, env):+ ref = _ref(2 * (world // 2), optim = "adamw_8bit", bnb_8bit = True)+ if not ref["optimizer"].startswith("bitsandbytes"):+ pytest.skip(f"bitsandbytes cannot step CPU tensors here ({ref['optimizer']})")+ assert ref["optim_bits"] == 8 and "torch.uint8" in ref["state_dtypes"], ref+ results = _spawn(+ "env", world, {"UNSLOTH_TP_SIZE": "2", **env}, bs = 2, optim = "adamw_8bit", bnb_8bit = True+ )+ for rank, res in enumerate(results):+ assert res["optim_arg"] == "adamw_8bit" and res["local_shard_bnb"], res["optimizer"]+ assert res["optim_bits"] == 8 and "torch.uint8" in res["state_dtypes"], res["state_dtypes"]+ # 8-bit state is quantized per 256-element block of each local shard (one GPU: of the whole+ # tensor), so the run matches one process within the 8-bit band, not bitwise.+ assert res["a"]["losses"] == pytest.approx(ref["a"]["losses"], rel = 2e-3), (+ rank,+ res["a"]["losses"],+ ref["a"]["losses"],+ )+ for key, value in ref["a"]["state"].items():+ torch.testing.assert_close(res["a"]["state"][key], value, rtol = 0.05, atol = 2e-3, msg = key)+++ "world,env,optim",+ [+ (2, {}, "adamw_torch"),+ (4, {"UNSLOTH_FSDP2": "1"}, "adamw_torch"),+ (4, {}, "adamw_torch"),+ (2, {}, "adamw_8bit"),+ ],+ ids = ["tp2", "tp2_fsdp2_dp2", "tp2_ddp_dp2", "tp2_adamw_8bit"],+)+def test_env_tp_checkpoint_resume_equals_uninterrupted(world, env, optim):+ if optim == "adamw_8bit" and not _bnb_cpu():+ pytest.skip("bitsandbytes not installed")+ results = _spawn(+ "env",+ world,+ {"UNSLOTH_TP_SIZE": "2", **env},+ bs = 2,+ optim = optim,+ resume = True,+ bnb_8bit = optim == "adamw_8bit",+ )+ for rank, res in enumerate(results):+ a, b = res["a"], dict(res["b"])+ # The resumed log history starts with steps 1-2 restored from trainer_state.json.+ assert a["steps"] == [1, 2, 3, 4] and b["steps"] == [1, 2, 3, 4], (a["steps"], b["steps"])+ b["losses"], b["grad_norms"] = b["losses"][2:], b["grad_norms"][2:]+ assert "adapter_model.safetensors" in res["ckpt_files"], res["ckpt_files"]+ assert f"rank{rank:05d}.pt" in res["ckpt_files"], res["ckpt_files"]+ # Bitwise: the same local shards, optimizer state, RNG and data position as the uninterrupted run.+ assert b["losses"] == a["losses"][2:], (rank, b["losses"], a["losses"])+ assert b["grad_norms"] == a["grad_norms"][2:], (rank, b["grad_norms"], a["grad_norms"])+ for key, value in a["state"].items():+ assert torch.equal(b["state"][key], value), key+ assert "written on another layout" in (res["bad_layout"] or ""), res["bad_layout"]+++def test_dp_average_matches_ddp_for_gradients_on_some_replicas():+ for res in _spawn("dp_average", 2):+ assert res["one"] == [2.0] * 3 and res["both"] == [1.5] * 3, res+ assert res["none"] is None and res["frozen"] is None, res+++def test_env_tp_x_accelerate_fsdp_is_refused():+ env = {"UNSLOTH_TP_SIZE": "2", "UNSLOTH_FSDP2": "1", "ACCELERATE_USE_FSDP": "true"}+ for res in _spawn("accelerate_fsdp", 4, env):+ assert "needs Unsloth's native FSDP2" in (res["refused"] or ""), resdiff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.pyindex d3b3ccc39b5..60197b9202c 100644--- a/tests/test_tp_native_gloo.py+++ b/tests/test_tp_native_gloo.py@@ -1001,12 +1001,9 @@ def test_tp2_entry_points_outside_the_regions_are_refused():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,- )+ # The Trainer takes a tensor parallel model with its default args (save_strategy "steps":+ # per-rank checkpoints).+ assert value is None, (applied, key, value)elif key.startswith("cached:"):assert value and "cached decoding" in value, (applied, key, value)@@ -1155,6 +1152,13 @@ def test_trainer_splits_mixed_optimizer_groups_for_tp_only():res["losses"],ref["losses"],)+ # transformers 5.x would clip mixed DTensor / plain gradients itself (_mixed_mesh_grad_norm). The+ # reference norm is torch's CPU fp32 vector_norm over the plain lm_head gradient: ~2e-4 off.+ assert res["grad_norms"] == pytest.approx(ref["grad_norms"], rel = 1e-3), (+ rank,+ res["grad_norms"],+ ref["grad_norms"],+ )@pytest.mark.parametrize("dp,tp", [(1, 2), (2, 2)])@@ -1181,9 +1185,10 @@ def test_trainer_trains_a_tensor_parallel_model_like_one_process(dp, tp):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+ # Checkpoints are per rank, bitsandbytes AdamW steps local shards (or switches to torch's AdamW).+ assert refusals["checkpoints"] is None, refusalsassert "evaluation during training" in (refusals["eval"] or ""), refusals- assert "optim = 'adamw_bnb_8bit'" in (refusals["optim_8bit"] or ""), refusals+ assert refusals["optim_8bit"] is None, refusalsassert "Trainer.evaluate is not supported" in (refusals["evaluate"] or ""), refusalsif dp > 1:assert "covers 2 of 4 ranks" in (refusals["no_shard_model"] or ""), refusalsdiff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 381601b51c3..43919e3879d 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -6021,7 +6021,8 @@ def patch_gradient_accumulation_fix(Trainer):# 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)+ # UNSLOTH_TP_SIZE (unmodified scripts): tensor parallel before native FSDP2 shards the dp dimension.+ tp_env = _tensor_parallel_env_trainer_pre(model)from .. import fsdp2_launch as _fsdp2_launch# Env reads only; fsdp2_native (and torch.distributed.fsdp) is imported only under the flag.@@ -6035,6 +6036,18 @@ def patch_gradient_accumulation_fix(Trainer):"args"])+ if native_fsdp2 and tp_env is not None and tp_env.dp == 1:+ native_fsdp2 = (+ False # UNSLOTH_TP_SIZE = world size: no data parallel dimension to shard+ )+ if tp_env is not None and tp_env.dp > 1 and tp_env.fsdp2 and not native_fsdp2:+ # The dp dimension would be neither FSDP2-sharded nor gradient-averaged: replicas would drift.+ raise RuntimeError(+ f"Unsloth: UNSLOTH_TP_SIZE={tp_env.tp} with UNSLOTH_FSDP2=1 needs Unsloth's native FSDP2 for "+ f"the data parallel dimension (dp {tp_env.dp}), but this launch selects accelerate's FSDP "+ "(ACCELERATE_USE_FSDP / an accelerate FSDP config, or a non-CUDA install). Launch with "+ "torchrun and UNSLOTH_FSDP2_BACKEND unset, or unset UNSLOTH_FSDP2 for DDP-style data parallel."+ )if native_fsdp2:from .fsdp2_native import (native_fsdp2_trainer_init_arguments,@@ -6066,6 +6079,8 @@ def patch_gradient_accumulation_fix(Trainer):)except Exception:pass+ # After native FSDP2's shard over mesh['dp']: the tp Trainer setup checks the (dp, tp) world.+ tensor_parallel = _tensor_parallel_trainer_pre(model)_original_trainer_init(self, *args, **kwargs)if native_fsdp2:native_fsdp2_trainer_setup(self, phase = "post")@@ -6170,6 +6185,13 @@ def _refuse_pipeline_parallel_for_trainer(model):)+def _tensor_parallel_env_trainer_pre(model):+ if not os.environ.get("UNSLOTH_TP_SIZE") and not os.environ.get("UNSLOTH_PP_SIZE"):+ return None+ from .tp_env import tensor_parallel_env_trainer_pre+ return tensor_parallel_env_trainer_pre(model)++def _tensor_parallel_trainer_pre(model):if not _is_unsloth_tensor_parallel(model):return Falsediff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex f6d61eca61f..8fc7657b5d0 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -3923,6 +3923,13 @@ def _refuse_save_on_each_node(training_args):)+def _env_tensor_parallel_dp_mesh(model):+ if not os.environ.get("UNSLOTH_TP_SIZE"):+ return None+ from .tp_env import fsdp2_dp_mesh+ return fsdp2_dp_mesh(model)++def native_fsdp2_trainer_setup(trainer = None,model = None,@@ -3948,7 +3955,10 @@ def native_fsdp2_trainer_setup(_refuse_projection_optim(training_args)_refuse_clef(model)_refuse_parallelism_config(training_args)- _refuse_tensor_parallel_model(model)+ # UNSLOTH_TP_SIZE + UNSLOTH_FSDP2=1: the tensor parallel model is sharded over mesh['dp'] below.+ tp_dp_mesh = _env_tensor_parallel_dp_mesh(model)+ if tp_dp_mesh is None:+ _refuse_tensor_parallel_model(model)if model_init is not None:# Trainer.train / hyperparameter_search call model_init again for a fresh model (and# rebuild the accelerator per trial), which would train unsharded.@@ -3987,6 +3997,8 @@ def native_fsdp2_trainer_setup(if _trainer_uses_cpu(training_args):config.device = "cpu" # the Trainer will run on the CPU: no GPU mesh_trainer_process_group(training_args, config)+ if tp_dp_mesh is not None:+ config.mesh = tp_dp_meshreturn shard_model(model, config)if trainer is not None and is_native_fsdp2(getattr(trainer, "model", None)):_scaler_for_native(trainer)diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 5c6d273056e..7ec5c574a16 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -76,6 +76,7 @@ from .loader_utils import (raise_if_fast_inference_under_fsdp2,)import os, contextlib, functools, sys+from .tp_env import tensor_parallel_env_load, tensor_parallel_env_pefttry:from huggingface_hub import get_token@@ -1199,6 +1200,7 @@ class FastLanguageModel(FastLlamaModel):# Text-diffusion models load through FastModel's slow path; these route them there for the PEFT / mode helpers.@staticmethod+ @tensor_parallel_env_peft@functools.wraps(FastLlamaModel.get_peft_model)def get_peft_model(model, *args, **kwargs):raise_if_unsaved_reap(model)@@ -1230,6 +1232,7 @@ class FastLanguageModel(FastLlamaModel):return get_mtp_head(model, *args, **kwargs)@staticmethod+ @tensor_parallel_env_load@fsdp2_sharded_load_env@tokenizers_v1_on_return@_offline_aware_load@@ -2163,6 +2166,7 @@ class FastModel(FastBaseModel):return model@staticmethod+ @tensor_parallel_env_peftdef get_peft_model(model, *args, **kwargs):raise_if_unsaved_reap(model)# Route text-diffusion models (slow path) to the transformers-only PEFT helper.@@ -2188,6 +2192,7 @@ class FastModel(FastBaseModel):return FastBaseModel.for_training(model, use_gradient_checkpointing)@staticmethod+ @tensor_parallel_env_load@fsdp2_sharded_load_env@tokenizers_v1_on_return@_restore_load_scoped_envdiff --git a/unsloth/models/tp_env.py b/unsloth/models/tp_env.pynew file mode 100644index 00000000000..1a33b932442--- /dev/null+++ b/unsloth/models/tp_env.py@@ -0,0 +1,388 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Tensor parallelism from the environment, for unmodified training scripts.++ UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 2 train.py # tp 2+ UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 4 train.py # dp 2 (DDP-style) x tp 2+ UNSLOTH_TP_SIZE=2 UNSLOTH_FSDP2=1 torchrun --nproc-per-node 4 train.py # dp 2 (native FSDP2) x tp 2++The layout is read once. The world splits into dp x tp ranks (tp the inner dimension, as in+init_device_mesh(..., (dp, tp), ("dp", "tp"))). The script's own calls apply it:+- FastLanguageModel / FastModel.from_pretrained: 16-bit checkpoints load through sharded_loading (each rank+ reads its slices of the attention / MLP projections); 4-bit loads in full and is sharded at get_peft_model.+- get_peft_model: apply_tensor_parallel over mesh["tp"] once LoRA is attached (full-size LoRA, 1-GPU init).+- Trainer.__init__: tensor parallel if get_peft_model did not apply it; native FSDP2 shards over mesh["dp"]+ (UNSLOTH_FSDP2=1), otherwise gradients are averaged over mesh["dp"] before clipping and the optimizer step.+So the order is always split (pipeline parallel, not from the environment yet) -> tp -> FSDP2.++UNSLOTH_TP_SHARDED_LOAD=0 loads 16-bit checkpoints in full on every rank instead (then shards them).+"""++from __future__ import annotations++import functools+import inspect+import os++import torch++__all__ = [+ "TPEnvLayout",+ "env_layout",+ "env_hint",+ "tensor_parallel_env_load",+ "tensor_parallel_env_peft",+ "tensor_parallel_env_trainer_pre",+]++_UNSET = object()+_LAYOUT = _UNSET+_DEPTH = {"load": 0, "peft": 0}+_DDP_MESH = "_unsloth_tp_ddp_mesh"+++def _int_env(name):+ raw = os.environ.get(name)+ if raw is None or not raw.strip():+ return None+ try:+ value = int(raw.strip())+ except ValueError:+ raise ValueError(f"Unsloth: {name}={raw!r} must be an integer.") from None+ if value < 1:+ raise ValueError(f"Unsloth: {name}={value} must be >= 1.")+ return value+++class TPEnvLayout:+ """world = dp x tp; `mesh()` builds (once) the device mesh, initializing the process group if needed."""++ def __init__(self, tp, dp, world, fsdp2):+ self.tp, self.dp, self.world, self.fsdp2 = tp, dp, world, fsdp2+ self._mesh = None++ def __repr__(self):+ dp = f"dp {self.dp} ({'native FSDP2' if self.fsdp2 else 'DDP'}) x " if self.dp > 1 else ""+ return f"{dp}tp {self.tp}"++ @property+ def sharded_loading(self):+ return os.environ.get("UNSLOTH_TP_SHARDED_LOAD", "1").strip().lower() not in (+ "0",+ "false",+ "no",+ "off",+ )++ def mesh(self):+ if self._mesh is not None:+ return self._mesh+ import torch.distributed as dist+ from torch.distributed.device_mesh import init_device_mesh++ cuda = torch.cuda.is_available()+ if cuda:+ torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", "0")))+ if not dist.is_initialized():+ # What the Trainer's accelerate state would create; it reuses an existing group.+ dist.init_process_group("nccl" if cuda else "gloo")+ if dist.get_world_size() != self.world:+ raise RuntimeError(+ f"Unsloth: UNSLOTH_TP_SIZE={self.tp} read WORLD_SIZE={self.world}, but the process group has "+ f"{dist.get_world_size()} ranks."+ )+ device = "cuda" if cuda else "cpu"+ if self.dp == 1:+ mesh = init_device_mesh(device, (self.tp,), mesh_dim_names = ("tp",))+ else:+ mesh = init_device_mesh(device, (self.dp, self.tp), mesh_dim_names = ("dp", "tp"))+ from .pp_native import check_mesh_composition+ check_mesh_composition(+ {"dp": mesh["dp"], "tp": mesh["tp"]}, f"UNSLOTH_TP_SIZE={self.tp} (dp x tp)"+ )+ self._mesh = mesh+ if dist.get_rank() == 0:+ print(f"Unsloth: tensor parallel from UNSLOTH_TP_SIZE: {self} over {self.world} ranks.")+ return mesh++ @property+ def tp_mesh(self):+ return self.mesh()["tp"]++ @property+ def dp_mesh(self):+ return self.mesh()["dp"] if self.dp > 1 else None+++def _read_layout():+ pp = _int_env("UNSLOTH_PP_SIZE")+ if pp is not None and pp > 1:+ raise ValueError(+ f"Unsloth: UNSLOTH_PP_SIZE={pp}: pipeline parallelism cannot be launched from the environment yet "+ "(the Trainer cannot train a pipeline parallel model until Trainer support lands). Use the Python "+ "API (apply_pipeline_parallel and PipelineParallel.step in a custom loop, "+ "unsloth/models/pp_native.py), or unset UNSLOTH_PP_SIZE."+ )+ tp = _int_env("UNSLOTH_TP_SIZE")+ if tp is None or tp == 1:+ return None+ try:+ world = int(os.environ.get("WORLD_SIZE", "1"))+ except ValueError:+ world = 1+ if world % tp:+ raise ValueError(+ f"Unsloth: UNSLOTH_TP_SIZE={tp} must divide the number of ranks (WORLD_SIZE={world}); launch with "+ f"torchrun --nproc-per-node {tp} (or a multiple of {tp} for data parallel x tensor parallel), or "+ "unset UNSLOTH_TP_SIZE."+ )+ from ..fsdp2_launch import unsloth_fsdp2_requested++ fsdp2 = bool(unsloth_fsdp2_requested())+ backend = os.environ.get("UNSLOTH_FSDP2_BACKEND", "").strip().lower()+ if fsdp2 and backend in ("accelerate", "hf", "transformers"):+ raise ValueError(+ f"Unsloth: UNSLOTH_TP_SIZE={tp} composes with native FSDP2 only (UNSLOTH_FSDP2=1); "+ f"UNSLOTH_FSDP2_BACKEND={backend} would hand the tensor parallel model to accelerate's FSDP. "+ "Unset UNSLOTH_FSDP2_BACKEND."+ )+ return TPEnvLayout(tp, world // tp, world, fsdp2)+++def env_layout():+ """The layout from UNSLOTH_TP_SIZE (read once), or None when tensor parallelism is not requested."""+ global _LAYOUT+ if _LAYOUT is _UNSET:+ _LAYOUT = _read_layout()+ return _LAYOUT+++def _reset_env_layout():+ """Tests: read the environment again."""+ global _LAYOUT+ _LAYOUT = _UNSET+++def env_hint():+ """A suffix for refusals under an env-driven launch (empty otherwise)."""+ try:+ layout = _LAYOUT if _LAYOUT is not _UNSET else None+ except Exception:+ layout = None+ if layout is None:+ return ""+ return (+ f" (Tensor parallelism came from UNSLOTH_TP_SIZE={layout.tp}: unset it to run this script with "+ "DDP or UNSLOTH_FSDP2=1.)"+ )+++def _reraise_with_hint(exc):+ hint = env_hint()+ if hint and hint not in str(exc):+ try:+ new = type(exc)(f"{exc}{hint}")+ except Exception:+ raise exc+ raise new from exc+ raise exc+++def _rank0():+ import torch.distributed as dist+ return not dist.is_initialized() or dist.get_rank() == 0+++_REFUSED_LOAD_FLAGS = (+ ("fast_inference", "vLLM (fast_inference = True)"),+ ("full_finetuning", "full finetuning (full_finetuning = True; use UNSLOTH_FSDP2=1 instead)"),+ ("load_in_8bit", "8-bit weights (load_in_8bit = True; load in 4-bit or 16-bit)"),+ ("load_in_fp8", "fp8 weights (load_in_fp8)"),+ ("qat_scheme", "QAT (qat_scheme)"),+)+++def _bound(fn, args, kwargs):+ try:+ signature = inspect.signature(fn)+ bound = signature.bind_partial(*args, **kwargs)+ except (TypeError, ValueError):+ return dict(kwargs)+ values = dict(bound.arguments)+ for name, param in signature.parameters.items():+ if param.kind is inspect.Parameter.VAR_KEYWORD:+ values.update(values.pop(name, None) or {})+ return values+++def _four_bit(values, fn):+ if values.get("quantization_config") is not None:+ return True+ if "load_in_4bit" in values:+ return bool(values["load_in_4bit"])+ if values.get("load_in_16bit"):+ return False+ try:+ default = inspect.signature(fn).parameters["load_in_4bit"].default+ except (KeyError, TypeError, ValueError):+ return False+ return default is True+++def tensor_parallel_env_load(fn):+ """Decorator for a from_pretrained (FastLanguageModel / FastModel): sharded 16-bit loads under UNSLOTH_TP_SIZE."""++ @functools.wraps(fn)+ def from_pretrained(*args, **kwargs):+ layout = env_layout()+ if layout is None or _DEPTH["load"]:+ return fn(*args, **kwargs)+ values = _bound(fn, args, kwargs)+ refused = [what for key, what in _REFUSED_LOAD_FLAGS if values.get(key)]+ if refused:+ raise NotImplementedError(+ f"Unsloth: UNSLOTH_TP_SIZE={layout.tp} (tensor parallel) does not support "+ + "; ".join(refused)+ + ". Unset UNSLOTH_TP_SIZE to run this script with DDP or UNSLOTH_FSDP2=1."+ )+ from .fsdp2_load import fsdp2_sharded_load_requested++ if fsdp2_sharded_load_requested():+ # Its per-rank shard reads know nothing of the tp mesh.+ raise NotImplementedError(+ f"Unsloth: UNSLOTH_TP_SIZE={layout.tp} (tensor parallel) does not support "+ "UNSLOTH_FSDP2_SHARDED_LOAD=1. Unset UNSLOTH_FSDP2_SHARDED_LOAD; tensor parallel "+ "already loads 16-bit weights sharded."+ )+ mesh = layout.tp_mesh+ _DEPTH["load"] += 1+ try:+ if _four_bit(values, fn) or not layout.sharded_loading:+ return fn(+ *args, **kwargs+ ) # full load; get_peft_model shards it (Params4bit included)+ from .tp_native import sharded_loading++ try:+ with sharded_loading(mesh) as state:+ out = fn(*args, **kwargs)+ except ValueError as exc:+ if not str(exc).startswith("Unsloth: tensor parallel sharded loading"):+ raise+ if _rank0():+ print(f"{exc} Loading in full on every rank instead; get_peft_model shards it.")+ return fn(*args, **kwargs)+ if not state["models"] and _rank0():+ print(+ "Unsloth: UNSLOTH_TP_SIZE: this loader did not go through transformers from_pretrained; "+ "the model loaded in full and is sharded at get_peft_model."+ )+ return out+ finally:+ _DEPTH["load"] -= 1++ from_pretrained._unsloth_tp_env = True+ return from_pretrained+++def _model_of(out):+ if isinstance(out, (tuple, list)) and out and isinstance(out[0], torch.nn.Module):+ return out[0]+ return out if isinstance(out, torch.nn.Module) else None+++def _apply(model, layout):+ from .tp_native import apply_tensor_parallel, is_tensor_parallel+ if is_tensor_parallel(model):+ return model+ try:+ return apply_tensor_parallel(model, layout.tp_mesh)+ except (ValueError, RuntimeError, NotImplementedError) as exc:+ _reraise_with_hint(exc)+++def tensor_parallel_env_peft(fn):+ """Decorator for get_peft_model: shard over mesh["tp"] once LoRA is attached."""++ @functools.wraps(fn)+ def get_peft_model(*args, **kwargs):+ layout = env_layout()+ if layout is None or _DEPTH["peft"]:+ return fn(*args, **kwargs)+ _DEPTH["peft"] += 1+ try:+ out = fn(*args, **kwargs)+ finally:+ _DEPTH["peft"] -= 1+ model = _model_of(out)+ if model is not None:+ _apply(model, layout)+ return out++ get_peft_model._unsloth_tp_env = True+ return get_peft_model+++def _levels(model):+ from .tp_native import _tp_chain+ try:+ return _tp_chain(model)+ except Exception:+ return [model]+++def tensor_parallel_env_trainer_pre(model):+ """Trainer.__init__ before anything else touches the model: tensor parallel (if get_peft_model did not+ apply it) and the DDP-style dp dimension. Returns the layout (None without UNSLOTH_TP_SIZE)."""+ layout = env_layout()+ if layout is None or not isinstance(model, torch.nn.Module):+ return layout+ _apply(model, layout)+ if layout.dp > 1 and not layout.fsdp2:+ levels = _levels(model)+ if not any(level.__dict__.get(_DDP_MESH) is not None for level in levels):+ dp_mesh = layout.dp_mesh+ _broadcast_trainable(model, dp_mesh)+ for level in levels:+ level.__dict__[_DDP_MESH] = dp_mesh+ return layout+++def _broadcast_trainable(model, dp_mesh):+ """DDP's start: every dp replica begins from dp rank 0's trainable weights (same tp index)."""+ import torch.distributed as dist++ group = dp_mesh.get_group()+ src = dist.get_global_rank(group, 0)+ with torch.no_grad():+ for p in model.parameters():+ if p.requires_grad:+ local = getattr(p, "_local_tensor", p.data)+ work = (+ local if local.is_contiguous() else local.contiguous()+ ) # NCCL takes dense tensors+ dist.broadcast(work, src = src, group = group)+ if work is not local:+ local.copy_(work)+++def fsdp2_dp_mesh(model):+ """The dp mesh native FSDP2 shards a tensor parallel model over under UNSLOTH_TP_SIZE + UNSLOTH_FSDP2=1."""+ layout = _LAYOUT if _LAYOUT is not _UNSET else None+ if (+ layout is None+ or layout.dp == 1+ or not layout.fsdp2+ or not isinstance(model, torch.nn.Module)+ ):+ return None+ from .tp_native import is_tensor_parallel++ return layout.dp_mesh if is_tensor_parallel(model) else None+++def fsdp2_has_no_dp_dimension():+ """UNSLOTH_FSDP2=1 with UNSLOTH_TP_SIZE = world size: nothing for FSDP2 to shard over."""+ layout = _LAYOUT if _LAYOUT is not _UNSET else None+ return layout is not None and layout.dp == 1diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex 26ef5d01240..24976505b57 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -34,9 +34,13 @@ reads the same batch, dp replicas read different ones:... 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.+the tp ranks, batches sharded over dp only, tp-aware clipping and float16 scaler. Trainer checkpoints are per+rank (unsloth_tp/rank*.pt: local shards of the trainable weights and optimizer state, resumed on the same+layout) next to the 1-GPU adapter; bitsandbytes Adam / AdamW step the local shards; no evaluation;+trainer.save_model() writes the 1-GPU adapter.++Unmodified scripts: UNSLOTH_TP_SIZE=k torchrun ... applies all of the above from the environment+(models/tp_env.py), with UNSLOTH_FSDP2=1 (native FSDP2) or DDP-style gradient averaging for the dp dimension."""from __future__ import annotations@@ -1693,8 +1697,13 @@ def save_tp_adapter(model, save_directory, **kwargs):mesh = dp_mesh = Nonefor level in _tp_chain(model):mesh = mesh or level.__dict__.get("_unsloth_tp_mesh")- 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.+ dp_mesh = (+ dp_mesh+ or level.__dict__.get("_unsloth_tp_dp_mesh")+ or level.__dict__.get("_unsloth_tp_ddp_mesh")+ )+ # Under shard_model over the dp mesh every trainable DTensor spans the whole (dp, tp) world; DDP-style dp+ # replicas hold the same adapter, gathered over each tp group.ranks = (mesh.size() * (dp_mesh.size() if dp_mesh is not None else 1) if mesh is not None else None)@@ -2268,6 +2277,8 @@ def load_tensor_parallel(# turns into the token mean over the dp replicas, as for DDP on dp GPUs._TP_DATA = "_unsloth_tp_data"+_DDP_MESH = "_unsloth_tp_ddp_mesh"+_DP_SYNC = "_unsloth_tp_dp_sync"_UNSUPPORTED_OPTIMIZERS = ("8bit","bnb",@@ -2289,15 +2300,74 @@ def _tp_meshes(model):(m.__dict__["_unsloth_tp_dp_mesh"] for m in chain if "_unsloth_tp_dp_mesh" in m.__dict__),None,)+ if (+ dp is None+ ): # UNSLOTH_TP_SIZE with DDP-style data parallel (tp_env): gradients averaged over dp+ dp = next(+ (m.__dict__[_DDP_MESH] for m in chain if m.__dict__.get(_DDP_MESH) is not None), None+ )return tp, dp+def _ddp_mesh(model):+ return next(+ (m.__dict__[_DDP_MESH] for m in _tp_chain(model) if m.__dict__.get(_DDP_MESH) is not None),+ None,+ )+++def _env_hint():+ from .tp_env import env_hint+ return env_hint()++def _strategy(value):value = getattr(value, "value", value)return str(value or "no").lower()-def _refuse_tp_trainer_args(args):+def _optim_name(args):+ optim = getattr(args, "optim", "")+ return str(getattr(optim, "value", optim) or "").strip().lower()+++def _keeps_bnb(name, cpu_shards):+ from .fsdp2_native import _BNB_LOCAL_SHARD_OPTIMS, _bnb_local_shards_available+ return name in _BNB_LOCAL_SHARD_OPTIMS and _bnb_local_shards_available(cpu_shards)+++def _tp_bnb_optim(args, cpu_shards):+ """bitsandbytes Adam / AdamW (the notebooks' adamw_8bit) step each DTensor's local shard+ (fsdp2_bnb_optim, as under native FSDP2); the other bitsandbytes optims with a torch equivalent switch to it."""+ from .fsdp2_native import _BNB_OPTIMS++ name = _optim_name(args)+ if _keeps_bnb(name, cpu_shards):+ return False+ target = _BNB_OPTIMS.get(name)+ if target is None:+ return False+ if target == "adamw_torch_fused" and (cpu_shards or not torch.cuda.is_available()):+ target = "adamw_torch"+ _print_rank0(+ f"Unsloth: tensor parallel parameters are DTensors, which this bitsandbytes optimizer cannot step "+ f"(UNSLOTH_FSDP2_BNB_LOCAL=0 or no local-shard support). Switching optim = '{name}' to '{target}'."+ )+ try:+ from transformers.training_args import OptimizerNames+ args.optim = OptimizerNames(target)+ except Exception:+ args.optim = target+ return True+++def _print_rank0(message):+ import torch.distributed as dist+ if not dist.is_initialized() or dist.get_rank() == 0:+ print(message)+++def _refuse_tp_trainer_args(args, cpu_shards = False):problems = []if getattr(args, "deepspeed", None):problems.append("DeepSpeed")@@ -2305,10 +2375,6 @@ def _refuse_tp_trainer_args(args):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"@@ -2317,9 +2383,9 @@ def _refuse_tp_trainer_args(args):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')")+ optim = _optim_name(args)+ if any(key in optim for key in _UNSUPPORTED_OPTIMIZERS) and not _keeps_bnb(optim, cpu_shards):+ problems.append(f"optim = '{optim}' (use 'adamw_torch' or 'adamw_8bit')")config = getattr(args, "accelerator_config", None)if getattr(config, "dispatch_batches", None):problems.append("accelerator_config.dispatch_batches")@@ -2328,6 +2394,7 @@ def _refuse_tp_trainer_args(args):"Unsloth: the Trainer on a tensor parallel model does not support "+ "; ".join(problems)+ "."+ + _env_hint())@@ -2358,8 +2425,11 @@ def tp_trainer_setup(_install_tp_accelerate_hooks()return Truemodel = trainer.model- _refuse_tp_trainer_args(trainer.args)tp_mesh, dp_mesh = _tp_meshes(model)+ cpu_shards = tp_mesh.device_type == "cpu"+ _tp_bnb_optim(trainer.args, cpu_shards)+ _refuse_tp_trainer_args(trainer.args, cpu_shards)+ ddp_mesh = _ddp_mesh(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"] = (@@ -2369,6 +2439,21 @@ def tp_trainer_setup(trainer.__dict__["save_model"] = types.MethodType(_tp_trainer_save_model, trainer)for name in ("evaluate", "predict"):trainer.__dict__[name] = _refuse_tp_trainer_call(name)+ # Trainer checkpoints: per-rank local shards (instance level: before native FSDP2's class hooks, whose+ # full-state gathers do not restore the packed tp part order).+ for name, method in (+ ("_save_optimizer_and_scheduler", _tp_save_optimizer_and_scheduler),+ ("_load_optimizer_and_scheduler", _tp_load_optimizer_and_scheduler),+ ("_load_from_checkpoint", _tp_load_from_checkpoint),+ ):+ trainer.__dict__[name] = types.MethodType(method, trainer)+ sync = None+ if ddp_mesh is not None:+ # DDP-style dp (UNSLOTH_TP_SIZE without UNSLOTH_FSDP2): torch DDP cannot wrap DTensor parameters, so+ # the gradients are averaged over the dp mesh before clipping (Accelerator.clip_grad_norm_ below) or,+ # without clipping, at the optimizer step.+ sync = {"mesh": ddp_mesh, "synced": False}+ trainer.accelerator.__dict__[_DP_SYNC] = synccreate_optimizer = trainer.create_optimizerdef create_optimizer_tp(*args, **kwargs):@@ -2387,21 +2472,254 @@ def tp_trainer_setup("`unsloth.models.fsdp2_native.split_param_groups(...)` before the scheduler, or pass only the optimizer.")_split_mixed_param_groups(inner)+ _tp_localize_bnb(optimizer)+ if sync is not None and not getattr(inner, "_unsloth_tp_dp_hooked", False):+ inner.register_step_pre_hook(functools.partial(_dp_sync_before_step, sync))+ inner._unsloth_tp_dp_hooked = Truereturn optimizertrainer.__dict__["create_optimizer"] = create_optimizer_tp- train = trainer.train+ # transformers 5.x clips mixed DTensor / plain gradients (modules_to_save next to the LoRA DTensors) in its+ # own _mixed_mesh_grad_norm, which sums every DTensor's local square over its mesh and skips the dp+ # average: keep them on Accelerator.clip_grad_norm_ (tp_clip_grad_norm_ counts each element once).+ trainer.__dict__["_has_mixed_mesh_grads"] = lambda model: False+ return True- 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 _tp_localize_bnb(optimizer):+ """A bitsandbytes Adam / AdamW steps the local shards of the tp DTensors (fsdp2_bnb_optim)."""+ from .fsdp2_native import _inner_optimizer, _is_bnb_optimizer_class, _localize_bnb_optimizer++ inner = _inner_optimizer(optimizer)+ if _localize_bnb_optimizer(optimizer) or not _is_bnb_optimizer_class(type(inner)):+ return+ raise RuntimeError(+ f"Unsloth: a tensor parallel model's parameters are DTensors, which this bitsandbytes optimizer "+ f"({type(inner).__name__}) cannot step; only bitsandbytes Adam / AdamW step local shards. Use optim = "+ "'adamw_8bit' or 'adamw_torch'." + _env_hint()+ )+++def _dp_average(params, mesh):+ """Average the gradients over the dp mesh (DDP's all-reduce, one per dtype / device bucket). A trainable+ with a gradient on some dp replicas only (an unrouted expert, an unused tower) gets zeros on the others+ first, as DDP does, so every replica reduces the same buckets; one with no gradient anywhere stays None."""+ import torch.distributed as dist+ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors++ params = [p for p in params if p.requires_grad]+ if not params:+ return+ group, n = mesh.get_group(), mesh.size()+ device = (+ torch.device("cuda", torch.cuda.current_device())+ if mesh.device_type == "cuda"+ else torch.device(mesh.device_type)+ )+ has = torch.tensor([p.grad is not None for p in params], dtype = torch.int32, device = device)+ dist.all_reduce(has, op = dist.ReduceOp.MAX, group = group)+ buckets = {}+ for p, any_grad in zip(params, has.tolist()):+ if not any_grad:+ continue+ if p.grad is None:+ p.grad = torch.zeros_like(p)+ g = p.grad+ local = g._local_tensor if _is_dtensor(g) else g+ buckets.setdefault((local.device, local.dtype), []).append(local)+ with torch.no_grad():+ for tensors in buckets.values():+ flat = _flatten_dense_tensors(tensors)+ dist.all_reduce(flat, group = group)+ flat.div_(n)+ for t, value in zip(tensors, _unflatten_dense_tensors(flat, tensors)):+ t.copy_(value)+++def _dp_sync_before_step(sync, optimizer, args, kwargs):+ if sync["synced"]:+ sync["synced"] = False # clip_grad_norm_ already averaged this step's gradients+ return None+ _dp_average([p for group in optimizer.param_groups for p in group["params"]], sync["mesh"])+ return None+++# Trainer checkpoints under tensor parallelism: every rank writes its own local shards of the trainable+# weights and of the optimizer state (DTensor entries as local tensors), the scheduler / scaler / RNG / trainer+# state stay as the Trainer writes them, and save_model writes the 1-GPU adapter. A resume needs the same layout.+_CKPT_DIR = "unsloth_tp"+++def _ckpt_path(directory, rank):+ import os+ return os.path.join(directory, _CKPT_DIR, f"rank{rank:05d}.pt")+++def _tp_layout(trainer):+ import torch.distributed as dist++ tp_mesh, dp_mesh = _tp_meshes(trainer.model)+ params = [+ (name, tuple((p._local_tensor if _is_dtensor(p) else p).shape))+ for name, p in trainer.model.named_parameters()+ if p.requires_grad+ ]+ return {+ "world": dist.get_world_size() if dist.is_initialized() else 1,+ "tp": tp_mesh.size() if tp_mesh is not None else 1,+ "dp": dp_mesh.size() if dp_mesh is not None else 1,+ "dp_kind": None+ if dp_mesh is None+ else ("ddp" if _ddp_mesh(trainer.model) is not None else "fsdp2"),+ "params": params,+ }+++def _optimizer_local_state(optimizer):+ from .fsdp2_native import _inner_optimizer++ state_dict = _inner_optimizer(optimizer).state_dict()+ dtensors, state = [], {}+ for index, entry in state_dict["state"].items():+ out = {}+ for key, value in entry.items():+ if _is_dtensor(value):+ out[key] = value.to_local().detach()+ dtensors.append((index, key))+ else:+ out[key] = value.detach() if torch.is_tensor(value) else value+ state[index] = out+ return {"state": state, "param_groups": state_dict["param_groups"], "dtensor": dtensors}+++def _load_optimizer_local_state(optimizer, saved):+ from .fsdp2_native import _inner_optimizer++ DTensor = _dtensor_api()[0]+ inner = _inner_optimizer(optimizer)+ params = [p for group in inner.param_groups for p in group["params"]]+ saved_ids = [i for group in saved["param_groups"] for i in group["params"]]+ if len(params) != len(saved_ids):+ raise RuntimeError(+ f"Unsloth: tensor parallel resume: the checkpoint's optimizer has {len(saved_ids)} parameters, this "+ f"one {len(params)}."+ )+ param_of = dict(zip(saved_ids, params))+ wrap = {tuple(x) for x in saved["dtensor"]}+ state = {}+ for index, entry in saved["state"].items():+ p = param_of[index]+ out = {}+ for key, value in entry.items():+ if (index, key) in wrap:+ local = p._local_tensor+ value = DTensor.from_local(+ value.to(local.device),+ p.device_mesh,+ p.placements,+ run_check = False,+ shape = p.shape,+ stride = p.stride(),+ )+ out[key] = value+ state[index] = out+ inner.load_state_dict({"state": state, "param_groups": saved["param_groups"]})+++def _tp_save_optimizer_and_scheduler(self, output_dir):+ import os++ import torch.distributed as dist++ rank = dist.get_rank() if dist.is_initialized() else 0+ path = _ckpt_path(output_dir, rank)+ os.makedirs(os.path.dirname(path), exist_ok = True)+ trainables = {+ name: (p._local_tensor if _is_dtensor(p) else p).detach()+ for name, p in self.model.named_parameters()+ if p.requires_grad+ }+ payload = {+ "layout": _tp_layout(self),+ "trainables": trainables,+ "optimizer": _optimizer_local_state(self.optimizer)+ if getattr(self, "optimizer", None) is not None+ else None,+ }+ torch.save(payload, path)+ scheduler = getattr(self, "lr_scheduler", None)+ if self.args.should_save and scheduler is not None:+ from transformers.trainer import SCHEDULER_NAME+ torch.save(scheduler.state_dict(), os.path.join(output_dir, SCHEDULER_NAME))+ if dist.is_initialized():+ dist.barrier() # every rank's file is on disk before the Trainer state marks the checkpoint complete+++def _tp_resume_payload(self, checkpoint):+ import os++ import torch.distributed as dist++ cached = self.__dict__.get("_unsloth_tp_resume")+ if cached is not None and cached[0] == checkpoint:+ return cached[1]+ rank = dist.get_rank() if dist.is_initialized() else 0+ path = _ckpt_path(checkpoint, rank)+ if not os.path.isfile(path):+ raise RuntimeError(+ f"Unsloth: tensor parallel resume needs the per-rank state {path}, which this checkpoint does not "+ "have (it was not written by a tensor parallel Trainer, or with save_only_model = True, which saves "+ "no optimizer state to resume from)." + _env_hint()+ )+ payload = torch.load(path, map_location = "cpu", weights_only = True)+ want, got = _tp_layout(self), payload["layout"]+ if want != got:+ diff = {+ k: (got.get(k), want.get(k))+ for k in ("world", "tp", "dp", "dp_kind")+ if got.get(k) != want.get(k)+ }+ raise RuntimeError(+ f"Unsloth: tensor parallel resume from {checkpoint}: the checkpoint was written on another layout "+ f"({diff or 'trainable parameter names / shard shapes differ'}); resume with the same world size, "+ "UNSLOTH_TP_SIZE and data parallel mode."+ )+ self.__dict__["_unsloth_tp_resume"] = (checkpoint, payload)+ return payload+++def _tp_load_from_checkpoint(+ self,+ resume_from_checkpoint,+ model = None,+):+ payload = _tp_resume_payload(self, resume_from_checkpoint)+ target = model if model is not None else self.model+ with torch.no_grad():+ for name, p in target.named_parameters():+ if p.requires_grad:+ local = p._local_tensor if _is_dtensor(p) else p+ local.copy_(payload["trainables"][name].to(local.device))+ _print_rank0(+ f"Unsloth: tensor parallel resume: every rank restored its local shards from {resume_from_checkpoint}."+ )+++def _tp_load_optimizer_and_scheduler(self, checkpoint, *args, **kwargs):+ import os++ if checkpoint is None:+ return None+ payload = _tp_resume_payload(self, checkpoint)+ if payload.get("optimizer") is not None:+ _load_optimizer_local_state(self.optimizer, payload["optimizer"])+ from transformers.trainer import SCHEDULER_NAME++ path = os.path.join(checkpoint, SCHEDULER_NAME)+ if getattr(self, "lr_scheduler", None) is not None and os.path.isfile(path):+ self.lr_scheduler.load_state_dict(torch.load(path, weights_only = True))+ self.__dict__.pop("_unsloth_tp_resume", None)+ return Nonedef _refuse_tp_trainer_call(name):@@ -2409,6 +2727,7 @@ def _refuse_tp_trainer_call(name):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."+ + _env_hint())return refuse@@ -2483,7 +2802,7 @@ def _install_tp_accelerate_hooks():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)."+ "dispatches iterable datasets over every rank)." + _env_hint())dp_size, dp_rank = layout# The Trainer seeds workers with partial(seed_worker, rank = process_index): tp peers must draw the@@ -2522,7 +2841,12 @@ def _install_tp_accelerate_hooks():"Unsloth: tensor parallel gradient clipping supports the 2-norm only.")self.unscale_gradients()- return tp_clip_grad_norm_(list(parameters), max_norm)+ parameters = list(parameters)+ sync = self.__dict__.get(_DP_SYNC)+ if sync is not None:+ _dp_average(parameters, sync["mesh"])+ sync["synced"] = True+ return tp_clip_grad_norm_(parameters, max_norm)Accelerator.prepare_model = prepare_modelAccelerator.prepare_data_loader = prepare_data_loader