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.

Import fixes: disable a torchao too new for the installed torch instead of failing import unsloth (#15850)

Daniel Hanef8bc8774294
diff --git a/tests/test_torchao_subprocess_fix.py b/tests/test_torchao_subprocess_fix.py
index 5675d719109..48ffe265c5c 100644
--- a/tests/test_torchao_subprocess_fix.py
+++ b/tests/test_torchao_subprocess_fix.py
@@ -470,6 +470,9 @@ def test_the_in_process_fix_does_not_disable_the_subprocess_fix(monkeypatch, tmp
"""The gate must not trust hasattr, because the in-process fix installs placeholders that pass it."""
import torch.nn.functional as F
+ if IF.TORCHAO_DISABLED_FOR_OLD_TORCH:
+ pytest.skip("import unsloth disabled torchao for this torch; there is no torchao to shim")
+
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")
diff --git a/tests/test_torchao_too_new_for_torch.py b/tests/test_torchao_too_new_for_torch.py
new file mode 100644
index 00000000000..602046424b2
--- /dev/null
+++ b/tests/test_torchao_too_new_for_torch.py
@@ -0,0 +1,200 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A torchao too new for the installed torch reads as absent instead of failing `import unsloth`.
+
+`pip install unsloth` on torch 2.6 resolves torchao 0.18 (unsloth_zoo pins only `torchao>=0.13`),
+and transformers' quantizer import then dies on `torch.float4_e2m1fn_x2`. The torchao and torch
+versions are simulated, so this runs on any torch, CPU only.
+"""
+
+import functools
+import os
+import subprocess
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+import unsloth.import_fixes as import_fixes # noqa: E402
+
+GPU_INIT = ROOT / "unsloth" / "_gpu_init.py"
+
+
+def _write_fake_torchao(root, quantization_body):
+ package = root / "torchao"
+ (package / "quantization").mkdir(parents = True)
+ (package / "__init__.py").write_text("")
+ (package / "quantization" / "__init__.py").write_text(quantization_body)
+ return root
+
+
+def isolated(monkeypatch, tmp_path):
+ """Fake torchao on sys.path, real torchao modules and our flag restored afterwards."""
+ saved = {n: m for n, m in sys.modules.items() if n == "torchao" or n.startswith("torchao.")}
+ for name in saved:
+ del sys.modules[name]
+ monkeypatch.setattr(import_fixes, "TORCHAO_DISABLED_FOR_OLD_TORCH", False)
+ monkeypatch.syspath_prepend(str(tmp_path))
+ importlib.invalidate_caches()
+
+ def configure(torch_version, torchao_version, quantization_body):
+ import torch
+
+ _write_fake_torchao(tmp_path, quantization_body)
+ importlib.invalidate_caches()
+ monkeypatch.setattr(torch, "__version__", torch_version)
+ monkeypatch.setattr(import_fixes, "importlib_version", lambda name: torchao_version)
+
+ yield configure
+ for name in [n for n in list(sys.modules) if n == "torchao" or n.startswith("torchao.")]:
+ del sys.modules[name]
+ sys.modules.update(saved)
+ importlib.invalidate_caches()
+
+
+MISSING_TORCH_DTYPE = "import torch\nX = torch.float4_e2m1fn_x2_not_in_any_torch\n"
+
+
+def test_torchao_018_on_torch_26_is_disabled_not_fatal(isolated, capsys):
+ isolated("2.6.0+cu124", "0.18.0", MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert sys.modules["torchao"] is None
+ assert importlib.util.find_spec("torchao") is None
+ with pytest.raises(ImportError):
+ import torchao # noqa: F401
+ out = capsys.readouterr().out
+ assert "torchao==0.18.0" in out and "torch==2.6.0+cu124" in out
+ assert 'pip install "torchao<0.14"' in out, "names the torchao that supports torch 2.6"
+
+
+def test_torchao_that_imports_is_left_alone(isolated):
+ """torchao 0.15 / 0.16 / 0.17 do import on torch 2.6 (with the existing shims): never disable them."""
+ isolated("2.6.0", "0.18.0", "")
+ assert import_fixes.disable_torchao_if_torch_too_old() is False
+ assert sys.modules.get("torchao") is not None
+ assert import_fixes.TORCHAO_DISABLED_FOR_OLD_TORCH is False
+
+
+ "torch_version, torchao_version",
+ [
+ ("2.6.0", "0.13.0"),
+ ("2.7.1", "0.15.0"),
+ ("2.8.0", "0.16.0"),
+ ("2.9.0", "0.18.0"),
+ ("2.14.1", "0.18.0"),
+ ],
+)
+def test_supported_pairs_are_not_even_probed(isolated, torch_version, torchao_version):
+ isolated(torch_version, torchao_version, MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is False
+ assert "torchao" not in sys.modules, "a supported pair must not import torchao early"
+
+
+def test_a_real_torchao_failure_is_not_hidden(isolated):
+ """Only torch's missing-name wording counts; anything else must surface where it did before."""
+ isolated("2.6.0", "0.18.0", "raise RuntimeError('broken torchao build')\n")
+ assert import_fixes.disable_torchao_if_torch_too_old() is False
+ assert "torchao" not in sys.modules or sys.modules["torchao"] is not None
+ assert import_fixes.TORCHAO_DISABLED_FOR_OLD_TORCH is False
+
+
+def test_missing_torch_import_name_counts_as_skew(isolated):
+ isolated("2.7.1", "0.18.0", "from torch.nn.functional import NotInAnyTorchUnslothTest\n")
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert sys.modules["torchao"] is None
+
+
+def test_cached_availability_checks_are_cleared(isolated, monkeypatch):
+ """A library imported before unsloth cached True; it must answer False afterwards."""
+
+ @functools.lru_cache
+ def is_torchao_available(*args, **kwargs):
+ return True
+
+ fake = types.ModuleType("peft.import_utils")
+ fake.is_torchao_available = is_torchao_available
+ monkeypatch.setitem(sys.modules, "peft.import_utils", fake)
+ isolated("2.6.0", "0.18.0", MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert fake.is_torchao_available() is False
+
+
+def test_calling_twice_is_stable(isolated, capsys):
+ isolated("2.6.0", "0.18.0", MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert sys.modules["torchao"] is None
+ assert capsys.readouterr().out.count("disabled for this process") == 1
+
+
+def test_it_runs_after_the_torchao_shims_and_before_unsloth_zoo():
+ source = GPU_INIT.read_text()
+ call = source.index("\ndisable_torchao_if_torch_too_old()\n")
+ assert source.index("\nfix_torchao_torch_symbol_skew()\n") < call
+ assert source.index("\nfix_torchao_pytree_register_constant()\n") < call
+ assert source.index("\nfix_torchao_without_torch_distributed()\n") < call
+ assert call < source.index(" import unsloth_zoo\n")
+ assert "\ndel disable_torchao_if_torch_too_old\n" in source
+
+
+def test_disable_records_the_pair_for_subprocesses(isolated, monkeypatch):
+ monkeypatch.delenv(import_fixes._TORCHAO_DISABLED_ENV, raising = False)
+ isolated("2.6.0", "0.18.0", MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ assert os.environ[import_fixes._TORCHAO_DISABLED_ENV] == "0.18.0|0.18.0"
+
+
+def test_propagation_is_staged_when_torchao_was_disabled(monkeypatch, tmp_path):
+ monkeypatch.setattr(import_fixes, "TORCHAO_DISABLED_FOR_OLD_TORCH", True)
+ monkeypatch.setattr(import_fixes, "_subprocess_fix_directory", lambda: str(tmp_path))
+ monkeypatch.setenv("PYTHONPATH", "")
+ assert import_fixes.propagate_torchao_fix_to_subprocesses() == str(tmp_path)
+ assert (tmp_path / "sitecustomize.py").exists()
+
+
+def _child_sees_torchao(tmp_path, marker):
+ (tmp_path / "sitecustomize.py").write_text(import_fixes._subprocess_sitecustomize_source())
+ env = dict(os.environ, PYTHONPATH = str(tmp_path))
+ env.pop(import_fixes._TORCHAO_DISABLED_ENV, None)
+ if marker is not None:
+ env[import_fixes._TORCHAO_DISABLED_ENV] = marker
+ out = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import importlib.util; print(importlib.util.find_spec('torchao') is not None)",
+ ],
+ env = env,
+ capture_output = True,
+ text = True,
+ check = True,
+ ).stdout.strip()
+ return out == "True"
+
+
+def test_child_hides_torchao_only_for_the_same_pair(tmp_path):
+ from importlib.metadata import version
+
+ if importlib.util.find_spec("torchao") is None:
+ pytest.skip("torchao not installed")
+ pair = f"{version('torchao')}|{version('torch')}"
+ assert _child_sees_torchao(tmp_path, None) is True
+ assert _child_sees_torchao(tmp_path, pair) is False
+ assert (
+ _child_sees_torchao(tmp_path, "0.0.1|" + version("torch")) is True
+ ), "another env keeps its torchao"
+
+
+def test_torch_25_is_told_to_upgrade_torch_not_pin_below_the_zoo_floor(isolated, capsys):
+ isolated("2.5.1", "0.18.0", MISSING_TORCH_DTYPE)
+ assert import_fixes.disable_torchao_if_torch_too_old() is True
+ out = capsys.readouterr().out
+ assert "torchao<0.13" not in out and "torch>=2.6" in out
diff --git a/tests/test_torchao_torch_symbol_skew.py b/tests/test_torchao_torch_symbol_skew.py
index 6d2e59cf9a7..69eee41b22e 100644
--- a/tests/test_torchao_torch_symbol_skew.py
+++ b/tests/test_torchao_torch_symbol_skew.py
@@ -167,6 +167,8 @@ def test_the_real_torchao_018_import_line_is_unblocked(monkeypatch):
if getattr(getattr(F, n, None), "__unsloth_placeholder__", False):
delattr(F, n)
+ if IF.TORCHAO_DISABLED_FOR_OLD_TORCH:
+ pytest.skip("import unsloth disabled torchao for this torch; there is no torchao to shim")
# Gate on these two: `any` over the tuple is always true via scaled_dot_product_attention.
if all(hasattr(F, n) for n in ("ScalingType", "SwizzleType")):
pytest.skip("this torch already provides ScalingType/SwizzleType")
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index 5e67910983d..64088a2dc89 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -29,6 +29,7 @@ from .import_fixes import (
fix_torch_check_is_size,
fix_torchao_torch_symbol_skew,
fix_torchao_pytree_register_constant,
+ disable_torchao_if_torch_too_old,
propagate_torchao_fix_to_subprocesses,
check_fbgemm_gpu_version,
check_transformers_dependency_versions,
@@ -93,6 +94,8 @@ from ._torchao_nodist import fix_torchao_without_torch_distributed
fix_torchao_without_torch_distributed()
del fix_torchao_without_torch_distributed
+# After the torchao shims, before transformers imports torchao: a torchao too new for this torch reads as absent.
+disable_torchao_if_torch_too_old()
disable_broken_causal_conv1d()
disable_broken_vllm()
fix_message_factory_issue()
@@ -121,6 +124,7 @@ del patch_torch_missing_attribute_error
del fix_torch_check_is_size
del fix_torchao_torch_symbol_skew
del fix_torchao_pytree_register_constant
+del disable_torchao_if_torch_too_old
del propagate_torchao_fix_to_subprocesses
del check_fbgemm_gpu_version
del check_transformers_dependency_versions
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 2f1c8294c80..1c2dcb3d57c 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -11555,6 +11555,140 @@ def fix_torchao_pytree_register_constant():
return True
+# Newest torchao release whose Python API supports each torch minor (pytorch/ao#2919); newer torch has no ceiling.
+_TORCHAO_NEWEST_FOR_TORCH = {
+ (2, 4): (0, 12),
+ (2, 5): (0, 12),
+ (2, 6): (0, 13),
+ (2, 7): (0, 15),
+ (2, 8): (0, 16),
+}
+
+# What importing transformers / peft pulls from torchao at module scope (transformers 5 quantizer_torchao, peft lora).
+_TORCHAO_IMPORT_TIME_MODULES = (
+ "torchao",
+ "torchao.quantization",
+ "torchao.prototype.safetensors.safetensors_support",
+)
+
+# "<torchao>|<torch>" metadata versions; the subprocess sitecustomize hides torchao only on an exact match.
+_TORCHAO_DISABLED_ENV = "UNSLOTH_TORCHAO_DISABLED_FOR"
+
+TORCHAO_DISABLED_FOR_OLD_TORCH = False
+
+
+def _release_pair(version_string):
+ match = re.match(r"\s*(\d+)\.(\d+)", str(version_string))
+ return (int(match.group(1)), int(match.group(2))) if match else None
+
+
+def _is_torchao_torch_skew_error(error):
+ """Only torch's own missing-name wording; any other torchao failure stays visible."""
+ message = str(error)
+ if isinstance(error, AttributeError):
+ return message.startswith("module 'torch") and "has no attribute" in message
+ if isinstance(error, ImportError):
+ return "cannot import name" in message and "from 'torch" in message
+ return False
+
+
+def _hide_torchao_from_dependents():
+ """Make torchao read as not installed, as `disable_torchaudio_if_cuda_mismatched` does."""
+ for name in [n for n in list(sys.modules) if n == "torchao" or n.startswith("torchao.")]:
+ sys.modules.pop(name, None)
+ # find_spec returns None and `import torchao` raises ModuleNotFoundError: every guard takes its no-torchao branch.
+ sys.modules["torchao"] = None
+ # Libraries imported before unsloth cached the answer.
+ for module_name, flag_names in (
+ ("transformers.utils.import_utils", ("_torchao_available",)),
+ ("transformers.utils", ()),
+ ("peft.import_utils", ()),
+ ("diffusers.utils.import_utils", ("_torchao_available",)),
+ ):
+ module = sys.modules.get(module_name)
+ if module is None:
+ continue
+ for flag_name in flag_names:
+ if hasattr(module, flag_name):
+ try:
+ setattr(module, flag_name, False)
+ except Exception:
+ pass
+ check = getattr(module, "is_torchao_available", None)
+ if check is None:
+ continue
+ try:
+ check.cache_clear()
+ except AttributeError:
+ pass
+ try:
+ setattr(module, "is_torchao_available", lambda *args, **kwargs: False)
+ except Exception:
+ pass
+
+
+def disable_torchao_if_torch_too_old():
+ """Treat a torchao built for a newer torch as not installed instead of failing `import unsloth`.
+
+ unsloth_zoo's uncapped `torchao>=0.13.0` resolves 0.18 on torch 2.6, whose import reads
+ `torch.float4_e2m1fn_x2` (torch 2.7+). Disables only on a real missing torch name.
+ """
+ global TORCHAO_DISABLED_FOR_OLD_TORCH
+ if TORCHAO_DISABLED_FOR_OLD_TORCH:
+ _hide_torchao_from_dependents()
+ return True
+ try:
+ if "torchao" in sys.modules or importlib.util.find_spec("torchao") is None:
+ return False
+ torchao_version = importlib_version("torchao")
+ torchao_release = _release_pair(torchao_version)
+ import torch
+
+ torch_version = str(torch.__version__)
+ newest = _TORCHAO_NEWEST_FOR_TORCH.get(_release_pair(torch_version))
+ except Exception:
+ return False
+ if newest is None or torchao_release is None or torchao_release <= newest:
+ return False
+ reason = None
+ for module_name in _TORCHAO_IMPORT_TIME_MODULES:
+ try:
+ importlib.import_module(module_name)
+ except Exception as error:
+ if _is_torchao_torch_skew_error(error):
+ reason = str(error).split("\n", 1)[0]
+ break
+ if isinstance(error, ModuleNotFoundError) and str(
+ getattr(error, "name", "")
+ ).startswith("torchao"):
+ # An older torchao without this submodule: nothing imports it there.
+ continue
+ return False
+ if reason is None:
+ return False
+ TORCHAO_DISABLED_FOR_OLD_TORCH = True
+ _hide_torchao_from_dependents()
+ try:
+ os.environ[_TORCHAO_DISABLED_ENV] = (
+ f"{importlib_version('torchao')}|{importlib_version('torch')}"
+ )
+ except Exception:
+ pass
+ # unsloth_zoo needs torchao>=0.13, so below that only a newer torch is installable.
+ remedy = (
+ f' pip install "torchao<{newest[0]}.{newest[1] + 1}"\nor a newer torch.'
+ if newest >= (0, 13)
+ else ' pip install --upgrade "torch>=2.6"'
+ )
+ print(
+ f"Unsloth: torchao=={torchao_version} does not support torch=={torch_version} "
+ f"({reason}), so torchao is disabled for this process and everything that does "
+ f"not use it keeps working. QAT, torchao float8 and torchao-quantized checkpoints "
+ f"need a torchao that matches this torch:\n{remedy}"
+ )
+ return True
+
+
# vLLM inspects architectures in a separate process that imports torchao itself, never sees a
# parent monkey-patch, and fails the same way. sitecustomize is the one hook reaching a process
# we do not launch: site imports it at startup off the inherited PYTHONPATH. A .pth would need
@@ -11614,8 +11748,9 @@ def _subprocess_sitecustomize_source():
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)."""
+predates the symbols torchao 0.18 imports unconditionally, or hides a torchao
+the parent disabled, in processes unsloth did not launch (notably vLLM's
+model-architecture inspector)."""
import os
import sys
@@ -11796,6 +11931,15 @@ class _TorchaoImportHook:
# module object alive here: the finder below outlives this file's execution.
_SELF = sys.modules.get(__name__)
_chain_to_the_real_sitecustomize()
+# The parent disabled a torchao too new for its torch; hide it here only for the same torchao and torch.
+try:
+ _expected = os.environ.get("UNSLOTH_TORCHAO_DISABLED_FOR")
+ if _expected:
+ import importlib.metadata as _md
+ if _expected == "%s|%s" % (_md.version("torchao"), _md.version("torch")):
+ sys.modules["torchao"] = None
+except Exception:
+ pass
try:
sys.meta_path.insert(0, _TorchaoImportHook())
except Exception:
@@ -11890,12 +12034,30 @@ def _torch_really_has(F, name):
return not getattr(symbol, "__unsloth_placeholder__", False)
+def _child_torchao_symbol_fix_needed():
+ if importlib.util.find_spec("torchao") is None:
+ return False
+ try:
+ if Version(importlib_version("torchao")) < Version("0.18.0"):
+ return False
+ import torch.nn.functional as F
+
+ # Our own in-process patches do not count as torch having the symbols.
+ return not (
+ 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")
+ )
+ except Exception:
+ return 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.
+ A no-op unless the symbol fix is needed (torchao 0.18+ on a torch missing its
+ symbols) or `disable_torchao_if_torch_too_old` disabled torchao here. 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
@@ -11907,24 +12069,7 @@ def propagate_torchao_fix_to_subprocesses():
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
-
- # Nothing to do only when both the functional symbols and the aten op are missing; our own in-process patches do not count.
- 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:
+ if not TORCHAO_DISABLED_FOR_OLD_TORCH and not _child_torchao_symbol_fix_needed():
return None
try:
@@ -11956,9 +12101,9 @@ def propagate_torchao_fix_to_subprocesses():
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.",
+ "Unsloth: torchao %s does not match this torch. Added a "
+ "sitecustomize to PYTHONPATH so subprocesses (vLLM's model "
+ "inspector) get the same torchao fix.",
importlib_version("torchao"),
)
return directory