Repository navigation
Studio on Windows: recommend Repair when an existing home is older than the managed torch / xFormers #19870
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Studio on Windows: recommend Repair when an existing home is older than the managed torch / xFormers #19870
Changes from 4 commits
c49e733
7ceae54
8e2ada6
fb89fd7
df67a70
1aceba7
03c5e73
5a046a6
c55eba0
24cbe58
339128d
84ee157
5e4e149
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| # SPDX-License-Identifier: AGPL-3.0-only | ||
| # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 | ||
|
|
||
| """An existing Windows home on an RTX 50-series card gets a Repair recommendation when its torch or | ||
| xFormers is older than the managed pair.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from utils.hardware import windows_repair as wr | ||
|
|
||
| RTX50, RTX40 = (12, 0), (8, 9) | ||
|
|
||
|
|
||
| def _rec( | ||
| torch = "2.10.0+cu128", | ||
| xformers = None, | ||
| caps = (RTX50,), | ||
| platform = "win32", | ||
| route_host = True, | ||
| driver = (13, 0), | ||
| ): | ||
| versions = {"torch": torch, "xformers": xformers} | ||
| return wr.windows_repair_recommendation( | ||
| platform = platform, | ||
| dist_version = versions.get, | ||
| capabilities = lambda: dict(enumerate(caps)), | ||
| managed_route_host = lambda: route_host, | ||
| driver_cuda_version = lambda: driver, | ||
| ) | ||
|
|
||
|
|
||
| def test_a_driver_too_old_for_the_managed_route_asks_for_a_driver_update_first(): | ||
| # Repair alone would keep the cu128 torch, so the recommendation names the driver instead. | ||
| assert _rec(driver = (12, 8))["reason"] == "driver_older_than_managed" | ||
| assert _rec(driver = None)["reason"] == "torch_older_than_managed" # unknown driver: Repair | ||
|
|
||
|
|
||
| def test_a_host_off_the_managed_route_gets_no_recommendation(): | ||
| # Windows on ARM, or a venv Python other than 3.13: Repair would not move torch. | ||
| assert _rec(route_host = False) is None | ||
|
|
||
|
|
||
| def test_the_driver_header_is_parsed_as_install_ps1_reads_it(monkeypatch): | ||
| from types import SimpleNamespace | ||
|
|
||
| from utils.hardware import gpu_query | ||
|
|
||
| header = "| NVIDIA-SMI 576.88 Driver Version: 576.88 CUDA Version: 12.9 |" | ||
| monkeypatch.setattr(gpu_query, "run_nvidia_smi", lambda *a, **k: SimpleNamespace(stdout = header)) | ||
| wr._driver_cuda_version.cache_clear() | ||
| try: | ||
| assert wr._driver_cuda_version() == (12, 9) | ||
| finally: | ||
| wr._driver_cuda_version.cache_clear() | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "env, minor", | ||
| [ | ||
| ({}, "3.13"), | ||
| ({"UNSLOTH_PYTHON": "3.12"}, "3.12"), | ||
| ({"UNSLOTH_PYTHON": "3.13.9"}, "3.13"), | ||
| ({"UNSLOTH_PYTHON": ""}, "3.13"), | ||
| ], | ||
| ) | ||
| def test_repair_builds_its_venv_with_the_python_install_ps1_selects(env, minor): | ||
| # Repair (UNSLOTH_TORCH_UPGRADE=1) does not keep the running venv's minor: a 3.12 home moves to 3.13. | ||
| assert wr._repair_python_minor(env) == minor | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "env, eligible", | ||
| [ | ||
| ({}, True), | ||
| ({"UNSLOTH_TORCH_INDEX_FAMILY": "cu128"}, False), | ||
| ({"UNSLOTH_TORCH_INDEX_FAMILY": "cu130"}, True), | ||
| ({"UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/cu128/"}, False), | ||
| ({"UNSLOTH_TORCH_INDEX_URL": "https://mirror.example/whl/cu130?x=1"}, True), | ||
| ({"UNSLOTH_PYTHON": "3.12"}, False), | ||
| ], | ||
| ) | ||
| def test_an_index_override_off_cu130_closes_the_route(monkeypatch, env, eligible): | ||
| # install.ps1 honors these overrides before the driver, and the 2.13 route needs the cu130 leaf. | ||
| monkeypatch.setattr(wr._platform, "machine", lambda: "AMD64") | ||
| assert wr._managed_route_host(env) is eligible | ||
|
|
||
|
|
||
| def test_the_route_gate_matches_install_ps1(): | ||
| install = Path(__file__).resolve().parents[3] / "install.ps1" | ||
| body = re.search( | ||
| r"function Test-Cu130Torch213Platform \{.*?\n \}", | ||
| install.read_text(encoding = "utf-8"), | ||
| re.S, | ||
| ).group(0) | ||
| assert '-ne "cu130"' in body and '-ne "x86_64"' in body and '"3.13 win-amd64"' in body | ||
|
|
||
|
|
||
| def test_an_old_torch_on_rtx50_recommends_repair(): | ||
| rec = _rec() | ||
| assert rec["reason"] == "torch_older_than_managed" | ||
| assert rec["torch"] == "2.10.0+cu128" | ||
| assert (rec["managed_torch"], rec["managed_xformers"]) == ("2.13", "0.0.35") | ||
|
|
||
|
|
||
| def test_an_old_xformers_on_the_managed_torch_recommends_repair(): | ||
| assert _rec(torch = "2.13.0+cu130", xformers = "0.0.33")["reason"] == "xformers_older_than_managed" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "kwargs", | ||
| [ | ||
| dict(torch = "2.13.0+cu130", xformers = "0.0.35"), # the managed pair | ||
| dict(torch = "2.14.0+cu134"), # newer, no xFormers | ||
| dict(caps = (RTX40,)), # older cards train fine on this torch | ||
| dict(caps = ()), # no readable card | ||
| dict(torch = "2.10.0+cpu"), # a CPU wheel is a different repair | ||
| dict(torch = None), # no torch (Chat only) | ||
| dict(platform = "linux"), | ||
| dict(platform = "darwin"), | ||
| ], | ||
| ) | ||
| def test_nothing_is_recommended_otherwise(kwargs): | ||
| assert _rec(**kwargs) is None | ||
|
|
||
|
|
||
| def test_a_mixed_host_answers_for_its_rtx50_card(): | ||
| assert _rec(caps = (RTX40, RTX50))["reason"] == "torch_older_than_managed" | ||
|
|
||
|
|
||
| def test_the_floor_matches_install_ps1(): | ||
| """The managed torch floor is install.ps1's new-install CUDA spec; bumping one must bump the other.""" | ||
| install = Path(__file__).resolve().parents[3] / "install.ps1" | ||
| spec = re.search( | ||
| r'\$script:Cu130NewInstallTorchSpec = "torch>=(\d+)\.(\d+)', | ||
| install.read_text(encoding = "utf-8"), | ||
| ) | ||
| assert spec, "Cu130NewInstallTorchSpec not found in install.ps1" | ||
| assert (int(spec.group(1)), int(spec.group(2))) == wr.WINDOWS_MANAGED_TORCH_FLOOR | ||
|
|
||
|
|
||
| def test_system_route_ships_the_recommendation(monkeypatch): | ||
| import main | ||
|
|
||
| monkeypatch.setattr( | ||
| wr, "windows_repair_recommendation", lambda: {"reason": "torch_older_than_managed"} | ||
| ) | ||
| assert main._repair_recommendation() == {"reason": "torch_older_than_managed"} | ||
|
|
||
| def boom(): | ||
| raise RuntimeError("probe failed") | ||
|
|
||
| monkeypatch.setattr(wr, "windows_repair_recommendation", boom) | ||
| assert main._repair_recommendation() is None | ||
| src = Path(main.__file__).read_text(encoding = "utf-8") | ||
| assert '"repair_recommendation": _repair_recommendation(),' in src | ||
|
|
||
|
|
||
| def test_the_module_stays_torch_free(): | ||
| src = Path(wr.__file__).read_text(encoding = "utf-8") | ||
| assert "import torch" not in src |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| # SPDX-License-Identifier: AGPL-3.0-only | ||
| # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 | ||
|
|
||
| """Windows: whether an existing install should be repaired onto the managed PyTorch. | ||
|
|
||
| An existing home keeps the torch it was installed with; only a repair (UNSLOTH_TORCH_UPGRADE=1) moves it to | ||
| the managed build. On RTX 50-series (sm_120) cards xFormers trains only with torch 2.13 and xFormers 0.0.35, | ||
| so an older home there runs attention on SDPA instead, or fails in the backward of an old xFormers build. | ||
| Torch-free: package metadata and the cached nvidia-smi capability query, so the polled /api/system may call it.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import functools | ||
| import os | ||
| import platform as _platform | ||
| import re | ||
| import sys | ||
| from typing import Callable, Optional | ||
|
|
||
| # Lower bound of install.ps1's managed CUDA torch for new installs ($script:Cu130NewInstallTorchSpec). | ||
| WINDOWS_MANAGED_TORCH_FLOOR = (2, 13) | ||
| # The first xFormers whose sm_120 build ships the backward kernels, paired with that torch. | ||
| WINDOWS_MANAGED_XFORMERS_FLOOR = (0, 0, 35) | ||
| _SM120 = 12 | ||
| # The managed torch comes from the cu130 index, which install.ps1 picks only for a driver supporting CUDA 13.0. | ||
| _MANAGED_ROUTE_DRIVER_CUDA = (13, 0) | ||
|
|
||
|
|
||
| def _dist_version(name: str) -> Optional[str]: | ||
| try: | ||
| from importlib.metadata import version | ||
| return version(name) | ||
| except Exception: # noqa: BLE001 -- not installed or unreadable | ||
| return None | ||
|
|
||
|
|
||
| def _release(version: Optional[str]) -> Optional[tuple[int, ...]]: | ||
| match = re.match(r"(\d+(?:\.\d+)*)", version or "") | ||
| return tuple(int(p) for p in match.group(1).split(".")) if match else None | ||
|
|
||
|
|
||
| def _capabilities() -> dict: | ||
| try: | ||
| from utils.hardware.nvidia import get_compute_capabilities | ||
| return get_compute_capabilities() | ||
| except Exception: # noqa: BLE001 -- unreadable counts as no card | ||
| return {} | ||
|
|
||
|
|
||
| @functools.lru_cache(maxsize = 1) | ||
| def _driver_cuda_version() -> Optional[tuple[int, int]]: | ||
| """The CUDA version the driver supports, from nvidia-smi's header as install.ps1 reads it; None when | ||
| unreadable. Cached: the driver does not change under a running server.""" | ||
| try: | ||
| from utils.hardware import gpu_query | ||
| from utils.hardware.nvidia import _nvidia_smi_executable | ||
|
|
||
| result = gpu_query.run_nvidia_smi( | ||
| [_nvidia_smi_executable()], | ||
| capture_output = True, | ||
| text = True, | ||
| encoding = "utf-8", | ||
| errors = "replace", | ||
| timeout = 5, | ||
| ) | ||
| match = re.search(r"CUDA Version:\s*(\d+)\.(\d+)", result.stdout or "") | ||
| return (int(match.group(1)), int(match.group(2))) if match else None | ||
| except Exception: # noqa: BLE001 -- unknown driver | ||
| return None | ||
|
|
||
|
|
||
| def _repair_python_minor(environ = os.environ) -> str: | ||
| """The Python minor a Repair builds its venv with: UNSLOTH_PYTHON when set, else install.ps1's 3.13 | ||
| (UNSLOTH_TORCH_UPGRADE=1 does not keep the existing venv's minor).""" | ||
| match = re.match(r"\s*(3\.\d+)", environ.get("UNSLOTH_PYTHON") or "") | ||
| return match.group(1) if match else "3.13" | ||
|
|
||
|
|
||
| def _index_override_leaf(environ = os.environ) -> Optional[str]: | ||
| """The torch index leaf a user override pins ("cu128"), as install.ps1's Get-TorchIndexUrl honors it | ||
| before the driver; None when nothing is overridden.""" | ||
| url = (environ.get("UNSLOTH_TORCH_INDEX_URL") or "").strip() | ||
| if url: | ||
| return re.split(r"[?#]", url, maxsplit = 1)[0].rstrip("/").split("/")[-1].lower() | ||
| family = (environ.get("UNSLOTH_TORCH_INDEX_FAMILY") or "").strip().strip("/") | ||
| return family.split("/")[-1].lower() if family else None | ||
|
|
||
|
|
||
| def _managed_route_host(environ = os.environ) -> bool: | ||
| """install.ps1's 2.13 route (Test-Cu130Torch213Platform): x64 Windows, the venv Repair builds is 3.13, and | ||
| no index override pins a leaf other than cu130.""" | ||
| leaf = _index_override_leaf(environ) | ||
| return ( | ||
| _platform.machine().lower() in ("amd64", "x86_64") | ||
| and _repair_python_minor(environ) == "3.13" | ||
| and leaf in (None, "cu130") | ||
|
Comment on lines
+172
to
+174
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
On an x64 Windows RTX 50-series host with an older CUDA torch and a CUDA 13-capable driver, setting Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 5a046a6: the route gate now applies |
||
| ) | ||
|
|
||
|
|
||
| def windows_repair_recommendation( | ||
| platform: str = sys.platform, | ||
| dist_version: Callable[[str], Optional[str]] = _dist_version, | ||
| capabilities: Callable[[], dict] = _capabilities, | ||
| managed_route_host: Callable[[], bool] = _managed_route_host, | ||
| driver_cuda_version: Callable[[], Optional[tuple[int, int]]] = _driver_cuda_version, | ||
| ) -> Optional[dict]: | ||
| """``{"reason", "torch", "xformers", "managed_torch", "managed_xformers"}`` when this Windows CUDA install | ||
| has an sm_120+ card and a torch (or an installed xFormers) older than the managed pair, and Repair can | ||
| reach that pair; else None. A driver too old for the cu130 route gets ``driver_older_than_managed`` | ||
| instead, since Repair alone would keep the old torch.""" | ||
| if platform != "win32": | ||
| return None | ||
| torch_version = dist_version("torch") | ||
| # Only CUDA builds: a CPU wheel is a different repair (the GPU verdict already says so). | ||
| if not torch_version or "+cu" not in torch_version: | ||
| return None | ||
| if not any(int(cap[0]) >= _SM120 for cap in capabilities().values()): | ||
| return None | ||
| torch_release = _release(torch_version) | ||
| xformers_version = dist_version("xformers") | ||
| xformers_release = _release(xformers_version) | ||
| if torch_release is not None and torch_release[:2] < WINDOWS_MANAGED_TORCH_FLOOR: | ||
| reason = "torch_older_than_managed" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
On an RTX 50-series Windows host whose driver reports CUDA 12.8, this recommends Repair even though Repair cannot install the advertised PyTorch 2.13. In Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 7ceae54: the recommendation now follows |
||
| elif xformers_release is not None and xformers_release < WINDOWS_MANAGED_XFORMERS_FLOOR: | ||
| reason = "xformers_older_than_managed" | ||
| else: | ||
| return None | ||
| # Only x64 with the Python 3.13 venv takes the managed torch; elsewhere Repair would not change it. | ||
| if not managed_route_host(): | ||
| return None | ||
| driver = driver_cuda_version() | ||
| if driver is not None and driver < _MANAGED_ROUTE_DRIVER_CUDA: | ||
| reason = "driver_older_than_managed" | ||
| return { | ||
| "reason": reason, | ||
| "torch": torch_version, | ||
| "xformers": xformers_version, | ||
| "managed_torch": ".".join(map(str, WINDOWS_MANAGED_TORCH_FLOOR)), | ||
| "managed_xformers": ".".join(map(str, WINDOWS_MANAGED_XFORMERS_FLOOR)), | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On a Windows desktop installation with an outdated torch/xFormers pair and an RTX 50-series GPU, the first
/api/systemrequest reaches this probe. Unlikeget_compute_capabilities()inutils/hardware/nvidia.py, this invocation omitswindows_hidden_subprocess_kwargs(), andgpu_query.run_nvidia_smi()forwards the arguments directly tosubprocess.runwithout adding window-suppression flags. Because the desktop backend runs without a console, this creates a visible console window during an otherwise background status request. Pass the existing hidden-subprocess kwargs here as the other NVIDIA probes do.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in df67a70: the probe now passes
windows_hidden_subprocess_kwargs()andchild_env_without_native_path_secret(), asnvidia.py's queries do; the parsing test asserts the hidden-window flags reach the call.