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
Fix DDP "marked ready twice" for VLMs with CPU offload + TiledMLP (#4240)
Daniel Han46764a63da4b
diff --git a/tests/test_tiled_mlp_ddp.py b/tests/test_tiled_mlp_ddp.pynew file mode 100644index 00000000000..612f67184ed--- /dev/null+++ b/tests/test_tiled_mlp_ddp.py@@ -0,0 +1,160 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""TiledMLP under 2-rank gloo DDP must produce the untiled all-reduced grads in every DDP mode."""++import importlib.util+import os+import pathlib+import sys+import tempfile++import pytest+import torch+import torch.distributed as dist+import torch.multiprocessing as mp++if not dist.is_available() or not dist.is_gloo_available():+ pytest.skip("needs gloo", allow_module_level = True)+++def _tiled_mlp():+ # Spawned ranks skip conftest, so repeat its accelerator-less import of unsloth_zoo.device_type.+ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")+ if "unsloth_zoo.device_type" not in sys.modules and not torch.cuda.is_available():+ is_available = torch.cuda.is_available+ torch.cuda.is_available = lambda: True+ try:+ import unsloth_zoo.device_type # noqa: F401+ finally:+ torch.cuda.is_available = is_available+ from unsloth_zoo.tiled_mlp import TiledMLP++ return TiledMLP+++_PATCH = pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "models" / "_tiled_mlp_ddp.py"+_MODES = {+ "default": {},+ "find_unused_parameters": {"find_unused_parameters": True},+ "static_graph": {"static_graph": True},+ "gradient_as_bucket_view": {"gradient_as_bucket_view": True},+}+++class _MLP(torch.nn.Module):+ def __init__(self, tiled):+ super().__init__()+ torch.manual_seed(0)+ self.up = torch.nn.Linear(8, 32)+ self.down = torch.nn.Linear(32, 8)+ self.frozen = torch.nn.Linear(8, 8).requires_grad_(False)+ self.tiled = tiled++ def mlp(self, x):+ return self.down(torch.nn.functional.gelu(self.up(x))) + self.frozen(x)++ def forward(self, x):+ if self.tiled:+ return _tiled_mlp().apply(self.mlp, self, x, False, 4, None)+ return self.mlp(x)+++def _inputs(rank, step):+ g = torch.Generator().manual_seed(100 + rank)+ return (torch.randn(2, 16, 8, generator = g) * (step + 1)).requires_grad_(True)+++def _grads(model, x):+ return [p.grad.tolist() for p in model.parameters() if p.requires_grad] + [x.grad.tolist()]+++def _load_patch():+ spec = importlib.util.spec_from_file_location("_tiled_mlp_ddp_under_test", _PATCH)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _worker(rank, init_file, queue):+ try:+ _load_patch().patch_tiled_mlp_for_ddp()+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = 2)+ out = {}+ for mode, ddp_kwargs in _MODES.items():+ try:+ model = torch.nn.parallel.DistributedDataParallel(_MLP(tiled = True), **ddp_kwargs)+ out[mode] = []+ for step in range(3):+ model.zero_grad(set_to_none = True)+ x = _inputs(rank, step)+ model(x).pow(2).sum().backward()+ out[mode].append(_grads(model.module, x))+ except Exception as e:+ out[mode] = repr(e)+ queue.put((rank, out))+ except Exception as e:+ queue.put((rank, {mode: repr(e) for mode in _MODES}))+ finally:+ if dist.is_initialized():+ dist.destroy_process_group()+++def _reference(rank, step):+ model = _MLP(tiled = False)+ xs = [_inputs(r, step) for r in range(2)]+ for x in xs:+ model(x).pow(2).sum().backward()+ for p in model.parameters():+ if p.grad is not None:+ p.grad /= 2+ return _grads(model, xs[rank])++[email protected](scope = "module")+def ddp_grads(tmp_path_factory):+ ctx = mp.get_context("spawn")+ queue = ctx.Queue()+ init_file = tempfile.mktemp(dir = tmp_path_factory.mktemp("ddp"))+ procs = [ctx.Process(target = _worker, args = (r, init_file, queue)) for r in range(2)]+ for p in procs:+ p.start()+ results = dict(queue.get(timeout = 300) for _ in procs)+ for p in procs:+ p.join(30)+ if p.is_alive():+ p.kill()+ return results++[email protected]("mode", list(_MODES))+def test_tiled_mlp_ddp_grads_match_untiled(mode, ddp_grads):+ for rank, by_mode in ddp_grads.items():+ grads = by_mode[mode]+ assert not isinstance(grads, str), grads+ for step, got in enumerate(grads):+ for a, b in zip(got, _reference(rank, step)):+ torch.testing.assert_close(torch.tensor(a), torch.tensor(b), rtol = 1e-4, atol = 1e-4)+++def test_single_process_matches_stock_tiled_mlp():+ stock = _MLP(tiled = True)+ x = _inputs(0, 0)+ stock(x).pow(2).sum().backward()+ expected = _grads(stock, x)++ TiledMLP = _tiled_mlp()+ original_apply = TiledMLP.__dict__.get("apply")+ _load_patch().patch_tiled_mlp_for_ddp()+ try:+ patched = _MLP(tiled = True)+ x = _inputs(0, 0)+ patched(x).pow(2).sum().backward()+ got = _grads(patched, x)+ finally:+ if original_apply is not None:+ TiledMLP.apply = original_apply+ elif "apply" in TiledMLP.__dict__:+ del TiledMLP.apply+ for a, b in zip(got, expected):+ torch.testing.assert_close(torch.tensor(a), torch.tensor(b), rtol = 1e-5, atol = 1e-5)diff --git a/unsloth/models/_tiled_mlp_ddp.py b/unsloth/models/_tiled_mlp_ddp.pynew file mode 100644index 00000000000..d28f7782437--- /dev/null+++ b/unsloth/models/_tiled_mlp_ddp.py@@ -0,0 +1,70 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++import torch+from unsloth_zoo.gradient_checkpointing import set_device_states+from unsloth_zoo.tiled_mlp import TiledMLP, torch_amp_custom_bwd++__all__ = ["patch_tiled_mlp_for_ddp"]+++class _TiledMLPWithParams(torch.autograd.Function):+ # Stock TiledMLP's per-chunk .backward() fires DDP's grad hooks once per chunk (wrong grads / "marked ready twice");+ # taking the params as inputs and returning summed grads accumulates each exactly once.+ @staticmethod+ def forward(+ ctx, mlp_forward, mlp_module, x, preserve_rng_state, num_shards, max_flat_qlen, *params+ ):+ ctx.params = params+ return TiledMLP.forward(+ ctx, mlp_forward, mlp_module, x, preserve_rng_state, num_shards, max_flat_qlen+ )++ @staticmethod+ @torch_amp_custom_bwd+ def backward(ctx, grad_output, *args):+ x = ctx.saved_tensors[0]+ H = x.shape[-1]+ rng_devices = ctx.fwd_devices if ctx.preserve_rng_state and ctx.had_device_in_fwd else []+ with torch.random.fork_rng(+ devices = rng_devices, enabled = ctx.preserve_rng_state, device_type = ctx.device_type+ ):+ if ctx.preserve_rng_state:+ torch.set_rng_state(ctx.fwd_cpu_state)+ if ctx.had_device_in_fwd:+ set_device_states(+ ctx.fwd_devices, ctx.fwd_device_states, device_type = ctx.device_type+ )+ x_gradients = torch.zeros_like(x, memory_format = torch.preserve_format)+ param_grads = [None] * len(ctx.params)+ extra_outputs = []+ for x_split, grad_split, x_grad in zip(+ torch.split(x.view(-1, H), ctx.split_sizes, dim = 0),+ torch.split(grad_output.reshape(-1, H), ctx.split_sizes, dim = 0),+ torch.split(x_gradients.view(-1, H), ctx.split_sizes, dim = 0),+ ):+ x_split = x_split.unsqueeze(0).requires_grad_(True)+ with torch.enable_grad():+ outputs = TiledMLP.handle_output(ctx.mlp_forward(x_split), extra_outputs)+ grads = torch.autograd.grad(+ outputs,+ (x_split, *ctx.params),+ grad_split.unsqueeze(0),+ allow_unused = True,+ )+ x_grad.copy_(grads[0].squeeze(0))+ for i, g in enumerate(grads[1:]):+ if g is not None:+ param_grads[i] = g if param_grads[i] is None else param_grads[i].add_(g)+ return (None, None, x_gradients, None, None, None, *param_grads)+++def _apply_with_params(mlp_forward, mlp_module, x, preserve_rng_state, num_shards, max_flat_qlen):+ params = [p for p in mlp_module.parameters() if p.requires_grad]+ return _TiledMLPWithParams.apply(+ mlp_forward, mlp_module, x, preserve_rng_state, num_shards, max_flat_qlen, *params+ )+++def patch_tiled_mlp_for_ddp():+ TiledMLP.apply = staticmethod(_apply_with_params)diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 5a8b3cbd87e..b4754990866 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -49,6 +49,7 @@ from .loader_utils import (_offline_quantize_to_fp8,_tag_model_with_fp8_torchao_config,get_model_name,+ is_distributed,is_automatic_device_map,prepare_device_map,requested_device_map,@@ -79,6 +80,7 @@ from ..device_type import (from unsloth_zoo.utils import Version, _get_dtypefrom unsloth_zoo.hf_utils import dtype_from_configfrom unsloth_zoo.tiled_mlp import patch_tiled_mlp+from ._tiled_mlp_ddp import patch_tiled_mlp_for_ddptransformers_version = Version(transformers_version)SUPPORTS_FOURBIT = transformers_version >= Version("4.37")@@ -1519,6 +1521,8 @@ class FastLanguageModel(FastLlamaModel):)if patch_tiled_mlp_choice != "0" or unsloth_tiled_mlp:patch_tiled_mlp(model, patch_options_str = patch_tiled_mlp_choice)+ if is_distributed():+ patch_tiled_mlp_for_ddp()model = _fix_rope_inv_freq(model)model = _exclude_rope_inv_freq_from_ddp(model)@@ -2698,6 +2702,8 @@ class FastModel(FastBaseModel):)if patch_tiled_mlp_choice != "0" or unsloth_tiled_mlp:patch_tiled_mlp(model, patch_options_str = patch_tiled_mlp_choice)+ if is_distributed():+ patch_tiled_mlp_for_ddp()model = _fix_rope_inv_freq(model)model = _exclude_rope_inv_freq_from_ddp(model)diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex add9afa8e32..47044a19915 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -1869,6 +1869,18 @@ def _tolerate_dtype_cast_on_quantized_model(enabled):PreTrainedModel.to = original_to+def _offload_activation_pack(x):+ # Only activations (they require grad); masks and rotary tables are shared across layers.+ if x.requires_grad and x.device.type != "cpu":+ return x.device, x.to("cpu", non_blocking = True)+ return None, x+++def _offload_activation_unpack(packed):+ device, x = packed+ return x if device is None else x.to(device, non_blocking = True)++class FastBaseModel:@staticmethod@_offline_aware_load@@ -3518,17 +3530,28 @@ class FastBaseModel:if _get_dtype(dtype_from_config(model.config)) == torch.bfloat16 and full_finetuning:float32_mixed_precision = False- # VLMs can hit DDP "marked ready twice" with re-entrant checkpointing (#3713), so under DDP skip the offloaded/re-entrant checkpoint patch and default native checkpoint to non-reentrant.+ # VLMs can hit DDP "marked ready twice" with re-entrant checkpointing (#3713), so under DDP skip the offloaded/re-entrant checkpoint patch and default native checkpoint to non-reentrant, offloading via saved-tensor hooks instead.use_reentrant = not is_distributed()if not use_reentrant:unpatch_unsloth_gradient_checkpointing()unpatch_unsloth_smart_gradient_checkpointing()- _orig_checkpoint = torch_checkpoint.checkpoint+ _orig_checkpoint = getattr(+ torch_checkpoint.checkpoint,+ "_unsloth_original",+ torch_checkpoint.checkpoint,+ )+ _offload = use_gradient_checkpointing == "unsloth"def _nonre_checkpoint(function, *args, **kwargs):kwargs["use_reentrant"] = False- return _orig_checkpoint(function, *args, **kwargs)+ if not _offload:+ return _orig_checkpoint(function, *args, **kwargs)+ with torch.autograd.graph.saved_tensors_hooks(+ _offload_activation_pack, _offload_activation_unpack+ ):+ return _orig_checkpoint(function, *args, **kwargs)+ _nonre_checkpoint._unsloth_original = _orig_checkpointtorch_checkpoint.checkpoint = _nonre_checkpointhf_modeling_utils.checkpoint = _nonre_checkpoint@@ -3551,11 +3574,17 @@ class FastBaseModel:if full_finetuning:# prepare_model_for_training re-enabled every parameter, a kept wrapper's siblings too._freeze_unused_siblings(model)+ _model_type = getattr(getattr(model, "config", None), "model_type", "") or ""+ if not use_reentrant and not any(x in _model_type.lower() for x in ("gemma3n", "gemma4")):+ # _set_gradient_checkpointing() binds torch's checkpoint as a default argument, bypassing the patch above.+ for module in model.modules():+ func = getattr(module, "_gradient_checkpointing_func", None)+ if getattr(func, "__module__", None) == "torch.utils.checkpoint":+ module._gradient_checkpointing_func = _nonre_checkpoint# Persist the configured GC mode so the trainer restores it verbatim: for_inference() clears the module flags every GRPO generation step, and TrainingArguments defaults gradient_checkpointing=False, which would silently disable it at train time (#4735).model._unsloth_gradient_checkpointing = use_gradient_checkpointing# The Gemma3N audio conformer's variable-length tensors cause stride mismatches in the AOT autograd compiled backward under non-reentrant checkpointing, and TRL may override gradient_checkpointing_kwargs later, so intercept the enable and force use_reentrant=True.- _model_type = getattr(getattr(model, "config", None), "model_type", "") or ""if "gemma3n" in _model_type.lower() or "gemma4" in _model_type.lower():_original_gc_enable = model.gradient_checkpointing_enable