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.

Settle deferred compile-mode switches between training steps (#7955)

Daniel Han24efe618e6eb
diff --git a/tests/test_peft_stale_torchao.py b/tests/test_peft_stale_torchao.py
new file mode 100644
index 00000000000..b1af7c4914f
--- /dev/null
+++ b/tests/test_peft_stale_torchao.py
@@ -0,0 +1,258 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""An old torchao must not end LoRA creation that never touches torchao.
+
+`peft.import_utils.is_torchao_available` returns False when torchao is absent
+but raises when it is installed and older than peft's minimum, and
+`dispatch_torchao` calls it for every LoRA layer, so one stale optional
+dependency ends `get_peft_model`. FunctionGemma_(270M)-LMStudio dies this way
+on Kaggle, whose preinstalled torchao is 0.10.0; its sibling notebook survives
+the same kernel only because it upgrades torchao first.
+
+"Installed but unusable" is closer to "not installed" than to "fatal". Any
+other ImportError still propagates, including ones whose message also says
+"torchao" (missing submodule, unloadable extension), which is why the version
+complaint is matched rather than the word.
+"""
+
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO_ROOT))
+
+
+def peft_env(monkeypatch):
+ """A fake peft: import_utils plus a consumer that imported the name."""
+ saved = {k: v for k, v in sys.modules.items() if k.startswith("peft")}
+
+ def build(raiser):
+ import_utils = types.ModuleType("peft.import_utils")
+ import_utils.is_torchao_available = raiser
+ consumer = types.ModuleType("peft.tuners.lora.torchao")
+ # `from peft.import_utils import ...` binds the ORIGINAL here, and
+ # this is the copy that actually gets called.
+ consumer.is_torchao_available = raiser
+ pkg = types.ModuleType("peft")
+ pkg.__path__ = []
+ pkg.import_utils = import_utils
+ for name, mod in (
+ ("peft", pkg),
+ ("peft.import_utils", import_utils),
+ ("peft.tuners.lora.torchao", consumer),
+ ):
+ monkeypatch.setitem(sys.modules, name, mod)
+ return import_utils, consumer
+
+ yield build
+ for k in [k for k in sys.modules if k.startswith("peft")]:
+ if k not in saved:
+ sys.modules.pop(k, None)
+
+
+_WANTED = ("fix_peft_stale_torchao_import_error", "_TORCHAO_STALE_VERSION_ERROR")
+
+
+def _fix(warning = None):
+ """Load the function without importing unsloth (which needs a GPU).
+
+ The module-level regex it consults must come along, or the wrapper
+ NameErrors on the first suppressed ImportError.
+ """
+ import ast
+ import re
+
+ src = (REPO_ROOT / "unsloth" / "import_fixes.py").read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ ns = {
+ "functools": __import__("functools"),
+ "sys": sys,
+ "re": re,
+ "logger": types.SimpleNamespace(
+ warning = warning if warning is not None else (lambda *a, **k: None),
+ ),
+ }
+ for node in tree.body:
+ name = None
+ if isinstance(node, ast.FunctionDef):
+ name = node.name
+ elif isinstance(node, ast.Assign) and len(node.targets) == 1:
+ if isinstance(node.targets[0], ast.Name):
+ name = node.targets[0].id
+ if name in _WANTED:
+ exec(ast.get_source_segment(src, node), ns)
+ for name in _WANTED:
+ assert name in ns, f"{name} not found in import_fixes.py"
+ return ns["fix_peft_stale_torchao_import_error"]
+
+
+FIX = _fix()
+
+STALE = ImportError(
+ "Found an incompatible version of torchao. Found version "
+ "0.10.0, but only versions above 0.16.0 are supported"
+)
+
+
+def _raiser(exc):
+ def is_torchao_available():
+ raise exc
+
+ return is_torchao_available
+
+
+# ---- the bug --------------------------------------------------------------
+
+
+def test_stale_torchao_becomes_false(peft_env):
+ iu, _ = peft_env(_raiser(STALE))
+ assert FIX() is True
+ assert iu.is_torchao_available() is False
+
+
+def test_the_module_that_actually_calls_it_is_patched(peft_env):
+ # dispatch_torchao holds its own reference; patching import_utils alone
+ # would leave the real call site raising.
+ _, consumer = peft_env(_raiser(STALE))
+ FIX()
+ assert consumer.is_torchao_available() is False
+
+
+def test_warning_is_emitted_once(peft_env):
+ iu, _ = peft_env(_raiser(STALE))
+ seen = []
+ _fix(warning = seen.append)()
+ for _ in range(5):
+ iu.is_torchao_available()
+ assert len(seen) == 1, "one stale dependency, one message"
+ assert "torchao" in seen[0]
+ assert "upgrade" in seen[0].lower()
+
+
+# ---- what must still fail -------------------------------------------------
+
+
+def test_an_unrelated_import_error_still_raises(peft_env):
+ iu, _ = peft_env(_raiser(ImportError("libcudart.so.12: cannot open shared object file")))
+ FIX()
+ with pytest.raises(ImportError):
+ iu.is_torchao_available()
+
+
+ "message",
+ [
+ # Half-installed torchao: says "torchao", is not a version complaint,
+ # and calling it "unavailable" would hide a broken install.
+ "No module named 'torchao.quantization'",
+ "cannot import name 'quantize_' from 'torchao'",
+ # An extension built against a different torch/CUDA.
+ "libtorchao_ops_cuda.so: cannot open shared object file: No such file or directory",
+ "/site-packages/torchao/_C.so: undefined symbol: _ZN3c105ErrorC1E",
+ ],
+)
+def test_a_broken_torchao_still_raises_even_though_it_says_torchao(peft_env, message):
+ iu, _ = peft_env(_raiser(ImportError(message)))
+ FIX()
+ with pytest.raises(ImportError):
+ iu.is_torchao_available()
+
+
+ "message",
+ [
+ # peft's current wording.
+ "Found an incompatible version of torchao. Found version 0.10.0, "
+ "but only versions above 0.16.0 are supported",
+ # Rewordings that must keep being read as "too old", not "broken".
+ "torchao 0.10.0 is installed but only versions above 0.16.0 are supported",
+ "This requires torchao>=0.16.0",
+ ],
+)
+def test_every_spelling_of_the_version_complaint_is_swallowed(peft_env, message):
+ iu, _ = peft_env(_raiser(ImportError(message)))
+ FIX()
+ assert iu.is_torchao_available() is False
+
+
+def test_a_non_import_error_still_raises(peft_env):
+ iu, _ = peft_env(_raiser(RuntimeError("torchao exploded")))
+ FIX()
+ with pytest.raises(RuntimeError):
+ iu.is_torchao_available()
+
+
+# ---- what must not change -------------------------------------------------
+
+
+def test_a_working_torchao_still_answers_true(peft_env):
+ iu, _ = peft_env(lambda: True)
+ FIX()
+ assert iu.is_torchao_available() is True
+
+
+def test_absent_torchao_still_answers_false(peft_env):
+ iu, _ = peft_env(lambda: False)
+ FIX()
+ assert iu.is_torchao_available() is False
+
+
+def test_no_peft_is_not_an_error(monkeypatch):
+ for k in [k for k in sys.modules if k.startswith("peft")]:
+ monkeypatch.delitem(sys.modules, k, raising = False)
+ monkeypatch.setattr(sys, "path", [p for p in sys.path])
+ import builtins
+
+ real = builtins.__import__
+
+ def no_peft(name, *a, **k):
+ if name.startswith("peft"):
+ raise ModuleNotFoundError("No module named 'peft'")
+ return real(name, *a, **k)
+
+ monkeypatch.setattr(builtins, "__import__", no_peft)
+ assert FIX() is None
+
+
+def test_applying_twice_is_a_no_op(peft_env):
+ iu, _ = peft_env(_raiser(STALE))
+ assert FIX() is True
+ first = iu.is_torchao_available
+ assert FIX() is False, "already patched"
+ assert iu.is_torchao_available is first, "must not stack wrappers"
+
+
+def test_metadata_survives(peft_env):
+ iu, _ = peft_env(_raiser(STALE))
+ FIX()
+ assert iu.is_torchao_available.__name__ == "is_torchao_available"
+
+
+# ---- wiring ---------------------------------------------------------------
+
+
+def test_called_from_gpu_init():
+ src = (REPO_ROOT / "unsloth" / "_gpu_init.py").read_text(encoding = "utf-8")
+ assert "fix_peft_stale_torchao_import_error,\n" in src, "not imported"
+ assert "\nfix_peft_stale_torchao_import_error()\n" in src, "not called"
+ assert "\ndel fix_peft_stale_torchao_import_error\n" in src, "not cleaned up"
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_pythonpath_empty_components.py b/tests/test_pythonpath_empty_components.py
new file mode 100644
index 00000000000..55207554c8f
--- /dev/null
+++ b/tests/test_pythonpath_empty_components.py
@@ -0,0 +1,170 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""An empty PYTHONPATH component is an import location, not padding.
+
+`propagate_torchao_fix_to_subprocesses` prepends its directory to PYTHONPATH
+for every descendant process, and rebuilding that value with
+`[p for p in current.split(os.pathsep) if p]` would drop empty components.
+`export PYTHONPATH="$PYTHONPATH:/opt/mylib"` leaves one on the very common
+machine where PYTHONPATH was unset, and CPython reads it as the cwd: 3.11+
+absolutises every component in Modules/getpath.py (abspath("") is the cwd),
+and 3.10 puts the literal "" on sys.path, which site.removeduppaths() then
+makes absolute. Same outcome, different layer.
+
+A SET-BUT-EMPTY PYTHONPATH is the opposite case: CPython ignores it entirely,
+so turning "" into a lone "" component would ADD the cwd to every descendant.
+The rebuild keeps that special case.
+"""
+
+import importlib.util
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from unsloth import import_fixes as IF # noqa: E402
+
+
+def _stage(monkeypatch, tmp_path, pythonpath):
+ """Drive the real function with its gate forced open.
+
+ The gate returns None on a healthy torch/torchao pair, so without this
+ nothing below would run any of the code under test. `find_spec("torchao")`
+ is the one part not faked, so skip rather than pass when it is absent.
+ """
+ if importlib.util.find_spec("torchao") is None:
+ pytest.skip("no torchao here; the function returns before PYTHONPATH")
+ monkeypatch.setattr(
+ IF, "importlib_version", lambda name: "0.18.0" if name == "torchao" else "0"
+ )
+ monkeypatch.setattr(IF, "_torch_really_has", lambda F, name: False)
+ # Keep the generated sitecustomize in tmp_path, so no staged directory
+ # is left behind in the real temp dir.
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ # monkeypatch.setenv/delenv restores PYTHONPATH at teardown even though
+ # the function writes os.environ directly, so no restore fixture is needed.
+ if pythonpath is None:
+ monkeypatch.delenv("PYTHONPATH", raising = False)
+ else:
+ monkeypatch.setenv("PYTHONPATH", pythonpath)
+
+ directory = IF.propagate_torchao_fix_to_subprocesses()
+ assert directory is not None, "gate did not fire; the test proves nothing"
+ # Makes the exact-string assertions below sound.
+ assert os.pathsep not in directory, directory
+ return directory, os.environ.get("PYTHONPATH", "")
+
+
+ "before",
+ [
+ os.pathsep + "/opt/lib", # PYTHONPATH=$PYTHONPATH:/opt/lib, unset
+ "/opt/lib" + os.pathsep, # PYTHONPATH=/opt/lib:$PYTHONPATH, unset
+ "/opt/a" + os.pathsep + os.pathsep + "/opt/b", # interior empty
+ os.pathsep, # separator only
+ ],
+)
+def test_empty_components_survive(monkeypatch, tmp_path, before):
+ directory, after = _stage(monkeypatch, tmp_path, before)
+ assert after == directory + os.pathsep + before, after
+
+
[email protected]("before", [None, ""])
+def test_an_absent_or_empty_pythonpath_does_not_gain_the_cwd(monkeypatch, tmp_path, before):
+ """CPython ignores a set-but-empty PYTHONPATH, so "" must not be split
+ into a lone "" component."""
+ directory, after = _stage(monkeypatch, tmp_path, before)
+ assert after == directory, after
+
+
+def test_it_is_still_idempotent(monkeypatch, tmp_path):
+ """Two calls must not stack the directory, nor eat the empty components
+ the first preserved."""
+ before = os.pathsep + "/opt/lib"
+ directory, after = _stage(monkeypatch, tmp_path, before)
+ assert IF.propagate_torchao_fix_to_subprocesses() == directory
+ assert os.environ["PYTHONPATH"] == after
+
+
+# ---- the premise and the consequence, with real child processes -----------
+
+
+def _probe_tree(tmp_path):
+ """cwddir holds a module reachable ONLY through the cwd.
+
+ The child runs as a script in scriptdir, so sys.path[0] is scriptdir, never
+ the cwd. `only_in_cwd` is importable iff a PYTHONPATH component is the cwd.
+ """
+ cwddir = tmp_path / "cwddir"
+ libdir = tmp_path / "libdir"
+ scriptdir = tmp_path / "scriptdir"
+ for d in (cwddir, libdir, scriptdir):
+ d.mkdir(exist_ok = True)
+ (cwddir / "only_in_cwd.py").write_text("MARKER = 1\n", encoding = "utf-8")
+ (scriptdir / "probe.py").write_text(
+ "import importlib.util as u\nprint(u.find_spec('only_in_cwd') is not None)\n",
+ encoding = "utf-8",
+ )
+ return cwddir, libdir, scriptdir
+
+
+def _cwd_is_importable(cwddir, scriptdir, pythonpath):
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
+ if pythonpath is not None:
+ env["PYTHONPATH"] = pythonpath
+ out = subprocess.run(
+ [sys.executable, str(scriptdir / "probe.py")],
+ cwd = str(cwddir),
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ assert out.returncode == 0, out.stderr
+ return out.stdout.strip() == "True"
+
+
+def test_the_cwd_really_is_importable_from_an_empty_component(tmp_path):
+ """The premise, against this interpreter, with both controls."""
+ cwddir, libdir, scriptdir = _probe_tree(tmp_path)
+ assert _cwd_is_importable(cwddir, scriptdir, None) is False
+ assert _cwd_is_importable(cwddir, scriptdir, str(libdir)) is False
+ assert _cwd_is_importable(cwddir, scriptdir, os.pathsep + str(libdir)) is True
+
+
+def test_the_rewritten_pythonpath_still_reaches_the_cwd(monkeypatch, tmp_path):
+ """The consequence: what a descendant process actually sees afterwards."""
+ cwddir, libdir, scriptdir = _probe_tree(tmp_path)
+ before = os.pathsep + str(libdir)
+ assert _cwd_is_importable(cwddir, scriptdir, before) is True
+ _directory, after = _stage(monkeypatch, tmp_path, before)
+ assert _cwd_is_importable(cwddir, scriptdir, after) is True, after
+
+
+def test_a_set_but_empty_pythonpath_still_reaches_nothing_new(monkeypatch, tmp_path):
+ """And the mirror image: no cwd before, no cwd after."""
+ cwddir, _libdir, scriptdir = _probe_tree(tmp_path)
+ assert _cwd_is_importable(cwddir, scriptdir, "") is False
+ _directory, after = _stage(monkeypatch, tmp_path, "")
+ assert _cwd_is_importable(cwddir, scriptdir, after) is False, after
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_settle_eager_fallbacks_between_steps.py b/tests/test_settle_eager_fallbacks_between_steps.py
new file mode 100644
index 00000000000..38f7983c388
--- /dev/null
+++ b/tests/test_settle_eager_fallbacks_between_steps.py
@@ -0,0 +1,79 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""A deferred compile-mode switch must be settled between training steps.
+
+unsloth_zoo defers the switch to eager on recompile-limit exhaustion, because
+switching mid-call splits a non-reentrant checkpoint region across two compile
+modes and the backward dies with "Something went unexpectedly wrong in
+activation checkpoint". The top of `Trainer.training_step` is the point where
+no region is half-packed.
+"""
+
+import pytest
+
+pytest.importorskip("transformers")
+utils = pytest.importorskip("unsloth_zoo.temporary_patches.utils")
+
+from unsloth.models._utils import patch_gradient_accumulation_fix
+
+pytestmark = pytest.mark.skipif(
+ not hasattr(utils, "apply_pending_eager_fallbacks"),
+ reason = "unsloth_zoo without the deferred compile-mode switch",
+)
+
+
+def FakeTrainer():
+ """Enough of a Trainer for the patch to wrap.
+
+ `training_step` has no `num_items_in_batch` on purpose, so the gradient
+ accumulation source rewrite skips it and only the settler is exercised.
+ A fresh class per test keeps the patch's install-once flag honest.
+ """
+
+ class _FakeTrainer:
+ def training_step(self, model, inputs):
+ return "stepped"
+
+ return _FakeTrainer
+
+
+def test_training_step_settles_pending_eager_fallbacks(FakeTrainer, monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ utils,
+ "apply_pending_eager_fallbacks",
+ lambda: calls.append(1),
+ )
+ patch_gradient_accumulation_fix(FakeTrainer)
+
+ assert getattr(FakeTrainer, "_unsloth_settles_eager_fallbacks", False)
+ assert FakeTrainer().training_step("model", "inputs") == "stepped"
+ assert calls == [1], "every step must settle the pending switch exactly once"
+
+
+def test_a_settler_failure_never_breaks_the_step(FakeTrainer, monkeypatch):
+ def _boom():
+ raise RuntimeError("no")
+
+ monkeypatch.setattr(utils, "apply_pending_eager_fallbacks", _boom)
+ patch_gradient_accumulation_fix(FakeTrainer)
+ assert FakeTrainer().training_step("model", "inputs") == "stepped"
+
+
+def test_the_settler_is_installed_only_once(FakeTrainer):
+ patch_gradient_accumulation_fix(FakeTrainer)
+ first = FakeTrainer.training_step
+ patch_gradient_accumulation_fix(FakeTrainer)
+ assert FakeTrainer.training_step is first, "re-patching must not stack wrappers"
diff --git a/tests/test_torchao_aten_grouped_mm.py b/tests/test_torchao_aten_grouped_mm.py
new file mode 100644
index 00000000000..31a2894eaa6
--- /dev/null
+++ b/tests/test_torchao_aten_grouped_mm.py
@@ -0,0 +1,207 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""`import unsloth` must survive a torchao wanting an aten op this torch lacks.
+
+torchao 0.18 does `@implements([aten._grouped_mm.default])` at module scope,
+and that op arrived in torch 2.8, so older torch raises AttributeError on the
+lookup. transformers imports torchao from `modeling_utils`, so this kills
+`import transformers` and therefore `import unsloth`. Seen on Colab in
+Granite4.0, which pins torch 2.7.1 via uv against a current torchao.
+
+Sibling of the `ScalingType` skew in test_torchao_subprocess_fix.py, but not
+the same bug: this lookup goes through `torch.ops`, so adding names to
+`torch.nn.functional` does nothing for it.
+
+These tests run on a torch that HAS the operator, so they mostly assert the
+safety properties: the fix stays out of the way, refuses to guess, and never
+registers twice. Registering into `aten` on a healthy torch would be far worse
+than the crash being fixed.
+"""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+import torch # noqa: E402
+
+from unsloth import import_fixes as IF # noqa: E402
+
+
+# ---- the guard ----------------------------------------------------------
+
+
+def test_a_present_op_is_reported_as_present():
+ assert IF._torch_op_is_missing("aten", "mm") is False
+
+
+def test_an_absent_op_is_reported_as_missing():
+ assert IF._torch_op_is_missing("aten", "_unsloth_definitely_not_an_op") is True
+
+
+def test_an_op_in_an_unknown_namespace_is_missing():
+ """`getattr(torch.ops, "nope")` hands back a namespace object, but looking
+ an op up inside it still raises AttributeError, so an op in a namespace
+ that does not exist is correctly missing. Harmless only because the sole
+ caller passes "aten", which always exists.
+ """
+ assert IF._torch_op_is_missing("unsloth_no_such_namespace", "_grouped_mm") is True
+
+
+def test_a_non_attribute_error_means_do_not_touch_it(monkeypatch):
+ """Only a plain AttributeError proves absence; anything else means we
+ could not tell, so leave torch alone."""
+
+ class Exploding:
+ def __getattr__(self, item):
+ raise RuntimeError("something else entirely")
+
+ monkeypatch.setattr(torch.ops, "aten", Exploding(), raising = False)
+ assert IF._torch_op_is_missing("aten", "_grouped_mm") is False
+
+
+# ---- the fix, on a torch that does not need it --------------------------
+
+
+ not hasattr(torch.ops.aten, "_grouped_mm"),
+ reason = "this torch is missing the op; see the live test",
+)
+def test_it_does_nothing_when_torch_already_has_the_op():
+ """Registering a placeholder over the real aten operator would replace a
+ working grouped matmul with one that raises."""
+ before = torch.ops.aten._grouped_mm
+ assert IF._ensure_aten_grouped_mm("detail") is False
+ assert torch.ops.aten._grouped_mm is before
+
+
+ not hasattr(torch.ops.aten, "_grouped_mm"),
+ reason = "this torch is missing the op; see the live test",
+)
+def test_the_real_operator_still_works_afterwards():
+ IF._ensure_aten_grouped_mm("detail")
+ assert callable(torch.ops.aten._grouped_mm)
+ # The schema is torch's own, not a placeholder we substituted.
+ assert "offs" in str(torch.ops.aten._grouped_mm.default._schema)
+
+
+def test_it_never_registers_twice(monkeypatch):
+ """A second call must be a no-op even if the op still looks missing:
+ re-defining a schema raises, and the fix must not depend on that."""
+ monkeypatch.setattr(IF, "_aten_grouped_mm_library", object())
+ assert IF._ensure_aten_grouped_mm("detail") is False
+
+
+# ---- the schema ---------------------------------------------------------
+
+
+def test_the_placeholder_schema_matches_upstream():
+ """Read off `torch.ops.aten._grouped_mm.default._schema` on torch 2.9.
+
+ If it drifts, torchao's decorator still resolves but anything introspecting
+ the signature sees a lie, so pin it.
+ """
+ s = IF._ATEN_GROUPED_MM_SCHEMA
+ assert s.startswith("_grouped_mm(Tensor self, Tensor mat2")
+ for kwarg in ("Tensor? offs=None", "Tensor? bias=None", "ScalarType? out_dtype=None"):
+ assert kwarg in s, kwarg
+ assert s.endswith("-> Tensor")
+
+
+def test_the_schema_parses_as_a_real_torch_schema():
+ """A private namespace proves torch accepts the string without touching
+ `aten` on a machine that does not need help."""
+ lib = torch.library.Library("unsloth_schema_probe", "FRAGMENT")
+ try:
+ lib.define(IF._ATEN_GROUPED_MM_SCHEMA)
+ assert hasattr(torch.ops.unsloth_schema_probe, "_grouped_mm")
+ finally:
+ del lib
+
+
+def test_the_placeholder_refuses_to_compute_rather_than_guessing():
+ """A placeholder returning a plausible tensor would be the worst outcome:
+ a silently wrong grouped matmul is not debuggable."""
+ lib = torch.library.Library("unsloth_refuse_probe", "FRAGMENT")
+ try:
+ lib.define(IF._ATEN_GROUPED_MM_SCHEMA)
+
+ def _refuse(
+ self,
+ mat2,
+ offs = None,
+ bias = None,
+ out_dtype = None,
+ ):
+ raise RuntimeError("Unsloth: placeholder, cannot be used")
+
+ lib.impl("_grouped_mm", _refuse, "CompositeExplicitAutograd")
+ a = torch.ones(4, 4)
+ b = torch.ones(1, 4, 4)
+ with pytest.raises(RuntimeError, match = "placeholder"):
+ torch.ops.unsloth_refuse_probe._grouped_mm(a, b)
+ finally:
+ del lib
+
+
+# ---- wiring -------------------------------------------------------------
+
+
+def test_the_subprocess_fix_covers_the_op_too():
+ """vLLM's inspector child never sees an in-process patch, so the generated
+ sitecustomize must carry this fix as well as the functional-symbol one."""
+ src = IF._subprocess_sitecustomize_source()
+ assert "torch.ops.aten._grouped_mm" in src
+ assert "_grouped_mm(Tensor self, Tensor mat2" in src
+ assert "CompositeExplicitAutograd" in src
+
+
+def test_the_subprocess_fix_keeps_the_library_alive():
+ """A torch.library.Library deregisters its schema once collected, so a
+ local would silently undo the fix."""
+ src = IF._subprocess_sitecustomize_source()
+ assert "global _ATEN_LIBRARY" in src
+ assert "_ATEN_LIBRARY = None" in src
+
+
+def test_the_generated_sitecustomize_is_valid_python():
+ import ast
+ ast.parse(IF._subprocess_sitecustomize_source())
+
+
+def test_the_subprocess_fix_never_aborts_interpreter_startup():
+ """It runs in every child process on the machine, so raising there would
+ be far worse than the import error it fixes."""
+ src = IF._subprocess_sitecustomize_source()
+ tail = src[src.index("_chain_to_the_real_sitecustomize()") :]
+ assert "try:" in tail and "except Exception:" in tail
+
+
+def test_the_symbol_fix_reports_the_op_as_one_of_its_patches():
+ """The op half must count towards the return value, or a torch needing
+ only that fix reports False."""
+ import inspect
+
+ src = inspect.getsource(IF.fix_torchao_torch_symbol_skew)
+ assert "_ensure_aten_grouped_mm" in src
+ assert 'patched.append("aten::_grouped_mm")' in src
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_torchao_nf4tensor_move.py b/tests/test_torchao_nf4tensor_move.py
new file mode 100644
index 00000000000..80b26998c62
--- /dev/null
+++ b/tests/test_torchao_nf4tensor_move.py
@@ -0,0 +1,297 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""torchao 0.18.0 moved nf4tensor; torchtune still imports the old path.
+
+torchao 0.18.0 relocated `torchao/dtypes/nf4tensor.py` under
+`quantization/quantize_/workflows/nf4/`. torchtune imports the old path and
+xcodec2 imports torchtune, so every Llasa TTS notebook died one cell after a
+green install with ModuleNotFoundError. Pinning torchao below 0.18 fixes those
+notebooks; aliasing the module fixes anyone importing the old path, anywhere,
+on the new torchao.
+
+Built like the vLLM tokenizer stub beside it: a meta path finder APPENDED after
+the real ones, so an older torchao that still ships the module wins, and
+resolution is lazy so `import unsloth` pays nothing.
+
+The layouts are real package trees written to tmp_path and imported in a
+SUBPROCESS. Stubbing `sys.modules` would test the stub; this tests the import
+machinery, where appended-versus-inserted actually matters.
+"""
+
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def _make_torchao(root: Path, *, old: bool, new: bool):
+ """A minimal torchao package with either layout, or neither."""
+ pkg = root / "torchao"
+ (pkg / "dtypes").mkdir(parents = True, exist_ok = True)
+ (pkg / "__init__.py").write_text("__version__ = '0.18.0'\n", encoding = "utf-8")
+ (pkg / "dtypes" / "__init__.py").write_text("", encoding = "utf-8")
+ if old:
+ (pkg / "dtypes" / "nf4tensor.py").write_text(
+ "WHICH = 'old'\ndef to_nf4(x): return x\n", encoding = "utf-8"
+ )
+ if new:
+ d = pkg / "quantization" / "quantize_" / "workflows" / "nf4"
+ d.mkdir(parents = True, exist_ok = True)
+ for part in (
+ pkg / "quantization",
+ pkg / "quantization" / "quantize_",
+ pkg / "quantization" / "quantize_" / "workflows",
+ d,
+ ):
+ (part / "__init__.py").write_text("", encoding = "utf-8")
+ (d / "nf4_tensor.py").write_text(
+ "WHICH = 'new'\ndef to_nf4(x): return x\n", encoding = "utf-8"
+ )
+ return pkg
+
+
+def _run(root: Path, body: str):
+ """Import the fix in a subprocess with `root` first on sys.path.
+
+ Loaded by file path, not as `unsloth.import_fixes`, so one function does
+ not trigger unsloth's full GPU init.
+ """
+ script = textwrap.dedent(f"""
+ import sys, importlib.util
+ sys.path.insert(0, {str(root)!r})
+ spec = importlib.util.spec_from_file_location(
+ "_if", {str(ROOT / "unsloth" / "import_fixes.py")!r})
+ _if = importlib.util.module_from_spec(spec)
+ sys.modules["_if"] = _if
+ spec.loader.exec_module(_if)
+ """) + textwrap.dedent(body)
+ return subprocess.run(
+ [sys.executable, "-c", script], capture_output = True, text = True, timeout = 180
+ )
+
+
+def test_the_new_layout_is_reachable_under_the_old_name(tmp_path):
+ """The actual fix: torchao 0.18, torchtune's import works anyway."""
+ _make_torchao(tmp_path, old = False, new = True)
+ r = _run(
+ tmp_path,
+ """
+ _if.fix_torchao_nf4tensor_move()
+ import torchao.dtypes.nf4tensor as m
+ print("RESOLVED", m.WHICH, hasattr(m, "to_nf4"))
+ """,
+ )
+ assert "RESOLVED new True" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_without_the_fix_that_import_fails(tmp_path):
+ """The premise. Without it the test above could pass on any torchao."""
+ _make_torchao(tmp_path, old = False, new = True)
+ r = _run(
+ tmp_path,
+ """
+ try:
+ import torchao.dtypes.nf4tensor
+ print("UNEXPECTEDLY OK")
+ except ModuleNotFoundError as e:
+ print("EXPECTED FAILURE", e)
+ """,
+ )
+ assert "EXPECTED FAILURE" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_an_older_torchao_still_gets_its_own_module(tmp_path):
+ """Appended, not inserted at 0: on torchao < 0.18 the real module must
+ win, or the fix silently swaps out working code."""
+ _make_torchao(tmp_path, old = True, new = True)
+ r = _run(
+ tmp_path,
+ """
+ _if.fix_torchao_nf4tensor_move()
+ import torchao.dtypes.nf4tensor as m
+ print("RESOLVED", m.WHICH)
+ """,
+ )
+ assert "RESOLVED old" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_neither_layout_still_raises(tmp_path):
+ """An empty alias would turn a clear ModuleNotFoundError into an
+ AttributeError later."""
+ _make_torchao(tmp_path, old = False, new = False)
+ r = _run(
+ tmp_path,
+ """
+ _if.fix_torchao_nf4tensor_move()
+ try:
+ import torchao.dtypes.nf4tensor
+ print("UNEXPECTEDLY OK")
+ except ModuleNotFoundError:
+ print("STILL RAISES")
+ """,
+ )
+ assert "STILL RAISES" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_it_is_idempotent(tmp_path):
+ """`import unsloth` twice, or a re-import, must not stack finders."""
+ _make_torchao(tmp_path, old = False, new = True)
+ r = _run(
+ tmp_path,
+ """
+ import sys
+ before = len(sys.meta_path)
+ for _ in range(5):
+ _if.fix_torchao_nf4tensor_move()
+ print("ADDED", len(sys.meta_path) - before)
+ """,
+ )
+ assert "ADDED 1" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_no_torchao_means_no_finder(tmp_path):
+ """Nothing installed: do not append a finder that can never fire.
+
+ site-packages is pruned from sys.path first, because an empty tmp_path is
+ not enough when this venv really has torchao.
+ """
+ r = _run(
+ tmp_path,
+ """
+ import sys
+ sys.path = [p for p in sys.path
+ if "site-packages" not in p and "dist-packages" not in p]
+ import importlib
+ importlib.invalidate_caches()
+ assert importlib.util.find_spec("torchao") is None, "torchao still visible"
+ before = len(sys.meta_path)
+ _if.fix_torchao_nf4tensor_move()
+ print("ADDED", len(sys.meta_path) - before)
+ """,
+ )
+ assert "ADDED 0" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_it_does_not_import_torchao_eagerly(tmp_path):
+ """Calling the fix must not drag torchao into every `import unsloth`,
+ which on some builds is seconds and a CUDA probe."""
+ _make_torchao(tmp_path, old = False, new = True)
+ r = _run(
+ tmp_path,
+ """
+ import sys
+ _if.fix_torchao_nf4tensor_move()
+ print("LOADED", "torchao.dtypes.nf4tensor" in sys.modules)
+ """,
+ )
+ assert "LOADED False" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_it_is_wired_into_the_init_sequence():
+ """A fix nobody calls is not a fix."""
+ src = (ROOT / "unsloth" / "_gpu_init.py").read_text(encoding = "utf-8")
+ assert "fix_torchao_nf4tensor_move," in src, "not imported"
+ assert "fix_torchao_nf4tensor_move()" in src, "not called"
+
+
+def test_the_real_environment_is_left_alone():
+ """On a torchao that still ships the old path the fix must be a no-op
+ rather than redirecting a working import."""
+ # In a child: once anything in this session has imported unsloth the alias
+ # is registered, so an in-process check would read the new layout as old.
+ p = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ textwrap.dedent("""
+ import importlib.util, os, sys
+ if importlib.util.find_spec("torchao") is None:
+ print("SKIP torchao not installed"); raise SystemExit
+ import torchao
+ old = os.path.join(os.path.dirname(torchao.__file__),
+ "dtypes", "nf4tensor.py")
+ if not os.path.isfile(old):
+ print("SKIP this torchao already uses the new layout"); raise SystemExit
+ spec = importlib.util.spec_from_file_location("_if_real", sys.argv[1])
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules["_if_real"] = mod
+ spec.loader.exec_module(mod)
+ mod.fix_torchao_nf4tensor_move()
+ import torchao.dtypes.nf4tensor as m
+ print("FILE", getattr(m, "__file__", ""))
+ """),
+ str(ROOT / "unsloth" / "import_fixes.py"),
+ ],
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+ assert p.returncode == 0, p.stdout + p.stderr
+ if "SKIP " in p.stdout:
+ pytest.skip(p.stdout.split("SKIP ", 1)[1].strip())
+ line = [l for l in p.stdout.splitlines() if l.startswith("FILE ")]
+ assert line, p.stdout + p.stderr
+ assert "quantize_" not in line[0], line[0]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
+
+
+def test_the_relocated_module_keeps_its_own_specification(tmp_path):
+ """create_module() returns the module torchao ships, and module_from_spec
+ then overwrites that shared object's __spec__ with the alias's. Left alone,
+ find_spec reports the old name for the new module and reload runs the alias
+ loader's no-op exec_module instead of the file."""
+ _make_torchao(tmp_path, old = False, new = True)
+ r = _run(
+ tmp_path,
+ """
+ import importlib.util
+ NEW = "torchao.quantization.quantize_.workflows.nf4.nf4_tensor"
+ _if.fix_torchao_nf4tensor_move()
+ import torchao.dtypes.nf4tensor as m
+ print("SPEC", m.__spec__.name)
+ print("FINDSPEC", importlib.util.find_spec(NEW).name)
+ print("SAME", sys.modules[NEW] is m)
+ """,
+ )
+ new = "torchao.quantization.quantize_.workflows.nf4.nf4_tensor"
+ assert f"SPEC {new}" in r.stdout, (r.stdout, r.stderr[-2000:])
+ assert f"FINDSPEC {new}" in r.stdout, (r.stdout, r.stderr[-2000:])
+ assert "SAME True" in r.stdout, (r.stdout, r.stderr[-2000:])
+
+
+def test_the_mlx_branch_installs_the_alias_too():
+ """The MLX branch never reaches _gpu_init.py, the only other caller, so
+ Apple Silicon xcodec2 would still die on the old path. Checked at source
+ level because the branch only runs when mlx is importable."""
+ import ast
+
+ src = (ROOT / "unsloth" / "__init__.py").read_text(encoding = "utf-8")
+ branch = [
+ n
+ for n in ast.walk(ast.parse(src))
+ if isinstance(n, ast.If)
+ and any(getattr(x, "id", None) == "_IS_MLX" for x in ast.walk(n.test))
+ ]
+ assert branch, "the _IS_MLX branch moved; this test needs updating"
+ body = ast.get_source_segment(src, branch[0])
+ assert "fix_torchao_nf4tensor_move" in body
+ assert "fix_torchao_torch_symbol_skew" in body
diff --git a/tests/test_torchao_subprocess_fix.py b/tests/test_torchao_subprocess_fix.py
new file mode 100644
index 00000000000..aa41c9a2a0d
--- /dev/null
+++ b/tests/test_torchao_subprocess_fix.py
@@ -0,0 +1,832 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The torchao fix has to reach processes unsloth does not launch.
+
+`fix_torchao_torch_symbol_skew` patches `torch.nn.functional` in the current
+interpreter, but vLLM inspects model architectures in a SEPARATE process that
+imports torch and torchao itself, so `fast_inference = True` still dies with
+the same ImportError, shown only as "Model architectures [...] failed to be
+inspected". Observed on Colab AFTER the in-process fix reported success.
+
+`sitecustomize` is the hook that reaches such a process: `site` imports it at
+interpreter startup off PYTHONPATH, which subprocesses inherit. A `.pth` would
+work too, but only inside a real site directory, which a library should not be
+writing into.
+
+The hazard dominating these tests is shadowing: `sitecustomize` is a single
+global name that other things legitimately install (this machine has one at
+/etc/unslothai/python/), so replacing it would silently disable them.
+"""
+
+import os
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from unsloth import import_fixes as IF # noqa: E402
+
+
+# ---- the generated sitecustomize -----------------------------------------
+
+
+def test_it_is_valid_python():
+ """A syntax error breaks every subprocess on the machine, which is far
+ worse than the bug being fixed."""
+ compile(IF._subprocess_sitecustomize_source(), "<sitecustomize>", "exec")
+
+
+def test_it_chains_instead_of_shadowing():
+ src = IF._subprocess_sitecustomize_source()
+ assert "_chain_to_the_real_sitecustomize" in src
+ assert 'PathFinder.find_spec("sitecustomize"' in src
+
+
+def test_the_chain_runs_before_the_fix():
+ src = IF._subprocess_sitecustomize_source()
+ assert src.index("_chain_to_the_real_sitecustomize()") < src.index("sys.meta_path.insert")
+
+
+def test_it_never_raises_at_interpreter_startup():
+ src = IF._subprocess_sitecustomize_source()
+ tail = src[src.index("_chain_to_the_real_sitecustomize()") :]
+ assert "except Exception:" in tail
+
+
+def test_it_is_version_gated():
+ src = IF._subprocess_sitecustomize_source()
+ assert "(0, 18)" in src, "torchao < 0.18 guards its own import"
+
+
+def test_it_does_not_overwrite_existing_torch_symbols():
+ assert "if hasattr(F, name):" in IF._subprocess_sitecustomize_source()
+
+
+def test_the_child_never_imports_unsloth():
+ """Importing unsloth at the start of every subprocess would pay the full
+ import cost each time and could recurse back through
+ propagate_torchao_fix_to_subprocesses, so the logic is inlined."""
+ src = IF._subprocess_sitecustomize_source()
+ assert "import unsloth" not in src
+ assert "from unsloth" not in src
+
+
+def test_it_only_imports_the_stdlib_and_torch():
+ """Anything heavier makes interpreter startup slower for every process."""
+ import ast
+
+ tree = ast.parse(IF._subprocess_sitecustomize_source())
+ allowed = {
+ "os",
+ "sys",
+ "importlib",
+ "importlib.util",
+ "importlib.machinery",
+ "importlib.metadata",
+ "torch",
+ "torch.nn.functional",
+ }
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for a in node.names:
+ assert a.name in allowed, f"unexpected import: {a.name}"
+ elif isinstance(node, ast.ImportFrom) and node.module:
+ assert node.module in allowed, f"unexpected import: {node.module}"
+
+
+# ---- staging ---------------------------------------------------------------
+
+
[email protected](autouse = True)
+def _restore_pythonpath():
+ before = os.environ.get("PYTHONPATH")
+ yield
+ if before is None:
+ os.environ.pop("PYTHONPATH", None)
+ else:
+ os.environ["PYTHONPATH"] = before
+
+
+def _torchao_is_broken_here() -> bool:
+ try:
+ import importlib.metadata as md
+ from packaging.version import Version
+ if Version(md.version("torchao")) < Version("0.18.0"):
+ return False
+ except Exception:
+ return False
+ import torch.nn.functional as F
+
+ # `_torch_really_has`, not `hasattr`: conftest.py imports unsloth, so on a
+ # broken environment the placeholders are already on F and hasattr would
+ # read it as healthy.
+ return not all(IF._torch_really_has(F, n) for n in IF._TORCHAO_TORCH_SYMBOLS)
+
+
+def test_it_is_a_noop_on_a_healthy_environment():
+ """Nothing is written and PYTHONPATH is untouched unless the fix is
+ actually needed."""
+ if _torchao_is_broken_here():
+ pytest.skip("this environment genuinely needs the fix")
+ before = os.environ.get("PYTHONPATH")
+ assert IF.propagate_torchao_fix_to_subprocesses() is None
+ assert os.environ.get("PYTHONPATH") == before
+
+
+def test_it_uses_the_platform_path_separator():
+ """Windows uses ';'. A hardcoded ':' would corrupt PYTHONPATH there."""
+ import inspect
+
+ src = inspect.getsource(IF.propagate_torchao_fix_to_subprocesses)
+ assert "os.pathsep" in src
+ assert 'split(":")' not in src
+
+
+def test_it_writes_atomically():
+ """A truncated sitecustomize read by a concurrent subprocess is a
+ SyntaxError at startup."""
+ import inspect
+
+ src = inspect.getsource(IF._write_hook_atomically)
+ assert "os.replace" in src
+
+
+def test_the_temporary_file_cannot_be_pre_empted():
+ """A predictable temporary name can be pre-created as a symlink by anyone
+ who could write into the directory before it was tightened."""
+ import inspect
+
+ src = inspect.getsource(IF._write_hook_atomically)
+ assert "O_EXCL" in src
+ assert "O_NOFOLLOW" in src
+ assert "os.urandom" in src
+ assert "getpid" not in src
+
+
+def test_it_is_idempotent_on_pythonpath():
+ import inspect
+ src = inspect.getsource(IF.propagate_torchao_fix_to_subprocesses)
+ assert "if directory not in parts:" in src
+
+
+# ---- the directory it writes into -----------------------------------------
+
+
+def test_the_directory_is_private_to_this_user():
+ """The temp dir is shared and everything on PYTHONPATH runs in every
+ subprocess, so a fixed name there is code execution for whoever creates it
+ first."""
+ directory = IF._subprocess_fix_directory()
+ if hasattr(os, "getuid"):
+ assert directory.endswith("-%d" % os.getuid()), directory
+ info = os.lstat(directory)
+ assert info.st_uid == os.getuid()
+ assert oct(info.st_mode & 0o777) == oct(0o700), oct(info.st_mode)
+
+
+def test_it_refuses_a_directory_owned_by_someone_else(monkeypatch, tmp_path):
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX ownership only")
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ hostile = tmp_path / ("unsloth_subprocess_import_fix-%d" % os.getuid())
+ hostile.mkdir()
+
+ real_lstat = os.lstat
+
+ class _NotOurs:
+ st_mode = real_lstat(str(hostile)).st_mode
+ st_uid = os.getuid() + 1
+
+ monkeypatch.setattr(
+ os, "lstat", lambda p: _NotOurs() if str(p) == str(hostile) else real_lstat(p)
+ )
+ with pytest.raises(RuntimeError, match = "owned by another user"):
+ IF._subprocess_fix_directory()
+
+
[email protected]("mode", [0o777, 0o770, 0o707, 0o702, 0o720])
+def test_an_existing_loose_directory_is_tightened(monkeypatch, tmp_path, mode):
+ """`os.makedirs(mode = 0o700, exist_ok = True)` does NOT re-apply the mode
+ to an existing directory, and one left group- or world-writable is code
+ execution in every subprocess started after `import unsloth`."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX permissions only")
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ loose = tmp_path / ("unsloth_subprocess_import_fix-%d" % os.getuid())
+ loose.mkdir()
+ os.chmod(loose, mode)
+ assert os.lstat(loose).st_mode & 0o022, "fixture did not take"
+
+ directory = IF._subprocess_fix_directory()
+
+ assert directory == str(loose)
+ after = os.lstat(directory).st_mode & 0o777
+ assert not after & 0o022, "still writable by group/other: %04o" % after
+ assert oct(after) == oct(0o700), oct(after)
+
+
+def test_a_directory_that_cannot_be_tightened_is_refused(monkeypatch, tmp_path):
+ """Some network and FUSE mounts accept chmod and change nothing; handing
+ back a world-writable PYTHONPATH entry anyway is the whole bug."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX permissions only")
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ loose = tmp_path / ("unsloth_subprocess_import_fix-%d" % os.getuid())
+ loose.mkdir()
+ os.chmod(loose, 0o777)
+ monkeypatch.setattr(os, "chmod", lambda *a, **k: None) # silently ignored
+
+ with pytest.raises(RuntimeError, match = "group- or world-writable"):
+ IF._subprocess_fix_directory()
+
+
+def test_the_refusal_does_not_propagate_as_a_crash(monkeypatch):
+ """A hostile directory must degrade to "no subprocess fix", not kill the
+ import."""
+ import inspect
+
+ src = inspect.getsource(IF.propagate_torchao_fix_to_subprocesses)
+ i = src.index("_subprocess_fix_directory()")
+ assert "try:" in src[:i]
+ assert "except Exception as exception:" in src[i:]
+
+
+# ---- behaviour, with real interpreters ------------------------------------
+
+
+def staged(tmp_path):
+ """The generated sitecustomize on a PYTHONPATH dir, plus a fake torch and
+ a fake torchao 0.18 that reproduces the real import error."""
+ site = tmp_path / "hook"
+ site.mkdir()
+ (site / "sitecustomize.py").write_text(IF._subprocess_sitecustomize_source(), encoding = "utf-8")
+
+ fake = tmp_path / "fake"
+ (fake / "torch" / "nn").mkdir(parents = True)
+ (fake / "torch" / "__init__.py").write_text(
+ "from . import nn\n__version__='2.9.0'\n", encoding = "utf-8"
+ )
+ (fake / "torch" / "nn" / "__init__.py").write_text(
+ "from . import functional\n", encoding = "utf-8"
+ )
+ (fake / "torch" / "nn" / "functional.py").write_text(
+ "def linear(*a, **k):\n return None\n", encoding = "utf-8"
+ )
+ (fake / "torchao").mkdir()
+ (fake / "torchao" / "__init__.py").write_text(
+ "from torch.nn.functional import ScalingType, scaled_grouped_mm\n__version__='0.18.0'\n",
+ encoding = "utf-8",
+ )
+ d = fake / "torchao-0.18.0.dist-info"
+ d.mkdir()
+ (d / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: torchao\nVersion: 0.18.0\n", encoding = "utf-8"
+ )
+ return site, fake
+
+
[email protected](scope = "session")
+def bare_interpreter(tmp_path_factory):
+ """An interpreter whose site-packages is empty.
+
+ PYTHONPATH can shadow a module but cannot un-install one: the child still
+ finds the real torchao's dist-info, which is what the hook reads. On a
+ machine that has torchao, "absent" is only expressible as a bare venv.
+ """
+ venv = tmp_path_factory.mktemp("bare") / "venv"
+ try:
+ subprocess.run(
+ [sys.executable, "-m", "venv", "--without-pip", str(venv)],
+ check = True,
+ capture_output = True,
+ timeout = 300,
+ )
+ except Exception as exception:
+ pytest.skip(f"cannot build a venv here ({exception})")
+ exe = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ if not exe.is_file():
+ pytest.skip("venv produced no interpreter")
+ return str(exe)
+
+
+def _child(
+ code: str,
+ path_entries,
+ timeout = 300,
+ executable = None,
+):
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
+ env["PYTHONPATH"] = os.pathsep.join(str(p) for p in path_entries)
+ return subprocess.run(
+ [executable or sys.executable, "-c", textwrap.dedent(code)],
+ capture_output = True,
+ text = True,
+ timeout = timeout,
+ env = env,
+ )
+
+
+def test_the_broken_import_really_fails_without_the_hook(staged):
+ """Guards the premise; without this the test below proves nothing."""
+ _site, fake = staged
+ p = _child("import torchao", [fake])
+ assert p.returncode != 0
+ assert "cannot import name 'ScalingType'" in p.stderr, p.stderr
+
+
+def test_the_hook_fixes_a_process_we_never_launched(staged):
+ site, fake = staged
+ p = _child("import torchao; print('OK', torchao.__version__)", [site, fake])
+ assert "OK 0.18.0" in p.stdout, p.stdout + p.stderr
+
+
+def test_it_does_not_import_torch_until_torchao_is(staged):
+ """Most Python descendants never use torchao, and importing torch there
+ costs seconds of startup and torch's memory."""
+ site, fake = staged
+ p = _child("import sys; print('TORCH', 'torch' in sys.modules)", [site, fake])
+ assert "TORCH False" in p.stdout, p.stdout + p.stderr
+ p = _child("import torchao, sys; print('TORCH', 'torch' in sys.modules)", [site, fake])
+ assert "TORCH True" in p.stdout, p.stdout + p.stderr
+
+
+def test_it_also_reaches_a_grandchild(staged):
+ """vLLM's inspector is not necessarily a direct child."""
+ site, fake = staged
+ p = _child(
+ "import subprocess, sys;"
+ "r = subprocess.run([sys.executable, '-c',"
+ "'import torchao; print(\"GRANDCHILD OK\")'],"
+ "capture_output=True, text=True);"
+ "print(r.stdout, r.stderr)",
+ [site, fake],
+ )
+ assert "GRANDCHILD OK" in p.stdout, p.stdout + p.stderr
+
+
+def test_the_placeholder_still_refuses_to_be_used(staged):
+ site, fake = staged
+ p = _child(
+ """
+ import torchao
+ from torch.nn.functional import ScalingType
+ try:
+ ScalingType.DYNAMIC
+ print("NO ERROR")
+ except RuntimeError as e:
+ print("RAISED", "does not exist in this torch" in str(e))
+ """,
+ [site, fake],
+ )
+ assert "RAISED True" in p.stdout, p.stdout + p.stderr
+
+
+def test_an_existing_sitecustomize_still_runs(staged, tmp_path):
+ """The shadowing hazard is real: this machine already has a sitecustomize
+ at /etc/unslothai/python/, and ours must chain to it."""
+ site, fake = staged
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / "sitecustomize.py").write_text("print('OTHER SITECUSTOMIZE RAN')\n", encoding = "utf-8")
+ p = _child("import torchao; print('OK')", [site, other, fake])
+ assert "OTHER SITECUSTOMIZE RAN" in p.stdout, p.stdout + p.stderr
+ assert "OK" in p.stdout
+
+
+def test_a_package_form_existing_sitecustomize_still_runs(staged, tmp_path):
+ """CPython imports the package form exactly like the file form, so probing
+ for a `sitecustomize.py` would silently drop it in every subprocess."""
+ site, fake = staged
+ other = tmp_path / "other"
+ (other / "sitecustomize").mkdir(parents = True)
+ (other / "sitecustomize" / "__init__.py").write_text(
+ "from . import extra\nprint('PACKAGE SITECUSTOMIZE RAN', extra.NAME)\n",
+ encoding = "utf-8",
+ )
+ (other / "sitecustomize" / "extra.py").write_text("NAME = 'submodule'\n", encoding = "utf-8")
+ p = _child("import torchao; print('OK')", [site, other, fake])
+ assert "PACKAGE SITECUSTOMIZE RAN submodule" in p.stdout, p.stdout + p.stderr
+ assert "OK" in p.stdout
+
+
+def test_a_pyc_only_existing_sitecustomize_still_runs(staged, tmp_path):
+ """Same argument for a shipped `sitecustomize.pyc` with no source."""
+ import py_compile
+
+ site, fake = staged
+ source = tmp_path / "src"
+ source.mkdir()
+ written = source / "sitecustomize.py"
+ written.write_text("print('PYC SITECUSTOMIZE RAN')\n", encoding = "utf-8")
+ other = tmp_path / "other_pyc"
+ other.mkdir()
+ py_compile.compile(str(written), cfile = str(other / "sitecustomize.pyc"), doraise = True)
+ p = _child("import torchao; print('OK')", [site, other, fake])
+ assert "PYC SITECUSTOMIZE RAN" in p.stdout, p.stdout + p.stderr
+ assert "OK" in p.stdout
+
+
+def test_a_broken_package_form_sitecustomize_does_not_kill_the_process(staged, tmp_path):
+ site, fake = staged
+ other = tmp_path / "other"
+ (other / "sitecustomize").mkdir(parents = True)
+ (other / "sitecustomize" / "__init__.py").write_text(
+ "raise RuntimeError('boom')\n", encoding = "utf-8"
+ )
+ p = _child("import torchao; print('STILL OK')", [site, other, fake])
+ assert "STILL OK" in p.stdout, p.stdout + p.stderr
+
+
+def test_a_broken_existing_sitecustomize_does_not_kill_the_process(staged, tmp_path):
+ """Chaining must not turn somebody else's bug into a startup crash."""
+ site, fake = staged
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / "sitecustomize.py").write_text("raise RuntimeError('boom')\n", encoding = "utf-8")
+ p = _child("import torchao; print('STILL OK')", [site, other, fake])
+ assert "STILL OK" in p.stdout, p.stdout + p.stderr
+
+
+def test_it_does_nothing_when_torchao_is_absent(staged, tmp_path, bare_interpreter):
+ """No torchao, no patching: torch.nn.functional must be untouched."""
+ site, _fake = staged
+ bare = tmp_path / "bare"
+ (bare / "torch" / "nn").mkdir(parents = True)
+ (bare / "torch" / "__init__.py").write_text(
+ "from . import nn\n__version__='2.9.0'\n", encoding = "utf-8"
+ )
+ (bare / "torch" / "nn" / "__init__.py").write_text(
+ "from . import functional\n", encoding = "utf-8"
+ )
+ (bare / "torch" / "nn" / "functional.py").write_text(
+ "def linear(*a, **k):\n return None\n", encoding = "utf-8"
+ )
+ p = _child(
+ """
+ import torch.nn.functional as F
+ print("PATCHED", hasattr(F, "ScalingType"))
+ """,
+ [site, bare],
+ executable = bare_interpreter,
+ )
+ assert "PATCHED False" in p.stdout, p.stdout + p.stderr
+
+
+def test_the_hook_does_not_disturb_ordinary_startup(staged):
+ site, fake = staged
+ p = _child("print('HELLO')", [site, fake])
+ assert p.returncode == 0
+ assert "HELLO" in p.stdout
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
+
+
+# ---- the in-process fix must not disable this one -------------------------
+
+
+def test_the_in_process_fix_does_not_disable_the_subprocess_fix(monkeypatch, tmp_path):
+ """_gpu_init.py runs fix_torchao_torch_symbol_skew() immediately before
+ this one, so a gate asking only `hasattr` would read its placeholders as a
+ healthy torch and stage nothing, in exactly the environments vLLM's
+ inspector child needs it."""
+ import torch.nn.functional as F
+
+ if all(IF._torch_really_has(F, n) for n in IF._TORCHAO_TORCH_SYMBOLS):
+ pytest.skip("this torch provides every symbol; nothing to place")
+
+ # conftest.py imports unsloth, so on an affected environment the
+ # placeholders are already installed and the call below would return False.
+ # _gpu_init sees a fresh interpreter; reproduce that.
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+
+ monkeypatch.setattr(
+ IF, "importlib_version", lambda name: "0.18.0" if name == "torchao" else "0"
+ )
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ monkeypatch.delenv("PYTHONPATH", raising = False)
+ try:
+ assert IF.fix_torchao_torch_symbol_skew() is True # the _gpu_init order
+ directory = IF.propagate_torchao_fix_to_subprocesses()
+ assert (
+ directory is not None
+ ), "staged nothing: the in-process placeholders defeated the gate"
+ assert os.path.isfile(os.path.join(directory, "sitecustomize.py"))
+ assert directory in os.environ["PYTHONPATH"].split(os.pathsep)
+ finally:
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+
+
+def test_a_placeholder_does_not_count_as_a_real_torch_symbol():
+ """The distinction the gate above turns on."""
+ import torch.nn.functional as F
+
+ placeholder = IF._make_torch_symbol_placeholder("ScalingType", "detail")
+ assert IF._torch_really_has(F, "scaled_dot_product_attention") is True
+ assert (
+ IF._torch_really_has(type("_F", (), {"ScalingType": placeholder}), "ScalingType") is False
+ )
+ assert IF._torch_really_has(type("_F", (), {}), "ScalingType") is False
+
+
+# ---- a hook file planted before the directory was tightened ---------------
+
+
+def _plant(directory, kind, source):
+ """A `sitecustomize.py` as it could survive a once-writable directory."""
+ target = directory / "sitecustomize.py"
+ if kind == "symlink":
+ elsewhere = directory.parent / "planted_elsewhere.py"
+ elsewhere.write_text(source, encoding = "utf-8")
+ os.symlink(elsewhere, target)
+ return elsewhere
+ target.write_text(source, encoding = "utf-8")
+ if kind == "group_writable":
+ os.chmod(target, 0o666)
+ return target
+
+
[email protected]("kind", ["symlink", "group_writable"])
+def test_a_planted_hook_is_not_trusted(tmp_path, kind):
+ """Contents equal to ours are what an attacker arranges to skip the
+ rewrite; only a private regular file of ours makes them evidence."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX ownership/permissions only")
+ directory = tmp_path / "dir"
+ directory.mkdir()
+ _plant(directory, kind, IF._subprocess_sitecustomize_source())
+ assert IF._existing_hook_is_trustworthy(str(directory / "sitecustomize.py")) is False
+
+
+def test_a_foreign_owned_hook_is_not_trusted(tmp_path, monkeypatch):
+ """A file created while the directory was world-writable stays theirs to
+ rewrite after the directory is tightened."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX ownership only")
+ target = tmp_path / "sitecustomize.py"
+ target.write_text("x = 1\n", encoding = "utf-8")
+ real_lstat = os.lstat
+ theirs = os.stat_result(
+ tuple(real_lstat(str(target)))[:4] + (os.getuid() + 1,) + tuple(real_lstat(str(target)))[5:]
+ )
+ monkeypatch.setattr(os, "lstat", lambda p: theirs if str(p) == str(target) else real_lstat(p))
+ assert IF._existing_hook_is_trustworthy(str(target)) is False
+
+
+def test_our_own_hook_file_is_trusted(tmp_path):
+ """The fast path must survive, or concurrent runs fight over the file."""
+ target = tmp_path / "sitecustomize.py"
+ target.write_text(IF._subprocess_sitecustomize_source(), encoding = "utf-8")
+ os.chmod(target, 0o600)
+ assert IF._existing_hook_is_trustworthy(str(target)) is True
+ assert IF._existing_hook_is_trustworthy(str(tmp_path / "absent.py")) is True
+
+
[email protected]("kind", ["symlink", "group_writable"])
+def test_a_planted_hook_is_replaced_even_when_it_matches(monkeypatch, tmp_path, kind):
+ """End to end: a once-world-writable directory already holds a hook whose
+ contents match ours. Tightening the directory does not revoke write access
+ to that file, so leaving it is code execution in every subprocess."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX ownership/permissions only")
+ import torch.nn.functional as F
+
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+ if all(IF._torch_really_has(F, n) for n in IF._TORCHAO_TORCH_SYMBOLS):
+ pytest.skip("this torch provides every symbol; nothing to stage")
+
+ monkeypatch.setattr(
+ IF, "importlib_version", lambda name: "0.18.0" if name == "torchao" else "0"
+ )
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ monkeypatch.delenv("PYTHONPATH", raising = False)
+
+ loose = tmp_path / ("unsloth_subprocess_import_fix-%d" % os.getuid())
+ loose.mkdir()
+ os.chmod(loose, 0o777)
+ planted = _plant(loose, kind, IF._subprocess_sitecustomize_source())
+
+ try:
+ directory = IF.propagate_torchao_fix_to_subprocesses()
+ assert directory == str(loose)
+ target = loose / "sitecustomize.py"
+ info = os.lstat(target)
+ import stat as _stat
+
+ assert _stat.S_ISREG(info.st_mode), "still a symlink to a file we do not own"
+ assert not _stat.S_IMODE(info.st_mode) & 0o022, oct(info.st_mode)
+ assert target.read_text(encoding = "utf-8") == IF._subprocess_sitecustomize_source()
+ if kind == "symlink":
+ # Rewriting the planted file must no longer reach any child.
+ planted.write_text("raise SystemExit('hijacked')\n", encoding = "utf-8")
+ assert target.read_text(encoding = "utf-8") != planted.read_text(encoding = "utf-8")
+ finally:
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+
+
+def test_a_pre_created_temporary_symlink_is_not_followed(monkeypatch, tmp_path):
+ """The other half of a once-world-writable directory: the temporary file
+ the hook is staged through. A predictable name lets someone leave a
+ symlink behind, and os.replace would install that link as the hook."""
+ if not hasattr(os, "getuid"):
+ pytest.skip("POSIX symlinks only")
+ import stat as _stat
+
+ import torch.nn.functional as F
+
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+ if all(IF._torch_really_has(F, n) for n in IF._TORCHAO_TORCH_SYMBOLS):
+ pytest.skip("this torch provides every symbol; nothing to stage")
+
+ monkeypatch.setattr(
+ IF, "importlib_version", lambda name: "0.18.0" if name == "torchao" else "0"
+ )
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ monkeypatch.delenv("PYTHONPATH", raising = False)
+
+ loose = tmp_path / ("unsloth_subprocess_import_fix-%d" % os.getuid())
+ loose.mkdir()
+ os.chmod(loose, 0o777)
+ theirs = tmp_path / "planted_elsewhere.py"
+ theirs.write_text("# theirs\n", encoding = "utf-8")
+ os.symlink(theirs, loose / ("sitecustomize.py.%d.tmp" % os.getpid()))
+
+ try:
+ assert IF.propagate_torchao_fix_to_subprocesses() == str(loose)
+ target = loose / "sitecustomize.py"
+ info = os.lstat(target)
+ assert _stat.S_ISREG(info.st_mode), "installed the planted symlink as the hook"
+ assert not _stat.S_IMODE(info.st_mode) & 0o022, oct(info.st_mode)
+ assert target.read_text(encoding = "utf-8") == IF._subprocess_sitecustomize_source()
+ # Their file was never opened, so rewriting it reaches nothing.
+ assert theirs.read_text(encoding = "utf-8") == "# theirs\n"
+ finally:
+ for name in IF._TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, name, None), "__unsloth_placeholder__", False):
+ delattr(F, name)
+
+
+def test_the_staging_file_is_private_and_leaves_nothing_behind(tmp_path):
+ directory = tmp_path / "dir"
+ directory.mkdir(mode = 0o700)
+ target = directory / "sitecustomize.py"
+ IF._write_hook_atomically(str(target), "MARK = 1\n")
+ assert target.read_text(encoding = "utf-8") == "MARK = 1\n"
+ assert [p.name for p in directory.iterdir()] == ["sitecustomize.py"]
+ if hasattr(os, "getuid"):
+ import stat as _stat
+ assert oct(_stat.S_IMODE(os.lstat(target).st_mode)) == oct(0o600)
+
+
+# ---- the chained sitecustomize keeps its own name -------------------------
+
+
+def test_a_chained_package_stays_importable(staged, tmp_path):
+ """Restoring our module under `sitecustomize` would hide the real one from
+ `import sitecustomize` and break the relative imports its own callbacks
+ perform after startup."""
+ site, fake = staged
+ other = tmp_path / "other"
+ (other / "sitecustomize").mkdir(parents = True)
+ (other / "sitecustomize" / "__init__.py").write_text(
+ textwrap.dedent(
+ """
+ import atexit
+ NAME = 'the_real_package'
+ def _later():
+ from . import extra # delayed, as installed hooks do
+ print('LATER OK', extra.NAME)
+ atexit.register(_later)
+ """
+ ),
+ encoding = "utf-8",
+ )
+ (other / "sitecustomize" / "extra.py").write_text("NAME = 'submodule'\n", encoding = "utf-8")
+ p = _child(
+ """
+ import sitecustomize, torchao
+ print('NAME', getattr(sitecustomize, 'NAME', '<<shadowed by ours>>'))
+ print('PACKAGE', hasattr(sitecustomize, '__path__'))
+ """,
+ [site, other, fake],
+ )
+ assert "NAME the_real_package" in p.stdout, p.stdout + p.stderr
+ assert "PACKAGE True" in p.stdout, p.stdout + p.stderr
+ assert "LATER OK submodule" in p.stdout, p.stdout + p.stderr
+ assert "Exception ignored in atexit" not in p.stderr, p.stderr
+
+
+def test_a_broken_chained_module_does_not_keep_our_name(staged, tmp_path):
+ """The handover only happens on success: one that raised half-way through
+ must not be left behind under the name."""
+ site, fake = staged
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / "sitecustomize.py").write_text(
+ "MARK = 'half-initialised'\nraise RuntimeError('boom')\n", encoding = "utf-8"
+ )
+ p = _child(
+ """
+ import sys, torchao
+ print('IN MODULES', 'sitecustomize' in sys.modules)
+ print('MARK', getattr(sys.modules.get('sitecustomize'), 'MARK', '<<none>>'))
+ print('STILL OK')
+ """,
+ [site, other, fake],
+ )
+ assert "STILL OK" in p.stdout, p.stdout + p.stderr
+ assert "MARK <<none>>" in p.stdout, p.stdout + p.stderr
+
+
+# ---- a second spelling of our own directory on sys.path -------------------
+
+
+_COUNT_HOOKS = (
+ "import sys;"
+ "print('HOOKS', sum(1 for h in sys.meta_path"
+ " if type(h).__name__ == '_TorchaoImportHook'))"
+)
+
+
+def test_a_symlink_alias_of_our_own_directory_is_not_chained(staged, tmp_path):
+ """A string compare treats an alias as somebody else's sitecustomize, so
+ the two spellings load and execute one another until the stack runs out.
+ Every unwound level then installs another finder."""
+ if not hasattr(os, "symlink"):
+ pytest.skip("symlinks only")
+ site, _fake = staged
+ alias = tmp_path / "alias"
+ try:
+ os.symlink(site, alias, target_is_directory = True)
+ except (OSError, NotImplementedError) as exception:
+ pytest.skip(f"cannot create a directory symlink here ({exception})")
+
+ p = _child(_COUNT_HOOKS, [alias, site])
+ assert "HOOKS 1" in p.stdout, p.stdout + p.stderr
+ assert "RecursionError" not in p.stderr, p.stderr
+
+
+def test_a_symlinked_copy_of_the_hook_file_is_not_chained(staged, tmp_path):
+ """Same hazard one level down: the directory differs, but the
+ `sitecustomize.py` inside it is this very file."""
+ if not hasattr(os, "symlink"):
+ pytest.skip("symlinks only")
+ site, _fake = staged
+ other = tmp_path / "other"
+ other.mkdir()
+ try:
+ os.symlink(site / "sitecustomize.py", other / "sitecustomize.py")
+ except (OSError, NotImplementedError) as exception:
+ pytest.skip(f"cannot create a symlink here ({exception})")
+
+ p = _child(_COUNT_HOOKS, [site, other])
+ assert "HOOKS 1" in p.stdout, p.stdout + p.stderr
+ assert "RecursionError" not in p.stderr, p.stderr
+
+
+def test_an_aliased_directory_still_chains_to_a_real_sitecustomize(staged, tmp_path):
+ """The canonical compare must reject only ourselves, not everyone else."""
+ if not hasattr(os, "symlink"):
+ pytest.skip("symlinks only")
+ site, fake = staged
+ alias = tmp_path / "alias"
+ try:
+ os.symlink(site, alias, target_is_directory = True)
+ except (OSError, NotImplementedError) as exception:
+ pytest.skip(f"cannot create a directory symlink here ({exception})")
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / "sitecustomize.py").write_text("print('OTHER SITECUSTOMIZE RAN')\n", encoding = "utf-8")
+
+ p = _child("import torchao; print('OK')", [alias, site, other, fake])
+ assert "OTHER SITECUSTOMIZE RAN" in p.stdout, p.stdout + p.stderr
+ assert "OK" in p.stdout, p.stdout + p.stderr
diff --git a/tests/test_torchao_torch_symbol_skew.py b/tests/test_torchao_torch_symbol_skew.py
new file mode 100644
index 00000000000..23c766bbb6d
--- /dev/null
+++ b/tests/test_torchao_torch_symbol_skew.py
@@ -0,0 +1,339 @@
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""torchao 0.18 must not be able to kill `import unsloth`.
+
+torchao 0.17 guarded `from torch.nn.functional import ScalingType, SwizzleType`
+behind `torch_version_at_least("2.10.0")`; 0.18.0 left it unguarded at module
+level, so torch below 2.10 raises ImportError. It surfaces while importing
+transformers, where unsloth_zoo's import guard re-raises a bare Exception
+naming neither torchao nor torch. Seen on Colab in Gemma3_(4B)-Vision-GRPO,
+Qwen3_5_(4B)_Vision and Qwen3_8B_FP8_GRPO.
+
+The placeholder refuses to be used: 0.17 left these names undefined on old
+torch anyway, and a stub impersonating a real enum could hand a float8 path a
+meaningless value, which is worse than the crash. Checked against the 0.18.0
+source: neither symbol is evaluated at import time, so being strict is safe.
+"""
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from unsloth.import_fixes import ( # noqa: E402
+ _TORCHAO_TORCH_SYMBOLS,
+ _make_torch_symbol_placeholder,
+ fix_torchao_torch_symbol_skew,
+)
+
+GPU_INIT = ROOT / "unsloth" / "_gpu_init.py"
+
+
+# ---- the placeholder ------------------------------------------------------
+
+
+def test_it_can_be_imported():
+ """The whole point: satisfy `from torch.nn.functional import X`."""
+ ph = _make_torch_symbol_placeholder("ScalingType", "detail here")
+ assert ph is not None
+ assert ph.__name__ == "ScalingType"
+
+
+def test_using_it_raises_with_an_actionable_message():
+ ph = _make_torch_symbol_placeholder("ScalingType", "torchao 0.18 vs torch 2.9")
+ with pytest.raises(RuntimeError) as e:
+ ph.DYNAMIC
+ msg = str(e.value)
+ assert "torchao<0.18" in msg, "the user needs something to actually do"
+ assert "ScalingType" in msg
+
+
+def test_instantiating_it_raises_too():
+ ph = _make_torch_symbol_placeholder("SwizzleType", "d")
+ with pytest.raises(RuntimeError):
+ ph()
+
+
+def test_it_never_pretends_to_be_a_real_value():
+ """A stub returning None or 0 would flow into a float8 config and produce
+ silently wrong behaviour instead of an error."""
+ ph = _make_torch_symbol_placeholder("ScalingType", "d")
+ for attr in ("DYNAMIC", "STATIC", "value", "name"):
+ with pytest.raises(RuntimeError):
+ getattr(ph, attr)
+
+
+def test_repr_is_honest():
+ ph = _make_torch_symbol_placeholder("ScalingType", "d")
+ assert "placeholder" in repr(ph)
+
+
+def test_it_is_marked_as_ours():
+ ph = _make_torch_symbol_placeholder("ScalingType", "d")
+ assert getattr(ph, "__unsloth_placeholder__", False) is True
+
+
+# ---- the gating -----------------------------------------------------------
+
+
+def test_it_is_a_no_op_when_torch_already_has_the_symbols():
+ """On torch >= 2.10 overwriting the real enum with a raising placeholder
+ would BREAK float8 rather than fix anything."""
+ import torch.nn.functional as F
+
+ added = [n for n in _TORCHAO_TORCH_SYMBOLS if not hasattr(F, n)]
+ if not added:
+ assert fix_torchao_torch_symbol_skew() is False
+
+
+def test_a_healthy_torchao_is_left_alone():
+ """0.17 and earlier guard their own import, so patching there would put a
+ placeholder into torch for no reason."""
+ if importlib.util.find_spec("torchao") is None:
+ pytest.skip("torchao not installed")
+ from importlib.metadata import version
+ from packaging.version import Version
+
+ if Version(version("torchao")) < Version("0.18.0"):
+ import torch.nn.functional as F
+
+ before = {n: hasattr(F, n) for n in _TORCHAO_TORCH_SYMBOLS}
+ assert fix_torchao_torch_symbol_skew() is False
+ after = {n: hasattr(F, n) for n in _TORCHAO_TORCH_SYMBOLS}
+ assert before == after, "nothing may be added for a healthy torchao"
+
+
+def test_no_torchao_means_nothing_to_do():
+ if importlib.util.find_spec("torchao") is not None:
+ pytest.skip("torchao is installed here")
+ assert fix_torchao_torch_symbol_skew() is False
+
+
+def test_it_never_raises():
+ """It runs during `import unsloth`, so anything it raises replaces the
+ problem it exists to prevent."""
+ assert fix_torchao_torch_symbol_skew() in (True, False)
+
+
+def test_calling_it_twice_is_stable():
+ first = fix_torchao_torch_symbol_skew()
+ second = fix_torchao_torch_symbol_skew()
+ assert second is False or first == second
+
+
+# ---- the wiring -----------------------------------------------------------
+
+
+def test_it_runs_before_unsloth_zoo_is_imported():
+ """unsloth_zoo pulls in transformers and therefore torchao, so calling the
+ fix after that import would be pointless."""
+ lines = GPU_INIT.read_text(encoding = "utf-8").splitlines()
+ call = next(i for i, l in enumerate(lines) if l.strip() == "fix_torchao_torch_symbol_skew()")
+ zoo = next(i for i, l in enumerate(lines) if l.strip() == "import unsloth_zoo")
+ assert call < zoo, f"called at line {call + 1}, too late for line {zoo + 1}"
+
+
+def test_it_is_imported_and_cleaned_up():
+ src = GPU_INIT.read_text(encoding = "utf-8")
+ assert "fix_torchao_torch_symbol_skew," in src, "not imported"
+ assert (
+ "del fix_torchao_torch_symbol_skew" in src
+ ), "every other fix is deleted after use; this one must be too"
+
+
+def test_the_symbol_list_matches_what_torchao_imports():
+ """Taken from the whole installed package, not one file.
+
+ Reading only mx_formats/mx_tensor.py misses scaled_grouped_mm, which
+ float8_tensor.py imports on the path of a plain `import torchao`, so a list
+ without it leaves the import exactly as dead.
+ """
+ assert set(_TORCHAO_TORCH_SYMBOLS) == {
+ "ScalingType",
+ "SwizzleType",
+ "scaled_grouped_mm",
+ "scaled_dot_product_attention",
+ }
+
+
+def test_symbols_torch_already_provides_are_never_replaced():
+ """scaled_dot_product_attention exists on every supported torch, so a
+ raising placeholder would break attention itself."""
+ import torch.nn.functional as F
+ import unsloth.import_fixes as IF
+
+ real = F.scaled_dot_product_attention
+ IF.fix_torchao_torch_symbol_skew()
+ assert F.scaled_dot_product_attention is real
+
+
+# ---- the fix actually unblocks the import --------------------------------
+
+
+def test_the_real_torchao_018_import_line_is_unblocked(monkeypatch):
+ """The decisive test: run torchao 0.18's own import line on this torch and
+ show it goes from raising to succeeding. Everything above is gating."""
+ import torch.nn.functional as F
+ import unsloth.import_fixes as IF
+
+ # conftest.py imports unsloth, so on an affected environment the
+ # placeholders are already on F. Drop them, or the "before" half cannot
+ # raise, this test skips itself, and the guard test after it fails.
+ for n in _TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, n, None), "__unsloth_placeholder__", False):
+ delattr(F, n)
+
+ # Gate on the two symbols the line below imports: `any` over the whole
+ # tuple is always true (scaled_dot_product_attention always exists), which
+ # made this test skip on every machine.
+ if all(hasattr(F, n) for n in ("ScalingType", "SwizzleType")):
+ pytest.skip("this torch already provides ScalingType/SwizzleType")
+
+ # the line as torchao 0.18 ships it
+ line = "from torch.nn.functional import ScalingType, SwizzleType"
+
+ with pytest.raises(ImportError):
+ exec(line, {})
+
+ monkeypatch.setattr(
+ IF, "importlib_version", lambda name: "0.18.0" if name == "torchao" else "0"
+ )
+ try:
+ assert IF.fix_torchao_torch_symbol_skew() is True
+ exec(line, {}) # must not raise now
+ from torch.nn.functional import ScalingType
+
+ with pytest.raises(RuntimeError):
+ ScalingType.DYNAMIC # still refuses to be used
+ finally:
+ for n in _TORCHAO_TORCH_SYMBOLS:
+ if getattr(getattr(F, n, None), "__unsloth_placeholder__", False):
+ delattr(F, n)
+
+
+def test_the_cleanup_in_the_test_above_is_real():
+ """Guards the fixture, not the product: a failed delattr above would let
+ every later test see a patched torch and pass vacuously."""
+ import torch.nn.functional as F
+ for n in _TORCHAO_TORCH_SYMBOLS:
+ obj = getattr(F, n, None)
+ assert not getattr(
+ obj, "__unsloth_placeholder__", False
+ ), f"a placeholder for {n} leaked out of a test"
+
+
+# ---- the Mac / MLX path ---------------------------------------------------
+
+INIT = ROOT / "unsloth" / "__init__.py"
+
+
+def test_the_mlx_path_applies_the_fix_too():
+ """The MLX branch imports unsloth_zoo directly and never reaches
+ _gpu_init, so without the fix there Apple Silicon hits the same dead
+ import."""
+ lines = INIT.read_text(encoding = "utf-8").splitlines()
+ fix = next(i for i, l in enumerate(lines) if "_fix_torchao()" in l)
+ zoo = next(i for i, l in enumerate(lines) if l.strip() == "import unsloth_zoo")
+ assert fix < zoo, "the fix must precede the MLX unsloth_zoo import"
+
+
+def test_the_mlx_call_is_inside_the_mlx_branch():
+ """_gpu_init already owns the GPU path, and calling it outside the branch
+ would touch torch before the Apple Silicon detection wants it. Checked
+ structurally: string offsets cannot tell "inside the if" from "after it".
+ """
+ import ast as _ast
+
+ tree = _ast.parse(INIT.read_text(encoding = "utf-8"))
+
+ def _mlx_if(nodes):
+ for n in nodes:
+ if isinstance(n, _ast.If) and _ast.dump(n.test).count("_IS_MLX"):
+ return n
+ return None
+
+ node = _mlx_if(tree.body)
+ assert node is not None, "no `if _IS_MLX:` branch found"
+ inside = any(
+ isinstance(c, _ast.Call) and getattr(c.func, "id", "") == "_fix_torchao"
+ for stmt in node.body
+ for c in _ast.walk(stmt)
+ )
+ assert inside, "the call must be INSIDE the `if _IS_MLX:` body"
+
+ outside = any(
+ isinstance(c, _ast.Call) and getattr(c.func, "id", "") == "_fix_torchao"
+ for stmt in tree.body
+ if stmt is not node
+ for c in _ast.walk(stmt)
+ )
+ assert not outside, "it must not also run on the non-MLX path"
+
+
+def test_the_mlx_call_cannot_break_the_import():
+ """On Mac this runs first, so an exception here would replace a torchao
+ problem with an unsloth problem."""
+ src = INIT.read_text(encoding = "utf-8")
+ i = src.index("_fix_torchao()")
+ window = src[max(0, i - 400) : i + 200]
+ assert "except Exception" in window and "pass" in window
+
+
+# ---- version gating across the strings that actually ship ----------------
+
+
+ "version,affected",
+ [
+ ("0.18.0", True),
+ ("0.18.0+cu130", True), # wheels carry a local version
+ ("0.19.0.dev20260801", True), # a dev build of a later release still has it
+ ("1.0.0", True), # future majors, until upstream fixes it
+ ("0.17.0", False), # guards its own import
+ ("0.17.0+cu130", False),
+ ("0.13.0", False), # the floor in pyproject
+ ],
+)
+def test_the_version_gate(version, affected):
+ """The gate decides whether we touch torch at all, so it must cope with
+ local versions and dev builds, not just clean releases."""
+ from unsloth.import_fixes import Version
+ assert (Version(version) >= Version("0.18.0")) is affected
+
+
+def test_an_unparseable_version_is_not_patched(monkeypatch):
+ """Leave torch alone rather than guess from a version we cannot parse."""
+ import unsloth.import_fixes as IF
+
+ monkeypatch.setattr(IF, "importlib_version", lambda name: "not-a-version-at-all")
+ assert IF.fix_torchao_torch_symbol_skew() is False
+
+
+def test_a_missing_version_is_not_patched(monkeypatch):
+ import unsloth.import_fixes as IF
+
+ def _boom(name):
+ raise Exception("no metadata")
+
+ monkeypatch.setattr(IF, "importlib_version", _boom)
+ assert IF.fix_torchao_torch_symbol_skew() is False
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/unsloth/__init__.py b/unsloth/__init__.py
index 58057025b69..72a4d9d8f29 100644
--- a/unsloth/__init__.py
+++ b/unsloth/__init__.py
@@ -81,6 +81,22 @@ def _is_mlx_available():
_IS_MLX = _is_mlx_available()
if _IS_MLX:
+ # _gpu_init does this on the GPU path; the MLX path never reaches it, so
+ # torchao 0.18 + torch < 2.10 dies on `ScalingType`. No-op otherwise.
+ try:
+ from .import_fixes import fix_torchao_torch_symbol_skew as _fix_torchao
+ _fix_torchao()
+ del _fix_torchao
+ except Exception:
+ pass
+ try:
+ # Same reason: MLX audio reaches xcodec2 -> torchtune -> the old
+ # torchao.dtypes.nf4tensor path.
+ from .import_fixes import fix_torchao_nf4tensor_move as _fix_nf4
+ _fix_nf4()
+ del _fix_nf4
+ except Exception:
+ pass
try:
import unsloth_zoo
except ImportError as _e:
@@ -592,9 +608,7 @@ if _IS_MLX:
def _assign_mlx_positional_kwarg(kwargs, name, value):
if name in kwargs:
- raise TypeError(
- f"UnslothTrainer.__init__() got multiple values for argument " f"{name!r}"
- )
+ raise TypeError(f"UnslothTrainer.__init__() got multiple values for argument {name!r}")
kwargs[name] = value
def _normalize_mlx_trainer_init_args(args, kwargs):
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index 7e8f9ced465..6f5ce6b7dd5 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -27,6 +27,8 @@ already_imported = [mod for mod in critical_modules if mod in sys.modules]
from .import_fixes import (
fix_message_factory_issue,
fix_torch_check_is_size,
+ fix_torchao_torch_symbol_skew,
+ propagate_torchao_fix_to_subprocesses,
check_fbgemm_gpu_version,
disable_broken_causal_conv1d,
disable_broken_vllm,
@@ -74,6 +76,10 @@ disable_broken_causal_conv1d()
disable_broken_vllm()
fix_message_factory_issue()
fix_torch_check_is_size()
+fix_torchao_torch_symbol_skew()
+# The above fixes THIS process only; vLLM's model-architecture inspector
+# is a subprocess that imports torchao itself and hits the same ImportError.
+propagate_torchao_fix_to_subprocesses()
check_fbgemm_gpu_version()
torchvision_compatibility_check()
fix_diffusers_warnings()
@@ -84,6 +90,8 @@ del disable_broken_causal_conv1d
del disable_broken_vllm
del fix_message_factory_issue
del fix_torch_check_is_size
+del fix_torchao_torch_symbol_skew
+del propagate_torchao_fix_to_subprocesses
del check_fbgemm_gpu_version
del torchvision_compatibility_check
del fix_diffusers_warnings
@@ -172,6 +180,7 @@ from .import_fixes import (
fix_xformers_performance_issue,
fix_vllm_aimv2_issue,
fix_vllm_lora_tokenizer_module,
+ fix_torchao_nf4tensor_move,
check_vllm_torch_sm100_compatibility,
fix_vllm_guided_decoding_params,
fix_vllm_pdl_blackwell,
@@ -195,12 +204,16 @@ from .import_fixes import (
fix_peft_transformers_tensor_parallel_import_compat,
fix_peft_transformers_weight_conversion_import,
patch_peft_weight_converter_compatibility,
+ fix_peft_stale_torchao_import_error,
patch_accelerate_recursively_apply,
)
fix_xformers_performance_issue()
fix_vllm_aimv2_issue()
fix_vllm_lora_tokenizer_module()
+# torchao 0.18.0 moved nf4tensor; torchtune (via xcodec2) still imports the
+# old path. Lazy alias, so it costs nothing unless asked for.
+fix_torchao_nf4tensor_move()
# Check vLLM + torch < 2.9.0 + SM100 compatibility BEFORE importing vLLM
check_vllm_torch_sm100_compatibility()
fix_vllm_guided_decoding_params()
@@ -231,11 +244,15 @@ disable_broken_wandb()
fix_peft_transformers_tensor_parallel_import_compat()
fix_peft_transformers_weight_conversion_import()
patch_peft_weight_converter_compatibility()
+# After peft is importable, so the already-bound `is_torchao_available` in
+# peft.tuners.lora.torchao is replaced too, not just import_utils'.
+fix_peft_stale_torchao_import_error()
patch_accelerate_recursively_apply()
del fix_xformers_performance_issue
del fix_vllm_aimv2_issue
del fix_vllm_lora_tokenizer_module
+del fix_torchao_nf4tensor_move
del check_vllm_torch_sm100_compatibility
del fix_vllm_guided_decoding_params
del fix_trl_vllm_ascend
@@ -258,6 +275,7 @@ del disable_broken_wandb
del fix_peft_transformers_tensor_parallel_import_compat
del fix_peft_transformers_weight_conversion_import
del patch_peft_weight_converter_compatibility
+del fix_peft_stale_torchao_import_error
del patch_accelerate_recursively_apply
# Torch 2.4 has including_emulation
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 8580c09c394..3cfb3ed0cf1 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -3199,3 +3199,796 @@ def patch_accelerate_recursively_apply():
setattr(mod, "find_device", _patched_find_device)
except Exception:
pass
+
+
+# The one ImportError worth answering False to. Matching "torchao" anywhere is
+# too wide: "No module named 'torchao.quantization'" and a missing
+# libtorchao_ops_cuda.so also say it, and both mean genuinely broken rather than
+# merely old, so they must keep propagating. Match the version complaint itself.
+# peft's current wording is the first alternative; the rest are how other
+# libraries phrase the same sentence, so an upstream reword does not silently
+# turn this back into a raise.
+_TORCHAO_STALE_VERSION_ERROR = re.compile(
+ r"incompatible version of torchao"
+ r"|torchao.{0,120}?only versions?\s+(?:above|below|>=|<=)"
+ r"|(?:requires|needs|expected)\s+torchao\s*[><=!]",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+def fix_peft_stale_torchao_import_error():
+ """Stop an old torchao from aborting LoRA creation that never uses it.
+
+ ``peft.import_utils.is_torchao_available`` returns False when torchao is
+ absent but raises when it is installed and older than peft's minimum, and
+ ``dispatch_torchao`` calls it for every LoRA layer, so one stale optional
+ dependency ends ``get_peft_model``. "Installed but unusable" is closer to
+ "not installed" than to "fatal", so answer False and warn once.
+
+ Returns True when patched, False when no patch is needed, None when peft
+ is absent.
+ """
+ try:
+ import peft.import_utils as peft_import_utils
+ except Exception:
+ return None
+
+ original = getattr(peft_import_utils, "is_torchao_available", None)
+ if original is None:
+ return None
+ if getattr(original, "__unsloth_patched__", False):
+ return False
+
+ warned = [False]
+
+ @functools.wraps(original)
+ def is_torchao_available(*args, **kwargs):
+ try:
+ return original(*args, **kwargs)
+ except ImportError as exc:
+ # Only the version complaint; any other torchao import failure is
+ # a real problem and must still surface.
+ message = str(exc)
+ if _TORCHAO_STALE_VERSION_ERROR.search(message) is None:
+ raise
+ if not warned[0]:
+ warned[0] = True
+ logger.warning(
+ f"Unsloth: Ignoring an unusable torchao so LoRA can still "
+ f"be built ({message}). Run "
+ f"`pip install --upgrade torchao` if you need torchao "
+ f"quantization."
+ )
+ return False
+
+ is_torchao_available.__unsloth_patched__ = True
+
+ patched = False
+ try:
+ peft_import_utils.is_torchao_available = is_torchao_available
+ patched = True
+ except Exception:
+ return False
+
+ # `from peft.import_utils import is_torchao_available` binds the original
+ # into each importing module, so patching import_utils alone would leave
+ # peft.tuners.lora.torchao, the actual caller, still raising.
+ for mod_name, mod in tuple(sys.modules.items()):
+ if not mod_name.startswith("peft") or mod is None:
+ continue
+ if getattr(mod, "is_torchao_available", None) is original:
+ try:
+ setattr(mod, "is_torchao_available", is_torchao_available)
+ except Exception:
+ pass
+ return patched
+
+
+# Every name torchao 0.18.0 imports from torch.nn.functional, from
+# grep -rh "from torch.nn.functional import" torchao/
+# scaled_grouped_mm is on the path of a plain `import torchao`.
+# scaled_dot_product_attention is listed for completeness only: it exists on
+# every supported torch, and the loop below skips symbols torch provides.
+_TORCHAO_TORCH_SYMBOLS = (
+ "ScalingType",
+ "SwizzleType",
+ "scaled_grouped_mm",
+ "scaled_dot_product_attention",
+)
+
+
+def _make_torch_symbol_placeholder(name, detail):
+ """A stand-in that imports cleanly and refuses to be used.
+
+ Pretending to be a real enum would be worse than the crash it replaces: it
+ could hand a float8 path a meaningless value. torchao 0.17 left these names
+ undefined on older torch anyway, so anything wanting them already raised.
+ """
+ message = (
+ f"Unsloth: `torch.nn.functional.{name}` does not exist in this torch. "
+ f"{detail} Unsloth supplied a placeholder so that importing torchao "
+ f"(and therefore unsloth) still works, but this symbol cannot be used. "
+ f"Install `torchao<0.18` to use float8/MX features on this torch, or "
+ f"upgrade torch."
+ )
+
+ class _Meta(type):
+ def __getattr__(cls, item):
+ raise RuntimeError(message)
+
+ def __call__(cls, *args, **kwargs):
+ raise RuntimeError(message)
+
+ def __repr__(cls):
+ return f"<unsloth placeholder for torch.nn.functional.{name}>"
+
+ placeholder = _Meta(name, (), {"__doc__": message})
+ # So we can recognise our own object later and never double-patch.
+ type.__setattr__(placeholder, "__unsloth_placeholder__", True)
+ return placeholder
+
+
+# The same skew one layer down: torchao 0.18 does `@implements([aten.
+# _grouped_mm.default])` at module scope in float8/float8_tensor.py, and that
+# op only arrived in torch 2.8, so older torch raises AttributeError on the
+# lookup. The torch.nn.functional names above do not help; this goes through
+# torch.ops, so the schema itself has to exist.
+_ATEN_GROUPED_MM_SCHEMA = (
+ "_grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, "
+ "Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor"
+)
+
+# Module level on purpose: a torch.library.Library deregisters everything it
+# defined once collected, so a local would undo itself.
+_aten_grouped_mm_library = None
+
+
+def _torch_op_is_missing(namespace, name):
+ """Is `torch.ops.<namespace>.<name>` absent on this torch?
+
+ Only a plain AttributeError counts: anything else means we could not tell,
+ and when unsure we must not register into the aten namespace.
+ """
+ try:
+ import torch
+ ns = getattr(torch.ops, namespace)
+ except Exception:
+ return False
+ try:
+ getattr(ns, name)
+ except AttributeError:
+ return True
+ except Exception:
+ return False
+ return False
+
+
+def _ensure_aten_grouped_mm(detail):
+ """Define an unusable `aten::_grouped_mm` so torchao's decorator resolves.
+
+ No real implementation on purpose: torchao only wants somewhere to hang a
+ float8 handler this torch never dispatches to, so the schema is the whole
+ requirement, and a silently wrong grouped matmul would be worse than the
+ crash it replaces. Calling it raises and says why.
+ """
+ global _aten_grouped_mm_library
+ if _aten_grouped_mm_library is not None:
+ return False
+ if not _torch_op_is_missing("aten", "_grouped_mm"):
+ return False
+
+ message = (
+ f"Unsloth: `torch.ops.aten._grouped_mm` does not exist in this torch. "
+ f"{detail} Unsloth registered a placeholder schema so that importing "
+ f"torchao (and therefore unsloth) still works, but the operator cannot "
+ f"be used. Upgrade to torch >= 2.8 for grouped matmul, or install "
+ f"`torchao<0.18`."
+ )
+
+ def _refuse(
+ self,
+ mat2,
+ offs = None,
+ bias = None,
+ out_dtype = None,
+ ):
+ raise RuntimeError(message)
+
+ try:
+ import torch
+
+ # FRAGMENT adds to a namespace someone else owns; DEF would try to
+ # claim "aten" outright and be rejected.
+ library = torch.library.Library("aten", "FRAGMENT")
+ library.define(_ATEN_GROUPED_MM_SCHEMA)
+ library.impl("_grouped_mm", _refuse, "CompositeExplicitAutograd")
+ except Exception:
+ # A torch that will not let us register keeps its own error.
+ return False
+
+ _aten_grouped_mm_library = library
+ return True
+
+
+def fix_torchao_torch_symbol_skew():
+ """Let `import unsloth` survive a torchao built for a newer torch.
+
+ torchao 0.17 guarded the import behind `torch_version_at_least("2.10.0")`;
+ 0.18.0 left it unguarded at module level, so torch below 2.10 raises
+ "cannot import name 'ScalingType' from 'torch.nn.functional'" while
+ importing transformers, naming neither torchao nor torch.
+
+ Narrow by design: only fires when torchao is installed, its version has
+ the bug, and torch really lacks the symbol. Nothing is masked otherwise.
+ """
+ if importlib.util.find_spec("torchao") is None:
+ return False
+ try:
+ torchao_version = importlib_version("torchao")
+ except Exception:
+ return False
+ try:
+ # 0.17 and earlier guard their own import.
+ if Version(torchao_version) < Version("0.18.0"):
+ return False
+ except Exception:
+ return False
+
+ try:
+ import torch
+ import torch.nn.functional as F
+ torch_version = str(torch.__version__)
+ except Exception:
+ return False
+
+ detail = (
+ f"torchao {torchao_version} imports it unconditionally, but "
+ f"torch {torch_version} does not provide it (it arrived in "
+ f"torch 2.10)."
+ )
+
+ patched = []
+ for name in _TORCHAO_TORCH_SYMBOLS:
+ if hasattr(F, name):
+ continue # real torch symbol, or already placed by us
+ try:
+ setattr(F, name, _make_torch_symbol_placeholder(name, detail))
+ patched.append(name)
+ except Exception:
+ pass
+ if patched:
+ logger.info(
+ "Unsloth: torchao %s needs torch.nn.functional.%s, which torch %s "
+ "does not have. Adding an unusable placeholder so the import "
+ "succeeds; install torchao<0.18 to use float8/MX features.",
+ torchao_version,
+ "/".join(patched),
+ torch_version,
+ )
+
+ # The aten-op half of the same skew. Independent of the loop above: a torch
+ # can have every functional symbol and still lack the operator, or vice
+ # versa, so neither result gates the other.
+ op_detail = (
+ f"torchao {torchao_version} registers a handler for it at "
+ f"import time, but torch {torch_version} does not provide it "
+ f"(it arrived in torch 2.8)."
+ )
+ if _ensure_aten_grouped_mm(op_detail):
+ patched.append("aten::_grouped_mm")
+ logger.info(
+ "Unsloth: torchao %s registers a handler for torch.ops.aten."
+ "_grouped_mm, which torch %s does not have. Registering an "
+ "unusable placeholder schema so the import succeeds.",
+ torchao_version,
+ torch_version,
+ )
+ return bool(patched)
+
+
+# vLLM inspects model architectures in a separate process, which imports
+# torchao itself, never sees a parent monkey-patch, and fails with the same
+# ImportError as the generic "Model architectures ['...'] failed to be
+# inspected".
+#
+# `sitecustomize` is the one hook that reaches a process we do not launch:
+# `site` imports it at interpreter startup off PYTHONPATH, which subprocesses
+# inherit. A `.pth` would also work, but only inside a real site directory,
+# which a library has no business writing into.
+
+_SUBPROCESS_FIX_DIRNAME = "unsloth_subprocess_import_fix"
+
+
+def _subprocess_fix_directory():
+ """A private directory for the generated sitecustomize.
+
+ Everything on PYTHONPATH runs in every subprocess and /tmp is shared on
+ Linux, so a fixed name there would let whoever created it first run code as
+ everyone else. Scope it per user and refuse a path this user does not own.
+
+ Ownership alone is not enough: ``exist_ok = True`` does not apply ``mode``
+ to an existing directory, so one left group- or world-writable stays that
+ way and anyone who can write into it can replace the ``sitecustomize.py``.
+ Take the write bits away, and refuse the directory if they will not go.
+ """
+ import stat
+ import tempfile
+
+ name = _SUBPROCESS_FIX_DIRNAME
+ try:
+ name += "-%d" % os.getuid()
+ except AttributeError:
+ name += "-" + (os.environ.get("USERNAME") or "user")
+ directory = os.path.join(tempfile.gettempdir(), name)
+ os.makedirs(directory, mode = 0o700, exist_ok = True)
+ if hasattr(os, "getuid"):
+ info = os.lstat(directory)
+ if stat.S_ISLNK(info.st_mode) or info.st_uid != os.getuid():
+ raise RuntimeError(
+ "refusing a subprocess fix directory owned by another user: " + directory
+ )
+ # chmod then re-read: some network and FUSE mounts ignore mode bits
+ # and report success without changing anything.
+ if stat.S_IMODE(info.st_mode) & 0o022:
+ try:
+ os.chmod(directory, 0o700)
+ except Exception:
+ pass
+ info = os.lstat(directory)
+ if stat.S_IMODE(info.st_mode) & 0o022:
+ raise RuntimeError(
+ "refusing a group- or world-writable subprocess fix "
+ "directory (mode %04o): %s" % (stat.S_IMODE(info.st_mode), directory)
+ )
+ return directory
+
+
+def _subprocess_sitecustomize_source():
+ """The sitecustomize we hand to child processes.
+
+ It chains rather than shadows: `sitecustomize` is a single global name that
+ other things legitimately install, so replacing it would disable them in
+ every subprocess. Ours runs the next one on sys.path first, then the fix.
+ """
+ return '''"""Written by unsloth. Makes `import torchao` survive a torch that
+predates the symbols torchao 0.18 imports unconditionally, in processes
+unsloth did not launch (notably vLLM's model-architecture inspector)."""
+import os
+import sys
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def _same_path(a, b):
+ """Two spellings of one file or directory, symlinks included."""
+ try:
+ if os.path.samefile(a, b):
+ return True
+ except Exception:
+ pass
+ return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
+
+
+def _chain_to_the_real_sitecustomize():
+ """Do not shadow somebody else's sitecustomize."""
+ import importlib.util
+ from importlib.machinery import PathFinder
+ for entry in sys.path:
+ # Ask the import system rather than probing for a filename, so the
+ # package (`sitecustomize/__init__.py`) and .pyc forms chain too.
+ try:
+ # Canonical comparison, not a string one: a symlink alias of our
+ # own directory also on sys.path would otherwise look like a
+ # different location, and the two spellings would chain to each
+ # other until the stack ran out.
+ if not entry or _same_path(entry, _HERE):
+ continue
+ spec = PathFinder.find_spec("sitecustomize", [entry])
+ except Exception:
+ continue
+ if spec is None or spec.loader is None:
+ continue
+ # Second guard for the same hazard, in case the alias is the file
+ # rather than the directory: never chain to this very hook.
+ try:
+ origin = getattr(spec, "origin", None)
+ if origin and (_same_path(origin, __file__)
+ or _same_path(os.path.dirname(origin), _HERE)):
+ continue
+ except Exception:
+ continue
+ try:
+ mod = importlib.util.module_from_spec(spec)
+ # A package needs its own name in sys.modules for `from . import`
+ # to resolve, and it needs it AFTER initialization too: a callback
+ # it registers (atexit, a hook) does its relative imports later,
+ # and would find our non-package module under `sitecustomize` and
+ # fail. So leave the real one there on success -- which is also
+ # what `import sitecustomize` returns when we are not installed --
+ # and only put the previous entry back if it failed to load.
+ previous = sys.modules.get("sitecustomize")
+ sys.modules["sitecustomize"] = mod
+ try:
+ spec.loader.exec_module(mod)
+ except BaseException:
+ if previous is None:
+ sys.modules.pop("sitecustomize", None)
+ else:
+ sys.modules["sitecustomize"] = previous
+ raise
+ break
+ except Exception:
+ # A broken sitecustomize elsewhere must not stop us, and must not
+ # take down every subprocess either.
+ break
+
+
+def _apply():
+ import importlib.metadata as md
+ try:
+ version = md.version("torchao")
+ except Exception:
+ return
+ try:
+ major, minor = (int("".join(c for c in p if c.isdigit()) or 0)
+ for p in str(version).split(".")[:2])
+ if (major, minor) < (0, 18):
+ return
+ except Exception:
+ return
+ try:
+ import torch
+ import torch.nn.functional as F
+ except Exception:
+ return
+ detail = ("torchao %s imports it unconditionally, but torch %s does not "
+ "provide it (it arrived in torch 2.10)." % (version, torch.__version__))
+ for name in ("ScalingType", "SwizzleType", "scaled_grouped_mm",
+ "scaled_dot_product_attention"):
+ if hasattr(F, name):
+ continue
+ message = ("Unsloth: `torch.nn.functional.%s` does not exist in this "
+ "torch. %s Unsloth supplied a placeholder so that importing "
+ "torchao still works, but this symbol cannot be used. "
+ "Install `torchao<0.18`, or upgrade torch." % (name, detail))
+
+ def _make(msg):
+ class _Meta(type):
+ def __getattr__(cls, item):
+ raise RuntimeError(msg)
+
+ def __call__(cls, *args, **kwargs):
+ raise RuntimeError(msg)
+ return _Meta
+
+ try:
+ placeholder = _make(message)(name, (), {"__doc__": message})
+ type.__setattr__(placeholder, "__unsloth_placeholder__", True)
+ setattr(F, name, placeholder)
+ except Exception:
+ pass
+
+ # torchao also hangs a handler off aten._grouped_mm at import time, and
+ # that operator only exists from torch 2.8. Same skew, different lookup:
+ # supplying the torch.nn.functional names above does not help it.
+ try:
+ torch.ops.aten._grouped_mm
+ except AttributeError:
+ op_message = (
+ "Unsloth: `torch.ops.aten._grouped_mm` does not exist in this "
+ "torch. torchao %s registers a handler for it at import time, but "
+ "torch %s does not provide it (it arrived in torch 2.8). Unsloth "
+ "registered a placeholder schema so the import succeeds; the "
+ "operator itself cannot be used."
+ % (version, torch.__version__))
+
+ def _refuse(self, mat2, offs=None, bias=None, out_dtype=None):
+ raise RuntimeError(op_message)
+
+ try:
+ # Held on the module so the Library is not collected -- that
+ # would deregister the schema again.
+ global _ATEN_LIBRARY
+ _ATEN_LIBRARY = torch.library.Library("aten", "FRAGMENT")
+ _ATEN_LIBRARY.define(
+ "_grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, "
+ "Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor")
+ _ATEN_LIBRARY.impl("_grouped_mm", _refuse,
+ "CompositeExplicitAutograd")
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+
+_ATEN_LIBRARY = None
+
+
+class _TorchaoImportHook:
+ """Runs the fix when a child actually imports torchao, and not before.
+
+ This module is on PYTHONPATH, so it starts every Python descendant, most
+ of which never touch torchao. Calling `_apply()` here would import torch
+ in all of them, adding seconds of startup and torch's memory to unrelated
+ utilities and workers. A meta_path finder costs a string compare instead,
+ and still runs before torchao's module body, which is the only ordering
+ the fix needs.
+ """
+
+ def find_spec(self, fullname, path = None, target = None):
+ if fullname != "torchao":
+ return None
+ try:
+ sys.meta_path.remove(self) # once, and before _apply imports torch
+ except ValueError:
+ pass
+ try:
+ _apply()
+ except Exception:
+ pass
+ return None # let the normal finders import torchao
+
+
+# Chaining gives our name away to the real sitecustomize, so keep our own
+# module object alive here: the finder below outlives this file's execution.
+_SELF = sys.modules.get(__name__)
+_chain_to_the_real_sitecustomize()
+try:
+ sys.meta_path.insert(0, _TorchaoImportHook())
+except Exception:
+ # Never let this abort interpreter startup: it would break every
+ # subprocess, which is far worse than the import error it fixes.
+ pass
+'''
+
+
+def _write_hook_atomically(target, source):
+ """Put `source` at `target` without ever writing through a symlink.
+
+ A predictable temporary name (`sitecustomize.py.<pid>.tmp`) can be
+ pre-created as a symlink while the directory is still group- or
+ world-writable: tightening it afterwards does not revoke what is already
+ inside. The write would land on a file the other user owns, and os.replace
+ renames the link itself into place, so `sitecustomize.py` stays theirs to
+ rewrite. A random name opened O_EXCL|O_NOFOLLOW cannot be pre-empted and
+ refuses a symlink instead of following it.
+ """
+ import binascii
+
+ directory = os.path.dirname(target)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ flags |= getattr(os, "O_BINARY", 0)
+ payload = source.encode("utf-8")
+ for _ in range(16):
+ tmp = os.path.join(
+ directory,
+ ".sitecustomize.py.%s.tmp" % binascii.hexlify(os.urandom(8)).decode(),
+ )
+ try:
+ handle = os.open(tmp, flags, 0o600) # nobody else may rewrite it
+ except FileExistsError:
+ continue
+ try:
+ try:
+ os.fchmod(handle, 0o600) # a loose umask must not widen it
+ except Exception:
+ pass
+ with os.fdopen(handle, "wb") as stream:
+ stream.write(payload)
+ os.replace(tmp, target) # atomic
+ except BaseException:
+ # A random name is never reused, so a failed attempt would be
+ # litter rather than something the next run overwrites.
+ try:
+ os.unlink(tmp)
+ except Exception:
+ pass
+ raise
+ return
+ raise RuntimeError("could not create a private temporary file in " + directory)
+
+
+def _existing_hook_is_trustworthy(target):
+ """Can the file already at `target` only have been written by us?
+
+ Tightening the directory does not revoke access to what is already inside
+ it: a file planted while it was group- or world-writable stays foreign
+ owned, or is a symlink into somewhere still writable. This file runs in
+ every Python descendant, so anything but a private regular file of ours is
+ replaced outright, even when its contents match, which is exactly what an
+ attacker would arrange to skip the write below.
+ """
+ import stat
+
+ try:
+ info = os.lstat(target)
+ except FileNotFoundError:
+ return True # nothing there yet; the write creates it
+ except Exception:
+ return False
+ if not stat.S_ISREG(info.st_mode): # symlink, directory, fifo, device
+ return False
+ if hasattr(os, "getuid") and info.st_uid != os.getuid():
+ return False
+ # Writable by anyone else means its contents prove nothing.
+ return not stat.S_IMODE(info.st_mode) & 0o022
+
+
+def _torch_really_has(F, name):
+ """Does torch itself provide `name`, or is it a placeholder we installed?
+
+ `_gpu_init` runs `fix_torchao_torch_symbol_skew()` just before the function
+ below, so a plain `hasattr` would read as healthy in exactly the
+ environments the child fix exists for.
+ """
+ symbol = getattr(F, name, None)
+ if symbol is None:
+ return False
+ return not getattr(symbol, "__unsloth_placeholder__", False)
+
+
+def propagate_torchao_fix_to_subprocesses():
+ """Make the torchao fix apply to child processes too.
+
+ A no-op unless the fix is needed: returns early when torchao is absent,
+ old enough to guard its own import, or when torch already has the symbols.
+ Nothing is written and PYTHONPATH is untouched on a healthy pair.
+
+ The generated file inlines the symbol fix rather than importing unsloth: a
+ sitecustomize runs at the start of every subprocess on the machine, so an
+ `import unsloth` there would pay the full import cost each time and could
+ recurse through this function. Anything else found to be needed should be
+ inlined here too. The other two torchao fixes need no child: both guard
+ work in this process (LoRA construction, `import torchtune` via xcodec2),
+ and the vLLM inspector this hook exists for imports neither.
+
+ Returns the directory added to PYTHONPATH, or None.
+ """
+ if importlib.util.find_spec("torchao") is None:
+ return None
+ try:
+ if Version(importlib_version("torchao")) < Version("0.18.0"):
+ return None
+ except Exception:
+ return None
+ try:
+ import torch.nn.functional as F
+
+ # Both halves of the skew must be absent for there to be nothing to do.
+ # Today a torch missing the operator also misses the functional symbols
+ # (2.8 vs 2.10), so the second check never fires alone; it keeps the
+ # gate correct if that ever stops holding. Our own patches do not count
+ # as torch being new enough: the in-process fix ran first.
+ if (
+ all(_torch_really_has(F, n) for n in _TORCHAO_TORCH_SYMBOLS)
+ and _aten_grouped_mm_library is None
+ and not _torch_op_is_missing("aten", "_grouped_mm")
+ ):
+ return None # this torch is new enough; nothing to do
+ except Exception:
+ return None
+
+ try:
+ directory = _subprocess_fix_directory()
+ target = os.path.join(directory, "sitecustomize.py")
+ source = _subprocess_sitecustomize_source()
+ # Rewrite only when it differs, so concurrent runs do not fight and a
+ # reader never sees a truncated file. Matching contents only count as
+ # evidence when the file is ours: see the helper. A directory in the
+ # way makes os.replace raise, which the handler below turns into "no
+ # subprocess fix" rather than into a hook we do not trust.
+ if _existing_hook_is_trustworthy(target):
+ try:
+ existing = open(target, "r", encoding = "utf-8").read()
+ except Exception:
+ existing = None
+ else:
+ existing = None
+ if existing != source:
+ _write_hook_atomically(target, source)
+ except Exception as exception:
+ logger.warning(
+ "Unsloth: could not stage the torchao subprocess fix (%s). vLLM "
+ "may fail to inspect model architectures.",
+ exception,
+ )
+ return None
+
+ # os.pathsep, not ":" -- Windows uses ";".
+ current = os.environ.get("PYTHONPATH", "")
+ # An empty component is an import location, not padding: it is what
+ # `PYTHONPATH="$PYTHONPATH:/opt/lib"` leaves behind when PYTHONPATH was
+ # unset, and CPython reads it as the cwd, so dropping it would take an
+ # import location away from every descendant. A SET-BUT-EMPTY PYTHONPATH is
+ # the opposite case: CPython ignores it entirely, so it must not become a
+ # lone "" component, which would ADD the cwd instead.
+ parts = current.split(os.pathsep) if current else []
+ if directory not in parts:
+ os.environ["PYTHONPATH"] = os.pathsep.join([directory] + parts)
+ logger.info(
+ "Unsloth: torchao %s needs torch symbols this torch lacks. Added "
+ "a sitecustomize to PYTHONPATH so subprocesses (vLLM's model "
+ "inspector) can import torchao too.",
+ importlib_version("torchao"),
+ )
+ return directory
+
+
+# torchao 0.18.0 moved `torchao/dtypes/nf4tensor.py` under
+# `quantization/quantize_/workflows/nf4/`, but torchtune (and xcodec2 through
+# it) still imports the old path and dies with ModuleNotFoundError.
+#
+# Same shape as the vLLM tokenizer stub above: a meta path finder APPENDED
+# after the real ones, so an older torchao that still ships the module wins,
+# and the alias resolves lazily so `import unsloth` pays nothing.
+_TORCHAO_NF4_OLD = "torchao.dtypes.nf4tensor"
+_TORCHAO_NF4_NEW = "torchao.quantization.quantize_.workflows.nf4.nf4_tensor"
+_TORCHAO_NF4_SENTINEL = "__unsloth_torchao_nf4_alias__"
+
+
+class _TorchaoNF4AliasLoader(importlib.abc.Loader):
+ __slots__ = ("module_name", "real_spec")
+
+ def __init__(self, module_name):
+ self.module_name = module_name
+ self.real_spec = None
+
+ def create_module(self, spec):
+ # Return the RELOCATED module itself, not a stub with a hand-copied
+ # surface: torchtune then sees whatever torchao actually ships, and
+ # this cannot rot as symbols are added.
+ module = importlib.import_module(_TORCHAO_NF4_NEW)
+ # module_from_spec is about to overwrite this shared object's __spec__
+ # with the old-name one (_bootstrap.py assigns __spec__ unconditionally,
+ # unlike every other attribute), which would leave find_spec reporting
+ # the old name for the new module and make reload run the no-op
+ # exec_module below instead of the file.
+ self.real_spec = getattr(module, "__spec__", None)
+ return module
+
+ def exec_module(self, module):
+ # Already imported, so nothing to execute. Put back the __spec__
+ # module_from_spec just clobbered.
+ if self.real_spec is not None:
+ try:
+ module.__spec__ = self.real_spec
+ except Exception:
+ pass
+ return None
+
+
+class _TorchaoNF4AliasFinder(importlib.abc.MetaPathFinder):
+ __slots__ = (_TORCHAO_NF4_SENTINEL,)
+
+ def __init__(self):
+ setattr(self, _TORCHAO_NF4_SENTINEL, True)
+
+ def find_spec(
+ self,
+ fullname,
+ path = None,
+ target = None,
+ ):
+ if fullname != _TORCHAO_NF4_OLD:
+ return None
+ try:
+ if importlib.util.find_spec(_TORCHAO_NF4_NEW) is None:
+ return None # neither layout: let the real ImportError happen
+ except Exception:
+ return None
+ return importlib.machinery.ModuleSpec(
+ name = fullname,
+ loader = _TorchaoNF4AliasLoader(fullname),
+ is_package = False,
+ )
+
+
+def fix_torchao_nf4tensor_move():
+ if importlib.util.find_spec("torchao") is None:
+ return
+ for finder in sys.meta_path:
+ if getattr(finder, _TORCHAO_NF4_SENTINEL, False):
+ return
+ # Appended, not inserted at 0, so a real module on older torchao wins.
+ sys.meta_path.append(_TorchaoNF4AliasFinder())
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 12cbe4dca01..77a7e663ad7 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -3198,6 +3198,34 @@ def patch_gradient_accumulation_fix(Trainer):
exec(function, globals())
Trainer.training_step = _unsloth_training_step
+ # Settle any deferred compile-mode switch at the start of every step.
+ # On recompile-limit exhaustion unsloth_zoo defers the switch to eager
+ # instead of flipping mid-call: non-reentrant checkpointing packs the
+ # forward compiled and would recompute it eagerly, aborting the backward
+ # with "Something went unexpectedly wrong in activation checkpoint".
+ # Between steps nothing is half-packed, so the switch is free.
+ if not getattr(Trainer, "_unsloth_settles_eager_fallbacks", False):
+ try:
+ from unsloth_zoo.temporary_patches.utils import (
+ apply_pending_eager_fallbacks as _apply_pending_eager_fallbacks,
+ )
+ except Exception:
+ # Older unsloth_zoo has no deferred switch, so nothing to settle.
+ _apply_pending_eager_fallbacks = None
+ if _apply_pending_eager_fallbacks is not None:
+ _training_step_before_settle = Trainer.training_step
+
+ @functools.wraps(_training_step_before_settle)
+ def _unsloth_training_step_settling_fallbacks(self, *args, **kwargs):
+ try:
+ _apply_pending_eager_fallbacks()
+ except Exception:
+ pass
+ return _training_step_before_settle(self, *args, **kwargs)
+
+ Trainer.training_step = _unsloth_training_step_settling_fallbacks
+ Trainer._unsloth_settles_eager_fallbacks = True
+
# Wrap Trainer.__init__: (1) pre-init, shadow accepts_loss_kwargs on whatever
# model was passed in (covers PEFT wrapping done after FastModel.from_pretrained);
# (2) post-init, clamp accelerator GA to 1 for the transformers 5.0-5.5