Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Name the matching build when flash-attn or causal-conv1d was built for another torch (#12211)
Daniel Hanf9672f312dc0
diff --git a/tests/test_stale_kernel_hint.py b/tests/test_stale_kernel_hint.pynew file mode 100644index 00000000000..c309b22e4a8--- /dev/null+++ b/tests/test_stale_kernel_hint.py@@ -0,0 +1,193 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A flash-attn / causal-conv1d build for another torch fails with "undefined symbol" and Unsloth+falls back to slower kernels; the hint says how to get matching ones back."""++import importlib.util+import pathlib+import sys+import types++import pytest++_REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]+_STALE = ImportError(+ "/venv/lib/python3.13/site-packages/flash_attn_2_cuda.cpython-313-x86_64-linux-gnu.so: "+ "undefined symbol: _ZN3c104cuda29c10_cuda_check_implementationEiPKcS2_ib"+)+++def _load_import_fixes():+ # By path: importing the unsloth package needs an accelerator.+ spec = importlib.util.spec_from_file_location(+ "unsloth_import_fixes_stale_kernel", _REPO_ROOT / "unsloth" / "import_fixes.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++[email protected](scope = "module")+def fixes():+ return _load_import_fixes()+++def _host(+ monkeypatch,+ fixes,+ *,+ torch_version = "2.14.0+cu130",+ cuda = "13.0",+ py = (3, 13),+ machine = "x86_64",+ platform = "linux",+ cxx11 = True,+ libc = ("glibc", "2.35"),+ free_threaded = False,+):+ fake_torch = types.SimpleNamespace(+ __version__ = torch_version,+ version = types.SimpleNamespace(cuda = cuda),+ _C = types.SimpleNamespace(_GLIBCXX_USE_CXX11_ABI = cxx11),+ )+ monkeypatch.setitem(sys.modules, "torch", fake_torch)+ monkeypatch.setattr(fixes.sys, "platform", platform)+ monkeypatch.setattr(fixes.sys, "version_info", (*py, 0, "final", 0))+ monkeypatch.setattr(fixes.platform, "machine", lambda: machine)+ monkeypatch.setattr(fixes.platform, "libc_ver", lambda: libc)+ real = fixes.sysconfig.get_config_var+ monkeypatch.setattr(+ fixes.sysconfig,+ "get_config_var",+ lambda name: (1 if free_threaded else 0) if name == "Py_GIL_DISABLED" else real(name),+ )+++ "package, wheel",+ [+ ("flash_attn", "flash_attn-2.8.4+cu13torch2.14cxx11abiTRUE-cp313-cp313-linux_x86_64.whl"),+ (+ "causal_conv1d",+ "causal_conv1d-1.7.0+cu13torch2.14cxx11abiTRUE-cp313-cp313-linux_x86_64.whl",+ ),+ ],+)+def test_a_published_cell_names_our_matching_wheel(monkeypatch, fixes, package, wheel):+ _host(monkeypatch, fixes)+ hint = fixes.stale_kernel_hint(package, _STALE)+ assert "built for a different torch than 2.14.0+cu130" in hint+ assert hint.endswith(+ "pip install --no-deps --force-reinstall "+ f"https://github.com/unslothai/unsloth/releases/download/prebuilt-wheels-cu13/{wheel}"+ )+++def test_the_wheel_names_are_the_published_ones(fixes):+ # Kept in step with the release the prebuilt workflow publishes (studio/backend/utils/wheel_utils.py).+ source = (_REPO_ROOT / "studio" / "backend" / "utils" / "wheel_utils.py").read_text(+ encoding = "utf-8"+ )+ for package, version in fixes._PREBUILT_KERNEL_VERSIONS.items():+ assert (+ f'"{package}": "{version}"' in source or f"'{package}': '{version}'" in source+ ), package+ assert fixes._PREBUILT_KERNEL_RELEASE_URL.endswith("/prebuilt-wheels-cu13")+++ "host",+ [+ {"torch_version": "2.12.1+cu130"},+ {"cuda": "12.8", "torch_version": "2.14.0+cu128"},+ {"py": (3, 12)},+ {"machine": "aarch64"},+ {"platform": "win32"},+ {"cxx11": False},+ {"libc": ("glibc", "2.31")},+ {"libc": ("", "")},+ {"free_threaded": True},+ {"torch_version": "2.14.0.dev20260901+cu130"},+ {"torch_version": "2.13.0rc1+cu130"},+ ],+)+def test_anywhere_else_it_names_a_source_rebuild(monkeypatch, fixes, host):+ _host(monkeypatch, fixes, **host)+ hint = fixes.stale_kernel_hint("causal_conv1d", _STALE)+ assert "releases/download" not in hint+ assert hint.endswith(+ "pip install --no-deps --no-build-isolation --no-cache-dir --force-reinstall --no-binary causal-conv1d causal-conv1d"+ )+++ "host, pinned",+ [+ ({"py": (3, 12)}, True),+ ({"torch_version": "2.14.0.dev20260901+cu130"}, True),+ ({"torch_version": "2.12.1+cu130"}, False),+ ],+)+def test_flash_attn_rebuilds_from_a_revision_that_compiles_on_torch_2_13(+ monkeypatch, fixes, host, pinned+):+ _host(monkeypatch, fixes, **host)+ hint = fixes.stale_kernel_hint("flash_attn", _STALE)+ if pinned:+ assert hint.endswith(f'--force-reinstall "{fixes._FLASH_ATTN_TORCH213_SOURCE}"')+ else:+ assert hint.endswith("--no-binary flash-attn flash-attn")+++def test_the_flash_attn_source_pin_is_the_one_the_prebuilt_wheels_use(fixes):+ source = (_REPO_ROOT / ".github" / "scripts" / "prebuilt_wheels.py").read_text(encoding = "utf-8")+ ref = fixes._FLASH_ATTN_TORCH213_SOURCE.rsplit("@", 1)[1]+ assert f'"ref": "{ref}"' in source+++ "symbol",+ [+ "_ZN3c1013MessageLoggerC1EPKciib",+ "_ZNK2at10TensorBase8data_ptrEv",+ "aoti_torch_create_device_guard",+ ],+)+def test_every_torch_abi_symbol_seen_in_practice_is_recognised(monkeypatch, fixes, symbol):+ _host(monkeypatch, fixes)+ error = ImportError(f"/x/causal_conv1d_cuda.so: undefined symbol: {symbol}")+ assert "causal_conv1d-1.7.0" in fixes.stale_kernel_hint("causal_conv1d", error)+++def test_a_chained_cause_is_found(monkeypatch, fixes):+ _host(monkeypatch, fixes)+ try:+ try:+ raise _STALE+ except ImportError as inner:+ raise RuntimeError("causal_conv1d import failed") from inner+ except RuntimeError as outer:+ assert "causal_conv1d-1.7.0" in fixes.stale_kernel_hint("causal_conv1d", outer)+++ "error",+ [+ ImportError("No module named 'flash_attn_2_cuda'"),+ OSError("libcudart.so.13: cannot open shared object file"),+ ImportError(+ "libcusparse.so.12: undefined symbol: __nvJitLinkAddData_12_8, version libnvJitLink.so.12"+ ),+ ],+)+def test_other_failures_add_nothing(monkeypatch, fixes, error):+ _host(monkeypatch, fixes)+ assert fixes.stale_kernel_hint("flash_attn", error) == ""+++def test_both_fallback_messages_print_the_hint():+ utils = (_REPO_ROOT / "unsloth" / "models" / "_utils.py").read_text(encoding = "utf-8")+ fixes_src = (_REPO_ROOT / "unsloth" / "import_fixes.py").read_text(encoding = "utf-8")+ assert 'if hint := stale_kernel_hint("flash_attn", error):' in utils+ assert 'hint = stale_kernel_hint("causal_conv1d", error)' in fixes_srcdiff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 0edc427ba6a..aca464a67dd 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -27,7 +27,9 @@ import reimport loggingimport textwrapimport warnings+import platformimport sys+import sysconfigimport threadingimport functoolsimport inspect@@ -9032,6 +9034,85 @@ def _is_broken_causal_conv1d_error(error) -> bool:return False+# Our Linux x86_64 cp313 CUDA 13 builds for torch 2.13 / 2.14, the minors whose extension ABI no+# upstream wheel matches (release prebuilt-wheels-cu13, .github/workflows/prebuilt-cuda-wheels.yml).+_PREBUILT_KERNEL_RELEASE_URL = (+ "https://github.com/unslothai/unsloth/releases/download/prebuilt-wheels-cu13"+)+_FLASH_ATTN_TORCH213_SOURCE = "flash-attn @ git+https://github.com/Dao-AILab/flash-attention@edb5c76ee329b18ed95d1f7ea9aa522a1331ab7d"+_PREBUILT_KERNEL_VERSIONS = {+ "flash_attn": "2.8.4",+ "causal_conv1d": "1.7.0",+ "mamba_ssm": "2.3.2.post1",+}+++def _glibc_at_least(major: int, minor: int) -> bool:+ # The builds run on ubuntu-22.04, and the linux_x86_64 tag lets pip install them on older glibc.+ try:+ name, version = platform.libc_ver()+ return name == "glibc" and tuple(int(x) for x in version.split(".")[:2]) >= (major, minor)+ except Exception:+ return False+++def stale_kernel_hint(package: str, error) -> str:+ """How to rebuild ``package`` when ``error`` says its extension was built for another torch, else ""."""+ checked = set()+ current = error+ while current is not None and id(current) not in checked:+ checked.add(id(current))+ # A torch ABI break leaves a mangled c10 / at / torch symbol unresolved; other undefined+ # symbols (e.g. CUDA libraries out of step) are not fixed by a rebuild.+ if re.search(r"undefined symbol: (?:_ZN\w*?(?:3c10|2at|5torch)|aoti_torch_)", str(current)):+ break+ current = getattr(current, "__cause__", None) or getattr(current, "__context__", None)+ else:+ return ""+ try:+ import torch++ torch_version = str(torch.__version__)+ cuda = str(torch.version.cuda or "")+ cxx11 = bool(getattr(torch._C, "_GLIBCXX_USE_CXX11_ABI", True))+ except Exception:+ return ""+ public = torch_version.split("+")[0]+ # Only a stable release matches the wheel; a nightly or rc of the same minor has its own ABI.+ stable = re.fullmatch(r"(\d+)\.(\d+)\.\d+", public)+ minor = ".".join(stable.groups()) if stable else ""+ loose = re.match(r"(\d+)\.(\d+)", public)+ torch_minor = tuple(int(x) for x in loose.groups()) if loose else (0, 0)+ head = f"Unsloth: {package} was built for a different torch than {torch_version}, so its fast kernels are off."+ if (+ package in _PREBUILT_KERNEL_VERSIONS+ and sys.platform.startswith("linux")+ and platform.machine().lower() in ("x86_64", "amd64")+ and sys.version_info[:2] == (3, 13)+ and not sysconfig.get_config_var("Py_GIL_DISABLED")+ and _glibc_at_least(2, 35)+ and minor in ("2.13", "2.14")+ and cuda.startswith("13.")+ and cxx11+ ):+ wheel = (+ f"{package}-{_PREBUILT_KERNEL_VERSIONS[package]}+cu13torch{minor}cxx11abiTRUE"+ "-cp313-cp313-linux_x86_64.whl"+ )+ return f"{head} To restore them:\n pip install --no-deps --force-reinstall {_PREBUILT_KERNEL_RELEASE_URL}/{wheel}"+ dist = package.replace("_", "-")+ if package == "flash_attn" and torch_minor >= (2, 13):+ # The last flash-attn release predates the c++20 switch torch 2.13 headers need.+ return (+ f"{head} To restore them, rebuild it against this torch:\n"+ f' pip install --no-deps --no-build-isolation --no-cache-dir --force-reinstall "{_FLASH_ATTN_TORCH213_SOURCE}"'+ )+ return (+ f"{head} To restore them, rebuild it against this torch:\n"+ f" pip install --no-deps --no-build-isolation --no-cache-dir --force-reinstall --no-binary {dist} {dist}"+ )++def _is_broken_vllm_error(error) -> bool:checked = set()current = error@@ -9530,6 +9611,7 @@ def disable_broken_causal_conv1d():except Exception as error:if not _is_broken_causal_conv1d_error(error):return+ hint = stale_kernel_hint("causal_conv1d", error)CAUSAL_CONV1D_BROKEN = True_clear_causal_conv1d_modules()@@ -9539,6 +9621,8 @@ def disable_broken_causal_conv1d():"Unsloth: Detected broken causal_conv1d binary; ""disabling causal_conv1d fast path and continuing import.")+ if hint:+ print(hint)_BNB_ROCM_DLL_RE = re.compile(r"libbitsandbytes_rocm(\d+)\.dll", re.IGNORECASE)diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 88c43c894aa..c3fea244978 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -139,7 +139,7 @@ from ..device_type import (apply_gfx101x_triton_workaround,gfx101x_triton_workaround_applied,)-from ..import_fixes import UNSLOTH_ENABLE_LOGGING+from ..import_fixes import UNSLOTH_ENABLE_LOGGING, stale_kernel_hintfrom unsloth_zoo.log import loggerfrom unsloth_zoo.tokenizer_utils import (patch_tokenizer as _patch_tokenizer,@@ -3468,11 +3468,13 @@ elif DEVICE_TYPE == "cuda":"To update flash-attn, do the below:\n"'\npip install --no-deps --no-build-isolation --upgrade "flash-attn>=2.6.3"')- except:+ except Exception as error:print("Unsloth: Your Flash Attention 2 installation seems to be broken. ""Using Xformers instead. No performance changes will be seen.")+ if hint := stale_kernel_hint("flash_attn", error):+ print(hint)import transformers.utils.import_utils