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
UNSLOTH_PARALLEL: one flag and one root mesh for dp / tp / pp / cp, pipeline parallel from the environment, and a capability registry (#16407)
Daniel Han93413519544a
diff --git a/tests/test_context_parallel.py b/tests/test_context_parallel.pyindex 50b955e3199..0b0be959228 100644--- a/tests/test_context_parallel.py+++ b/tests/test_context_parallel.py@@ -447,7 +447,7 @@ def test_fsdp2_shards_over_dp_shard_cp_and_a_later_trainer_restores_the_config(maccelerator = _fsdp2_accelerator(user_pc)Trainer, _, built = _gated_trainer(monkeypatch, accelerator = accelerator)Trainer()- assert built == [(2, "ring", "allgather", "fsdp2")]+ assert built == [(2, "ulysses", "allgather", "fsdp2")] # the default backend: autopc = accelerator.state.parallelism_config# What accelerate's fsdp2_prepare_model indexes the mesh with; cp stays Unsloth's own.assert pc.fsdp_dim_names == ["dp_shard_cp"]@@ -897,7 +897,7 @@ def test_cp_methods_are_wrapped_only_once_a_trainer_enables_cp(monkeypatch):Trainer, _, built = _gated_trainer(monkeypatch, install_cp_methods = False)plain = {name: Trainer.__dict__[name] for name in _CP_METHODS}Trainer()- assert built == [(2, "ring", "allgather")]+ assert built == [(2, "ulysses", "allgather")] # the default backend: autofor name in _CP_METHODS:assert Trainer.__dict__[name].__wrapped__ is plain[name]@@ -938,17 +938,19 @@ def test_bad_cp_options_fail_before_the_trainer_builds(monkeypatch, overrides, edef test_cp_option_defaults_and_size_one():import types- assert cp.context_parallel_options(None) == (1, "ring", "allgather")+ assert cp.context_parallel_options(None) == (1, "auto", "allgather")config = types.SimpleNamespace(context_parallel_size = 1, context_parallel_backend = "ulysses")assert cp.context_parallel_options(config) == (1, "ulysses", "allgather")config = types.SimpleNamespace(context_parallel_size = 4, context_parallel_rotate_method = "alltoall")- assert cp.context_parallel_options(config) == (4, "ring", "alltoall")+ assert cp.context_parallel_options(config) == (4, "auto", "alltoall")def test_manager_gets_the_backend_and_rotate_method(monkeypatch):- Trainer, _, built = _gated_trainer(monkeypatch, context_parallel_rotate_method = "alltoall")+ Trainer, _, built = _gated_trainer(+ monkeypatch, context_parallel_backend = "ring", context_parallel_rotate_method = "alltoall"+ )Trainer()assert built == [(2, "ring", "alltoall")]@@ -1114,7 +1116,7 @@ def test_unsloth_training_arguments_keep_the_cp_options():context_parallel_rotate_method = "alltoall",report_to = "none",)- assert cp.context_parallel_options(args) == (2, "ring", "alltoall")+ assert cp.context_parallel_options(args) == (2, "auto", "alltoall")def test_cli_forwards_the_cp_options():@@ -1165,9 +1167,9 @@ def test_generated_sft_config_carries_the_cp_options(tmp_path):context_parallel_rotate_method = "alltoall",report_to = "none",)- assert cp.context_parallel_options(config) == (2, "ring", "alltoall")+ assert cp.context_parallel_options(config) == (2, "auto", "alltoall")default = config_module.SFTConfig(output_dir = str(tmp_path), report_to = "none")- assert cp.context_parallel_options(default) == (1, "ring", "allgather")+ assert cp.context_parallel_options(default) == (1, "auto", "allgather")class _FakeCPMesh:@@ -1375,7 +1377,7 @@ def test_instance_wrappers_made_in_init_capture_the_cp_methods(monkeypatch):Trainer(None, args = args) # SFTTrainer(model, args = SFTConfig(context_parallel_size = 2))- assert built == [(2, "ring", "allgather")]+ assert built == [(2, "ulysses", "allgather")] # the default backend: autofor name, method in captured.items():assert method is not plain[name] and method.__wrapped__ is plain[name]@@ -1410,7 +1412,7 @@ def test_a_trainer_built_before_cp_still_restores_the_accelerator_state(monkeypaassert early._context_parallel_manager is Noneearly.accelerator = types.SimpleNamespace(state = types.SimpleNamespace(device_mesh = None))Trainer(None, args = args) # enables CP: installs the class wrappers- assert built == [(2, "ring", "allgather")]+ assert built == [(2, "ulysses", "allgather")] # the default backend: autorestored.clear()assert early.train() == "trained"assert restored == [early.accelerator.state]diff --git a/tests/test_context_parallel_compose_refusal.py b/tests/test_context_parallel_compose_refusal.pyindex e1bfa49b711..85213c4c1ff 100644--- a/tests/test_context_parallel_compose_refusal.py+++ b/tests/test_context_parallel_compose_refusal.py@@ -4,6 +4,7 @@"""Context parallelism beside UNSLOTH_TP_SIZE (or a model split by hand) is refused before the trainer __init__,without a process group (tests/test_parallel_cp_compose_gloo.py trains the layouts on gloo ranks)."""+import functoolsimport typesimport pytest@@ -135,3 +136,186 @@ def test_cp_with_a_tp_env_value_tp_env_rejects_is_left_to_tp_env(clean_env, monkexcept Exception:passassert len(inits) == 1+++def test_env_cp_survives_plain_training_arguments(clean_env):+ # Failing before: the env cp size was set as an attribute of plain TrainingArguments, which Unsloth's trainer+ # wrapper rebuilds from to_dict() (dropping it): the trainer silently ran without context parallelism.+ from transformers import TrainingArguments++ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ args = TrainingArguments(output_dir = "unused", report_to = "none")+ kwargs = {}+ assert cp._inject_env_cp(args, kwargs, 1, "SFTTrainer") == 2+ assert kwargs.get("context_parallel_size") == 2+ assert "context_parallel_size" not in args.to_dict()+++def test_env_cp_sets_trl_style_configs_in_place(clean_env):+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ config = _config(1)+ kwargs = {}+ assert cp._inject_env_cp(config, kwargs, 1, "SFTTrainer") == 2+ assert config.context_parallel_size == 2 and "context_parallel_size" not in kwargs+++def test_env_cp_with_positional_plain_training_arguments_becomes_a_keyword(clean_env, monkeypatch):+ # Failing before: SFTTrainer(model, TrainingArguments(...)) got context_parallel_size as a kwarg while the+ # config stayed positional; Unsloth's trainer wrapper folds cp kwargs only into a keyword `args`, so the+ # original __init__ raised "unexpected keyword argument".+ import trl+ from transformers import TrainingArguments++ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ monkeypatch.setattr(cp, "_check_cp_runtime", lambda *a, **k: None)+ monkeypatch.setattr(cp, "_resolve_auto_backend", lambda *a, **k: None)+ monkeypatch.setattr(cp, "_refuse_model_parallel_cp", lambda *a, **k: None)+ calls = []++ def signature(+ self,+ model = None,+ args = None,+ data_collator = None,+ **kwargs,+ ):+ pass++ # As Unsloth's trainer wrapper: (*args, **kwargs) behind functools.wraps of the real signature.+ @functools.wraps(signature)+ def init(self, *args, **kwargs):+ calls.append((args, kwargs))++ class Trainer:+ __init__ = init++ monkeypatch.setattr(trl, "SFTTrainer", Trainer)+ cp.patch_sft_trainer()+ model, training_args = (+ torch.nn.Linear(2, 2),+ TrainingArguments(output_dir = "unused", report_to = "none"),+ )+ try:+ trl.SFTTrainer(model, training_args)+ except Exception:+ pass # past the original __init__ the CP setup needs a process group+ assert calls, "the original __init__ never ran"+ got_args, got_kwargs = calls[0]+ assert got_args == () and got_kwargs["model"] is model and got_kwargs["args"] is training_args+ assert got_kwargs.get("context_parallel_size") == 2+++def test_a_backend_kwarg_overrides_the_config_in_the_pre_init_check(clean_env, monkeypatch):+ # Failing before: the capability check read the config's backend (ring) although the constructor kwarg+ # (ulysses) is what the trainer uses, refusing a valid ulysses + packing call.+ import unsloth.parallel_capabilities as caps++ seen = []+ monkeypatch.setattr(+ caps, "check_layout", lambda *a, cp_backend = None, **k: seen.append(cp_backend)+ )+ cp._refuse_model_parallel_cp(2, torch.nn.Linear(2, 2), None, _config(2), backend = "ulysses")+ assert seen == ["ulysses"]+++def test_env_cp_dpo_with_a_positional_reference_model_gets_a_config(clean_env, monkeypatch):+ # Failing before: DPOTrainer(model, ref_model, ...) skipped the default config (two positionals), so the env+ # cp values reached the constructor as kwargs, which TRL rejects.+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ monkeypatch.setattr(cp, "_check_cp_runtime", lambda *a, **k: None)+ monkeypatch.setattr(cp, "_resolve_auto_backend", lambda *a, **k: None)+ monkeypatch.setattr(cp, "_refuse_model_parallel_cp", lambda *a, **k: None)+ import dataclasses+ import sys++ @dataclasses.dataclass+ class DPOConfig:+ context_parallel_size: int = 1+ context_parallel_backend: str = "auto"++ module = types.ModuleType("fake_dpo_module")+ module.DPOConfig = DPOConfig+ monkeypatch.setitem(sys.modules, "fake_dpo_module", module)+ calls = []++ def signature(+ self,+ model = None,+ ref_model = None,+ args = None,+ train_dataset = None,+ **kwargs,+ ):+ pass++ @functools.wraps(signature)+ def init(self, *args, **kwargs):+ calls.append((args, kwargs))++ Trainer = type("DPOTrainer", (), {"__init__": init, "__module__": "fake_dpo_module"})+ cp.patch_rl_trainer(Trainer, "dpo_trainer")+ model, ref = torch.nn.Linear(2, 2), torch.nn.Linear(2, 2)+ try:+ Trainer(model, ref, train_dataset = [])+ except Exception:+ pass+ assert calls+ got_args, got_kwargs = calls[0]+ assert got_kwargs.get("ref_model") is ref and "context_parallel_size" not in got_kwargs+ assert (+ isinstance(got_kwargs.get("args"), DPOConfig)+ and got_kwargs["args"].context_parallel_size == 2+ )+++def test_auto_backend_reads_a_model_id_config_with_the_loader_options(clean_env, monkeypatch):+ # Failing before: only trust_remote_code was forwarded, so a checkpoint under a subfolder was not found and+ # 'auto' committed to ulysses with unknown heads.+ import unsloth.trainer as trainer_mod++ seen = []+ monkeypatch.setattr(+ trainer_mod,+ "_resolve_string_model_config",+ lambda name, config: seen.append((name, config)) or None,+ )+ config = _config(2, model_init_kwargs = {"subfolder": "weights"})+ config.context_parallel_backend = "auto"+ try:+ cp._resolve_auto_backend(config, {}, 2, "org/model")+ except Exception:+ pass+ assert seen and seen[0][0] == "org/model" and seen[0][1] is config+++def test_config_field_kwargs_override_the_config_in_the_pre_init_check(clean_env, monkeypatch):+ # Failing before: SFTTrainer(..., args = config, router_aux_loss_coef = 0.0) was checked against the config's+ # own value, refusing a layout the trainer would run (the wrapper moves the kwarg into the config).+ import trl++ seen = []+ monkeypatch.setattr(cp, "_check_cp_runtime", lambda *a, **k: None)+ monkeypatch.setattr(cp, "_resolve_auto_backend", lambda *a, **k: None)+ monkeypatch.setattr(+ cp,+ "_refuse_model_parallel_cp",+ lambda size, model, cls, config, **k: seen.append(config.router_aux_loss_coef),+ )++ class Trainer:+ def __init__(+ self,+ model = None,+ args = None,+ **kwargs,+ ):+ pass++ monkeypatch.setattr(trl, "SFTTrainer", Trainer)+ cp.patch_sft_trainer()+ config = _config(2, router_aux_loss_coef = None)+ try:+ trl.SFTTrainer(model = torch.nn.Linear(2, 2), args = config, router_aux_loss_coef = 0.0)+ except Exception:+ pass+ assert seen == [0.0]diff --git a/tests/test_muon_dtensor_gloo.py b/tests/test_muon_dtensor_gloo.pynew file mode 100644index 00000000000..c962aecef48--- /dev/null+++ b/tests/test_muon_dtensor_gloo.py@@ -0,0 +1,62 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""torch.optim.Muon on Shard(0) DTensors (native FSDP2 / tensor parallel parameters) steps the whole matrix,+which is why the registry lets it through: a step on the local shards alone lands far from it."""++import multiprocessing+import os+import sys+import tempfile++import pytest+import torch++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_pp_native_gloo import _free_port # noqa: E402+++def _worker(rank, world, port, tmp):+ os.environ.update(MASTER_ADDR = "127.0.0.1", MASTER_PORT = str(port))+ import torch.distributed as dist+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.tensor import Shard, distribute_tensor++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ mesh = init_device_mesh("cpu", (world,))+ torch.manual_seed(0)+ w, g = torch.randn(64, 32), torch.randn(64, 32)+ whole = torch.nn.Parameter(w.clone())+ whole.grad = g.clone()+ torch.optim.Muon([whole], lr = 0.1).step()+ shard = torch.nn.Parameter(distribute_tensor(w.clone(), mesh, [Shard(0)]))+ shard.grad = distribute_tensor(g.clone(), mesh, [Shard(0)])+ torch.optim.Muon([shard], lr = 0.1).step()+ local = torch.nn.Parameter(w.clone().chunk(world)[rank])+ local.grad = g.clone().chunk(world)[rank]+ torch.optim.Muon([local], lr = 0.1).step()+ update = whole.detach() - w+ dtensor = (shard.detach().full_tensor() - whole.detach()).norm() / update.norm()+ mine = whole.detach().chunk(world)[rank]+ per_shard = (local.detach() - mine).norm() / update.chunk(world)[rank].norm()+ torch.save((float(dtensor), float(per_shard)), os.path.join(tmp, f"r{rank}.pt"))+ finally:+ dist.destroy_process_group()+++def test_torch_muon_steps_dtensor_shards_as_whole_matrices():+ if getattr(torch.optim, "Muon", None) is None:+ pytest.skip("torch.optim.Muon needs torch >= 2.9")+ ctx = multiprocessing.get_context("spawn")+ port = _free_port()+ with tempfile.TemporaryDirectory() as tmp:+ procs = [ctx.Process(target = _worker, args = (r, 2, port, tmp)) for r in range(2)]+ for p in procs:+ p.start()+ for p in procs:+ p.join(300)+ assert [p.exitcode for p in procs] == [0, 0]+ dtensor, per_shard = torch.load(os.path.join(tmp, "r0.pt"))+ # Newton-Schulz runs in bfloat16: the DTensor step matches the whole-matrix step to bf16 noise, the shard step does not.+ assert dtensor < 0.05 and per_shard > 0.2, (dtensor, per_shard)diff --git a/tests/test_parallel_cp_compose_gloo.py b/tests/test_parallel_cp_compose_gloo.pyindex 90a7c60e00c..62db8ec2592 100644--- a/tests/test_parallel_cp_compose_gloo.py+++ b/tests/test_parallel_cp_compose_gloo.py@@ -1,15 +1,21 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""Ulysses CP beside DDP, FSDP2 and TP through SFTTrainer on gloo CPU ranks vs one process (losses, grads,-adapters); cp x tp is refused. CPU ranks use the HF attention with the hybrids' Ulysses wrapper, the rest is-the production path."""+"""Context parallel (Ulysses) composed with tensor / pipeline parallel through SFTTrainer, on a gloo CPU world, vs+the same script in one process: losses, per-parameter gradients of the first optimizer step and the adapters+after the run.++CPU ranks cannot run Unsloth's fast Llama attention (it needs CUDA), so the attention is the Hugging Face one with+the Ulysses wrapper hybrids use (utils/ulysses_hybrid.install_hf_attention_wrapper), and the model support check is+opened for it. Everything else (the env layout, the mesh, tensor parallel, the CP sharding, the token count and+the gradient reduction) is the production path."""import multiprocessingimport os-if multiprocessing.parent_process() is not None or getattr(- multiprocessing.current_process(), "_inheriting", False+if os.environ.get("UNSLOTH_TEST_RANKS_ON_GPU") != "1" and (+ 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@@ -44,20 +50,116 @@ SEQ = 16N_LAYERS = 4-def _checkpoint(tmp):- # 4 heads / 4 kv heads: tp 2 leaves 2 local heads, which Ulysses splits over cp 2.- path = _save_checkpoint("llama", os.path.join(tmp, "ckpt"), {"num_hidden_layers": N_LAYERS})+def _checkpoint(tmp, arch = "llama"):from transformers import AutoTokenizer- from test_tp_native_oracle import LLAMA-+ from test_tp_native_oracle import LLAMA, QWEN3, QWEN3_MOE, build++ if arch in ("qwen3_moe", "qwen3", "qwen3_moe_wide"):+ # qwen3_moe: 4 heads / 2 kv heads, 4 experts (2 per token), router aux loss off as shipped.+ # qwen3_moe_wide: hidden and expert widths of 32, so Unsloth's Triton grouped GEMM takes the experts (it+ # needs multiples of 16; the shipped hidden size 8 sends unsloth_triton to torch._grouped_mm).+ repo = QWEN3 if arch == "qwen3" else QWEN3_MOE+ overrides = {"num_hidden_layers": 2}+ if arch == "qwen3_moe_wide":+ overrides.update(hidden_size = 32, moe_intermediate_size = 32)+ path = os.path.join(tmp, "ckpt")+ model = build(repo, overrides, lora = False)+ model.generation_config.pad_token_id = None+ model.save_pretrained(path, safe_serialization = True)+ AutoTokenizer.from_pretrained(repo).save_pretrained(path)+ return path+ # 4 heads / 4 kv heads: tp 2 leaves 2 local heads, which Ulysses splits over cp 2.+ path = _save_checkpoint("llama", os.path.join(tmp, "ckpt"), {"num_hidden_layers": N_LAYERS})AutoTokenizer.from_pretrained(LLAMA).save_pretrained(path)return pathdef _full(t):from torch.distributed.tensor import DTensor- return (t.full_tensor() if isinstance(t, DTensor) else t).detach().float().clone()+ return (t.full_tensor() if isinstance(t, DTensor) else t).detach().float().cpu().clone()+++def _block_compile_on_cpu(model):+ """Unsloth's block compile (one torch.compile region per decoder layer) on CPU ranks: its CUDA gate opened+ and the aot_eager backend instead of inductor. Graph breaks and recompiles are Dynamo's, so they count the+ same; the generated kernels are not under test here."""+ from unsloth.models import _block_compile as bc++ real_compile = torch.compile++ def compile_aot_eager(fn, **kwargs):+ kwargs.pop("options", None)+ kwargs["backend"] = "aot_eager"+ return real_compile(fn, **kwargs)++ available = torch.cuda.is_available+ bc.torch.cuda.is_available = lambda: True+ bc.torch.compile = compile_aot_eager+ try:+ return bc.patch_block_compile(model)+ finally:+ bc.torch.cuda.is_available = available+ bc.torch.compile = real_compile+++def _selected_moe_backend():+ try:+ from unsloth_zoo.temporary_patches import moe_utils+ return moe_utils.select_moe_backend()+ except Exception as e:+ return f"unknown: {e!r}"[:200]+++def _count_moe_backend_calls():+ """Engagement for GPU MoE cells: calls into each Unsloth Zoo expert backend and into torch._grouped_mm."""+ import collections++ calls = collections.Counter()+ try:+ from unsloth_zoo.temporary_patches import moe_utils+ except Exception:+ return calls+ modules = [moe_utils]+ try:+ cached = moe_utils._load_cached_moe_utils_module()+ if cached is not None and cached is not moe_utils:+ modules.append(cached)+ except Exception:+ pass+ try:+ from unsloth_zoo.temporary_patches import moe_utils_bnb4bit+ modules.append(moe_utils_bnb4bit)+ except Exception:+ pass++ def counted(name, fn):+ def wrapper(*a, **k):+ calls[name] += 1+ return fn(*a, **k)++ wrapper.__wrapped__ = fn+ return wrapper++ for module in modules:+ for name in (+ "forward_native_grouped_mm",+ "forward_triton_grouped_gemm",+ "forward_native_moe_loop",+ "forward_moe_backend_bnb4bit",+ "_triton_grouped_mm",+ "_manual_grouped_mm",+ ):+ if callable(getattr(module, name, None)):+ setattr(module, name, counted(name, getattr(module, name)))+ try:+ from unsloth.kernels.moe.grouped_gemm import interface+ interface.grouped_gemm = counted("unsloth grouped_gemm (Triton)", interface.grouped_gemm)+ except Exception:+ pass+ if hasattr(torch, "_grouped_mm"):+ torch._grouped_mm = counted("torch._grouped_mm", torch._grouped_mm)+ return callsdef _case_train(@@ -71,7 +173,16 @@ def _case_train(ga = 2,sft_cp = True,keep = False,- rows_dp = None,+ compile = False,+ arch = "llama",+ router_aux = False,+ attn = "sdpa",+ ungate = False,+ mode = "lora",+ trl_aux = False,+ device = "cpu",+ bypass_pre = False,+ bypass_post = False,):error = _import_checkout_unsloth()if error is not None:@@ -83,18 +194,50 @@ def _case_train(from transformers import AutoModelForCausalLM, AutoTokenizerfrom unsloth import context_parallel as cpm- from unsloth.models import fsdp2_native, pp_native, tp_env, tp_native+ from unsloth.models import pp_native, tp_env, tp_nativefrom unsloth.models._utils import patch_gradient_accumulation_fixfrom unsloth.utils.ulysses_hybrid import install_hf_attention_wrapperpatch_gradient_accumulation_fix(transformers.Trainer)cpm.patch_sft_trainer()- cpm.DEVICE_TYPE_TORCH = "cpu"+ if device == "cpu":+ cpm.DEVICE_TYPE_TORCH = "cpu"+ else: # NCCL ranks under torchrun (scripts/local_correctness.py): one GPU each+ if torch.cuda.device_count() < world:+ # Correctness only: every rank shares the one card (a one-GPU cloud VM). NCCL >= 2.32 takes that with+ # NCCL_MULTI_RANK_GPU_ENABLE=1 (the driver probes it), else gloo on CUDA tensors.+ os.environ["LOCAL_RANK"], os.environ["LOCAL_WORLD_SIZE"] = "0", "1"+ import torch.distributed as dist+ if world > 1 and not dist.is_initialized():+ dist.init_process_group(os.environ.get("UNSLOTH_TEST_SHARED_GPU_BACKEND", "gloo"))+ torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", "0")))+ # fp32 like the CPU reference: no TF32 matmuls / convolutions (Unsloth may have allowed them).+ torch.backends.cuda.matmul.allow_tf32 = False+ torch.backends.cudnn.allow_tf32 = False+ torch.set_float32_matmul_precision("highest")+ # The math SDPA kernel: deterministic fp32 (the fused ones differ in the last bits per head count).+ torch.backends.cuda.enable_flash_sdp(False)+ torch.backends.cuda.enable_mem_efficient_sdp(False)+ torch.backends.cuda.enable_cudnn_sdp(False)+ torch.use_deterministic_algorithms(True, warn_only = True)# The test seam: CPU ranks run the Hugging Face attention through the Ulysses wrapper.cpm._supports_context_parallel = lambda model, backend = "ring": True+ if bypass_pre or bypass_post:+ # Evidence runs only: switch off the aux-loss guards to show what each one catches.+ from unsloth import parallel_capabilities+ if bypass_pre:+ parallel_capabilities._aux_loss_on = lambda *a, **k: False+ if bypass_post:+ cpm._refuse_router_aux_loss_after_init = lambda *a, **k: None+ if ungate:+ # Measure a cell the registry refuses for lack of evidence (the evidence run itself).+ from unsloth import parallel_capabilities+ parallel_capabilities._gated = lambda query: Falsefrom unsloth.utils import attention_dispatch- attention_dispatch.HAS_XFORMERS = False # CUDA only: torch SDPA on the CPU ranks+ attention_dispatch.HAS_XFORMERS = (+ False # torch SDPA on every rank (fp32: flash / xformers take 16-bit)+ )attention_dispatch.HAS_FLASH_ATTENTION = Falselayout = tp_env.env_layout()@@ -103,8 +246,19 @@ def _case_train(load_in_4bit = True,**kwargs,):+ extra = {}+ if mode == "qlora":+ from transformers import BitsAndBytesConfig+ extra = dict(+ quantization_config = BitsAndBytesConfig(+ load_in_4bit = True,+ bnb_4bit_quant_type = "nf4",+ bnb_4bit_compute_dtype = torch.float32,+ ),+ device_map = {"": torch.cuda.current_device()},+ )return AutoModelForCausalLM.from_pretrained(- model_name, torch_dtype = torch.float32, attn_implementation = "sdpa"+ model_name, torch_dtype = torch.float32, attn_implementation = attn, **extra)def peft(model):@@ -120,22 +274,32 @@ def _case_train(load = tp_env.tensor_parallel_env_load(load)peft = tp_env.tensor_parallel_env_peft(peft)- model = peft(load(ckpt, load_in_4bit = False))+ model = load(ckpt, load_in_4bit = False)+ if mode in ("lora", "qlora"):+ model = peft(model)+ else:+ model.train()+ count = device != "cpu" or os.environ.get("UNSLOTH_TEST_COUNT_MOE") == "1"+ moe_calls = _count_moe_backend_calls() if count else None+ if router_aux:+ model.config.output_router_logits = Truefor name, module in model.named_modules():if name.endswith("self_attn"):install_hf_attention_wrapper(module, "sdpa", cpm.get_cp_manager)+ compiled = _block_compile_on_cpu(model) if compile else []- dp = 1 if layout is None else layout.dp- data_dp = getattr(layout, "data_dp", dp) if layout is not None else 1- if rows_dp is not None: # DDP / native FSDP2 (no tp layout): the data parallel width- data_dp = rows_dp+ # Data parallel replicas read different rows; cp / tp / pp peers share theirs.+ model_ranks = cp * (1 if layout is None else layout.tp * layout.pp)+ data_dp = world // model_ranksg = torch.Generator().manual_seed(1)ids = torch.randint(0, 1000, (steps * ga * bs * data_dp, SEQ), generator = g)import datasets- data = datasets.Dataset.from_dict({"input_ids": ids.tolist()})+ data = datasets.Dataset.from_dict({"input_ids": ids.tolist(), "row": list(range(len(ids)))})+ rows_read = [] # dataset row ids per micro-batch, in order: parity needs the same rows on both sidesdef collate(rows):+ rows_read.append([int(r["row"]) for r in rows])input_ids = torch.tensor([r["input_ids"] for r in rows])batch = {"input_ids": input_ids, "labels": input_ids.clone()}batch["labels"][@@ -180,7 +344,7 @@ def _case_train(logging_steps = 1,save_strategy = "no",report_to = [],- use_cpu = True,+ use_cpu = device == "cpu",seed = 0,dataloader_drop_last = True,remove_unused_columns = False,@@ -188,9 +352,21 @@ def _case_train(dataset_kwargs = {"skip_prepare_dataset": True},gradient_checkpointing = False,)+ if device != "cpu" and torch.cuda.device_count() < world:+ args.ddp_backend = os.environ.get("UNSLOTH_TEST_SHARED_GPU_BACKEND", "gloo")+ if hasattr(args, "router_aux_loss_coef"):+ # TRL turns the MoE load balancing loss on from the architecture's coefficient unless this is 0.0+ # (it then sets output_router_logits on the config itself): aux off unless the case asks for it.+ args.router_aux_loss_coef = None if (router_aux or trl_aux) else 0.0if sft_cp:args.context_parallel_size = cpargs.context_parallel_backend = "ulysses"+ if device != "cpu":+ # Pure fp32 like the CPU reference. SFTConfig defaults to bf16 = True, and Unsloth's trainer turns+ # bf16 = fp16 = False on a float32 model into bf16 autocast on a bf16 GPU, so both flags alone are not+ # enough: the stamp below is the per-model "train this one in float32" switch the trainer honours.+ args.bf16 = args.fp16 = False+ model._unsloth_forced_float32 = Truetokenizer = AutoTokenizer.from_pretrained(ckpt)trainer = SequentialSFT(model = model,@@ -200,10 +376,19 @@ def _case_train(processing_class = tokenizer,callbacks = [Grabber()],)+ if device != "cpu":+ assert trainer.accelerator.mixed_precision == "no", trainer.accelerator.mixed_precisionmanager = getattr(trainer, "_context_parallel_manager", None)seen_lengths, ulysses_calls = set(), []embed = trainer.model.get_input_embeddings()embed.register_forward_pre_hook(lambda m, a: seen_lengths.add(int(a[0].shape[-1])))+ autocast_seen = (+ set()+ ) # autocast state inside every training forward (pure fp32 cells: {False} only)+ autocast_device = "cpu" if device == "cpu" else "cuda"+ embed.register_forward_pre_hook(+ lambda m, a: autocast_seen.add(bool(torch.is_autocast_enabled(autocast_device)))+ )from unsloth.utils import ulysses_hybridoriginal_ulysses = ulysses_hybrid._ulysses_hf_attention@@ -212,14 +397,27 @@ def _case_train(ulysses_calls.append(1)return original_ulysses(*a, **k)- ulysses_hybrid._ulysses_hf_attention = counted+ if not compile:+ # A Python counter inside a compiled region would be guarded on (a recompile per call).+ ulysses_hybrid._ulysses_hf_attention = counted+ from unsloth.utils import compile_counters++ torch._dynamo.reset()+ before = compile_counters.snapshot()trainer.train()+ compile_used = compile_counters.since(before)+ if device != "cpu":+ assert autocast_seen == {False}, ("a GPU cell ran under autocast", autocast_seen)logs = [h for h in trainer.state.log_history if "loss" in h]is_tp = tp_native.is_tensor_parallel(trainer.model)if is_tp:state = tp_native.tp_full_state_dict(trainer.model, adapters_only = True)else:- state = {k: _full(v) for k, v in trainer.model.state_dict().items() if "lora_" in k}+ state = {+ k: _full(v)+ for k, v in trainer.model.state_dict().items()+ if "lora_" in k or mode == "full"+ }stage = pp_native.pipeline_stage_of(trainer.model)res = {"layout": None if layout is None else repr(layout),@@ -229,16 +427,32 @@ def _case_train("state": {k.replace("module.", "").replace("_orig_mod.", ""): _full(v)for k, v in state.items()- if "lora_" in k+ if "lora_" in k or mode == "full"},"cp_group": Noneif manager is Noneelse sorted(int(r) for r in manager.mesh.mesh.flatten().tolist()),"is_tp": is_tp,- "is_fsdp2": fsdp2_native.is_native_fsdp2(trainer.model),- "seen_lengths": sorted(seen_lengths),- "ulysses_calls": len(ulysses_calls),"stage": None if stage is None else int(stage.stage_index),+ "seen_lengths": sorted(seen_lengths),+ "autocast_seen": sorted(autocast_seen),+ "ulysses_calls": None if compile else len(ulysses_calls),+ "cp_backend": None if manager is None else manager.backend,+ "epoch": float(trainer.state.epoch or 0.0),+ "rows_read": rows_read,+ "dataset_rows": len(data),+ "ga": ga,+ "compiled_classes": [getattr(c, "__name__", c) for c in compiled],+ "native_fsdp2": __import__("unsloth.models.fsdp2_native", fromlist = ["x"]).is_native_fsdp2(+ trainer.model+ ),+ "banner": trainer.__dict__.get("_unsloth_parallel_announced"),+ "output_router_logits": bool(getattr(trainer.model.config, "output_router_logits", False)),+ "compile": compile_used,+ "moe_calls": None if moe_calls is None else dict(moe_calls),+ "moe_backend": _selected_moe_backend(),+ "device_name": torch.cuda.get_device_name() if device != "cpu" else "cpu",+ "dist_backend": dist.get_backend() if dist.is_initialized() else None,}if dist.is_initialized():dist.barrier()@@ -287,7 +501,7 @@ def _spawn(ctx = multiprocessing.get_context("spawn")port = _free_port()with tempfile.TemporaryDirectory() as tmp:- kwargs["ckpt"] = _checkpoint(tmp)+ kwargs["ckpt"] = _checkpoint(tmp, kwargs.get("arch", "llama"))procs = [ctx.Process(target = _worker, args = (r, world, port, case, tmp, env or {}, kwargs))for r in range(world)@@ -315,11 +529,48 @@ def _spawn(_REF = {}-def _ref(bs):- if bs not in _REF:- (_REF[bs],) = _spawn("train", 1, bs = bs)- assert "error" not in _REF[bs], _REF[bs]- return _REF[bs]+def _ref(+ bs,+ compile = False,+ arch = "llama",+ **kwargs,+):+ key = (bs, compile, arch, tuple(sorted(kwargs.items())))+ if key not in _REF:+ (_REF[key],) = _spawn("train", 1, bs = bs, compile = compile, arch = arch, **kwargs)+ assert "error" not in _REF[key], _REF[key]+ return _REF[key]+++def _rows_per_step(res):+ """The dataset rows each optimizer step trained on (one rank's view)."""+ ga, read = res["ga"], res["rows_read"]+ return [+ sorted(r for mb in read[i : i + ga] for r in mb)+ for i in range(0, len(read) - len(read) % ga, ga)+ ]+++def _same_rows(+ results,+ want,+ what = "",+):+ """Every step of the composed run trains on exactly the rows one process trains on (data parallel replicas+ split them, cp / tp / pp peers share theirs), and no side read a row twice (no second epoch)."""+ expected = _rows_per_step(want)+ flat = [r for step in expected for r in step]+ assert len(flat) == len(set(flat)), (what, "one process read a row twice", want["rows_read"])+ union = [set() for _ in expected]+ for res in results:+ for i, step in enumerate(_rows_per_step(res)[: len(expected)]):+ union[i] |= set(step)+ assert [sorted(u) for u in union] == expected, (+ what,+ "the composed run read other rows",+ union,+ expected,+ )def _close(@@ -327,8 +578,14 @@ def _close(want,rel = 1e-4,what = "",+ state_atol = 1e-6,):assert "error" not in got, (what, got.get("error"), got.get("trace"))+ # The run must read every row once and no row twice: too few rows for the data parallel replicas wrap the+ # dataloader into a second epoch, and the later steps then train on other rows than one process.+ for side in (got, want):+ if "epoch" in side:+ assert side["epoch"] <= 1.0 + 1e-6, (what, "the dataloader wrapped", side["epoch"])assert got["losses"] == pytest.approx(want["losses"], rel = rel), (what,got["losses"],@@ -346,53 +603,253 @@ def _close(sorted(set(got[kind]) - set(want[kind])),)for key, value in got[kind].items():+ atol = state_atol if kind == "state" else 1e-6torch.testing.assert_close(- value, want[kind][key], rtol = rel * 10, atol = 1e-6, msg = f"{what} {kind} {key}"+ value, want[kind][key], rtol = rel * 10, atol = atol, msg = f"{what} {kind} {key}")-def _engaged(res, cp = 2):- # Each rank embedded SEQ / cp tokens and every layer's attention went through the Ulysses exchange.- assert res["seen_lengths"] == [SEQ // cp], res["seen_lengths"]- assert res["ulysses_calls"] >= N_LAYERS, res["ulysses_calls"]--def test_cp2_alone_matches_one_process():- """The control: Ulysses cp 2 through SFTTrainer reproduces one process (losses, grads, adapters)."""+ """The harness: Ulysses cp 2 through SFTTrainer reproduces one process (losses, grads, adapters)."""ref = _ref(2)assert ref["seen_lengths"] == [SEQ] and ref["ulysses_calls"] == 0for rank, res in enumerate(_spawn("train", 2, bs = 2, cp = 2)):+ assert "error" not in res, (rank, res.get("error"), res.get("trace"))assert res["cp_group"] == [0, 1]- _engaged(res)+ assert res["seen_lengths"] == [SEQ // 2] and res["ulysses_calls"] >= N_LAYERS_close(res, ref, what = rank)def test_cp2_with_ddp_dp2_matches_one_process():"""Plain DDP x cp 2 on 4 ranks: cp peers adjacent, dp replicas averaged, same as one process on the batch."""ref = _ref(4)- for rank, res in enumerate(_spawn("train", 4, bs = 2, cp = 2, rows_dp = 2)):- assert res["cp_group"] == [rank - rank % 2, rank - rank % 2 + 1], (rank, res.get("error"))- assert not res["is_fsdp2"] and not res["is_tp"]- _engaged(res)+ for rank, res in enumerate(_spawn("train", 4, bs = 2, cp = 2)):+ assert "error" not in res, (rank, res.get("error"), res.get("trace"))+ assert res["cp_group"] == [rank - rank % 2, rank - rank % 2 + 1], (rank, res["cp_group"])+ assert not res["native_fsdp2"] and not res["is_tp"]+ assert res["seen_lengths"] == [SEQ // 2] and res["ulysses_calls"] >= N_LAYERS_close(res, ref, what = ("ddp", rank))[email protected]("world, ref_bs", [(2, 2), (4, 4)], ids = ["fsdp2_cp2", "fsdp2_dp2_cp2"])-def test_cp2_with_native_fsdp2_matches_one_process(world, ref_bs):- """UNSLOTH_FSDP2=1 x cp 2: native FSDP2 shards over every rank, the cp peers share a batch."""[email protected]("env", [{"UNSLOTH_PP_SIZE": "2"}], ids = ["pp2"])+def test_cp_with_pipeline_parallel_env_is_refused_before_the_split(env):+ for res in _spawn("train", 4, env, bs = 2, cp = 2):+ assert "does not compose with" in (res.get("error") or ""), (+ res.get("error") or res["losses"]+ )+ assert "pipeline parallel (UNSLOTH_PP_SIZE=2)" in res["error"]+++def test_cp_from_the_config_beside_a_tp_launch_is_refused_with_the_layout_hint():+ """SFTConfig(context_parallel_size = 2) under UNSLOTH_TP_SIZE=2: the layout was read without a cp axis."""+ for res in _spawn("train", 4, {"UNSLOTH_TP_SIZE": "2"}, bs = 2, cp = 2):+ error = res.get("error") or ""+ assert "does not compose with" in error and "UNSLOTH_PARALLEL" in error, (+ error or res["losses"]+ )+++ "world, flag, bs, ref_bs, layout",+ [+ (4, "tp=2,cp=2", 2, 2, "cp 2 x tp 2"),+ (8, "tp=2,cp=2", 2, 4, "dp 2 (DDP) x cp 2 x tp 2"),+ (8, "dp=2,tp=2,cp=2,fsdp=1", 2, 4, "dp 2 (native FSDP2) x cp 2 x tp 2"),+ (+ 8,+ "dp=2,tp=2,pp=1,cp=2,fsdp=1,cp_backend=ulysses",+ 2,+ 4,+ "dp 2 (native FSDP2) x cp 2 x tp 2",+ ),+ ],+ ids = ["cp2_tp2", "dp2_cp2_tp2", "fsdp2_cp2_tp2", "launcher_form"],+)+def test_cp_x_tp_from_unsloth_parallel_matches_one_process(world, flag, bs, ref_bs, layout):ref = _ref(ref_bs)- results = _spawn("train", world, {"UNSLOTH_FSDP2": "1"}, bs = 2, cp = 2, rows_dp = world // 2)+ env = {"UNSLOTH_PARALLEL": flag}+ if flag.startswith("dp=2,tp=2,pp=1"):+ # What the notebooks launcher exports: every axis, plus agreeing single-axis variables.+ env.update(UNSLOTH_FSDP2 = "1", UNSLOTH_TP_SIZE = "2", UNSLOTH_CP_SIZE = "2", UNSLOTH_PP_SIZE = "1")+ results = _spawn("train", world, env, bs = bs, cp = 2, sft_cp = False)for rank, res in enumerate(results):assert "error" not in res, (rank, res.get("trace"))- assert res["is_fsdp2"], "native FSDP2 did not engage"- assert res["cp_group"] == [rank - rank % 2, rank - rank % 2 + 1], (rank, res["cp_group"])- _engaged(res)- _close(res, ref, what = ("fsdp2", world, rank))+ assert res["layout"] == layout and res["is_tp"], res["layout"]+ # cp peers are 2 apart (tp innermost), never tp peers.+ tp_index = rank % 2+ base = rank - rank % 4+ assert res["cp_group"] == [base + tp_index, base + tp_index + 2], (rank, res["cp_group"])+ # Engaged: 'auto' picked Ulysses, each rank embedded SEQ / cp tokens, every layer's attention exchanged.+ assert res["cp_backend"] == "ulysses" and res["seen_lengths"] == [SEQ // 2], res[+ "seen_lengths"+ ]+ assert res["ulysses_calls"] >= N_LAYERS, res["ulysses_calls"]+ _close(res, ref, what = (flag, rank))-def test_cp_with_tensor_parallel_env_is_refused_before_the_split():- """UNSLOTH_TP_SIZE=2 x cp 2 on 4 ranks trained with the wrong loss (the CP groups were the tp pairs)."""- for res in _spawn("train", 4, {"UNSLOTH_TP_SIZE": "2"}, bs = 2, cp = 2):[email protected]("flag", ["pp=2,cp=2", "pp=2,tp=2,cp=2"])+def test_cp_x_pp_is_refused_by_the_registry_before_the_split(flag):+ world = 8 if "tp" in flag else 4+ for res in _spawn("train", world, {"UNSLOTH_PARALLEL": flag}, bs = 2, cp = 2, sft_cp = False):error = res.get("error") or ""- assert "does not compose with" in error, error or res["losses"]- assert "tensor parallel (UNSLOTH_TP_SIZE=2)" in error, error+ assert "cp x pp" in error and "Instead:" in error, error or res["losses"]+ assert res.get("stage") is None+++# The registry's BLOCK_COMPILE_TORCH (checked in test_parallel_env.py), read here without importing unsloth: below it+# these cells run eager (torch 2.10 recompiles more than one process).+_BLOCK_COMPILE_TORCH = (2, 13)+needs_block_compile_torch = pytest.mark.skipif(+ tuple(int(x) for x in torch.__version__.split("+")[0].split(".")[:2]) < _BLOCK_COMPILE_TORCH,+ reason = "block compile cells need torch >= 2.13 (the registry runs them eager below)",+)+++@needs_block_compile_torch+ "world, flag, ref_bs",+ [(4, "tp=2,cp=2", 2), (8, "dp=2,tp=2,cp=2,fsdp=1", 4)],+ ids = ["cp2_tp2", "fsdp2_cp2_tp2"],+)+def test_block_compile_composes_like_one_process(world, flag, ref_bs):+ """Unsloth's block compile under cp x tp: the same numbers as one eager process, every decoder layer compiled,+ and no more graph breaks / recompiles than the same compiled script in one process (Dynamo's counters)."""+ from unsloth.utils.compile_counters import not_above++ eager = _ref(ref_bs)+ single = _ref(ref_bs, compile = True)+ assert (+ single["compiled_classes"] == ["LlamaDecoderLayer"]+ and single["compile"]["unique_graphs"] > 0+ )+ _close(single, eager, what = "one process compiled")+ for rank, res in enumerate(+ _spawn("train", world, {"UNSLOTH_PARALLEL": flag}, bs = 2, cp = 2, sft_cp = False, compile = True)+ ):+ assert "error" not in res, (rank, res.get("trace"))+ assert (+ res["compiled_classes"] == ["LlamaDecoderLayer"] and res["compile"]["unique_graphs"] > 0+ )+ assert res["cp_backend"] == "ulysses" and res["seen_lengths"] == [SEQ // 2], res[+ "seen_lengths"+ ]+ assert not not_above(res["compile"], single["compile"]), (+ rank,+ res["compile"],+ single["compile"],+ )+ _close(res, eager, what = (flag, "compiled", rank))+++ "env, sft_cp",+ [({"UNSLOTH_FSDP2": "1"}, True), ({"UNSLOTH_PARALLEL": "cp=2,fsdp=1"}, False)],+ ids = ["fsdp2_env_cp_config", "unsloth_parallel"],+)+def test_cp_with_native_fsdp2_matches_one_process(env, sft_cp):+ """Native FSDP2 (UNSLOTH_FSDP2=1) never reads context_parallel_size: it must shard over the whole+ (dp_shard, cp) world so cp peers' gradients are reduced together, and the loss is normalised over dp x cp."""+ ref = _ref(4)+ for rank, res in enumerate(_spawn("train", 4, env, bs = 2, cp = 2, sft_cp = sft_cp)):+ assert "error" not in res, (rank, res.get("trace"))+ assert res["native_fsdp2"] and res["cp_group"] == [rank - rank % 2, rank - rank % 2 + 1]+ assert res["seen_lengths"] == [SEQ // 2] and res["ulysses_calls"] >= N_LAYERS+ assert "FSDP2 shards and reduces over dp_shard x cp" in (res["banner"] or ""), res["banner"]+ _close(res, ref, what = (env, rank))+++def test_dense_qwen3_under_cp_matches_one_process():+ """The control for the MoE cell below: the same family without experts trains like one process."""+ ref = _ref(2, arch = "qwen3")+ for rank, res in enumerate(_spawn("train", 2, bs = 2, cp = 2, arch = "qwen3")):+ assert "error" not in res, (rank, res.get("trace"))+ assert res["seen_lengths"] == [SEQ // 2] and res["ulysses_calls"] >= 2+ _close(res, ref, what = ("qwen3", rank))+++ "mode, world, env, cp",+ [+ ("lora", 2, {}, 1),+ ("lora", 2, {"UNSLOTH_FSDP2": "1"}, 1),+ ("lora", 2, {}, 2),+ ("lora", 4, {"UNSLOTH_FSDP2": "1"}, 2),+ ("full", 2, {"UNSLOTH_FSDP2": "1"}, 1),+ ("full", 2, {}, 2),+ ],+ ids = ["lora-ddp", "lora-fsdp2", "lora-cp2", "lora-fsdp2_cp2", "full-fsdp2", "full-cp2"],+)+def test_moe_under_data_and_context_parallel_matches_one_process(mode, world, env, cp):+ """Tiny Qwen3-MoE (4 experts, 2 per token) with the router aux loss off (router_aux_loss_coef = 0.0: TRL+ would otherwise turn it on from the architecture's coefficient): LoRA on attention, router and the experts+ (ParamWrapper), or full finetuning, under DDP / native FSDP2 / Ulysses cp, trains like one process."""+ ref = _ref(2 * world // cp, arch = "qwen3_moe", mode = mode)+ assert not ref["output_router_logits"]+ results = _spawn("train", world, env, bs = 2, cp = cp, arch = "qwen3_moe", mode = mode)+ _same_rows(results, ref, what = (mode, world, env, cp))+ for rank, res in enumerate(results):+ assert "error" not in res, (rank, res.get("trace"))+ assert not res["output_router_logits"]+ experts = [k for k in res["grads"] if ".experts." in k]+ assert experts and all(+ res["grads"][k].abs().sum() > 0 for k in experts+ ), experts # routed experts train+ if mode == "lora":+ assert any("lora_" in k for k in experts), experts+ if cp > 1:+ assert res["seen_lengths"] == [SEQ // cp] and res["ulysses_calls"] >= 2+ # Full finetuning also steps the 151936-row embedding: Adam (lr 1e-2, eps 1e-4) turns 1e-8 gradient noise+ # on a nearly unused row into a 2e-6 weight difference after two steps (losses agree to 1e-7).+ _close(+ res, ref, what = (mode, world, env, cp, rank), state_atol = 1e-5 if mode == "full" else 1e-6+ )++[email protected]("env", [{}, {"UNSLOTH_FSDP2": "1"}], ids = ["ddp", "fsdp2"])+def test_moe_with_router_aux_loss_under_ddp_matches_per_micro_batch(env):+ """The load balancing loss is per micro-batch (a product of means). Data parallel keeps each micro-batch on+ one rank, so dp 2 x accumulation 2 equals one process accumulating the same 4 micro-batches."""+ (ref,) = _spawn("train", 1, bs = 2, ga = 4, arch = "qwen3_moe", router_aux = True)+ assert ref["output_router_logits"]+ results = _spawn("train", 2, env, bs = 2, ga = 2, arch = "qwen3_moe", router_aux = True)+ _same_rows(results, ref, what = env)+ for rank, res in enumerate(results):+ assert "error" not in res, (rank, res.get("trace"))+ assert res["output_router_logits"]+ _close(res, ref, what = (env, rank))+++# LoRA on the experts is eager only under cp (the registry's qwen3_moe x lora+experts x cp row): its per instance+# ParametrizedQwen3MoeTopKRouter type guards recompile more than one process once the router capture hooks are+# installed before the first block compiles.+@needs_block_compile_torch[email protected]("mode", ["full"])+def test_moe_block_compile_under_cp_is_compile_clean(mode):+ from unsloth.utils.compile_counters import not_above++ atol = 1e-5 if mode == "full" else 1e-6 # the embedding row note in the parity test above+ ref = _ref(2, arch = "qwen3_moe", mode = mode)+ single = _ref(2, compile = True, arch = "qwen3_moe", mode = mode)+ assert single["compiled_classes"] and single["compile"]["unique_graphs"] > 0+ _close(single, ref, what = "qwen3_moe one process compiled", state_atol = atol)+ results = _spawn("train", 2, bs = 2, cp = 2, arch = "qwen3_moe", mode = mode, compile = True)+ _same_rows(results, ref, what = ("compiled", mode))+ for rank, res in enumerate(results):+ assert "error" not in res, (rank, res.get("trace"))+ assert res["compiled_classes"] and res["seen_lengths"] == [SEQ // 2]+ assert not not_above(res["compile"], single["compile"]), (res["compile"], single["compile"])+ _close(res, ref, what = ("qwen3_moe cp2 compiled", mode, rank), state_atol = atol)+++ "config_flag", [True, False], ids = ["output_router_logits", "trl_default_coef"]+)+def test_moe_with_router_aux_loss_under_cp_is_refused(config_flag):+ """Refused before the split, also when only TRL's default router_aux_loss_coef would turn the loss on."""+ for res in _spawn(+ "train", 2, bs = 2, cp = 2, arch = "qwen3_moe", router_aux = config_flag, trl_aux = True+ ):+ error = res.get("error") or ""+ assert "MoE x pp / cp" in error and "router_aux_loss_coef = 0.0" in error, (+ error or res["losses"]+ )diff --git a/tests/test_parallel_env.py b/tests/test_parallel_env.pynew file mode 100644index 00000000000..e41e9806b1f--- /dev/null+++ b/tests/test_parallel_env.py@@ -0,0 +1,1488 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""UNSLOTH_PARALLEL / unsloth.parallelize and the context parallel x tensor / pipeline parallel refusals, without a+process group (tests/test_parallel_cp_compose_gloo.py trains the composed layouts on gloo ranks)."""++import pytest+import torch++import unsloth # noqa: F401+from unsloth import context_parallel as cp++_ENV = (+ "UNSLOTH_PARALLEL",+ "UNSLOTH_TP_SIZE",+ "UNSLOTH_PP_SIZE",+ "UNSLOTH_CP_SIZE",+ "UNSLOTH_CP_BACKEND",+ "UNSLOTH_FSDP2",+ "UNSLOTH_PP_SCHEDULE",+ "UNSLOTH_PP_MICROBATCHES",+ "WORLD_SIZE",+)+++def clean_env(monkeypatch):+ import os++ from unsloth import parallel_env+ from unsloth.models import tp_env++ for key in _ENV:+ monkeypatch.delenv(key, raising = False)+ yield monkeypatch+ for key in _ENV: # what apply_parallel_env / parallelize wrote around monkeypatch+ os.environ.pop(key, None)+ parallel_env._SET_BY_PARALLELIZE[:] = [None, {}]+ tp_env._reset_env_layout()+++def _fake_sft(monkeypatch, inits):+ import trl++ class Trainer:+ def __init__(+ self,+ model = None,+ args = None,+ **kwargs,+ ):+ inits.append(model)+ self.model = model+ self.args = args++ monkeypatch.setattr(trl, "SFTTrainer", Trainer)+ cp.patch_sft_trainer()+ return Trainer+++ "env, axis",+ [+ ({"UNSLOTH_TP_SIZE": "2"}, "tensor parallel (UNSLOTH_TP_SIZE=2)"),+ ({"UNSLOTH_PP_SIZE": "2"}, "pipeline parallel (UNSLOTH_PP_SIZE=2)"),+ (+ {"UNSLOTH_PP_SIZE": "2", "UNSLOTH_TP_SIZE": "2"},+ "pipeline parallel (UNSLOTH_PP_SIZE=2) and tensor",+ ),+ ],+)[email protected]("via", ["config", "kwarg"])+def test_cp_with_tp_or_pp_env_is_refused_before_the_trainer_init(clean_env, env, axis, via):+ import types++ for key, value in env.items():+ clean_env.setenv(key, value)+ inits = []+ Trainer = _fake_sft(clean_env, inits)+ model = torch.nn.Linear(2, 2)+ if via == "config":+ call = lambda: Trainer(model = model, args = types.SimpleNamespace(context_parallel_size = 2))+ else:+ call = lambda: Trainer(+ model, types.SimpleNamespace(context_parallel_size = 1), context_parallel_size = 2+ )+ with pytest.raises(NotImplementedError, match = "does not compose with") as info:+ call()+ assert axis in str(info.value), str(info.value)+ assert inits == [], "refused after the trainer __init__ ran (the model may already be split)"+++def test_cp_alone_and_tp_without_cp_are_not_refused(clean_env):+ import types++ inits = []+ Trainer = _fake_sft(clean_env, inits)+ clean_env.setenv("UNSLOTH_TP_SIZE", "2")+ Trainer(model = torch.nn.Linear(2, 2), args = types.SimpleNamespace(context_parallel_size = 1))+ assert len(inits) == 1+++# UNSLOTH_PARALLEL parsing and translation (parallel_env).+++def test_flag_parses_every_key_and_fills_dp(clean_env):+ from unsloth import parallel_env as pe++ spec = pe.parse_parallel_spec(+ "dp=2, tp=2 ,pp=2,cp=2,cp_backend=Ulysses,fsdp=1,pp_schedule=1F1B,mb=4"+ )+ assert spec == {+ "dp": 2,+ "tp": 2,+ "pp": 2,+ "cp": 2,+ "cp_backend": "ulysses",+ "fsdp": True,+ "pp_schedule": "1f1b",+ "pp_microbatches": 4,+ }+ clean_env.setenv("WORLD_SIZE", "16")+ assert pe.translate(spec) == {+ "UNSLOTH_TP_SIZE": "2",+ "UNSLOTH_PP_SIZE": "2",+ "UNSLOTH_CP_SIZE": "2",+ "UNSLOTH_CP_BACKEND": "ulysses",+ "UNSLOTH_FSDP2": "1",+ "UNSLOTH_PP_SCHEDULE": "1f1b",+ "UNSLOTH_PP_MICROBATCHES": "4",+ }+ # dp omitted fills the world; size-1 axes write nothing.+ clean_env.setenv("WORLD_SIZE", "8")+ assert pe.translate(pe.parse_parallel_spec("tp=2")) == {"UNSLOTH_TP_SIZE": "2"}+++ "raw, match",+ [+ ("tp=0", "must be >= 1"),+ ("tp=two", "positive integer"),+ ("tp", "not key=value"),+ ("xp=2", "unknown key"),+ ("tp=2,tp=2", "twice"),+ ("pp=2,pp_schedule=interleaved", "interleaved virtual stages are not supported yet"),+ ("cp=2,cp_backend=tree", "must be one of"),+ ("fsdp=maybe", "must be 0 or 1"),+ ],+)+def test_bad_flags_name_the_bad_part(raw, match):+ from unsloth import parallel_env as pe+ with pytest.raises(ValueError, match = match):+ pe.parse_parallel_spec(raw)+++def test_world_size_and_legacy_conflicts_are_refused(clean_env):+ from unsloth import parallel_env as pe++ clean_env.setenv("WORLD_SIZE", "6")+ with pytest.raises(ValueError, match = "must divide the number of ranks"):+ pe.translate(pe.parse_parallel_spec("tp=4"))+ with pytest.raises(ValueError, match = "needs dp x pp x cp x tp = 8 ranks, but WORLD_SIZE=6"):+ pe.translate(pe.parse_parallel_spec("dp=2,tp=2,cp=2"))+ clean_env.setenv("WORLD_SIZE", "8")+ clean_env.setenv("UNSLOTH_TP_SIZE", "4")+ with pytest.raises(ValueError, match = "UNSLOTH_TP_SIZE=4 asks for something else"):+ pe.translate(pe.parse_parallel_spec("tp=2"))+ with pytest.raises(ValueError, match = "UNSLOTH_TP_SIZE=4"):+ pe.translate(pe.parse_parallel_spec("cp=2")) # tp absent means 1+ clean_env.setenv("UNSLOTH_TP_SIZE", "2")+ assert pe.translate(pe.parse_parallel_spec("tp=2"))["UNSLOTH_TP_SIZE"] == "2" # agreeing: fine+ clean_env.setenv("UNSLOTH_FSDP2", "1")+ with pytest.raises(ValueError, match = "UNSLOTH_FSDP2=1"):+ pe.translate(pe.parse_parallel_spec("tp=2,fsdp=0"))+ assert "UNSLOTH_FSDP2" not in pe.translate(+ pe.parse_parallel_spec("tp=2")+ ) # fsdp not given: left alone+++def test_apply_is_idempotent(clean_env):+ import os++ from unsloth import parallel_env as pe++ clean_env.setenv("WORLD_SIZE", "4")+ clean_env.setenv("UNSLOTH_PARALLEL", "tp=2,cp=2,cp_backend=ulysses")+ assert pe.apply_parallel_env() == {"tp": 2, "cp": 2, "cp_backend": "ulysses"}+ assert os.environ["UNSLOTH_TP_SIZE"] == "2" and os.environ["UNSLOTH_CP_SIZE"] == "2"+ assert pe.apply_parallel_env() is not None # sees its own values: no conflict+ assert pe.env_cp_size() == 2 and pe.env_cp_backend() == "ulysses"+++def test_import_unsloth_translates_the_flag_and_refuses_a_conflict(tmp_path):+ import os+ import subprocess+ import sys++ repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ code = (+ "import importlib.util, os, sys\n"+ f"sys.path.insert(0, {repo!r})\n"+ f"spec = importlib.util.spec_from_file_location('c', {os.path.join(repo, 'tests', 'conftest.py')!r})\n"+ "spec.loader.exec_module(importlib.util.module_from_spec(spec))\n"+ "import unsloth\n"+ "print(os.environ.get('UNSLOTH_TP_SIZE'), os.environ.get('UNSLOTH_CP_SIZE'), callable(unsloth.parallelize))\n"+ )+ env = {k: v for k, v in os.environ.items() if k not in _ENV}+ env.update(UNSLOTH_PARALLEL = "tp=2,cp=2", WORLD_SIZE = "4", CUDA_VISIBLE_DEVICES = "")+ out = subprocess.run(+ [sys.executable, "-c", code], env = env, capture_output = True, text = True, timeout = 600+ )+ assert out.stdout.strip().splitlines()[-1] == "2 2 True", out.stderr[-2000:]+ env["UNSLOTH_TP_SIZE"] = "4"+ out = subprocess.run(+ [sys.executable, "-c", code], env = env, capture_output = True, text = True, timeout = 600+ )+ assert (+ out.returncode != 0 and "UNSLOTH_TP_SIZE=4 asks for something else" in out.stderr+ ), out.stderr[-2000:]+++def test_parallelize_sets_the_flag_and_refuses_after_a_load(clean_env):+ import os++ import unsloth as u+ from unsloth.models import tp_env++ clean_env.setenv("WORLD_SIZE", "4")+ tp_env._reset_env_layout()+ try:+ resolved = u.parallelize(tp = 2, cp = 2)+ assert resolved == {"UNSLOTH_TP_SIZE": "2", "UNSLOTH_CP_SIZE": "2"}+ assert os.environ["UNSLOTH_PARALLEL"] == "tp=2,cp=2"+ layout = tp_env.env_layout()+ assert (layout.dp, layout.cp, layout.tp, repr(layout)) == (1, 2, 2, "cp 2 x tp 2")+ with pytest.raises(RuntimeError, match = "must run before from_pretrained"):+ u.parallelize(tp = 4)+ with pytest.raises(ValueError, match = "positive integer"):+ u.parallelize(tp = 0)+ finally:+ for key in _ENV:+ os.environ.pop(key, None)+ tp_env._reset_env_layout()+++def test_layout_rules_run_when_the_layout_is_read(clean_env):+ from unsloth.models import tp_env++ clean_env.setenv("WORLD_SIZE", "8")+ clean_env.setenv("UNSLOTH_PP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ tp_env._reset_env_layout()+ try:+ with pytest.raises(NotImplementedError, match = r"cp x pp: .* Instead: drop cp, or drop pp"):+ tp_env.env_layout()+ finally:+ tp_env._reset_env_layout()+++def test_layout_rules_read_the_env_cp_backend_before_the_load(clean_env):+ # UNSLOTH_CP_BACKEND=ring beside tensor parallel is refused when the layout is read (from_pretrained), before+ # the tensor parallel split moves any weight, not first at Trainer.__init__.+ from unsloth.models import tp_env++ clean_env.setenv("WORLD_SIZE", "4")+ clean_env.setenv("UNSLOTH_TP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_BACKEND", "ring")+ tp_env._reset_env_layout()+ try:+ with pytest.raises(NotImplementedError, match = r"cp x tp: .*ring backend"):+ tp_env.env_layout()+ clean_env.setenv("UNSLOTH_CP_BACKEND", "ulysses")+ tp_env._reset_env_layout()+ assert tp_env.env_layout().cp_backend == "ulysses"+ finally:+ tp_env._reset_env_layout()+++# UNSLOTH_CP_SIZE into the trainer arguments.+++def test_env_cp_is_injected_into_the_trainer_args(clean_env):+ import types++ inits = []+ Trainer = _fake_sft(clean_env, inits)+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_BACKEND", "ulysses")+ args = types.SimpleNamespace(context_parallel_size = 1)+ seen = {}++ def stop(self, *a, **k):+ raise RuntimeError("stop") # past the injection; the CP runtime checks need a process group++ clean_env.setattr(cp, "_check_cp_runtime", stop)+ with pytest.raises(RuntimeError, match = "stop"):+ Trainer(model = torch.nn.Linear(2, 2), args = args)+ assert args.context_parallel_size == 2 and args.context_parallel_backend == "ulysses"+ with pytest.raises(ValueError, match = "UNSLOTH_CP_SIZE=2"):+ Trainer(model = torch.nn.Linear(2, 2), args = types.SimpleNamespace(context_parallel_size = 4))+ del seen+++# context_parallel_backend = 'auto'.+++ "heads, kv, size, tp, rl, want",+ [+ (4, 4, 2, 1, False, "ulysses"),+ (4, 2, 4, 1, False, "ulysses"), # kv heads replicated+ (6, 6, 4, 1, False, "ring"), # heads do not divide cp+ (4, 4, 4, 2, False, "ring"), # 2 heads per tp rank, cp 4+ (4, 4, 2, 2, False, "ulysses"),+ (6, 6, 4, 1, True, "ulysses"), # RL: Ulysses only (then refused on the heads)+ (None, None, 2, 1, False, "ulysses"), # unknown model+ ],+)+def test_auto_backend(heads, kv, size, tp, rl, want):+ import types++ config = types.SimpleNamespace(num_attention_heads = heads, num_key_value_heads = kv)+ model = types.SimpleNamespace(config = config) if heads else None+ assert cp.resolve_cp_backend("auto", size, model, tp = tp, rl = rl) == want+ assert cp.resolve_cp_backend(None, size, model, tp = tp, rl = rl) == want+ assert cp.resolve_cp_backend("ring", size, model) == "ring" # explicit: as given+ assert cp.resolve_cp_backend("ulysses", size, model) == "ulysses"+++def _auto_packing(monkeypatch, config, model):+ from types import SimpleNamespace++ import unsloth.trainer as trainer_module++ class _Stub:+ def __init__(+ self,+ model = None,+ args = None,+ **kwargs,+ ):+ self.model, self.args = model, args++ for name in ("enable_padding_free_metadata", "enable_sample_packing"):+ monkeypatch.setattr(trainer_module, name, lambda model, trainer: None)+ module = SimpleNamespace(SFTTrainer = _Stub)+ trainer_module._patch_sft_trainer_auto_packing(module)+ return module.SFTTrainer(model = model, args = config)+++class _Packable(torch.nn.Module):+ def __init__(self, heads):+ super().__init__()+ import types++ self.config = types.SimpleNamespace(+ num_attention_heads = heads, num_key_value_heads = heads, model_type = "llama"+ )+ self.lin = torch.nn.Linear(2, 2)++ def forward(+ self,+ input_ids = None,+ packed_seq_lengths = None,+ **kwargs,+ ):+ return input_ids+++def test_auto_keeps_packing_and_ring_turns_it_off(monkeypatch):+ # Ring packing keeps its released behaviour (packing off with a notice), never a new refusal.+ from types import SimpleNamespace++ packed = lambda backend: SimpleNamespace(+ packing = True,+ padding_free = None,+ max_length = 64,+ context_parallel_size = 2,+ context_parallel_backend = backend,+ )+ config = packed("auto")+ _auto_packing(monkeypatch, config, _Packable(4))+ assert config.packing is True, "auto (Ulysses) must keep packing on"+ config = packed("ring")+ _auto_packing(monkeypatch, config, _Packable(4))+ assert config.packing is False and config.padding_free is False+ config = packed("auto")+ config._unsloth_cp_backend_auto = True+ _auto_packing(monkeypatch, config, _Packable(3))+ assert config.packing is False+++def test_parallelize_refuses_a_legacy_variable_that_disagrees(clean_env):+ import unsloth as u+ clean_env.setenv("UNSLOTH_TP_SIZE", "4")+ with pytest.raises(ValueError, match = "UNSLOTH_TP_SIZE=4"):+ u.parallelize(tp = 2)+++# The capability registry (parallel_capabilities).+++def _q(**kw):+ from unsloth.parallel_capabilities import Query++ base = dict(trainer = "sft", family = "llama", torch = (2, 13), dp = 1)+ base.update(kw)+ return Query(**base)+++def test_tensor_parallel_alone_keeps_what_tp_native_supports():+ """Tensor parallel trains full finetuning and MoE models by itself (models/tp_native.py and its gloo+ tests): the registry reports those layouts and runs them; only their compositions it has no row for refuse."""+ from unsloth import parallel_capabilities as caps++ for extra in (dict(mode = "full"), dict(moe = True, family = "qwen3_moe")):+ assert caps.cell_status(_q(tp = 2, **extra))[0] in ("single", "unverified"), extra+ caps.check(_q(tp = 2, **extra))+ with pytest.raises(NotImplementedError, match = r"^Unsloth: pp x mode"):+ caps.check(_q(pp = 2, mode = "full"))+++ "query, axis, instead",+ [+ (dict(pp = 2, cp = 2), "cp x pp", "drop cp, or drop pp"),+ (dict(pp = 2, tp = 2, cp = 2), "cp x pp", "drop cp, or drop pp"),+ (dict(tp = 2, cp = 2, cp_backend = "ring"), "cp x tp", "cp_backend=ulysses"),+ (+ dict(tp = 2, cp = 2, cp_backend = "ulysses", trainer = "grpo"),+ "cp x tp",+ "run DPO / GRPO with cp alone",+ ),+ (dict(tp = 2, cp = 2, cp_backend = "ulysses", hybrid = True), "cp x tp", "drop tp"),+ (dict(tp = 2, cp = 2, cp_backend = "ulysses", packing = True), "cp x tp", "packing = False"),+ (dict(tp = 2, cp = 2, cp_backend = "ulysses", mode = "full"), "cp x tp", "use LoRA"),+ (dict(cp = 2, cp_backend = "ring", packing = True), "cp backend", "cp_backend=ulysses"),+ (dict(cp = 2, cp_backend = "ring", hybrid = True), "cp backend", "cp_backend=ulysses"),+ (dict(cp = 2, cp_backend = "ring", trainer = "dpo"), "cp backend", "cp_backend=ulysses"),+ (dict(cp = 2, cp_backend = "ring", sm = 7), "cp backend", "cp_backend=ulysses"),+ (dict(cp = 2, cp_backend = "ulysses", windowed = True), "cp x attention", "drop cp"),+ (dict(cp = 2, torch = (2, 6)), "cp x torch", "upgrade torch"),+ (dict(pp = 2, trainer = "grpo"), "pp x trainer", "drop pp"),+ (dict(pp = 2, packing = True), "pp x packing", "packing = False"),+ (dict(pp = 2, mode = "full"), "pp x mode", "use LoRA, or UNSLOTH_FSDP2=1"),+ (dict(tp = 2, vllm = True), "pp / tp x vLLM", "fast_inference = False"),+ ],+)+def test_every_refusal_names_its_axis_and_the_alternative(query, axis, instead):+ from unsloth import parallel_capabilities as caps++ with pytest.raises(NotImplementedError) as info:+ caps.check(_q(**query))+ message = str(info.value)+ assert message.startswith(f"Unsloth: {axis}: ") and f"Instead: {instead}" in message, message+++ "query",+ [+ dict(tp = 2, cp = 2, cp_backend = "ulysses"),+ dict(dp = 2, tp = 2, cp = 2, cp_backend = "ulysses", fsdp2 = True),+ dict(cp = 2, cp_backend = "ulysses", packing = True, hybrid = True),+ dict(cp = 2, cp_backend = "ulysses", trainer = "grpo"),+ dict(cp = 2, cp_backend = "ring", sm = 9),+ dict(pp = 2, tp = 2, dp = 2, fsdp2 = True),+ dict(tp = 2, mode = "qlora"),+ dict(dp = 4, mode = "full", fsdp2 = True),+ ],+)+def test_supported_cells_pass(query):+ from unsloth import parallel_capabilities as caps+ caps.check(_q(**query))+++def test_registry_table_and_query_from_a_model():+ import types++ from unsloth import parallel_capabilities as caps++ table = caps.markdown_table()+ assert table.count("\n") == len(caps.RULES) + 1 and "| cp x pp |" in table+ config = types.SimpleNamespace(+ model_type = "qwen3_next",+ layer_types = ["linear_attention", "full_attention"],+ sliding_window = None,+ )+ model = types.SimpleNamespace(config = config, peft_config = {"default": 1})+ layout = types.SimpleNamespace(dp = 1, tp = 2, pp = 1, cp = 2, fsdp2 = False, cp_backend = None)+ q = caps.query_from(+ layout, None, model, types.SimpleNamespace(packing = False), cp_backend = "ulysses"+ )+ assert (q.family, q.hybrid, q.windowed, q.mode, q.cp, q.tp) == (+ "qwen3_next",+ True,+ False,+ "lora",+ 2,+ 2,+ )+ with pytest.raises(NotImplementedError, match = "hybrid"):+ caps.check(q)+++def test_cp_env_with_a_plain_trainer_is_refused(clean_env):+ import transformers++ from unsloth.models import _utils++ clean_env.setenv("UNSLOTH_CP_SIZE", "2")++ class Plain(transformers.Trainer):+ def __init__(self):+ pass++ with pytest.raises(NotImplementedError, match = r"cp x trainer: .*Plain would train every rank"):+ _utils._parallel_capabilities_pre(Plain(), Plain.__init__, (), {}, None)+++def test_banner_names_the_mesh_backend_and_batch():+ import types++ from unsloth import parallel_env as pe++ trainer = types.SimpleNamespace(+ args = types.SimpleNamespace(+ per_device_train_batch_size = 2,+ gradient_accumulation_steps = 4,+ gradient_checkpointing = False,+ ),+ model = types.SimpleNamespace(config = types.SimpleNamespace(_attn_implementation = "sdpa")),+ )+ layout = pe.ParallelLayout(2, 2, 8, True, cp = 2)+ manager = types.SimpleNamespace(size = 2, backend = "ulysses")+ line = pe.announce(trainer, layout, manager)+ assert "mesh (pp 1, dp_replicate 1, dp_shard 2, cp 2, tp 2)" in line, line+ assert "effective batch 2 x 4 accumulation x 2 data parallel = 16 rows" in line+ assert (+ "cp backend ulysses" in line+ and "attention sdpa" in line+ and "gradient checkpointing off" in line+ )+ assert pe.announce(trainer, layout, manager) is None # once per trainer+++# The modularity contract: declarations, composition from them, and evidence per cell.+++def test_every_contract_axis_has_declared_features():+ from unsloth import parallel_capabilities as caps++ kinds = {f.kind for f in caps.FEATURES}+ assert {+ "parallel",+ "precision",+ "compile",+ "attention",+ "packing",+ "memory",+ "kernels",+ "loss",+ } <= kinds+ names = {f.name for f in caps.FEATURES}+ assert {+ "ddp",+ "fsdp2",+ "tp",+ "pp",+ "cp.ulysses",+ "cp.ring",+ "block_compile",+ "flash_varlen",+ "flex",+ } <= names+ for f in caps.FEATURES:+ assert f.module and f.scope in ("instance", "class"), f+ assert set(f.hooks) | set(f.exclusive) <= set(caps.HOOKS), (f.name, f.hooks, f.exclusive)+ assert set(f.consumes) | set(f.uses) | set(f.produces) <= set(caps.METADATA), f.name+ assert set(f.mesh) <= {"dp", "tp", "pp", "cp"}, f.name+ table = caps.markdown_table("features")+ assert table.count("\n") == len(caps.FEATURES) + 1+++ "query, match",+ [+ (+ dict(pp = 2, cp = 2, cp_backend = "ulysses"),+ r"pp x cp.ulysses: both run Trainer.training_step",+ ),+ (dict(attention = "flash_varlen"), r"flash_varlen consumes cu_seqlens"),+ ],+)+def test_composition_follows_from_the_declarations(query, match):+ from unsloth import parallel_capabilities as caps+ with pytest.raises(NotImplementedError, match = match):+ caps.check_features(_q(**query))+++def test_declarations_accept_what_composes():+ from unsloth import parallel_capabilities as caps+ assert caps.check_features(_q(attention = "flash_varlen", packing = True)) == [+ "lora",+ "flash_varlen",+ "packing",+ ]+ assert "cp.ulysses" in caps.check_features(+ _q(tp = 2, cp = 2, cp_backend = "ulysses", compile = "block")+ )+++def test_every_cell_carries_three_kinds_of_evidence_that_exist():+ import os+ import re++ from unsloth import parallel_capabilities as caps++ here = os.path.dirname(os.path.abspath(__file__))+ for cell in caps.CELLS:+ if cell.missing():+ # A cell waiting for evidence says why, and is refused (tests below).+ assert cell.note, cell.name+ for kind in ("parity", "engagement", "compile"):+ ref = getattr(cell, kind)+ if ref is None:+ continue+ if ref.startswith("eager:"):+ assert cell.match["compile"] == ("eager",), cell.name+ continue+ path, name = re.match(r"(tests/[\w.]+\.py)::(\w+)", ref).groups()+ with open(os.path.join(os.path.dirname(here), path)) as f:+ assert f"def {name}(" in f.read(), ref+ assert caps.markdown_table("cells").count("\n") == len(caps.CELLS) + 1+++ "extra, missing",+ [+ (dict(memory = "unsloth_offload"), "memory='unsloth_offload'"),+ (dict(mode = "qlora"), "mode='qlora'"),+ (dict(kernels = True), "kernels=True"),+ (dict(family = "qwen3"), "family='qwen3'"),+ (dict(dp = 4), "dp=4"),+ ],+)+def test_a_composed_cell_without_evidence_is_refused(extra, missing):+ from unsloth import parallel_capabilities as caps++ query = _q(tp = 2, cp = 2, cp_backend = "ulysses", **extra)+ assert caps.cell_status(query)[0] == "unverified"+ with pytest.raises(+ NotImplementedError, match = "no numeric parity / engagement / compile evidence"+ ) as info:+ caps.check(query)+ assert missing in str(info.value)+++def test_supported_cells_and_legacy_layouts(clean_env):+ from unsloth import parallel_capabilities as caps++ for query in (+ _q(tp = 2, cp = 2, cp_backend = "ulysses"),+ _q(tp = 2, cp = 2, dp = 2, cp_backend = "ulysses", memory = "gc"),+ _q(tp = 2, cp = 2, dp = 2, fsdp2 = True, cp_backend = "ulysses", compile = "block"),+ ):+ assert caps.cell_status(query)[0] == "supported", query+ caps.check(query)+ legacy = _q(tp = 2, dp = 2)+ assert caps.cell_status(legacy)[0] == "unverified"+ caps.check(legacy) # shipped before the registry: runs unless strict+ assert caps.cell_status(_q(tp = 2))[0] == "single"+ clean_env.setenv("UNSLOTH_PARALLEL_STRICT", "1")+ with pytest.raises(NotImplementedError, match = "composition"):+ caps.check(legacy)+ caps.check(legacy, cells = False) # the layout-only check at from_pretrained+++ "query, axis",+ [+ (dict(cp = 2, cp_backend = "ulysses", attention = "flex_sparse"), "cp x attention"),+ (dict(cp = 2, cp_backend = "ulysses", mode = "fp8"), "cp x precision"),+ (dict(tp = 2, mode = "nvfp4"), "tp / pp x precision"),+ (dict(pp = 2, pp_schedule = "interleaved"), "pp x schedule"),+ ],+)+def test_new_axis_rules(query, axis):+ from unsloth import parallel_capabilities as caps+ with pytest.raises(NotImplementedError, match = f"^Unsloth: {axis}: .*Instead: "):+ caps.check(_q(**query))+++def test_query_reads_compile_memory_and_attention_from_the_model():+ import types++ import torch.utils.checkpoint as checkpoint++ from unsloth import parallel_capabilities as caps++ class Layer(torch.nn.Module):+ def forward(self, x):+ return x++ model = torch.nn.Sequential(Layer())+ model.config = types.SimpleNamespace(model_type = "llama", _attn_implementation = "flex_attention")+ q = caps.query_from(None, None, model, types.SimpleNamespace(gradient_checkpointing = True))+ assert (q.compile, q.attention, q.memory) == ("eager", "flex", "gc")+ Layer.forward._unsloth_block_compiled = True+ original = checkpoint.checkpoint++ def unsloth_offloaded_gradient_checkpoint(*a, **k):+ return original(*a, **k)++ checkpoint.checkpoint = unsloth_offloaded_gradient_checkpoint+ try:+ q = caps.query_from(+ None, None, model, types.SimpleNamespace(gradient_checkpointing = True, packing = True)+ )+ finally:+ checkpoint.checkpoint = original+ assert (q.compile, q.memory, q.packing) == ("block", "unsloth_offload", True)+++def test_compile_counters_count_breaks_and_recompiles():+ from unsloth.utils import compile_counters as cc++ torch._dynamo.reset()+ before = cc.snapshot()++ @torch.compile(backend = "aot_eager")+ def f(x):+ return x * 2 + 1++ f(torch.ones(3))+ f(torch.ones(3, 2)) # a rank change: one recompile+ used = cc.since(before)+ assert used["recompiles"] >= 1 and used["unique_graphs"] >= 2 and used["graph_breaks"] == 0+ assert cc.not_above(used, used) == []+ assert cc.not_above(+ {"graph_breaks": 1, "recompiles": 0}, {"graph_breaks": 0, "recompiles": 0}+ ) == ["graph_breaks 1 > 0"]+++# transformers DistributedConfig names, reserved axes, HSDP.+++ "raw, want",+ [+ ("fsdp=4,tp=2", {"tp": 2, "dp": 4, "fsdp": True}),+ (+ "fsdp_size=2,tp_size=2,cp_size=2,pp_size=2",+ {"tp": 2, "cp": 2, "pp": 2, "dp": 2, "fsdp": True},+ ),+ ("dp_shard=2,cp=2", {"cp": 2, "dp": 2, "fsdp": True}),+ ("dp_replicate=2,tp=2", {"tp": 2, "dp": 2, "fsdp": False}),+ ("fsdp=1,dp=2", {"fsdp": True, "dp": 2}), # 0 / 1 stays the switch+ ("fsdp=0,tp=2", {"fsdp": False, "tp": 2}),+ # Failing before: the size-1 axis was compared with the other's dp and refused as a conflict.+ ("dp_shard=1,dp_replicate=2", {"dp": 2, "fsdp": False}),+ ("dp_shard=2,dp_replicate=1", {"dp": 2, "fsdp": True}),+ ("dp=2,dp_shard=1,dp_replicate=2", {"dp": 2, "fsdp": False}),+ ],+)+def test_distributed_config_names_are_accepted(raw, want):+ from unsloth import parallel_env as pe+ assert dict(pe.parse_parallel_spec(raw)) == want+++ "raw, match",+ [+ ("ep=2", "expert parallel"),+ ("ep_size=2,tp=2", "expert parallel"),+ ("efsdp=2", "expert FSDP"),+ ("dp_shard=2,dp_replicate=2", "HSDP"),+ ("dp=4,dp_shard=2", "disagrees"),+ ("fsdp=0,dp_shard=2", "disagrees"),+ ],+)+def test_reserved_and_conflicting_dp_keys_are_refused(raw, match):+ from unsloth import parallel_env as pe+ with pytest.raises(ValueError, match = match):+ pe.parse_parallel_spec(raw)+++# Muon on shards.+++class Muon(torch.optim.SGD):+ """A Muon outside torch.optim: whether it reads the local shard or the DTensor is unknown."""+++def test_a_shard_unaware_muon_is_refused_on_fsdp2_and_tp_shards():+ from unsloth import parallel_capabilities as caps++ muon = Muon([torch.nn.Parameter(torch.randn(4, 4))], lr = 0.1)+ adamw = torch.optim.AdamW([torch.nn.Parameter(torch.randn(4, 4))])+ torch_muon = torch.optim.Muon([torch.nn.Parameter(torch.randn(4, 4))])+ for what in ("fsdp2", "tp"):+ with pytest.raises(+ NotImplementedError,+ match = r"^Unsloth: fsdp2 / tp x optimizer: Muon .*Instead: torch.optim.Muon",+ ):+ caps.refuse_shard_unaware_optimizer(muon, what)+ caps.refuse_shard_unaware_optimizer(adamw, what)+ # torch.optim.Muon steps DTensor shards as whole matrices (tests/test_muon_dtensor_gloo.py), as before.+ caps.refuse_shard_unaware_optimizer(torch_muon, what)+ caps.check(_q(dp = 2, optim = "muon")) # DDP holds whole matrices+ from unsloth.models import fsdp2_native++ with pytest.raises(NotImplementedError, match = "Muon"):+ fsdp2_native._refuse_bnb_optimizer_instance(+ muon+ ) # every native FSDP2 optimizer hook calls it+ fsdp2_native._refuse_bnb_optimizer_instance(torch_muon)+++def test_a_shard_unaware_muon_is_refused_before_native_fsdp2_shards(clean_env):+ import transformers++ from unsloth.models import _utils++ clean_env.setenv("UNSLOTH_FSDP2", "1")+ clean_env.setenv("WORLD_SIZE", "2")++ class Plain(transformers.Trainer):+ def __init__(+ self,+ model = None,+ args = None,+ optimizers = (None, None),+ ):+ pass++ muon = Muon([torch.nn.Parameter(torch.randn(4, 4))], lr = 0.1)+ with pytest.raises(NotImplementedError, match = "Muon"):+ _utils._parallel_capabilities_pre(+ Plain(), Plain.__init__, (), {"optimizers": (muon, None)}, None+ )+ torch_muon = torch.optim.Muon([torch.nn.Parameter(torch.randn(4, 4))])+ _utils._parallel_capabilities_pre(+ Plain(), Plain.__init__, (), {"optimizers": (torch_muon, None)}, None+ )+++# MoE cells.+++def test_moe_rows_cover_family_precision_aux_and_mode():+ import types++ from unsloth import parallel_capabilities as caps++ moe = [+ c+ for c in caps.CELLS+ if c.name.startswith("MoE ") and not c.name.endswith(", block compile")+ ]+ assert len(moe) == len(caps.MOE_FAMILIES) * 4 * 2 * 6+ proven = sorted(c.name for c in moe if not c.missing())+ assert "MoE qwen3_moe x lora+experts x aux off x cp" in proven+ assert "MoE qwen3_moe x full x aux off x fsdp2" in proven+ assert "MoE qwen3_moe x lora+experts x aux on x ddp" in proven+ moe_q = dict(family = "qwen3_moe", moe = True, expert_lora = True)+ assert caps.cell_status(_q(cp = 2, cp_backend = "ulysses", **moe_q))[0] == "supported"+ # LoRA on the experts under cp: eager only (block compile recompiles more than one process).+ assert (+ caps.cell_status(_q(cp = 2, cp_backend = "ulysses", compile = "block", **moe_q))[0] != "supported"+ )+ caps.check(_q(dp = 2, cp = 2, fsdp2 = True, cp_backend = "ulysses", **moe_q))+ caps.check(+ _q(+ cp = 2,+ cp_backend = "ulysses",+ compile = "block",+ **{**moe_q, "mode": "full", "expert_lora": False},+ )+ )+ # FSDP2 x cp block compile recompiles more than one process (measured): eager only.+ assert (+ caps.cell_status(+ _q(dp = 2, cp = 2, fsdp2 = True, cp_backend = "ulysses", compile = "block", **moe_q)+ )[0]+ != "supported"+ )+ for extra, why in (+ (dict(family = "qwen3_5_moe"), "no tiny-checkpoint gloo run"),+ (dict(mode = "qlora"), "4-bit experts need bitsandbytes on a GPU"),+ (dict(expert_lora = False), "not run yet"),+ ):+ with pytest.raises(NotImplementedError, match = why):+ caps.check(_q(cp = 2, cp_backend = "ulysses", **{**moe_q, **extra}))+ with pytest.raises(+ NotImplementedError, match = r"^Unsloth: MoE x pp / cp: .*router_aux_loss_coef = 0.0"+ ):+ caps.check(_q(cp = 2, cp_backend = "ulysses", router_aux_loss = True, **moe_q))+ # Pipeline parallel carries the Qwen3-MoE router auxiliary loss (tests/test_pp_moe_aux_gloo.py): gpipe /+ # 1f1b, one stage per rank, aux on or off; other families, full finetuning and checkpointing stay refused.+ for aux in (True, False):+ for schedule in ("gpipe", "1f1b"):+ pp_q = _q(pp = 2, pp_schedule = schedule, router_aux_loss = aux, **moe_q)+ assert caps.cell_status(pp_q)[0] == "supported", (aux, schedule)+ caps.check(pp_q)+ with pytest.raises(NotImplementedError, match = r"x pp' lacks .*Qwen3-MoE only"):+ caps.check(_q(pp = 2, pp_schedule = "gpipe", **{**moe_q, "family": "gpt_oss"}))+ with pytest.raises(NotImplementedError, match = r"^Unsloth: pp x schedule"):+ caps.check(_q(pp = 2, pp_schedule = "interleaved", **moe_q))+ with pytest.raises(NotImplementedError, match = r"^Unsloth: pp x mode"):+ caps.check(_q(pp = 2, pp_schedule = "gpipe", **{**moe_q, "mode": "full"}))+ with pytest.raises(NotImplementedError, match = r"no numeric parity"):+ caps.check(_q(pp = 2, pp_schedule = "gpipe", memory = "gc", **moe_q))+ with pytest.raises(NotImplementedError, match = r"no numeric parity"):+ caps.check(_q(pp = 2, dp = 2, pp_schedule = "gpipe", **moe_q))+ # Tensor parallel MoE runs (main's tp_native support): reported, not refused.+ assert caps.cell_status(_q(tp = 2, **moe_q))[0] == "unverified"+ caps.check(_q(tp = 2, **moe_q))+ assert caps.cell_status(_q(dp = 2, fsdp2 = True, router_aux_loss = True, **moe_q))[0] == "supported"+ assert (+ caps.cell_status(_q(dp = 2, router_aux_loss = True, **{**moe_q, "family": "gpt_oss"}))[0]+ == "unverified"+ )+ caps.check(+ _q(dp = 2, router_aux_loss = True, **{**moe_q, "family": "gpt_oss"})+ ) # dp alone: reported, runs+++def test_aux_loss_is_read_the_way_trl_turns_it_on():+ import types++ from unsloth import parallel_capabilities as caps++ class SFTTrainer:+ pass++ config = types.SimpleNamespace(+ model_type = "qwen3_moe",+ num_experts = 4,+ output_router_logits = False,+ router_aux_loss_coef = 0.001,+ )+ model = types.SimpleNamespace(config = config)+ trl_default = types.SimpleNamespace(router_aux_loss_coef = None)+ assert caps.query_from(None, SFTTrainer, model, trl_default).router_aux_loss is True+ assert (+ caps.query_from(+ None, SFTTrainer, model, types.SimpleNamespace(router_aux_loss_coef = 0.0)+ ).router_aux_loss+ is False+ )+ assert (+ caps.query_from(None, None, model, trl_default).router_aux_loss is False+ ) # a plain Trainer+ config.output_router_logits = True+ assert caps.query_from(None, None, model, None).router_aux_loss is True+ dense = types.SimpleNamespace(+ model_type = "qwen3_next",+ num_experts = 2,+ num_hidden_layers = 2,+ mlp_only_layers = [0, 1],+ output_router_logits = True,+ )+ assert (+ caps.query_from(None, SFTTrainer, types.SimpleNamespace(config = dense), trl_default).moe+ is False+ )+++def test_cp_with_native_fsdp2_is_a_supported_cell():+ from unsloth import parallel_capabilities as caps+ status, cell = caps.cell_status(_q(dp = 2, cp = 2, fsdp2 = True, cp_backend = "ulysses"))+ assert status == "supported" and "native FSDP2" in cell.name+++# The notebooks launcher (fsdp2_scripts, M4) writes every axis and an agreeing UNSLOTH_FSDP2.++LAUNCHER_KEYS = ("dp", "tp", "pp", "cp", "fsdp", "cp_backend", "pp_schedule")+++ "flag, world, legacy",+ [+ ("dp=2,tp=1,pp=1,cp=1,fsdp=1", "2", {"UNSLOTH_FSDP2": "1"}),+ ("dp=2,tp=1,pp=1,cp=1,fsdp=0", "2", {"UNSLOTH_FSDP2": "0"}),+ ("dp=1,tp=2,pp=1,cp=1,fsdp=0", "2", {"UNSLOTH_FSDP2": "0", "UNSLOTH_TP_SIZE": "2"}),+ (+ "dp=1,tp=1,pp=2,cp=1,fsdp=0,pp_schedule=1f1b",+ "2",+ {"UNSLOTH_FSDP2": "0", "UNSLOTH_PP_SIZE": "2", "UNSLOTH_PP_SCHEDULE": "1F1B"},+ ),+ (+ "dp=1,tp=1,pp=1,cp=2,fsdp=1,cp_backend=ulysses",+ "2",+ {"UNSLOTH_FSDP2": "true", "UNSLOTH_CP_SIZE": "2", "UNSLOTH_CP_BACKEND": "Ulysses"},+ ),+ (+ "dp=2,tp=2,pp=2,cp=2,fsdp=1",+ "16",+ {+ "UNSLOTH_FSDP2": "1",+ "UNSLOTH_TP_SIZE": "2",+ "UNSLOTH_PP_SIZE": "2",+ "UNSLOTH_CP_SIZE": "2",+ },+ ),+ (+ "dp=2,tp=1,pp=1,cp=1,fsdp=0,cp_backend=auto",+ "2",+ {"UNSLOTH_TP_SIZE": "1", "UNSLOTH_CP_SIZE": "1"},+ ),+ ],+)+def test_launcher_flag_with_agreeing_legacy_variables_is_accepted(clean_env, flag, world, legacy):+ import os++ from unsloth import parallel_env as pe++ clean_env.setenv("WORLD_SIZE", world)+ clean_env.setenv("UNSLOTH_PARALLEL", flag)+ for key, value in legacy.items():+ clean_env.setenv(key, value)+ spec = pe.apply_parallel_env()+ assert set(spec) <= set(LAUNCHER_KEYS)+ assert (+ pe.apply_parallel_env() == spec+ ) # idempotent: the second read agrees with what the first wrote+ fsdp = os.environ.get("UNSLOTH_FSDP2")+ assert fsdp in ("1", "0", "true") and (fsdp in ("1", "true")) == spec["fsdp"]+++ "flag, legacy, name",+ [+ ("dp=2,tp=1,pp=1,cp=1,fsdp=1", {"UNSLOTH_FSDP2": "0"}, "UNSLOTH_FSDP2"),+ ("dp=1,tp=2,pp=1,cp=1,fsdp=0", {"UNSLOTH_TP_SIZE": "4"}, "UNSLOTH_TP_SIZE"),+ ("dp=1,tp=1,pp=1,cp=2,fsdp=0", {"UNSLOTH_CP_SIZE": "4"}, "UNSLOTH_CP_SIZE"),+ (+ "dp=1,tp=1,pp=1,cp=2,fsdp=0,cp_backend=ring",+ {"UNSLOTH_CP_BACKEND": "ulysses"},+ "UNSLOTH_CP_BACKEND",+ ),+ ("dp=2,tp=1,pp=1,cp=1,fsdp=0", {"UNSLOTH_PP_SIZE": "2"}, "UNSLOTH_PP_SIZE"),+ ],+)+def test_launcher_flag_with_a_disagreeing_legacy_variable_is_refused(clean_env, flag, legacy, name):+ from unsloth import parallel_env as pe++ clean_env.setenv("WORLD_SIZE", "2")+ clean_env.setenv("UNSLOTH_PARALLEL", flag)+ for key, value in legacy.items():+ clean_env.setenv(key, value)+ with pytest.raises(ValueError, match = f"{name}=.*asks for something else"):+ pe.apply_parallel_env()+++def test_the_launcher_keys_are_accepted_and_ep_is_reserved():+ from unsloth import parallel_env as pe+ assert set(LAUNCHER_KEYS) <= set(pe._KEYS)+ assert {"ep", "efsdp"} <= set(pe._RESERVED)++[email protected]("kind", ["sft", "dpo", "grpo"])+def test_router_aux_loss_after_init_is_refused_under_cp_for_each_trl_trainer(kind):+ """SFTTrainer writes output_router_logits into the config; DPOTrainer / GRPOTrainer only set aux_loss_enabled+ and pass the flag per forward. The post-init guard reads both; router_aux_loss_coef = 0.0 runs."""+ import types++ from unsloth import context_parallel as cpm+ from unsloth import parallel_capabilities as caps++ def trainer(aux, coef):+ config = types.SimpleNamespace(+ model_type = "qwen3_moe",+ num_experts = 4,+ router_aux_loss_coef = 0.001,+ output_router_logits = aux and kind == "sft",+ )+ model = types.SimpleNamespace(config = config)+ args = types.SimpleNamespace(router_aux_loss_coef = coef)+ return types.SimpleNamespace(model = model, args = args, aux_loss_enabled = aux), model, args++ on, model, args = trainer(True, None)+ with pytest.raises(+ NotImplementedError, match = r"^Unsloth: MoE x pp / cp: .*router_aux_loss_coef = 0.0"+ ):+ cpm._refuse_router_aux_loss_after_init(on, 2)+ assert (+ caps.query_from(None, type(f"{kind.upper()}Trainer", (), {}), model, args).router_aux_loss+ is True+ )+ off, model, args = trainer(False, 0.0)+ cpm._refuse_router_aux_loss_after_init(off, 2)+ assert (+ caps.query_from(None, type(f"{kind.upper()}Trainer", (), {}), model, args).router_aux_loss+ is False+ )+++def _strict_sft(monkeypatch, inits):+ """A trainer whose __init__ takes no unknown keyword, like TRL's SFTTrainer: a CP option left in the+ constructor kwargs is a TypeError there."""+ import trl++ class SFTTrainer:+ def __init__(+ self,+ model = None,+ args = None,+ train_dataset = None,+ peft_config = None,+ ):+ inits.append(args)+ self.model, self.args = model, args++ monkeypatch.setattr(trl, "SFTTrainer", SFTTrainer)+ cp.patch_sft_trainer()+ return SFTTrainer+++def _stop_at_cp_runtime(monkeypatch):+ def stop(self, *a, **k):+ raise RuntimeError(+ "stop"+ ) # past the pre-init steps; the CP runtime checks need a process group++ monkeypatch.setattr(cp, "_check_cp_runtime", stop)++[email protected]("via", ["env", "kwarg"])+def test_cp_without_trainer_args_builds_the_default_config(clean_env, via):+ import trl++ inits = []+ Trainer = _strict_sft(clean_env, inits)+ _stop_at_cp_runtime(clean_env)+ kwargs = {}+ if via == "env":+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_BACKEND", "ulysses")+ else:+ kwargs = dict(context_parallel_size = 2, context_parallel_backend = "ulysses")+ with pytest.raises(RuntimeError, match = "stop"):+ Trainer(model = torch.nn.Linear(2, 2), train_dataset = [], **kwargs)+ (args,) = inits+ assert isinstance(args, trl.SFTConfig), type(args)+ assert args.context_parallel_size == 2 and args.context_parallel_backend == "ulysses"+++def test_auto_backend_reads_the_config_of_a_model_id(clean_env):+ import types++ import transformers++ inits = []+ Trainer = _strict_sft(clean_env, inits)+ _stop_at_cp_runtime(clean_env)+ loaded = []++ def from_pretrained(name, *a, **k):+ loaded.append(name)+ return types.SimpleNamespace(+ num_attention_heads = 6, num_key_value_heads = 6, model_type = "llama"+ )++ clean_env.setattr(transformers.AutoConfig, "from_pretrained", from_pretrained)+ args = types.SimpleNamespace(context_parallel_size = 4, context_parallel_backend = "auto")+ with pytest.raises(RuntimeError, match = "stop"):+ Trainer(model = "org/six-heads", args = args)+ assert loaded == ["org/six-heads"]+ # 6 heads do not split over cp 4: the loaded model would fail Ulysses' divisibility check.+ assert args.context_parallel_backend == "ring", args.context_parallel_backend+ assert args._unsloth_cp_backend_auto is True+++def test_pre_init_query_reads_a_pending_peft_config(clean_env):+ import types++ from peft import LoraConfig++ inits = []+ Trainer = _strict_sft(clean_env, inits)+ _stop_at_cp_runtime(clean_env)+ clean_env.setenv("UNSLOTH_TP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ clean_env.setenv("WORLD_SIZE", "4")+ clean_env.setenv("UNSLOTH_CP_BACKEND", "ulysses")+ model = _Packable(+ 4+ ) # a dense llama, trainable, no adapters yet: full finetuning without the peft_config+ args = lambda: types.SimpleNamespace(context_parallel_size = 1)+ with pytest.raises(NotImplementedError, match = "cp x tp"):+ Trainer(model = model, args = args())+ with pytest.raises(RuntimeError, match = "stop"):+ Trainer(model = model, args = args(), peft_config = LoraConfig(r = 8))+++class UnslothDPOConfig: # what the generated module defines next to UnslothDPOTrainer+ context_parallel_size = 1+ context_parallel_backend = "auto"+++def test_rl_cp_without_trainer_args_builds_the_default_config(clean_env):+ inits = []++ class UnslothDPOTrainer:+ def __init__(+ self,+ model = None,+ ref_model = None,+ args = None,+ train_dataset = None,+ ):+ inits.append(args)+ self.model, self.args = model, args++ UnslothDPOTrainer.__module__ = __name__+ cp.patch_rl_trainer(UnslothDPOTrainer, "dpo_trainer")+ _stop_at_cp_runtime(clean_env)+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ with pytest.raises(RuntimeError, match = "stop"):+ UnslothDPOTrainer(model = torch.nn.Linear(2, 2), train_dataset = [])+ (args,) = inits+ assert isinstance(args, UnslothDPOConfig) and args.context_parallel_size == 2+++def test_pp_env_refuses_router_aux_loss_split_over_micro_batches():+ # Failing before: the env pipeline added coef x aux per micro-batch, a different objective from the one-GPU+ # Trainer step (aux over the whole batch); the micro-batch count changed the loss and gradients.+ import types++ from unsloth.models import pp_env++ owner = types.SimpleNamespace(+ config = types.SimpleNamespace(output_router_logits = True), router_aux_loss_coef = 0.01+ )+ stage = types.SimpleNamespace(+ ctx = types.SimpleNamespace(moe = types.SimpleNamespace(owner = owner)),+ env_layout = None,+ num_stages = 2,+ )+ with pytest.raises(NotImplementedError, match = "load-balancing loss per micro-batch"):+ pp_env._refuse_split_router_aux(stage, 2)+ pp_env._refuse_split_router_aux(stage, 1)+ owner.config.output_router_logits = False+ pp_env._refuse_split_router_aux(stage, 2)+++def test_pending_expert_lora_counts_in_the_capability_query():+ # Failing before: SFTTrainer(peft_config = LoraConfig(target_modules = expert projections)) was queried as+ # attention-only LoRA (expert_lora read only the attached adapters) and hit an unverified cell.+ import types++ import torch+ from unsloth import parallel_capabilities as caps++ class Expert(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.down_proj = torch.nn.Linear(4, 4)++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.q_proj = torch.nn.Linear(4, 4)+ self.experts = torch.nn.ModuleList([Expert(), Expert()])++ model = Block()+ assert caps._pending_expert_lora(+ model, types.SimpleNamespace(target_modules = ["down_proj"], target_parameters = None)+ )+ assert caps._pending_expert_lora(+ model, types.SimpleNamespace(target_modules = None, target_parameters = ["x"])+ )+ assert not caps._pending_expert_lora(+ model, types.SimpleNamespace(target_modules = ["q_proj"], target_parameters = None)+ )+ q = caps.query_from(+ model = model,+ peft_config = types.SimpleNamespace(target_modules = ["down_proj"], target_parameters = None),+ )+ assert q.expert_lora+++def test_pp_dp_optimizer_hook_takes_self_optimizer_when_create_returns_none():+ import inspect++ from unsloth.models import pp_env++ # The wrapper must not hand None to the step hook (a create_optimizer override may only set self.optimizer).+ src = inspect.getsource(pp_env)+ assert "optimizer = trainer.optimizer" in src+++def test_pp_replica_syncs_parameters_trained_before_a_freeze():+ # Failing before: gather_replica synced only parameters that currently require grad, so freezing the model+ # for generate / export dropped the trained adapters from the other stages' copies.+ import types++ import torch+ from unsloth.models import pp_env++ model = torch.nn.Sequential(torch.nn.Linear(2, 2), torch.nn.Linear(2, 2))+ model[0].requires_grad_(False)+ stage = types.SimpleNamespace(model = model)+ pp_env._note_trained(stage)+ model.requires_grad_(False)+ assert pp_env._trained_names(stage) == ["1.weight", "1.bias"]+++def test_pp_checkpoint_load_releases_the_replica_first(monkeypatch):+ # Failing before: a replica left by generate made the checkpoint layout check see every stage's parameters.+ import unsloth.models.tp_native as tp_native+ from unsloth.models import pp_env++ order = []+ monkeypatch.setattr(pp_env, "release_replica", lambda model: order.append("release"))+ monkeypatch.setattr(+ tp_native, "_tp_load_from_checkpoint", lambda self, *a, **k: order.append("load")+ )+ trainer = __import__("types").SimpleNamespace(model = object())+ pp_env._pp_load_from_checkpoint(trainer, "ckpt")+ assert order == ["release", "load"]+++def test_pp_env_refuses_sft_loss_types_the_pipeline_skips():+ # Failing before: SFTConfig(loss_type = "dft") was accepted, and the pipeline step (plain causal LM loss)+ # silently trained with NLL instead of DFT.+ import types++ import trl+ from unsloth.models import pp_env++ layout = types.SimpleNamespace(env_vars = "UNSLOTH_PP_SIZE=2")+ dft = trl.SFTConfig(output_dir = "unused", report_to = "none", loss_type = "dft")+ with pytest.raises(NotImplementedError, match = "loss_type"):+ pp_env.pp_trainer_refusals(trl.SFTTrainer, dft, layout)+ nll = trl.SFTConfig(output_dir = "unused", report_to = "none")+ pp_env.pp_trainer_refusals(trl.SFTTrainer, nll, layout)+++def test_repeated_parallelize_keeps_inherited_variables(clean_env):+ # Failing before: a second call cleared every legacy variable and restored only its own output, so an+ # inherited UNSLOTH_FSDP2=1 left alone by both calls turned a native FSDP2 run into DDP.+ import os++ import unsloth as u+ from unsloth.models import tp_env++ clean_env.setenv("WORLD_SIZE", "4")+ clean_env.setenv("UNSLOTH_FSDP2", "1")+ tp_env._reset_env_layout()+ try:+ assert u.parallelize(tp = 2) == {"UNSLOTH_TP_SIZE": "2"}+ tp_env._reset_env_layout()+ assert u.parallelize(tp = 2) == {"UNSLOTH_TP_SIZE": "2"}+ assert os.environ.get("UNSLOTH_FSDP2") == "1"+ tp_env._reset_env_layout()+ # What the earlier call wrote (cp) still goes away when the next call drops it.+ u.parallelize(tp = 2, cp = 2)+ tp_env._reset_env_layout()+ u.parallelize(tp = 2)+ assert "UNSLOTH_CP_SIZE" not in os.environ and os.environ["UNSLOTH_TP_SIZE"] == "2"+ assert os.environ.get("UNSLOTH_FSDP2") == "1"+ finally:+ for key in _ENV:+ os.environ.pop(key, None)+ tp_env._reset_env_layout()+++def test_block_compile_cells_carry_a_torch_floor():+ # torch 2.10 failed the block compile cells' own compile gates (recompiles 6 > 1 under cp x tp, 1 > 0 for MoE+ # under cp), so those cells cover torch >= BLOCK_COMPILE_TORCH only and older versions get the eager cells.+ from unsloth import parallel_capabilities as caps++ assert caps.BLOCK_COMPILE_TORCH == (+ 2,+ 13,+ ) # tests/test_parallel_cp_compose_gloo.py skips below the same floor+ block = _q(tp = 2, cp = 2, cp_backend = "ulysses", compile = "block")+ eager = _q(tp = 2, cp = 2, cp_backend = "ulysses", compile = "eager")+ assert caps.cell_status(block)[0] == "supported"+ assert caps.cell_status(eager)[0] == "supported"+ old = _q(tp = 2, cp = 2, cp_backend = "ulysses", compile = "block", torch = (2, 10))+ status, reason = caps.cell_status(old)+ assert (+ status == "unverified"+ and "torch 2.10 < 2.13" in reason+ and "UNSLOTH_BLOCK_COMPILE_LEGACY=0" in reason+ ), reason+ assert (+ caps.cell_status(_q(tp = 2, cp = 2, cp_backend = "ulysses", compile = "eager", torch = (2, 10)))[0]+ == "supported"+ )+ moe = dict(family = "qwen3_moe", moe = True, mode = "full", cp = 2, cp_backend = "ulysses")+ assert caps.cell_status(_q(compile = "block", **moe))[0] == "supported"+ assert caps.cell_status(_q(compile = "block", torch = (2, 10), **moe))[0] == "unverified"+ assert caps.cell_status(_q(compile = "eager", torch = (2, 10), **moe))[0] == "supported"+++def test_tp_checkpoint_layout_records_the_cp_width(clean_env, monkeypatch):+ # Failing before: dp_mesh is the flattened (dp, cp) mesh, so a tp=2,cp=2 checkpoint (one data replica) and a+ # tp=2 one with two replicas had the same layout, and a resume across them skipped the wrong number of rows.+ from types import SimpleNamespace++ from unsloth.models import tp_env, tp_native++ mesh = SimpleNamespace(size = lambda: 2)+ monkeypatch.setattr(tp_native, "_tp_meshes", lambda model: (mesh, mesh))+ monkeypatch.setattr(tp_native, "_pp_size", lambda model: 1)+ monkeypatch.setattr(tp_native, "_ddp_mesh", lambda model: object())+ trainer = SimpleNamespace(model = torch.nn.Linear(4, 4))+ layouts = {}+ for cp in (1, 2):+ monkeypatch.setattr(tp_env, "_LAYOUT", SimpleNamespace(cp = cp))+ layouts[cp] = tp_native._tp_layout(trainer)+ assert layouts[1] != layouts[2] and layouts[2]["cp"] == 2+ assert "cp" not in layouts[1] # tp-only checkpoints keep their old keys+++def test_cp_x_tp_never_turns_padding_free_on_automatically(clean_env, monkeypatch):+ # Failing before: under tp=2,cp=2 the auto padding-free choice set padding_free = True with packing = False,+ # and the capability check then refused the run as packed, with no setting left for the user to change.+ from types import SimpleNamespace++ import unsloth.trainer as trainer_module++ clean_env.setenv("UNSLOTH_TP_SIZE", "2")+ clean_env.setenv("UNSLOTH_CP_SIZE", "2")+ monkeypatch.setattr(trainer_module, "_auto_padding_choice", lambda *a, **k: (True, "test"))+ monkeypatch.setattr(+ trainer_module, "configure_padding_free", lambda c: setattr(c, "padding_free", True)+ )+ config = SimpleNamespace(packing = False, padding_free = None, max_length = 64)+ _auto_packing(monkeypatch, config, _Packable(4))+ assert config.padding_free is not True and config.packing is False+ # An explicit request stays, so the capability check refuses it with the alternative.+ config = SimpleNamespace(packing = True, padding_free = None, max_length = 64)+ _auto_packing(monkeypatch, config, _Packable(4))+ assert config.packing is True+++def test_sft_ring_packing_reaches_the_released_fallback():+ # Failing before: the pre-init capability check refused ring x packing for SFT before the SFT wrapper could+ # turn packing off with its notice (the released behaviour), for explicit ring and for auto choosing ring.+ from types import SimpleNamespace++ from unsloth import parallel_capabilities as caps++ class SFTTrainer:+ pass++ layout = SimpleNamespace(dp = 1, tp = 1, pp = 1, cp = 2, fsdp2 = False, cp_backend = None, schedule = None)+ args = SimpleNamespace(packing = True, padding_free = None)+ caps.check_layout(layout, SFTTrainer, None, args, cp_backend = "ring")+ # Other trainers have no such fallback: still refused before anything runs.+ with pytest.raises(NotImplementedError, match = "ring context parallel with packed rows"):+ caps.check_layout(layout, None, None, args, cp_backend = "ring")+++def test_pp_replica_restores_detached_layers_with_the_live_adapter_state():+ # Failing before: gather_replica put the other stages' LoRA layers back with their adapters enabled, so+ # generate inside model.disable_adapter() ran a partly adapted model, a different part on each rank.+ import inspect++ from peft import LoraConfig, get_peft_model+ from peft.tuners.tuners_utils import BaseTunerLayer++ from unsloth.models import pp_env++ class Two(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.a = torch.nn.Linear(8, 8)+ self.b = torch.nn.Linear(8, 8)++ model = get_peft_model(Two(), LoraConfig(r = 2, target_modules = ["a", "b"]))+ inner = model.base_model.model+ detached = inner.b # another stage's layer, kept off the model while split+ inner.b = torch.nn.Identity()+ grads = {n: p.requires_grad for n, p in detached.named_parameters()}+ with model.disable_adapter():+ pp_env._apply_adapter_state(detached, pp_env._adapter_state(model))+ assert all(m.disable_adapters for m in detached.modules() if isinstance(m, BaseTunerLayer))+ pp_env._apply_adapter_state(detached, pp_env._adapter_state(model))+ assert not any(m.disable_adapters for m in detached.modules() if isinstance(m, BaseTunerLayer))+ assert {n: p.requires_grad for n, p in detached.named_parameters()} == grads+ assert "_apply_adapter_state(module, adapters)" in inspect.getsource(pp_env.gather_replica)diff --git a/tests/test_pp_env_gloo.py b/tests/test_pp_env_gloo.pynew file mode 100644index 00000000000..d19149dc3ea--- /dev/null+++ b/tests/test_pp_env_gloo.py@@ -0,0 +1,950 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""UNSLOTH_PP_SIZE (models/pp_env.py): pipeline parallel from the environment inside the HF Trainer, on a gloo+CPU world (pp 2, pp 2 x tp 2, pp 2 x dp 2 DDP-style / native FSDP2), vs the same script in 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,+)++_ADAM_EPS = 1e-4 # as test_tp_env_gloo: fp32 reduction-order noise stays below 1e-6 over 3 steps+_ENV_KEYS = (+ "UNSLOTH_TP_SIZE",+ "UNSLOTH_PP_SIZE",+ "UNSLOTH_PP_MICROBATCHES",+ "UNSLOTH_PP_SCHEDULE",+ "UNSLOTH_PP_KEEP_REPLICA",+ "UNSLOTH_FSDP2",+ "UNSLOTH_FSDP2_BACKEND",+ "ACCELERATE_USE_FSDP",+)+N_LAYERS = 4+++def _checkpoint(tmp, arch = "llama"):+ overrides = {"num_hidden_layers": N_LAYERS}+ if (+ arch == "gemma3"+ ): # sliding / full layers on both stages, window shorter than the 9-token rows+ overrides.update(+ layer_types = ["sliding_attention", "full_attention"] * (N_LAYERS // 2), sliding_window = 4+ )+ return _save_checkpoint(arch, os.path.join(tmp, "ckpt"), overrides)+++def _case_units(rank, world, tmp):+ """Layout parsing, load / Trainer refusals (no process group)."""+ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ from unsloth.models import pp_env, tp_env++ out = {}+ # TrainingArguments set up accelerate's state from WORLD_SIZE: build them before the layouts below set it.+ args = _trainer_args(tmp, 2)+ best = _trainer_args(+ tmp, 2, load_best_model_at_end = True, eval_strategy = "steps", save_strategy = "steps"+ )+ smoothed = _trainer_args(tmp, 2, label_smoothing_factor = 0.3)+ try:+ from trl import SFTConfig, SFTTrainer+ packed = SFTConfig(output_dir = tmp, packing = True, report_to = [], use_cpu = True)+ plain_sft = SFTConfig(output_dir = tmp, report_to = [], use_cpu = True)+ except ImportError:+ SFTTrainer = None++ 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.pp,+ got.dp,+ got.tp,+ got.world,+ got.fsdp2,+ got.microbatches,+ got.schedule,+ repr(got),+ )+ )++ out["pp2"] = layout(UNSLOTH_PP_SIZE = 2, WORLD_SIZE = 2)+ out["pp2_dp2"] = layout(UNSLOTH_PP_SIZE = 2, WORLD_SIZE = 4)+ out["pp2_fsdp2"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_FSDP2 = 1, WORLD_SIZE = 4)+ out["pp2_tp2"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 4)+ out["pp2_tp2_dp2"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 8)+ out["pp_one"] = layout(UNSLOTH_PP_SIZE = 1, WORLD_SIZE = 4)+ out["no_divide"] = layout(UNSLOTH_PP_SIZE = 3, WORLD_SIZE = 4)+ out["no_divide_tp"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_TP_SIZE = 2, WORLD_SIZE = 6)+ out["zero"] = layout(UNSLOTH_PP_SIZE = 0, WORLD_SIZE = 2)+ out["text"] = layout(UNSLOTH_PP_SIZE = "two", WORLD_SIZE = 2)+ out["mb"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_PP_MICROBATCHES = 3, WORLD_SIZE = 2)+ out["mb_text"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_PP_MICROBATCHES = "x", WORLD_SIZE = 2)+ out["schedule"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_PP_SCHEDULE = "1F1B", WORLD_SIZE = 2)+ out["schedule_bad"] = layout(UNSLOTH_PP_SIZE = 2, UNSLOTH_PP_SCHEDULE = "zb", WORLD_SIZE = 2)+ out["schedule_mb"] = layout(+ UNSLOTH_PP_SIZE = 4, UNSLOTH_PP_SCHEDULE = "1f1b", UNSLOTH_PP_MICROBATCHES = 2, WORLD_SIZE = 4+ )+ out["accelerate_fsdp"] = layout(+ UNSLOTH_PP_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_PP_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["refused_before_load"] = calls == []++ # Trainer refusals (classes / arguments), before anything is split.+ import transformers++ lay = tp_env.env_layout()++ class DPOTrainer(transformers.Trainer):+ pass++ DPOTrainer.__module__ = "trl.trainer.dpo_trainer"++ class UnslothGRPOTrainer(transformers.Trainer):+ pass++ class MyTrainer(transformers.Trainer):+ def compute_loss(self, *args, **kwargs):+ return None++ class PlainSubclass(transformers.Trainer):+ def _get_train_sampler(self, *args, **kwargs):+ return None++ out["dpo"] = _raised(lambda: pp_env.pp_trainer_refusals(DPOTrainer, args, lay))+ out["grpo"] = _raised(lambda: pp_env.pp_trainer_refusals(UnslothGRPOTrainer, args, lay))+ out["custom_loss"] = _raised(lambda: pp_env.pp_trainer_refusals(MyTrainer, args, lay))+ out["plain"] = _raised(lambda: pp_env.pp_trainer_refusals(PlainSubclass, args, lay))+ out["trainer"] = _raised(lambda: pp_env.pp_trainer_refusals(transformers.Trainer, args, lay))+ out["best"] = _raised(lambda: pp_env.pp_trainer_refusals(transformers.Trainer, best, lay))+ # Failing before: label smoothing and compute_loss_func were accepted and silently skipped.+ out["smoothing"] = _raised(+ lambda: pp_env.pp_trainer_refusals(transformers.Trainer, smoothed, lay)+ )+ out["loss_func"] = _raised(+ lambda: pp_env.pp_trainer_refusals(+ transformers.Trainer, args, lay, compute_loss_func = lambda *a, **k: None+ )+ )+ if SFTTrainer is not None:+ out["packing"] = _raised(lambda: pp_env.pp_trainer_refusals(SFTTrainer, packed, lay))+ out["sft"] = _raised(lambda: pp_env.pp_trainer_refusals(SFTTrainer, plain_sft, lay))+ else:+ out["packing"] = out["sft"] = "no trl"+ # A model the split refuses is refused at from_pretrained, naming the variable: a mixture-of-experts+ # family whose router auxiliary loss pipeline parallel does not carry (Mixtral). Qwen3-MoE, whose loss it+ # carries between stages (tests/test_pp_moe_aux_gloo.py), loads.+ from transformers import AutoConfig, AutoModelForCausalLM++ config = transformers.MixtralConfig(+ vocab_size = 128,+ hidden_size = 64,+ intermediate_size = 96,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 16,+ num_local_experts = 4,+ num_experts_per_tok = 2,+ )+ moe = tp_env.tensor_parallel_env_load(+ lambda name, load_in_4bit = True: AutoModelForCausalLM.from_config(config)+ )+ qwen3_moe_config = AutoConfig.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")+ qwen3_moe = tp_env.tensor_parallel_env_load(+ lambda name, load_in_4bit = True: AutoModelForCausalLM.from_config(qwen3_moe_config)+ )+ os.environ.update(+ MASTER_ADDR = "127.0.0.1", MASTER_PORT = str(_free_port()), RANK = "0", LOCAL_RANK = "0"+ )+ layout(UNSLOTH_PP_SIZE = 1, WORLD_SIZE = 1) # (no world for the mesh here: refusal path only)+ os.environ["UNSLOTH_PP_SIZE"] = "2"+ tp_env._reset_env_layout()+ tp_env._LAYOUT = tp_env.TPEnvLayout(1, 1, 2, False, 2)+ tp_env._LAYOUT._mesh = object() # the refusal comes from the model, not the mesh+ out["moe"] = _raised(lambda: moe("m", load_in_4bit = False))+ out["qwen3_moe"] = _raised(lambda: qwen3_moe("m", load_in_4bit = False))+ # Failing before: under pp x tp the tensor split in Trainer.__init__ replaced the parameters a prebuilt+ # optimizer held, so training stepped the old ones (no update, no error).+ from unsloth.models import _utils as unsloth_utils++ tp_env._LAYOUT = tp_env.TPEnvLayout(2, 1, 4, False, 2)+ trainer_like = object.__new__(transformers.Trainer)+ prebuilt = torch.optim.SGD([torch.nn.Parameter(torch.zeros(1))], lr = 0.1)+ out["prebuilt_optimizer"] = _raised(+ lambda: unsloth_utils._pipeline_parallel_env_refusals(+ trainer_like,+ transformers.Trainer.__init__,+ (),+ {"args": args, "optimizers": (prebuilt, None)},+ )+ )+ out["prebuilt_param_groups"] = _raised(+ lambda: unsloth_utils._pipeline_parallel_env_refusals(+ trainer_like,+ transformers.Trainer.__init__,+ (),+ {+ "args": args,+ "optimizer_cls_and_kwargs": (+ torch.optim.SGD,+ {"params": prebuilt.param_groups, "lr": 0.1},+ ),+ },+ )+ )+ out["no_prebuilt_optimizer"] = _raised(+ lambda: unsloth_utils._pipeline_parallel_env_refusals(+ trainer_like, transformers.Trainer.__init__, (), {"args": args}+ )+ )+ # Hidden states sent between stages: float32 for a model Unsloth trains in float32 (Gemma 3 on a T4).+ import types++ from unsloth.models import pp_native++ parts = types.SimpleNamespace(+ embed = types.SimpleNamespace(weight = torch.zeros(1, dtype = torch.float16))+ )+ plain, forced = torch.nn.Linear(1, 1), torch.nn.Linear(1, 1)+ forced._unsloth_forced_float32 = True+ out["act_dtype"] = (+ pp_native._default_activation_dtype(plain, parts),+ pp_native._default_activation_dtype(forced, parts),+ )++ # Later stages' embedding stub returns zeros in the dtype the real (here upcasting) embedding returns.+ class Upcast(torch.nn.Embedding):+ def forward(self, ids):+ return super().forward(ids).float()++ stub = pp_native._PPEmbeddingStub(Upcast(10, 4).half())+ out["stub_dtype"] = stub(torch.zeros(2, 3, dtype = torch.long)).dtype+ return out+++def _case_env(+ rank,+ world,+ tmp,+ ckpt,+ bs,+ steps = 3,+ evaluate = True,+ post = True,+ optim = "adamw_torch",+ ga = 2,+ eval_bs = None,+ noisy = 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 safetensors.torch import load_file+ from transformers import AutoModelForCausalLM++ from unsloth.models import pp_env, pp_native, tp_env, tp_native+ from unsloth.models._utils import patch_gradient_accumulation_fix++ patch_gradient_accumulation_fix(transformers.Trainer)+ 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 collate(rows):+ batch = {+ "input_ids": torch.stack([r["input_ids"] for r in rows]),+ "labels": torch.stack([r["labels"] for r in rows]).clone(),+ }+ # Uneven token counts per micro-batch / replica, the same per row however the rows are batched.+ batch["labels"][batch["labels"] % 5 == 0] = -100+ if noisy:+ # A stochastic collator whose RNG the stages advance differently (as dropout over different layers).+ if rank % 2 == 1:+ torch.rand(7)+ swap = torch.rand(batch["input_ids"].shape) < 0.3+ batch["input_ids"] = torch.where(+ swap, torch.randint_like(batch["input_ids"], 1, 50), batch["input_ids"]+ )+ seen.append(batch["input_ids"].sum().item())+ return transformers.BatchEncoding(+ batch+ ) # what tokenizer-based collators return (a Mapping)++ 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)+ model = peft(load(ckpt, load_in_4bit = False))+ pre_split = not pp_native.is_pipeline_parallel(model)+ dp = layout.dp if layout is not None else 1+ g = torch.Generator().manual_seed(1)+ ids = torch.randint(0, 1000, (steps * ga * bs * max(dp, 1), 9), generator = g)+ data = _Rows(list(ids))+ eval_data = _Rows(list(torch.randint(0, 1000, (4 * bs * max(dp, 1), 9), generator = g)))+ args = _trainer_args(+ os.path.join(tmp, "out"),+ bs,+ optim = optim,+ max_steps = steps,+ adam_epsilon = _ADAM_EPS,+ gradient_accumulation_steps = ga,+ per_device_eval_batch_size = eval_bs or bs,+ )+ trainer = SequentialTrainer(model = model, args = args, train_dataset = data, data_collator = collate)+ stage_ids = []+ split = pp_native.pipeline_stage_of(trainer.model)+ if split is not None and not split.is_first:+ # Later stages run the model on the batch's real token ids (not zeros), as one GPU does.+ def record(module, args, kwargs):+ if torch.is_grad_enabled() and kwargs.get("input_ids") is not None:+ stage_ids.append(int(kwargs["input_ids"].sum()))++ split.parts.inner.register_forward_pre_hook(record, with_kwargs = True)+ trainer.train()+ logs = [h for h in trainer.state.log_history if "loss" in h]+ res = {+ "steps": [h["step"] for h in logs],+ "losses": [h["loss"] for h in logs],+ "grad_norms": [h.get("grad_norm") for h in logs],+ "seen": list(seen),+ "stage_ids": list(stage_ids), # the training run above (not the later cells)+ "pre_split": pre_split,+ "layout": None if layout is None else repr(layout),+ "is_pp": pp_native.is_pipeline_parallel(trainer.model),+ "wrapped": type(trainer.model_wrapped).__name__,+ }+ stage = pp_native.pipeline_stage_of(trainer.model)+ if stage is not None:+ res["stage"] = stage.stage_index+ # Every stage seeds its train sampler per dp replica (LengthGroupedSampler would draw from the global RNG).+ res["sampler_hooked"] = "_get_train_sampler" in trainer.__dict__+ res["owned"] = sorted(n for n, p in trainer.model.named_parameters() if p.requires_grad)+ res["kept_on_cpu"] = (+ all(p.device.type == "cpu" for _, _, m, _ in stage._kept for p in m.parameters())+ if stage._kept and stage.tp_mesh is None+ else None+ )+ if evaluate:+ res["eval_loss"] = trainer.evaluate(eval_data)["eval_loss"]+ save_dir = os.path.join(tmp, "adapter")+ if stage is not None:+ pp_env.pp_save_adapter(trainer.model, (save_dir,), {})+ elif rank == 0:+ trainer.model.save_pretrained(save_dir)+ if dist.is_initialized():+ dist.barrier()+ res["adapter"] = (+ load_file(os.path.join(save_dir, "adapter_model.safetensors")) if rank == 0 else None+ )+ trainer.save_model(os.path.join(tmp, "trainer_save"))+ if dist.is_initialized():+ dist.barrier()+ res["trainer_adapter"] = (+ load_file(os.path.join(tmp, "trainer_save", "adapter_model.safetensors"))+ if rank == 0+ else None+ )+ if post:+ prompt = ids[:1, :4]+ refusal = pp_env.replica_refusal(stage, "generate") if stage is not None else None+ if refusal is None:+ trainer.model.eval()+ out = trainer.model.generate(+ input_ids = prompt, max_new_tokens = 4, do_sample = False, pad_token_id = 0+ )+ res["generated"] = out.tolist()+ if stage is not None:+ res["replica_active"] = stage.replica is not None+ # Failing before: the other stages' modules came back in training mode (dropout on).+ res["replica_training"] = sorted(+ n for n, m in trainer.model.named_modules() if m.training+ )[:3]+ # An export: the whole one-GPU state dict, built on rank 0 only (the others wait).+ full = pp_env.pp_collective(+ trainer.model,+ "export",+ lambda: {k: v.detach().clone() for k, v in trainer.model.state_dict().items()},+ )+ res["export"] = full if rank == 0 else None+ # The other ranks return rank 0's result (as tp_replica's collective saves do).+ res["export_other"] = sorted(full) if rank != 0 else None+ # Failing before: a checkpoint written with the replica active recorded every stage's params.+ trainer._save_optimizer_and_scheduler(os.path.join(tmp, "ckpt_with_replica"))+ res["released_by_save"] = stage.replica is None+ trainer.model.train()+ pp_env.release_replica(trainer.model)+ res["released"] = stage.replica is None and all(+ not isinstance(layer, torch.nn.Module)+ or type(layer).__name__ == "_PPPassThrough"+ for i, layer in enumerate(stage.parts.layers)+ if not (stage.start <= i < stage.end)+ )+ # A training step after generate: the pipeline split is back.+ trainer.args.max_steps = steps + 1+ res["after_generate"] = _raised(lambda: trainer.train(resume_from_checkpoint = None))+ else:+ res["export"] = {+ k: v.detach().clone() for k, v in trainer.model.state_dict().items()+ }+ else:+ res["generate_refused"] = _raised(+ lambda: trainer.model.generate(+ input_ids = prompt, max_new_tokens = 4, do_sample = False, pad_token_id = 0+ )+ )+ res["export_refused"] = _raised(+ lambda: pp_env.pp_collective(trainer.model, "export", lambda: None)+ )+ if dist.is_initialized():+ dist.barrier()+ return res+++def _case_resume(+ rank,+ world,+ tmp,+ ckpt,+ bs = 2,+):+ """save_strategy = "steps" checkpoints (the 1-GPU adapter + per-rank optimizer state) and an exact resume."""+ 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)+ layout = tp_env.env_layout()+ dp = layout.dp if layout is not None else 1++ class SequentialTrainer(transformers.Trainer):+ def _get_train_sampler(self, *args, **kwargs):+ return torch.utils.data.SequentialSampler(self.train_dataset)++ load = tp_env.tensor_parallel_env_load(+ lambda name, load_in_4bit = True: AutoModelForCausalLM.from_pretrained(+ name, torch_dtype = torch.float32, attn_implementation = "eager"+ )+ )++ def fresh():+ torch.manual_seed(1)+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False)+ return get_peft_model(load(ckpt, load_in_4bit = False), config)++ g = torch.Generator().manual_seed(1)+ data = _Rows(list(torch.randint(0, 1000, (4 * 2 * bs * dp, 9), generator = g)))++ def run(out):+ args = _trainer_args(+ os.path.join(tmp, out),+ bs,+ max_steps = 4,+ adam_epsilon = _ADAM_EPS,+ save_strategy = "steps",+ save_steps = 2,+ )+ return SequentialTrainer(model = fresh(), args = args, train_dataset = data)++ def summary(trainer):+ logs = [h for h in trainer.state.log_history if "loss" in h]+ return {+ "steps": [h["step"] for h in logs],+ "losses": [h["loss"] for h in logs],+ "norms": [h["grad_norm"] for h in logs],+ }++ a = run("a")+ a.train()+ ckpt2 = os.path.join(tmp, "a", "checkpoint-2")+ files = sorted(os.listdir(ckpt2)) + sorted(os.listdir(os.path.join(ckpt2, "unsloth_tp")))+ b = run("b")+ b.train(resume_from_checkpoint = ckpt2)+ state_a = {n: p.detach().clone() for n, p in a.model.named_parameters() if p.requires_grad}+ state_b = {n: p.detach().clone() for n, p in b.model.named_parameters() if p.requires_grad}+ return {+ "a": summary(a),+ "b": summary(b),+ "files": files,+ "same": all(torch.equal(state_a[k], state_b[k]) for k in state_a),+ }+++def _case_scaler_clip(+ rank,+ world,+ tmp,+ wrapper_unscale = False,+):+ """float16: the Trainer clip under pp unscales the gradients once, for the torch optimizer the+ AcceleratedOptimizer hands the GradScaler (a second unscale inside scaler.step would shrink the update)."""+ error = _import_checkout_unsloth()+ if error is not None:+ return {"skip": error}+ import types++ from accelerate.optimizer import AcceleratedOptimizer+ from torch.distributed.device_mesh import init_device_mesh+ from test_pp_fsdp2_gloo import LLAMA, build, global_batch++ from unsloth.models import pp_env, pp_native++ import torch.distributed as dist++ if wrapper_unscale: # the old lookup: unscale the AcceleratedOptimizer itself+ pp_env._unwrap_optimizer = lambda opt: opt++ dist.init_process_group("gloo")+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))+ model = build(LLAMA)+ stage = pp_native.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)+ ids, labels = global_batch(model, 4)+ from accelerate import Accelerator++ Accelerator(cpu = True) # the state AcceleratedOptimizer reads+ scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)+ inner = torch.optim.SGD(stage.parameters(), lr = 1.0)+ optimizer = AcceleratedOptimizer(inner, device_placement = False, scaler = scaler)+ accelerator = types.SimpleNamespace(scaler = scaler, _optimizers = [optimizer])+ stage.step(ids, labels, scaler = scaler)+ norm = pp_env._pp_clip(accelerator, stage)(model.parameters(), 1e9)+ grads = [p.grad.detach().clone() for p in stage.parameters()]+ before = [p.detach().clone() for p in stage.parameters()]+ optimizer.step()+ deltas = [(b - p.detach()) for b, p in zip(before, stage.parameters())]+ return {+ "norm": float(norm),+ "max_rel": max(+ float((d - g).abs().max() / g.abs().max().clamp_min(1e-30))+ for d, g in zip(deltas, grads)+ ),+ "scale": scaler.get_scale(),+ }+++CASES = {+ "units": _case_units,+ "env": _case_env,+ "resume": _case_resume,+ "scaler_clip": _case_scaler_clip,+}+++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 faulthandler++ faulthandler.dump_traceback_later(+ max(int(os.environ.get("PP_TEST_TIMEOUT", 600)) - 30, 30), exit = True+ )+ 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", "resume"):+ kwargs["ckpt"] = _checkpoint(tmp, kwargs.pop("arch", "llama"))+ 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(int(os.environ.get("PP_TEST_TIMEOUT", 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 _pipelining_available():+ try:+ import inspect++ from torch.distributed.pipelining import ScheduleGPipe+ except ImportError:+ return False+ return "return_outputs" in inspect.signature(ScheduleGPipe.step).parameters+++needs_pipelining = pytest.mark.skipif(+ not _pipelining_available(),+ reason = "torch.distributed.pipelining with step(return_outputs) (torch >= 2.10)",+)+++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"],+ )+ # Step 1 is tight; later steps carry the one-process reference's own run-to-run spread on this host+ # (3e-5 absolute at a 2.3 grad norm between two identical reference runs).+ assert got["grad_norms"][:1] == pytest.approx(want["grad_norms"][:1], rel = rel), (+ what,+ got["grad_norms"],+ )+ assert got["grad_norms"] == pytest.approx(want["grad_norms"], rel = 1e-4), (+ what,+ got["grad_norms"],+ want["grad_norms"],+ )+ if "eval_loss" in want:+ assert got["eval_loss"] == pytest.approx(want["eval_loss"], rel = rel), (+ what,+ got["eval_loss"],+ want["eval_loss"],+ )+++def _same_tensors(+ got,+ want,+ rel = 1e-4,+ atol = 1e-5,+ what = "",+):+ assert set(got) == set(want) and want, (what, sorted(set(got) ^ set(want))[:6])+ for key, value in want.items():+ torch.testing.assert_close(+ got[key], value, rtol = rel, atol = atol, msg = lambda m: f"{what} {key}: {m}"+ )+++def _ref(bs, **kwargs):+ return _spawn("env", 1, bs = bs, **kwargs)[0]+++@needs_pipelining+def test_pp_env_layout_and_refusals():+ (res,) = _spawn("units")+ assert res["pp2"][:5] == (2, 1, 1, 2, False) and res["pp2"][7] == "pp 2", res["pp2"]+ assert res["pp2_dp2"][:5] == (2, 2, 1, 4, False) and res["pp2_dp2"][7] == "pp 2 x dp 2 (DDP)"+ assert res["pp2_fsdp2"][:5] == (2, 2, 1, 4, True) and "native FSDP2" in res["pp2_fsdp2"][7]+ assert res["pp2_tp2"][:5] == (2, 1, 2, 4, False) and res["pp2_tp2"][7] == "pp 2 x tp 2"+ assert res["pp2_tp2_dp2"][:5] == (2, 2, 2, 8, False)+ assert res["pp_one"] is None+ assert "UNSLOTH_PP_SIZE=3" in res["no_divide"] and "WORLD_SIZE=4" in res["no_divide"], res[+ "no_divide"+ ]+ assert "UNSLOTH_PP_SIZE x UNSLOTH_TP_SIZE = 4" in res["no_divide_tp"], res["no_divide_tp"]+ assert "must be >= 1" in res["zero"] and "must be an integer" in res["text"]+ assert res["mb"][5] == 3 and "UNSLOTH_PP_MICROBATCHES" in res["mb_text"]+ assert res["schedule"][6] == "1f1b" and "UNSLOTH_PP_SCHEDULE" in res["schedule_bad"]+ assert "UNSLOTH_PP_MICROBATCHES >= UNSLOTH_PP_SIZE" in res["schedule_mb"], res["schedule_mb"]+ assert (+ "native FSDP2 only" in res["accelerate_fsdp"]+ and "UNSLOTH_PP_SIZE=2" in res["accelerate_fsdp"]+ )+ assert (+ "vLLM" in res["refuse_vllm"]+ and "UNSLOTH_PP_SIZE=2 (pipeline parallel)" in res["refuse_vllm"]+ )+ assert "full finetuning" in res["refuse_full_ft"] and res["refused_before_load"]+ for key in ("dpo", "grpo"):+ assert (+ "Trainer / SFTTrainer only" in (res[key] or "") and "UNSLOTH_PP_SIZE=2" in res[key]+ ), res[key]+ assert "overrides compute_loss" in (res["custom_loss"] or ""), res["custom_loss"]+ assert res["plain"] is None and res["trainer"] is None, (res["plain"], res["trainer"])+ assert "load_best_model_at_end" in (res["best"] or ""), res["best"]+ assert "label_smoothing_factor" in (res["smoothing"] or ""), res["smoothing"]+ assert "compute_loss_func" in (res["loss_func"] or ""), res["loss_func"]+ assert "optimizers = (optimizer" in (res["prebuilt_optimizer"] or ""), res["prebuilt_optimizer"]+ assert res["no_prebuilt_optimizer"] is None, res["no_prebuilt_optimizer"]+ # Failing before: parameter groups passed through optimizer_cls_and_kwargs went around the guard.+ assert "optimizers = (optimizer" in (res["prebuilt_param_groups"] or ""), res[+ "prebuilt_param_groups"+ ]+ if res["sft"] != "no trl":+ assert res["sft"] is None, res["sft"]+ assert "packing" in (res["packing"] or ""), res["packing"]+ assert (+ "mixture-of-experts" in (res["moe"] or "") and "UNSLOTH_PP_SIZE=2: unset it" in res["moe"]+ ), res["moe"]+ assert res["qwen3_moe"] is None, res["qwen3_moe"]+ assert res["act_dtype"] == (torch.float16, torch.float32), res["act_dtype"]+ assert res["stub_dtype"] == torch.float32, res["stub_dtype"]+++@needs_pipelining+ "world,env,ref_bs",+ [+ (2, {"UNSLOTH_PP_SIZE": "2"}, 2),+ (4, {"UNSLOTH_PP_SIZE": "2", "UNSLOTH_TP_SIZE": "2"}, 2),+ (4, {"UNSLOTH_PP_SIZE": "2"}, 4),+ (4, {"UNSLOTH_PP_SIZE": "2", "UNSLOTH_FSDP2": "1"}, 4),+ ],+ ids = ["pp2", "pp2_x_tp2", "pp2_x_ddp2", "pp2_x_fsdp2_dp2"],+)+def test_pp_env_trainer_matches_one_process(world, env, ref_bs):+ ref = _ref(ref_bs, eval_bs = 2) # eval batches as each dp replica's+ results = _spawn("env", world, env, bs = 2)+ stages = set()+ for rank, res in enumerate(results):+ assert res["is_pp"] and res["pre_split"], res # whole until the Trainer+ if res["stage"] == 1:+ assert res["stage_ids"] and sum(res["stage_ids"]) == sum(res["seen"]), (+ res["stage_ids"],+ res["seen"],+ )+ assert "DistributedDataParallel" not in res["wrapped"]+ assert res["sampler_hooked"], res+ _close(res, ref, what = rank)+ stages.add(res["stage"])+ assert stages == {0, 1}+ owned = [set(r["owned"]) for r in results if r["stage"] == 0][0] | [+ set(r["owned"]) for r in results if r["stage"] == 1+ ][0]+ assert not (+ [set(r["owned"]) for r in results if r["stage"] == 0][0]+ & [set(r["owned"]) for r in results if r["stage"] == 1][0]+ )+ assert owned, owned+ _same_tensors(results[0]["adapter"], ref["adapter"], what = "save_pretrained")+ _same_tensors(results[0]["trainer_adapter"], ref["adapter"], what = "Trainer.save_model")+ dp = 2 if world == 4 and "UNSLOTH_TP_SIZE" not in env else 1+ by_replica = {}+ for rank, res in enumerate(results):+ by_replica.setdefault(rank % dp if dp > 1 else 0, []).append(res["seen"])+ for replica, seen in by_replica.items():+ assert all(s == seen[0] for s in seen), (+ replica,+ seen,+ ) # every stage of a replica: same rows+ if dp > 1:+ assert by_replica[0][0] != by_replica[1][0]+ replica_ok = "UNSLOTH_TP_SIZE" not in env and "UNSLOTH_FSDP2" not in env+ for rank, res in enumerate(results):+ if replica_ok:+ assert res["kept_on_cpu"] is True, res["kept_on_cpu"]+ assert res["generated"] == ref["generated"], (rank, res["generated"], ref["generated"])+ assert res["replica_active"] and res["released"], res+ assert res["replica_training"] == [], res["replica_training"]+ assert res["released_by_save"], res+ assert res["after_generate"] is None, res["after_generate"]+ if rank == 0:+ _same_tensors(res["export"], ref["export"], what = "export")+ else:+ assert res["export_other"] == sorted(ref["export"]), res["export_other"]+ else:+ assert "not supported yet on a pipeline parallel x" in (+ res["generate_refused"] or ""+ ), res+ assert "UNSLOTH_PP_SIZE=2" in res["generate_refused"], res["generate_refused"]+ assert res["export_refused"] == res["generate_refused"].replace(+ "`generate`", "`export`"+ )+++@needs_pipelining+ "ga,bs,mb,schedule,arch",+ [+ (1, 4, None, None, "llama"),+ (4, 2, None, None, "llama"),+ (2, 4, "1", None, "llama"),+ (2, 1, None, "1f1b", "llama"),+ (1, 4, None, None, "gemma3"),+ ],+ ids = ["ga1_bs4", "ga4_bs2", "mb1", "bs1_1f1b_padded", "gemma3_ga1_bs4"],+)+def test_pp_env_gradient_accumulation_and_microbatches(ga, bs, mb, schedule, arch):+ if mb == "1" and tuple(int(x) for x in torch.__version__.split("+")[0].split(".")[:2]) < (+ 2,+ 13,+ ):+ # torch 2.10's gpipe needs micro-batches >= stages; Unsloth raises a ValueError naming both counts.+ pytest.skip("gpipe with 1 micro-batch over 2 stages needs torch >= 2.13")+ # bs1_1f1b_padded: 1F1B needs 2 micro-batches, so the 1-row batch gets a fully masked filler row.+ # gemma3_ga1_bs4: the Gemma3_(270M) notebook's shape (scaled tied embedding, sliding layers).+ ref = _ref(bs, ga = ga, evaluate = False, post = False, arch = arch)+ env = {"UNSLOTH_PP_SIZE": "2"}+ if mb:+ env["UNSLOTH_PP_MICROBATCHES"] = mb+ if schedule:+ env["UNSLOTH_PP_SCHEDULE"] = schedule+ for rank, res in enumerate(+ _spawn("env", 2, env, bs = bs, ga = ga, evaluate = False, post = False, arch = arch)+ ):+ _close(res, ref, what = rank)+ _same_tensors(res["adapter"] or ref["adapter"], ref["adapter"])+++@needs_pipelining+def test_pp_env_stages_train_on_the_first_stage_batch():+ # Failing before: each stage collated its own batch, so with a stochastic collator the last stage scored labels+ # for tokens the first stage never embedded.+ results = _spawn(+ "env", 2, {"UNSLOTH_PP_SIZE": "2"}, bs = 2, noisy = True, evaluate = False, post = False+ )+ first, last = sorted(results, key = lambda r: r["stage"])+ assert first["seen"] != last["seen"] # the collators did diverge+ assert last["stage_ids"] and sum(last["stage_ids"]) == sum(first["seen"]), (+ last["stage_ids"],+ first["seen"],+ )+++@needs_pipelining[email protected]("world", [2, 4], ids = ["pp2", "pp2_x_ddp2"])+def test_pp_env_checkpoint_resume_equals_uninterrupted(world):+ for rank, res in enumerate(_spawn("resume", world, {"UNSLOTH_PP_SIZE": "2"})):+ a, b = res["a"], res["b"]+ assert a["steps"] == [1, 2, 3, 4] and b["steps"] == [1, 2, 3, 4], (a, b)+ assert (+ "adapter_model.safetensors" in res["files"] and f"rank{rank:05d}.pt" in res["files"]+ ), res["files"]+ assert b["losses"][2:] == a["losses"][2:] and b["norms"][2:] == a["norms"][2:], (rank, a, b)+ assert res["same"], rank+++@needs_pipelining+def test_pp_env_fp16_scaler_unscales_once():+ for res in _spawn("scaler_clip", 2):+ assert (+ res["norm"] > 0 and res["max_rel"] < 1e-3+ ), res # update == -lr x the unscaled gradient+ for res in _spawn("scaler_clip", 2, wrapper_unscale = True):+ assert (+ res["max_rel"] > 0.9+ ), res # unscaled twice: the update is 1 / 1024 of it (the bug this pins)+++@needs_pipelining+def test_pp_env_tensor_peers_train_on_one_batch():+ # Failing before: only the pipeline group took the first stage's batch, so under pp=2,tp=2 a stochastic+ # collator left tensor parallel peers [0, 1] / [2, 3] reducing activations of different examples.+ results = _spawn(+ "env",+ 4,+ {"UNSLOTH_PP_SIZE": "2", "UNSLOTH_TP_SIZE": "2"},+ bs = 2,+ noisy = True,+ evaluate = False,+ post = False,+ )+ assert results[0]["seen"] != results[1]["seen"] # the tensor peers' collators did diverge+ first = [r for r in results if r["stage"] == 0]+ last = [+ r for r in results if r["stage"] == 1+ ] # the scoring stage records the ids it trained on+ sums = [sum(r["stage_ids"]) for r in last]+ assert len(last) == 2 and all(r["stage_ids"] for r in last), sums+ assert sums == [sum(first[0]["seen"])] * 2, (sums, [sum(r["seen"]) for r in first])diff --git a/tests/test_pp_native_fp16_skip_gloo.py b/tests/test_pp_native_fp16_skip_gloo.pyindex b90fae1d601..7fcaa9c4ad3 100644--- a/tests/test_pp_native_fp16_skip_gloo.py+++ b/tests/test_pp_native_fp16_skip_gloo.py@@ -22,7 +22,8 @@ import torch # noqa: E402sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from test_pp_native_gloo import LLAMA, _free_port, _torch_pipelining_error, batch, build, ppn # noqa: E402-RECIPES = ("pp_unscale", "scaler_unscale", "scaler_step_only")+# fused_step_only: a fused optimizer (adamw_torch_fused), whose scaler.step checks infs without unscale_.+RECIPES = ("pp_unscale", "scaler_unscale", "scaler_step_only", "fused_step_only")def _one_step(rank, world, recipe, inf_rank):@@ -33,8 +34,12 @@ def _one_step(rank, world, recipe, inf_rank):mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)- opt = torch.optim.SGD(pp.parameters(), lr = 1.0)+ if recipe == "fused_step_only":+ opt = torch.optim.AdamW(pp.parameters(), lr = 1.0, fused = True)+ else:+ opt = torch.optim.SGD(pp.parameters(), lr = 1.0)pp.step(ids, labels, scaler = scaler)+ trained = len(pp.__dict__.get("_unsloth_trained_names", ()))if rank == inf_rank:pp.parameters()[0].grad.view(-1)[0] = float("inf")before = [p.detach().clone() for p in pp.parameters()]@@ -56,6 +61,7 @@ def _one_step(rank, world, recipe, inf_rank):"unchanged": all(torch.equal(a, b) for a, b in zip(before, after)),"scale": float(scaler.get_scale()),"picklable": picklable,+ "trained": trained,}@@ -175,6 +181,8 @@ def test_pp2_finite_step_updates_every_stage(recipe):results = _spawn("step", recipe = recipe, inf_rank = -1)assert [r["unchanged"] for r in results] == [False, False], (recipe, results)assert [r["scale"] for r in results] == [1024.0, 1024.0], (recipe, results)+ # Native steps record what each stage trains, so a later requires_grad_(False) still syncs it.+ assert all(r["trained"] > 0 for r in results), resultsdef test_pp2_clip_before_unscale_is_refused():diff --git a/tests/test_pp_native_gloo.py b/tests/test_pp_native_gloo.pyindex 3b329622a4d..fc2954beee3 100644--- a/tests/test_pp_native_gloo.py+++ b/tests/test_pp_native_gloo.py@@ -301,8 +301,16 @@ def _case_ga(rank, world, tmp, arch, n_mb):# [1, seq] position_ids (the default positions) are broadcast to every micro-batch.loss = float(pp.step(ids, labels, position_ids = torch.arange(ids.shape[1])[None]))grads = {n: p.grad.detach().clone() for n, p in model.named_parameters() if p.grad is not None}+ # Failing before: eval_loss did not expand [1, seq] kwargs ("Expecting 2 arg_mbs but got 1").+ eval_loss = float(pp.eval_loss(ids, labels, position_ids = torch.arange(ids.shape[1])[None]))# Unscaled-mean mistake check: what scale_grads=True (divide by n_mb) would have produced.- return {"ga_loss": total, "ga_grads": ga_grads, "loss": loss, "grads": grads}+ return {+ "ga_loss": total,+ "ga_grads": ga_grads,+ "loss": loss,+ "grads": grads,+ "eval_loss": eval_loss,+ }def _case_scaler(rank, world, tmp):@@ -685,6 +693,7 @@ def test_pp2_tied_embeddings_kept_on_both_ends():def test_pp2_microbatches_equal_gradient_accumulation(n_mb):for res in _spawn("ga", 2, arch = "qwen3", n_mb = n_mb):assert res["loss"] == pytest.approx(res["ga_loss"], rel = 1e-5)+ assert res["eval_loss"] == pytest.approx(res["ga_loss"], rel = 1e-5)assert res["grads"]for name, grad in res["grads"].items():torch.testing.assert_close(grad, res["ga_grads"][name], rtol = 1e-4, atol = 1e-6, msg = name)diff --git a/tests/test_return_logits_survives_for_training.py b/tests/test_return_logits_survives_for_training.pyindex 7ab1098835f..2cc8ba82f7e 100644--- a/tests/test_return_logits_survives_for_training.py+++ b/tests/test_return_logits_survives_for_training.py@@ -75,7 +75,10 @@ def _fast_base_model():# Follow the lifted code into every other _utils.py helper it names, so a guard either method# gains (for_inference's tensor parallel refusal, #15137) runs here instead of resolving to None.helpers = {n.name: n for n in utils.body if isinstance(n, ast.FunctionDef)}- lifted = {n.name for n in wanted}+ # Helpers that import a sibling module (a relative import has no package in this namespace): stubbed with what+ # they return for these fakes. A model split by hand (apply_pipeline_parallel) keeps no UNSLOTH_PP_SIZE replica.+ stubbed = {"_pipeline_keeps_replica": lambda model: False}+ lifted = {n.name for n in wanted} | set(stubbed)todo = list(wanted)while todo:for ref in ast.walk(todo.pop()):@@ -85,7 +88,9 @@ def _fast_base_model():lifted.add(node.name)wanted.insert(0, node)todo.append(node)- namespace = _Namespace(os = os, inspect = inspect, torch = _torch_or_stub(), functools = functools)+ namespace = _Namespace(+ os = os, inspect = inspect, torch = _torch_or_stub(), functools = functools, **stubbed+ )module = ast.fix_missing_locations(ast.Module(body = wanted, type_ignores = []))exec(compile(module, str(MODELS / "vision.py"), "exec"), namespace)for name in ("for_inference", "for_training"):@@ -254,3 +259,25 @@ def test_generated_trainer_init_never_writes_the_flag():)assert FLAG not in ast.unparse(patcher)assert FLAG not in _template()+++def test_train_restores_eval_without_a_replica_on_a_parallel_trainer():+ # Failing before: the restore called for_inference, which gathers a whole replica under tensor / pipeline+ # parallel and is refused for pp x tp, so train() raised after the training finished.+ calls = []+ model = _Model()+ model.for_inference = lambda: calls.append("for_inference")+ model.for_training = lambda use_gradient_checkpointing = None: model.train()++ class _Trainer:+ args = types.SimpleNamespace(gradient_checkpointing = False)+ _unsloth_tensor_parallel = True++ def train(self):+ return "trained"++ trainer = _Trainer()+ trainer.model = model+ model.eval()+ assert _prepare_for_training_mode()(_Trainer.train)(trainer) == "trained"+ assert model.training is False and calls == []diff --git a/tests/test_tp_env_gloo.py b/tests/test_tp_env_gloo.pyindex 485c2b5fb90..25581bf26c0 100644--- a/tests/test_tp_env_gloo.py+++ b/tests/test_tp_env_gloo.py@@ -605,8 +605,11 @@ def test_env_layout_parsing_and_refusals():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]+ # UNSLOTH_PP_SIZE is env-driven too now (models/pp_env.py, tests/test_pp_env_gloo.py).+ assert res["pp"] == (1, 2, 4, False) and res["pp_with_tp"] == (2, 1, 4, False), (+ res["pp"],+ res["pp_with_tp"],+ )assert res["pp_one"] == (2, 2, 4, False)assert res["tp_world"] == (4, 1, 4, False)assert res["ddp"] == (2, 2, 4, False)@@ -788,6 +791,29 @@ def test_env_tp_model_and_model_init_is_refused():assert "model_init" in res["refused"], res+def _pipelining_step_outputs():+ try:+ import inspect++ from torch.distributed.pipelining import ScheduleGPipe+ except Exception:+ return False+ return "return_outputs" in inspect.signature(ScheduleGPipe.step).parameters++[email protected](not _pipelining_step_outputs(), reason = "UNSLOTH_PP_SIZE needs torch >= 2.10")[email protected]("import_only", [False, True], ids = ["patched", "plain_import"])[email protected]("hooked", [False, True], ids = ["plain", "unsloth_loaders"])+def test_env_pp_model_init_is_refused(hooked, import_only):+ """The same silent DDP under UNSLOTH_PP_SIZE: the pipeline split runs on the __init__ model only."""+ for res in _spawn(+ "model_init", 2, {"UNSLOTH_PP_SIZE": "2"}, hooked = hooked, import_only = import_only+ ):+ assert "UNSLOTH_PP_SIZE=2 (pipeline parallel)" in (res["refused"] or ""), res+ assert "unset UNSLOTH_PP_SIZE." in res["refused"], res+ assert "model_init" in res["refused"] and res["built"] == [], res++@pytest.mark.parametrize("hooked", [False, True], ids = ["plain", "unsloth_loaders"])def test_env_tp_model_init_is_refused_after_plain_import(hooked):"""Only `import unsloth`: nothing installed the Trainer wrapper before model_init ran, so it trained."""diff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.pyindex 6e1dfee2f7d..ed116542d97 100644--- a/tests/test_tp_native_gloo.py+++ b/tests/test_tp_native_gloo.py@@ -6,8 +6,9 @@import multiprocessingimport os-if multiprocessing.parent_process() is not None or getattr(- multiprocessing.current_process(), "_inheriting", False+if os.environ.get("UNSLOTH_TEST_RANKS_ON_GPU") != "1" and (+ 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 hostsdiff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 2ecd3563594..9af4d7e9b03 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -34,6 +34,13 @@ if os.environ.get("UNSLOTH_DEBUG_DISTRIBUTED"):_apply_debug_distributed_env()del _apply_debug_distributed_env+# UNSLOTH_PARALLEL="dp=..,tp=..,pp=..,cp=.." -> UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE / UNSLOTH_CP_SIZE / UNSLOTH_FSDP2,+# before anything below reads those. A conflict with a variable set by hand raises here, on every rank.+from .parallel_env import apply_parallel_env as _apply_parallel_env, parallelize++_apply_parallel_env()+del _apply_parallel_env+# UNSLOTH_FSDP2=1 under plain torchrun: export accelerate's FSDP2 launch env before transformers or# accelerate read it. A conflicting launch (DeepSpeed, FSDP_VERSION=1) raises here, on every rank.from .fsdp2_launch import apply_unsloth_fsdp2_launch_env as _apply_fsdp2_env@@ -1710,7 +1717,7 @@ else:if any(os.environ.get(_name, "").strip() not in ("", "1")- for _name in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE")+ for _name in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE", "UNSLOTH_CP_SIZE")):from .models.tp_env import (install_tensor_parallel_env_trainer_init as _install_tp_trainer_init,diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.pyindex 6a688124c0c..5170f377ff8 100644--- a/unsloth/context_parallel.py+++ b/unsloth/context_parallel.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport contextlibimport functools+import typesimport weakreffrom typing import Iterator, Optional@@ -34,7 +35,7 @@ except ImportError:SDPBackend = Nonesdpa_kernel = None-_CP_BACKENDS = ("ring", "ulysses")+_CP_BACKENDS = ("auto", "ring", "ulysses")_ROTATE_METHODS = ("allgather", "alltoall")@@ -96,7 +97,7 @@ def context_parallel_options(config) -> tuple:raise ValueError(f"Unsloth: context_parallel_size must be a positive integer, got {size!r}.")- backend = getattr(config, "context_parallel_backend", None) or "ring"+ backend = getattr(config, "context_parallel_backend", None) or "auto"if backend not in _CP_BACKENDS:raise ValueError(f"Unsloth: context_parallel_backend must be one of {_CP_BACKENDS}, got {backend!r}."@@ -110,6 +111,41 @@ def context_parallel_options(config) -> tuple:return size, backend, rotate_method+def _model_heads(model):+ config = getattr(model, "config", None)+ text = getattr(config, "text_config", None) or config+ heads = getattr(text, "num_attention_heads", None)+ if not isinstance(heads, int):+ return None, None+ kv = getattr(text, "num_key_value_heads", None)+ return heads, kv if isinstance(kv, int) and kv > 0 else heads+++def resolve_cp_backend(+ backend,+ size: int,+ model = None,+ tp: int = 1,+ rl: bool = False,+) -> str:+ """context_parallel_backend = 'auto' (the default): Ulysses, which keeps packing, hybrids, RL, T4 / V100+ and needs no flash kernels; ring only when the attention heads (per tensor parallel rank) cannot be split+ over cp. An explicit backend is returned as given (the checks then honour or refuse it)."""+ backend = backend or "auto"+ if backend != "auto" or size <= 1:+ return backend+ if rl:+ return "ulysses"+ heads, kv = _model_heads(model)+ if heads is None:+ return "ulysses"+ try:+ ulysses_head_plan(heads // tp, kv // tp if kv % tp == 0 else kv, size)+ except ValueError:+ return "ring"+ return "ulysses"++def _unsupported_attention(config, backend = "ring") -> Optional[str]:# Ring and Llama's forward ignore mask, window and softcap, so both backends refuse them.allowed = {"full_attention", "linear_attention"} if backend == "ulysses" else {"full_attention"}@@ -274,11 +310,26 @@ class ContextParallelManager:backend: str = "ring",rotate_method: str = "allgather",fsdp2: bool = False,+ layout = None,):self.size = sizeself.backend = backendself.rotate_method = rotate_methodself.fsdp2 = fsdp2+ if layout is not None:+ # UNSLOTH_PARALLEL / UNSLOTH_TP_SIZE with UNSLOTH_CP_SIZE: the cp axis of the one root mesh+ # (parallel_env.ParallelLayout). Tensor parallel splits the rows over dp only and averages the+ # gradients over the flattened (dp, cp) mesh, so nothing is installed on the accelerator here.+ if layout.cp != size:+ raise RuntimeError(+ f"Unsloth: context_parallel_size = {size} but the parallel layout has cp {layout.cp}."+ )+ self.layout = layout+ self.fsdp2 = False+ self.device_mesh = None+ self.mesh = layout.cp_mesh+ return+ self.layout = Noneworld_size = dist.get_world_size()# FSDP2 shards parameters over dp_shard x cp flattened (torchtitan, accelerate's dp_shard_cp):# CP peers hold different tokens, so their gradients must be reduced like data parallel ones.@@ -628,6 +679,11 @@ def _install_accelerator_state(self):returnif accelerator is None:return+ if manager.device_mesh is None:+ # A root-mesh manager (parallel_env): the tensor parallel hooks split the data and reduce gradients.+ _restore_parallelism_config(accelerator.state)+ _cp_scaler_start(self, accelerator)+ returncurrent = getattr(accelerator.state, "device_mesh", None)if _INSTALLED_MESH and current is _INSTALLED_MESH[0]:current = _INSTALLED_MESH[1] if len(_INSTALLED_MESH) > 1 else None@@ -672,42 +728,360 @@ def _cp_scaler_start(trainer, accelerator) -> None:def _model_parallel_axes(model) -> list:- """Tensor / pipeline parallel axes in use: UNSLOTH_TP_SIZE or a model split by hand."""+ """The tensor / pipeline parallel axes a trainer would combine with context parallelism: from+ UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE (read without building anything) or a model split by hand."""import osaxes = []- raw = str(os.environ.get("UNSLOTH_TP_SIZE", "")).strip()- try:- tp = int(raw) if raw else 1 # as tp_env._int_env, which raises its own error on a bad value- except ValueError:- tp = 1- if tp > 1:- axes.append(f"tensor parallel (UNSLOTH_TP_SIZE={raw})")+ for name, what in (+ ("UNSLOTH_PP_SIZE", "pipeline parallel"),+ ("UNSLOTH_TP_SIZE", "tensor parallel"),+ ):+ raw = str(os.environ.get(name, "")).strip()+ try:+ size = (+ int(raw) if raw else 1+ ) # as tp_env._int_env, which raises its own error on a bad value+ except ValueError:+ size = 1+ if size > 1:+ axes.append(f"{what} ({name}={raw})")if isinstance(model, torch.nn.Module):try:from .models.pp_native import is_pipeline_parallelfrom .models.tp_native import is_tensor_parallelexcept Exception:return axes- if is_pipeline_parallel(model):+ if is_pipeline_parallel(model) and not any(a.startswith("pipeline") for a in axes):axes.append("pipeline parallel (apply_pipeline_parallel)")- if is_tensor_parallel(model) and not axes:+ if is_tensor_parallel(model) and not any(a.startswith("tensor") for a in axes):axes.append("tensor parallel (apply_tensor_parallel)")return axes-def _refuse_model_parallel_cp(size: int, args, kwargs) -> None:- """The CP mesh (world // cp, cp) would reuse a tp launch's groups and silently train on mixed-up shards."""- model = kwargs["model"] if "model" in kwargs else (args[0] if args else None)+def _composed_layout(size: int):+ """The UNSLOTH_PARALLEL / UNSLOTH_TP_SIZE layout whose root mesh has this cp axis, or None."""+ import os++ if not any(+ str(os.environ.get(k, "")).strip() not in ("", "1")+ for k in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE")+ ):+ return None+ from .parallel_env import env_cp_size++ if env_cp_size() != size:+ return None # cp from the trainer config only: the layout was read without a cp axis+ from .models.tp_env import env_layout++ layout = env_layout()+ return layout if layout is not None and layout.cp == size else None+++def _refuse_model_parallel_cp(+ size: int,+ model,+ trainer_cls = None,+ config = None,+ peft_config = None,+ backend = None,+) -> None:+ """Before the trainer's __init__ touches the model: a CP manager building its own (dp, cp) mesh would make+ its cp groups the tensor parallel / pipeline data parallel groups of a tp / pp launch, so the step would run+ and train on mixed-up shards. Context parallel composes through the root mesh only (cp in UNSLOTH_PARALLEL+ or UNSLOTH_CP_SIZE, read with the layout); the capability registry decides which compositions run."""axes = _model_parallel_axes(model)+ import os+if not axes:+ # Context parallel alone (DDP or native FSDP2 over the rest): the registry's rules and cells too.+ import types++ from .fsdp2_launch import unsloth_fsdp2_native_requested+ from .parallel_capabilities import check_layout++ try:+ world = int(os.environ.get("WORLD_SIZE", "1") or 1)+ except ValueError:+ world = 1+ try:+ fsdp2 = bool(unsloth_fsdp2_native_requested())+ except Exception:+ fsdp2 = False+ alone = types.SimpleNamespace(+ dp = max(world // size, 1),+ tp = 1,+ pp = 1,+ cp = size,+ fsdp2 = fsdp2,+ cp_backend = None,+ schedule = None,+ )+ # A constructor kwarg (context_parallel_backend = ...) overrides the config's value.+ backend = backend or getattr(config, "context_parallel_backend", None)+ check_layout(alone, trainer_cls, model, config, cp_backend = backend, peft_config = peft_config)return++ layout = _composed_layout(size) if all("UNSLOTH_" in a for a in axes) else None+ if layout is not None:+ from .parallel_capabilities import check_layout++ backend = backend or getattr(config, "context_parallel_backend", None) or layout.cp_backend+ check_layout(+ layout, trainer_cls, model, config, cp_backend = backend, peft_config = peft_config+ )+ return+ env_cp = str(os.environ.get("UNSLOTH_CP_SIZE", "")).strip()+ hint = ""+ if not env_cp and all("UNSLOTH_" in a for a in axes):+ hint = (+ f' To compose them, put cp in the launch layout instead: UNSLOTH_PARALLEL="...,cp={size}" or '+ f"UNSLOTH_CP_SIZE={size} beside the other variables, so the mesh is built with a cp axis."+ )raise NotImplementedError(f"Unsloth: context parallelism (context_parallel_size = {size}) does not compose with "f"{' and '.join(axes)} yet: its context parallel groups would be the other axis' groups, and training ""would run with wrong gradients. Use context parallelism alone (with DDP or UNSLOTH_FSDP2=1), or "- "tensor / pipeline parallelism with context_parallel_size = 1."+ "tensor / pipeline parallelism with context_parallel_size = 1." + hint+ )+++def _trainer_model_argument(args, kwargs):+ if "model" in kwargs:+ return kwargs["model"]+ # (self, model, args, ...) for every Trainer / TRL trainer __init__.+ return args[1] if len(args) > 1 else None+++_CP_KWARGS = ("context_parallel_size", "context_parallel_backend", "context_parallel_rotate_method")+++def _default_cp_config(+ config_cls,+ args,+ kwargs,+ name = None,+):+ """The trainer was called without `args` but with context parallel on (UNSLOTH_CP_SIZE, cp in+ UNSLOTH_PARALLEL, or context_parallel_size = N as a constructor kwarg). The trainer's __init__ takes no+ such kwarg, and _backwards_compatible_trainer only moves them into a config it was given, so build the+ default config the trainer would build, move the CP kwargs onto it and pass it as `args`."""+ config = config_cls(name) if name else config_cls()+ for key in _CP_KWARGS:+ if key in kwargs:+ setattr(config, key, kwargs.pop(key))+ if len(args) > 1: # SFTTrainer(model, None, ...): args excludes self+ args = args[:1] + (config,) + args[2:]+ else:+ kwargs["args"] = config+ return config, args+++def _cp_requested(kwargs) -> bool:+ from .parallel_env import env_cp_size++ forwarded = kwargs.get("context_parallel_size")+ forwarded = forwarded if isinstance(forwarded, int) and not isinstance(forwarded, bool) else 1+ return forwarded > 1 or env_cp_size() > 1+++def _sft_default_name(model):+ # TRL's SFTTrainer: args = SFTConfig(f"{model_name}-SFT").+ name = (+ model+ if isinstance(model, str)+ else getattr(getattr(model, "config", None), "_name_or_path", None)+ )+ name = str(name or "").rstrip("/").split("/")[-1]+ return f"{name}-SFT" if name else None+++def _declares_cp_fields(config) -> bool:+ import dataclasses+ if not dataclasses.is_dataclass(config):+ return True # a plain namespace / object keeps what is set on it+ return "context_parallel_size" in {f.name for f in dataclasses.fields(config)}+++class _ConfigOverlay:+ """The trainer config as the trainer will see it: constructor kwargs that name config fields+ (SFTTrainer(..., router_aux_loss_coef = 0.0)) win, as Unsloth's trainer wrapper moves them into the config."""++ def __init__(self, base, overrides):+ self.__dict__["_base"] = base+ self.__dict__["_overrides"] = overrides++ @property+ def __class__(self):+ return type(self.__dict__["_base"])++ def __getattr__(self, name):+ overrides = self.__dict__["_overrides"]+ return overrides[name] if name in overrides else getattr(self.__dict__["_base"], name)+++def _effective_config(config, kwargs):+ if config is None:+ return None+ overrides = {+ k: v+ for k, v in kwargs.items()+ if k not in ("model", "args", "peft_config") and hasattr(config, k)+ }+ return _ConfigOverlay(config, overrides) if overrides else config+++def _positional_config_to_keyword(+ init,+ self,+ args,+ kwargs,+ require_args = True,+):+ """(args, kwargs) with a positional trainer config passed as `args = ...` instead (every positional bound+ to its name), so Unsloth's trainer wrapper rebuilds it with the cp values set as kwargs. Unchanged when the+ signature cannot bind them."""+ import inspect++ try:+ bound = inspect.signature(init).bind(self, *args, **kwargs)+ except (TypeError, ValueError):+ return args, kwargs+ params = inspect.signature(init).parameters+ if any(+ p.kind is inspect.Parameter.VAR_POSITIONAL and bound.arguments.get(n)+ for n, p in params.items()+ ):+ return args, kwargs+ if require_args and "args" not in bound.arguments:+ return args, kwargs+ out = {}+ for i, (name, value) in enumerate(bound.arguments.items()):+ if i == 0:+ continue # self+ if params[name].kind is inspect.Parameter.VAR_KEYWORD:+ out.update(value)+ else:+ out[name] = value+ return (), out+++def _inject_env_cp(config, kwargs, requested: int, trainer_name: str) -> int:+ """UNSLOTH_CP_SIZE / UNSLOTH_CP_BACKEND (also from UNSLOTH_PARALLEL) into the trainer arguments, the way+ SFTTrainer(context_parallel_size = N) is handled. Returns the context parallel size the trainer will get."""+ from .parallel_env import env_cp_backend, env_cp_size++ size = env_cp_size()+ backend = env_cp_backend()+ if config is not None and not _declares_cp_fields(config):+ # Plain TrainingArguments: Unsloth's trainer wrapper rebuilds the trainer config from to_dict(), which drops+ # attributes set here, so the values travel as trainer kwargs (routed into the new config).+ config = None+ if size == 1:+ if backend is not None and requested > 1:+ if config is not None and "context_parallel_backend" not in kwargs:+ config.context_parallel_backend = backend+ else:+ kwargs["context_parallel_backend"] = backend+ return requested+ if requested > 1 and requested != size:+ raise ValueError(+ f"Unsloth: {trainer_name} asks for context_parallel_size = {requested}, but UNSLOTH_CP_SIZE={size} "+ "(or cp in UNSLOTH_PARALLEL) asks for another; use one of the two."+ )+ if "context_parallel_size" in kwargs or config is None:+ kwargs["context_parallel_size"] = size+ if backend is not None:+ kwargs["context_parallel_backend"] = backend+ else:+ config.context_parallel_size = size+ if backend is not None:+ config.context_parallel_backend = backend+ return size+++def _resolve_auto_backend(+ config,+ kwargs,+ size: int,+ model,+ rl: bool = False,+) -> None:+ """Write the backend 'auto' resolves to into the trainer arguments before the trainer's __init__, so auto+ packing and every later check read the same backend. `_unsloth_cp_backend_auto` records that it was auto."""+ in_kwargs = "context_parallel_backend" in kwargs+ current = (+ kwargs["context_parallel_backend"]+ if in_kwargs+ else getattr(config, "context_parallel_backend", None))+ if (current or "auto") != "auto":+ return+ if isinstance(model, str) and not rl:+ # A model id is loaded inside the trainer's __init__, after this commits the backend: read its heads+ # from the config now, so 'auto' picks ring when they cannot be split over cp.+ try:+ # The trainer's own loader options (subfolder, revision, token, cache_dir, trust_remote_code).+ from .trainer import _resolve_string_model_config+ model_config = _resolve_string_model_config(model, config)+ model = types.SimpleNamespace(config = model_config) if model_config is not None else None+ except Exception:+ model = None+ layout = _composed_layout(size)+ resolved = resolve_cp_backend(+ "auto", size, model, tp = layout.tp if layout is not None else 1, rl = rl+ )+ if in_kwargs or config is None:+ kwargs["context_parallel_backend"] = resolved+ else:+ config.context_parallel_backend = resolved+ try:+ config._unsloth_cp_backend_auto = True+ except Exception:+ pass+++def _check_native_fsdp2_reduces_over_cp(model, manager) -> None:+ """UNSLOTH_FSDP2=1 (native FSDP2, models/fsdp2_native.py) shards inside Trainer.__init__ without knowing about+ context parallel. CP peers hold different tokens of the same rows, so their gradients must be reduced together:+ the FSDP2 mesh must contain the cp group (the world mesh does: FSDP2 then shards over dp_shard x cp, and its+ gradient average over dp x cp matches the CP token count). A sub-mesh that splits a cp group is refused."""+ try:+ from .models.fsdp2_native import is_native_fsdp2+ from .models.fsdp2_save import model_mesh+ except Exception:+ return+ if not is_native_fsdp2(model):+ return+ mesh = model_mesh(model)+ manager.fsdp2_native = True+ if mesh is None:+ return # the default world group+ fsdp_ranks = set(int(r) for r in mesh.mesh.flatten().tolist())+ cp_ranks = set(int(r) for r in manager.mesh.mesh.flatten().tolist())+ if not cp_ranks <= fsdp_ranks:+ raise NotImplementedError(+ f"Unsloth: cp x fsdp2: native FSDP2 shards over ranks {sorted(fsdp_ranks)}, which leaves out context "+ f"parallel peers {sorted(cp_ranks - fsdp_ranks)}; their gradients would not be reduced together. "+ "Instead: let UNSLOTH_PARALLEL / UNSLOTH_FSDP2=1 shard over the whole (dp_shard, cp) mesh (no FSDP2 "+ "sub-mesh), or drop cp."+ )+++def _refuse_router_aux_loss_after_init(trainer, size: int) -> None:+ """TRL's SFTTrainer / DPOTrainer set output_router_logits on the config inside their __init__ (from the+ architecture's router_aux_loss_coef unless router_aux_loss_coef = 0.0). A load balancing loss computed per+ sequence shard is not the one-process objective; this catches what the pre-init registry check predicted."""+ from .parallel_capabilities import Query, _moe, check++ moe, aux = _moe(getattr(trainer, "model", None))+ # DPO passes output_router_logits per forward instead of writing the config: read the trainer's switch too.+ aux = aux or bool(getattr(trainer, "aux_loss_enabled", False))+ if moe and aux:+ check(+ Query(trainer = "sft", moe = True, router_aux_loss = True, cp = size, torch = (99, 0)),+ cells = False,+ )def _check_cp_runtime(self, size: int, backend: str) -> None:@@ -744,6 +1118,7 @@ def _check_cp_model(size: int,backend: str,allow_hybrids: bool = True,+ tp: int = 1,) -> None:model_config = getattr(model, "config", None)unsupported = _unsupported_attention(model_config, backend)@@ -753,12 +1128,10 @@ def _check_cp_model()if backend == "ulysses":# Every rank raises here, before any collective.- text_config = getattr(model_config, "text_config", None) or model_config- ulysses_head_plan(- text_config.num_attention_heads,- getattr(text_config, "num_key_value_heads", None) or text_config.num_attention_heads,- size,- )+ heads, kv_heads = _model_heads(model)+ if heads is not None:+ # Under tensor parallel each rank holds heads / tp of them (and kv heads / tp, or all when fewer).+ ulysses_head_plan(heads // tp, kv_heads // tp if kv_heads % tp == 0 else kv_heads, size)if _stateful_mixers(model) and not allow_hybrids:raise NotImplementedError("Unsloth: DPO / GRPO context parallelism does not support Gated DeltaNet hybrids yet."@@ -809,6 +1182,7 @@ def _check_cp_trainer(backend: str,models,allow_fsdp2: bool = False,+ tp: int = 1,) -> bool:"""Shared trainer checks; returns whether the trainer runs under FSDP2."""import accelerate@@ -819,7 +1193,7 @@ def _check_cp_trainer(for model in models:if model is not None:# SFT shards the inputs of the whole model; the RL hooks only shard Llama-style decoders.- _check_cp_model(model, size, backend, allow_hybrids = allow_fsdp2)+ _check_cp_model(model, size, backend, allow_hybrids = allow_fsdp2, tp = tp)accelerator = getattr(self, "accelerator", None)distributed_type = getattr(getattr(accelerator, "distributed_type", None), "name", "NO")fsdp2 = allow_fsdp2 and _is_fsdp2(accelerator, distributed_type)@@ -900,8 +1274,38 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:forwarded = kwargs["context_parallel_size"]valid = isinstance(forwarded, int) and not isinstance(forwarded, bool)requested = forwarded if valid else 1+ if config is None and (requested > 1 or _cp_requested(kwargs)):+ import sys++ import trl++ model = _trainer_model_argument((self,) + args, kwargs)+ module = sys.modules.get(trainer_cls.__module__)+ config_cls = getattr(module, "UnslothSFTConfig", None) or getattr(+ module, "SFTConfig", None+ )+ config, args = _default_cp_config(+ config_cls or trl.SFTConfig, args, kwargs, _sft_default_name(model)+ )+ if "args" not in kwargs and config is not None and not _declares_cp_fields(config):+ from .parallel_env import env_cp_size+ if env_cp_size() > 1:+ # A positional plain TrainingArguments: the env cp values go into kwargs, which Unsloth's+ # trainer wrapper only folds into a keyword `args`.+ args, kwargs = _positional_config_to_keyword(original_init, self, args, kwargs)+ requested = _inject_env_cp(config, kwargs, requested, "SFTTrainer")if requested > 1:- _refuse_model_parallel_cp(requested, args, kwargs)+ _resolve_auto_backend(+ config, kwargs, requested, _trainer_model_argument((self,) + args, kwargs)+ )+ _refuse_model_parallel_cp(+ requested,+ _trainer_model_argument((self,) + args, kwargs),+ type(self),+ _effective_config(config, kwargs),+ peft_config = kwargs.get("peft_config"),+ backend = kwargs.get("context_parallel_backend"),+ )# Before the original __init__: Unsloth wraps instance methods there (auto packing's# train reset, the token budget's training_step), and they must capture the CP ones.install_methods()@@ -927,6 +1331,15 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:f"{source} with cp_size > 1.")size, backend, rotate_method = context_parallel_options(getattr(self, "args", None))+ if size > 1 and backend == "auto":+ layout = _composed_layout(size)+ backend = resolve_cp_backend(+ backend,+ size,+ getattr(self, "model", None),+ tp = layout.tp if layout is not None else 1,+ )+ self.args.context_parallel_backend = backendif size <= 1:_install_accelerator_state(self)if not trainer_cls.__dict__.get("__unsloth_context_parallel_methods__"):@@ -935,6 +1348,7 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:pre_cp_trainers.append(weakref.ref(self))return_check_cp_runtime(self, size, backend)+ _refuse_router_aux_loss_after_init(self, size)# These recompute loss outside our forward from sharded labels, losing cross-shard targets.if (getattr(self.args, "label_smoothing_factor", 0)@@ -958,10 +1372,23 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:raise NotImplementedError("Unsloth: context parallelism needs average_tokens_across_devices = True.")+ layout = _composed_layout(size)fsdp2 = _check_cp_trainer(- self, size, backend, [getattr(self, "model", None)], allow_fsdp2 = True+ self,+ size,+ backend,+ [getattr(self, "model", None)],+ allow_fsdp2 = True,+ tp = layout.tp if layout is not None else 1,+ )+ manager = ContextParallelManager(+ size,+ backend,+ rotate_method,+ fsdp2 = fsdp2,+ **({"layout": layout} if layout is not None else {}),)- manager = ContextParallelManager(size, backend, rotate_method, fsdp2 = fsdp2)+ _check_native_fsdp2_reduces_over_cp(self.model, manager)self._context_parallel_manager = managerinstall_methods()manager.attach_attention_hooks(self.model)@@ -970,6 +1397,9 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:from .utils.packing import _scope_flash_attention_impl_scope_flash_attention_impl(self.model, self)+ from .parallel_env import announce++ announce(self, layout, manager)print(f"Unsloth: Context parallelism enabled with size = {size} ({backend}"+ (f", rotate_method = {rotate_method})" if backend == "ring" else ")")@@ -1511,6 +1941,16 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:@functools.wraps(original_init)def patched_init(self, *args, **kwargs):+ if "args" not in kwargs and len(args) > 1:+ from .parallel_env import env_cp_size+ if env_cp_size() > 1 or _cp_requested(kwargs):+ # DPOTrainer(model, ref_model, ...): bind the positionals to their names, so a missing or None+ # `args` gets the default config below and the cp values never reach the constructor as kwargs.+ args, kwargs = _positional_config_to_keyword(+ original_init, self, args, kwargs, require_args = False+ )+ if kwargs.get("args", 0) is None:+ kwargs.pop("args")config = kwargs.get("args")if config is None:config = next((x for x in args if hasattr(x, "context_parallel_size")), None)@@ -1518,8 +1958,29 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:requested = context_parallel_options(config)[0]except ValueError:requested = 1 # Raised again after the original __init__.+ # Positional arguments past the model: the config's position differs per trainer, so leave those.+ if config is None and "args" not in kwargs and len(args) <= 1 and _cp_requested(kwargs):+ import sys++ # The generated Unsloth{X}Trainer builds Unsloth{X}Config() for args = None.+ config_cls = getattr(+ sys.modules.get(trainer_cls.__module__),+ trainer_cls.__name__.replace("Trainer", "Config"),+ None,+ )+ if config_cls is not None:+ config, args = _default_cp_config(config_cls, args, kwargs)+ requested = _inject_env_cp(config, kwargs, requested, trainer_cls.__name__)if requested > 1:- _refuse_model_parallel_cp(requested, args, kwargs)+ _resolve_auto_backend(config, kwargs, requested, None, rl = True)+ _refuse_model_parallel_cp(+ requested,+ _trainer_model_argument((self,) + args, kwargs),+ type(self),+ _effective_config(config, kwargs),+ peft_config = kwargs.get("peft_config"),+ backend = kwargs.get("context_parallel_backend"),+ )# Before the original __init__, so instance wrappers made there capture the CP methods.install_methods()original_init(self, *args, **kwargs)@@ -1530,6 +1991,7 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:", context_parallel_backend = 'ulysses'",)size, backend, _ = context_parallel_options(getattr(self, "args", None))+ backend = resolve_cp_backend(backend, size, rl = True)if size <= 1:_install_accelerator_state(self)if not trainer_cls.__dict__.get("__unsloth_context_parallel_methods__"):@@ -1542,6 +2004,7 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:"Unsloth: DPO / GRPO context parallelism needs context_parallel_backend = 'ulysses'.")_check_cp_runtime(self, size, backend)+ _refuse_router_aux_loss_after_init(self, size)_check_rl_config(self, kind)ref_model = getattr(self, "ref_model", None)_check_cp_trainer(self, size, backend, [self.model, ref_model])diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 4184264fdde..c31b7bca645 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -6388,7 +6388,13 @@ 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)- # UNSLOTH_TP_SIZE (unmodified scripts): tensor parallel before native FSDP2 shards the dp dimension.+ # UNSLOTH_PARALLEL / UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE / UNSLOTH_CP_SIZE: the capability registry,+ # before anything below splits or shards the model.+ _parallel_capabilities_pre(self, _original_trainer_init, args, kwargs, model)+ # UNSLOTH_PP_SIZE: trainers / arguments the pipeline step cannot run, refused before the split.+ _pipeline_parallel_env_refusals(self, _original_trainer_init, args, kwargs)+ # UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE (unmodified scripts): the pipeline split, then tensor parallel,+ # before native FSDP2 shards the dp dimension.tp_env = _tensor_parallel_env_trainer_pre(model)if (tp_env is not None@@ -6407,14 +6413,12 @@ 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:+ if native_fsdp2 and tp_env is not None and tp_env.grad_size == 1:+ native_fsdp2 = False # UNSLOTH_TP_SIZE x UNSLOTH_PP_SIZE = world size: no data parallel dimension to shard+ if tp_env is not None and tp_env.grad_size > 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"Unsloth: {tp_env.env_vars} 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."@@ -6458,6 +6462,17 @@ def patch_gradient_accumulation_fix(Trainer):if tensor_parallel:from .tp_native import tp_trainer_setuptp_trainer_setup(phase = "post", trainer = self)+ if _is_env_pipeline_parallel(getattr(self, "model", None)):+ # After the tensor parallel setup: the pipeline schedule owns the step, eval, saves and clipping.+ from .pp_env import pp_trainer_setup+ pp_trainer_setup(self)+ if (+ tp_env is not None+ and (getattr(getattr(self, "args", None), "context_parallel_size", 1) or 1) <= 1+ ):+ # With context parallel the CP setup (after this __init__) prints it, backend included.+ from ..parallel_env import announce+ announce(self, tp_env)try:accelerator = getattr(self, "accelerator", None)if (@@ -6557,13 +6572,145 @@ def _refuse_tensor_parallel_for_trainer(model):_refuse_pipeline_parallel_for_trainer(model)+def _is_env_pipeline_parallel(model):+ """A model split under UNSLOTH_PP_SIZE (models/pp_env.py): the Trainer runs it through the pipeline."""+ if not _is_unsloth_pipeline_parallel(model):+ return False+ from .pp_native import pipeline_stage_of++ stage = pipeline_stage_of(model)+ return stage is not None and getattr(stage, "env_layout", None) is not None++def _refuse_pipeline_parallel_for_trainer(model):- if _is_unsloth_pipeline_parallel(model):+ if _is_unsloth_pipeline_parallel(model) and not _is_env_pipeline_parallel(model):raise RuntimeError("Unsloth: a pipeline parallel model (apply_pipeline_parallel) cannot be trained by the "- "Trainer yet: each rank holds one stage, and a stage cannot run a forward alone. Use a custom "- "training loop with PipelineParallel.step (unsloth/models/pp_native.py)."+ "Trainer: each rank holds one stage, and a stage cannot run a forward alone. Use a custom "+ "training loop with PipelineParallel.step (unsloth/models/pp_native.py), or launch the unchanged "+ "script with UNSLOTH_PP_SIZE (the Trainer then splits the model and runs the pipeline itself)."+ )+++def _trainer_init_args(trainer, init, args, kwargs):+ training_args = kwargs.get("args")+ if training_args is None:+ try:+ import inspect+ bound = inspect.signature(init).bind_partial(trainer, *args, **kwargs)+ training_args = bound.arguments.get("args")+ except (TypeError, ValueError):+ training_args = None+ return training_args+++def _prebuilt_optimizer(trainer, init, args, kwargs):+ optimizers = kwargs.get("optimizers")+ if optimizers is None:+ try:+ import inspect+ bound = inspect.signature(init).bind_partial(trainer, *args, **kwargs)+ optimizers = bound.arguments.get("optimizers")+ except (TypeError, ValueError):+ optimizers = None+ if isinstance(optimizers, (tuple, list)) and optimizers:+ return optimizers[0]+ return None+++def _optimizer_kwargs_hold_params(trainer, init, args, kwargs):+ """Trainer(optimizer_cls_and_kwargs = (cls, {"params": ...})) carries parameters chosen before __init__."""+ value = kwargs.get("optimizer_cls_and_kwargs")+ if value is None:+ try:+ import inspect+ bound = inspect.signature(init).bind_partial(trainer, *args, **kwargs)+ value = bound.arguments.get("optimizer_cls_and_kwargs")+ except (TypeError, ValueError):+ value = None+ if not isinstance(value, (tuple, list)) or len(value) < 2 or not isinstance(value[1], dict):+ return False+ return "params" in value[1]+++def _parallel_capabilities_pre(trainer, init, args, kwargs, model):+ from .. import fsdp2_launch as _launch++ try:+ native_fsdp2 = bool(_launch.unsloth_fsdp2_native_requested())+ except Exception:+ native_fsdp2 = False+ tp_env_set = os.environ.get("UNSLOTH_TP_SIZE", "").strip() not in ("", "1")+ if native_fsdp2 or tp_env_set:+ # Before anything is sharded: a prebuilt Muon (or args.optim naming one) would orthogonalize shards.+ from ..parallel_capabilities import refuse_shard_unaware_optimizer++ optimizer = _prebuilt_optimizer(trainer, init, args, kwargs)+ if optimizer is None:+ optim = getattr(_trainer_init_args(trainer, init, args, kwargs), "optim", None)+ optimizer = str(getattr(optim, "value", optim) or "") # its name only+ for what, on in (("fsdp2", native_fsdp2), ("tp", tp_env_set)):+ if on:+ refuse_shard_unaware_optimizer(optimizer, what)+ if not any(+ os.environ.get(name, "").strip() not in ("", "1")+ for name in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE", "UNSLOTH_CP_SIZE")+ ):+ return+ from ..parallel_env import env_cp_size+ from ..parallel_capabilities import check_layout++ cp = env_cp_size()+ if cp > 1 and not getattr(type(trainer), "__unsloth_context_parallel__", False):+ raise NotImplementedError(+ f"Unsloth: cp x trainer: context parallel (UNSLOTH_CP_SIZE={cp}) runs through SFTTrainer, "+ f"DPOTrainer and GRPOTrainer; {type(trainer).__name__} would train every rank on the whole sequence. "+ "Instead: use SFTTrainer (a plain Trainer script: SFTTrainer takes the same arguments), or drop cp."+ )+ from .tp_env import env_layout++ layout = env_layout()+ training_args = _trainer_init_args(trainer, init, args, kwargs)+ if layout is None:+ return # context parallel alone: the CP trainer setup checks it+ backend = getattr(training_args, "context_parallel_backend", None) or layout.cp_backend+ check_layout(layout, type(trainer), model, training_args, cp_backend = backend)+++def _pipeline_parallel_env_refusals(trainer, init, args, kwargs):+ if not os.environ.get("UNSLOTH_PP_SIZE"):+ return+ from .tp_env import env_layout++ layout = env_layout()+ if layout is None or layout.pp == 1:+ return+ training_args = kwargs.get("args")+ compute_loss_func = kwargs.get("compute_loss_func")+ if training_args is None or (compute_loss_func is None and args):+ try:+ import inspect++ bound = inspect.signature(init).bind_partial(trainer, *args, **kwargs)+ training_args = bound.arguments.get("args", training_args)+ compute_loss_func = bound.arguments.get("compute_loss_func", compute_loss_func)+ except (TypeError, ValueError):+ pass+ if layout.tp > 1 and (+ _prebuilt_optimizer(trainer, init, args, kwargs) is not None+ or _optimizer_kwargs_hold_params(trainer, init, args, kwargs)+ ):+ # The tensor parallel split happens in Trainer.__init__ under a pipeline launch and replaces the+ # trainable parameters: an optimizer built before it would step the old ones (training does nothing).+ raise NotImplementedError(+ f"Unsloth: {layout.env_vars} (pipeline x tensor parallel): Trainer(optimizers = (optimizer, ...)) or "+ "optimizer_cls_and_kwargs = (cls, {'params': ...}) holds "+ "parameters the tensor parallel split replaces, so it would never update the model. Let the Trainer "+ "build the optimizer (TrainingArguments optim / learning_rate), or override create_optimizer.")+ from .pp_env import pp_trainer_refusals++ pp_trainer_refusals(type(trainer), training_args, layout, compute_loss_func = compute_loss_func)def _tensor_parallel_env_trainer_pre(model):@@ -6574,7 +6721,8 @@ def _tensor_parallel_env_trainer_pre(model):def _refuse_tensor_parallel_env_model_init(layout, init, args, kwargs):- """UNSLOTH_TP_SIZE setup runs on the __init__ model, so a model_init model would silently train as plain DDP."""+ """UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE setup runs on the __init__ model, so a model_init model would silently+ train as plain DDP."""model_init = kwargs.get("model_init")if model_init is None:import inspect@@ -6605,11 +6753,20 @@ def _refuse_tensor_parallel_env_model_init(layout, init, args, kwargs):index = names.index("model_init")model_init = args[index] if index < len(args) else Noneif model_init is not None:+ pp = getattr(layout, "pp", 1) > 1+ what = "pipeline parallel" if pp else "tensor parallel"+ if pp and layout.tp > 1:+ what += " x tensor parallel"+ names = (+ " and ".join(v.split("=")[0] for v in layout.env_vars.split())+ if pp+ else "UNSLOTH_TP_SIZE"+ )raise RuntimeError(- f"Unsloth: UNSLOTH_TP_SIZE={layout.tp} (tensor parallel) does not support "+ f"Unsloth: {layout.env_vars if pp else f'UNSLOTH_TP_SIZE={layout.tp}'} ({what}) does not support ""`Trainer(model_init = ...)` or `hyperparameter_search`: the model model_init builds would not "- "be tensor parallel. Build the model first and pass it as `Trainer(model = model)`, or unset "- "UNSLOTH_TP_SIZE."+ f"be {what}. Build the model first and pass it as `Trainer(model = model)`, or unset "+ f"{names}.")@@ -6633,24 +6790,49 @@ def _refuse_model_parallel_export(model, method):f"base model with that adapter and call `{method}` there.")if _is_unsloth_pipeline_parallel(model):+ from .pp_native import pipeline_stage_of+ from .tp_env import env_hint++ stage = pipeline_stage_of(model)+ if stage is not None and stage._kept is not None:+ from .pp_env import replica_refusal++ refusal = replica_refusal(stage, method)+ if refusal is not None:+ raise RuntimeError(refusal)+ returnraise RuntimeError(f"Unsloth: `{method}` does not support a pipeline parallel model (apply_pipeline_parallel): each ""rank holds one stage, and the other stages' layers, embeddings and lm_head are placeholders. Save ""the adapter with `pp.save_adapter(directory)` (on every pp rank), then in a single process load "- f"the base model with that adapter and call `{method}` there."+ f"the base model with that adapter and call `{method}` there.{env_hint()}")def _tensor_parallel_for_inference(model):"""for_inference on a tensor parallel model gathers a whole replica on every rank (tp_replica.py)."""+ if _is_unsloth_pipeline_parallel(model) and _pipeline_keeps_replica(model):+ # Every rank puts the whole model back (the other stages' CPU copies + their trained weights).+ from .pp_env import pp_for_inference+ return pp_for_inference(model)if _is_unsloth_tensor_parallel(model):from .tp_replica import tp_for_inferencereturn tp_for_inference(model)_refuse_tensor_parallel_for_inference(model)+def _pipeline_keeps_replica(model):+ from .pp_native import pipeline_stage_of+ stage = pipeline_stage_of(model)+ return stage is not None and stage._kept is not None++def _tensor_parallel_for_training(model):"""for_training puts the sharded parameters back after a for_inference replica."""+ if _is_unsloth_pipeline_parallel(model):+ from .pp_env import pp_for_training+ pp_for_training(model)+ returnif _is_unsloth_tensor_parallel(model):from .tp_replica import tp_for_trainingtp_for_training(model)diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 378360f4559..04503d1b53f 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -3925,7 +3925,14 @@ def _refuse_bnb_optimizer_instance(optimizer):"""A prebuilt optimizer passed as Trainer(optimizers = (opt, ...)) or to accelerator.prepare:_swap_bnb_optimizer only edits args.optim, so a bitsandbytes instance would be kept and stepDTensor shards it cannot handle. Torch optimizers pass."""- if optimizer is None or _localize_bnb_optimizer(optimizer):+ if optimizer is None:+ return+ from ..parallel_capabilities import refuse_shard_unaware_optimizer++ refuse_shard_unaware_optimizer(+ _inner_optimizer(optimizer), "fsdp2"+ ) # Muon would orthogonalize shards+ if _localize_bnb_optimizer(optimizer):returninner = _inner_optimizer(optimizer)if "galore" in type(inner).__name__.lower():@@ -4188,7 +4195,7 @@ def _refuse_save_on_each_node(training_args):def _env_tensor_parallel_dp_mesh(model):- if not os.environ.get("UNSLOTH_TP_SIZE"):+ if not os.environ.get("UNSLOTH_TP_SIZE") and not os.environ.get("UNSLOTH_PP_SIZE"):return Nonefrom .tp_env import fsdp2_dp_meshreturn fsdp2_dp_mesh(model)diff --git a/unsloth/models/pp_env.py b/unsloth/models/pp_env.pynew file mode 100644index 00000000000..bcb85b4e715--- /dev/null+++ b/unsloth/models/pp_env.py@@ -0,0 +1,1024 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Pipeline parallelism from the environment (UNSLOTH_PP_SIZE, models/tp_env.py) for unmodified scripts.++ UNSLOTH_PP_SIZE=2 torchrun --nproc-per-node 2 train.py++- Trainer.__init__ splits the model (apply_pipeline_parallel over mesh["pp"]); the other stages' layers,+ embedding and lm_head go to this rank's CPU memory instead of being dropped (PPConfig.keep_replica).+- Trainer / SFTTrainer: every training step runs through the pipeline schedule (PipelineParallel.step runs the+ backward, the Trainer does not). The Trainer batch is split into UNSLOTH_PP_MICROBATCHES micro-batches+ (default 2 x pp, lowered to a divisor of the batch); every micro-batch loss is its summed token loss over the+ token count of the whole accumulation window over every dp replica, as with gradient accumulation on one+ GPU. The pp (and tp) ranks of one dp replica read the same batches; the optimizer steps each stage's own+ parameters; clipping, the fp16 GradScaler skip and the logged loss are global. Evaluation runs the pipeline+ forward. Trainer checkpoints: the 1-GPU adapter (rank 0) plus per-rank optimizer state.+- for_inference / generate / merged and GGUF exports: each rank puts the whole model back on its GPU (the CPU+ copies of the other stages plus their trained weights, broadcast from the stage that trained them), then runs+ the one-GPU path; the next training step splits it again. Exports run on rank 0 only; the other ranks wait+ on the rendezvous store (no collective timeout). An adapter save_pretrained gathers the LoRA weights only.+- GRPO / DPO / other RL trainers, vLLM and full finetuning are refused (v1).+"""++from __future__ import annotations++import collections.abc+import functools+import gc+import os+import types++import torch+import torch.nn as nn++__all__ = [+ "pipeline_parallel_env_apply",+ "offload_kept",+ "gather_replica",+ "release_replica",+ "replica_generate",+ "pp_for_inference",+ "pp_for_training",+ "pp_collective",+ "pp_save_adapter",+ "pp_trainer_refusals",+ "pp_trainer_setup",+]++_MiB = 1 << 20+_GENERATE_DEPTH = [0]+# Trainers whose loss the pipeline computes the way they do (causal LM loss on `labels`).+_ALLOWED_TRAINERS = {+ "Trainer",+ "Seq2SeqTrainer",+ "SFTTrainer",+ "UnslothSFTTrainer",+ "_UnslothSFTTrainer",+}+# Batch keys the pipeline carries (or that only shaped `labels`, already applied by the collator).+_BATCH_KEYS = ("input_ids", "labels", "attention_mask", "position_ids")+_DROPPED_KEYS = ("completion_mask", "assistant_masks", "return_loss", "num_items_in_batch")+++def _dist():+ import torch.distributed as dist+ return dist if dist.is_available() and dist.is_initialized() else None+++def _rank():+ dist = _dist()+ return dist.get_rank() if dist is not None else 0+++def _print_rank0(message):+ if _rank() == 0:+ print(message)+++def _gib(n):+ return f"{n / (1 << 30):.2f} GiB" if n >= (1 << 30) // 10 else f"{n / _MiB:.1f} MiB"+++def _hint():+ from .tp_env import env_hint+ return env_hint()+++def _stage_of(model):+ from .pp_native import PipelineParallel, pipeline_stage_of+ return model if isinstance(model, PipelineParallel) else pipeline_stage_of(model)+++def _env_vars(stage):+ layout = getattr(stage, "env_layout", None)+ return layout.env_vars if layout is not None else f"UNSLOTH_PP_SIZE={stage.num_stages}"+++def pipeline_parallel_env_apply(model, layout):+ """Trainer.__init__ under UNSLOTH_PP_SIZE: split `model` over mesh["pp"] (once) and attach the DDP-style dp+ dimension. Native FSDP2 (UNSLOTH_FSDP2=1) shards the stage over mesh["dp"] next (fsdp2_native)."""+ from .pp_native import PPConfig, apply_pipeline_parallel, pipeline_stage_of++ stage = pipeline_stage_of(model)+ if stage is not None:+ if getattr(stage, "env_layout", None) is None:+ raise RuntimeError(+ "Unsloth: this model was split by apply_pipeline_parallel already; under "+ f"{layout.env_vars} pass the Trainer the model loaded and given LoRA as usual."+ )+ return stage+ keep = os.environ.get("UNSLOTH_PP_KEEP_REPLICA", "1").strip().lower() not in (+ "0",+ "false",+ "no",+ "off",+ )+ default = layout.microbatches or 2 * layout.pp+ try:+ stage = apply_pipeline_parallel(+ model,+ layout.pp_mesh,+ n_microbatches = default,+ schedule = layout.schedule,+ config = PPConfig(keep_replica = keep),+ )+ except (ValueError, RuntimeError, NotImplementedError) as exc:+ from .tp_env import _reraise_with_hint+ _reraise_with_hint(exc)+ stage.env_layout = layout+ if layout.dp > 1 and not layout.fsdp2:+ from .tp_env import _broadcast_trainable++ dp_mesh = layout.dp_mesh+ _broadcast_trainable(model, dp_mesh) # DDP's start: dp rank 0's adapter on every replica+ stage.ddp_mesh = dp_mesh+ return stage++[email protected]_cache(maxsize = None)+def _gpipe_needs_stage_count():+ """torch 2.10's single-stage schedules (GPipe too) refuse fewer micro-batches than stages; later ones+ only 1F1B."""+ import inspect++ from torch.distributed.pipelining import ScheduleGPipe++ for cls in ScheduleGPipe.__mro__:+ init = cls.__dict__.get("__init__")+ if init is None:+ continue+ try:+ if "must be greater than" in inspect.getsource(init):+ return True+ except (OSError, TypeError):+ continue+ return False+++def resolve_microbatches(+ stage,+ batch_size,+ train = True,+):+ """(n_microbatches, padded rows) for a batch of `batch_size` rows. UNSLOTH_PP_MICROBATCHES must divide it;+ the default (2 x pp) is lowered to the largest divisor of the batch. A schedule that needs at least pp+ micro-batches (1F1B; GPipe on torch 2.10) gets fully masked filler rows (labels -100: no loss, no gradient)+ when the batch has fewer rows than that."""+ layout = getattr(stage, "env_layout", None)+ explicit = layout.microbatches if layout is not None else None+ want = int(explicit or stage.n_microbatches)+ floor = (+ stage.num_stages+ if (stage.schedule == "1f1b" and train) or _gpipe_needs_stage_count()+ else 1+ )+ if batch_size % want == 0:+ m = want+ elif explicit is not None and train:+ raise ValueError(+ f"Unsloth: UNSLOTH_PP_MICROBATCHES={explicit} must divide the Trainer batch size ({batch_size} rows "+ "per device): set per_device_train_batch_size to a multiple of it, or unset UNSLOTH_PP_MICROBATCHES."+ )+ else:+ m = max(d for d in range(1, min(want, batch_size) + 1) if batch_size % d == 0)+ pad = 0+ if m < floor:+ # Whole micro-batches of filler rows after the real ones (the real rows keep their micro-batch shape).+ pad = (floor - m) * (batch_size // m)+ m = floor+ if m == want and not pad:+ return m, 0+ if train and not stage.__dict__.get("_unsloth_mb_note"):+ stage.__dict__["_unsloth_mb_note"] = True+ rows = batch_size + pad+ note = (+ f", padded with {pad} fully masked row(s) (this schedule needs {floor} micro-batches; a "+ f"per_device_train_batch_size of {floor} or more avoids the extra compute)"+ if pad+ else ""+ )+ _print_rank0(+ f"Unsloth: pipeline parallel: {m} micro-batch(es) of {rows // m} row(s) per step (batch of "+ f"{batch_size}{note}; UNSLOTH_PP_MICROBATCHES sets the count)."+ )+ return m, pad+++def _pad_rows(input_ids, labels, extra, pad):+ """`pad` copies of the first row with every label ignored (attention on, so no fully masked row)."""+ if not pad:+ return input_ids, labels, extra+ rows = input_ids.shape[0]++ def take(t):+ return t[:1].expand(pad, *t.shape[1:])++ out = {}+ for key, value in extra.items():+ if isinstance(value, torch.Tensor) and value.dim() and value.shape[0] == rows:+ filler = torch.ones_like(take(value)) if key == "attention_mask" else take(value)+ value = torch.cat([value, filler])+ out[key] = value+ labels = torch.cat([labels, torch.full_like(take(labels), -100)])+ return torch.cat([input_ids, take(input_ids)]), labels, out+++def _move(module, device, skip):+ """Every parameter / buffer of `module` not in `skip` (ids) to `device`, in place (Params4bit with its+ QuantState)."""+ for sub in module.modules():+ for param in sub._parameters.values():+ if param is None or id(param) in skip:+ continue+ if param.device != device:+ param.data = param.data.to(device)+ state = getattr(param, "quant_state", None)+ if state is not None and hasattr(state, "to"):+ state.to(device)+ for name, buf in list(sub._buffers.items()):+ if buf is not None and id(buf) not in skip and buf.device != device:+ sub._buffers[name] = buf.to(device)+++def _put(container, key, module):+ if isinstance(container, nn.ModuleList):+ container[key] = module+ else:+ setattr(container, key, module)+++def _live_ids(stage):+ out = {id(p) for p in stage.model.parameters()}+ out.update(id(b) for b in stage.model.buffers())+ return out+++def offload_kept(stage):+ """The kept modules of the other stages to the CPU; tensors this stage still uses (tied weights) stay."""+ live = _live_ids(stage)+ for _, _, module, _ in stage._kept or ():+ _move(module, torch.device("cpu"), live)+++def _tensor_bytes(t):+ return t.numel() * t.element_size() if isinstance(t, torch.Tensor) else 0+++def _kept_bytes(stage):+ """Bytes the kept modules occupy on the CPU (what a whole replica adds to this GPU)."""+ seen, total = set(), 0+ for _, _, module, _ in stage._kept or ():+ for t in list(module.parameters()) + list(module.buffers()):+ if id(t) in seen or t.device.type != "cpu":+ continue+ seen.add(id(t))+ total += _tensor_bytes(t)+ state = getattr(t, "quant_state", None)+ if state is not None:+ for value in vars(state).values():+ total += _tensor_bytes(value)+ return total+++def _free_bytes(device):+ if device.type != "cuda":+ return None+ free, _ = torch.cuda.mem_get_info(device)+ return free + max(torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device), 0)+++def _comm_device(stage):+ from .tp_replica import _comm_device+ return _comm_device(stage.group, stage.device)+++def replica_refusal(stage, what):+ """None when the whole model can be put back on each rank for `what`, else why not."""+ if stage is None:+ return f"Unsloth: `{what}` found no pipeline stage on this model."+ hint = _hint()+ if stage._kept is None:+ return (+ f"Unsloth: `{what}` needs the whole model, but this pipeline parallel model dropped the other "+ "stages' layers (apply_pipeline_parallel without PPConfig(keep_replica = True), or "+ "UNSLOTH_PP_KEEP_REPLICA=0). Save the adapter (model.save_pretrained / PipelineParallel.save_adapter) "+ f"and run `{what}` on one GPU.{hint}"+ )+ if stage.tp_mesh is not None or stage.dp_mesh is not None:+ dim = (+ "tensor parallel (UNSLOTH_TP_SIZE)"+ if stage.tp_mesh is not None+ else "native FSDP2 data parallel"+ )+ return (+ f"Unsloth: `{what}` is not supported yet on a pipeline parallel x {dim} model (each stage's weights "+ "are sharded over its other ranks). Save the adapter (model.save_pretrained, on every rank) and run "+ f"`{what}` on one GPU, or launch with UNSLOTH_PP_SIZE alone (DDP-style data parallel).{hint}"+ )+ return None+++def gather_replica(+ model,+ what = "generate",+ persistent = True,+):+ """Collective over the world: put the whole model back on every rank (the kept CPU copies moved to this+ GPU, the trained weights of every stage broadcast from it). Refused on every rank alike, with the memory+ numbers, when some rank lacks the room. Returns the stage."""+ dist = _dist()+ stage = _stage_of(model)+ refusal = replica_refusal(stage, what)+ if refusal is not None:+ raise RuntimeError(refusal)+ if stage.replica is not None:+ if persistent:+ stage.replica["persistent"] = True+ return stage+ device = stage.device+ need = _kept_bytes(stage)+ free = _free_bytes(device)+ margin = max(512 * _MiB, need // 10)+ fits = free is None or need + margin <= free+ if dist is not None:+ comm = _comm_device(stage)+ row = torch.tensor(+ [float(need), float(free if free is not None else -1), 1.0 if fits else 0.0],+ dtype = torch.float64,+ device = comm,+ )+ rows = [torch.empty_like(row) for _ in range(dist.get_world_size())]+ dist.all_gather(rows, row)+ rows = [r.cpu().tolist() for r in rows]+ else:+ rows = [[float(need), float(free if free is not None else -1), 1.0 if fits else 0.0]]+ short = [(rank, r) for rank, r in enumerate(rows) if r[2] < 1]+ if short:+ detail = "; ".join(+ f"rank {rank} needs {_gib(int(r[0]))} (+ {_gib(max(512 * _MiB, int(r[0]) // 10))} margin) and has "+ f"{_gib(int(r[1]))} free"+ for rank, r in short[:4]+ )+ raise RuntimeError(+ f"Unsloth: `{what}` on a pipeline parallel model puts the whole model back on every GPU, which does "+ f"not fit: {detail}. Save the adapter (model.save_pretrained) and run `{what}` on one GPU, or free "+ f"memory first.{_hint()}"+ )+ owned = _trained_names(stage)+ adapters = _adapter_state(stage.model)+ for container, key, module, _ in stage._kept:+ _move(module, device, set())+ # Detached while the caller set the mode (model.eval() before generate): follow the root's mode.+ module.train(stage.model.training)+ # The same for PEFT's adapter switches (disable_adapter(), set_adapter) made while they were detached.+ _apply_adapter_state(module, adapters)+ _put(container, key, module)+ stage.replica = {"persistent": persistent}+ try:+ _sync_trained(stage, owned)+ except BaseException:+ release_replica(stage)+ raise+ if _rank() == 0 and not stage.__dict__.get("_unsloth_replica_note"):+ stage.__dict__["_unsloth_replica_note"] = True+ print(+ f"Unsloth: pipeline parallel `{what}`: the whole model is back on every rank ({_gib(need)} from the "+ "CPU copies of the other stages); the next training step splits it again."+ )+ return stage+++def _adapter_state(model):+ """(disabled, active adapters) of the attached PEFT tuner layers, or None without any."""+ try:+ from peft.tuners.tuners_utils import BaseTunerLayer+ except ImportError:+ return None+ for module in model.modules():+ if isinstance(module, BaseTunerLayer):+ return bool(module.disable_adapters), module.active_adapter+ return None+++def _apply_adapter_state(root, state):+ # PEFT's private fields, not enable_adapters / set_adapter: those also flip requires_grad on the adapters.+ if state is None:+ return+ from peft.tuners.tuners_utils import BaseTunerLayer++ disabled, active = state+ for module in root.modules():+ if isinstance(module, BaseTunerLayer):+ module._disable_adapters = disabled+ module._active_adapter = active+++def _note_trained(stage):+ """Remember which parameters this stage trains: a later requires_grad_(False) (before generate / export) must+ not drop them from the replica sync."""+ seen = stage.__dict__.setdefault("_unsloth_trained_names", set())+ seen.update(name for name, p in stage.model.named_parameters() if p.requires_grad)+++def _trained_names(stage):+ seen = stage.__dict__.get("_unsloth_trained_names", ())+ return [name for name, p in stage.model.named_parameters() if p.requires_grad or name in seen]+++def _sync_trained(stage, owned):+ """Broadcast every trained parameter from the stage that trained it (same names on every rank now)."""+ dist = _dist()+ if dist is None or stage.num_stages == 1:+ return+ names = [None] * stage.num_stages+ dist.all_gather_object(names, owned, group = stage.group)+ owner = {}+ for index, part in enumerate(names):+ for name in part:+ owner.setdefault(name, index)+ with torch.no_grad():+ for name, param in stage.model.named_parameters():+ src = owner.get(name)+ if src is None:+ continue+ data = param.data+ work = data if data.is_contiguous() else data.contiguous()+ dist.broadcast(work, src = stage._global_ranks[src], group = stage.group)+ if work is not data:+ data.copy_(work)+++def release_replica(model):+ """Back to this rank's stage (local, no collective): the kept modules to the CPU, the stubs in place."""+ stage = _stage_of(model)+ if stage is None or stage.replica is None:+ return False+ stage.replica = None+ for container, key, _, stub in stage._kept:+ _put(container, key, stub)+ offload_kept(stage)+ gc.collect()+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ return True+++def _sync_generation_rng(stage):+ """Global rank 0's RNG states everywhere: every rank samples the same tokens."""+ dist = _dist()+ if dist is None:+ return+ comm = _comm_device(stage)+ cpu = torch.get_rng_state().to(comm)+ dist.broadcast(cpu, src = 0)+ torch.set_rng_state(cpu.cpu())+ device = stage.device+ if device.type == "cuda":+ state = torch.cuda.get_rng_state(device).to(comm)+ dist.broadcast(state, src = 0)+ torch.cuda.set_rng_state(state.cpu(), device)+++def replica_generate(level, prior):+ """generate on a pipeline parallel level: every rank puts the whole model back first (it stays until the+ next training step), then the one-GPU generate runs locally."""++ def generate(*args, **kwargs):+ if _GENERATE_DEPTH[0] == 0:+ stage = gather_replica(level, "generate")+ _sync_generation_rng(stage)+ if prior is not None:+ fn = prior+ elif hasattr(type(level), "generate"):+ fn = types.MethodType(type(level).generate, level)+ else: # a forwarding wrapper (PEFT LoraModel): what its __getattr__ resolves, the level below+ fn = type(level).__getattr__(level, "generate")+ _GENERATE_DEPTH[0] += 1+ try:+ return fn(*args, **kwargs)+ finally:+ _GENERATE_DEPTH[0] -= 1++ generate._unsloth_pp_generate = True+ return generate+++def pp_for_inference(model):+ gather_replica(model, "for_inference")+++def pp_for_training(model):+ release_replica(model)+++def pp_collective(model, what, call):+ """Every rank calls: the whole model goes back on every rank, rank 0 runs `call` (the unchanged+ single-process export), the others wait on the store and return its result."""+ from . import tp_replica++ if tp_replica._ACTIVE or _dist() is None:+ return call()+ stage = _stage_of(model)+ gathered = stage is not None and stage.replica is None+ gather_replica(model, what, persistent = False)+ key = tp_replica._key("pp_save")+ try:+ return tp_replica._on_rank0(key, what, call, model)+ finally:+ if gathered and stage.replica is not None and not stage.replica["persistent"]:+ release_replica(stage)+++def pp_save_adapter(model, args, kwargs):+ """PeftModel.save_pretrained on a pipeline parallel model: every stage's adapter weights gathered, the+ standard 1-GPU adapter written by rank 0 (collective)."""+ import inspect++ from peft import PeftModel++ stage = _stage_of(model)+ try:+ bound = inspect.signature(PeftModel.save_pretrained).bind(model, *args, **kwargs)+ except TypeError:+ bound = None+ if bound is None:+ raise TypeError(+ f"Unsloth: save_pretrained{args} could not be read as PeftModel.save_pretrained."+ )+ values = dict(bound.arguments)+ values.pop("self", None)+ extra = values.pop("kwargs", {}) or {}+ directory = values.pop("save_directory")+ for key in (+ "push_to_hub",+ "token",+ "state_dict",+ "save_function",+ "max_shard_size",+ "tokenizer",+ ):+ extra.pop(key, None)+ if values.get("safe_serialization", True) is None:+ values["safe_serialization"] = True+ values.pop("is_main_process", None)+ stage.save_adapter(directory, **values, **extra)+ return None+++def _trainer_classes(cls):+ return [c for c in cls.__mro__ if c is not object]+++def pp_trainer_refusals(+ trainer_cls,+ args,+ layout,+ compute_loss_func = None,+):+ """Before Trainer.__init__ splits anything: the trainers / arguments the pipeline step cannot honour."""+ hint = _hint()+ builtin = ("transformers.", "trl.", "unsloth", "Unsloth")+ kind = next(+ (+ c+ for c in _trainer_classes(trainer_cls)+ if c.__module__.startswith(builtin) or c.__name__.startswith("Unsloth")+ ),+ None,+ )+ if kind is not None and kind.__name__ not in _ALLOWED_TRAINERS:+ raise NotImplementedError(+ f"Unsloth: {layout.env_vars} (pipeline parallel) trains with the Trainer / SFTTrainer only in v1; "+ f"{kind.__name__} (GRPO / DPO / other RL trainers need the whole model per rank for their rollouts / "+ f"reference logits) is not supported.{hint}"+ )+ for cls in _trainer_classes(trainer_cls):+ if cls.__name__ in _ALLOWED_TRAINERS:+ break+ for method in ("compute_loss", "training_step"):+ if method in cls.__dict__:+ raise NotImplementedError(+ f"Unsloth: {layout.env_vars} (pipeline parallel): {cls.__name__} overrides {method}, but under "+ "pipeline parallel the loss is computed by the pipeline schedule (the causal LM loss on "+ f"`labels`), so the override would be skipped.{hint}"+ )+ if compute_loss_func is not None:+ raise NotImplementedError(+ f"Unsloth: {layout.env_vars} (pipeline parallel): Trainer(compute_loss_func = ...) would be skipped, "+ f"the pipeline schedule computes the causal LM loss on `labels`.{hint}"+ )+ problems = []+ if args is None:+ return+ if getattr(args, "label_smoothing_factor", 0) or 0:+ problems.append("label_smoothing_factor (the pipeline computes the plain causal LM loss)")+ loss_type = getattr(args, "loss_type", None)+ if isinstance(loss_type, str) and loss_type.lower() != "nll" and "SFT" in type(args).__name__:+ # TRL's SFTTrainer.compute_loss applies DFT (and later variants); the pipeline schedule never calls it.+ problems.append(+ f'SFTConfig(loss_type = "{loss_type}") (the pipeline computes the plain causal LM loss; use "nll")'+ )+ 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 (UNSLOTH_FSDP2=1 shards the dp dimension)"+ )+ for flag in ("load_best_model_at_end", "push_to_hub"):+ if getattr(args, flag, False):+ problems.append(flag)+ config = getattr(args, "accelerator_config", None)+ if getattr(config, "dispatch_batches", None):+ problems.append("accelerator_config.dispatch_batches")+ if getattr(args, "packing", False) or getattr(args, "padding_free", False):+ problems.append("packing / padding_free (packed rows are not carried between stages yet)")+ if problems:+ raise NotImplementedError(+ f"Unsloth: the Trainer under {layout.env_vars} (pipeline parallel) does not support "+ + "; ".join(problems)+ + "."+ + hint+ )+++def _dp_info(stage):+ mesh = stage.dp_mesh if stage.dp_mesh is not None else stage.ddp_mesh+ return (mesh.size(), mesh.get_local_rank(), mesh) if mesh is not None else (1, 0, None)+++def _batch(stage, inputs):+ if not isinstance(inputs, collections.abc.Mapping): # dict, BatchEncoding+ raise RuntimeError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel) needs dict batches from the Trainer's collator, "+ f"got {type(inputs).__name__}.{_hint()}"+ )+ other = sorted(k for k in inputs if k not in _BATCH_KEYS and k not in _DROPPED_KEYS)+ if other:+ raise NotImplementedError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel): the Trainer batch has {other}, which the pipeline "+ "does not carry between stages yet (packed / padding-free rows, multimodal inputs). Use text rows "+ f"with packing = False.{_hint()}"+ )+ input_ids, labels = inputs.get("input_ids"), inputs.get("labels")+ if input_ids is None or labels is None:+ raise NotImplementedError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel) needs input_ids and labels in every batch (the last "+ f"stage computes the causal LM loss).{_hint()}"+ )+ extra = {k: inputs[k] for k in ("attention_mask", "position_ids") if inputs.get(k) is not None}+ return input_ids, labels, extra+++def _refuse_split_router_aux(stage, n_microbatches):+ """The pipeline adds the router load-balancing loss of each micro-batch (gradient accumulation semantics),+ while the Trainer's step on one GPU forms it once over the whole batch: a product of means, so the micro-batch+ sum is a different objective. Refused when the step has more than one micro-batch."""+ moe = getattr(getattr(stage, "ctx", None), "moe", None)+ if n_microbatches <= 1 or moe is None:+ return+ owner = moe.owner+ if not getattr(owner.config, "output_router_logits", False) or not getattr(+ owner, "router_aux_loss_coef", 0+ ):+ return+ raise NotImplementedError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel) splits each Trainer batch into {n_microbatches} "+ "micro-batches, and the pipeline adds the router load-balancing loss per micro-batch, which is not the "+ "loss the Trainer forms over the whole batch on one GPU. Set UNSLOTH_PP_MICROBATCHES=1 with "+ "UNSLOTH_PP_SCHEDULE=gpipe (where this torch allows one micro-batch), or turn the auxiliary loss off "+ f"(model.config.output_router_logits = False).{_hint()}"+ )+++def _first_stage_batch(stage, input_ids, labels, extra, count):+ """Every stage takes the first stage's batch (and its token count). The sampler gives the stages the same rows,+ but a stochastic collator or dataset transform draws from each rank's own RNG, which the stages advance+ differently (dropout over different layers), so the stage embedding the tokens and the stage scoring the labels+ could otherwise see different batches. Tensor parallel peers inside a stage are synced first: their reductions+ combine one example's activations."""+ import torch.distributed as dist++ if getattr(stage, "num_stages", 1) <= 1 or not dist.is_available() or not dist.is_initialized():+ return input_ids, labels, extra, count+ tp_mesh = getattr(stage, "tp_mesh", None)+ if tp_mesh is not None and tp_mesh.size() > 1:+ group = tp_mesh.get_group()+ src = dist.get_process_group_ranks(group)[0]+ input_ids, labels, extra, count = _broadcast_batch(+ stage, src, group, input_ids, labels, extra, count+ )+ return _broadcast_batch(+ stage, stage._global_ranks[0], stage.group, input_ids, labels, extra, count+ )+++def _broadcast_batch(stage, src, group, input_ids, labels, extra, count):+ import torch.distributed as dist++ payload = [None]+ if dist.get_rank() == src:+ tensors = {"input_ids": input_ids, "labels": labels, **extra}+ payload = [({k: v.detach().cpu() for k, v in tensors.items()}, count)]+ dist.broadcast_object_list(payload, src = src, group = group, device = _comm_device(stage))+ tensors, count = payload[0]+ device = input_ids.device+ tensors = {k: v.to(device) for k, v in tensors.items()}+ input_ids, labels = tensors.pop("input_ids"), tensors.pop("labels")+ return input_ids, labels, tensors, count+++def _global_items(trainer, stage, num_items_in_batch):+ """The token count of the whole accumulation window over every dp replica. The Trainer's own count is+ gathered over accelerator.gather, which counts the dp group only here (see _dp_gather)."""+ if num_items_in_batch is None:+ return None+ if torch.is_tensor(num_items_in_batch):+ value = int(num_items_in_batch.detach().reshape(-1)[0])+ else:+ value = int(num_items_in_batch)+ if (+ getattr(trainer.args, "average_tokens_across_devices", False)+ and trainer.args.world_size > 1+ ):+ return value # already summed over the dp replicas+ dp, _, mesh = _dp_info(stage)+ if dp == 1:+ return value+ import torch.distributed as dist++ count = torch.tensor([value], dtype = torch.int64, device = _comm_device(stage))+ dist.all_reduce(count, group = mesh.get_group())+ return int(count[0])+++def _pp_training_step(+ self,+ model,+ inputs,+ num_items_in_batch = None,+ *args,+ **kwargs,+):+ stage = self.__dict__["_unsloth_pipeline_parallel"]+ _note_trained(stage)+ model.train()+ if hasattr(self.optimizer, "train") and callable(self.optimizer.train):+ self.optimizer.train()+ inputs = self._prepare_inputs(inputs)+ input_ids, labels, extra = _batch(stage, inputs)+ n = _global_items(self, stage, num_items_in_batch)+ input_ids, labels, extra, n = _first_stage_batch(stage, input_ids, labels, extra, n)+ scale = 1.0+ if n is None:+ # No window token count: each step averages its own tokens, the window averages the steps.+ scale = 1.0 / max(+ int(+ getattr(self, "current_gradient_accumulation_steps", 0)+ or self.args.gradient_accumulation_steps+ ),+ 1,+ )+ scaler = getattr(self.accelerator, "scaler", None)+ scaler = scaler if scaler is not None and scaler.is_enabled() else None+ m, pad = resolve_microbatches(stage, input_ids.shape[0])+ _refuse_split_router_aux(stage, m)+ input_ids, labels, extra = _pad_rows(input_ids, labels, extra, pad)+ loss = stage.step(+ input_ids,+ labels,+ num_items_in_batch = n,+ scaler = scaler,+ n_microbatches = m,+ loss_scale = scale,+ **extra,+ )+ del inputs+ return loss.detach().to(self.args.device)+++def _eval_items(trainer, inputs, labels):+ """The loss normaliser of one eval batch, counted as this Trainer counts it on one GPU (Unsloth's+ prediction step passes _get_num_items_in_batch: unshifted labels on transformers 4.x), for this dp+ replica's batch only; else the shifted label count (the model's own mean)."""+ getter = getattr(trainer, "_get_num_items_in_batch", None)+ if callable(getter):+ args = trainer.args+ flag = getattr(args, "average_tokens_across_devices", None)+ try:+ if flag:+ args.average_tokens_across_devices = False+ value = getter([inputs], args.device)+ except Exception:+ value = None+ finally:+ if flag:+ args.average_tokens_across_devices = flag+ if value is not None:+ return int(value.reshape(-1)[0]) if torch.is_tensor(value) else int(value)+ return int((labels[:, 1:] != -100).sum())+++def _pp_prediction_step(+ self,+ model,+ inputs,+ prediction_loss_only,+ ignore_keys = None,+):+ stage = self.__dict__["_unsloth_pipeline_parallel"]+ if not prediction_loss_only:+ raise NotImplementedError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel): evaluation returns the loss only (the last stage "+ "does not send logits); remove compute_metrics / set prediction_loss_only = True, or evaluate on one "+ f"GPU.{_hint()}"+ )+ inputs = self._prepare_inputs(inputs)+ input_ids, labels, extra = _batch(stage, inputs)+ count = _eval_items(self, inputs, labels)+ input_ids, labels, extra, count = _first_stage_batch(stage, input_ids, labels, extra, count)+ m, pad = resolve_microbatches(stage, input_ids.shape[0], train = False)+ _refuse_split_router_aux(stage, m)+ input_ids, labels, extra = _pad_rows(input_ids, labels, extra, pad)+ loss = stage.eval_loss(input_ids, labels, num_items_in_batch = count, n_microbatches = m, **extra)+ return (loss.detach().to(self.args.device), None, None)+++def _pp_save_model(+ self,+ output_dir = None,+ _internal_call = False,+):+ stage = self.__dict__["_unsloth_pipeline_parallel"]+ output_dir = output_dir if output_dir is not None else self.args.output_dir+ model = stage.model+ if not hasattr(model, "peft_config"):+ raise NotImplementedError(+ f"Unsloth: {_env_vars(stage)} (pipeline parallel) saves LoRA adapters only.{_hint()}"+ )+ stage.save_adapter(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 _dp_gather(accelerator, stage):+ """accelerator.gather over the dp group only: the pp / tp ranks of a replica hold the same batch, so the+ world gather would count it pp x tp times (token counts, eval losses, logged losses)."""+ from accelerate.utils import recursively_apply++ dp, _, mesh = _dp_info(stage)++ def one(tensor):+ if tensor.dim() == 0:+ tensor = tensor.clone()[None]+ if dp == 1:+ return tensor+ import torch.distributed as dist++ work = tensor.contiguous()+ out = [torch.empty_like(work) for _ in range(dp)]+ dist.all_gather(out, work, group = mesh.get_group())+ return torch.cat(out, dim = 0)++ def gather(tensor):+ return recursively_apply(one, tensor, error_on_other_type = True)++ return gather+++def _unwrap_optimizer(opt):+ try:+ from accelerate.optimizer import AcceleratedOptimizer+ except Exception:+ AcceleratedOptimizer = ()+ seen = 0+ while isinstance(opt, AcceleratedOptimizer) and seen < 8:+ opt = opt.optimizer+ seen += 1+ return opt+++def _pp_clip(accelerator, stage):+ from .tp_native import _DP_SYNC, _dp_average+ def clip_grad_norm_(+ parameters,+ max_norm,+ norm_type = 2,+ ):+ if float(norm_type) != 2.0:+ raise RuntimeError(+ "Unsloth: pipeline parallel gradient clipping supports the 2-norm only."+ )+ params = [p for p in parameters if p.requires_grad]+ sync = accelerator.__dict__.get(_DP_SYNC)+ if sync is not None:+ _dp_average(params, sync["mesh"])+ sync["synced"] = True+ scaler = getattr(accelerator, "scaler", None)+ if scaler is not None and scaler.is_enabled():+ from torch.amp.grad_scaler import OptState+ for opt in getattr(accelerator, "_optimizers", []):+ # The torch optimizer AcceleratedOptimizer.step hands the scaler: the scaler keys its+ # unscaled state by optimizer, so unscaling the wrapper would divide the gradients again there.+ opt = _unwrap_optimizer(opt)+ state = scaler._per_optimizer_states[id(opt)]+ if state["stage"] is OptState.READY:+ stage.unscale_(scaler, opt)+ return stage.clip_grad_norm_(max_norm, params)++ return clip_grad_norm_+++def _pp_save_optimizer_and_scheduler(self, output_dir):+ """A checkpoint records this rank's stage only: drop a replica left by generate / for_inference first."""+ from .tp_native import _tp_save_optimizer_and_scheduler++ release_replica(self.model)+ return _tp_save_optimizer_and_scheduler(self, output_dir)+++def _pp_load_from_checkpoint(self, *args, **kwargs):+ """A checkpoint holds this rank's stage only: drop a replica left by generate / for_inference before the+ layout check, as the optimizer save does."""+ from .tp_native import _tp_load_from_checkpoint++ release_replica(self.model)+ return _tp_load_from_checkpoint(self, *args, **kwargs)+++def pp_trainer_setup(trainer):+ """After Trainer.__init__ (models/_utils.py) for a model split under UNSLOTH_PP_SIZE."""+ from .tp_native import (+ _DP_SYNC,+ _TP_DATA,+ _dp_sync_before_step,+ _install_tp_accelerate_hooks,+ _tp_load_optimizer_and_scheduler,+ _tp_save_optimizer_and_scheduler,+ _tp_train_sampler,+ )++ stage = _stage_of(trainer.model)+ dp, dp_rank, _ = _dp_info(stage)+ accelerator = trainer.accelerator+ if not trainer.__dict__.get("_unsloth_tensor_parallel"):+ # Every stage must draw the same rows: seed the train sampler per dp replica, not from the global RNG.+ _tp_train_sampler(trainer, dp, dp_rank)+ _install_tp_accelerate_hooks() # map-style data sharded over dp only, no DDP / device move of the model+ accelerator.__dict__[_TP_DATA] = (dp, dp_rank)+ accelerator.__dict__["_unsloth_pp_stage"] = stage+ accelerator.__dict__["gather"] = _dp_gather(accelerator, stage)+ accelerator.__dict__["clip_grad_norm_"] = _pp_clip(accelerator, stage)+ if stage.ddp_mesh is not None and accelerator.__dict__.get(_DP_SYNC) is None:+ accelerator.__dict__[_DP_SYNC] = {"mesh": stage.ddp_mesh, "synced": False}+ sync = accelerator.__dict__.get(_DP_SYNC)+ # The generated TRL trainers skip their post-init for_inference() (it would gather the whole model).+ trainer.__dict__["_unsloth_tensor_parallel"] = True+ trainer.__dict__["_unsloth_pipeline_parallel"] = stage+ for name, method in (+ ("training_step", _pp_training_step),+ ("prediction_step", _pp_prediction_step),+ ("save_model", _pp_save_model),+ ("_save_optimizer_and_scheduler", _pp_save_optimizer_and_scheduler),+ ("_load_optimizer_and_scheduler", _tp_load_optimizer_and_scheduler),+ ("_load_from_checkpoint", _pp_load_from_checkpoint),+ ):+ trainer.__dict__[name] = types.MethodType(method, trainer)+ trainer.__dict__["_has_mixed_mesh_grads"] = lambda model: False+ from .fsdp2_native import _scaler_for_native++ try:+ scaled = _scaler_for_native(trainer)+ except Exception:+ scaled = False+ if scaled is not False and getattr(accelerator, "scaler", None) is not None:+ 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:+ accelerator.scaler._init_scale = (+ 2.0**16 / dp+ ) # the loss scale grows with dp, never with pp+ if sync is not None and sync.get("_unsloth_pp_hooked") is None:+ create_optimizer = trainer.create_optimizer++ def create_optimizer_pp(*args, **kwargs):+ # DDP-style dp without clipping: average the gradients at the optimizer step instead.+ optimizer = create_optimizer(*args, **kwargs)+ if optimizer is None:+ # An override may set self.optimizer and return nothing (the Trainer reads self.optimizer).+ optimizer = trainer.optimizer+ from .fsdp2_native import _inner_optimizer++ inner = _inner_optimizer(optimizer)+ if 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 = True+ return optimizer++ trainer.__dict__["create_optimizer"] = create_optimizer_pp+ sync["_unsloth_pp_hooked"] = True+ _print_rank0(+ f"Unsloth: Trainer under {_env_vars(stage)}: {stage}; every step runs through the pipeline schedule."+ )+ return Truediff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.pyindex f8580fb81b8..5bbf6453167 100644--- a/unsloth/models/pp_native.py+++ b/unsloth/models/pp_native.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport astimport collections+import osimport dataclassesimport functoolsimport inspect@@ -42,6 +43,7 @@ __all__ = ["PipelineParallel","apply_pipeline_parallel","check_mesh_composition",+ "check_pipeline_model","check_pp_dp_composition","derive_pp_split","is_pipeline_parallel",@@ -70,6 +72,7 @@ _CROSS_LAYER_CONFIG_KEYS = ()_ATTENTION_LAYER_TYPES = {"full_attention", "sliding_attention", "chunked_attention", "attention"}_STEP_KWARGS = ("attention_mask", "position_ids")+_STAGE_IDS = "_unsloth_pp_input_ids" # the batch's token ids, for stages after the first_MULTI_STAGE_DP = ("Unsloth: native FSDP2 data parallel over a pipeline with several stages per rank is not supported ""(each FSDP2 root must be one stage's module); use one stage per rank (schedule = 'gpipe' / '1f1b') "@@ -93,6 +96,10 @@ class PPConfig:# Stages per rank for multi-stage schedules (interleaved1f1b, loopedbfs, ...); None = the schedule's# default (1 for gpipe / 1f1b, 2 otherwise). The decoder is cut into pp x stages_per_rank stages.stages_per_rank: Optional[int] = None+ # Keep the layers / embedding / lm_head of the other stages on the CPU (host RAM, not this GPU) instead of+ # dropping them, so for_inference / generate / exports can rebuild the whole model on each rank after+ # training (pp_env.py; UNSLOTH_PP_SIZE sets it).+ keep_replica: bool = Falseclass _StageOutput(BaseException):@@ -421,24 +428,77 @@ def _refuse_shared_across_stages(parts, bounds):)+def _forward_candidates(inner):+ """The forward and the functions it wraps (__wrapped__, and closure cells of wrappers that drop it)."""+ first = inner.__dict__.get("forward") or type(inner).forward+ out, todo, seen = [], [getattr(first, "__func__", first)], set()+ while todo and len(out) < 12:+ fn = todo.pop(0)+ fn = getattr(fn, "__func__", fn)+ if id(fn) in seen:+ continue+ seen.add(id(fn))+ out.append(fn)+ wrapped = getattr(fn, "__wrapped__", None)+ if wrapped is not None:+ todo.append(wrapped)+ for cell in getattr(fn, "__closure__", None) or ():+ try:+ value = cell.cell_contents+ except ValueError:+ continue+ if inspect.isfunction(value) or inspect.ismethod(value):+ todo.append(value)+ return out+++def _is_unsloth_function(fn):+ module = getattr(fn, "__module__", None) or ""+ filename = os.path.basename(getattr(getattr(fn, "__code__", None), "co_filename", "") or "")+ return (+ module.split(".")[0] in ("unsloth", "unsloth_zoo")+ or module.startswith("unsloth_compiled")+ or filename.startswith("unsloth_compiled")+ )++def _check_loss_normalization(inner):"""PipelineParallel sums the micro-batch losses, each normalised by the token count of the whole batch(num_items_in_batch). A causal LM forward that drops num_items_in_batch takes a per-micro-batch mean, so the- sum would be n_microbatches times the one-process loss (BART / Whisper / TrOCR decoders)."""- try:- source = inspect.getsource(_forward_function(inner))- except (OSError, TypeError):- source = ""- passes_kwargs = re.search(r"loss_function\([^()]*(?:\([^()]*\)[^()]*)*\*\*\s*\w+", source)- if "num_items_in_batch" in source or passes_kwargs:- return+ sum would be n_microbatches times the one-process loss (BART / Whisper / TrOCR decoders). Unsloth's own+ forwards (patched / compiled, the gradient accumulation fix) always take it."""+ candidates = _forward_candidates(inner)+ for fn in candidates:+ try:+ source = inspect.getsource(fn)+ except (OSError, TypeError):+ source = ""+ passes_kwargs = re.search(r"loss_function\([^()]*(?:\([^()]*\)[^()]*)*\*\*\s*\w+", source)+ if "num_items_in_batch" in source or passes_kwargs:+ return+ if _is_unsloth_function(fn):+ return+ names = ", ".join(+ f"{getattr(fn, '__qualname__', type(fn).__name__)}"+ f" ({getattr(getattr(fn, '__code__', None), 'co_filename', '?')})"+ for fn in candidates[:3]+ )raise ValueError(f"Unsloth: pipeline parallelism v1 needs the {type(inner).__name__} loss to take num_items_in_batch ""(self.loss_function(..., **kwargs)); this forward computes a per-micro-batch mean, so micro-batches "- "cannot be summed like gradient accumulation."+ f"cannot be summed like gradient accumulation (forward: {names}).")+def check_pipeline_model(model):+ """The checks apply_pipeline_parallel makes on the model's structure, without splitting it: a ValueError+ for a model it would refuse. Run right after loading (UNSLOTH_PP_SIZE), before LoRA freezes the base, so+ the tied embedding trainability check waits for the split."""+ parts = _find_parts(model)+ _refuse_unsupported(model, parts, at_load = True)+ return parts++@dataclasses.dataclassclass _MoEAux:"""How a stage collects its routers' logits and forms the load-balancing loss (_moe_aux_plan)."""@@ -587,10 +647,12 @@ def _record_router(ctx, module, args, output):def _refuse_unsupported(model,parts,+ at_load = False,allow_moe = True,):- """Refusals before anything is cut. Returns the _MoEAux of a mixture-of-experts family whose router- auxiliary loss PipelineParallel carries (allow_moe), else None."""+ """Refusals before anything is cut (at_load: the structural ones only, before LoRA freezes the base).+ Returns the _MoEAux of a mixture-of-experts family whose router auxiliary loss PipelineParallel carries+ (allow_moe), else None."""text = _text_config(model)inner = parts.innerconfig = getattr(inner, "config", None)@@ -661,7 +723,7 @@ def _refuse_unsupported("Unsloth: this model is already distributed (DTensor parameters or a transformers tp_plan); ""load it without tp_plan before apply_pipeline_parallel.")- if parts.tied and parts.embed.weight.requires_grad:+ if parts.tied and parts.embed.weight.requires_grad and not at_load:raise ValueError("Unsloth: pipeline parallelism v1 cannot train tied input / output embeddings (the first and ""last stage would each update their own copy). Freeze them, or untie them before splitting."@@ -884,7 +946,8 @@ def _placeholder(weight):class _PPEmbeddingStub(nn.Module):- """The input embedding on stages > 0: zeros in its place (replaced before the first owned layer)."""+ """The input embedding on stages > 0: zeros in its place (replaced before the first owned layer), in the+ dtype the real embedding returns (model-level masks and rotary tables are built in that dtype)."""def __init__(self, source):super().__init__()@@ -896,9 +959,25 @@ class _PPEmbeddingStub(nn.Module):if scale is not None:self.__dict__["embed_scale"] = scaleself.__dict__["_pp_width"] = weight.shape[-1]+ self.__dict__["_pp_out_dtype"] = _embedding_output_dtype(source)def forward(self, input_ids, *args, **kwargs):- return self.weight.new_zeros(*input_ids.shape, self._pp_width)+ return torch.zeros(+ (*input_ids.shape, self._pp_width), dtype = self._pp_out_dtype, device = input_ids.device+ )+++def _embedding_output_dtype(embedding):+ """What `embedding` returns for one token (a patched / scaled embedding may upcast), else its weight dtype."""+ weight = embedding.weight+ try:+ with torch.no_grad():+ out = embedding(torch.zeros((1, 1), dtype = torch.long, device = weight.device))+ if isinstance(out, torch.Tensor) and out.is_floating_point():+ return out.dtype+ except Exception:+ pass+ return weight.dtypeclass _PPHeadStub(nn.Module):@@ -1014,10 +1093,17 @@ class _PPStageModule(nn.Module):def _stage_forward(self, x, *carry, **kwargs):ctx = self._pp_ctxmoe = ctx.moe+ # Every rank holds the batch: later stages get the real token ids too (the embedding stub ignores them),+ # so model-level code reading input_ids (padding / pad-token masks, token types) sees what one GPU does.+ ids = kwargs.pop(_STAGE_IDS, None)if ctx.is_first:input_ids = xelse:- input_ids = torch.zeros(x.shape[:2], dtype = torch.long, device = x.device)+ input_ids = (+ ids+ if ids is not None+ else torch.zeros(x.shape[:2], dtype = torch.long, device = x.device)+ )ctx.stage_input = xctx.active = Truecaptured = None@@ -1200,6 +1286,24 @@ def _refuse_generate(*args, **kwargs):)+def _batch_kwargs(kwargs, bsz, device, what):+ """Tensor kwargs with the batch dimension first: a size-1 batch dimension (broadcast position_ids) is+ expanded so the schedule splits it per micro-batch like input_ids."""+ out = {}+ for key, value in kwargs.items():+ if isinstance(value, torch.Tensor):+ if value.dim() == 0 or value.shape[0] not in (1, bsz):+ raise ValueError(+ f"Unsloth: PipelineParallel.{what} {key} must have the batch dimension first "+ f"({bsz} or 1), got {tuple(value.shape)}."+ )+ if value.shape[0] == 1 and bsz > 1:+ value = value.expand(bsz, *value.shape[1:])+ value = value.to(device)+ out[key] = value+ return out++class PipelineParallel:"""This rank's pipeline stage of a model split by apply_pipeline_parallel."""@@ -1265,6 +1369,15 @@ class PipelineParallel:self._loss_multiplier = 1self.last_aux_loss = None # mixture-of-experts models: the step's router auxiliary lossself.dp_mesh = None # set by shard_model (FSDP2 over the data parallel dimension)+ # DDP-style data parallel (UNSLOTH_PP_SIZE without UNSLOTH_FSDP2): replicated stage weights, the loss+ # normalised over the dp replicas' tokens, gradients averaged over this mesh by the caller.+ self.ddp_mesh = None+ self._kept = (+ None # PPConfig.keep_replica: [(container, key, module, stub)] of the other stages+ )+ self.replica = (+ None # pp_env: the whole model is in place (for_inference / generate / exports)+ )# composition with FSDP2 (dp) / tensor parallelism (tp): every other mesh dimension must be applied@property@@ -1285,6 +1398,8 @@ class PipelineParallel:meshes = {"pp": self.mesh}if self.dp_mesh is not None:meshes["dp"] = self.dp_mesh+ elif self.ddp_mesh is not None:+ meshes["dp"] = self.ddp_meshif self.tp_mesh is not None:meshes["tp"] = self.tp_meshreturn meshes@@ -1379,10 +1494,17 @@ class PipelineParallel:output = output * self._loss_multiplierreturn output if self._scaler is None else self._scaler.scale(output)- def _schedule_for(self, mb, seq):+ def _schedule_for(+ self,+ mb,+ seq,+ n_microbatches = None,+ train = True,+ ):from torch.distributed.pipelining import PipelineStage- key = (mb, seq)+ m = int(n_microbatches or self.n_microbatches)+ key = (mb, seq, m, train)if key in self._shapes:self._shapes.move_to_end(key)return self._shapes[key]@@ -1431,9 +1553,12 @@ class PipelineParallel:))cls = torch_schedule_class(self.spec)+ if not train and not self.spec.multi:+ from torch.distributed.pipelining import ScheduleGPipe+ cls = ScheduleGPipe # forward only (eval_loss): no backward order to keepschedule = cls(stages if self.spec.multi else stages[0],- self.n_microbatches,+ m,loss_fn = self._loss_fn,scale_grads = False,)@@ -1448,10 +1573,12 @@ class PipelineParallel:labels,num_items_in_batch = None,scaler = None,+ n_microbatches = None,+ loss_scale = 1.0,**kwargs,):"""Forward + backward of one optimizer step's batch (the same batch on every pp rank), split into- n_microbatches micro-batches. Gradients accumulate into this stage's parameters (call+ n_microbatches micro-batches (the default given to apply_pipeline_parallel unless passed here). Gradients accumulate into this stage's parameters (calloptimizer.zero_grad between steps). Returns the batch loss (sum over tokens / num_items_in_batch,unscaled) on every rank.@@ -1464,6 +1591,14 @@ class PipelineParallel:count summed over dp) and the returned loss is the global batch loss."""import torch.distributed as dist+ from .pp_env import _note_trained, release_replica++ if self.replica is not None:+ release_replica(+ self+ ) # a whole model gathered for generate / a save: back to this stage+ # A later requires_grad_(False) before generate / export must still sync what native loops trained.+ _note_trained(self)self._check_composed()if self.ctx.moe is not None and (self.composed or self.dp_mesh is not None or self.tp_mesh is not None@@ -1485,13 +1620,23 @@ class PipelineParallel:f"{tuple(input_ids.shape)} / {tuple(labels.shape)}.")bsz, seq = input_ids.shape- m = self.n_microbatches+ m = int(n_microbatches or self.n_microbatches)if bsz % m:raise ValueError(f"Unsloth: the batch size {bsz} must be a multiple of n_microbatches = {m}.")+ if self.schedule == "1f1b" and m < self.num_stages:+ raise ValueError(+ f"Unsloth: the 1F1B schedule needs n_microbatches >= stages ({m} < {self.num_stages})."+ )+ if self.spec.multi and m != self.n_microbatches:+ raise ValueError(+ f"Unsloth: the {self.schedule} schedule was validated for n_microbatches = "+ f"{self.n_microbatches}; a per-step count ({m}) is supported on single-stage schedules only."+ )device = self.device- dp_group = self.dp_mesh.get_group() if self.dp_mesh is not None else None+ dp_mesh = self.dp_mesh if self.dp_mesh is not None else self.ddp_mesh+ dp_group = dp_mesh.get_group() if dp_mesh is not None else Noneif num_items_in_batch is None:# Tokens the loss averages over in one process: shifted labels that are not ignored.count = (labels[:, 1:] != -100).sum()@@ -1505,21 +1650,13 @@ class PipelineParallel:num_items_in_batch) # a non-tensor kwarg is replicated per micro-batchnum_items_in_batch = max(num_items_in_batch, 1)- self._loss_multiplier = self.dp_mesh.size() if self.dp_mesh is not None else 1- schedule = self._schedule_for(bsz // m, seq)- step_kwargs = {}- for key, value in kwargs.items():- if isinstance(value, torch.Tensor):- if value.dim() == 0 or value.shape[0] not in (1, bsz):- raise ValueError(- f"Unsloth: PipelineParallel.step {key} must have the batch dimension first "- f"({bsz} or 1), got {tuple(value.shape)}."- )- if value.shape[0] == 1 and bsz > 1:- value = value.expand(bsz, *value.shape[1:]) # split per micro-batch on dim 0- value = value.to(device)- step_kwargs[key] = value+ # FSDP2 / DDP-style dp average the gradients over dp: dp x (this replica's token loss sum / global tokens).+ self._loss_multiplier = (dp_mesh.size() if dp_mesh is not None else 1) * float(loss_scale)+ schedule = self._schedule_for(bsz // m, seq, m)+ step_kwargs = _batch_kwargs(kwargs, bsz, device, "step")step_kwargs["labels"] = labels.to(device)+ if self._needs_stage_ids():+ step_kwargs[_STAGE_IDS] = input_ids.to(device)self.ctx.num_items_in_batch = num_items_in_batchif scaler is not None and scaler.is_enabled():scaler.scale(@@ -1539,6 +1676,17 @@ class PipelineParallel:self.ctx.num_items_in_batch = Noneif self.dp_mesh is not None:self._average_replicated_grads()+ total = self._batch_loss(m, device, dp_group)+ return total * float(loss_scale) if loss_scale != 1 else total++ def _needs_stage_ids(self):+ """A local stage after the first one runs here: it gets the batch's real token ids (_STAGE_IDS)."""+ return any(k != 0 for k in self.local_stages)++ def _batch_loss(self, m, device, dp_group):+ """The sum of the last stage's micro-batch losses, on every rank of the pp group (summed over dp)."""+ import torch.distributed as dist+if self.is_last:if len(self._mb_losses) != m:raise RuntimeError(@@ -1563,6 +1711,55 @@ class PipelineParallel:self.last_aux_loss = total[1]return total[0]+ @torch.no_grad()+ def eval_loss(+ self,+ input_ids,+ labels,+ num_items_in_batch = None,+ n_microbatches = None,+ **kwargs,+ ):+ """Forward only (no gradients) of one batch through the pipeline: the token mean loss of this batch+ (sum over its shifted labels / their count, as the model's own loss on one GPU) on every rank of the+ pp group. Each dp replica evaluates its own batch."""+ if self.replica is not None:+ from .pp_env import release_replica+ release_replica(self)+ self._check_composed()+ unknown = sorted(set(kwargs) - set(_STEP_KWARGS))+ if unknown:+ raise ValueError(f"Unsloth: PipelineParallel.eval_loss takes no {unknown}.")+ bsz, seq = input_ids.shape+ m = int(n_microbatches or self.n_microbatches)+ if bsz % m:+ raise ValueError(+ f"Unsloth: the batch size {bsz} must be a multiple of n_microbatches = {m}."+ )+ device = self.device+ if num_items_in_batch is None:+ num_items_in_batch = int((labels[:, 1:] != -100).sum())+ step_kwargs = _batch_kwargs(kwargs, bsz, device, "eval_loss")+ step_kwargs["labels"] = labels.to(device)+ if self._needs_stage_ids():+ step_kwargs[_STAGE_IDS] = input_ids.to(device)+ schedule = self._schedule_for(bsz // m, seq, m, train = False)+ self._mb_losses = []+ self._loss_multiplier = 1+ args = (input_ids.to(device),) if self.is_first else ()+ target = step_kwargs["labels"] if self.is_last else None+ has_backward = schedule._has_backward+ schedule._has_backward = (+ False # what schedule.eval() does; called directly for return_outputs+ )+ self.ctx.num_items_in_batch = max(int(num_items_in_batch), 1)+ try:+ schedule.step(*args, target = target, return_outputs = False, **step_kwargs)+ finally:+ schedule._has_backward = has_backward+ self.ctx.num_items_in_batch = None+ return self._batch_loss(m, device, None)+def _average_replicated_grads(self):"""Trainable parameters FSDP2 keeps replicated (Unsloth averages them over dp like DDP from anautograd callback, deferred while gradient sync is off): the pipeline schedule runs every micro-batch@@ -1662,6 +1859,8 @@ class PipelineParallel:cls = type(scaler)unscale = cls.unscale_.__get__(scaler)update = cls.update.__get__(scaler)+ check_inf = getattr(cls, "_check_inf_per_device", None)+ check_inf = check_inf.__get__(scaler) if check_inf is not None else Nonepipeline = weakref.ref(self)def unscale_(optimizer):@@ -1670,11 +1869,19 @@ class PipelineParallel:if pp is not None and scaler.is_enabled():pp._agree_found_inf(scaler, optimizer)+ def check_inf_per_device_(optimizer):+ # scaler.step on a fused optimizer (adamw_torch_fused) checks here instead of calling unscale_.+ found = check_inf(optimizer)+ pp = pipeline()+ if pp is not None and scaler.is_enabled():+ pp._agree_found_inf(scaler, optimizer)+ return scaler._per_optimizer_states[id(optimizer)].get("found_inf_per_device", found)+def update_(new_scale = None):try:return update(new_scale)finally:- for name in ("unscale_", "update", "_unsloth_pp_agree"):+ for name in ("unscale_", "update", "_check_inf_per_device", "_unsloth_pp_agree"):scaler.__dict__.pop(name, None)pp = pipeline()if pp is not None and pp._step_scaler is scaler:@@ -1684,6 +1891,8 @@ class PipelineParallel:scaler.unscale_ = unscale_scaler.update = update_+ if check_inf is not None:+ scaler._check_inf_per_device = check_inf_per_device_scaler._unsloth_pp_agree = pipelinedef _check_unscaled(self):@@ -1810,6 +2019,19 @@ class PipelineParallel:dist.barrier(group = self.group)+def _default_activation_dtype(model, parts):+ """The input embedding dtype, except for a model Unsloth trains in float32 because its activations overflow+ float16 (Gemma 3, gpt-oss: UNSLOTH_FORCE_FLOAT32, stamped `_unsloth_forced_float32` by from_pretrained): its+ hidden states are float32 while the embedding may stay 16-bit, and a float16 send would turn them to inf."""+ dtype = parts.embed.weight.dtype+ if dtype not in (torch.float16, torch.bfloat16):+ return dtype+ stamps = [getattr(level, "_unsloth_forced_float32", None) for level in _model_chain(model)]+ stamps = [s for s in stamps if s is not None]+ forced = any(stamps) if stamps else os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"+ return torch.float32 if forced else dtype++def _local_stage_modules(pp_stage, parts, owned):"""One _PPStageModule per local stage of a multi-stage rank. Every one runs the same model; while stage kruns, this rank's layers of its other stages are swapped for pass-throughs and, unless k is the first@@ -1967,7 +2189,12 @@ def apply_pipeline_parallel(stage_indices(spec, rank, pp, stages_per_rank),parts,)- dtype = config.activation_dtype or parts.embed.weight.dtype+ if config.keep_replica and (stages_per_rank > 1 or preloaded is not None):+ raise ValueError(+ "Unsloth: PPConfig.keep_replica (UNSLOTH_PP_SIZE) keeps the whole model for generate / exports: it "+ "needs one stage per rank (gpipe / 1f1b) and a model loaded in full, not pipeline_sharded_loading."+ )+ dtype = config.activation_dtype or _default_activation_dtype(model, parts)if config.sync_trainable and pp > 1:owners = Noneif preloaded is not None:@@ -1994,6 +2221,7 @@ def apply_pipeline_parallel(start, end = bounds[local[0]]is_first, is_last = pp_stage.is_first, pp_stage.is_lastlayers = parts.layers+ kept = [] if config.keep_replica else Noneif moe is not None:# This stage's routers report their logits into the context while its forward runs.pp_stage.ctx.moe = moe@@ -2003,15 +2231,22 @@ def apply_pipeline_parallel(module.register_forward_hook(functools.partial(_record_router, pp_stage.ctx))for i in range(len(layers)):if i not in owned:- layers[i] = _PPPassThrough(i, pp_stage.ctx, layers[i])+ stub = _PPPassThrough(i, pp_stage.ctx, layers[i])+ if kept is not None:+ kept.append((layers, i, layers[i], stub))+ layers[i] = stubembed, lm_head = parts.embed, parts.lm_headif not is_first:parent, attr = _owner(parts.decoder, parts.embed)embed = _PPEmbeddingStub(parts.embed)+ if kept is not None:+ kept.append((parent, attr, parts.embed, embed))setattr(parent, attr, embed)if not is_last:parent, attr = _owner(parts.inner, parts.lm_head)lm_head = _PPHeadStub(parts.lm_head)+ if kept is not None:+ kept.append((parent, attr, parts.lm_head, lm_head))setattr(parent, attr, lm_head)# A norm registered before the layer list (Bloom's word_embeddings_layernorm) feeds the first stage; one# after it (the final norm) the last. Other stages keep it frozen, so it trains on its owner only.@@ -2049,8 +2284,16 @@ def apply_pipeline_parallel(level.__dict__[_PP_FLAG] = infolevel.__dict__["_unsloth_pp_stage"] = pp_stageif callable(getattr(level, "generate", None)):- level.__dict__["generate"] = _refuse_generate+ if kept is not None:+ from .pp_env import replica_generate+ level.__dict__["generate"] = replica_generate(level, level.__dict__.get("generate"))+ else:+ level.__dict__["generate"] = _refuse_generatedel inner+ if kept is not None:+ from .pp_env import offload_kept+ pp_stage._kept = kept+ offload_kept(pp_stage) # the other stages' weights to the CPU (host RAM)import gcgc.collect() # the dropped layers sit in reference cycles: free their weights now, not at a later collectiondiff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 284f2c12cc0..1aea0701ead 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -567,7 +567,11 @@ def prepare_for_training_mode(f):output = f(self, *args, **kwargs)# Restore previous mode when possibleif hasattr(self, 'model') and hasattr(self.model, "for_inference"):- if _was_training is False:+ if _was_training is False and getattr(self, '_unsloth_tensor_parallel', False):+ # Tensor / pipeline parallel: for_inference gathers a whole replica (refused for some layouts);+ # restoring the mode needs only eval, and generate gathers when it is asked for.+ self.model.eval()+ elif _was_training is False:self.model.for_inference()elif _was_training is True and hasattr(self.model, "for_training"):self.model.for_training(use_gradient_checkpointing=use_gc)@@ -3526,8 +3530,8 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):metadata = {'help': 'Ranks per context parallel group. 1 disables it.'},)context_parallel_backend : Optional[str] = field(- default = 'ring',- metadata = {'help': 'Context parallel attention backend: ring or ulysses (keeps packing).'},+ default = 'auto',+ metadata = {'help': 'Context parallel attention backend: auto (Ulysses unless the heads cannot be split, then ring), ulysses (keeps packing) or ring.'},)context_parallel_rotate_method : Optional[str] = field(default = 'allgather',@@ -3535,7 +3539,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):)"""max_seq_length_call += ("context_parallel_size = 1,"- "context_parallel_backend = 'ring',"+ "context_parallel_backend = 'auto',""context_parallel_rotate_method = 'allgather',")max_seq_length_post += (@@ -3552,10 +3556,10 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):metadata = {'help': 'Ranks per context parallel group (training forwards only). 1 disables it.'},)context_parallel_backend : Optional[str] = field(- default = 'ulysses',- metadata = {'help': 'Context parallel attention backend; preference and RL trainers support ulysses.'},+ default = 'auto',+ metadata = {'help': 'Context parallel attention backend: auto (= ulysses); preference and RL trainers support ulysses.'},)"""- max_seq_length_call += "context_parallel_size = 1,context_parallel_backend = 'ulysses',"+ max_seq_length_call += "context_parallel_size = 1,context_parallel_backend = 'auto',"max_seq_length_post += ("\n self.context_parallel_size = context_parallel_size""\n self.context_parallel_backend = context_parallel_backend"diff --git a/unsloth/models/tp_env.py b/unsloth/models/tp_env.pyindex 52c40c9dd6b..7fcfc7dbb4a 100644--- a/unsloth/models/tp_env.py+++ b/unsloth/models/tp_env.py@@ -1,8 +1,35 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""UNSLOTH_TP_SIZE sets tp from the env (layout read once); order tp then FSDP2 (UNSLOTH_FSDP2=1)-over dp, else dp grads averaged before clipping and the optimizer step."""+"""Tensor / pipeline 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+ UNSLOTH_PP_SIZE=2 torchrun --nproc-per-node 2 train.py # pp 2+ UNSLOTH_PP_SIZE=2 UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 4 train.py # pp 2 x tp 2+ UNSLOTH_PP_SIZE=2 [UNSLOTH_FSDP2=1] torchrun --nproc-per-node 4 train.py # pp 2 x dp 2 (DDP-style / FSDP2)++UNSLOTH_PARALLEL="dp=..,tp=..,pp=..,cp=.." (unsloth/parallel_env.py) sets these variables in one flag, and adds+UNSLOTH_CP_SIZE: context parallel on the same mesh. The layout (parallel_env.ParallelLayout, TPEnvLayout here) is+read once. The world splits into pp x dp x cp x tp ranks (pp outermost, tp the inner dimension; one root+DeviceMesh, size-1 axes left out). Tensor parallel alone:+- 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 -> tp -> FSDP2.++With UNSLOTH_PP_SIZE (models/pp_env.py) the model loads in full on every rank and stays whole until the+Trainer: Trainer.__init__ splits it (apply_pipeline_parallel over mesh["pp"], the other stages' weights kept on+the CPU for the post-training cells), then applies tensor parallel inside the stage, then FSDP2 / DDP-style+averaging over mesh["dp"], and runs every training step through the pipeline schedule.+UNSLOTH_PP_MICROBATCHES (default 2 x pp, lowered to a divisor of the batch) and UNSLOTH_PP_SCHEDULE (gpipe,+1f1b) tune it.++UNSLOTH_TP_SHARDED_LOAD=0 loads 16-bit checkpoints in full on every rank instead (then shards them).+"""from __future__ import annotations@@ -28,112 +55,10 @@ _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)+from ..parallel_env import PP_SCHEDULES as _PP_SCHEDULES # noqa: F401 (old import path)+from ..parallel_env import ParallelLayout as TPEnvLayout+from ..parallel_env import _int_env # noqa: F401+from ..parallel_env import read_layout as _read_layoutdef env_layout():@@ -158,6 +83,12 @@ def env_hint():layout = Noneif layout is None:return ""+ if layout.pp > 1:+ what = "Pipeline parallelism" + (" x tensor parallelism" if layout.tp > 1 else "")+ return (+ f" ({what} came from {layout.env_vars}: unset {'them' if layout.tp > 1 else 'it'} to run this "+ "script with DDP or UNSLOTH_FSDP2=1.)"+ )return (f" (Tensor parallelism came from UNSLOTH_TP_SIZE={layout.tp}: unset it to run this script with ""DDP or UNSLOTH_FSDP2=1.)"@@ -185,6 +116,10 @@ _REFUSED_LOAD_FLAGS = (("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)"),)+_REFUSED_PIPELINE_LOAD_FLAGS = (+ ("full_finetuning", "full finetuning (full_finetuning = True; use UNSLOTH_FSDP2=1 instead)"),+ ("qat_scheme", "QAT (qat_scheme)"),+)def _bound(fn, args, kwargs):@@ -223,31 +158,55 @@ def tensor_parallel_env_load(fn):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)]+ what = (+ "tensor parallel"+ if layout.pp == 1+ else ("pipeline parallel" + (" x tensor parallel" if layout.tp > 1 else ""))+ )+ unset = " / ".join(var.split("=")[0] for var in layout.env_vars.split())+ refused = [what_ for key, what_ in _REFUSED_LOAD_FLAGS if values.get(key)]+ if (+ layout.pp > 1+ ): # tensor parallel alone trains these; pipeline parallel v1 trains LoRA adapters+ refused += [what_ for key, what_ in _REFUSED_PIPELINE_LOAD_FLAGS if values.get(key)]if refused:raise NotImplementedError(- f"Unsloth: UNSLOTH_TP_SIZE={layout.tp} (tensor parallel) does not support "+ f"Unsloth: {layout.env_vars} ({what}) does not support "+ "; ".join(refused)- + ". Unset UNSLOTH_TP_SIZE to run this script with DDP or UNSLOTH_FSDP2=1."+ + f". Unset {unset} to run this script with DDP or UNSLOTH_FSDP2=1.")from .fsdp2_load import fsdp2_sharded_load_requestedif fsdp2_sharded_load_requested():- # Its per-rank shard reads know nothing of the tp mesh.+ # Its per-rank shard reads know nothing of the tp / pp 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."+ f"Unsloth: {layout.env_vars} ({what}) does not support "+ "UNSLOTH_FSDP2_SHARDED_LOAD=1. Unset UNSLOTH_FSDP2_SHARDED_LOAD"+ + (+ "; tensor parallel already loads 16-bit weights sharded."+ if layout.pp == 1+ else "."+ ))+ if layout.tp == 1:+ # Pipeline parallel alone: a whole model on every rank (split at the Trainer), checked now.+ layout.mesh()+ _DEPTH["load"] += 1+ try:+ out = fn(*args, **kwargs)+ finally:+ _DEPTH["load"] -= 1+ return _check_pipeline_model(out, layout)mesh = layout.tp_mesh_DEPTH["load"] += 1try:# QAT swaps the loaded Linears for torchao FakeQuantizedLinear copies: load in full, shard later.qat = values.get("qat_scheme") is not Noneif _four_bit(values, fn) or not layout.sharded_loading or _is_adapter(values) or qat:- return fn(+ out = fn(*args, **kwargs) # full load; get_peft_model shards it (Params4bit included)+ return _check_pipeline_model(out, layout) if layout.pp > 1 else outfrom .tp_native import sharded_loadingtry:@@ -272,6 +231,25 @@ def tensor_parallel_env_load(fn):return _marks_world_save(from_pretrained)+def _check_pipeline_model(out, layout):+ """UNSLOTH_PP_SIZE: refuse a model the pipeline split cannot take right after loading it (not at the+ Trainer), naming the environment variable."""+ model = _model_of(out)+ if model is None or layout.pp == 1 or _is_peft_adapter_model(model):+ return out+ from .pp_native import check_pipeline_model++ try:+ check_pipeline_model(model)+ except (ValueError, RuntimeError, NotImplementedError) as exc:+ _reraise_with_hint(exc)+ return out+++def _is_peft_adapter_model(model):+ return hasattr(model, "peft_config") and bool(getattr(model, "peft_config", None))++def _marks_world_save(from_pretrained):@functools.wraps(from_pretrained)def wrapper(*args, **kwargs):@@ -330,7 +308,8 @@ def tensor_parallel_env_peft(fn):@functools.wraps(fn)def get_peft_model(*args, **kwargs):layout = env_layout()- if layout is None or _DEPTH["peft"]:+ if layout is None or _DEPTH["peft"] or layout.tp == 1 or layout.pp > 1:+ # Under UNSLOTH_PP_SIZE tensor parallel comes after the split, at the Trainer.return fn(*args, **kwargs)_DEPTH["peft"] += 1try:@@ -357,12 +336,13 @@ def _levels(model):def parallel_env_requested():return any(str(os.environ.get(name, "")).strip() not in ("", "1")- for name in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE")+ for name in ("UNSLOTH_TP_SIZE", "UNSLOTH_PP_SIZE", "UNSLOTH_CP_SIZE"))def install_tensor_parallel_env_trainer_init():- """Wrap Trainer.__init__ at import: model_init loads and non-Fast* models (encoders) would else train as plain DDP."""+ """Install the Trainer.__init__ wrapper at import: loads that all run inside model_init (and non-Fast*+ models such as encoders) would otherwise train in an unwrapped Trainer, without tensor / pipeline parallel."""if not parallel_env_requested():return Falsefrom transformers import Trainer@@ -374,13 +354,26 @@ def install_tensor_parallel_env_trainer_init():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)."""+ """Trainer.__init__ before anything else touches the model: the pipeline split (UNSLOTH_PP_SIZE), tensor+ parallel (if get_peft_model did not apply it) and the DDP-style dp dimension. Returns the layout (None+ without UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE)."""layout = env_layout()if layout is None or not isinstance(model, torch.nn.Module):return layout+ if layout.pp > 1:+ from .pp_env import pipeline_parallel_env_apply++ pipeline_parallel_env_apply(+ model, layout+ ) # also the DDP-style dp start (broadcast, stage.ddp_mesh)+ if layout.tp > 1:+ _apply(model, layout)+ if layout.grad_size > 1 and not layout.fsdp2:+ for level in _levels(model):+ level.__dict__[_DDP_MESH] = layout.dp_mesh+ return layout_apply(model, layout)- if layout.dp > 1 and not layout.fsdp2:+ if layout.grad_size > 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@@ -413,17 +406,18 @@ def fsdp2_dp_mesh(model):layout = _LAYOUT if _LAYOUT is not _UNSET else Noneif (layout is None- or layout.dp == 1+ or layout.grad_size == 1or not layout.fsdp2or not isinstance(model, torch.nn.Module)):return None+ from .pp_native import is_pipeline_parallelfrom .tp_native import is_tensor_parallel- return layout.dp_mesh if is_tensor_parallel(model) else None+ return layout.dp_mesh if is_tensor_parallel(model) or is_pipeline_parallel(model) else Nonedef 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 == 1+ return layout is not None and layout.grad_size == 1diff --git a/unsloth/models/tp_native.py b/unsloth/models/tp_native.pyindex 49784dece51..4833175bae4 100644--- a/unsloth/models/tp_native.py+++ b/unsloth/models/tp_native.py@@ -2881,6 +2881,19 @@ def _tp_meshes(model):return tp, dp+def _env_data_layout():+ """(data parallel size, rank) of an UNSLOTH_PARALLEL / UNSLOTH_TP_SIZE layout with context parallel, else+ None (the dp mesh is then the data mesh)."""+ import sys++ tp_env = sys.modules.get(__name__.rsplit(".", 1)[0] + ".tp_env")+ layout = getattr(tp_env, "_LAYOUT", None) if tp_env is not None else None+ if layout is None or layout is getattr(tp_env, "_UNSET", None) or getattr(layout, "cp", 1) == 1:+ return None+ data = layout.data_mesh+ return (layout.dp, data.get_local_rank() if data is not None else 0)++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),@@ -2939,7 +2952,11 @@ def _print_rank0(message):print(message)-def _refuse_tp_trainer_args(args, cpu_shards = False):+def _refuse_tp_trainer_args(+ args,+ cpu_shards = False,+ pipeline = False,+):problems = []if getattr(args, "deepspeed", None):problems.append("DeepSpeed")@@ -2947,6 +2964,16 @@ def _refuse_tp_trainer_args(args, cpu_shards = False):problems.append("accelerate FSDP / ParallelismConfig (use shard_model over mesh['dp'] for data parallel)")+ if (+ not pipeline # pp_env: the pipeline evaluates, gathering over the dp group only+ and _env_data_layout()+ is not None # cp x tp: the eval loss is not gathered over the data mesh yet+ and _strategy(getattr(args, "eval_strategy", getattr(args, "evaluation_strategy", "no")))+ != "no"+ ):+ problems.append(+ "evaluation during training with context parallel x tensor parallel (set eval_strategy = 'no')"+ )for flag in ("load_best_model_at_end", "push_to_hub"):if getattr(args, flag, False):problems.append(flag)@@ -3088,7 +3115,7 @@ def tp_trainer_setup("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)+ ranks = tp_mesh.size() * (dp_mesh.size() if dp_mesh is not None else 1) * _pp_size(model)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, "@@ -3101,18 +3128,27 @@ def tp_trainer_setup(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)+ from .pp_native import is_pipeline_parallel++ pipeline = is_pipeline_parallel(model)+ _refuse_tp_trainer_args(trainer.args, cpu_shards, pipeline)_refuse_full_finetuning_fsdp2(model)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.accelerator.__dict__[_TP_GATHER] = dp_mesh- _tp_train_sampler(trainer, dp_size, dp_rank)+ # The gradient mesh flattens (dp, cp) under context parallel, whose peers read the same rows.+ cp_data = _env_data_layout()+ data_size, data_rank = cp_data or (dp_size, dp_rank)+ trainer.accelerator.__dict__[_TP_DATA] = (data_size, data_rank)+ if not pipeline: # pp_env gathers over its own dp group (pp_env._dp_gather)+ trainer.accelerator.__dict__[_TP_GATHER] = dp_mesh+ _tp_train_sampler(trainer, data_size, data_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") if cp_data is not None and not pipeline else ():+ 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 (@@ -3137,6 +3173,9 @@ def tp_trainer_setup(from .fsdp2_native import _inner_optimizer, _mixed_param_groups, _split_mixed_param_groupsinner = _inner_optimizer(optimizer)+ from ..parallel_capabilities import refuse_shard_unaware_optimizer++ refuse_shard_unaware_optimizer(inner, "tp") # Muon would orthogonalize the tp shardsif 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(@@ -3232,6 +3271,12 @@ def _ckpt_path(directory, rank):return os.path.join(directory, _CKPT_DIR, f"rank{rank:05d}.pt")+def _cp_width():+ from . import tp_env+ layout = tp_env._LAYOUT if tp_env._LAYOUT is not tp_env._UNSET else None+ return int(getattr(layout, "cp", 1) or 1)++def _tp_layout(trainer):import torch.distributed as dist@@ -3241,8 +3286,16 @@ def _tp_layout(trainer):for name, p in trainer.model.named_parameters()if p.requires_grad]+ pp = _pp_size(trainer.model)+ cp = _cp_width()return {"world": dist.get_world_size() if dist.is_initialized() else 1,+ **(+ {"pp": pp} if pp > 1 else {}+ ), # pp_env Trainer checkpoints (a tp-only layout keeps its old keys)+ # dp_mesh is the flattened (dp, cp) mesh: without cp, tp=2,cp=2 and tp=2 x 2 replicas look alike, and the+ # resumed step count would skip the wrong number of rows.+ **({"cp": cp} if cp > 1 else {}),"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@@ -3353,13 +3406,13 @@ def _tp_resume_payload(self, checkpoint):if want != got:diff = {k: (got.get(k), want.get(k))- for k in ("world", "tp", "dp", "dp_kind")+ for k in ("world", "pp", "cp", "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."+ "UNSLOTH_TP_SIZE / UNSLOTH_CP_SIZE and data parallel mode.")self.__dict__["_unsloth_tp_resume"] = (checkpoint, payload)return payload@@ -3428,6 +3481,17 @@ def _dp_gather_object(obj, dp_mesh):return [x for y in out for x in y]+def _refuse_tp_trainer_call(name):+ def refuse(*args, **kwargs):+ raise RuntimeError(+ f"Unsloth: Trainer.{name} is not supported under context parallel x tensor parallel yet (the eval "+ "loss is not gathered over the data mesh); evaluate without context parallel, or on one GPU."+ + _env_hint()+ )++ return refuse++def _tp_trainer_save_model(self,output_dir = None,@@ -3476,8 +3540,14 @@ def _install_tp_accelerate_hooks():original_gather_for_metrics = Accelerator.gather_for_metricsdef _tp_model(self, model):- if self.__dict__.get(_TP_DATA) is None or not is_tensor_parallel(model):+ if self.__dict__.get(_TP_DATA) is None:return False+ if not is_tensor_parallel(model):+ from .pp_native import is_pipeline_parallel+ if not is_pipeline_parallel(+ model+ ): # UNSLOTH_PP_SIZE (pp_env.pp_trainer_setup): no DDP either+ return Falsetry:from .fsdp2_native import is_native_fsdp2except Exception:diff --git a/unsloth/models/tp_replica.py b/unsloth/models/tp_replica.pyindex 2b98c9e7d9c..f4c97d9230b 100644--- a/unsloth/models/tp_replica.py+++ b/unsloth/models/tp_replica.py@@ -91,6 +91,16 @@ def _fsdp2_units(model):def _refusal(root, what):"""None when `what` can run on this model, else why not."""if _marked(root, "_unsloth_pp"):+ from .pp_native import pipeline_stage_of++ stage = pipeline_stage_of(root)+ if (+ stage is not None and stage._kept is not None+ ): # UNSLOTH_PP_SIZE (pp_env): why the replica cannot+ from .pp_env import replica_refusal+ refusal = replica_refusal(stage, what)+ if refusal is not None:+ return refusalreturn (f"Unsloth: `{what}` is not supported on a pipeline parallel model (each rank holds one stage); save ""the adapter (PipelineParallel.save_adapter) and run it on one GPU."diff --git a/unsloth/parallel_capabilities.py b/unsloth/parallel_capabilities.pynew file mode 100644index 00000000000..30a19625172--- /dev/null+++ b/unsloth/parallel_capabilities.py@@ -0,0 +1,1245 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Which parallel compositions run, in one table, consulted before anything touches the model.++Three tables, the only place features meet:++- `FEATURES`: every feature (parallel axes, precision, compile, attention backend, packing, GC / offload,+ kernels, fused losses) declares what it takes from the root mesh (parallel_env.ParallelLayout), the batch+ metadata it consumes and produces (positions, packed lengths / cu_seqlens, BlockMask, the CP permutation,+ shifted labels, the sequence shard) and the hooks it installs (and whether it must own a hook alone).+ `check_features` refuses a set of active features whose meshes are missing, whose consumed metadata nobody+ produces, or that claim one exclusive hook twice. Features never patch each other.+- `RULES`: known refusals; each names its axis and what to run instead.+- `CELLS`: the composed layouts that are supported, each with its three kinds of evidence (numeric parity vs+ one process, engagement: the feature really ran, compile: graph breaks and recompiles not above one process),+ as test ids. A composition M1 opened (context parallel with tensor / pipeline parallel) runs only when a+ cell with all three covers it; anything else is refused with the evidence that is missing. Layouts that+ shipped before the registry (tp, pp, dp alone or together) report their status (`cell_status`) and run;+ UNSLOTH_PARALLEL_STRICT=1 refuses them too until their cells carry the evidence.++A request is a `Query` over every axis: trainer, model family (hybrid, multimodal, windowed), mode (LoRA, QLoRA,+full, FP8, NVFP4, MXFP8), packing, attention backend, compile, memory (GC / offload), kernels, loss, the CP+backend, torch / sm, and the layout. `check` runs `check_features`, `RULES` and the cell gate, in that order.+`markdown_table` prints the refusals and the cells (docs, launcher README).++Rules about one axis alone stay where that axis is implemented (context_parallel.py, models/pp_env.py,+models/tp_env.py); the rows here that repeat them run earlier, before the split, so a refused launch leaves the+model untouched.+"""++from __future__ import annotations++import dataclasses+import sys+from typing import Callable, Optional++__all__ = [+ "Query",+ "Rule",+ "RULES",+ "Feature",+ "FEATURES",+ "Cell",+ "CELLS",+ "MOE_FAMILIES",+ "METADATA",+ "HOOKS",+ "active_features",+ "check_features",+ "cell_status",+ "check",+ "check_layout",+ "query_from",+ "refuse_shard_unaware_optimizer",+ "markdown_table",+]++[email protected](frozen = True)+class Query:+ trainer: str = "trainer" # trainer, sft, dpo, grpo, other_rl, other+ family: str = "" # config.model_type+ hybrid: bool = False # linear attention / state space layers beside attention+ multimodal: bool = False+ windowed: bool = False # sliding window, chunked attention or logit softcapping+ mode: str = "lora" # lora, qlora, full+ packing: bool = False+ cp_backend: Optional[str] = None # ulysses, ring (resolved)+ torch: tuple = (0, 0)+ sm: Optional[int] = None # CUDA compute capability major, None off CUDA+ dp: int = 1+ tp: int = 1+ pp: int = 1+ cp: int = 1+ fsdp2: bool = False+ vllm: bool = False+ pp_schedule: Optional[str] = None # gpipe, 1f1b, interleaved+ attention: str = "sdpa" # sdpa, eager, flash, flash_varlen, fa3, fa4, flex, flex_sparse+ compile: str = "eager" # eager, block (Unsloth's per decoder layer torch.compile)+ memory: str = "none" # none, gc (torch checkpoint), unsloth_gc, unsloth_offload, tiled_mlp+ kernels: bool = False # Unsloth's fused RoPE / RMSNorm / SwiGLU / LoRA kernels+ loss: str = "standard" # standard, fused_ce, chunked_ce, fused_rl+ moe: bool = False # routed experts+ router_aux_loss: bool = (+ False # the load balancing loss is on (output_router_logits, or TRL's default coef)+ )+ expert_lora: bool = False # LoRA on the routed experts (PEFT target_parameters / ParamWrapper)+ moe_backend: str = (+ "" # UNSLOTH_MOE_BACKEND: grouped_mm, unsloth_triton, native_torch ("" = default)+ )+ optim: str = "" # the optimizer (args.optim or the class of a prebuilt one), lower case++[email protected](frozen = True)+class Rule:+ axis: str+ when: str # the cell, in words (the table's first column)+ applies: Callable[[Query], bool]+ reason: str+ alternative: str+++def _rl(q):+ return q.trainer in ("dpo", "grpo", "other_rl")+++RULES = (+ Rule(+ "cp x pp",+ "context parallel inside pipeline stages",+ lambda q: q.cp > 1 and q.pp > 1,+ "context parallel inside pipeline stages is not composed yet (stage boundaries would carry sequence "+ "shards the schedule does not know about)",+ "drop cp, or drop pp (cp composes with tp and with DDP / FSDP2)",+ ),+ Rule(+ "cp x tp",+ "context parallel x tensor parallel with the ring backend",+ lambda q: q.cp > 1 and q.tp > 1 and q.cp_backend == "ring",+ "ring attention on tensor parallel heads is not verified",+ "cp_backend=ulysses (or auto)",+ ),+ Rule(+ "cp x tp",+ "context parallel x tensor parallel for DPO / GRPO",+ lambda q: q.cp > 1 and q.tp > 1 and _rl(q),+ "the DPO / GRPO context parallel hooks build their own mesh",+ "run DPO / GRPO with cp alone (DDP), or with tp and cp = 1",+ ),+ Rule(+ "cp x tp",+ "context parallel x tensor parallel on hybrid (linear attention) or multimodal models",+ lambda q: q.cp > 1 and q.tp > 1 and (q.hybrid or q.multimodal),+ "tensor parallel keeps the linear attention layers replicated, and that path is not verified with "+ "Ulysses",+ "drop tp (Ulysses cp runs Qwen3-Next / Qwen3.5 hybrids alone or with DDP / FSDP2)",+ ),+ Rule(+ "cp x tp",+ "context parallel x tensor parallel with packed rows",+ lambda q: q.cp > 1 and q.tp > 1 and q.packing,+ "packed rows under cp x tp are not verified",+ "packing = False, or drop tp",+ ),+ Rule(+ "cp x tp",+ "context parallel x tensor parallel on full finetuning",+ lambda q: q.cp > 1 and q.tp > 1 and q.mode == "full",+ "full finetuning under cp x tp has no parity evidence yet (tensor parallel alone trains it)",+ "use LoRA, or UNSLOTH_FSDP2=1 with cp for full finetuning",+ ),+ Rule(+ "cp backend",+ "ring context parallel with packed rows",+ lambda q: q.cp > 1 and q.cp_backend == "ring" and q.packing,+ "ring attention cannot see document boundaries in a packed row",+ "cp_backend=ulysses (or auto), or packing = False",+ ),+ Rule(+ "cp backend",+ "ring context parallel on hybrid (linear attention) models",+ lambda q: q.cp > 1 and q.cp_backend == "ring" and q.hybrid,+ "ring attention cannot split the sequential scans of linear attention layers",+ "cp_backend=ulysses (or auto)",+ ),+ Rule(+ "cp backend",+ "ring context parallel for DPO / GRPO",+ lambda q: q.cp > 1 and q.cp_backend == "ring" and _rl(q),+ "the DPO / GRPO context parallel hooks shard decoder inputs for Ulysses only",+ "cp_backend=ulysses (or auto)",+ ),+ Rule(+ "cp backend",+ "ring context parallel on GPUs below compute capability 8.0",+ lambda q: q.cp > 1 and q.cp_backend == "ring" and q.sm is not None and q.sm < 8,+ "torch ring attention fails in backward without flash attention (T4, V100)",+ "cp_backend=ulysses (or auto)",+ ),+ Rule(+ "cp x attention",+ "context parallel on sliding window / chunked / softcapped attention",+ lambda q: q.cp > 1 and q.windowed,+ "Unsloth's context parallel attention drops the window / chunk / softcap",+ "drop cp for this model",+ ),+ Rule(+ "cp x torch",+ "context parallel on torch < 2.7",+ lambda q: q.cp > 1 and q.torch < (2, 7),+ "torch's context parallel API arrived in 2.7",+ "upgrade torch, or drop cp",+ ),+ Rule(+ "pp x trainer",+ "pipeline parallel for DPO / GRPO / other RL trainers",+ lambda q: q.pp > 1 and (_rl(q) or q.trainer == "other"),+ "pipeline parallel v1 runs the Trainer / SFTTrainer causal LM loss only",+ "drop pp (tp, cp or FSDP2 run the RL trainers' whole model per rank)",+ ),+ Rule(+ "pp x packing",+ "pipeline parallel with packed / padding-free rows",+ lambda q: q.pp > 1 and q.packing,+ "packed rows are not carried between pipeline stages yet",+ "packing = False, or drop pp",+ ),+ Rule(+ "pp x mode",+ "pipeline parallel full finetuning",+ lambda q: q.pp > 1 and q.mode == "full",+ "pipeline parallel trains LoRA adapters",+ "use LoRA, or UNSLOTH_FSDP2=1 (dp) / UNSLOTH_TP_SIZE (tp) for full finetuning",+ ),+ Rule(+ "pp x schedule",+ "interleaved pipeline schedules",+ lambda q: q.pp > 1 and q.pp_schedule == "interleaved",+ "one stage per rank in v1",+ "pp_schedule=gpipe or 1f1b",+ ),+ Rule(+ "cp x attention",+ "context parallel with flex attention block masks",+ lambda q: q.cp > 1 and q.attention in ("flex", "flex_sparse"),+ "the BlockMask is built for the whole sequence, not for the rank-local (permuted) shard",+ "attention sdpa / flash, or drop cp",+ ),+ Rule(+ "cp x precision",+ "context parallel with FP8 / NVFP4 / MXFP8 training",+ lambda q: q.cp > 1 and q.mode in ("fp8", "nvfp4", "mxfp8"),+ "low precision training is not composed with the sequence exchange",+ "LoRA / QLoRA / full in 16-bit, or drop cp",+ ),+ Rule(+ "tp / pp x precision",+ "tensor / pipeline parallel with FP8 / NVFP4 / MXFP8 training",+ lambda q: (q.tp > 1 or q.pp > 1) and q.mode in ("fp8", "nvfp4", "mxfp8"),+ "the low precision linear layers are not sharded by tensor parallel or split by pipeline parallel",+ "UNSLOTH_FSDP2=1 (dp) for FP8 / NVFP4, or 16-bit LoRA with tp / pp",+ ),+ Rule(+ "MoE x pp / cp",+ "the MoE router auxiliary loss (output_router_logits) under context parallel",+ lambda q: q.moe and q.router_aux_loss and q.cp > 1,+ "the load balancing loss is a product of whole-batch means; per shard pieces would be summed wrong "+ "(pipeline parallel carries the router statistics between stages, context parallel does not yet). "+ "TRL's SFTTrainer turns it on from the architecture's router_aux_loss_coef by default",+ "router_aux_loss_coef = 0.0 in the trainer config (and output_router_logits = False), or drop cp",+ ),+ Rule(+ "fsdp2 / tp x optimizer",+ "Muon under native FSDP2 or tensor parallel",+ lambda q: (q.fsdp2 or q.tp > 1) and "muon" in q.optim and q.optim != "torch.optim.muon",+ "Muon orthogonalizes each weight matrix, and every rank holds only a shard of it, so a Muon that "+ "reads the local tensors would orthogonalize the shards",+ "torch.optim.Muon (it steps DTensor shards as whole matrices), adamw_torch / adamw_8bit, or DDP "+ "(dp without fsdp) for another Muon",+ ),+ Rule(+ "pp / tp x vLLM",+ "pipeline / tensor parallel with vLLM (fast_inference)",+ lambda q: (q.pp > 1 or q.tp > 1) and q.vllm,+ "vLLM needs the whole model on each rank",+ "fast_inference = False, or drop tp / pp",+ ),+)+++# Batch metadata a feature can consume or produce. "batch" means the collator's own keys.+METADATA = (+ "input_ids",+ "labels",+ "attention_mask",+ "position_ids", # per token positions (global ones once the sequence is sharded)+ "packed_seq_lengths", # document lengths of a packed row (Unsloth's packing)+ "cu_seqlens", # cumulative lengths for varlen kernels, derived from packed_seq_lengths+ "block_mask", # flex attention BlockMask+ "cp_permutation", # ring CP load balancing: the order tokens were sharded in+ "seq_shard", # this rank holds a slice of the sequence+ "shift_labels", # next-token labels built before sharding (a shard cannot see its neighbour)+ "num_items_in_batch", # the accumulation window's token count (loss normaliser)+ "stage_hidden", # hidden states sent between pipeline stages+)+_BATCH = ("input_ids", "labels", "attention_mask", "position_ids", "num_items_in_batch")++# Where a feature hooks in. Exclusive hooks run the step themselves: two owners cannot compose.+HOOKS = (+ "from_pretrained",+ "get_peft_model",+ "Trainer.__init__",+ "Trainer.training_step",+ "Trainer.prediction_step",+ "Trainer.save_model",+ "Accelerator.prepare_model",+ "Accelerator.prepare_data_loader",+ "Accelerator.clip_grad_norm_",+ "optimizer.step",+ "collator",+ "decoder_layer.forward",+ "attention_function",+ "loss_function",+ "torch.utils.checkpoint",+)++[email protected](frozen = True)+class Feature:+ name: str+ kind: str # parallel, precision, compile, attention, packing, memory, kernels, loss+ module: str # where it is implemented+ active: Callable[[Query], bool]+ mesh: tuple = () # root mesh axes it takes (parallel_env.ParallelLayout.dims names; "dp" = the dp axis)+ consumes: tuple = () # required: someone must produce it+ uses: tuple = () # read when present (e.g. packed lengths for Ulysses)+ produces: tuple = ()+ hooks: tuple = ()+ exclusive: tuple = () # hooks it must own alone+ scope: str = (+ "instance" # instance: hooks per trainer / model; class: still patches a class (debt)+ )+++def _gc(q):+ return q.memory in ("gc", "unsloth_gc", "unsloth_offload")+++FEATURES = (+ # Parallel axes.+ Feature(+ "ddp",+ "parallel",+ "transformers / accelerate DDP; tp_native._dp_average under tp / pp",+ lambda q: q.dp > 1 and not q.fsdp2,+ mesh = ("dp", "cp"),+ consumes = ("num_items_in_batch",),+ hooks = ("Accelerator.prepare_model", "Accelerator.clip_grad_norm_"),+ ),+ Feature(+ "fsdp2",+ "parallel",+ "models/fsdp2_native.py",+ lambda q: q.dp > 1 and q.fsdp2,+ mesh = ("dp", "cp"),+ consumes = ("num_items_in_batch",),+ hooks = (+ "Trainer.__init__",+ "Accelerator.prepare_model",+ "Accelerator.clip_grad_norm_",+ "optimizer.step",+ ),+ ),+ Feature(+ "tp",+ "parallel",+ "models/tp_native.py, models/tp_env.py",+ lambda q: q.tp > 1,+ mesh = ("tp",),+ hooks = (+ "from_pretrained",+ "get_peft_model",+ "Trainer.__init__",+ "Accelerator.prepare_model",+ "Accelerator.prepare_data_loader",+ "Accelerator.clip_grad_norm_",+ "Trainer.save_model",+ ),+ ),+ Feature(+ "pp",+ "parallel",+ "models/pp_native.py, models/pp_env.py",+ lambda q: q.pp > 1,+ mesh = ("pp",),+ consumes = ("input_ids", "labels", "position_ids", "num_items_in_batch"),+ produces = ("stage_hidden",),+ hooks = (+ "Trainer.__init__",+ "Accelerator.prepare_data_loader",+ "Accelerator.clip_grad_norm_",+ "Trainer.save_model",+ ),+ exclusive = ("Trainer.training_step", "Trainer.prediction_step"),+ ),+ Feature(+ "cp.ulysses",+ "parallel",+ "context_parallel.py, utils/ulysses.py, utils/ulysses_hybrid.py",+ lambda q: q.cp > 1 and q.cp_backend != "ring",+ mesh = ("cp",),+ consumes = ("input_ids", "labels", "position_ids", "num_items_in_batch"),+ uses = ("packed_seq_lengths",),+ produces = ("seq_shard", "shift_labels", "position_ids"),+ hooks = ("Trainer.__init__", "attention_function"),+ exclusive = ("Trainer.training_step", "Trainer.prediction_step"),+ scope = "class",+ ),+ Feature(+ "cp.ring",+ "parallel",+ "context_parallel.py (torch context_parallel)",+ lambda q: q.cp > 1 and q.cp_backend == "ring",+ mesh = ("cp",),+ consumes = ("input_ids", "labels", "position_ids", "num_items_in_batch"),+ produces = ("seq_shard", "shift_labels", "cp_permutation", "position_ids"),+ hooks = ("Trainer.__init__", "attention_function"),+ exclusive = ("Trainer.training_step", "Trainer.prediction_step"),+ scope = "class",+ ),+ # Precision.+ Feature(+ "lora",+ "precision",+ "peft + models/lora_init.py",+ lambda q: q.mode == "lora",+ hooks = ("get_peft_model",),+ ),+ Feature(+ "qlora",+ "precision",+ "bitsandbytes 4-bit + peft",+ lambda q: q.mode == "qlora",+ hooks = ("from_pretrained", "get_peft_model"),+ ),+ Feature(+ "full",+ "precision",+ "full finetuning",+ lambda q: q.mode == "full",+ hooks = ("from_pretrained",),+ ),+ Feature(+ "low_precision",+ "precision",+ "models/float8_training.py (FP8 / MXFP8 / NVFP4 via torchao)",+ lambda q: q.mode in ("fp8", "nvfp4", "mxfp8"),+ hooks = ("from_pretrained", "Trainer.__init__"),+ ),+ # Compile.+ Feature(+ "block_compile",+ "compile",+ "models/_block_compile.py (torch.compile per decoder layer)",+ lambda q: q.compile == "block",+ hooks = ("decoder_layer.forward",),+ ),+ # Attention backends.+ Feature(+ "sdpa",+ "attention",+ "torch SDPA",+ lambda q: q.attention in ("sdpa", "eager"),+ hooks = ("attention_function",),+ ),+ Feature(+ "flash",+ "attention",+ "utils/attention_dispatch.py (flash dense / xformers)",+ lambda q: q.attention == "flash",+ uses = ("attention_mask",),+ hooks = ("attention_function",),+ ),+ Feature(+ "flash_varlen",+ "attention",+ "utils/attention_dispatch.py (flash / FA3 / FA4 varlen)",+ lambda q: q.attention in ("flash_varlen", "fa3", "fa4"),+ consumes = ("cu_seqlens",),+ hooks = ("attention_function",),+ ),+ Feature(+ "flex",+ "attention",+ "utils/attention_dispatch.py (flex attention)",+ lambda q: q.attention in ("flex", "flex_sparse"),+ consumes = ("position_ids",),+ produces = ("block_mask",),+ hooks = ("attention_function",),+ ),+ # Packing.+ Feature(+ "packing",+ "packing",+ "utils/packing.py (sample packing / padding-free)",+ lambda q: q.packing,+ produces = ("packed_seq_lengths", "cu_seqlens", "position_ids"),+ hooks = ("collator",),+ ),+ # Memory.+ Feature(+ "gradient_checkpointing",+ "memory",+ "torch.utils.checkpoint / unsloth_zoo gradient_checkpointing",+ _gc,+ hooks = ("torch.utils.checkpoint",),+ ),+ Feature(+ "tiled_mlp",+ "memory",+ "models/_tiled_mlp_ddp.py + unsloth_zoo tiled MLP",+ lambda q: q.memory == "tiled_mlp",+ hooks = ("decoder_layer.forward",),+ ),+ # Kernels and losses.+ Feature(+ "unsloth_kernels",+ "kernels",+ "kernels/ (RoPE, RMSNorm, SwiGLU, fast LoRA)",+ lambda q: q.kernels,+ hooks = ("decoder_layer.forward", "attention_function"),+ ),+ Feature(+ "fused_loss",+ "loss",+ "unsloth_zoo fused / chunked CE, models/_fused_rl_logprobs.py",+ lambda q: q.loss in ("fused_ce", "chunked_ce", "fused_rl"),+ consumes = ("labels",),+ hooks = ("loss_function",),+ ),+)+++def active_features(query: Query) -> list:+ return [f for f in FEATURES if f.active(query)]+++def check_features(query: Query) -> list:+ """Composition from the declarations alone: mesh axes, metadata and exclusive hooks. Returns the active+ feature names; NotImplementedError on the first conflict."""+ active = active_features(query)+ sizes = {"dp": query.dp, "tp": query.tp, "pp": query.pp, "cp": query.cp}+ for feature in active:+ # A data parallel feature reduces over (dp, cp); it needs at least one of them.+ if (+ feature.mesh+ and feature.kind == "parallel"+ and not any(sizes.get(a, 1) > 1 for a in feature.mesh)+ ):+ raise NotImplementedError(+ f"Unsloth: {feature.name}: needs the {' / '.join(feature.mesh)} mesh axis. ({_describe(query)})"+ )+ produced = set(_BATCH)+ for feature in active:+ produced.update(feature.produces)+ for feature in active:+ missing = [m for m in feature.consumes if m not in produced]+ if missing:+ raise NotImplementedError(+ f"Unsloth: {feature.kind} x metadata: {feature.name} consumes {', '.join(missing)}, which no "+ f"active feature produces. ({_describe(query)})"+ )+ owners = {}+ for feature in active:+ for hook in feature.exclusive:+ if hook in owners:+ raise NotImplementedError(+ f"Unsloth: {owners[hook]} x {feature.name}: both run {hook} themselves, so neither would "+ f"see the other's step. ({_describe(query)})"+ )+ owners[hook] = feature.name+ return [f.name for f in active]++[email protected](frozen = True)+class Cell:+ """A supported composition: `match` holds the allowed values per Query field (a tuple), and the three+ kinds of evidence as test ids. A missing kind is None."""++ name: str+ match: dict+ parity: Optional[str]+ engagement: Optional[str]+ compile: Optional[str]+ note: str = ""+ min_torch: Optional[tuple] = None++ def covers(self, query: Query) -> bool:+ if self.min_torch is not None and tuple(query.torch) < self.min_torch:+ return False+ return all(getattr(query, k) in v for k, v in self.match.items())++ def missing(self) -> list:+ return [k for k in ("parity", "engagement", "compile") if not getattr(self, k)]+++_GLOO = "tests/test_parallel_cp_compose_gloo.py::"+# Block compile cells: their compile tests pass on torch 2.13 and 2.15; torch 2.10 recompiles more than one+# process (6 > 1 under cp x tp, 1 > 0 for MoE under cp), so older versions run them eager.+BLOCK_COMPILE_TORCH = (2, 13)+_CP_TP = {+ "trainer": ("sft",),+ "family": ("llama",),+ "hybrid": (False,),+ "multimodal": (False,),+ "windowed": (False,),+ "mode": ("lora",),+ "packing": (False,),+ "cp_backend": ("ulysses",),+ "pp": (1,),+ "attention": ("sdpa", "eager"),+ "memory": ("none", "gc"),+ "kernels": (False,),+ "loss": ("standard",),+ "vllm": (False,),+ "moe": (False,),+}+_PARITY = _GLOO + "test_cp_x_tp_from_unsloth_parallel_matches_one_process"+_CP_DP = {**_CP_TP, "tp": (1,), "moe": (False,)}+_FSDP2_CP = _GLOO + "test_cp_with_native_fsdp2_matches_one_process"+_MOE_CP = _GLOO + "test_moe_without_aux_loss_under_cp_matches_one_process"+CELLS = (+ Cell(+ "cp x native FSDP2 (dp_shard x cp), eager",+ {**_CP_DP, "fsdp2": (True,), "compile": ("eager",), "dp": (1, 2), "cp": (2,)},+ parity = _FSDP2_CP,+ engagement = _FSDP2_CP+ + " (FSDP2 mesh covers the cp group, seq / cp tokens, Ulysses exchanges)",+ compile = "eager: no compiled region",+ ),+ Cell(+ "cp x tp (DDP dp), eager",+ {**_CP_TP, "fsdp2": (False,), "compile": ("eager",), "dp": (1, 2), "tp": (2,), "cp": (2,)},+ parity = _PARITY + "[cp2_tp2|dp2_cp2_tp2]",+ engagement = _PARITY+ + " (seq / cp tokens per rank, one Ulysses exchange per layer, cp group != tp group)",+ compile = "eager: no compiled region",+ ),+ Cell(+ "cp x tp (FSDP2 dp), eager",+ {**_CP_TP, "fsdp2": (True,), "compile": ("eager",), "dp": (2,), "tp": (2,), "cp": (2,)},+ parity = _PARITY + "[fsdp2_cp2_tp2]",+ engagement = _PARITY+ + "[fsdp2_cp2_tp2] (as above, FSDP2 over the flattened (dp_shard, cp) mesh)",+ compile = "eager: no compiled region",+ ),+ Cell(+ "cp x tp, Unsloth block compile",+ {+ **_CP_TP,+ "fsdp2": (False, True),+ "compile": ("block",),+ "dp": (1, 2),+ "tp": (2,),+ "cp": (2,),+ },+ parity = _GLOO + "test_block_compile_composes_like_one_process",+ engagement = _GLOO+ + "test_block_compile_composes_like_one_process (compiled classes, seq / cp tokens)",+ compile = _GLOO+ + "test_block_compile_composes_like_one_process (graph breaks / recompiles <= one process)",+ min_torch = BLOCK_COMPILE_TORCH,+ ),+)+++# MoE rows: family x precision x router aux loss x parallel mode. Evidence where a CPU gloo run proves it; every+# other row is refused (under cp / pp / tp) or reported unverified (dp alone), with what it waits for.+MOE_FAMILIES = ("qwen3_moe", "qwen3_5_moe", "gpt_oss", "deepseek_v3", "kimi_linear")+_MOE_PRECISION = {+ "lora": {"mode": ("lora",), "expert_lora": (False,)},+ "lora+experts": {"mode": ("lora",), "expert_lora": (True,)},+ "qlora": {"mode": ("qlora",)},+ "full": {"mode": ("full",)},+}+_ONE = (1,)+_MOE_MODES = {+ "ddp": {"dp": (2, 4, 8), "fsdp2": (False,), "cp": _ONE, "tp": _ONE, "pp": _ONE},+ "fsdp2": {"dp": (2, 4, 8), "fsdp2": (True,), "cp": _ONE, "tp": _ONE, "pp": _ONE},+ "cp": {"dp": (1, 2, 4), "fsdp2": (False,), "cp": (2, 4, 8), "tp": _ONE, "pp": _ONE},+ "fsdp2_cp": {"dp": (1, 2, 4), "fsdp2": (True,), "cp": (2, 4, 8), "tp": _ONE, "pp": _ONE},+ # Pipeline parallel carries the router auxiliary loss on a pp-only mesh, one stage per rank (gpipe / 1f1b),+ # and refuses it under reentrant checkpointing (models/pp_native.py).+ "pp": {+ "dp": _ONE,+ "fsdp2": (False,),+ "cp": _ONE,+ "tp": _ONE,+ "pp": (2, 4, 8),+ "pp_schedule": ("gpipe", "1f1b"),+ "memory": ("none",),+ },+ "tp": {"tp": (2, 4, 8)},+}+_MOE_COMMON = {+ "trainer": ("sft",),+ "moe": (True,),+ "attention": ("sdpa", "eager"),+ "memory": ("none", "gc"),+ "kernels": (False,),+ "loss": ("standard",),+ "packing": (False,),+ "vllm": (False,),+}+_MOE_TEST = _GLOO + "test_moe_under_data_and_context_parallel_matches_one_process"+_MOE_AUX_TEST = _GLOO + "test_moe_with_router_aux_loss_under_ddp_matches_per_micro_batch"+_MOE_COMPILE = _GLOO + "test_moe_block_compile_under_cp_is_compile_clean"+_MOE_PP = "tests/test_pp_moe_aux_gloo.py::test_pp2_moe_aux_matches_gradient_accumulation"+# (family, precision, aux, mode) -> (parity, engagement, compile) for the rows a test proves.+_MOE_EVIDENCE = {+ ("qwen3_moe", "lora+experts", False, "ddp"): (_MOE_TEST + "[lora-ddp]",) * 2+ + ("eager: no compiled region",),+ ("qwen3_moe", "lora+experts", False, "fsdp2"): (_MOE_TEST + "[lora-fsdp2]",) * 2+ + ("eager: no compiled region",),+ # Block compile with LoRA experts: cp 2 measures 28-34 recompiles vs 22-25 in one process (per-instance+ # ParametrizedQwen3MoeTopKRouter type guards, router hooks from #16410): eager only, as FSDP2 x cp below.+ ("qwen3_moe", "lora+experts", False, "cp"): (_MOE_TEST + "[lora-cp2]",) * 2+ + ("eager: block compile recompiles more than one process",),+ # Block compile under FSDP2 x cp measured 28 recompiles against 26 in one process (one more+ # ParametrizedQwen3MoeTopKRouter type guard in the router forward and in PEFT's get_base_layer): eager only.+ ("qwen3_moe", "lora+experts", False, "fsdp2_cp"): (_MOE_TEST + "[lora-fsdp2_cp2]",) * 2+ + ("eager: block compile recompiles more than one process",),+ ("qwen3_moe", "full", False, "fsdp2"): (_MOE_TEST + "[full-fsdp2]",) * 2+ + ("eager: no compiled region",),+ ("qwen3_moe", "full", False, "cp"): (_MOE_TEST + "[full-cp2]",) * 2+ + (_MOE_COMPILE + "[full]",),+ ("qwen3_moe", "lora+experts", True, "ddp"): (_MOE_AUX_TEST,) * 2+ + ("eager: no compiled region",),+ ("qwen3_moe", "lora+experts", True, "fsdp2"): (_MOE_AUX_TEST,) * 2+ + ("eager: no compiled region",),+ # pp2 vs gradient accumulation over the same micro-batches in one process (losses, aux, every gradient).+ ("qwen3_moe", "lora+experts", True, "pp"): (+ _MOE_PP + "[lora_coef1_gpipe_mask|lora_coef0.01_1f1b_nomask]",+ )+ * 2+ + ("eager: no compiled region",),+ ("qwen3_moe", "lora+experts", False, "pp"): (_MOE_PP + "[lora_aux_off_1f1b_mask]",) * 2+ + ("eager: no compiled region",),+}+++def _moe_note(family, precision, aux, mode):+ if mode == "tp":+ return "tensor parallel MoE runs (models/tp_native.py, its own gloo tests); no registry parity row yet"+ if aux and mode == "cp":+ return "refused by the MoE x pp / cp rule (aux-loss injection first)"+ if mode == "pp":+ if family != "qwen3_moe":+ return "pipeline parallel carries the router auxiliary loss for Qwen3-MoE only (refused at the split)"+ if precision == "full":+ return "refused by the pp x mode rule (pipeline parallel trains LoRA adapters)"+ if precision == "qlora":+ # Measured on one G4 (2 NCCL ranks sharing the card): qwen3_moe QLoRA under DDP equals one process over the+ # same micro-batches (bitsandbytes 4-bit expert path engaged); cp / FSDP2 x QLoRA have not run.+ return "4-bit experts need bitsandbytes on a GPU (only DDP measured so far; L4 / G4 via notebook_cloud_run.py)"+ if family != "qwen3_moe":+ return "no tiny-checkpoint gloo run for this family yet"+ return "not run yet"+++def _moe_cells():+ cells = []+ for family in MOE_FAMILIES:+ for precision, pmatch in _MOE_PRECISION.items():+ for aux in (False, True):+ for mode, mmatch in _MOE_MODES.items():+ evidence = _MOE_EVIDENCE.get((family, precision, aux, mode))+ match = {+ **_MOE_COMMON,+ **pmatch,+ **mmatch,+ "family": (family,),+ "router_aux_loss": (aux,),+ "compile": ("eager",),+ }+ name = f"MoE {family} x {precision} x aux {'on' if aux else 'off'} x {mode}"+ if evidence:+ cells.append(Cell(name, match, *evidence))+ if not evidence[2].startswith("eager:"):+ cells.append(+ Cell(+ name + ", block compile",+ {**match, "compile": ("block",)},+ *evidence,+ min_torch = BLOCK_COMPILE_TORCH,+ )+ )+ else:+ cells.append(+ Cell(+ name,+ match,+ None,+ None,+ None,+ note = _moe_note(family, precision, aux, mode),+ )+ )+ return tuple(cells)+++CELLS = CELLS + _moe_cells()+++def _strict() -> bool:+ import os+ return os.environ.get("UNSLOTH_PARALLEL_STRICT", "0").strip().lower() in (+ "1",+ "true",+ "yes",+ "on",+ )+++def _gated(query: Query) -> bool:+ """Compositions opened by the one-flag work, and MoE under context / pipeline parallel: they run only with a+ cell carrying all three kinds of evidence. MoE under tensor parallel alone keeps tp_native's own support."""+ return (query.cp > 1 and (query.tp > 1 or query.pp > 1)) or (+ query.moe and (query.cp > 1 or query.pp > 1)+ )+++def cell_status(query: Query) -> tuple:+ """("supported", cell) | ("unverified", reason) | ("single", None) for one axis alone or none."""+ axes = sum(1 for n in (query.tp, query.pp, query.cp) if n > 1) + (query.dp > 1)+ for cell in CELLS:+ if cell.covers(query):+ missing = cell.missing()+ if not missing:+ return ("supported", cell)+ note = f"; {cell.note}" if cell.note else ""+ return ("unverified", f"cell {cell.name!r} lacks {', '.join(missing)} evidence{note}")+ if axes <= 1 and not _gated(query):+ return ("single", None)+ for cell in CELLS:+ if cell.min_torch is not None and all(+ getattr(query, k) in v for k, v in cell.match.items()+ ):+ have, need = ".".join(map(str, query.torch)), ".".join(map(str, cell.min_torch))+ eager = (+ "; UNSLOTH_BLOCK_COMPILE_LEGACY=0 at load runs it eager"+ if query.compile == "block"+ else ""+ )+ return (+ "unverified",+ f"cell {cell.name!r} is proven on torch >= {need} only (torch {have} < {need}){eager}",+ )+ differ = []+ for cell in CELLS:+ off = [+ f"{k}={getattr(query, k)!r}"+ for k, v in cell.match.items()+ if getattr(query, k) not in v+ ]+ differ.append(f"{cell.name!r} differs in {', '.join(off)}")+ return (+ "unverified",+ "no supported cell covers it" + (f" ({'; '.join(differ[:3])})" if differ else ""),+ )+++def check(query: Query, cells: bool = True) -> None:+ for rule in RULES:+ if rule.applies(query):+ raise NotImplementedError(+ f"Unsloth: {rule.axis}: {rule.when} is not supported: {rule.reason}. Instead: "+ f"{rule.alternative}. ({_describe(query)})"+ )+ check_features(query)+ if not cells:+ return # the layout alone (read at from_pretrained): the trainer checks the cell once it knows the rest+ status, detail = cell_status(query)+ if status == "unverified" and (_gated(query) or _strict()):+ raise NotImplementedError(+ f"Unsloth: composition: this cell has no numeric parity / engagement / compile evidence yet: "+ f"{detail}. Instead: a supported cell (see unsloth.parallel_capabilities.CELLS), or drop an axis. "+ f"({_describe(query)})"+ )+++def _describe(q: Query) -> str:+ parts = [+ f"{name} {getattr(q, name)}" for name in ("pp", "dp", "cp", "tp") if getattr(q, name) > 1+ ]+ if q.cp > 1 and q.cp_backend:+ parts.append(f"cp_backend {q.cp_backend}")+ if q.fsdp2:+ parts.append("FSDP2")+ return (+ "layout "+ + (" x ".join(parts) or "single rank")+ + f", trainer {q.trainer}"+ + (f", model {q.family}" if q.family else "")+ )+++def _torch_version():+ import torch+ from packaging.version import Version++ v = Version(Version(torch.__version__).base_version)+ return (v.major, v.minor)+++def _sm():+ try:+ import torch+ if torch.cuda.is_available() and getattr(torch.version, "cuda", None):+ return torch.cuda.get_device_capability()[0]+ except Exception:+ pass+ return None+++def _trainer_kind(trainer_cls) -> str:+ if trainer_cls is None:+ return "trainer"+ names = [c.__name__ for c in getattr(trainer_cls, "__mro__", ())]+ for kind, markers in (+ ("grpo", ("GRPOTrainer",)),+ ("dpo", ("DPOTrainer",)),+ ("sft", ("SFTTrainer",)),+ ):+ if any(n in markers or n == "Unsloth" + markers[0] for n in names):+ return kind+ rl = (+ "ORPOTrainer",+ "KTOTrainer",+ "PPOTrainer",+ "RLOOTrainer",+ "CPOTrainer",+ "OnlineDPOTrainer",+ "RewardTrainer",+ )+ if any(n in rl or n.removeprefix("Unsloth") in rl for n in names):+ return "other_rl"+ return "trainer" if "Trainer" in names else "other"+++def _model_traits(model):+ config = getattr(model, "config", None)+ if config is None and isinstance(model, str):+ return "", False, False, False+ text = getattr(config, "text_config", None) or config+ family = str(getattr(text, "model_type", "") or getattr(config, "model_type", "") or "")+ layer_types = list(getattr(text, "layer_types", None) or [])+ hybrid = any(+ t not in ("full_attention", "sliding_attention", "chunked_attention") for t in layer_types+ )+ multimodal = getattr(config, "vision_config", None) is not None+ window = getattr(text, "sliding_window", None)+ windowed = (+ (isinstance(window, int) and window > 0)+ or getattr(text, "use_sliding_window", None) is True+ or any(t in ("sliding_attention", "chunked_attention") for t in layer_types)+ or bool(getattr(text, "attention_chunk_size", None))+ or bool(getattr(text, "attn_logit_softcapping", None))+ )+ return family, hybrid, multimodal, windowed+++def _mode(model):+ if model is None or isinstance(model, str):+ return "lora"+ if getattr(model, "is_loaded_in_4bit", False) or getattr(+ getattr(model, "config", None), "quantization_config", None+ ):+ return "qlora"+ if hasattr(model, "peft_config") and getattr(model, "peft_config", None):+ return "lora"+ try:+ trainable = any(p.requires_grad for n, p in model.named_parameters() if "lora_" not in n)+ except Exception:+ trainable = False+ return "full" if trainable else "lora"+++def _compile_mode(model):+ if model is None or isinstance(model, str):+ return "eager"+ try:+ modules = list(model.modules())+ except Exception:+ return "eager"+ seen = set()+ for m in modules:+ cls = type(m)+ if cls in seen:+ continue+ seen.add(cls)+ if getattr(cls.forward, "_unsloth_block_compiled", False):+ return "block"+ return "eager"+++def _attention(model, packing):+ config = getattr(model, "config", None)+ impl = str(getattr(config, "_attn_implementation", None) or "sdpa")+ if impl.startswith("flex"):+ return "flex"+ if "flash" in impl or "kernels-community" in impl:+ return "flash_varlen" if packing else "flash"+ return "eager" if impl == "eager" else "sdpa"+++def _memory(model, args):+ try:+ import torch.utils.checkpoint as checkpoint+ name = getattr(checkpoint.checkpoint, "__name__", "")+ except Exception:+ name = ""+ gc = bool(getattr(args, "gradient_checkpointing", False)) or bool(+ getattr(model, "is_gradient_checkpointing", False)+ )+ if not gc:+ return "none"+ if name == "unsloth_offloaded_gradient_checkpoint":+ return "unsloth_offload"+ if name == "unsloth_gradient_checkpoint":+ return "unsloth_gc"+ return "gc"+++def _kernels(model):+ if model is None or isinstance(model, str):+ return False+ try:+ for m in model.modules():+ forward = getattr(type(m), "forward", None)+ if getattr(forward, "__module__", "").startswith("unsloth.models.") and type(+ m+ ).__name__.endswith("Attention"):+ return True+ except Exception:+ pass+ return False+++def _moe(model):+ config = getattr(model, "config", None)+ text = getattr(config, "text_config", None) or config+ experts = 0+ for name in ("num_experts", "num_local_experts", "n_routed_experts", "moe_num_experts"):+ value = getattr(text, name, None)+ if isinstance(value, int):+ experts = max(experts, value)+ dense = list(getattr(text, "mlp_only_layers", None) or [])+ layers = getattr(text, "num_hidden_layers", None)+ if experts > 1 and dense and isinstance(layers, int) and sorted(dense) == list(range(layers)):+ experts = 0 # every layer dense+ return experts > 1, bool(getattr(text, "output_router_logits", False)) and experts > 1+++def _aux_loss_on(model, args, trainer_kind) -> bool:+ """As the trainer will run it: TRL's SFTTrainer / DPOTrainer turn the load balancing loss on (and set+ output_router_logits on the config) from the architecture's router_aux_loss_coef unless the trainer argument+ router_aux_loss_coef is 0.0; a plain Trainer only follows output_router_logits."""+ moe, configured = _moe(model)+ if not moe:+ return False+ if configured:+ return True+ if (+ trainer_kind in ("sft", "dpo", "grpo", "other_rl")+ and args is not None+ and hasattr(args, "router_aux_loss_coef")+ ):+ config = getattr(model, "config", None)+ text = getattr(config, "text_config", None) or config+ coef = args.router_aux_loss_coef+ if coef is None:+ coef = getattr(text, "router_aux_loss_coef", 0.0) or 0.0+ return bool(coef) and hasattr(text, "output_router_logits")+ return False+++def _expert_lora(model) -> bool:+ if model is None or isinstance(model, str):+ return False+ for config in (getattr(model, "peft_config", None) or {}).values():+ if getattr(config, "target_parameters", None):+ return True+ try:+ return any("experts" in n and "lora_" in n for n, _ in model.named_parameters())+ except Exception:+ return False+++def _pending_expert_lora(model, peft_config) -> bool:+ """A LoraConfig not attached yet (SFTTrainer(peft_config = ...)) that will put adapters on the experts."""+ if peft_config is None or model is None or isinstance(model, str):+ return False+ if getattr(peft_config, "target_parameters", None):+ return True+ targets = getattr(peft_config, "target_modules", None)+ if not targets:+ return False+ try:+ experts = [(n, m) for n, m in model.named_modules() if "experts" in n.split(".")]+ except Exception:+ return False+ if isinstance(targets, str):+ import re+ if targets == "all-linear":+ import torch+ return any(isinstance(m, torch.nn.Linear) for _, m in experts)+ return any(re.fullmatch(targets, n) for n, _ in experts)+ targets = set(targets)+ return any(n.split(".")[-1] in targets or n in targets for n, _ in experts)+++def _optimizer_name(args, optimizer = None):+ if optimizer is not None:+ inner = getattr(optimizer, "optimizer", optimizer)+ torch_muon = getattr(sys.modules.get("torch.optim"), "Muon", None)+ if torch_muon is not None and isinstance(inner, torch_muon):+ # DTensor math: its Newton-Schulz matmuls run on the whole matrix, so shards step exactly.+ return "torch.optim.muon"+ return type(inner).__name__.lower()+ optim = getattr(args, "optim", "") if args is not None else ""+ return str(getattr(optim, "value", optim) or "").lower()+++def query_from(+ layout = None,+ trainer_cls = None,+ model = None,+ args = None,+ cp = None,+ cp_backend = None,+ optimizer = None,+ peft_config = None,+):+ family, hybrid, multimodal, windowed = _model_traits(model)+ mode = _mode(model)+ if peft_config is not None and mode == "full":+ mode = "lora" # SFTTrainer(peft_config = ...) attaches the adapters inside its __init__+ moe, _ = _moe(model)+ router_aux_loss = _aux_loss_on(model, args, _trainer_kind(trainer_cls))+ packing = bool(getattr(args, "packing", False) or getattr(args, "padding_free", False))+ backend = cp_backend if cp_backend is not None else getattr(layout, "cp_backend", None)+ if packing and backend == "ring" and _trainer_kind(trainer_cls) == "sft":+ # Unsloth's SFTTrainer turns packing off for ring with a notice (trainer.py), inside the __init__ this+ # check runs before: the released behaviour, not a refusal.+ packing = False+ kernels = _kernels(model)+ return Query(+ trainer = _trainer_kind(trainer_cls),+ family = family,+ hybrid = hybrid,+ multimodal = multimodal,+ windowed = windowed,+ mode = mode,+ packing = packing,+ cp_backend = backend,+ torch = _torch_version(),+ sm = _sm(),+ dp = getattr(layout, "dp", 1),+ tp = getattr(layout, "tp", 1),+ pp = getattr(layout, "pp", 1),+ cp = cp if cp is not None else getattr(layout, "cp", 1),+ fsdp2 = bool(getattr(layout, "fsdp2", False)),+ vllm = bool(+ getattr(model, "vllm_engine", None) is not None or getattr(args, "use_vllm", False)+ ),+ pp_schedule = getattr(layout, "schedule", None) if getattr(layout, "pp", 1) > 1 else None,+ attention = _attention(model, packing),+ compile = _compile_mode(model),+ memory = _memory(model, args),+ kernels = kernels,+ # Unsloth's fast models compute the loss fused / chunked unless logits are asked for.+ loss = "fused_ce"+ if kernels and __import__("os").environ.get("UNSLOTH_RETURN_LOGITS", "0") != "1"+ else "standard",+ moe = moe,+ router_aux_loss = router_aux_loss,+ expert_lora = _expert_lora(model) or _pending_expert_lora(model, peft_config),+ moe_backend = __import__("os").environ.get("UNSLOTH_MOE_BACKEND", "").strip().lower(),+ optim = _optimizer_name(args, optimizer),+ )+++def refuse_shard_unaware_optimizer(optimizer, what: str) -> None:+ """At the optimizer hooks of native FSDP2 / tensor parallel (the optimizer exists only then): the+ "fsdp2 / tp x optimizer" rule on the optimizer actually built."""+ name = optimizer.lower() if isinstance(optimizer, str) else _optimizer_name(None, optimizer)+ check(+ Query(+ trainer = "trainer",+ fsdp2 = what == "fsdp2",+ tp = 2 if what == "tp" else 1,+ optim = name,+ torch = _torch_version(),+ ),+ cells = False,+ )+++def check_layout(+ layout,+ trainer_cls = None,+ model = None,+ args = None,+ cp = None,+ cp_backend = None,+ cells = True,+ optimizer = None,+ peft_config = None,+):+ """`check` for a ParallelLayout (and what is known of the trainer / model / arguments). `cells = False`:+ the rules and feature declarations only (the model and trainer are not known yet)."""+ size = cp if cp is not None else getattr(layout, "cp", 1)+ if size > 1 and cp_backend in (None, "auto"):+ from .context_parallel import resolve_cp_backend+ cp_backend = resolve_cp_backend("auto", size, model, tp = getattr(layout, "tp", 1))+ check(+ query_from(layout, trainer_cls, model, args, cp, cp_backend, optimizer, peft_config),+ cells = cells,+ )+++def markdown_table(kind = "rules") -> str:+ """kind: rules (refusals), features (declarations) or cells (supported compositions + evidence)."""+ if kind == "features":+ lines = [+ "| feature | kind | mesh | consumes | uses | produces | hooks | owns alone | scope | module |",+ "|---|---|---|---|---|---|---|---|---|---|",+ ]+ for f in FEATURES:+ cols = [+ ", ".join(x) or "-"+ for x in (f.mesh, f.consumes, f.uses, f.produces, f.hooks, f.exclusive)+ ]+ lines.append(+ f"| {f.name} | {f.kind} | " + " | ".join(cols) + f" | {f.scope} | {f.module} |"+ )+ return "\n".join(lines)+ if kind == "cells":+ lines = [+ "| cell | covers | parity | engagement | compile | note |",+ "|---|---|---|---|---|---|",+ ]+ for c in CELLS:+ covers = "; ".join(f"{k} {'/'.join(map(str, v))}" for k, v in c.match.items())+ lines.append(+ f"| {c.name} | {covers} | {c.parity or 'missing'} | {c.engagement or 'missing'} | "+ f"{c.compile or 'missing'} | {c.note or '-'} |"+ )+ return "\n".join(lines)+ lines = ["| axis | refused cell | why | instead |", "|---|---|---|---|"]+ for rule in RULES:+ lines.append(f"| {rule.axis} | {rule.when} | {rule.reason} | {rule.alternative} |")+ return "\n".join(lines)diff --git a/unsloth/parallel_env.py b/unsloth/parallel_env.pynew file mode 100644index 00000000000..bd254eccb4d--- /dev/null+++ b/unsloth/parallel_env.py@@ -0,0 +1,719 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""One flag (or one line) for every parallel axis of an unmodified training script.++ UNSLOTH_PARALLEL="tp=2,cp=2" torchrun --nproc-per-node 8 train.py # dp 2 (filled in) x cp 2 x tp 2+ UNSLOTH_PARALLEL="dp=2,pp=2,fsdp=1" torchrun --nproc-per-node 4 train.py++ import unsloth+ unsloth.parallelize(tp = 2, cp = 2) # before from_pretrained++Keys: dp, tp, pp, cp (positive integers; dp may be omitted and then fills the world), cp_backend (auto, ulysses,+ring), fsdp (0 / 1: native FSDP2 over the data parallel ranks instead of DDP-style averaging; fsdp=N with N > 1+is dp_shard=N), dp_shard=N / dp_replicate=N (dp with FSDP2 / DDP), pp_schedule (gpipe, 1f1b), pp_microbatches.+transformers' DistributedConfig names are accepted too (tp_size, pp_size, fsdp_size, cp_size); ep / ep_size and+efsdp are reserved and refused until expert parallel lands. The flag is parsed once, at `import unsloth`, and translated to the variables+the existing paths read: UNSLOTH_TP_SIZE, UNSLOTH_PP_SIZE, UNSLOTH_FSDP2, UNSLOTH_PP_SCHEDULE,+UNSLOTH_PP_MICROBATCHES, UNSLOTH_CP_SIZE and UNSLOTH_CP_BACKEND. Those variables keep working on their own; a+variable that disagrees with the flag is refused.++The world splits pp x dp x cp x tp, pp outermost and tp innermost (adjacent ranks share a tensor parallel group,+the fastest link). `root_mesh` builds that DeviceMesh once; tensor parallel takes mesh["tp"], pipeline parallel+mesh["pp"], context parallel mesh["cp"], and data parallel gradients (FSDP2 sharding or DDP-style averaging) the+flattened (dp, cp) mesh, because context parallel peers hold different tokens of the same rows. The data loader+splits over dp only. Size-1 axes are left out of the mesh, so they create no process group.++Imports nothing heavy at module level: the flag is translated before transformers / accelerate read it.+"""++from __future__ import annotations++import math+import os++__all__ = [+ "ParallelSpec",+ "parse_parallel_spec",+ "apply_parallel_env",+ "parallelize",+ "env_cp_size",+ "env_cp_backend",+ "CP_BACKENDS",+ "PP_SCHEDULES",+]++FLAG = "UNSLOTH_PARALLEL"+CP_BACKENDS = ("auto", "ulysses", "ring")+PP_SCHEDULES = ("gpipe", "1f1b")+_SIZE_KEYS = ("dp", "tp", "pp", "cp")+_ALIASES = {+ "microbatches": "pp_microbatches",+ "mb": "pp_microbatches",+ "schedule": "pp_schedule",+ "backend": "cp_backend",+ "fsdp2": "fsdp",+ # transformers' DistributedConfig names (tp_size, fsdp_size, pp_size, ep_size) and the mesh axis names.+ "tp_size": "tp",+ "pp_size": "pp",+ "cp_size": "cp",+ "dp_size": "dp",+ "fsdp_size": "dp_shard",+ "ep_size": "ep",+}+# Kept for compatibility with transformers' naming; refused until Unsloth implements them.+_RESERVED = {+ "ep": "expert parallel (ep) is not supported yet; MoE trains with its experts whole on every rank",+ "efsdp": "expert FSDP (efsdp) is not supported yet",+}+_KEYS = _SIZE_KEYS + (+ "dp_shard",+ "dp_replicate",+ "cp_backend",+ "fsdp",+ "pp_schedule",+ "pp_microbatches",+)+_TRUTHY = ("1", "true", "yes", "on")+_FALSY = ("0", "false", "no", "off")+# The variables each key writes, in the form the legacy readers expect.+_LEGACY = {+ "tp": "UNSLOTH_TP_SIZE",+ "pp": "UNSLOTH_PP_SIZE",+ "cp": "UNSLOTH_CP_SIZE",+ "cp_backend": "UNSLOTH_CP_BACKEND",+ "fsdp": "UNSLOTH_FSDP2",+ "pp_schedule": "UNSLOTH_PP_SCHEDULE",+ "pp_microbatches": "UNSLOTH_PP_MICROBATCHES",+}+++class ParallelSpec(dict):+ """The parsed flag: {key: value} for the keys given (sizes as int, fsdp as bool)."""++ def sizes(self):+ return {k: self.get(k, 1) for k in ("pp", "tp", "cp")}++ def describe(self):+ return ",".join(f"{k}={_format(v)}" for k, v in self.items())+++def _format(value):+ if isinstance(value, bool):+ return "1" if value else "0"+ return str(value)+++def _positive(key, raw, source):+ try:+ value = int(str(raw).strip())+ except ValueError:+ raise ValueError(f"Unsloth: {source}: {key}={raw!r} must be a positive integer.") from None+ if value < 1:+ raise ValueError(f"Unsloth: {source}: {key}={value} must be >= 1.")+ return value+++def parse_parallel_spec(raw, source = FLAG):+ """'dp=2,tp=2,cp=2,cp_backend=ulysses' -> ParallelSpec; ValueError naming the bad part otherwise."""+ spec = ParallelSpec()+ if raw is None or not str(raw).strip():+ return spec+ for part in str(raw).replace(";", ",").split(","):+ part = part.strip()+ if not part:+ continue+ if "=" not in part:+ raise ValueError(+ f'Unsloth: {source}={raw!r}: {part!r} is not key=value (e.g. {FLAG}="dp=2,tp=2,cp=2").'+ )+ key, value = (x.strip() for x in part.split("=", 1))+ key = _ALIASES.get(key.lower(), key.lower())+ if key in _RESERVED:+ raise ValueError(f"Unsloth: {source}={raw!r}: {_RESERVED[key]}; drop {key}=.")+ if key == "fsdp" and value.strip().isdigit() and int(value) > 1:+ key = "dp_shard" # fsdp=N: N FSDP2 shards (transformers' fsdp_size); fsdp=0 / 1 stays the switch+ if key not in _KEYS:+ raise ValueError(+ f"Unsloth: {source}={raw!r}: unknown key {key!r}; the keys are {', '.join(_KEYS)}."+ )+ if key in spec:+ raise ValueError(f"Unsloth: {source}={raw!r} gives {key} twice.")+ if key in _SIZE_KEYS or key in ("pp_microbatches", "dp_shard", "dp_replicate"):+ spec[key] = _positive(key, value, source)+ elif key == "fsdp":+ low = value.lower()+ if low not in _TRUTHY + _FALSY:+ raise ValueError(f"Unsloth: {source}={raw!r}: fsdp={value!r} must be 0 or 1.")+ spec[key] = low in _TRUTHY+ elif key == "cp_backend":+ low = value.lower()+ if low not in CP_BACKENDS:+ raise ValueError(+ f"Unsloth: {source}={raw!r}: cp_backend={value!r} must be one of {', '.join(CP_BACKENDS)}."+ )+ spec[key] = low+ else: # pp_schedule+ low = value.lower().replace("-", "").replace("_", "")+ if low not in PP_SCHEDULES:+ hint = (+ " (interleaved virtual stages are not supported yet)"+ if low.startswith("interleav")+ else ""+ )+ raise ValueError(+ f"Unsloth: {source}={raw!r}: pp_schedule={value!r} must be one of "+ f"{', '.join(PP_SCHEDULES)}{hint}."+ )+ spec[key] = low+ shard, replicate = spec.pop("dp_shard", None), spec.pop("dp_replicate", None)+ if shard is not None and replicate is not None and shard > 1 and replicate > 1:+ raise ValueError(+ f"Unsloth: {source}={raw!r}: dp_shard x dp_replicate (HSDP) is not supported by {FLAG} yet; give one."+ )+ if shard is not None or replicate is not None:+ # Together: a size-1 axis is inactive (dp_shard=1,dp_replicate=2 is plain DDP over 2 ranks).+ size = (shard or 1) * (replicate or 1)+ fsdp = True if (shard or 1) > 1 else False if (replicate or 1) > 1 else None+ if "dp" in spec and spec["dp"] != size:+ raise ValueError(+ f"Unsloth: {source}={raw!r}: dp={spec['dp']} disagrees with the dp_shard / dp_replicate size."+ )+ if fsdp is not None and "fsdp" in spec and spec["fsdp"] != fsdp:+ raise ValueError(+ f"Unsloth: {source}={raw!r}: fsdp={_format(spec['fsdp'])} disagrees with the dp_shard / dp_replicate key."+ )+ spec["dp"] = size+ if fsdp is not None:+ spec["fsdp"] = fsdp+ # cp_backend at cp=1 and pp_schedule / pp_microbatches at pp=1 are accepted unused (launchers write every axis).+ return spec+++def _world(environ):+ raw = environ.get("WORLD_SIZE")+ if raw is None or not str(raw).strip():+ return None+ try:+ return int(raw)+ except ValueError:+ return None+++def _legacy_value(key, environ):+ name = _LEGACY[key]+ raw = environ.get(name)+ if raw is None or not str(raw).strip():+ return None+ raw = str(raw).strip()+ if key == "fsdp":+ low = raw.lower()+ return True if (low in _TRUTHY or low == "native") else (False if low in _FALSY else raw)+ if key == "cp_backend":+ return raw.lower()+ if key == "pp_schedule":+ return raw.lower().replace("-", "").replace("_", "")+ try:+ return int(raw)+ except ValueError:+ return raw+++def translate(spec, environ = None):+ """{legacy variable: value} for a parsed spec, after checking the world size and the legacy variables+ already set (ValueError on a conflict). Pure: the environment is only read."""+ environ = os.environ if environ is None else environ+ world = _world(environ)+ sizes = spec.sizes()+ model_ranks = math.prod(sizes.values())+ given = spec.describe()+ if "dp" in spec:+ need = spec["dp"] * model_ranks+ if world is not None and world != need:+ raise ValueError(+ f'Unsloth: {FLAG}="{given}" needs dp x pp x cp x tp = {need} ranks, but WORLD_SIZE={world}; '+ f"launch with torchrun --nproc-per-node {need}, or drop dp= to let it fill the world."+ )+ elif world is not None and world % model_ranks:+ raise ValueError(+ f'Unsloth: {FLAG}="{given}": pp x cp x tp = {model_ranks} must divide the number of ranks '+ f"(WORLD_SIZE={world}); launch with torchrun --nproc-per-node {model_ranks} (or a multiple of it)."+ )+ out = {}+ wanted = {+ "tp": sizes["tp"],+ "pp": sizes["pp"],+ "cp": sizes["cp"],+ }+ for key in ("cp_backend", "fsdp", "pp_schedule", "pp_microbatches"):+ if key in spec:+ wanted[key] = spec[key]+ for key, value in wanted.items():+ current = _legacy_value(key, environ)+ if key in _SIZE_KEYS and current is None and value == 1:+ continue+ if (+ current is not None+ and current != value+ and not (key in _SIZE_KEYS and current == 1 and value == 1)+ ):+ raise ValueError(+ f'Unsloth: {FLAG}="{given}" sets {key}={_format(value)}, but {_LEGACY[key]}='+ f"{environ.get(_LEGACY[key])} asks for something else. Use one of the two forms: unset "+ f"{_LEGACY[key]}, or drop {FLAG}."+ )+ out[_LEGACY[key]] = _format(value)+ return out+++def apply_parallel_env(environ = None):+ """`import unsloth` (and `parallelize`): translate UNSLOTH_PARALLEL into the legacy variables. Returns the+ spec, or None when the flag is not set. Idempotent: a second call sees its own values and no conflict."""+ environ = os.environ if environ is None else environ+ raw = environ.get(FLAG)+ if raw is None or not str(raw).strip():+ return None+ spec = parse_parallel_spec(raw)+ environ.update(translate(spec, environ))+ return spec+++def env_cp_size(environ = None):+ """UNSLOTH_CP_SIZE (1 when unset); ValueError on a non-positive / non-integer value."""+ environ = os.environ if environ is None else environ+ raw = environ.get("UNSLOTH_CP_SIZE")+ if raw is None or not str(raw).strip():+ return 1+ return _positive("UNSLOTH_CP_SIZE", raw, "UNSLOTH_CP_SIZE")+++def env_cp_backend(environ = None):+ """UNSLOTH_CP_BACKEND (None when unset); ValueError outside auto / ulysses / ring."""+ environ = os.environ if environ is None else environ+ raw = environ.get("UNSLOTH_CP_BACKEND")+ if raw is None or not str(raw).strip():+ return None+ low = str(raw).strip().lower()+ if low not in CP_BACKENDS:+ raise ValueError(+ f"Unsloth: UNSLOTH_CP_BACKEND={raw!r} must be one of {', '.join(CP_BACKENDS)}."+ )+ return low+++def parallelize(+ dp = None,+ tp = 1,+ pp = 1,+ cp = 1,+ cp_backend = None,+ fsdp = None,+ pp_schedule = None,+ pp_microbatches = None,+):+ """`UNSLOTH_PARALLEL` from Python: call after `import unsloth` and before `from_pretrained`, on every rank.++ import unsloth+ unsloth.parallelize(tp = 2, cp = 2)++ Returns the resolved {legacy variable: value}. Refused once a model has been loaded under another layout."""+ parts = []+ if dp is not None:+ parts.append(f"dp={dp}")+ for key, value in (("tp", tp), ("pp", pp), ("cp", cp)):+ if value is None:+ continue+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise ValueError(+ f"Unsloth: parallelize({key} = {value!r}): must be a positive integer."+ )+ if value > 1:+ parts.append(f"{key}={value}")+ if dp is not None and (isinstance(dp, bool) or not isinstance(dp, int) or dp < 1):+ raise ValueError(f"Unsloth: parallelize(dp = {dp!r}): must be a positive integer.")+ if cp_backend is not None:+ parts.append(f"cp_backend={cp_backend}")+ if fsdp is not None:+ parts.append(f"fsdp={1 if fsdp else 0}")+ if pp_schedule is not None:+ parts.append(f"pp_schedule={pp_schedule}")+ if pp_microbatches is not None:+ parts.append(f"pp_microbatches={pp_microbatches}")+ raw = ",".join(parts)+ spec = parse_parallel_spec(raw, source = "unsloth.parallelize")+ current = os.environ.get(FLAG)+ ours = bool(current) and current == _SET_BY_PARALLELIZE[0]+ from_env = bool(current and current.strip()) and not ours+ if from_env and parse_parallel_spec(current) != spec:+ raise ValueError(+ f'Unsloth: unsloth.parallelize({raw}) disagrees with {FLAG}="{current}" from the environment; '+ "use one of the two."+ )+ # Our own earlier call: undo only what it wrote, so inherited variables it left alone stay.+ prior = dict(_SET_BY_PARALLELIZE[1]) if ours else {}+ environ = dict(os.environ)+ for name, value in prior.items():+ if value is None:+ environ.pop(name, None)+ else:+ environ[name] = value+ resolved = translate(spec, environ)+ _refuse_after_layout_read(resolved)+ for name, value in prior.items():+ if value is None:+ os.environ.pop(name, None)+ else:+ os.environ[name] = value+ _SET_BY_PARALLELIZE[1] = {name: os.environ.get(name) for name in resolved}+ os.environ.update(resolved)+ os.environ[FLAG] = raw+ _SET_BY_PARALLELIZE[0] = raw+ _reinstall_after_import()+ return resolved+++# The last call's flag value, and what each variable it wrote held before it.+_SET_BY_PARALLELIZE = [None, {}]+++def _refuse_after_layout_read(resolved):+ """A layout already read (a model loaded) cannot change under it."""+ import sys++ tp_env = sys.modules.get("unsloth.models.tp_env")+ if tp_env is None:+ return+ layout = getattr(tp_env, "_LAYOUT", None)+ if layout is getattr(tp_env, "_UNSET", None):+ return+ before = (1, 1) if layout is None else (layout.pp, layout.tp)+ after = (int(resolved.get("UNSLOTH_PP_SIZE", 1)), int(resolved.get("UNSLOTH_TP_SIZE", 1)))+ if before != after:+ raise RuntimeError(+ "Unsloth: unsloth.parallelize(...) must run before from_pretrained: a model was already loaded "+ f"with pp {before[0]} x tp {before[1]}."+ )+ tp_env._reset_env_layout()+++def _reinstall_after_import():+ """What `import unsloth` installs from these variables (it already ran when parallelize is called)."""+ import sys++ if "unsloth" not in sys.modules:+ return+ from .fsdp2_launch import apply_unsloth_fsdp2_launch_env, install_native_fsdp2_trainer_init++ apply_unsloth_fsdp2_launch_env()+ install_native_fsdp2_trainer_init()+ from .models.tp_env import _reset_env_layout, install_tensor_parallel_env_trainer_init++ _reset_env_layout()+ install_tensor_parallel_env_trainer_init()+++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 ParallelLayout:+ """world = pp x dp x cp x tp; `mesh()` builds (once) the root device mesh, initializing the process group+ if needed. (models/tp_env.TPEnvLayout is this class.)"""++ def __init__(+ self,+ tp,+ dp,+ world,+ fsdp2,+ pp = 1,+ microbatches = None,+ schedule = "gpipe",+ cp = 1,+ cp_backend = None,+ ):+ self.tp, self.dp, self.world, self.fsdp2 = tp, dp, world, fsdp2+ self.pp, self.microbatches, self.schedule = pp, microbatches, schedule+ self.cp, self.cp_backend = cp, cp_backend+ self._mesh = None+ self._grad_mesh = None++ def __repr__(self):+ parts = [f"pp {self.pp}"] if self.pp > 1 else []+ if self.dp > 1:+ parts.append(f"dp {self.dp} ({'native FSDP2' if self.fsdp2 else 'DDP'})")+ if self.cp > 1:+ parts.append(f"cp {self.cp}")+ if self.tp > 1:+ parts.append(f"tp {self.tp}")+ return " x ".join(parts)++ @property+ def env_vars(self):+ """The environment variables that asked for this layout, e.g. "UNSLOTH_PP_SIZE=2 UNSLOTH_TP_SIZE=2"."""+ out = [f"UNSLOTH_PP_SIZE={self.pp}"] if self.pp > 1 else []+ if self.tp > 1:+ out.append(f"UNSLOTH_TP_SIZE={self.tp}")+ if self.cp > 1:+ out.append(f"UNSLOTH_CP_SIZE={self.cp}")+ return " ".join(out)++ @property+ def sharded_loading(self):+ if self.pp > 1:+ return False # the pipeline split comes first, on whole layers (models/pp_env.py)+ return os.environ.get("UNSLOTH_TP_SHARDED_LOAD", "1").strip().lower() not in _FALSY++ @property+ def dims(self):+ """[(name, size)] of the root mesh, pp outermost and tp innermost; size-1 axes left out."""+ dp_name = "dp_shard" if self.fsdp2 else "dp_replicate"+ dims = [("pp", self.pp), (dp_name, self.dp), ("cp", self.cp), ("tp", self.tp)]+ return [(name, size) for name, size in dims if size > 1]++ def mesh(self):+ if self._mesh is not None:+ return self._mesh+ import torch+ 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: {self.env_vars} read WORLD_SIZE={self.world}, but the process group has "+ f"{dist.get_world_size()} ranks."+ )+ device = "cuda" if cuda else "cpu"+ dims = self.dims or [("tp", self.tp)]+ mesh = init_device_mesh(+ device, tuple(size for _, size in dims), mesh_dim_names = tuple(name for name, _ in dims)+ )+ if len(dims) > 1:+ from .models.pp_native import check_mesh_composition+ check_mesh_composition(+ {name: mesh[name] for name, _ in dims}, f"{self.env_vars} ({self})"+ )+ self._mesh = mesh+ if dist.get_rank() == 0:+ what = "pipeline" if self.pp > 1 else "tensor"+ if self.pp > 1 and self.tp > 1:+ what = "pipeline x tensor"+ print(f"Unsloth: {what} parallel from {self.env_vars}: {self} over {self.world} ranks.")+ return mesh++ def _dim(self, name):+ return self.mesh()[name] if any(n == name for n, _ in self.dims) else None++ @property+ def tp_mesh(self):+ return self._dim("tp")++ @property+ def pp_mesh(self):+ return self._dim("pp")++ @property+ def cp_mesh(self):+ return self._dim("cp")++ @property+ def data_mesh(self):+ """The data parallel ranks: they read different rows (cp / tp / pp peers read the same ones)."""+ return self._dim("dp_shard" if self.fsdp2 else "dp_replicate")++ @property+ def grad_size(self):+ return self.dp * self.cp++ @property+ def dp_mesh(self):+ """The mesh data parallel gradients reduce over (FSDP2 sharding / DDP-style averaging): dp, and cp+ flattened in when context parallel is on (cp peers hold different tokens of the same rows)."""+ if self.cp == 1:+ return self.data_mesh+ if self.dp == 1:+ return self.cp_mesh+ if self._grad_mesh is None:+ dp_name = "dp_shard" if self.fsdp2 else "dp_replicate"+ self._grad_mesh = self.mesh()[(dp_name, "cp")]._flatten(f"{dp_name}_cp")+ return self._grad_mesh+++def read_layout():+ """The layout UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE (and UNSLOTH_CP_SIZE beside them) ask for, or None."""+ pp = _int_env("UNSLOTH_PP_SIZE") or 1+ tp = _int_env("UNSLOTH_TP_SIZE") or 1+ if pp == 1 and tp == 1:+ return None # context parallel alone is the CP manager's (context_parallel.py)+ cp = env_cp_size()+ cp_backend = env_cp_backend()+ try:+ world = int(os.environ.get("WORLD_SIZE", "1"))+ except ValueError:+ world = 1+ sizes = (("UNSLOTH_PP_SIZE", pp), ("UNSLOTH_CP_SIZE", cp), ("UNSLOTH_TP_SIZE", tp))+ names = " x ".join(name for name, size in sizes if size > 1)+ given = " ".join(f"{name}={size}" for name, size in sizes if size > 1)+ if world % (pp * tp * cp):+ what = (+ "data parallel x tensor parallel"+ if pp == 1+ else "data parallel x pipeline parallel" + (" x tensor parallel" if tp > 1 else "")+ )+ raise ValueError(+ f"Unsloth: {given}: {names} = {pp * tp * cp} must divide the number of ranks (WORLD_SIZE={world}); "+ f"launch with torchrun --nproc-per-node {pp * tp * cp} (or a multiple of {pp * tp * cp} for {what}), or "+ f"unset {' / '.join(name for name in names.split(' x '))}."+ )+ microbatches, schedule = None, "gpipe"+ if pp > 1:+ microbatches = _int_env("UNSLOTH_PP_MICROBATCHES")+ schedule = (+ (os.environ.get("UNSLOTH_PP_SCHEDULE") or "gpipe").strip().lower().replace("-", "")+ )+ schedule = schedule.replace("_", "")+ if schedule not in PP_SCHEDULES:+ raise ValueError(+ f"Unsloth: UNSLOTH_PP_SCHEDULE={os.environ.get('UNSLOTH_PP_SCHEDULE')!r} must be one of "+ f"{PP_SCHEDULES}."+ )+ if schedule == "1f1b" and microbatches is not None and microbatches < pp:+ raise ValueError(+ f"Unsloth: UNSLOTH_PP_SCHEDULE=1f1b needs UNSLOTH_PP_MICROBATCHES >= UNSLOTH_PP_SIZE "+ f"({microbatches} < {pp})."+ )+ from .models.pp_native import _check_torch_pipelining++ try:+ _check_torch_pipelining()+ except RuntimeError as exc:+ raise RuntimeError(+ f"{exc} (UNSLOTH_PP_SIZE={pp}: unset it to run without pipeline parallel.)"+ ) from None+ 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"):+ what = "pipeline" if pp > 1 else "tensor"+ raise ValueError(+ f"Unsloth: {given} composes with native FSDP2 only (UNSLOTH_FSDP2=1); "+ f"UNSLOTH_FSDP2_BACKEND={backend} would hand the {what} parallel model to accelerate's FSDP. "+ "Unset UNSLOTH_FSDP2_BACKEND."+ )+ layout = ParallelLayout(+ tp,+ world // (pp * tp * cp),+ world,+ fsdp2,+ pp,+ microbatches,+ schedule,+ cp = cp,+ cp_backend = cp_backend,+ )+ from .parallel_capabilities import check_layout++ # Layout-only rules before any model loads (ring x tp is refused here, before the tp split).+ check_layout(layout, cells = False, cp_backend = cp_backend)+ return layout+++def describe_trainer_layout(+ trainer,+ layout = None,+ cp_manager = None,+):+ """One line: the resolved mesh (pp, dp_replicate, dp_shard, cp, tp), schedule and micro-batches, effective+ batch, context parallel backend, attention backend and gradient checkpointing mode."""+ world = _dist_value("get_world_size", 1)+ cp = cp_manager.size if cp_manager is not None else getattr(layout, "cp", 1)+ pp = getattr(layout, "pp", 1)+ tp = getattr(layout, "tp", 1)+ dp = getattr(layout, "dp", None) or max(world // max(pp * tp * cp, 1), 1)+ fsdp2 = getattr(layout, "fsdp2", None)+ if fsdp2 is None:+ from .fsdp2_launch import unsloth_fsdp2_native_requested+ try:+ fsdp2 = bool(unsloth_fsdp2_native_requested())+ except Exception:+ fsdp2 = False+ mesh = {+ "pp": pp,+ "dp_replicate": 1 if fsdp2 else dp,+ "dp_shard": dp if fsdp2 else 1,+ "cp": cp,+ "tp": tp,+ }+ parts = [f"mesh ({', '.join(f'{k} {v}' for k, v in mesh.items())}) over {world} ranks"]+ if pp > 1:+ mb = getattr(layout, "microbatches", None)+ parts.append(+ f"pp schedule {getattr(layout, 'schedule', 'gpipe')}, {mb or 'auto'} micro-batches"+ )+ args = getattr(trainer, "args", None)+ if args is not None:+ bs = getattr(args, "per_device_train_batch_size", 1)+ ga = getattr(args, "gradient_accumulation_steps", 1)+ parts.append(+ f"effective batch {bs} x {ga} accumulation x {dp} data parallel = {bs * ga * dp} rows"+ )+ if cp > 1:+ backend = (+ getattr(cp_manager, "backend", None) or getattr(layout, "cp_backend", None) or "auto"+ )+ parts.append(f"cp backend {backend}")+ if fsdp2 or getattr(cp_manager, "fsdp2_native", False):+ parts.append("FSDP2 shards and reduces over dp_shard x cp")+ model = getattr(trainer, "model", None)+ config = getattr(model, "config", None)+ attention = getattr(config, "_attn_implementation", None)+ if attention:+ parts.append(f"attention {attention}")+ gc = getattr(args, "gradient_checkpointing", None) if args is not None else None+ gc_mode = getattr(model, "_unsloth_gradient_checkpointing", None) or (+ "on" if gc else "off" if gc is not None else "unknown"+ )+ parts.append(f"gradient checkpointing {gc_mode}")+ return "; ".join(parts)+++def announce(+ trainer,+ layout = None,+ cp_manager = None,+):+ """Rank 0 prints the resolved layout once per trainer."""+ if getattr(trainer, "__dict__", {}).get("_unsloth_parallel_announced"):+ return None+ line = "Unsloth: parallel layout: " + describe_trainer_layout(trainer, layout, cp_manager) + "."+ try:+ trainer.__dict__["_unsloth_parallel_announced"] = line+ except Exception:+ pass+ if _dist_value("get_rank", 0) == 0:+ print(line)+ return line+++def _dist_value(name, default):+ try:+ import torch.distributed as dist+ return getattr(dist, name)() if dist.is_available() and dist.is_initialized() else default+ except Exception:+ return defaultdiff --git a/unsloth/save.py b/unsloth/save.pyindex a895dee57f5..6c049403775 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -70,6 +70,7 @@ from .models.loader_utils import (_tokenizer_wants_local_only,)from .models._utils import (+ _is_unsloth_pipeline_parallel,_is_unsloth_tensor_parallel,_refuse_model_parallel_export,_convert_torchao_model,@@ -1364,6 +1365,13 @@ def _model_parallel_refuses_save(method):@functools.wraps(fn)def wrapper(*args, **kwargs):model = args[0] if args else kwargs.get("model", kwargs.get("self"))+ if model is not None and _is_unsloth_pipeline_parallel(model):+ # UNSLOTH_PP_SIZE: the whole model back on every rank, rank 0 exports (refused otherwise).+ _refuse_model_parallel_export(model, method)+ from .models.pp_env import pp_collective++ _refuse_tp_in_place_merge(fn, method, args, kwargs)+ return pp_collective(model, method, lambda: fn(*args, **kwargs))if model is not None and _is_unsloth_tensor_parallel(model):from .models.tp_replica import collective_applies, tp_collectiveif collective_applies(model):@@ -6914,7 +6922,18 @@ def _tp_collective_save(method):def decorate(fn):@functools.wraps(fn)def wrapper(self, *args, **kwargs):- if isinstance(self, torch.nn.Module) and _is_unsloth_tensor_parallel(self):+ if isinstance(self, torch.nn.Module) and _is_unsloth_pipeline_parallel(self):+ from .models import tp_replica+ arguments = _fsdp2_save_arguments(fn, self, args, kwargs)+ if not tp_replica._ACTIVE and arguments.get("state_dict") is None:+ from .models.pp_env import pp_collective, pp_save_adapter++ if method == "save_pretrained" and isinstance(self, PeftModel):+ # The LoRA weights of every stage, the 1-GPU adapter written by rank 0.+ return pp_save_adapter(self, args, kwargs)+ _refuse_model_parallel_export(self, method)+ return pp_collective(self, method, lambda: fn(self, *args, **kwargs))+ elif isinstance(self, torch.nn.Module) and _is_unsloth_tensor_parallel(self):from .models.tp_replica import collective_applies, tp_collectivearguments = _fsdp2_save_arguments(fn, self, args, kwargs)if arguments.get("state_dict") is None and collective_applies(self):diff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex da7e41edaa7..dd5af1f4f1e 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -212,6 +212,23 @@ def _should_pack(config) -> bool:return not getattr(config, "_unsloth_disable_auto_packing", False)+def _pipeline_parallel_env_requested() -> bool:+ try:+ return int(os.environ.get("UNSLOTH_PP_SIZE", "1").strip() or 1) > 1+ except ValueError:+ return False+++def _cp_x_tp_env_requested() -> bool:+ """UNSLOTH_CP_SIZE and UNSLOTH_TP_SIZE above 1 (UNSLOTH_PARALLEL writes both): packed rows are refused there."""+ try:+ cp = int(os.environ.get("UNSLOTH_CP_SIZE", "1").strip() or 1)+ tp = int(os.environ.get("UNSLOTH_TP_SIZE", "1").strip() or 1)+ except ValueError:+ return False+ return cp > 1 and tp > 1++def _should_auto_padding_free(config) -> bool:if config is None or _AUTO_PADDING_FREE_ENV_DISABLED or getattr(config, "packing", False):return False@@ -971,7 +988,7 @@ class UnslothTrainingArguments(TrainingArguments):# Not fields of the pristine SFTConfig captured at import.context_parallel = {"context_parallel_size": kwargs.pop("context_parallel_size", 1),- "context_parallel_backend": kwargs.pop("context_parallel_backend", "ring"),+ "context_parallel_backend": kwargs.pop("context_parallel_backend", "auto"),"context_parallel_rotate_method": kwargs.pop("context_parallel_rotate_method", "allgather"),@@ -1907,17 +1924,38 @@ def _patch_sft_trainer_auto_packing(trl_module):# several classes, so a "yes" from the resolved one is not proof about the# instance. A correct "no" has already turned both flags off, which is the# condition the post-init check skips on, so leaving it armed is free.- is_ring_context_parallel = (getattr(config_arg, "context_parallel_size", 1) or 1) > 1 and (- getattr(config_arg, "context_parallel_backend", None) or "ring"- ) == "ring"+ cp_size = getattr(config_arg, "context_parallel_size", 1) or 1+ is_ring_context_parallel = False+ if isinstance(cp_size, int) and cp_size > 1:+ from .context_parallel import resolve_cp_backend++ # 'auto' (the default) is Ulysses unless the heads cannot be split, so packing stays on.+ cp_backend = resolve_cp_backend(+ getattr(config_arg, "context_parallel_backend", None),+ cp_size,+ model if not isinstance(model, str) else None,+ )+ # Ring cannot keep packed rows apart: packing goes off below, as before 'auto' existed.+ is_ring_context_parallel = cp_backend == "ring"boundary_blocker = packing_boundary_blocker(model, model_types)# Read before __init__: the compiled trainer ends it with model.for_inference(), which sets the flag.eval_logits_wanted = os.environ.get("UNSLOTH_RETURN_LOGITS", "0") == "1" or _wants_eval_logits(original_init, args, kwargs)+ # UNSLOTH_PP_SIZE: packed rows are not carried between pipeline stages yet (models/pp_env.py).+ is_pipeline_parallel_env = _pipeline_parallel_env_requested()+ # cp x tp refuses packed rows: never turn them on automatically there. An explicit packing /+ # padding_free = True stays, so the capability check refuses it with the alternative.+ auto_off_cp_tp = (+ _cp_x_tp_env_requested()+ and not getattr(config_arg, "packing", False)+ and getattr(config_arg, "padding_free", None) is not True+ )blocked = ((data_collator is not None)or is_ring_context_parallel+ or is_pipeline_parallel_env+ or auto_off_cp_tpor (is_processor and not processor_text_only)or is_auto_processor_vlmor is_vision_dataset@@ -1948,9 +1986,9 @@ def _patch_sft_trainer_auto_packing(trl_module):if hasattr(config_arg, "padding_free"):setattr(config_arg, "padding_free", False)# TRL resolves eval_packing on its own; packed eval batches would hit ring attention's varlen refusal.- if (is_ring_context_parallel or boundary_blocker is not None) and getattr(- config_arg, "eval_packing", None- ):+ if (+ is_ring_context_parallel or is_pipeline_parallel_env or boundary_blocker is not None+ ) and getattr(config_arg, "eval_packing", None):setattr(config_arg, "eval_packing", False)if blocked and requested_pack:@@ -1968,7 +2006,14 @@ def _patch_sft_trainer_auto_packing(trl_module):elif is_unsupported_model:reason = f"unsupported model type(s): {', '.join(model_types)}"elif is_ring_context_parallel:- reason = "ring context parallelism"+ reason = (+ "ring context parallelism ('auto' chose ring: the attention heads cannot be split over "+ f"{cp_size} ranks)"+ if getattr(config_arg, "_unsloth_cp_backend_auto", False)+ else "ring context parallelism; context_parallel_backend = 'ulysses' keeps it"+ )+ elif is_pipeline_parallel_env:+ reason = "pipeline parallel (UNSLOTH_PP_SIZE)"elif boundary_blocker is not None:reason = f"{boundary_blocker} mixes tokens across packed documents"elif forward_rejects_packing:diff --git a/unsloth/utils/compile_counters.py b/unsloth/utils/compile_counters.pynew file mode 100644index 00000000000..3912334e1e8--- /dev/null+++ b/unsloth/utils/compile_counters.py@@ -0,0 +1,68 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""torch.compile evidence for the parallel capability registry: graph breaks, recompiles and graphs compiled.++ before = compile_counters.snapshot()+ trainer.train()+ used = compile_counters.since(before) # {"graph_breaks": 0, "recompiles": 0, "unique_graphs": 8, ...}++A composed layout (tp, cp, pp, FSDP2) is compile-clean when `used` has no more graph breaks and recompiles than+the same script in one process (`not_above`)."""++from __future__ import annotations++from collections import Counter++__all__ = ["snapshot", "since", "not_above", "COUNTED"]++COUNTED = ("graph_breaks", "recompiles", "unique_graphs", "frames")+++def snapshot() -> dict:+ try:+ from torch._dynamo import utils+ except Exception:+ return {k: 0 for k in COUNTED} | {"graph_break_reasons": {}}+ counters = utils.counters+ reasons = {str(k).split("\n", 1)[0]: int(v) for k, v in counters.get("graph_break", {}).items()}+ failures = getattr(utils, "guard_failures", {}) or {}+ return {+ "graph_breaks": sum(reasons.values()),+ "recompiles": sum(len(v) for v in failures.values()),+ "unique_graphs": int(counters.get("stats", {}).get("unique_graphs", 0)),+ "frames": int(counters.get("frames", {}).get("ok", 0)),+ "graph_break_reasons": reasons,+ "recompile_reasons": [+ f"{getattr(code, 'co_name', code)}: {str(r).splitlines()[0] if str(r) else ''}"+ for code, v in failures.items()+ for r in v+ ],+ }+++def since(before: dict) -> dict:+ now = snapshot()+ out = {k: now[k] - before.get(k, 0) for k in COUNTED}+ old = before.get("graph_break_reasons", {})+ out["graph_break_reasons"] = {+ k: v - old.get(k, 0) for k, v in now["graph_break_reasons"].items() if v - old.get(k, 0)+ }+ seen = Counter(before.get("recompile_reasons", []))+ new = []+ for reason in now["recompile_reasons"]:+ if seen[reason]:+ seen[reason] -= 1+ else:+ new.append(reason)+ out["recompile_reasons"] = new[:50]+ return out+++def not_above(composed: dict, single: dict) -> list:+ """The counters where the composed run exceeds the one-process run (empty: compile-clean)."""+ return [+ f"{k} {composed.get(k, 0)} > {single.get(k, 0)}"+ for k in ("graph_breaks", "recompiles")+ if composed.get(k, 0) > single.get(k, 0)+ ]