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
DDP: find unused params for a fully finetuned VLM on text-only batches; native FSDP2 names expert parallelism (#15156)
Daniel Han0ef5f1665b46
diff --git a/tests/_ddp_vlm_text_only_worker.py b/tests/_ddp_vlm_text_only_worker.pynew file mode 100644index 00000000000..ac1033b56b0--- /dev/null+++ b/tests/_ddp_vlm_text_only_worker.py@@ -0,0 +1,55 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""One gloo rank for test_ddp_find_unused_default.py: full finetune of a tiny Llava on text-only+batches with non-reentrant gradient checkpointing, through transformers' Trainer on CPU."""++import importlib.util+import os+import sys++import torch+import transformers+from datasets import Dataset++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_ddp_find_unused_default import _llava # noqa: E402++HELPER = os.path.join(+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),+ "unsloth",+ "models",+ "_ddp_defaults.py",+)+++def main(out_dir):+ torch.set_num_threads(1)+ torch.manual_seed(0)+ model = _llava()+ g = torch.Generator().manual_seed(1)+ rows = []+ for _ in range(16):+ ids = torch.randint(1, 60, (12,), generator = g).tolist()+ rows.append({"input_ids": ids, "labels": ids, "attention_mask": [1] * 12})+ args = transformers.TrainingArguments(+ output_dir = out_dir,+ per_device_train_batch_size = 2,+ max_steps = 3,+ gradient_checkpointing = True,+ gradient_checkpointing_kwargs = {"use_reentrant": False},+ report_to = "none",+ save_strategy = "no",+ use_cpu = True,+ dataloader_num_workers = 0,+ )+ spec = importlib.util.spec_from_file_location("_unsloth_ddp_defaults_vlm", HELPER)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ module.unsloth_default_ddp_find_unused_parameters(args, model)+ trainer = transformers.Trainer(model = model, args = args, train_dataset = Dataset.from_list(rows))+ trainer.train()+ print(f"RANK_OK find_unused={trainer.args.ddp_find_unused_parameters}", flush = True)+++if __name__ == "__main__":+ main(sys.argv[1])diff --git a/tests/test_ddp_find_unused_default.py b/tests/test_ddp_find_unused_default.pyindex 38d8b5cf7a4..0a107b974ab 100644--- a/tests/test_ddp_find_unused_default.py+++ b/tests/test_ddp_find_unused_default.py@@ -8,6 +8,7 @@ path so the test stays CPU-only and does not import ``unsloth``."""import importlib.util+import osfrom pathlib import Pathimport types@@ -267,3 +268,129 @@ def test_generated_trainer_calls_helper():template_init = source.index("class Unsloth{RLTrainer_name}(_Unsloth{RLTrainer_name}):")super_call = source.index("super().__init__({RLTrainer_call_args}", template_init)assert template_init < source.index(call, template_init) < super_call+++def _llava(**text_extra):+ text = transformers.LlamaConfig(+ vocab_size = 64,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ **text_extra,+ )+ vision = transformers.CLIPVisionConfig(+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ image_size = 8,+ patch_size = 4,+ )+ config = transformers.LlavaConfig(text_config = text, vision_config = vision, image_token_index = 63)+ model = transformers.LlavaForConditionalGeneration(config)+ # FastBaseModel.post_patch_model under DDP: VLMs checkpoint non-reentrantly.+ model._unsloth_vlm_gc_non_reentrant = True+ return model+++def test_full_finetune_vlm_searches_unused_tower(ddp_env):+ # transformers' False would leave the tower without gradients on a text-only batch.+ args = _args()+ assert _helper()(args, _llava()) is True+ assert args.ddp_find_unused_parameters is True+++def test_frozen_tower_keeps_transformers_default(ddp_env):+ model = _llava()+ for name, param in model.named_parameters():+ if "vision" in name or "projector" in name:+ param.requires_grad_(False)+ assert _helper()(_args(), model) is None++[email protected]("case", ["no_flag", "reentrant_kwargs", "gemma4", "no_checkpointing"])+def test_vlm_tower_rule_needs_non_reentrant_checkpointing(ddp_env, case):+ model = _llava()+ kwargs = {}+ if case == "no_flag":+ model._unsloth_vlm_gc_non_reentrant = False+ elif case == "reentrant_kwargs":+ kwargs["gradient_checkpointing_kwargs"] = {"use_reentrant": True}+ elif case == "gemma4":+ model.config.model_type = "gemma4"+ else:+ kwargs["gradient_checkpointing"] = False+ assert _helper()(_args(**kwargs), model) is None+++def test_unsloth_config_reentrant_pin_is_overridden_by_the_ddp_wrapper(ddp_env, monkeypatch):+ # Unsloth's generated configs pin use_reentrant = True; under DDP vision.py swaps in a checkpoint+ # wrapper (marked _unsloth_original) that forces use_reentrant = False, so the pin is not what runs.+ import torch.utils.checkpoint as torch_checkpoint++ original = torch_checkpoint.checkpoint+ args = _args(gradient_checkpointing_kwargs = {"use_reentrant": True})+ assert _helper()(args, _llava()) is None++ def forced(function, *a, **k):+ k["use_reentrant"] = False+ return original(function, *a, **k)++ forced._unsloth_original = original+ monkeypatch.setattr(torch_checkpoint, "checkpoint", forced)+ args = _args(gradient_checkpointing_kwargs = {"use_reentrant": True})+ assert _helper()(args, _llava()) is True+++def test_lora_vlm_tower_is_true_like_transformers(ddp_env):+ # transformers already picks True for a PeftModel; the helper agrees.+ model = _lora(_llava(), target_modules = ["q_proj", "v_proj"])+ assert _helper()(_args(), model) is True+++def test_reused_args_redecide_after_an_auto_true(ddp_env):+ args = _args()+ helper = _helper()+ assert helper(args, _llava()) is True+ assert helper(args, _lora(_llama())) is False+ assert helper(args, _lora(_llama(num_local_experts = 4))) is None+++def test_full_finetune_vlm_text_only_batches_train_under_ddp(tmp_path):+ # Two gloo ranks through the real Trainer: before the fix the second step raised+ # "Expected to have finished reduction in the prior iteration".+ import subprocess+ import sys++ worker = Path(__file__).with_name("_ddp_vlm_text_only_worker.py")+ env = dict(os.environ, CUDA_VISIBLE_DEVICES = "", TMPDIR = str(tmp_path))+ env.pop("UNSLOTH_DDP_FIND_UNUSED_PARAMETERS_AUTO", None)+ proc = subprocess.run(+ [+ sys.executable,+ "-m",+ "torch.distributed.run",+ "--nproc_per_node",+ "2",+ "--master_port",+ str(_free_port()),+ str(worker),+ str(tmp_path),+ ],+ env = env,+ capture_output = True,+ text = True,+ timeout = 600,+ )+ out = proc.stdout + proc.stderr+ assert proc.returncode == 0, out[-4000:]+ assert out.count("RANK_OK find_unused=True") == 2, out[-4000:]+++def _free_port():+ import socket+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]diff --git a/tests/test_fsdp2_native_pg_tp_media_gloo.py b/tests/test_fsdp2_native_pg_tp_media_gloo.pyindex f59192e3158..332a8825ff1 100644--- a/tests/test_fsdp2_native_pg_tp_media_gloo.py+++ b/tests/test_fsdp2_native_pg_tp_media_gloo.py@@ -185,6 +185,29 @@ def test_parallelism_config_and_tp_models_are_refused(native_env, monkeypatch):native.native_fsdp2_trainer_setup(model = model, phase = "pre", training_args = types.SimpleNamespace(**BASE_ARGS))+ # transformers expert parallelism (DistributedConfig(tp_size = N, enable_expert_parallel = True)):+ # refused with a message that names it.+ for tp_size in (2, 4):+ for dc in (+ types.SimpleNamespace(enable_expert_parallel = True, tp_size = tp_size),+ {"enable_expert_parallel": True, "tp_size": tp_size},+ ):+ model = _tiny_llama()+ model._tp_size = tp_size+ model.config.distributed_config = dc+ with pytest.raises(RuntimeError, match = "expert parallelism") as e:+ native.native_fsdp2_trainer_setup(+ model = model, phase = "pre", training_args = types.SimpleNamespace(**BASE_ARGS)+ )+ assert "UNSLOTH_FSDP2_BACKEND=accelerate with" not in str(e.value)+ assert not native.is_native_fsdp2(model)+ # Expert parallelism off, or a stale flag on a model that was not distributed: not refused.+ for enable in (False, True):+ model = _tiny_llama()+ model.config.distributed_config = types.SimpleNamespace(+ enable_expert_parallel = enable, tp_size = 1+ )+ native._refuse_tensor_parallel_model(model)# ---- 4. torch 2.4 / 2.5 layout ----------------------------------------------------------------diff --git a/unsloth/models/_ddp_defaults.py b/unsloth/models/_ddp_defaults.pyindex b4bb498641d..be85c87661b 100644--- a/unsloth/models/_ddp_defaults.py+++ b/unsloth/models/_ddp_defaults.py@@ -10,6 +10,9 @@ forward runs without grad, DDP marks every LoRA weight unused, then the recomputtransformers already picks False for a ``PreTrainedModel`` under checkpointing; this does the same for aplain LoRA adapter on a dense text model, where every trainable parameter gets a gradient each step.Without checkpointing True works (and tolerates an adapter a step never runs), so it is left alone.++Conversely a fully finetuned VLM gets False from transformers, and a text-only batch leaves its+trainable tower without gradients; Unsloth checkpoints VLMs non-reentrantly, so True is picked (as TRL)."""import os@@ -159,21 +162,78 @@ def _lora_uses_every_trainable_param(model):return n_trainable > 0+# Towers a text-only batch never runs.+_TOWER_NAME_MARKERS = ("vision", "visual", "audio", "image", "projector")+# vision.py forces these back to reentrant checkpointing, where True fails ("marked ready twice").+_REENTRANT_VLM_MODEL_TYPES = ("gemma3n", "gemma4")+++def _unwrapped_models(model):+ out = []+ while model is not None and not any(model is m for m in out):+ out.append(model)+ model = getattr(model, "module", None)+ if out:+ get_base = getattr(out[-1], "get_base_model", None)+ if callable(get_base):+ base = get_base()+ if base is not None and not any(base is m for m in out):+ out.append(base)+ return out+++def _checkpoint_forced_non_reentrant():+ # vision.py's DDP wrapper (marked _unsloth_original) forces every checkpoint call non-reentrant.+ try:+ import torch.utils.checkpoint as torch_checkpoint+ except Exception:+ return False+ return getattr(torch_checkpoint.checkpoint, "_unsloth_original", None) is not None+++def _vlm_tower_needs_unused_search(args, model):+ """Trainable tower a text-only batch skips, under ``_unsloth_vlm_gc_non_reentrant``."""+ models = _unwrapped_models(model)+ if not any(getattr(m, "_unsloth_vlm_gc_non_reentrant", False) is True for m in models):+ return False+ kwargs = getattr(args, "gradient_checkpointing_kwargs", None) or {}+ # Unsloth's generated configs pin use_reentrant = True; under the DDP wrapper that pin is not what runs.+ if (+ isinstance(kwargs, dict)+ and kwargs.get("use_reentrant") is True+ and not _checkpoint_forced_non_reentrant()+ ):+ return False+ config = getattr(models[-1], "config", None)+ model_type = str(getattr(config, "model_type", "") or "").lower()+ if any(t in model_type for t in _REENTRANT_VLM_MODEL_TYPES):+ return False+ if not any(+ getattr(c, key, None) is not None for c in _configs(config) for key in _SUBMODEL_CONFIG_KEYS+ ):+ return False+ return any(+ p.requires_grad and any(m in name.lower() for m in _TOWER_NAME_MARKERS)+ for name, p in model.named_parameters()+ )++def unsloth_default_ddp_find_unused_parameters(args, model):"""Set ``args.ddp_find_unused_parameters = False`` for a plain LoRA model under DDP with gradientcheckpointing when the user left it None.Kept at None (transformers' True) for anything a step may skip: MoE / expert LoRA, vision or audiotowers, MTP heads, lm_head / embedding adapters, modules_to_save, several adapters, non-LoRA PEFT.- Returns the value now on ``args``.+ Set to True for a VLM with a trainable tower under non-reentrant checkpointing. Returns the value now on ``args``."""if args is None or not hasattr(args, "ddp_find_unused_parameters"):return None- if getattr(args, _AUTO_FLAG, False):- # Reused args object: our earlier False is not a user choice, re-decide; a value set since then wins.- if args.ddp_find_unused_parameters is False:+ auto = getattr(args, _AUTO_FLAG, None)+ if isinstance(auto, tuple):+ # Reused args object: our earlier value is not a user choice, re-decide; a value set since then wins.+ if args.ddp_find_unused_parameters is auto[0]:args.ddp_find_unused_parameters = None- object.__setattr__(args, _AUTO_FLAG, False)+ object.__setattr__(args, _AUTO_FLAG, None)if args.ddp_find_unused_parameters is not None:return args.ddp_find_unused_parametersif os.environ.get("UNSLOTH_DDP_FIND_UNUSED_PARAMETERS_AUTO", "1") == "0":@@ -181,12 +241,14 @@ def unsloth_default_ddp_find_unused_parameters(args, model):if not _is_distributed():return Nonetry:- safe = _gradient_checkpointing_on(args, model) and _lora_uses_every_trainable_param(model)+ gc_on = _gradient_checkpointing_on(args, model)+ safe = gc_on and _lora_uses_every_trainable_param(model)+ tower = gc_on and not safe and _vlm_tower_needs_unused_search(args, model)except Exception:- safe = False- if safe:- args.ddp_find_unused_parameters = False- object.__setattr__(args, _AUTO_FLAG, True)+ safe = tower = False+ if safe or tower:+ args.ddp_find_unused_parameters = not safe+ object.__setattr__(args, _AUTO_FLAG, (not safe,))return args.ddp_find_unused_parametersdiff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex ff07b6f209d..d5040f71b0a 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -3444,10 +3444,26 @@ def _refuse_parallelism_config(training_args):)+def _expert_parallel_requested(model):+ """from_pretrained(distributed_config = DistributedConfig(enable_expert_parallel = True))."""+ for m in (model, getattr(model, "get_base_model", lambda: None)()):+ dc = getattr(getattr(m, "config", None), "distributed_config", None)+ if dc is None:+ continue+ ep = (+ dc.get("enable_expert_parallel")+ if isinstance(dc, dict)+ else getattr(dc, "enable_expert_parallel", False)+ )+ if ep is True:+ return True+ return False++def _refuse_tensor_parallel_model(model):- """A model loaded with a tensor-parallel plan (from_pretrained(tp_plan = ...)) already holds- DTensor parameters on its own mesh; the Trainer would also build a ParallelismConfig from its- tp_size. Native FSDP2 cannot shard it again."""+ """A model loaded with tp_plan or expert parallelism already holds DTensor / per-rank expert+ parameters on its own mesh, and the Trainer would build a ParallelismConfig from its tp_size.+ Native FSDP2 cannot shard it again."""if not isinstance(model, nn.Module) or getattr(model, _NATIVE_FLAG, False):returntp_size = getattr(model, "tp_size", None)@@ -3455,6 +3471,14 @@ def _refuse_tensor_parallel_model(model):tp_size = int(tp_size) if tp_size is not None else Noneexcept (TypeError, ValueError):tp_size = None+ # tp_size > 1 too: a stale distributed_config on a model loaded without one is not expert parallel.+ if (tp_size or 1) > 1 and _expert_parallel_requested(model):+ raise RuntimeError(+ "Unsloth: native FSDP2 got a model loaded with transformers expert parallelism "+ f"(DistributedConfig(enable_expert_parallel = True), tp_size = {tp_size}): its experts are "+ "already split over the ranks, and FSDP2 would shard them again. Load it without "+ "distributed_config for native FSDP2, which shards every expert over all ranks itself."+ )DTensor = Nonetry:from torch.distributed.tensor import DTensor