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
Pipeline parallel: per-stage sharded loading (load models larger than one GPU) (#15656)
Daniel Hanbcd329b940af
diff --git a/tests/test_pp_load_gloo.py b/tests/test_pp_load_gloo.pynew file mode 100644index 00000000000..49e5607f5c4--- /dev/null+++ b/tests/test_pp_load_gloo.py@@ -0,0 +1,524 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""pipeline_sharded_loading on a gloo CPU world (2 / 4 ranks): each rank reads only its stages' layers (and the+embedding / head where their stage lives), and the split model trains bitwise like a full load split by+apply_pipeline_parallel; refusals before anything is cut."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None or getattr(+ multiprocessing.current_process(), "_inheriting", False+):+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import importlib.util # noqa: E402+import 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_pp_native_gloo import ( # noqa: E402+ GEMMA3,+ LLAMA,+ QWEN3,+ REPO,+ _free_port,+ _torch_pipelining_error,+ batch,+ build,+ ppn,+)+++def _pp_load():+ full = "unsloth.models.pp_load"+ if full in sys.modules:+ return sys.modules[full]+ spec = importlib.util.spec_from_file_location(+ full, os.path.join(REPO, "unsloth", "models", "pp_load.py")+ )+ module = importlib.util.module_from_spec(spec)+ sys.modules[full] = module+ spec.loader.exec_module(module)+ return module+++def _lora_init():+ full = "unsloth.models.lora_init"+ if full in sys.modules:+ return sys.modules[full]+ spec = importlib.util.spec_from_file_location(+ full, os.path.join(REPO, "unsloth", "models", "lora_init.py")+ )+ module = importlib.util.module_from_spec(spec)+ sys.modules[full] = module+ spec.loader.exec_module(module)+ return module+++ARCHS = {"llama": LLAMA, "qwen3": QWEN3, "gemma3": GEMMA3}+N_LAYERS = 8+++def _save_checkpoint(+ arch,+ directory,+ tie = None,+):+ model = build(ARCHS[arch], layers = N_LAYERS, lora = False, tie = tie)+ model.generation_config.pad_token_id = None # tiny repos ship -1, which save_pretrained rejects+ model.save_pretrained(directory, max_shard_size = "1MB", safe_serialization = True)+ return directory+++def _peft(model, **extra):+ import contextlib++ from peft import LoraConfig, get_peft_model++ torch.manual_seed(1)+ kw = dict(+ r = 4, lora_alpha = 8, target_modules = "all-linear", init_lora_weights = False, lora_dropout = 0.0+ )+ fast = extra.pop(+ "_fast", False+ ) # Unsloth's fast PiSSA / MiCA swap, as FastLanguageModel.get_peft_model+ kw.update(extra)+ with _lora_init().fast_lora_init() if fast else contextlib.nullcontext():+ return get_peft_model(model, LoraConfig(**kw)).train()+++def _placeholders(model):+ ppl = _pp_load()+ return [p for p in model.parameters() if ppl.is_placeholder(p)]+++def _zero_stride(p):+ return all(s == 0 for s in p.stride()) and p.untyped_storage().nbytes() <= p.element_size()+++def _load(ckpt):+ from transformers import AutoModelForCausalLM++ model = AutoModelForCausalLM.from_pretrained(+ ckpt, torch_dtype = torch.float32, attn_implementation = "eager"+ )+ for key in ("attention_dropout", "hidden_dropout", "dropout"):+ if isinstance(getattr(model.config, key, None), float):+ setattr(model.config, key, 0.0)+ return model+++def _storage_bytes(model):+ seen, total = set(), 0+ for p in model.parameters():+ storage = p.untyped_storage()+ if storage.data_ptr() in seen:+ continue+ seen.add(storage.data_ptr())+ total += storage.nbytes()+ return total+++def _train(+ model,+ pp,+ ids,+ labels,+ steps = 3,+):+ opt = torch.optim.AdamW(pp.parameters(), lr = 1e-2, foreach = False)+ losses, grads = [], None+ for step in range(steps):+ losses.append(float(pp.step(ids, labels)))+ if step == 0:+ grads = {+ n: p.grad.detach().clone()+ for n, p in model.named_parameters()+ if p.grad is not None+ }+ pp.clip_grad_norm_(1.0)+ opt.step()+ opt.zero_grad(set_to_none = True)+ return losses, grads+++# PEFT-created tensors (not read from the checkpoint), and those whose init is derived from base weights.+_ADAPTER_KEYS = ("lora_", "modules_to_save.", "trainable_tokens_")+_DERIVED_KEYS = ("lora_magnitude_vector",)+++def _case_load(+ rank,+ world,+ tmp,+ ckpt,+ schedule = "gpipe",+ n_mb = 2,+ v = None,+ peft = None,+):+ from torch.distributed.device_mesh import init_device_mesh++ ppl = _pp_load()+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))["pp"]+ config = ppn.PPConfig(stages_per_rank = v)+ peft = peft or {}+ full = _peft(_load(ckpt), **peft)++ def lora(m):+ return {+ n: p+ for n, p in m.named_parameters()+ if "lora_" in n and not any(k in n for k in _DERIVED_KEYS)+ }++ full_lora = {n: p.detach().clone() for n, p in lora(full).items()}+ full_bytes = _storage_bytes(full)+ ids, labels = batch(full)+ pp_full = ppn.apply_pipeline_parallel(+ full, mesh, n_microbatches = n_mb, schedule = schedule, config = config+ )+ full_after = _storage_bytes(full)+ seen, kept_numel = set(), 0+ for n, p in full.named_parameters():+ if id(p) not in seen and not any(k in n for k in _ADAPTER_KEYS):+ seen.add(id(p))+ kept_numel += p.numel()+ with ppl.pipeline_sharded_loading(mesh, schedule = schedule, config = config) as state:+ model = _load(ckpt)+ stats = dict(model._unsloth_pp_preload)+ loaded_bytes = _storage_bytes(model)+ unsplit = None+ try:+ model(input_ids = ids)+ except RuntimeError as exc:+ unsplit = str(exc)+ placeholders = _placeholders(model)+ model = _peft(model, **peft)+ peft_bytes = _storage_bytes(model)+ # Weight-reading inits (PiSSA, OLoRA, MiCA, ...) leave every placeholder storage-free: same tensors, still+ # zero-stride, none replaced.+ after = _placeholders(model)+ placeholders_kept = (+ len(placeholders) > 0+ and {id(p) for p in after} == {id(p) for p in placeholders}+ and all(_zero_stride(p) for p in after)+ )+ # LoRA of layers this rank read equals the full load's; another rank's (dropped at the split) is only+ # comparable when its init does not read the weight.+ weight_init = peft.get("init_lora_weights", False) not in (True, False, "gaussian")+ skipped = {+ name + "."+ for name, m in model.named_modules()+ if hasattr(m, "lora_A") and ppl.is_placeholder(m.get_base_layer().weight)+ }+ mine = {+ n: p+ for n, p in lora(model).items()+ if not (weight_init and any(n.startswith(k) for k in skipped))+ }+ lora_equal = (+ set(mine) <= set(full_lora)+ and len(mine) > 0+ and (weight_init or set(mine) == set(full_lora))+ and all(torch.equal(full_lora[n], p) for n, p in mine.items())+ )+ pp = ppn.apply_pipeline_parallel(+ model, mesh, n_microbatches = n_mb, schedule = schedule, config = config+ )+ sharded_after = _storage_bytes(model)+ # Same weights where this rank computes: every owned parameter / buffer bitwise equal to the full load.+ a, b = full.state_dict(), model.state_dict()+ diffs = sorted(set(a) ^ set(b)) + [k for k in a if k in b and not torch.equal(a[k], b[k])]+ full_res = _train(full, pp_full, ids, labels)+ res = _train(model, pp, ids, labels)+ return {+ "stats": stats,+ "models_loaded": len(state["models"]),+ "bytes": {+ "full": full_bytes,+ "full_after": full_after,+ "loaded": loaded_bytes,+ "peft": peft_bytes,+ "after": sharded_after,+ },+ "placeholders_kept": placeholders_kept,+ "weight_init": weight_init,+ "skipped_lora_layers": len(skipped),+ "unsplit": unsplit,+ "lora_equal": lora_equal,+ "diffs": diffs,+ "full": full_res,+ "sharded": res,+ "local": pp.local_stages,+ "bounds": pp.bounds,+ "kept_numel": kept_numel,+ "guards": len(model.base_model.model.__dict__.get("_unsloth_pp_preload_guards", ())),+ }+++def _case_refusals(rank, world, tmp, ckpt):+ from torch.distributed.device_mesh import init_device_mesh++ ppl = _pp_load()+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))["pp"]+ out = {}++ def catch(key, fn):+ try:+ fn()+ out[key] = None+ except (ValueError, RuntimeError) as exc:+ out[key] = str(exc)++ with ppl.pipeline_sharded_loading(mesh, schedule = "gpipe"):+ model = _peft(_load(ckpt))+ catch(+ "other_split",+ lambda: ppn.apply_pipeline_parallel(+ model, mesh, n_microbatches = 4, schedule = "interleaved1f1b"+ ),+ )+ out["other_split:uncut"] = not ppn.is_pipeline_parallel(model)+ catch(+ "other_layers_per_stage",+ lambda: ppn.apply_pipeline_parallel(+ model, mesh, config = ppn.PPConfig(layers_per_stage = [1, N_LAYERS - 1])+ ),+ )+ from transformers import AutoModelForCausalLM++ def quantized():+ with ppl.pipeline_sharded_loading(mesh):+ AutoModelForCausalLM.from_pretrained(ckpt, load_in_4bit = True)++ catch("quantized", quantized)+ catch(+ "unknown_schedule",+ lambda: ppl.pipeline_sharded_loading(mesh, schedule = "pipedream").__enter__(),+ )+ return out+++CASES = {"load": _case_load, "refusals": _case_refusals}+++def _worker(rank, world, port, case, tmp, kwargs):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ LOCAL_WORLD_SIZE = str(world),+ )+ import datetime++ import torch.distributed as dist++ torch.set_num_threads(2)+ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 180)+ )+ try:+ res = CASES[case](rank, world, tmp, **kwargs)+ torch.save(res, os.path.join(tmp, f"result_{rank}.pt"))+ finally:+ dist.destroy_process_group()+++def _spawn(+ case,+ world = 2,+ **kwargs,+):+ if _torch_pipelining_error():+ pytest.skip(_torch_pipelining_error())+ ctx = multiprocessing.get_context("spawn")+ port = _free_port()+ with tempfile.TemporaryDirectory() as tmp:+ procs = [+ ctx.Process(target = _worker, args = (r, world, port, case, tmp, kwargs))+ for r in range(world)+ ]+ for p in procs:+ p.start()+ for p in procs:+ p.join(600)+ codes = [p.exitcode for p in procs]+ assert codes == [0] * world, f"rank exit codes {codes}"+ return [+ torch.load(os.path.join(tmp, f"result_{r}.pt"), weights_only = False)+ for r in range(world)+ ]+++ "arch,world,schedule,v,tie,peft",+ [+ ("llama", 2, "gpipe", None, None, None),+ ("qwen3", 2, "1f1b", None, None, None),+ ("gemma3", 2, "gpipe", None, True, None), # tied embedding: read on both ends+ (+ "llama",+ 4,+ "gpipe",+ None,+ None,+ None,+ ), # middle ranks hold neither the embedding nor the head+ ("llama", 2, "interleaved1f1b", 2, None, None),+ (+ "gemma3",+ 2,+ "zbvzerobubble",+ 2,+ True,+ None,+ ), # V: rank 0 holds the first and the last stage+ # Checkpoint-derived trainables (modules_to_save copies, DoRA magnitudes, trainable token rows) of+ # weights another rank loaded: rank 0's copies come from placeholders and must not reach their owner.+ ("llama", 2, "gpipe", None, None, {"modules_to_save": ["input_layernorm"]}),+ ("llama", 4, "gpipe", None, None, {"modules_to_save": ["input_layernorm", "lm_head"]}),+ ("llama", 2, "interleaved1f1b", 2, None, {"use_dora": True}),+ ("qwen3", 2, "1f1b", None, None, {"trainable_token_indices": {"lm_head": [1, 2, 3]}}),+ # Inits that read / rewrite the base weight skip another rank's placeholders (no dense residual), and+ # the owner's init from its real weights trains bitwise like the full load's.+ ("llama", 2, "gpipe", None, None, {"init_lora_weights": "pissa"}),+ ("llama", 2, "gpipe", None, None, {"init_lora_weights": "pissa", "_fast": True}),+ ("qwen3", 4, "gpipe", None, None, {"init_lora_weights": "pissa_niter_2"}),+ ("qwen3", 2, "1f1b", None, None, {"init_lora_weights": "pissa_niter_2", "_fast": True}),+ ("llama", 2, "interleaved1f1b", 2, None, {"init_lora_weights": "olora"}),+ ("llama", 2, "gpipe", None, None, {"init_lora_weights": "mica", "_fast": True}),+ ("llama", 2, "gpipe", None, None, {"init_lora_weights": "pissa", "use_dora": True}),+ ],+)+def test_sharded_loading_matches_full_load_then_split(arch, world, schedule, v, tie, peft):+ if schedule in ("zbvzerobubble", "dualpipev"):+ import importlib+ if not importlib.import_module("unsloth.models.pp_schedules").v_schedules_supported():+ pytest.skip(f"V schedules need torch >= 2.12 (refused on {torch.__version__})")+ init = (peft or {}).get("init_lora_weights")+ if init in ("mica", "lora_ga"):+ import peft as peft_module+ from peft.tuners.lora.layer import LoraLayer+ if not hasattr(LoraLayer, f"{init}_init"):+ pytest.skip(f"peft {peft_module.__version__} has no {init} initialization")+ with tempfile.TemporaryDirectory() as ckpt:+ _save_checkpoint(arch, ckpt, tie = tie)+ n_mb = 4 if schedule != "gpipe" or world == 4 else 2+ results = _spawn("load", world, ckpt = ckpt, schedule = schedule, n_mb = n_mb, v = v, peft = peft)+ total_numel = None+ for rank, res in enumerate(results):+ stats = res["stats"]+ assert res["models_loaded"] == 1+ assert tuple(stats["local_stages"]) == tuple(res["local"]) and stats["bounds"] == [+ tuple(b) for b in res["bounds"]+ ]+ n = stats["loaded_numel"] + stats["placeholder_numel"]+ total_numel = total_numel or n+ assert n == total_numel # every rank saw the whole model, read part of it+ assert (+ stats["placeholder_numel"] > 0 and stats["read_bytes"] == stats["loaded_numel"] * 4+ ), stats+ # Exactly what this rank's stage keeps after a full load is split: nothing more was read.+ assert stats["loaded_numel"] == res["kept_numel"], (+ rank,+ stats["loaded_numel"],+ res["kept_numel"],+ )+ # Load peak: only this rank's share of the weights exists, and after the split it is what a full load+ # leaves (same stage).+ assert res["bytes"]["loaded"] < res["bytes"]["full"], res["bytes"]+ assert res["bytes"]["after"] == res["bytes"]["full_after"], res["bytes"]+ # Adapter creation keeps the bound: no placeholder was densified.+ assert res["placeholders_kept"], "a LoRA init densified a placeholder"+ assert res["bytes"]["peft"] < res["bytes"]["full"], res["bytes"]+ assert not res["weight_init"] or res["skipped_lora_layers"] > 0+ assert res["unsplit"] and "call apply_pipeline_parallel" in res["unsplit"], res["unsplit"]+ assert res["lora_equal"], "LoRA init differs from the full load"+ assert res["guards"] == 0+ assert res["diffs"] == [], res["diffs"][:6]+ full_losses, full_grads = res["full"]+ losses, grads = res["sharded"]+ assert losses == full_losses, (+ losses,+ full_losses,+ ) # bitwise: same weights, same stage program+ assert set(grads) == set(full_grads)+ for k, g in grads.items():+ assert torch.equal(g, full_grads[k]), k+++def test_sharded_loading_refusals_leave_the_model_uncut():+ with tempfile.TemporaryDirectory() as ckpt:+ _save_checkpoint("llama", ckpt)+ res = _spawn("refusals", 2, ckpt = ckpt)+ for r in res:+ assert "loaded with pipeline_sharded_loading for another split" in (+ r["other_split"] or ""+ ), r+ assert r["other_split:uncut"]+ assert "another split" in (r["other_layers_per_stage"] or ""), r+ assert "16-bit safetensors checkpoints only" in (r["quantized"] or ""), r+ assert "pipeline schedule must be one of" in (r["unknown_schedule"] or ""), r+++ "init",+ [+ "pissa",+ "pissa_niter_2",+ "olora",+ "mica",+ "loftq",+ "corda",+ "lora_ga",+ True,+ "gaussian",+ "orthogonal",+ ],+)+def test_lora_inits_leave_placeholders_storage_free(init):+ """Every PEFT init on a layer whose base weight is a placeholder (another stage reads it) leaves it zero-stride+ and runs nothing on it: LoftQ would quantize on CUDA, CorDA / LoRA-GA would need their calibration data."""+ import peft+ from peft import LoraConfig, get_peft_model+ from peft.tuners.lora.layer import LoraLayer++ if init in ("mica", "lora_ga") and not hasattr(LoraLayer, f"{init}_init"):+ # MiCA and LoRA-GA are newer than the PEFT floor (0.18.0): nothing to wrap there.+ pytest.skip(f"peft {peft.__version__} has no {init} initialization")+ ppl = _pp_load()+ ppl.install_placeholder_aware_lora_init()+ model = torch.nn.Sequential(torch.nn.Linear(64, 48, bias = False))+ model[0].weight = ppl._placeholder_param(model[0].weight, "cpu")+ kw = dict(r = 4, lora_alpha = 8, target_modules = ["0"], init_lora_weights = init)+ if init == "lora_ga":+ from peft import LoraGAConfig+ kw["lora_ga_config"] = LoraGAConfig()+ if init == "corda":+ from peft.tuners.lora.config import CordaConfig+ kw["corda_config"] = CordaConfig()+ if init == "loftq":+ # LoraConfig refuses "loftq" without scipy (absent here); LoftQ's own quantizer never runs on a placeholder.+ config = LoraConfig(**{**kw, "init_lora_weights": True})+ config.init_lora_weights, config.loftq_config = "loftq", {"loftq_bits": 4, "loftq_iter": 1}+ else:+ config = LoraConfig(**kw)+ torch.manual_seed(0)+ peft_model = get_peft_model(model, config)+ after = torch.random.get_rng_state()+ weight = peft_model.base_model.model[0].get_base_layer().weight+ assert ppl.is_placeholder(weight) and _zero_stride(weight)+ if init not in ("loftq", "corda", "lora_ga"):+ # The global RNG advanced exactly as on a real weight, so the ranks' later draws stay in step.+ real = torch.nn.Sequential(torch.nn.Linear(64, 48, bias = False))+ torch.manual_seed(0)+ get_peft_model(real, LoraConfig(**kw))+ assert torch.equal(torch.random.get_rng_state(), after), initdiff --git a/unsloth/models/lora_init.py b/unsloth/models/lora_init.pyindex 37a37300546..9f237d5ff20 100644--- a/unsloth/models/lora_init.py+++ b/unsloth/models/lora_init.py@@ -198,6 +198,11 @@ def _routed(base):)+def _pp_placeholder(weight):+ # pipeline_sharded_loading's zero-stride stand-in for a weight another pipeline rank reads.+ return bool(getattr(weight, "_unsloth_pp_placeholder", False))++def _check_float_weight(weight, init):# FSDP-QLoRA packs Params4bit into a float quant_storage: its dtype alone looks dense.if type(weight).__name__ in ("Params4bit", "Int8Params") or hasattr(weight, "quant_state"):@@ -219,12 +224,7 @@ def _pissa_init(self, adapter_name, init_lora_weights):_check_float_weight(weight, init_lora_weights)dtype = weight.dtyper = self.r[adapter_name]- if (- dtype not in _FLOATS- or r > min(weight.shape)- or weight.device.type == "meta"- or not torch.isfinite(weight).all()- ):+ if dtype not in _FLOATS or r > min(weight.shape) or weight.device.type == "meta":return _ORIGINAL["pissa_init"](self, adapter_name, init_lora_weights)if init_lora_weights == "pissa":n_iter, n_oversamples = 6, None@@ -234,6 +234,12 @@ def _pissa_init(self, adapter_name, init_lora_weights):return _ORIGINAL["pissa_init"](self, adapter_name, init_lora_weights)# PEFT's svd_lowrank(q = r, niter = N), device-independent so reloads rebuild the same residual.n_iter, n_oversamples = int(parts[-1]), 0+ if _pp_placeholder(weight):+ # Another pipeline stage owns this layer (pipeline_sharded_loading): its rank computes the init from+ # the real weight, and the split drops this adapter. The fast path draws no global RNG either.+ return+ if not torch.isfinite(weight).all():+ return _ORIGINAL["pissa_init"](self, adapter_name, init_lora_weights)_STATE["pissa"] = Trueself._unsloth_fast_pissa = getattr(self, "_unsloth_fast_pissa", set()) | {adapter_name}W = transpose(weight.to(torch.float32), self.fan_in_fan_out)@@ -258,6 +264,8 @@ def _mica_init(self, adapter_name):return _ORIGINAL["mica_init"](self, adapter_name)weight = self.get_base_layer().weight_check_float_weight(weight, "mica")+ if _pp_placeholder(weight):+ return # another pipeline stage owns this layer (see _pissa_init)r = self.r[adapter_name]if (self.lora_B[adapter_name].weight.device.type == "meta"diff --git a/unsloth/models/pp_load.py b/unsloth/models/pp_load.pynew file mode 100644index 00000000000..197e4c6351c--- /dev/null+++ b/unsloth/models/pp_load.py@@ -0,0 +1,343 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Per-stage loading for pipeline parallelism: each rank reads only the decoder layers its stages keep.++Inside `pipeline_sharded_loading(pp_mesh, schedule, config)` every transformers `from_pretrained` builds the+model on meta, derives the split apply_pipeline_parallel will use (weights only, so later LoRA does not move+it) and reads this rank's decoder layers plus the non-layer modules; the embedding only on the first stage's+rank, the head only on the last's (a tied pair where either end lives). Every other weight is a storage-free+zero-stride placeholder, so a model larger than one GPU can be split. apply_pipeline_parallel must use the+same split (checked); a forward before it is refused. Weight-derived trainable tensors sync only from ranks+that read the weight; weight-reading LoRA inits (PiSSA, OLoRA, MiCA, LoftQ, CorDA, LoRA-GA) skip placeholders+and calibration-forward inits are refused. 16-bit checkpoints only.++ mesh = init_device_mesh("cuda", (pp,), mesh_dim_names = ("pp",))+ with pipeline_sharded_loading(mesh["pp"], schedule = "1f1b"):+ model, tokenizer = FastLanguageModel.from_pretrained(name, load_in_4bit = False, ...)+ model = FastLanguageModel.get_peft_model(model, ...)+ pp = apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 4, schedule = "1f1b")+"""++from __future__ import annotations++import contextlib++import torch+import torch.nn as nn++__all__ = [+ "pipeline_sharded_loading",+ "load_pipeline_parallel",+ "check_preloaded_split",+]++_MARK = "_unsloth_pp_preload"+_GUARDS = "_unsloth_pp_preload_guards"+_PLACEHOLDER = "_unsloth_pp_placeholder"+_QUANTIZED_HINT = (+ "4-bit / 8-bit QLoRA loads the full quantized model and is split by apply_pipeline_parallel: drop "+ "pipeline_sharded_loading for it, or pass load_in_4bit = False."+)+++def _placeholder_param(old, device):+ value = torch.zeros((), dtype = old.dtype, device = device).expand(old.shape)+ new = nn.Parameter(value, requires_grad = old.requires_grad)+ setattr(new, _PLACEHOLDER, True)+ return new+++def is_placeholder(t):+ return bool(getattr(t, _PLACEHOLDER, False))+++def _refuse_unsplit_forward(+ module,+ args,+ kwargs = None,+):+ raise RuntimeError(+ "Unsloth: this model was loaded with pipeline_sharded_loading (each rank holds only its stages' "+ "layers); call apply_pipeline_parallel(model, pp_mesh, ...) with the same mesh, schedule and split "+ "after get_peft_model and before running it. LoRA initializations that run calibration forwards "+ "(init_lora_weights = 'corda' / 'eva' / 'lora_ga') need the whole model: load it without "+ "pipeline_sharded_loading, then apply_pipeline_parallel."+ )+++# PEFT LoraLayer initializers that read the base weight (and most rewrite it with a dense residual).+_WEIGHT_INITS = (+ "pissa_init",+ "olora_init",+ "mica_init",+ "corda_init",+ "loftq_init",+ "lora_ga_init",+)+_SKIPS_PLACEHOLDER = "_unsloth_pp_skips_placeholder"+++def base_is_placeholder(lora_layer):+ weight = getattr(lora_layer.get_base_layer(), "weight", None)+ return weight is not None and is_placeholder(weight)+++def _placeholder_aware(name, original):+ def init(self, adapter_name, *args, **kwargs):+ if not base_is_placeholder(self):+ return original(self, adapter_name, *args, **kwargs)+ # Another rank owns this layer: computing on the zero placeholder would densify it (fp32 copy plus a+ # full residual) for an adapter the split drops. Keep the global RNG in step with a full load:+ # PEFT's pissa_niter_N draws one sketch through torch.svd_lowrank (the other inits draw nothing).+ init_lora_weights = args[0] if args else kwargs.get("init_lora_weights")+ if (+ name == "pissa_init"+ and isinstance(init_lora_weights, str)+ and "_niter_" in init_lora_weights+ ):+ weight = self.get_base_layer().weight+ torch.randn(+ min(weight.shape[-2:]),+ self.r[adapter_name],+ dtype = torch.float32,+ device = weight.device,+ )+ return None++ init.__name__ = init.__qualname__ = name+ init.__wrapped__ = original+ setattr(init, _SKIPS_PLACEHOLDER, True)+ return init+++def install_placeholder_aware_lora_init():+ """Wrap PEFT's weight-dependent LoraLayer initializers to skip pipeline_sharded_loading placeholders (a no-op+ for every other layer). Idempotent; Unsloth's fast PiSSA / MiCA swap checks placeholders itself."""+ try:+ from peft.tuners.lora.layer import LoraLayer+ except Exception:+ return+ for name in _WEIGHT_INITS:+ original = LoraLayer.__dict__.get(name)+ if original is None or getattr(original, _SKIPS_PLACEHOLDER, False):+ continue+ setattr(LoraLayer, name, _placeholder_aware(name, original))+++def _split_for(model, mesh, schedule, config):+ from .pp_native import PPConfig, _find_parts, _refuse_unsupported, derive_pp_split+ from .pp_schedules import resolve_stages_per_rank, schedule_spec, stage_indices++ config = config or PPConfig()+ spec = schedule_spec(schedule)+ v = resolve_stages_per_rank(spec, config.stages_per_rank)+ pp, rank = mesh.size(), mesh.get_local_rank()+ parts = _find_parts(model)+ # The structural refusals (MoE, MLA, ...) before anything is read. Every weight of a fresh load is+ # trainable until get_peft_model freezes it: those refusals run again at apply_pipeline_parallel.+ flags = [(p, p.requires_grad) for p in model.parameters()]+ for p, _ in flags:+ p.requires_grad_(False)+ try:+ _refuse_unsupported(model, parts)+ finally:+ for p, flag in flags:+ p.requires_grad_(flag)+ bounds = derive_pp_split(model, pp * v, config)+ local = stage_indices(spec, rank, pp, v)+ return parts, spec, v, bounds, tuple(local)+++def _materialize(model, name, kwargs, mesh, plan, device):+ from .tp_native import _fill_from_checkpoint++ schedule, config = plan+ parts, spec, v, bounds, local = _split_for(model, mesh, schedule, config)+ total = len(bounds)+ owned = {i for k in local for i in range(*bounds[k])}+ holds_first, holds_last = 0 in local, total - 1 in local+ skip = set()+ for i, layer in enumerate(parts.layers):+ if i not in owned:+ skip.update(id(p) for p in layer.parameters())+ keep = set()+ if holds_first:+ keep.update(id(p) for p in parts.embed.parameters())+ if holds_last:+ keep.update(id(p) for p in parts.lm_head.parameters())+ for module in (parts.embed, parts.lm_head):+ skip.update(id(p) for p in module.parameters() if id(p) not in keep)+ placeholders = []++ def read_local(old, reader, key):+ if id(old) not in skip:+ return None+ new = _placeholder_param(old, device)+ placeholders.append(new)+ return new++ reader, skipped_numel, full_numel = _fill_from_checkpoint(+ model,+ name,+ kwargs,+ device,+ read_local,+ label = "pipeline parallel",+ fallback = "a full load, then apply_pipeline_parallel",+ )+ install_placeholder_aware_lora_init()+ guards = [model.register_forward_pre_hook(_refuse_unsplit_forward, with_kwargs = True)]+ for i, layer in enumerate(parts.layers):+ if i not in owned:+ guards.append(+ layer.register_forward_pre_hook(_refuse_unsplit_forward, with_kwargs = True)+ )+ model.__dict__[_GUARDS] = guards+ stats = {+ "pp": mesh.size(),+ "rank": mesh.get_local_rank(),+ "ranks": mesh.mesh.tolist(),+ "schedule": spec.name,+ "stages_per_rank": v,+ "bounds": [tuple(b) for b in bounds],+ "local_stages": local,+ "placeholder_tensors": len(placeholders),+ "placeholder_numel": skipped_numel,+ "loaded_numel": full_numel,+ "read_bytes": reader.full_bytes,+ }+ model.__dict__[_MARK] = stats+ return stats+++def _preload_info(model):+ from .pp_native import _model_chain+ for level in _model_chain(model) if isinstance(model, nn.Module) else ():+ for module in level.modules():+ info = module.__dict__.get(_MARK)+ if info is not None:+ return module, info+ return None, None+++def check_preloaded_split(model, pp_mesh, schedule, stages_per_rank, bounds, local_stages, parts):+ """A pipeline_sharded_loading model must be split as loaded (other layers are placeholders). Returns the+ loaded module or None."""+ holder, info = _preload_info(model)+ if info is None:+ return None+ want = {+ "ranks": pp_mesh.mesh.tolist(),+ "schedule": schedule,+ "stages_per_rank": stages_per_rank,+ "bounds": [tuple(b) for b in bounds],+ "local_stages": tuple(local_stages),+ }+ got = {k: info[k] for k in want}+ if got != want:+ diff = {k: (got[k], want[k]) for k in want if got[k] != want[k]}+ raise ValueError(+ "Unsloth: this model was loaded with pipeline_sharded_loading for another split (loaded, now): "+ f"{diff}. Pass apply_pipeline_parallel the mesh, schedule and PPConfig pipeline_sharded_loading "+ "used; the layers other stages own were never read."+ )+ return holder+++def loaded_by(parts, spec, pp, stages_per_rank, bounds):+ """{id(parameter): pp ranks that read it} for parameters under a layer, the embedding or the head (the rest+ was read everywhere). Weight-derived trainable tensors are synced only among these ranks, never from a+ placeholder copy."""+ from .pp_schedules import stage_indices++ per_rank = [stage_indices(spec, r, pp, stages_per_rank) for r in range(pp)]+ owners = {}++ def add(module, ranks):+ for p in module.parameters():+ owners.setdefault(id(p), set()).update(ranks)++ for i, layer in enumerate(parts.layers):+ add(+ layer,+ {+ r+ for r, local in enumerate(per_rank)+ if any(bounds[k][0] <= i < bounds[k][1] for k in local)+ },+ )+ # A tied embedding / head is one parameter: read where either end lives (the union).+ add(parts.embed, {r for r, local in enumerate(per_rank) if 0 in local})+ add(parts.lm_head, {r for r, local in enumerate(per_rank) if len(bounds) - 1 in local})+ return {k: frozenset(v) for k, v in owners.items()}+++def release_preload_guards(holder):+ for handle in holder.__dict__.pop(_GUARDS, ()):+ handle.remove()+++def pipeline_sharded_loading(+ pp_mesh = None,+ schedule = "gpipe",+ config = None,+):+ """Every transformers `from_pretrained` inside reads only this rank's pipeline stages (see the module+ docstring). Pass apply_pipeline_parallel the same pp_mesh, schedule and config afterwards."""+ from .pp_schedules import schedule_spec+ from .tp_native import _sharded_from_pretrained++ schedule_spec(schedule) # refuse an unknown schedule before loading anything+ if pp_mesh is None:+ pp_mesh = _default_load_mesh()+ if pp_mesh.ndim != 1:+ raise ValueError("Unsloth: pipeline_sharded_loading takes a 1-D pp mesh (pass mesh['pp']).")+ state = {+ "mesh": pp_mesh,+ "plan": (schedule, config),+ "materialize": _materialize,+ "label": "pipeline parallel",+ "quantized_hint": _QUANTIZED_HINT,+ "prequantized_hint": _QUANTIZED_HINT,+ "mesh_hint": "Unsloth: pipeline_sharded_loading takes a 1-D pp mesh (pass mesh['pp']).",+ }+ with _sharded_from_pretrained(state) as live:+ yield live+++def _default_load_mesh():+ import torch.distributed as dist+ from torch.distributed.device_mesh import init_device_mesh++ if not dist.is_initialized():+ raise RuntimeError(+ "Unsloth: pipeline_sharded_loading needs an initialized process group (torchrun) or a pp mesh."+ )+ device_type = "cuda" if torch.cuda.is_available() else "cpu"+ return init_device_mesh(device_type, (dist.get_world_size(),), mesh_dim_names = ("pp",))+++def load_pipeline_parallel(+ model_name,+ pp_mesh = None,+ schedule = "gpipe",+ config = None,+ loader = None,+ **kwargs,+):+ """`loader(model_name, **kwargs)` under pipeline_sharded_loading (default FastLanguageModel.from_pretrained,+ 16-bit). Returns what the loader returns; raises if no model went through the sharded path."""+ if loader is None:+ from unsloth import FastLanguageModel+ loader = FastLanguageModel.from_pretrained+ kwargs.setdefault("load_in_4bit", False)+ with pipeline_sharded_loading(pp_mesh, schedule, config) as state:+ out = loader(model_name, **kwargs)+ if not state["models"]:+ raise RuntimeError(+ "Unsloth: load_pipeline_parallel's loader did not call transformers from_pretrained; nothing was "+ "loaded sharded."+ )+ return outdiff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.pyindex 233015fac8d..6836d92e18b 100644--- a/unsloth/models/pp_native.py+++ b/unsloth/models/pp_native.py@@ -1562,12 +1562,37 @@ def _local_stage_modules(pp_stage, parts, owned):return modules-def _sync_trainable(model, group, src):+def _sync_trainable(+ model,+ group,+ src,+ owners = None,+):+ """Broadcast every trainable parameter from `src`. With `owners` ({id: pp ranks that loaded it}, from a+ pipeline_sharded_loading model) a parameter listed there is synced only among its owners (from pp rank 0 if+ it is one, else the lowest): a non-owner's copy may be built from a zero placeholder, and the split drops it+ anyway. A single owner keeps its own copy."""import torch.distributed as dist++ me = dist.get_rank(group) if owners is not None else Nonewith torch.no_grad():for param in model.parameters():- if param.requires_grad:+ if not param.requires_grad:+ continue+ held = owners.get(id(param)) if owners is not None else None+ if held is None:dist.broadcast(param.data, src = src, group = group)+ continue+ if len(held) < 2:+ continue+ root = 0 if 0 in held else min(held)+ # Non-owners receive into scratch: their copy may be a zero-stride placeholder.+ buf = (+ param.data+ if me in held+ else torch.empty(param.shape, dtype = param.dtype, device = param.device)+ )+ dist.broadcast(buf, src = dist.get_global_rank(group, root), group = group)def _default_mesh(model):@@ -1647,9 +1672,26 @@ def apply_pipeline_parallel(tuple_format = _layer_call_format(parts.decoder, parts.layers_name) == "tuple"bounds = derive_pp_split(model, total_stages, config)_refuse_shared_across_stages(parts, bounds)+ from .pp_load import check_preloaded_split, loaded_by, release_preload_guards++ # pipeline_sharded_loading read only this rank's stages: the split must be the one it loaded.+ preloaded = check_preloaded_split(+ model,+ pp_mesh,+ schedule,+ stages_per_rank,+ bounds,+ stage_indices(spec, rank, pp, stages_per_rank),+ parts,+ )dtype = config.activation_dtype or parts.embed.weight.dtypeif config.sync_trainable and pp > 1:- _sync_trainable(model, pp_mesh.get_group(), dist.get_global_rank(pp_mesh.get_group(), 0))+ owners = None+ if preloaded is not None:+ owners = loaded_by(parts, spec, pp, stages_per_rank, bounds)+ _sync_trainable(+ model, pp_mesh.get_group(), dist.get_global_rank(pp_mesh.get_group(), 0), owners+ )donated_off = props["split_backward"] and allow_split_backward()pp_stage = PipelineParallel(@@ -1700,6 +1742,8 @@ def apply_pipeline_parallel(if stages_per_rank > 1:pp_stage.stage_modules = _local_stage_modules(pp_stage, parts, owned)pp_stage.module = pp_stage.stage_modules[0]+ if preloaded is not None:+ release_preload_guards(preloaded) # the placeholder layers / embedding / head are gone nowinfo = {"size": pp,"rank": rank,