Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: skip xFormers when its torch requirement is unmet (#11847)
oobabooga14ceddf6b0e3
diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.pyindex 1b8d92b3247..00c0beb79e2 100644--- a/studio/backend/core/_torchao_stub.py+++ b/studio/backend/core/_torchao_stub.py@@ -11,7 +11,8 @@ Worker subprocesses call install_torchao_windows_rocm_stub() before importingtransformers / unsloth_zoo.xformers hits the same absent backend and takes diffusers with it, so the diffusion paths-install both stubs before importing diffusers.+install both stubs before importing diffusers. They also hide an xformers built for a newer+torch than the venv has, which fails the same import on any platform."""from __future__ import annotations@@ -236,3 +237,27 @@ def install_xformers_windows_rocm_stub() -> None:for _xf_name in ("xformers", "xformers.ops"):if _xf_name not in sys.modules:sys.modules[_xf_name] = _make_mod_stub(_xf_name)+++def hide_xformers_built_for_another_torch() -> None:+ """Hide an xFormers whose torch requirement is unmet (#11545); None, not a stub, so nothing sees usable attention."""+ if "xformers" in sys.modules:+ return+ try:+ if importlib.util.find_spec("xformers") is None:+ return+ from utils.wheel_utils import xformers_torch_requirement_unmet+ mismatch = xformers_torch_requirement_unmet()+ except Exception: # noqa: BLE001 -- a check that cannot answer leaves xformers alone+ return+ if mismatch is None:+ return+ sys.modules["xformers"] = None+ xformers_version, requirement, torch_version = mismatch+ print(+ f"Unsloth: xformers {xformers_version} requires torch{requirement} but torch "+ f"{torch_version} is installed, so it cannot be imported. Using PyTorch attention "+ "instead.",+ file = sys.stderr,+ flush = True,+ )diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex b8b1e67575f..e93134e2457 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -32,6 +32,7 @@ from pathlib import Pathfrom typing import Any, Callable, Optional, Sequencefrom core._torchao_stub import (+ hide_xformers_built_for_another_torch,install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,)@@ -230,6 +231,7 @@ logger = get_logger(__name__)# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent distributed# backend: diffusers imports xformers on sight, its quantizers torchao.install_xformers_windows_rocm_stub()+hide_xformers_built_for_another_torch()install_torchao_windows_rocm_stub()install_torchao_int_mm_patch()diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex 2d7aa36b485..a6829b901fe 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -444,6 +444,7 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Opt"""import importlib.utilimport os+ import sysspec = _INSTALLABLE_BACKENDS.get(backend)if spec is None:@@ -453,6 +454,18 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Optgate = os.environ.get(_ATTENTION_INSTALL_ENV, "auto").strip().lower()if gate in ("0", "false", "no", "off"):return None+ # A hidden package stays unusable until restart; skip without recording an attempt.+ if module in sys.modules and sys.modules[module] is None:+ reason = f"{module} is disabled in this process because it requires a different torch"+ if logger is not None:+ logger.warning(+ "diffusion.attention: not installing %s for backend=%s: %s; restart Studio "+ "once the installer has removed it. Using the default backend",+ package,+ backend,+ reason,+ )+ return reason# Refusing is a POLICY decision, not a failed attempt, so it is checked before the _INSTALL_ATTEMPTED memo below and# records nothing: a later request on a fixed environment must still be able to install. Scoped to kernels; the sage# / flash-attn / xformers wheels do not import huggingface_hub at module scope.@@ -507,7 +520,6 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Optreturn None_INSTALL_ATTEMPTED.add(package)import subprocess- import sysif logger is not None:logger.info(diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex c68b0f018d0..f7707677680 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -21,6 +21,7 @@ from pathlib import Pathfrom typing import Any, Callable, Optionalfrom core._torchao_stub import (+ hide_xformers_built_for_another_torch,install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,is_stubbed,@@ -39,6 +40,7 @@ from utils.paths.path_utils import drop_appledouble_metadata# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry# over. Both import this module first.install_xformers_windows_rocm_stub()+hide_xformers_built_for_another_torch()install_torchao_windows_rocm_stub()# Same child: the DiT trainer's int8 base-weight quantisation goes through torchao.install_torchao_int_mm_patch()diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 852fe698397..c9d9590697e 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -112,13 +112,15 @@ except ValueError as exc:# Windows ROCm ships no distributed backend, so torchao and the CUDA-only xformers both die on import,# taking diffusers/transformers with them. A stub only seeds a name nothing has imported yet, so both must-# precede the first import below.+# precede the first import below. An xformers built for a newer torch fails the same import anywhere.from core._torchao_stub import (+ hide_xformers_built_for_another_torch,install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,)install_xformers_windows_rocm_stub()+hide_xformers_built_for_another_torch()install_torchao_windows_rocm_stub()# Anaconda/conda-forge Python: seed platform._sys_version_cache before imports that trigger attrs ->diff --git a/studio/backend/tests/test_diffusers_prewarm.py b/studio/backend/tests/test_diffusers_prewarm.pyindex 31dc70e5651..d7789fa9be9 100644--- a/studio/backend/tests/test_diffusers_prewarm.py+++ b/studio/backend/tests/test_diffusers_prewarm.py@@ -252,6 +252,7 @@ def test_the_windows_rocm_stubs_are_installed_before_the_import(warm, monkeypatcorder = []for mod, name in ((_torchao_stub, "install_xformers_windows_rocm_stub"),+ (_torchao_stub, "hide_xformers_built_for_another_torch"),(_torchao_stub, "install_torchao_windows_rocm_stub"),(diffusion_torchao_patches, "install_torchao_int_mm_patch"),):@@ -273,12 +274,13 @@ def test_the_windows_rocm_stubs_are_installed_before_the_import(warm, monkeypatcwarm.prewarm_diffusers_if_image_models_exist()monkeypatch.undo()- assert order[:3] == [+ assert order[:4] == ["install_xformers_windows_rocm_stub",+ "hide_xformers_built_for_another_torch","install_torchao_windows_rocm_stub","install_torchao_int_mm_patch",], f"stubs did not run first, in the loader's order: {order}"- assert "import" in order and order.index("import") > 2+ assert "import" in order and order.index("import") > 3def test_a_failed_prewarm_leaves_no_half_imported_diffusers(diff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.pyindex d11964f9621..74b2c796268 100644--- a/studio/backend/tests/test_diffusion_attention.py+++ b/studio/backend/tests/test_diffusion_attention.py@@ -8,6 +8,7 @@ transformer that records / raises on ``set_attention_backend``.from __future__ import annotations+import sysimport typesimport pytest@@ -370,6 +371,42 @@ def test_xformers_installs_the_cuda_matched_wheel_not_the_package_name(monkeypatassert "xformers" not in [arg for arg in run.calls[0] if arg != _XFORMERS_WHEEL]+def test_a_hidden_xformers_is_not_reinstalled_in_the_same_process(monkeypatch):+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")+ monkeypatch.setitem(sys.modules, "xformers", None)++ def _no_resolve():+ raise AssertionError("resolved a wheel for a hidden xformers")++ monkeypatch.setattr(att, "_xformers_wheel_target", _no_resolve)+ run = _Recorder()+ _stub_subprocess(monkeypatch, run)+ logger = _CapturingLogger()++ reason = att._ensure_attention_backend_installed("xformers", logger)++ assert reason and "requires a different torch" in reason+ assert run.calls == []+ assert any("restart Studio" in line for line in logger.lines)+++def test_the_hidden_xformers_refusal_records_no_attempt(monkeypatch):+ """Policy, not a failed attempt: once the entry is gone the same process may still install."""+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")+ monkeypatch.setitem(sys.modules, "xformers", None)+ att._ensure_attention_backend_installed("xformers")+ monkeypatch.delitem(sys.modules, "xformers")++ import importlib.util++ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)+ _stub_xformers_wheel(monkeypatch)+ run = _Recorder()+ _stub_subprocess(monkeypatch, run)+ att._ensure_attention_backend_installed("xformers")+ assert len(run.calls) == 1++_CREDENTIALED_WHEEL = ("https://svc:[email protected]/whl/cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl")diff --git a/studio/backend/tests/test_xformers_stub_diffusion_parity.py b/studio/backend/tests/test_xformers_stub_diffusion_parity.pyindex c8ec9d9b30d..ef828fdcb33 100644--- a/studio/backend/tests/test_xformers_stub_diffusion_parity.py+++ b/studio/backend/tests/test_xformers_stub_diffusion_parity.py@@ -6,7 +6,8 @@The Windows xformers pin is CUDA-only, so against a ROCm torch (no distributed backend) ``importxformers.ops`` dies inside torch.distributed, and diffusers imports xformers on sight, so such ahost cannot load any image or video model and the error names neither xformers nor the cause.-diffusers reaches torchao the same way, through its quantizers.+diffusers reaches torchao the same way, through its quantizers. An xformers built for a newer+torch than the venv has fails the same import on any platform (#11545), so the same places hide it.Every ``import diffusers`` there is lazy, so a module-scope install is what puts the stubs infirst; asserting module scope stops a later edit tucking one inside a skippable function. Those@@ -27,6 +28,7 @@ import pytestfrom core import _torchao_stubfrom core._torchao_stub import (+ hide_xformers_built_for_another_torch,install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,)@@ -35,7 +37,11 @@ _BACKEND = Path(__file__).resolve().parent.parent # studio/backend_CORE = _BACKEND / "core"# Renaming either installer breaks the import above, loudly, rather than these assertions._INSTALLS = frozenset(- {install_xformers_windows_rocm_stub.__name__, install_torchao_windows_rocm_stub.__name__}+ {+ install_xformers_windows_rocm_stub.__name__,+ hide_xformers_built_for_another_torch.__name__,+ install_torchao_windows_rocm_stub.__name__,+ })# Where diffusers gets imported: the loader, and the trainers' shared module (a spawned child, so the loader's install does not carry over).@@ -84,7 +90,7 @@ def test_diffusion_modules_install_both_stubs_at_module_scope(path):tree = ast.parse(path.read_text(encoding = "utf-8"))assert _module_level_installs(tree) == _INSTALLS, (- f"{path.relative_to(_BACKEND)} must call both stub installers at module scope, before the "+ f"{path.relative_to(_BACKEND)} must call every import guard at module scope, before the ""lazy `import diffusers` calls below them.")@@ -124,7 +130,7 @@ def test_the_entry_point_installs_both_stubs_before_its_first_heavy_import():"reaches torchao or xformers is a no-op.")- assert installed == _INSTALLS, "run.py must call both stub installers at module scope"+ assert installed == _INSTALLS, "run.py must call every import guard at module scope"def _is_stub_key(name: str) -> bool:@@ -179,6 +185,90 @@ def test_no_stub_off_windows_rocm(monkeypatch):assert "xformers" not in sys.modules+_BROKEN_XFORMERS_PROBE = """+import importlib.util, json, sys+sys.path[:0] = [sys.argv[1], sys.argv[2]]+from core._torchao_stub import hide_xformers_built_for_another_torch+hide_xformers_built_for_another_torch()+out = {"visible": importlib.util.find_spec("xformers") is not None}+try:+ import xformers.ops+ out["import"] = "ok"+except Exception as exc:+ out["import"] = type(exc).__name__+if importlib.util.find_spec("diffusers") is not None:+ from diffusers.utils import is_xformers_available+ out["diffusers_sees_xformers"] = is_xformers_available()+print(json.dumps(out))+"""+++def _fake_xformers(root: Path, torch_requirement: str) -> Path:+ """An xformers whose ops import fails as 0.0.35's does on torch 2.6, declaring ``torch_requirement``."""+ pkg = root / "xformers"+ (pkg / "ops").mkdir(parents = True)+ (pkg / "__init__.py").write_text("")+ (pkg / "ops" / "__init__.py").write_text(+ "raise ImportError(\"cannot import name 'GroupName' from 'torch.distributed.distributed_c10d'\")\n"+ )+ dist = root / "xformers-0.0.35.dist-info"+ dist.mkdir()+ (dist / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: xformers\nVersion: 0.0.35\nRequires-Dist: {torch_requirement}\n"+ )+ return root+++def _probe_broken_xformers(tmp_path, torch_requirement):+ import json+ import subprocess+ from importlib.metadata import PackageNotFoundError, version++ try:+ version("torch")+ except PackageNotFoundError:+ pytest.skip("the check compares against the installed torch's metadata")+ site = _fake_xformers(tmp_path, torch_requirement)+ result = subprocess.run(+ [sys.executable, "-c", _BROKEN_XFORMERS_PROBE, str(site), str(_BACKEND)],+ capture_output = True,+ text = True,+ timeout = 300,+ )+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout.strip().splitlines()[-1]), result.stderr+++def test_an_xformers_requiring_a_newer_torch_looks_uninstalled(tmp_path):+ seen, stderr = _probe_broken_xformers(tmp_path, "torch>=999")++ assert seen["visible"] is False+ assert seen["import"] == "ModuleNotFoundError"+ assert seen.get("diffusers_sees_xformers", False) is False+ assert "requires torch>=999" in stderr+++def test_an_xformers_whose_torch_requirement_holds_is_left_visible(tmp_path):+ seen, stderr = _probe_broken_xformers(tmp_path, "torch>=1")++ assert seen["visible"] is True+ assert seen["import"] == "ImportError"+ assert "requires torch" not in stderr+++def test_an_already_imported_xformers_is_not_replaced(monkeypatch):+ real = types.ModuleType("xformers")+ monkeypatch.setitem(sys.modules, "xformers", real)+ monkeypatch.setattr(+ "utils.wheel_utils.xformers_torch_requirement_unmet",+ lambda: ("0.0.35", ">=2.10", "2.6.0+cu124"),+ )++ hide_xformers_built_for_another_torch()++ assert sys.modules["xformers"] is real++def test_the_finder_is_registered_once(on_windows_rocm):install_xformers_windows_rocm_stub()install_torchao_windows_rocm_stub()diff --git a/studio/backend/tests/test_xformers_torch_requirement.py b/studio/backend/tests/test_xformers_torch_requirement.pynew file mode 100644index 00000000000..b733ef2b4ee--- /dev/null+++ b/studio/backend/tests/test_xformers_torch_requirement.py@@ -0,0 +1,63 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Check xFormers torch requirements, version tags, and unreadable metadata (#11545)."""++from __future__ import annotations++from importlib.metadata import PackageNotFoundError++import pytest++from utils.wheel_utils import xformers_torch_requirement_unmet+++def _installed(monkeypatch, *, xformers, torch, requires):+ versions = {"xformers": xformers, "torch": torch}++ def _version(name):+ if versions.get(name) is None:+ raise PackageNotFoundError(name)+ return versions[name]++ monkeypatch.setattr("importlib.metadata.version", _version)+ monkeypatch.setattr("importlib.metadata.requires", lambda name: requires)+++ "xformers, torch, requires, expected",+ [+ ("0.0.35", "2.6.0+cu124", ["torch>=2.10"], ("0.0.35", ">=2.10", "2.6.0+cu124")),+ # 0.0.35 is built against 2.10 on the stable ABI, so a later torch keeps it.+ ("0.0.35", "2.11.0+cu130", ["torch>=2.10"], None),+ ("0.0.29.post3", "2.6.0+cu124", ["torch==2.6.0", "numpy"], None),+ (+ "0.0.29.post3",+ "2.7.1+cu126",+ ["torch==2.6.0"],+ ("0.0.29.post3", "==2.6.0", "2.7.1+cu126"),+ ),+ # AMD's Windows torch is a prerelease; it still satisfies a floor below it.+ ("0.0.32.post2", "2.8.0a0+gitfc14c65", ["torch>=2.7"], None),+ ("0.0.35", "2.6.0+cu124", ["torch>=2.10; extra == 'dev'"], None),+ ],+)+def test_the_declared_torch_requirement_decides(monkeypatch, xformers, torch, requires, expected):+ _installed(monkeypatch, xformers = xformers, torch = torch, requires = requires)+ assert xformers_torch_requirement_unmet() == expected+++ "xformers, torch, requires",+ [+ (None, "2.6.0+cu124", ["torch>=2.10"]),+ ("0.0.35", None, ["torch>=2.10"]),+ ("0.0.35", "2.6.0+cu124", None),+ ("0.0.35", "not a version", ["torch>=2.10"]),+ ("0.0.35", "2.6.0+cu124", ["torch >= >= 2.10"]),+ ],+ ids = ["no-xformers", "no-torch", "no-requirements", "bad-torch-version", "bad-requirement"],+)+def test_anything_unreadable_is_not_a_verdict(monkeypatch, xformers, torch, requires):+ _installed(monkeypatch, xformers = xformers, torch = torch, requires = requires)+ assert xformers_torch_requirement_unmet() is Nonediff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pyindex faa92ffebe5..b7bd5131268 100644--- a/studio/backend/utils/torch_warmup.py+++ b/studio/backend/utils/torch_warmup.py@@ -529,6 +529,7 @@ def prewarm_diffusers_if_image_models_exist() -> bool:# On Windows ROCm diffusers reaches xformers and torchao, both landing on an# absent distributed backend, so any first importer owes these stubs.from core._torchao_stub import ( # noqa: PLC0415+ hide_xformers_built_for_another_torch,install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,)@@ -537,6 +538,7 @@ def prewarm_diffusers_if_image_models_exist() -> bool:)install_xformers_windows_rocm_stub()+ hide_xformers_built_for_another_torch()install_torchao_windows_rocm_stub()install_torchao_int_mm_patch()except Exception as exc: # noqa: BLE001 -- importing unprotected is the hazard; skipdiff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.pyindex 1e296117656..60ac6b679e9 100644--- a/studio/backend/utils/wheel_utils.py+++ b/studio/backend/utils/wheel_utils.py@@ -179,7 +179,7 @@ def direct_wheel_url(return f"{release_base_url}/{release_tag}/{filename}"-# xformers/_C is linked against ONE exact (torch, CUDA) pair, and a mismatch is only a log warning, so the import "succeeds" with memory-efficient attention silently gone. PyPI publishes one win_amd64 flavour whose CUDA family churns across releases, which is why this resolves an exact download.pytorch.org URL instead of pinning a version. Keyed on the `torch` field of cpp_lib.json, not `cuda`, which is the NVCC toolkit version and does not separate flavours. Rows are exact, never interpolated: the extension ABI does not survive a torch minor bump, and an unlisted pair means "install nothing", the safe answer. cu118/cu121/cu124 are absent because they stop before the cp39-abi3 switch at 0.0.31, so one filename template cannot name them. The PyPI win wheel has been cu124 (0.0.29.post2), cu126 (0.0.30), cu128 (0.0.32), cu130 (0.0.33) and cu128 again (0.0.33.post1 onward); download.pytorch.org's cu126 0.0.34 also reports 1208, so only the `torch` field ("2.10.0+cu128") separates flavours. Every row was HEAD-verified live, e.g. cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl reports {"torch": "2.10.0+cu130"}. Keying on the CUDA MINOR is stricter than the ABI needs (cu126 and cu128 both link libcudart.so.12; only a major bump changes it), but it names a real directory, so torch 2.10.0+cu129 on Linux resolves to nothing. torch 2.11+ maps to 0.0.35, compiled against 2.10.0 and compatible with any later version since xFormers moved to the stable API/ABI in 0.0.34. Keep in step with $script:XformersWheelVersions in install.ps1 and the matrix in tests/python/test_windows_xformers_wheel_match.py.+# xformers/_C is linked against ONE exact (torch, CUDA) pair, and a mismatch its declared torch requirement allows is only a log warning, so the import "succeeds" with memory-efficient attention silently gone. PyPI publishes one win_amd64 flavour whose CUDA family churns across releases, which is why this resolves an exact download.pytorch.org URL instead of pinning a version. Keyed on the `torch` field of cpp_lib.json, not `cuda`, which is the NVCC toolkit version and does not separate flavours. Rows are exact, never interpolated: the extension ABI does not survive a torch minor bump, and an unlisted pair means "install nothing", the safe answer. cu118/cu121/cu124 are absent because they stop before the cp39-abi3 switch at 0.0.31, so one filename template cannot name them. The PyPI win wheel has been cu124 (0.0.29.post2), cu126 (0.0.30), cu128 (0.0.32), cu130 (0.0.33) and cu128 again (0.0.33.post1 onward); download.pytorch.org's cu126 0.0.34 also reports 1208, so only the `torch` field ("2.10.0+cu128") separates flavours. Every row was HEAD-verified live, e.g. cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl reports {"torch": "2.10.0+cu130"}. Keying on the CUDA MINOR is stricter than the ABI needs (cu126 and cu128 both link libcudart.so.12; only a major bump changes it), but it names a real directory, so torch 2.10.0+cu129 on Linux resolves to nothing. torch 2.11+ maps to 0.0.35, compiled against 2.10.0 and compatible with any later version since xFormers moved to the stable API/ABI in 0.0.34. Keep in step with $script:XformersWheelVersions in install.ps1 and the matrix in tests/python/test_windows_xformers_wheel_match.py.# ── xFormers ──────────────────────────────────────────────────────────────────PYTORCH_WHEEL_INDEX_BASE_URL = "https://download.pytorch.org/whl"@@ -291,6 +291,35 @@ def xformers_wheel_url(env: dict[str, str] | None) -> str | None:)+def xformers_torch_requirement_unmet() -> tuple[str, str, str] | None:+ """(xformers version, unmet torch specifier, torch version) from metadata, or None if unmet cannot be shown."""+ try:+ from importlib.metadata import requires, version++ from packaging.requirements import Requirement+ from packaging.version import Version++ xformers_version = version("xformers")+ torch_version = version("torch")+ installed = Version(torch_version)+ declared = requires("xformers") or []+ except Exception: # noqa: BLE001 -- either package absent, or no packaging+ return None+ for line in declared:+ try:+ requirement = Requirement(line)+ if requirement.name.lower() != "torch":+ continue+ if requirement.marker is not None and not requirement.marker.evaluate({"extra": ""}):+ continue+ except Exception: # noqa: BLE001 -- a line packaging cannot parse is not a verdict+ continue+ # Local tags are ignored as pip ignores them, so "torch==2.6.0" accepts 2.6.0+cu124.+ if not requirement.specifier.contains(installed, prereleases = True):+ return xformers_version, str(requirement.specifier), torch_version+ return None++def join_wheel_url(base: str, path: str) -> str:"""``base`` + ``path``, with any ?query / #fragment kept at the end. UNSLOTH_PYTORCH_MIRROR is allowed to authenticate by query string (``https://mirror/whl?token=abc``), and appending after the query put the wheel path INSIDE the token value, leaving the request path at /whl and the token unusable. The tokenized private mirror this setting exists for was the one shape that could not resolve a wheel."""cut = min([i for i in (base.find("?"), base.find("#")) if i >= 0], default = -1)diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex f29d8e0c27f..4fd089124b2 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -57,6 +57,7 @@ from backend.utils.wheel_utils import (install_wheel,probe_torch_wheel_env,url_exists,+ xformers_torch_requirement_unmet,)from backend.utils.uv_path_safety import uv_safe_path as _uv_safe_path@@ -7208,6 +7209,25 @@ def _evict_xformers_built_for_another_torch() -> bool:return True+def _evict_xformers_requiring_another_torch() -> bool:+ """Remove an xFormers whose torch requirement is unmet, even if torch is unchanged (--overrides, #11545)."""+ mismatch = xformers_torch_requirement_unmet()+ if mismatch is None:+ return False+ xformers_version, requirement, torch_version = mismatch+ if not _uninstall_distribution("xformers"):+ _safe_print(+ f" [WARN] xformers {xformers_version} requires torch{requirement}, not "+ f"{torch_version}, and could not be removed; diffusers cannot import it."+ )+ return False+ _note(+ f"xformers {xformers_version} requires torch{requirement}, not {torch_version} "+ "-- removed; attention uses torch SDPA"+ )+ return True++WINDOWS_ARM64_PUBLIC_INDEX_WHEELS: "dict[str, dict[str, str]]" = {"llvmlite": {"cp314": "0.49.0"},"numba": {"cp314": "0.67.0"},@@ -11802,6 +11822,7 @@ def install_python_stack() -> int:f"{_torch_after_repair} during the repair -- re-selecting torchao")_install_torchao_for_torch(_torch_after_repair)+ _evict_xformers_requiring_another_torch()# 13w. Windows torch flavor invariant, separate from step 13's Linux-shaped repair set# but in the same position: last, after the with-deps steps re-resolved torch.diff --git a/tests/studio/install/test_cuda_repair.py b/tests/studio/install/test_cuda_repair.pyindex 3d39b03ac79..532e09ddee2 100644--- a/tests/studio/install/test_cuda_repair.py+++ b/tests/studio/install/test_cuda_repair.py@@ -1996,6 +1996,54 @@ class TestTheResidentXformersBuildIsReadFromDisk:assert stack_mod._resident_xformers_build_torch() is None+class TestTheLinuxRepairRemovesAnXformersItsTorchCannotImport:+ """Remove incompatible xFormers even when the final repair leaves torch unchanged (#11545)."""++ def _evict(+ self,+ mismatch,+ *,+ uninstall_ok = True,+ ):+ with (+ patch.object(stack_mod, "xformers_torch_requirement_unmet", return_value = mismatch),+ patch.object(+ stack_mod, "_uninstall_distribution", return_value = uninstall_ok+ ) as uninstall,+ ):+ return stack_mod._evict_xformers_requiring_another_torch(), uninstall++ def test_an_xformers_requiring_a_newer_torch_is_removed(self, capsys):+ removed, uninstall = self._evict(("0.0.35", ">=2.10", "2.6.0+cu124"))+ assert removed is True+ uninstall.assert_called_once_with("xformers")+ out = capsys.readouterr().out+ assert "xformers 0.0.35 requires torch>=2.10, not 2.6.0+cu124" in out++ def test_an_xformers_whose_requirement_holds_is_kept(self):+ removed, uninstall = self._evict(None)+ assert removed is False+ uninstall.assert_not_called()++ def test_a_blocked_removal_is_reported(self, capsys):+ removed, _ = self._evict(("0.0.35", ">=2.10", "2.6.0+cu124"), uninstall_ok = False)+ assert removed is False+ assert "could not be removed" in capsys.readouterr().out++ def test_the_final_repair_checks_even_when_torch_did_not_move(self):+ source = inspect.getsource(stack_mod.install_python_stack)+ step = source.split('_progress(_torch_step_label("final"))', 1)[1]+ step = step.split("# 13w.", 1)[0]+ guard = "if _torch_after_repair and _torch_after_repair != _torch_before_repair:"+ assert guard in step+ after = step.split(guard, 1)[1]+ call = "\n _evict_xformers_requiring_another_torch()\n"+ assert (+ call in after+ ), "the check must sit at the step's indent, outside the torch-moved guard"+ assert after.index("_install_torchao_for_torch(_torch_after_repair)") < after.index(call)++class TestTheResyncNoticesItsOwnFailures:"""Both halves report failure by return value, not by raising.diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 1a77d7f1854..170b015b3c5 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -291,11 +291,13 @@ class TestStepThirteenWiring:# str() is the label coercion around the probe, not a step.step13 = [c for c in _calls_in(guards[1]) if c != "str"]# Step 13 also re-selects torchao when a repair moved the torch label, which both the- # spec and the leaf are read from. Nothing else may join the set.+ # spec and the leaf are read from, then removes an xFormers the final torch cannot+ # import (#11545). Nothing else may join the set.assert step13 == (["_progress", "_torch_step_label", "_probe_installed_torch_version"]+ repairs+ ["_probe_installed_torch_version", "_note", "_install_torchao_for_torch"]+ + ["_evict_xformers_requiring_another_torch"]), step13assert "_install_torchao_for_torch" not in _calls_in(guards[0])