Skip to content

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.

Tiled MLP: one flag or one line for any model, on the new sequence tiling engine (#16125)

Daniel Han673a44bce9a2
diff --git a/tests/test_fsdp_declines_fused_lora.py b/tests/test_fsdp_declines_fused_lora.py
index e8d2faf3ffb..bf8dbad4a1a 100644
--- a/tests/test_fsdp_declines_fused_lora.py
+++ b/tests/test_fsdp_declines_fused_lora.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import ast
import os
+import types
from pathlib import Path
import pytest
@@ -146,3 +147,182 @@ def test_the_trainer_init_wrapper_calls_the_decline():
source = inspect.getsource(_utils.patch_gradient_accumulation_fix)
assert "is_fsdp_enabled" in source and "_decline_fused_lora_for_fsdp" in source
+
+
+class _GroupedMLP(__import__("torch").nn.Module):
+ def __init__(self):
+ import torch
+ super().__init__()
+ self.up = torch.nn.Linear(4, 4)
+
+ def forward(self, x):
+ return self.up(x)
+
+
+def _adopted_forward(self, x):
+ return self.up(x) * 3
+
+
[email protected]("tiled", [False, True, "after"])
+def test_declining_restores_the_forward_before_the_fused_kernel(tiled):
+ """Decline restores the prior instance forward, not the class forward."""
+ import types
+
+ import torch
+ from unsloth.models import llama
+
+ mlp = _GroupedMLP()
+ mlp.forward = types.MethodType(_adopted_forward, mlp)
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry") if tiled else None
+ if tiled is True:
+ registry.install_module(mlp, "rows:2")
+ assert mlp.__dict__["_unsloth_forward"].__func__ is _adopted_forward
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ if tiled == "after":
+ registry.install_module(mlp, "rows:2")
+ assert mlp in llama._fused_lora_modules(mlp)
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ slot = "_unsloth_forward" if tiled else "forward"
+ assert registry is None or registry.is_tiled(mlp)
+ assert mlp.__dict__[slot].__func__ is _adopted_forward
+ x = torch.randn(2, 3, 4)
+ torch.testing.assert_close(mlp(x), mlp.up(x) * 3)
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 0
+
+
[email protected]("tiled", [False, True])
+def test_declining_a_plain_module_still_restores_the_class_forward(tiled):
+ import types
+
+ import torch
+ from unsloth.models import llama
+
+ mlp = _GroupedMLP()
+ if tiled:
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+ registry.install_module(mlp, "rows:2")
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ llama._install_fused_lora_mlp(
+ mlp, llama.apply_lora_mlp_swiglu
+ ) # a second patch pass keeps the first record
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ if tiled:
+ assert mlp.__dict__["_unsloth_forward"] is _GroupedMLP.forward
+ else:
+ assert "forward" not in mlp.__dict__
+ x = torch.randn(2, 3, 4)
+ torch.testing.assert_close(mlp(x), mlp.up(x))
+
+
+def test_tile_fuse_untile_decline_leaves_a_callable_module():
+ """Decline after untile must not put the unbound class function in `forward`."""
+ import torch
+ from unsloth.models import llama
+
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+ mlp = _GroupedMLP()
+ registry.install_module(mlp, "rows:2")
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ registry.uninstall(mlp)
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ assert "forward" not in mlp.__dict__
+ x = torch.randn(2, 3, 4)
+ torch.testing.assert_close(mlp(x), mlp.up(x))
+
+
+def _counting_hook():
+ hooks = pytest.importorskip("accelerate.hooks")
+
+ class _Count(hooks.ModelHook):
+ calls = 0
+
+ def pre_forward(self, module, *args, **kwargs):
+ type(self).calls += 1
+ return args, kwargs
+
+ return hooks, _Count
+
+
+def test_a_kernel_behind_an_adopted_accelerate_hook_is_found_and_declined():
+ """Kernel moved into an adopted hook's `_old_forward` is still detected and declined; the hook keeps running."""
+ import torch
+ from unsloth.models import llama
+
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+ hooks, count = _counting_hook()
+ mlp = _GroupedMLP()
+ registry.install_module(mlp, "rows:2")
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ hooks.add_hook_to_module(mlp, count())
+ registry.install_module(mlp, "rows:2") # Trainer revalidation
+ assert mlp in llama._fused_lora_modules(mlp)
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ assert llama._fused_lora_modules(mlp) == []
+ x = torch.randn(2, 3, 4)
+ before = count.calls
+ torch.testing.assert_close(mlp(x), mlp.up(x))
+ assert count.calls > before
+
+
+def test_a_kernel_behind_an_accelerate_hook_after_untile_is_declined():
+ """After untile the kernel sits in the hook's `_old_forward` and is still detected and declined."""
+ import torch
+ from unsloth.models import llama
+ from unsloth.tiling import untile_mlp
+
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+ hooks, count = _counting_hook()
+ mlp = _GroupedMLP()
+ registry.install_module(mlp, "rows:2")
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ hooks.add_hook_to_module(mlp, count())
+ untile_mlp(mlp)
+ assert mlp in llama._fused_lora_modules(mlp)
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ assert llama._fused_lora_modules(mlp) == []
+ x = torch.randn(2, 3, 4)
+ torch.testing.assert_close(mlp(x), mlp.up(x))
+
+
[email protected]("tiled", [False, True])
+def test_installing_the_kernel_keeps_an_accelerate_hook_running(tiled):
+ import torch
+ from unsloth.models import llama
+
+ hooks, count = _counting_hook()
+ mlp = _GroupedMLP()
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry") if tiled else None
+ if tiled:
+ registry.install_module(mlp, "rows:2")
+ hooks.add_hook_to_module(mlp, count())
+ if tiled:
+ registry.install_module(mlp, "rows:2") # the hook is adopted as the inner forward
+ seen = []
+ kernel = llama.apply_lora_mlp_swiglu
+ llama._install_fused_lora_mlp(mlp, kernel)
+ assert mlp in llama._fused_lora_modules(mlp)
+ slot = llama._fused_lora_mlp_slot(mlp)
+ mlp.__dict__[slot] = types.MethodType(lambda self, x: (seen.append(1), self.up(x))[1], mlp)
+ x = torch.randn(2, 3, 4)
+ before = count.calls
+ mlp(x)
+ assert count.calls > before and seen
+
+
[email protected]("wrap", ["lambda", "compiler_disable"])
+def test_instance_forward_fuse_tile_decline_still_calls(wrap):
+ """A restored instance function must not get `self` bound twice in a tiled inner slot."""
+ import torch
+ from unsloth.models import llama
+
+ registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+ mlp = _GroupedMLP()
+ if wrap == "lambda":
+ mlp.forward = lambda x: mlp.up(x) * 3
+ else:
+ mlp.forward = torch.compiler.disable(types.MethodType(_adopted_forward, mlp))
+ llama._install_fused_lora_mlp(mlp, llama.apply_lora_mlp_swiglu)
+ registry.install_module(mlp, "rows:2")
+ assert llama._decline_fused_lora_for_fsdp(mlp) == 1
+ x = torch.randn(2, 3, 4)
+ torch.testing.assert_close(mlp(x), mlp.up(x) * 3)
diff --git a/tests/test_tiled_mlp_ddp.py b/tests/test_tiled_mlp_ddp.py
deleted file mode 100644
index 9c5d72ea4ad..00000000000
--- a/tests/test_tiled_mlp_ddp.py
+++ /dev/null
@@ -1,163 +0,0 @@
-# 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 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:
- # Spawned workers lack conftest preloading and zoo GPU init refuses CPU-only runners.
- if not torch.cuda.is_available():
- os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = "1"
- _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/tests/test_tiling_block_compile.py b/tests/test_tiling_block_compile.py
new file mode 100644
index 00000000000..7196d7b66ab
--- /dev/null
+++ b/tests/test_tiling_block_compile.py
@@ -0,0 +1,76 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Tiled MLP under per-decoder-block compile (old TiledMLP hit a no_grad view error on torch >= 2.11)."""
+
+import os
+
+import pytest
+
+pytestmark = pytest.mark.gpu
+
+
[email protected]("spelling", ["env", "kwarg"])
+def test_tiled_mlp_trains_under_the_default_block_compile(spelling, monkeypatch, tmp_path, capfd):
+ torch = pytest.importorskip("torch")
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(tmp_path / "cache"))
+ monkeypatch.delenv("UNSLOTH_BLOCK_COMPILE", raising = False)
+ monkeypatch.delenv("UNSLOTH_BLOCK_COMPILE_LEGACY", raising = False)
+ kwargs = {}
+ if spelling == "env":
+ monkeypatch.setenv("UNSLOTH_TILED_MLP", "arctic")
+ else:
+ monkeypatch.delenv("UNSLOTH_TILED_MLP", raising = False)
+ kwargs["unsloth_tiled_mlp"] = "rows:16"
+ from unsloth import FastLanguageModel
+
+ model, _ = FastLanguageModel.from_pretrained(
+ "trl-internal-testing/tiny-Qwen3ForCausalLM",
+ max_seq_length = 512,
+ load_in_4bit = False,
+ dtype = torch.bfloat16,
+ **kwargs,
+ )
+ model = FastLanguageModel.get_peft_model(
+ model,
+ r = 8,
+ lora_alpha = 16,
+ lora_dropout = 0.0,
+ random_state = 0,
+ target_modules = [
+ "q_proj",
+ "k_proj",
+ "v_proj",
+ "o_proj",
+ "gate_proj",
+ "up_proj",
+ "down_proj",
+ ],
+ use_gradient_checkpointing = "unsloth",
+ )
+ try:
+ from unsloth_zoo import tiling_registry
+ except ImportError: # a zoo with the previous TiledMLP: the training loop below is the check
+ tiling_registry = None
+ if tiling_registry is not None:
+ assert tiling_registry.tiled_modules(model)
+ block = __import__("unsloth.models._block_compile", fromlist = ["_IN_COMPILED_REGION"])
+ assert hasattr(block, "_IN_COMPILED_REGION")
+ model.train()
+ params = [p for p in model.parameters() if p.requires_grad]
+ opt = torch.optim.AdamW(params, lr = 1e-4)
+ ids = torch.randint(10, 500, (1, 256), generator = torch.Generator().manual_seed(1)).cuda()
+ for _ in range(2):
+ hidden = model.base_model.model.model(input_ids = ids).last_hidden_state
+ loss = hidden.float().pow(2).mean()
+ loss.backward()
+ assert torch.isfinite(loss)
+ assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in params)
+ opt.step()
+ opt.zero_grad()
+ out = capfd.readouterr()
+ text = out.out + out.err
+ assert "compiling each transformer block as one region" in text
+ assert "block compile failed" not in text
diff --git a/tests/test_tiling_ddp.py b/tests/test_tiling_ddp.py
new file mode 100644
index 00000000000..74d77e6b4ba
--- /dev/null
+++ b/tests/test_tiling_ddp.py
@@ -0,0 +1,148 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Tiled MLP under 2-rank gloo DDP matches untiled grads with no DDP patch; grad hooks fire once per backward."""
+
+import os
+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)
+
+_MODES = {
+ "default": {},
+ "find_unused_parameters": {"find_unused_parameters": True},
+ "static_graph": {"static_graph": True},
+ "gradient_as_bucket_view": {"gradient_as_bucket_view": True},
+}
+
+
+def _registry():
+ 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
+ tiling_registry = pytest.importorskip(
+ "unsloth_zoo.tiling_registry"
+ ) # an older zoo has no registry
+ return tiling_registry
+
+
+class FooMLP(torch.nn.Module):
+ def __init__(self):
+ 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)
+
+ def forward(self, x):
+ return self.down(torch.nn.functional.gelu(self.up(x))) + self.frozen(x)
+
+
+def _model(tiled):
+ m = FooMLP()
+ if tiled:
+ _registry().install_module(m, "rows:8")
+ return m
+
+
+def _inputs(rank, step, frozen):
+ g = torch.Generator().manual_seed(100 + rank)
+ x = torch.randn(2, 16, 8, generator = g) * (step + 1)
+ return x if frozen else x.requires_grad_(True)
+
+
+def _grads(model, x):
+ out = [p.grad.tolist() for p in model.parameters() if p.requires_grad]
+ return out + ([x.grad.tolist()] if x.requires_grad else [])
+
+
+def _worker(rank, init_file, queue):
+ try:
+ if not torch.cuda.is_available():
+ os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = "1"
+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = 2)
+ out = {}
+ for mode, ddp_kwargs in _MODES.items():
+ for frozen in (False, True):
+ key = f"{mode}/{frozen}"
+ try:
+ inner = _model(tiled = True)
+ fired = {}
+ for name, p in inner.named_parameters():
+ if p.requires_grad:
+ p.register_hook(
+ lambda g, name = name: (
+ fired.__setitem__(name, fired.get(name, 0) + 1) or g
+ )
+ )
+ model = torch.nn.parallel.DistributedDataParallel(inner, **ddp_kwargs)
+ out[key] = []
+ for step in range(3):
+ model.zero_grad(set_to_none = True)
+ fired.clear()
+ x = _inputs(rank, step, frozen)
+ model(x).pow(2).sum().backward()
+ assert all(v == 1 for v in fired.values()) and len(fired) == 4, fired
+ out[key].append(_grads(model.module, x))
+ except Exception as e:
+ out[key] = repr(e)
+ queue.put((rank, out))
+ except Exception as e:
+ queue.put((rank, {"error": repr(e)}))
+ finally:
+ if dist.is_initialized():
+ dist.destroy_process_group()
+
+
+def _reference(rank, step, frozen):
+ model = _model(tiled = False)
+ xs = [_inputs(r, step, frozen) 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):
+ _registry() # skips here, before spawning, on a zoo without the registry
+ 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]("frozen", [False, True])
[email protected]("mode", list(_MODES))
+def test_tiled_mlp_ddp_grads_match_untiled(mode, frozen, ddp_grads):
+ for rank, by_mode in ddp_grads.items():
+ assert "error" not in by_mode, by_mode
+ grads = by_mode[f"{mode}/{frozen}"]
+ assert not isinstance(grads, str), grads
+ for step, got in enumerate(grads):
+ want = _reference(rank, step, frozen)
+ assert len(got) == len(want)
+ for a, b in zip(got, want):
+ torch.testing.assert_close(torch.tensor(a), torch.tensor(b), rtol = 1e-4, atol = 1e-4)
diff --git a/tests/test_tiling_integration.py b/tests/test_tiling_integration.py
new file mode 100644
index 00000000000..f714814cf09
--- /dev/null
+++ b/tests/test_tiling_integration.py
@@ -0,0 +1,276 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Unsloth side of sequence tiling. CPU only; unsloth/tiling.py is loaded by path (no GPU init)."""
+
+import ast
+import importlib.util
+import pathlib
+import types
+
+import pytest
+import torch
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+registry = pytest.importorskip("unsloth_zoo.tiling_registry")
+
+
+def _tiling():
+ spec = importlib.util.spec_from_file_location(
+ "_unsloth_tiling_under_test", ROOT / "unsloth" / "tiling.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class FooMLP(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.up = torch.nn.Linear(8, 16)
+ self.down = torch.nn.Linear(16, 8)
+
+ def forward(self, x):
+ return self.down(torch.nn.functional.gelu(self.up(x)))
+
+
+def _model(n = 2):
+ model = torch.nn.Module()
+ model.layers = torch.nn.ModuleList([torch.nn.Module() for _ in range(n)])
+ for layer in model.layers:
+ layer.mlp = FooMLP()
+ return model
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_TILED_MLP", raising = False)
+ monkeypatch.delenv("UNSLOTH_TILED_MLP_MODULES", raising = False)
+ yield
+
+
+ ("env", "kwarg", "want"),
+ [
+ (None, False, None),
+ (None, None, None),
+ (None, True, True),
+ (None, "auto", "auto"),
+ (None, "rows:256", "rows:256"),
+ (None, "0", None),
+ ("0", False, None),
+ ("0", True, True), # old behaviour: the kwarg turns it on even with UNSLOTH_TILED_MLP=0
+ ("arctic", False, "arctic"),
+ ("1", False, "1"),
+ ("target", False, "target"),
+ ("target:2", True, "target:2"),
+ ("target:2:mlp,ffn", False, "target:2:mlp,ffn"),
+ ("auto", "rows:8", "auto"), # the environment wins over the kwarg, as before
+ ("false", True, True),
+ ("off", True, True),
+ ("No", True, True),
+ ("none", True, True),
+ ("FALSE", False, None),
+ (None, 0, None),
+ (None, "false", None),
+ (None, "Off", None),
+ (None, "no", None),
+ (None, "none", None),
+ ],
+)
+def test_loader_mode_spellings(monkeypatch, env, kwarg, want):
+ if env is not None:
+ monkeypatch.setenv("UNSLOTH_TILED_MLP", env)
+ tiling = _tiling()
+ assert tiling.resolve_loader_mode(kwarg) == want
+ if want is not None:
+ assert registry.parse_mode(want) is not None # every accepted spelling parses
+
+
+def test_loader_tile_mlp_installs_and_reports(capsys):
+ tiling = _tiling()
+ model = _model()
+ assert tiling.loader_tile_mlp(model, False) is None and not registry.tiled_modules(model)
+ report = tiling.loader_tile_mlp(model, True)
+ assert len(report.tiled) == 2 and "Tiled MLP (auto) on 2 modules" in capsys.readouterr().out
+
+
+def test_tile_mlp_and_untile_mlp():
+ tiling = _tiling()
+ model = _model()
+ x = torch.randn(2, 9, 8)
+ want = sum(layer.mlp(x) for layer in model.layers)
+ report = tiling.tile_mlp(model, rows = 2, verbose = False)
+ assert report.plan.mode == "rows" and len(registry.tiled_modules(model)) == 2
+ torch.testing.assert_close(sum(layer.mlp(x) for layer in model.layers), want)
+ assert tiling.tile_mlp(model, target_gb = 1.5, verbose = False).plan.target_gb == 1.5
+ assert len(tiling.tile_mlp(model, rows = 2, modules = ["layers.0.mlp"], verbose = False).tiled) == 1
+ assert registry.is_tiled(model.layers[0].mlp) and not registry.is_tiled(model.layers[1].mlp)
+ with pytest.raises(ValueError):
+ tiling.tile_mlp(model, rows = 2, target_gb = 1.0)
+ assert tiling.untile_mlp(model) == 1
+ assert not registry.tiled_modules(model)
+ torch.testing.assert_close(sum(layer.mlp(x) for layer in model.layers), want)
+
+
[email protected]("off", ["0", "false", "OFF", "no", "none"])
+def test_tile_mlp_ignores_a_disabled_environment(monkeypatch, off):
+ monkeypatch.setenv("UNSLOTH_TILED_MLP", off)
+ assert _tiling().tile_mlp(_model(), verbose = False).plan.mode == "auto"
+ monkeypatch.setenv("UNSLOTH_TILED_MLP", "rows:4")
+ assert _tiling().tile_mlp(_model(), verbose = False).plan.rows == 4
+
+
+def test_trainer_revalidation_covers_peft_added_modules():
+ peft = pytest.importorskip("peft")
+ tiling = _tiling()
+ model = _model()
+ tiling.loader_tile_mlp(model, "rows:2")
+ model = peft.get_peft_model(
+ model, peft.LoraConfig(r = 2, target_modules = ["up", "down"], lora_dropout = 0.1)
+ )
+ extra = torch.nn.Module()
+ extra.mlp = FooMLP()
+ model.base_model.model.layers.append(extra)
+ report = tiling.revalidate_for_trainer(types.SimpleNamespace(model = model))
+ assert len(report.tiled) == 3 and registry.is_tiled(extra.mlp)
+ assert tiling.revalidate_for_trainer(types.SimpleNamespace(model = _model())) is None
+ assert tiling.revalidate_for_trainer(types.SimpleNamespace(model = None)) is None
+ model.train()
+ x = torch.randn(2, 9, 8)
+ out = sum(layer.mlp(x) for layer in model.base_model.model.layers)
+ out.sum().backward()
+ lora = [p for n, p in model.named_parameters() if "lora_B" in n]
+ assert lora and all(p.grad is not None for p in lora)
+
+
+def _calls(path, name):
+ tree = ast.parse((ROOT / path).read_text())
+ return [
+ n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, "id", None) == name
+ ]
+
+
+def test_loader_call_sites_use_the_new_install():
+ src = (ROOT / "unsloth" / "models" / "loader.py").read_text()
+ assert "_tiled_mlp_ddp" not in src and "patch_tiled_mlp" not in src
+ calls = _calls("unsloth/models/loader.py", "loader_tile_mlp")
+ assert len(calls) == 2 # FastLanguageModel and FastModel
+ for call in calls:
+ assert [getattr(a, "id", None) for a in call.args] == ["model", "unsloth_tiled_mlp"]
+ assert not (ROOT / "unsloth" / "models" / "_tiled_mlp_ddp.py").exists()
+
+
+def test_trainer_init_revalidates():
+ tree = ast.parse((ROOT / "unsloth" / "models" / "_utils.py").read_text())
+ init = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_trainer_init"
+ )
+ names = [getattr(n.func, "id", None) for n in ast.walk(init) if isinstance(n, ast.Call)]
+ assert "revalidate_for_trainer" in names
+ order = [n for n in names if n in ("_original_trainer_init", "revalidate_for_trainer")]
+ assert order.index("_original_trainer_init") < order.index("revalidate_for_trainer")
+
+
+def test_sentence_transformer_passes_the_kwarg_through():
+ tree = ast.parse((ROOT / "unsloth" / "models" / "sentence_transformer.py").read_text())
+ passed = [
+ kw
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ for kw in n.keywords
+ if kw.arg == "unsloth_tiled_mlp" and getattr(kw.value, "id", None) == "unsloth_tiled_mlp"
+ ]
+ assert passed
+
+
+def test_package_exports_tile_mlp_on_every_backend():
+ tree = ast.parse((ROOT / "unsloth" / "__init__.py").read_text())
+ top = [
+ n
+ for n in tree.body
+ if isinstance(n, ast.ImportFrom) and n.module == "tiling" and n.level == 1
+ ]
+ assert top and {a.name for a in top[0].names} == {"tile_mlp", "untile_mlp"}
+
+
[email protected]("off", [False, None, 0, "0", "false", "no"])
+def test_tiling_off_never_imports_the_registry(monkeypatch, off):
+ import sys
+
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.tiling_registry", None)
+ tiling = _tiling()
+ tiling.check_tiling_available(off)
+ assert tiling.loader_tile_mlp(_model(), off) is None
+
+
+ ("env", "kwarg"), [(None, True), (None, "auto"), ("arctic", False), ("0", True)]
+)
+def test_tiling_on_without_the_registry_fails_fast(monkeypatch, env, kwarg):
+ import sys
+
+ if env is not None:
+ monkeypatch.setenv("UNSLOTH_TILED_MLP", env)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.tiling_registry", None)
+ with pytest.raises(ImportError, match = "newer unsloth_zoo"):
+ _tiling().check_tiling_available(kwarg)
+
+
+def test_loaders_check_the_registry_before_loading_weights():
+ tree = ast.parse((ROOT / "unsloth" / "models" / "loader.py").read_text())
+ loaders = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef)
+ and n.name == "from_pretrained"
+ and any(
+ getattr(c.func, "id", None) == "loader_tile_mlp"
+ for c in ast.walk(n)
+ if isinstance(c, ast.Call)
+ )
+ ]
+ assert len(loaders) == 2 # FastLanguageModel and FastModel
+ for fn in loaders:
+ calls = [c for c in ast.walk(fn) if isinstance(c, ast.Call)]
+ check = [c.lineno for c in calls if getattr(c.func, "id", None) == "check_tiling_available"]
+ loads = [c.lineno for c in calls if getattr(c.func, "attr", None) == "from_pretrained"]
+ assert check and loads and min(check) < min(loads)
+
+
+def test_model_init_revalidates_the_fresh_model():
+ tree = ast.parse((ROOT / "unsloth" / "models" / "_utils.py").read_text())
+ fn = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_call_model_init"
+ )
+ calls = [
+ c
+ for c in ast.walk(fn)
+ if isinstance(c, ast.Call) and getattr(c.func, "id", None) == "revalidate_for_trainer"
+ ]
+ assert calls and [getattr(a, "id", None) for a in calls[0].args] == ["self", "model"]
+
+
+def test_revalidate_for_trainer_takes_the_model_explicitly():
+ tiling = _tiling()
+ model = _model()
+ tiling.tile_mlp(model, rows = 2, verbose = False)
+ model.layers.append(torch.nn.Module())
+ model.layers[-1].mlp = FooMLP()
+ trainer = types.SimpleNamespace(model = _model()) # still the previous instance
+ tiling.revalidate_for_trainer(trainer, model)
+ assert len(registry.tiled_modules(model)) == 3
+
+
+def test_tile_mlp_on_an_mlx_model_says_it_is_unsupported():
+ from unsloth.tiling import tile_mlp, untile_mlp
+
+ MlxModule = type("Module", (), {"__module__": "mlx.nn.layers.base"})
+ model = type("Model", (MlxModule,), {})()
+ for fn in (tile_mlp, untile_mlp):
+ with pytest.raises(NotImplementedError, match = "not supported on MLX"):
+ fn(model)
diff --git a/tests/vllm_compat/test_extended_module_imports.py b/tests/vllm_compat/test_extended_module_imports.py
index b17149cc418..768ed62d40e 100644
--- a/tests/vllm_compat/test_extended_module_imports.py
+++ b/tests/vllm_compat/test_extended_module_imports.py
@@ -86,12 +86,15 @@ _ZOO_VLLM_FREE_MODULES = [
"unsloth_zoo.llama_cpp",
"unsloth_zoo.logging_utils",
"unsloth_zoo.loss_utils",
+ "unsloth_zoo.memory_budget",
"unsloth_zoo.patching_utils",
"unsloth_zoo.patch_torch_functions",
"unsloth_zoo.peft_utils",
"unsloth_zoo.rl_replacements",
"unsloth_zoo.saving_utils",
+ "unsloth_zoo.sequence_tiling",
"unsloth_zoo.tiled_mlp",
+ "unsloth_zoo.tiling_registry",
"unsloth_zoo.tokenizer_utils",
"unsloth_zoo.training_utils",
"unsloth_zoo.utils",
@@ -132,6 +135,7 @@ _UNSLOTH_CORE_MODULES = [
"unsloth.models.loader",
"unsloth.models.loader_utils",
"unsloth.models.mapper",
+ "unsloth.tiling",
]
diff --git a/unsloth/__init__.py b/unsloth/__init__.py
index 9b23c0cb492..3354d3c9edc 100644
--- a/unsloth/__init__.py
+++ b/unsloth/__init__.py
@@ -1760,6 +1760,8 @@ else:
pass
+from .tiling import tile_mlp, untile_mlp
+
# A pip --target / PYTHONPATH layout makes dill pickle modules by value, breaking dataset fingerprints.
try:
from .import_fixes import fix_dill_module_by_value_pickling as _fix_dill
diff --git a/unsloth/models/_tiled_mlp_ddp.py b/unsloth/models/_tiled_mlp_ddp.py
deleted file mode 100644
index d28f7782437..00000000000
--- a/unsloth/models/_tiled_mlp_ddp.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# 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/_utils.py b/unsloth/models/_utils.py
index 17290f187e6..2bdb7d97719 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -6403,6 +6403,11 @@ def patch_gradient_accumulation_fix(Trainer):
if not keep_fused:
from .llama import _decline_fused_lora_for_fsdp
_decline_fused_lora_for_fsdp(getattr(self, "model", None), reason)
+ try:
+ from ..tiling import revalidate_for_trainer
+ revalidate_for_trainer(self)
+ except Exception as e:
+ logger.warning_once(f"Unsloth: tiled MLP revalidation skipped ({e})")
_replan_auto_offload_safely(self)
_size_auto_checkpoint_skip_for_trainer(self)
_block_swap_for_trainer_backend(self)
@@ -6431,6 +6436,11 @@ def patch_gradient_accumulation_fix(Trainer):
model = _original_call_model_init(self, *args, **kwargs)
_refuse_tensor_parallel_for_trainer(model)
_tensor_subclass_weights_for_ddp(self, model)
+ try:
+ from ..tiling import revalidate_for_trainer
+ revalidate_for_trainer(self, model)
+ except Exception as e:
+ logger.warning_once(f"Unsloth: tiled MLP revalidation skipped ({e})")
return model
_unsloth_call_model_init._unsloth_marks_ddp_ignores = True
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 172f280972e..5fcb2e55d1b 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -3386,14 +3386,55 @@ def _fused_lora_modules(model) -> list:
):
fused.append(module)
continue
- for name in ("forward", "_unsloth_forward"):
- func = getattr(module.__dict__.get(name), "__func__", None)
- if getattr(func, "func", func) in _FUSED_LORA_MLPS:
- fused.append(module)
- break
+ if _fused_lora_mlp_slot(module) is not None:
+ fused.append(module)
return fused
+# `_old_forward`: an accelerate hook calls it, so the kernel can live behind the hook.
+_MLP_FORWARD_SLOTS = ("forward", "_unsloth_forward", "_old_forward", "_orig_moe_forward")
+
+
+def _is_fused_lora_mlp(fn) -> bool:
+ func = getattr(fn, "__func__", None)
+ return getattr(func, "func", func) in _FUSED_LORA_MLPS
+
+
+def _fused_lora_mlp_slot(module):
+ d = getattr(module, "__dict__", {})
+ for name in _MLP_FORWARD_SLOTS:
+ if _is_fused_lora_mlp(d.get(name)):
+ return name
+ return None
+
+
+_PRE_FUSED_FORWARD = "_unsloth_forward_before_fused_lora"
+
+
+def _install_fused_lora_mlp(mlp_module, kernel):
+ """Bind the kernel into `_old_forward` (accelerate hook), `_unsloth_forward` (tiled) or `forward`."""
+ d = mlp_module.__dict__
+ if "_hf_hook" in d and "_old_forward" in d:
+ slot = "_old_forward"
+ elif hasattr(mlp_module, "_unsloth_forward"):
+ slot = "_unsloth_forward"
+ else:
+ slot = "forward"
+ current = d.get(slot)
+ if _PRE_FUSED_FORWARD not in d and not _is_fused_lora_mlp(current):
+ # Class forward is recorded as None: restored unbound into `forward` it would drop `self`. A plain
+ # instance function already takes x: partial() stops a tiled inner slot binding `self` again.
+ if current is type(mlp_module).forward:
+ previous = None
+ elif slot == "forward" and isinstance(current, types.FunctionType):
+ previous = functools.partial(current)
+ else:
+ previous = current
+ d[_PRE_FUSED_FORWARD] = previous
+ setattr(mlp_module, slot, types.MethodType(kernel, mlp_module))
+ return True
+
+
def _decline_fused_lora_for_fsdp(model, reason = None) -> int:
"""Put peft's forwards back on layers patch_peft_model gave a fused LoRA kernel.
@@ -3411,14 +3452,25 @@ def _decline_fused_lora_for_fsdp(model, reason = None) -> int:
if getattr(module, "apply_o", None) is apply_lora_o:
module.apply_o = original_apply_o
n += 1
- for name in ("forward", "_unsloth_forward"):
- func = getattr(module.__dict__.get(name), "__func__", None)
- if getattr(func, "func", func) not in _FUSED_LORA_MLPS:
+ for name in _MLP_FORWARD_SLOTS:
+ if not _is_fused_lora_mlp(module.__dict__.get(name)):
continue
+ previous = module.__dict__.pop(_PRE_FUSED_FORWARD, None)
+ if previous is type(module).forward:
+ previous = None
if name == "forward":
- delattr(module, "forward")
+ if previous is None:
+ delattr(module, "forward")
+ else:
+ module.forward = previous
+ elif name == "_unsloth_forward":
+ module._unsloth_forward = module.__class__.forward if previous is None else previous
else:
- module._unsloth_forward = module.__class__.forward
+ module.__dict__[name] = (
+ types.MethodType(module.__class__.forward, module)
+ if previous is None
+ else previous
+ )
n += 1
if n:
if reason is None:
@@ -3438,9 +3490,11 @@ def _fused_lora_layers(layers, mlp_function):
if getattr(getattr(layer, "self_attn", None), "apply_qkv", None) is apply_lora_qkv
or getattr(getattr(layer, "self_attn", None), "apply_o", None) is apply_lora_o
or any(
- getattr(getattr(getattr(layer, "mlp", None), name, None), "__func__", None)
+ getattr(
+ getattr(getattr(layer, "mlp", None), "__dict__", {}).get(name), "__func__", None
+ )
is mlp_function
- for name in ("forward", "_unsloth_forward")
+ for name in _MLP_FORWARD_SLOTS
)
]
@@ -5371,14 +5425,7 @@ class FastLlamaModel:
and not _fast_lora.lora_bias_blocks_fused(up_proj)
and not _fast_lora.lora_bias_blocks_fused(down_proj)
):
- # MethodType binds the replacement; see stackoverflow.com/questions/50599045.
- if hasattr(mlp_module, "_unsloth_forward"):
- # _unsloth_forward identifies an existing TiledMLP patch.
- mlp_module._unsloth_forward = types.MethodType(
- _apply_lora_mlp, mlp_module
- )
- else:
- mlp_module.forward = types.MethodType(_apply_lora_mlp, mlp_module)
+ _install_fused_lora_mlp(mlp_module, _apply_lora_mlp)
n_mlp += 1
else:
logger.warning_once(
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 121d2b9dffd..5a85254c007 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -100,8 +100,7 @@ from ..device_type import (
from unsloth_zoo.utils import Version, _get_dtype
from unsloth_zoo.hf_utils import dtype_from_config
-from unsloth_zoo.tiled_mlp import patch_tiled_mlp
-from ._tiled_mlp_ddp import patch_tiled_mlp_for_ddp
+from ..tiling import check_tiling_available, loader_tile_mlp
transformers_version = Version(transformers_version)
SUPPORTS_FOURBIT = transformers_version >= Version("4.37")
@@ -1310,6 +1309,8 @@ class FastLanguageModel(FastLlamaModel):
load_in_8bit = True
load_in_4bit = False
+ # Fail before any weights load.
+ check_tiling_available(unsloth_tiled_mlp)
# Login to allow private models. Before normalization: dtype is also derived below from a 4bit config's compute dtype, which is not a request for the whole model.
user_float32 = _requested_float32(dtype)
token = hf_login(token)
@@ -2140,14 +2141,7 @@ class FastLanguageModel(FastLlamaModel):
except Exception:
pass # optional speedup; never block model loading
- # Patch Tiled MLP; enable by setting UNSLOTH_TILED_MLP to "arctic", "target", or "target:{GB}".
- patch_tiled_mlp_choice = os.environ.get(
- "UNSLOTH_TILED_MLP", "arctic" if unsloth_tiled_mlp else "0"
- )
- 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()
+ loader_tile_mlp(model, unsloth_tiled_mlp)
model = _fix_rope_inv_freq(model)
model = _exclude_rope_inv_freq_from_ddp(model)
@@ -2295,6 +2289,8 @@ class FastModel(FastBaseModel):
load_in_8bit = True
load_in_4bit = False
+ # Fail before any weights load.
+ check_tiling_available(unsloth_tiled_mlp)
# Login to allow private models. Before normalization: dtype is also derived below from a 4bit config's compute dtype, which is not a request for the whole model.
user_float32 = _requested_float32(dtype)
token = hf_login(token)
@@ -3633,14 +3629,7 @@ class FastModel(FastBaseModel):
print("Unsloth: Applying QAT to mitigate quantization degradation")
model = FastModel._prepare_for_qat(model, qat_scheme)
- # Patch Tiled MLP; enable by setting UNSLOTH_TILED_MLP to "arctic", "target", or "target:{GB}".
- patch_tiled_mlp_choice = os.environ.get(
- "UNSLOTH_TILED_MLP", "arctic" if unsloth_tiled_mlp else "0"
- )
- 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()
+ loader_tile_mlp(model, unsloth_tiled_mlp)
model = _fix_rope_inv_freq(model)
model = _exclude_rope_inv_freq_from_ddp(model)
diff --git a/unsloth/tiling.py b/unsloth/tiling.py
new file mode 100644
index 00000000000..15145877574
--- /dev/null
+++ b/unsloth/tiling.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Sequence tiling (tiled MLP): `unsloth.tile_mlp(model)` / `unsloth.untile_mlp(model)`.
+
+Tensor parallel modules stay untiled (a row-parallel all-reduce would run once per tile) unless UNSLOTH_TILED_MLP_TP=1.
+"""
+
+import os
+
+__all__ = ["tile_mlp", "untile_mlp"]
+
+_ENV = "UNSLOTH_TILED_MLP"
+
+
+_OFF = ("", "0", "false", "off", "no", "none")
+
+
+def _is_off(value):
+ if value is None or value is False:
+ return True
+ if isinstance(value, bool):
+ return False
+ if isinstance(value, (int, float)):
+ return value == 0
+ if isinstance(value, str):
+ return value.strip().lower() in _OFF
+ return False
+
+
+def _env_mode():
+ env = os.environ.get(_ENV, "").strip()
+ return None if _is_off(env) else env
+
+
+def _registry():
+ import importlib
+ try:
+ tiling_registry = importlib.import_module("unsloth_zoo.tiling_registry")
+ except ImportError as e:
+ raise ImportError(
+ "Unsloth: tiled MLP needs a newer unsloth_zoo (unsloth_zoo.tiling_registry); "
+ "update with `pip install --upgrade unsloth_zoo`"
+ ) from e
+ return tiling_registry
+
+
+def _refuse_mlx(model):
+ if any(
+ (getattr(c, "__module__", "") or "").split(".")[0] == "mlx" for c in type(model).__mro__
+ ):
+ raise NotImplementedError(
+ "Unsloth: tiled MLP (tile_mlp / untile_mlp) needs a PyTorch model and is not supported on MLX."
+ )
+
+
+def tile_mlp(
+ model,
+ rows = None,
+ target_gb = None,
+ modules = None,
+ mode = None,
+ verbose = True,
+):
+ """Tile every eligible MLP / MoE / projector in `model`; idempotent. Returns the coverage report."""
+ _refuse_mlx(model)
+ if rows is not None and target_gb is not None:
+ raise ValueError("Unsloth: tile_mlp takes rows or target_gb, not both")
+ if rows is not None:
+ mode = f"rows:{int(rows)}"
+ elif target_gb is not None:
+ mode = f"target:{float(target_gb)}"
+ elif mode is None:
+ # An explicit call wins over a disabled environment.
+ env = _env_mode()
+ mode = env if env is not None else True
+ return _registry().install(model, mode, modules = modules, verbose = verbose)
+
+
+def untile_mlp(model):
+ """Undo `tile_mlp`; returns the number of modules restored."""
+ _refuse_mlx(model)
+ return _registry().uninstall(model)
+
+
+def resolve_loader_mode(unsloth_tiled_mlp):
+ """A set UNSLOTH_TILED_MLP wins; an off environment never overrides an explicit kwarg."""
+ env = _env_mode()
+ if env is not None:
+ return env
+ return None if _is_off(unsloth_tiled_mlp) else unsloth_tiled_mlp
+
+
+def check_tiling_available(unsloth_tiled_mlp):
+ """Fail fast before weights load; tiling off never imports the registry."""
+ if resolve_loader_mode(unsloth_tiled_mlp) is not None:
+ _registry()
+
+
+def loader_tile_mlp(model, unsloth_tiled_mlp):
+ mode = resolve_loader_mode(unsloth_tiled_mlp)
+ if mode is None:
+ return None
+ return _registry().install(model, mode)
+
+
+def revalidate_for_trainer(trainer, model = None):
+ if model is None:
+ model = getattr(trainer, "model", None)
+ if model is None:
+ return None
+ try:
+ return _registry().revalidate(model)
+ except ImportError:
+ return None