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
Studio: keep diffusion LoRA loading working on torchao 0.18 with peft 0.18 (#12494)
Daniel Han38d48d3e8ac3
diff --git a/studio/backend/core/inference/diffusion_torchao_patches.py b/studio/backend/core/inference/diffusion_torchao_patches.pyindex dacb1922e05..2916fd82f6b 100644--- a/studio/backend/core/inference/diffusion_torchao_patches.py+++ b/studio/backend/core/inference/diffusion_torchao_patches.py@@ -14,11 +14,13 @@ subclasses and never calls ``quantize_``.from __future__ import annotationsimport functools+import importlibimport importlib.abcimport importlib.utilimport inspectimport loggingimport os+import reimport syslogger = logging.getLogger(__name__)@@ -209,6 +211,12 @@ def install_torchao_int_mm_patch():"""Install the capture-safe ``safe_int_mm`` if torchao is present; idempotent, so several modules may eachask for it. ``UNSLOTH_TORCHAO_INT_MM_FIX=0`` keeps upstream's behaviour. True when patched or the finder wasinstalled, False when there is nothing to do, None when torchao is absent or the fix is off."""+ # Every diffusion, video and diffusion-training entry point calls this, so it also carries the+ # peft LoRA guard, which is independent of the int_mm switch.+ try:+ install_peft_torchao_dispatch_guard()+ except Exception:+ passif os.environ.get(_TORCHAO_INT_MM_ENV, "1").strip() == "0":return Nonetry:@@ -232,3 +240,255 @@ def install_torchao_int_mm_patch():return patched_nowsys.meta_path.insert(0, _TorchaoIntmmPatchFinder())return True+++# Studio's copy of ``unsloth/import_fixes.py::fix_peft_torchao_missing_tensor_subclass`` (#11168), for the+# same reason as the int_mm copy above: the diffusion process never runs ``unsloth/__init__``, so the+# original never reaches ``pipe.load_lora_weights``. peft <= 0.18 imports LinearActivationQuantizedTensor+# inside ``dispatch_torchao`` for every LoRA target, torchao 0.18 deleted it, and Studio installs torchao+# 0.18 on torch >= 2.12, so every diffusion LoRA load raised. Both copies mark their wrapper+# ``__unsloth_patched__``, so whichever runs second leaves the first in place.+# Matches both spellings a torchao removal produces: the class name, and the module that used to+# define it. Only these two, so a torchao that is BROKEN rather than newer still raises.+_PEFT_TORCHAO_MISSING_TENSOR_SUBCLASS = re.compile(+ r"linear_?activation_?quantized_?tensor|affine_?quantized_?tensor",+ re.IGNORECASE | re.DOTALL,+)+++# The two imports `dispatch_torchao` performs, in upstream's order.+_PEFT_TORCHAO_TENSOR_SUBCLASSES = (+ ("torchao.dtypes", "AffineQuantizedTensor"),+ ("torchao.quantization", "LinearActivationQuantizedTensor"),+)+++def _peft_torchao_tensor_subclasses():+ """``(classes, missing)`` for the two subclasses `dispatch_torchao` checks: a tuple usable as+ the second argument of ``isinstance``, plus the names that are gone. Only a failure naming one+ of those two counts as gone; anything else is a broken install and is re-raised."""+ classes = []+ missing = []+ for module_name, class_name in _PEFT_TORCHAO_TENSOR_SUBCLASSES:+ try:+ classes.append(getattr(importlib.import_module(module_name), class_name))+ except (ImportError, AttributeError) as exc:+ if _PEFT_TORCHAO_MISSING_TENSOR_SUBCLASS.search(str(exc)) is None:+ raise+ missing.append(class_name)+ return tuple(classes), tuple(missing)+++def _guard_peft_torchao_dispatcher(original):+ """Wrap one `dispatch_torchao` so a removed tensor subclass costs only that class.++ The wrapper calls through, so a torchao shipping both classes behaves exactly as upstream.+ Only on a failure naming one of the two does it redo upstream's work against the classes that+ remain, so an AffineQuantizedTensor weight still gets a TorchaoLoraLinear.+ """+ warned = [False]+ # The defining module's own globals, so the degraded path uses the very objects upstream would+ # have, including an is_torchao_available already patched by the sibling fix.+ namespace = getattr(original, "__globals__", None)+ if not isinstance(namespace, dict):+ namespace = {}++ def _upstream(name, module_name):+ value = namespace.get(name, None)+ if value is not None:+ return value+ return getattr(importlib.import_module(module_name), name, None)++ def _redo_dispatch(classes, args, kwargs):+ """Upstream's body, with `classes` standing in for the two-class isinstance tuple.++ Arguments are read by POSITION because peft 0.19 renamed the third parameter from+ `lora_config` to `config`, and forwarded as `target, adapter_name, **kwargs`, which is+ exactly how peft <= 0.18 builds TorchaoLoraLinear.+ """+ try:+ signature = inspect.signature(original)+ bound = signature.bind(*args, **kwargs)+ bound.apply_defaults()+ arguments = dict(bound.arguments)+ except (TypeError, ValueError):+ return None+ positional = [+ name+ for name, parameter in signature.parameters.items()+ if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD)+ ]+ layer_kwargs = {}+ for name, parameter in signature.parameters.items():+ if parameter.kind is parameter.VAR_KEYWORD:+ layer_kwargs = dict(arguments.get(name, None) or {})+ if len(positional) < 2:+ return None+ target = arguments.get(positional[0], None)+ adapter_name = arguments.get(positional[1], None)+ if target is None or adapter_name is None:+ return None++ base_tuner_layer = _upstream("BaseTunerLayer", "peft.tuners.tuners_utils")+ if base_tuner_layer is not None and isinstance(target, base_tuner_layer):+ target_base_layer = target.get_base_layer()+ else:+ target_base_layer = target+ if not hasattr(target_base_layer, "weight"):+ return None+ is_torchao_available = _upstream("is_torchao_available", "peft.import_utils")+ if is_torchao_available is not None and not is_torchao_available():+ return None+ if not classes or not isinstance(target_base_layer.weight, classes):+ return None # upstream's answer for an unrecognised weight: the loop moves on+ torchao_lora_linear = _upstream("TorchaoLoraLinear", "peft.tuners.lora.torchao")+ if torchao_lora_linear is None:+ return None+ return torchao_lora_linear(target, adapter_name, **layer_kwargs)++ @functools.wraps(original)+ def dispatch_torchao(*args, **kwargs):+ try:+ return original(*args, **kwargs)+ except ImportError as exc:+ message = str(exc)+ if _PEFT_TORCHAO_MISSING_TENSOR_SUBCLASS.search(message) is None:+ raise+ classes, missing = _peft_torchao_tensor_subclasses()+ if not missing:+ # The message named one of the two classes but both are there, so this came from+ # somewhere else in the dispatcher and is a real failure. Redoing the dispatch+ # would swallow it and re-run whatever construction already happened.+ raise+ if not warned[0]:+ warned[0] = True+ kept = ", ".join(cls.__name__ for cls in classes) or "none of them"+ logger.warning(+ f"Unsloth Studio: This torchao no longer ships "+ f"{' and '.join(missing) or 'a tensor subclass'}, which peft's "+ f"torchao LoRA dispatcher imports to run one isinstance check "+ f"({message}), so that dispatcher raised for every LoRA layer. "+ f"Studio now runs the same check against the subclasses this "+ f"torchao does ship ({kept}), so weights of those types still get "+ f"peft's torchao LoRA layer and everything else gets an ordinary "+ f"one. Only weights of the removed subclass cannot be matched; "+ f"install `torchao<0.18` if you need those."+ )+ return _redo_dispatch(classes, args, kwargs)++ dispatch_torchao.__unsloth_patched__ = True+ return dispatch_torchao+++_PEFT_LORA_DISPATCH_MODULE = "peft.tuners.lora.model"+_PEFT_TORCHAO_GUARD_SENTINEL = "__unsloth_studio_peft_torchao_guard__"+++def _patch_peft_torchao_dispatchers():+ """Wrap every loaded copy of ``dispatch_torchao``: ``peft.tuners.lora.model`` binds it by value,+ so patching the defining module alone leaves the dispatch list raising. True when anything changed."""+ wrapped = []+ patched = False+ for mod_name, mod in tuple(sys.modules.items()):+ if not mod_name.startswith("peft") or mod is None:+ continue+ original = getattr(mod, "dispatch_torchao", None)+ if original is None or not callable(original):+ continue+ if getattr(original, "__unsloth_patched__", False):+ continue+ replacement = None+ for seen, wrapper in wrapped:+ if seen is original:+ replacement = wrapper+ break+ if replacement is None:+ try:+ replacement = _guard_peft_torchao_dispatcher(original)+ except Exception:+ continue+ wrapped.append((original, replacement))+ try:+ setattr(mod, "dispatch_torchao", replacement)+ patched = True+ except Exception:+ pass+ return patched+++class _PeftLoraDispatchLoader(importlib.abc.Loader):+ """The real loader, plus the guard once ``peft.tuners.lora.model`` (and so ``.torchao``) has run."""++ __slots__ = ("_loader",)++ def __init__(self, loader):+ self._loader = loader++ def create_module(self, spec):+ create = getattr(self._loader, "create_module", None)+ if create is None:+ return None+ return create(spec)++ def exec_module(self, module):+ self._loader.exec_module(module)+ try:+ _patch_peft_torchao_dispatchers()+ except Exception:+ pass++ def __getattr__(self, attribute):+ return getattr(self._loader, attribute)+++class _PeftTorchaoGuardFinder(importlib.abc.MetaPathFinder):+ """Front of sys.meta_path, like the int_mm finder, so importing peft stays lazy."""++ __slots__ = (_PEFT_TORCHAO_GUARD_SENTINEL, "_finding")++ def __init__(self):+ setattr(self, _PEFT_TORCHAO_GUARD_SENTINEL, True)+ self._finding = False++ def find_spec(+ self,+ fullname,+ path = None,+ target = None,+ ):+ if fullname != _PEFT_LORA_DISPATCH_MODULE or self._finding:+ return None+ self._finding = True+ try:+ spec = importlib.util.find_spec(fullname)+ except Exception:+ return None+ finally:+ self._finding = False+ if spec is None or spec.loader is None or not hasattr(spec.loader, "exec_module"):+ return None+ try:+ spec.loader = _PeftLoraDispatchLoader(spec.loader)+ except Exception:+ return None+ return spec+++def install_peft_torchao_dispatch_guard():+ """Guard peft's ``dispatch_torchao`` now if peft's LoRA module is loaded, else when it is. Idempotent.+ True when patched or the finder was installed, False when there is nothing to do, None without peft."""+ try:+ if importlib.util.find_spec("peft") is None:+ return None+ except Exception:+ return None+ if _PEFT_LORA_DISPATCH_MODULE in sys.modules:+ try:+ return _patch_peft_torchao_dispatchers()+ except Exception:+ return False+ for finder in sys.meta_path:+ if getattr(finder, _PEFT_TORCHAO_GUARD_SENTINEL, False):+ return False+ sys.meta_path.insert(0, _PeftTorchaoGuardFinder())+ return Truediff --git a/studio/backend/tests/test_diffusion_peft_torchao_guard.py b/studio/backend/tests/test_diffusion_peft_torchao_guard.pynew file mode 100644index 00000000000..b12d676d425--- /dev/null+++ b/studio/backend/tests/test_diffusion_peft_torchao_guard.py@@ -0,0 +1,177 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Studio's copy of the peft ``dispatch_torchao`` guard: the diffusion process never imports unsloth,+so without it peft <= 0.18 plus torchao 0.18 raises on every diffusion LoRA load."""++from __future__ import annotations++import ast+import importlib+import sys+import types+from pathlib import Path++import pytest++import core.inference.diffusion_torchao_patches as patches++_REPO_ROOT = Path(__file__).resolve().parents[3]+_IMPORT_FIXES = _REPO_ROOT / "unsloth" / "import_fixes.py"+_PATCH_MODULE = Path(patches.__file__)++_REMOVED = "cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'"++# The Studio copy differs from unsloth's only in who the warning says is speaking.+_WORDING = (("Unsloth Studio: ", "Unsloth: "), ("Studio now runs", "Unsloth now runs"))+++def _function_dump(path: Path, name: str) -> str:+ source = path.read_text(encoding = "utf-8")+ for studio, unsloth in _WORDING:+ source = source.replace(studio, unsloth)+ for node in ast.parse(source).body:+ if isinstance(node, ast.FunctionDef) and node.name == name:+ if node.body and isinstance(node.body[0], ast.Expr):+ if isinstance(getattr(node.body[0], "value", None), ast.Constant):+ node.body = node.body[1:]+ return ast.dump(node)+ raise AssertionError(f"{path} has no top-level def {name}")+++ "name", ("_peft_torchao_tensor_subclasses", "_guard_peft_torchao_dispatcher")+)+def test_studio_copy_matches_unsloth_import_fixes(name):+ assert _function_dump(_PATCH_MODULE, name) == _function_dump(+ _IMPORT_FIXES, name+ ), f"{name} drifted from unsloth/import_fixes.py; port the change to both copies."++[email protected](autouse = True)+def _restore_peft_dispatchers(monkeypatch):+ """The patcher wraps every loaded peft copy, real ones included. Put them back afterwards so a+ later test of unsloth's own copy in this worker still finds an unpatched dispatcher."""+ for name, module in tuple(sys.modules.items()):+ if name.startswith("peft") and module is not None and hasattr(module, "dispatch_torchao"):+ monkeypatch.setattr(module, "dispatch_torchao", module.dispatch_torchao)+ yield+++class _AffineQuantizedTensor:+ pass+++class _TorchaoLoraLinear:+ def __init__(self, target, adapter_name, **kwargs):+ self.target, self.adapter_name, self.kwargs = target, adapter_name, kwargs+++def fake_peft(monkeypatch):+ """A torchao that lost LinearActivationQuantizedTensor, and a peft whose dispatcher imports it."""+ dtypes = types.ModuleType("torchao.dtypes")+ dtypes.AffineQuantizedTensor = _AffineQuantizedTensor+ quantization = types.ModuleType("torchao.quantization")+ torchao = types.ModuleType("torchao")+ torchao.dtypes, torchao.quantization = dtypes, quantization+ for name, module in (+ ("torchao", torchao),+ ("torchao.dtypes", dtypes),+ ("torchao.quantization", quantization),+ ):+ monkeypatch.setitem(sys.modules, name, module)++ lora_torchao = types.ModuleType("peft.tuners.lora.torchao")+ namespace = {+ "is_torchao_available": lambda: True,+ "TorchaoLoraLinear": _TorchaoLoraLinear,+ "BaseTunerLayer": type("BaseTunerLayer", (), {}),+ }+ exec(+ "def dispatch_torchao(target, adapter_name, lora_config, **kwargs):\n"+ f" raise ImportError({_REMOVED!r})\n",+ namespace,+ )+ lora_torchao.__dict__.update(namespace)+ lora_model = types.ModuleType("peft.tuners.lora.model")+ lora_model.dispatch_torchao = lora_torchao.dispatch_torchao+ monkeypatch.setitem(sys.modules, "peft.tuners.lora.torchao", lora_torchao)+ monkeypatch.setitem(sys.modules, "peft.tuners.lora.model", lora_model)+ return lora_torchao, lora_model+++def test_a_plain_linear_gets_no_torchao_layer_instead_of_an_import_error(fake_peft):+ lora_torchao, lora_model = fake_peft+ original = lora_torchao.dispatch_torchao+ with pytest.raises(ImportError):+ original(types.SimpleNamespace(weight = object()), "default", None)++ assert patches._patch_peft_torchao_dispatchers() is True+ # Both bindings point at one wrapper, so the list peft actually walks is the patched one.+ assert lora_model.dispatch_torchao is lora_torchao.dispatch_torchao is not original+ assert (+ lora_model.dispatch_torchao(types.SimpleNamespace(weight = object()), "default", None) is None+ )+ # Idempotent: a second pass finds nothing left to wrap.+ assert patches._patch_peft_torchao_dispatchers() is False+++def test_a_weight_of_a_surviving_subclass_still_gets_the_torchao_layer(fake_peft):+ _, lora_model = fake_peft+ patches._patch_peft_torchao_dispatchers()+ layer = types.SimpleNamespace(weight = _AffineQuantizedTensor())+ built = lora_model.dispatch_torchao(layer, "default", None, r = 4)+ assert isinstance(built, _TorchaoLoraLinear)+ assert built.target is layer and built.adapter_name == "default" and built.kwargs == {"r": 4}+++def test_an_unrelated_import_error_still_surfaces(monkeypatch, fake_peft):+ lora_torchao, lora_model = fake_peft++ def broken(target, adapter_name, lora_config, **kwargs):+ raise ImportError("libtorchao_ops.so: cannot open shared object file")++ monkeypatch.setattr(lora_torchao, "dispatch_torchao", broken)+ monkeypatch.setattr(lora_model, "dispatch_torchao", broken)+ patches._patch_peft_torchao_dispatchers()+ with pytest.raises(ImportError, match = "shared object"):+ lora_model.dispatch_torchao(types.SimpleNamespace(weight = object()), "default", None)+++def test_the_guard_waits_for_peft_instead_of_importing_it(monkeypatch):+ monkeypatch.delitem(sys.modules, patches._PEFT_LORA_DISPATCH_MODULE, raising = False)+ monkeypatch.setattr(+ sys,+ "meta_path",+ [f for f in sys.meta_path if not getattr(f, patches._PEFT_TORCHAO_GUARD_SENTINEL, False)],+ )+ monkeypatch.setattr(+ importlib.util, "find_spec", lambda name, *a, **k: object() if name == "peft" else None+ )+ assert patches.install_peft_torchao_dispatch_guard() is True+ assert patches._PEFT_LORA_DISPATCH_MODULE not in sys.modules+ finders = [f for f in sys.meta_path if getattr(f, patches._PEFT_TORCHAO_GUARD_SENTINEL, False)]+ assert len(finders) == 1 and sys.meta_path[0] is finders[0]+ assert patches.install_peft_torchao_dispatch_guard() is False # no second finder+++def test_every_diffusion_entry_point_installs_the_guard(monkeypatch):+ """The int_mm installer is what diffusion.py, video.py, the transformer quantiser and the+ diffusion trainer already call at import, so the guard rides on it regardless of its switch."""+ calls = []+ monkeypatch.setattr(patches, "install_peft_torchao_dispatch_guard", lambda: calls.append(1))+ monkeypatch.setenv(patches._TORCHAO_INT_MM_ENV, "0")+ patches.install_torchao_int_mm_patch()+ assert calls == [1]+++def test_real_peft_lora_injection_survives_the_installed_torchao():+ peft = pytest.importorskip("peft")+ pytest.importorskip("torchao")+ torch = pytest.importorskip("torch")+ patches.install_peft_torchao_dispatch_guard()+ importlib.import_module(patches._PEFT_LORA_DISPATCH_MODULE)+ net = torch.nn.Sequential(torch.nn.Linear(8, 8))+ peft.inject_adapter_in_model(peft.LoraConfig(r = 2, target_modules = ["0"]), net)+ assert hasattr(net[0], "lora_A")