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
# SPDX-License-Identifier: AGPL-3.0-only
"""Generic triton must not shadow torch's XPU Triton; the swap runs fetch, uninstall, then install."""
import os
import subprocess
import sys
import types
from pathlib import Path
import pytest
REPO = Path(__file__).resolve().parents[2]
STACK = REPO / "studio/install_python_stack.py"
def _load_real_index_env_scrub():
"""Pulls in the module's real _install_env_for_cmd, so the scrub is executed, not re-implemented."""
import ast as _ast
import atexit as _atexit
import functools as _functools
import locale as _locale
import os as _os
import shutil as _shutil
import subprocess as _subprocess
import sys as _sys
import tempfile as _tempfile
src = STACK.read_text(encoding = "utf-8")
ns: dict = {
"os": _os,
"ast": _ast,
"atexit": _atexit,
"functools": _functools,
"shutil": _shutil,
"subprocess": _subprocess,
"locale": _locale,
"sys": _sys,
"tempfile": _tempfile,
"_windows_hidden_subprocess_kwargs": dict,
}
for anchor, end, keep in (
("_UV_INDEX_ENV_VARS = (", "\n)\n", 2),
# Resolved at call time, so an omission is a NameError later.
("_PM_HASH_ENV_VARS = (", "\n)\n", 2),
("_PM_FORCE_SOURCE_ENV_VARS = (", "\n)\n", 2),
# One line, so it ends at the first newline; "\n)\n" would swallow the file.
("_PINNED_PIP_CONFIG_KEEP_KEYS = (", "\n)\n", 2),
("_PINNED_PIP_CONFIG_GLOBAL_SECTION = ", "\n", 1),
("_PINNED_PIP_CONFIG_DEFAULT_SECTION = ", "\n", 1),
("_PINNED_PIP_CONFIG_SEPARATORS = ", "\n", 1),
("_PINNED_PIP_CONFIG_ACCUMULATING = ", "\n", 1),
("_PINNED_PIP_CONFIG_LISTING: ", "\n", 1),
("_PINNED_PIP_CONFIG_TIMEOUT = ", "\n", 1),
("_PINNED_PIP_CONFIG_ATTEMPTS = ", "\n", 1),
("def _pip_subcommand_of(", "\n\ndef ", 0),
("def _decode_pip_output(", "\n\ndef ", 0),
("def _pinned_pip_config_overrides(", "\n\ndef ", 0),
# Omitting it made the exec'd scrub raise into a broad except and agree with anything.
("def _parse_pinned_pip_config(", "\n\ndef ", 0),
("def _relaxed_pip_policy_env(", "\n\ndef ", 0),
("def _is_pip_subcommand(", "\n\ndef ", 0),
("def _is_pinned_index_cmd(", "\n\ndef ", 0),
("def _install_env_for_cmd(", "\n\ndef ", 0),
):
start = src.index(anchor)
exec(compile(src[start : src.index(end, start) + keep], str(STACK), "exec"), ns)
assert "PIP_NO_INDEX" in ns["_UV_INDEX_ENV_VARS"], "extraction lost the pip vars"
assert "PIP_REQUIRE_HASHES" in ns["_PM_HASH_ENV_VARS"], "extraction lost the hash vars"
parsed = ns["_parse_pinned_pip_config"](b"global.cert='/etc/corp/ca.pem'\n")
assert parsed == {"PIP_CERT": "/etc/corp/ca.pem"}, f"extraction is inert: {parsed}"
return ns["_install_env_for_cmd"]
_real_install_env_for_cmd = _load_real_index_env_scrub()
def _load(
monkeypatch,
tmp_path,
*,
spec,
generic,
has_pip = True,
ensurepip_works = True,
download_ok = True,
drops_wheel = True,
uninstall_ok = True,
install_ok = True,
pinned = True,
torch_label = "2.9.1+xpu",
):
"""Import the module with the world stubbed, and return (module, action log)."""
log: list[str] = []
counted: list[int] = []
mod = types.ModuleType("_stack_under_test")
src = STACK.read_text(encoding = "utf-8")
# Importing the whole module would run the installer.
start = src.index("def _installed_torch_version_label() -> str:")
end = src.index('def _ensure_cpu_torch() -> "bool | None":')
body = src[start:end]
assert "_ensure_xpu_triton" in body, "extraction lost the swap"
assert "_ensure_venv_pip" in body, "extraction lost the pip bootstrap"
assert "_safe_print(" in body, "extraction lost the print helper the WARN stub hooks"
import glob as _glob
import importlib.util as _importlib_util
import os as _os
import re as _re
import shutil as _shutil
import tempfile as _tempfile
# find_spec would resolve this process's torch, so only the location step is stubbed.
_pkg = tmp_path / "torch"
_pkg.mkdir()
(_pkg / "__init__.py").write_text("raise AssertionError('torch must never be imported')\n")
if torch_label is not None:
(_pkg / "version.py").write_text(
f"from typing import Optional\n__version__ = '{torch_label}'\ndebug = False\n"
)
monkeypatch.setattr(
_importlib_util,
"find_spec",
lambda name: (
types.SimpleNamespace(origin = str(_pkg / "__init__.py"))
if name == "torch" and torch_label is not None
else None
),
)
pip_state = {"present": has_pip}
index_urls: list[str] = []
download_envs: list = []
def fake_run(cmd, **kw):
joined = " ".join(str(c) for c in cmd)
if "download" in cmd:
download_envs.append(kw.get("env"))
if "-m pip --version" in joined or ("pip" in cmd and "--version" in cmd):
return subprocess.CompletedProcess(cmd, 0 if pip_state["present"] else 1)
if "ensurepip" in joined:
log.append("ENSUREPIP")
if ensurepip_works:
pip_state["present"] = True
return subprocess.CompletedProcess(cmd, 0)
if "importlib.metadata" in joined:
out = f"SPEC={spec}\nGENERIC={generic}\n".encode()
return subprocess.CompletedProcess(cmd, 0, stdout = out)
if "download" in cmd:
log.append("DOWNLOAD")
index_urls.append(cmd[cmd.index("--index-url") + 1])
if download_ok and drops_wheel:
target = cmd[cmd.index("-d") + 1]
Path(target, "pytorch_triton_xpu-3.5.0-py3-none-any.whl").write_bytes(b"")
return subprocess.CompletedProcess(cmd, 0 if download_ok else 1, stdout = b"")
if "uninstall" in cmd:
log.append("UNINSTALL")
return subprocess.CompletedProcess(cmd, 0 if uninstall_ok else 1)
return subprocess.CompletedProcess(cmd, 0, stdout = b"")
def fake_pip_install_try(label, *args, **kw):
if label.startswith("pip"):
log.append("BOOTSTRAP")
if ensurepip_works:
pip_state["present"] = True
return pip_state["present"]
log.append("INSTALL")
return True
def fake_pip_install(label, *args, **kw):
# The real one exits via run(), which keeps the completion manifest unwritten.
log.append("INSTALL")
if not install_ok:
raise SystemExit(1)
ns = {
"subprocess": types.SimpleNamespace(
run = fake_run,
CompletedProcess = subprocess.CompletedProcess,
TimeoutExpired = subprocess.TimeoutExpired,
DEVNULL = subprocess.DEVNULL,
PIPE = subprocess.PIPE,
STDOUT = subprocess.STDOUT,
),
"sys": sys,
"glob": _glob,
"importlib": types.SimpleNamespace(util = _importlib_util, invalidate_caches = lambda: None),
"os": _os,
"re": _re,
"shutil": _shutil,
"tempfile": _tempfile,
"Path": Path,
"NO_TORCH": False,
"IS_MACOS": False,
"IS_WINDOWS": False,
"_PYTORCH_WHL_BASE": "https://download.pytorch.org/whl",
"_pytorch_whl_leaf_url": lambda leaf: f"https://download.pytorch.org/whl/{leaf}",
"_install_env_for_cmd": _real_install_env_for_cmd,
"_explicit_xpu_torch_index_url": (
(lambda: "https://download.pytorch.org/whl/xpu") if pinned else (lambda: None)
),
"pip_install_try": fake_pip_install_try,
"pip_install": fake_pip_install,
"_count_install_action": lambda: counted.append(1),
"_red": lambda s: s,
# The slice calls _handover_torch_flavor_tag by name; same semantics as the real one.
"_handover_torch_flavor_tag": (
lambda: os.environ.get("UNSLOTH_EXPECTED_TORCH_TAG", "").strip().lower()
),
# The slice calls _safe_print by name, so stubbing print would leave it undefined.
"_safe_print": (
lambda *a, **k: log.append("WARN") if a and "left in place" in str(a[0]) else None
),
}
exec(compile(body, str(STACK), "exec"), ns)
mod.__dict__.update(ns)
mod.__dict__["_test_counted"] = counted
mod.__dict__["_test_index_urls"] = index_urls
mod.__dict__["_test_download_envs"] = download_envs
return mod, log
def _run(monkeypatch, tmp_path, **kw):
mod, log = _load(monkeypatch, tmp_path, **kw)
mod.__dict__["_ensure_xpu_triton"]()
return log
class TestXpuTritonSwap:
def test_orders_fetch_uninstall_install(self, monkeypatch, tmp_path):
log = _run(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]
def test_the_uninstall_counts_as_an_environment_change(self, monkeypatch, tmp_path):
"""It removes a distribution outside pip_install, and the pass's final pip check only
runs when something said the environment moved. Uncounted, dropping generic triton on
an XPU host would leave torch's dependency unmet with nothing left to report it."""
mod, _log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
assert mod.__dict__["_test_counted"], "the uninstall did not count as a change"
def test_handles_the_triton_xpu_rename(self, monkeypatch, tmp_path):
# torch 2.10 renamed the distribution; the spec is read from torch, never hardcoded.
log = _run(monkeypatch, tmp_path, spec = "triton-xpu==3.6.0", generic = "3.7.1")
assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]
def test_bootstraps_pip_when_the_venv_has_none(self, monkeypatch, tmp_path):
log = _run(
monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", has_pip = False
)
assert log[0] == "ENSUREPIP"
assert log[-3:] == ["DOWNLOAD", "UNINSTALL", "INSTALL"]
def test_falls_back_to_installing_pip(self, monkeypatch, tmp_path):
# uv venv has no --seed, so a fresh venv cannot run pip download at all.
log = _run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
has_pip = False,
ensurepip_works = False,
)
assert "BOOTSTRAP" in log
assert "UNINSTALL" not in log
@pytest.mark.parametrize(
"spec, generic",
[
("pytorch-triton-xpu==3.5.0", ""), # nothing shadowing it
("triton==3.7.1", "3.7.1"), # torch is not the +xpu wheel
("", "3.7.1"), # torch declares no triton at all
],
)
def test_leaves_a_healthy_venv_alone(self, monkeypatch, tmp_path, spec, generic):
assert _run(monkeypatch, tmp_path, spec = spec, generic = generic) == []
def test_a_dead_mirror_removes_nothing(self, monkeypatch, tmp_path):
log = _run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
download_ok = False,
)
assert "UNINSTALL" not in log and "INSTALL" not in log
def test_a_successful_exit_with_no_wheel_removes_nothing(self, monkeypatch, tmp_path):
log = _run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
drops_wheel = False,
)
assert "UNINSTALL" not in log and "INSTALL" not in log
class TestFailedSwapIsNotSurvivable:
def test_a_failed_uninstall_changes_nothing(self, monkeypatch, tmp_path):
# A locked venv keeps generic triton; installing over it makes a later upgrade repeat the swap.
log = _run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
uninstall_ok = False,
)
assert log == ["DOWNLOAD", "UNINSTALL"]
assert "INSTALL" not in log
def test_a_failed_install_propagates(self, monkeypatch, tmp_path):
# The uninstall already took the shared files, so warning would commit a broken torch.compile.
with pytest.raises(SystemExit):
_run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
install_ok = False,
)
class TestTheInstalledWheelIsThePin:
"""The installed +xpu wheel is the durable signal; the UNSLOTH_TORCH_INDEX_FAMILY pin is one-shot."""
def test_swaps_with_no_pin_when_torch_is_the_xpu_wheel(self, monkeypatch, tmp_path):
log = _run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
pinned = False,
)
assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]
def test_no_pin_falls_back_to_the_default_xpu_index(self, monkeypatch, tmp_path):
mod, _ = _load(
monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", pinned = False
)
mod.__dict__["_ensure_xpu_triton"]()
assert mod.__dict__["_test_index_urls"] == ["https://download.pytorch.org/whl/xpu"]
@pytest.mark.parametrize("label", ["2.9.1+cu128", "2.9.1+rocm6.4", "2.9.1", "", None])
def test_no_pin_and_no_xpu_wheel_does_nothing(self, monkeypatch, tmp_path, label):
# Generic triton is correct for CUDA/ROCm/CPU venvs; removing it breaks torch.compile.
assert (
_run(
monkeypatch,
tmp_path,
spec = "pytorch-triton-xpu==3.5.0",
generic = "3.7.1",
pinned = False,
torch_label = label,
)
== []
)
def test_the_label_is_read_off_disk_not_imported(self, monkeypatch, tmp_path):
# `import torch` wedges on a stalled Intel driver, so the label must come from version.py.
mod, _ = _load(
monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", pinned = False
)
assert mod.__dict__["_installed_torch_version_label"]() == "2.9.1+xpu"
def test_an_explicit_pin_still_wins(self, monkeypatch, tmp_path):
mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
assert mod.__dict__["_test_index_urls"] == ["https://download.pytorch.org/whl/xpu"]
class TestTheFetchIgnoresTheUsersIndexEnvironment:
"""pip download honours PIP_* like pip install, so the fetch must scrub them or the pin breaks."""
@pytest.mark.parametrize(
"var, value",
[
("PIP_NO_INDEX", "1"),
("PIP_INDEX_URL", "https://mirror.internal/simple"),
("PIP_EXTRA_INDEX_URL", "https://mirror.internal/simple"),
("PIP_FIND_LINKS", "/opt/wheels"),
("UV_INDEX_URL", "https://mirror.internal/simple"),
],
)
def test_the_fetch_drops_index_environment(self, monkeypatch, tmp_path, var, value):
monkeypatch.setenv(var, value)
mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
env = mod.__dict__["_test_download_envs"][0]
assert env is not None, "the fetch inherited the ambient environment"
assert var not in env
def test_the_fetch_neutralises_the_pip_config_file(self, monkeypatch, tmp_path):
# A config no-index outranks the CLI pin, and devnull is the only spelling that reaches
# a SITE or GLOBAL file.
mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
env = mod.__dict__["_test_download_envs"][0]
assert env["PIP_CONFIG_FILE"] == os.devnull
assert env["UV_NO_CONFIG"] == "1"
def test_the_fetch_keeps_the_operators_build_policy(self, monkeypatch, tmp_path):
monkeypatch.setenv("PIP_ONLY_BINARY", ":all:")
monkeypatch.setenv("PIP_REQUIRE_HASHES", "1")
monkeypatch.setenv("UV_EXCLUDE_NEWER", "2024-01-01T00:00:00Z")
mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
env = mod.__dict__["_test_download_envs"][0]
assert env["PIP_ONLY_BINARY"] == ":all:"
assert "PIP_REQUIRE_HASHES" not in env
assert "UV_EXCLUDE_NEWER" not in env
def test_unrelated_environment_survives(self, monkeypatch, tmp_path):
# Scrub the index vars only: HTTPS_PROXY is how a corporate host reaches the index.
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:8080")
mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"]()
env = mod.__dict__["_test_download_envs"][0]
assert env["HTTPS_PROXY"] == "http://proxy.internal:8080"
class TestADeadDriverIsNotAFlavourMismatch:
"""A hung import torch on a supported +xpu wheel is a driver fault: warn, don't force-reinstall it."""
@pytest.mark.parametrize(
"label, supported",
[
("2.6.0+xpu", True),
("2.9.1+xpu", True),
("2.10.0+xpu", True),
("2.5.1+xpu", False), # below the floor unsloth raises at
("2.11.0+xpu", False), # past the tested ceiling
("3.0.0+xpu", False),
("2.9.1+cu128", False),
("2.9.1+rocm6.4", False),
("2.9.1", False),
("", False),
(None, False),
],
)
def test_the_supported_range_matches_the_probe(self, monkeypatch, tmp_path, label, supported):
mod, _ = _load(monkeypatch, tmp_path, spec = "", generic = "", torch_label = label)
assert mod.__dict__["_xpu_wheel_supported_on_disk"]() is supported
def test_the_disk_check_and_the_probe_agree_on_the_bounds(self):
src = STACK.read_text(encoding = "utf-8")
assert src.count("(2, 6) <= _n < (2, 11)") == 1, "the probe's range moved"
assert src.count("(2, 6) <= nums < (2, 11)") == 1, "the disk check's range moved"
def test_a_timeout_on_a_supported_wheel_reinstalls_nothing(self):
# _ensure_xpu_torch sits above the slice: the early return must precede the repair reason.
src = STACK.read_text(encoding = "utf-8")
start = src.index("def _ensure_xpu_torch(")
body = src[start : src.index("def _installed_torch_version_label", start)]
guard = body.index("_xpu_wheel_supported_on_disk()")
armed = body.index('_why = "torch could not be probed"')
assert guard < armed, "the guard runs after the repair is armed"
assert "return" in body[guard : guard + 400], "the guard does not return"
class TestPlatformGuards:
@pytest.mark.parametrize("flag", ["NO_TORCH", "IS_MACOS"])
def test_skipped_where_it_does_not_apply(self, monkeypatch, tmp_path, flag):
monkeypatch.delenv("UNSLOTH_EXPECTED_TORCH_TAG", raising = False)
mod, log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__[flag] = True
mod.__dict__["_ensure_xpu_triton"].__globals__[flag] = True
mod.__dict__["_ensure_xpu_triton"]()
assert log == []
def test_windows_defers_to_setup_ps1_when_setup_ps1_ran(self, monkeypatch, tmp_path):
# setup.ps1 does the same swap after this file exits, signalled by the handover variable.
monkeypatch.setenv("UNSLOTH_EXPECTED_TORCH_TAG", "xpu")
mod, log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"].__globals__["IS_WINDOWS"] = True
mod.__dict__["_ensure_xpu_triton"]()
assert log == []
def test_a_direct_windows_run_does_the_swap_itself(self, monkeypatch, tmp_path):
# Without the handover variable no setup.ps1 postlude will fix triton-windows, so do it here.
monkeypatch.delenv("UNSLOTH_EXPECTED_TORCH_TAG", raising = False)
mod, log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")
mod.__dict__["_ensure_xpu_triton"].__globals__["IS_WINDOWS"] = True
mod.__dict__["_ensure_xpu_triton"]()
assert "INSTALL" in log
def test_the_swap_is_wired_in_at_every_repair_point():
src = STACK.read_text(encoding = "utf-8")
assert src.count(" _ensure_xpu_triton()") == 3
def test_the_swap_runs_after_every_torch_migration():
"""Must run after every torch migration: a CPU pin over an XPU venv otherwise strands XPU triton."""
import ast as _ast
def _migration_call(statement):
expression = statement.value if isinstance(statement, _ast.Expr) else None
if isinstance(statement, _ast.If) and isinstance(statement.test, _ast.Compare):
expression = statement.test.left
if isinstance(expression, _ast.Call) and isinstance(expression.func, _ast.Name):
return expression.func.id
return ""
blocks = []
for node in _ast.walk(_ast.parse(STACK.read_text(encoding = "utf-8"))):
body = getattr(node, "body", None)
if not isinstance(body, list):
continue # Lambda / IfExp carry a single expression here, not a statement list
calls = [
name
for statement in body
if (name := _migration_call(statement)).startswith("_ensure_")
]
if "_ensure_xpu_triton" in calls:
blocks.append(calls)
assert len(blocks) == 3, f"expected 3 repair blocks, found {len(blocks)}: {blocks}"
for calls in blocks:
assert calls[-1] == "_ensure_xpu_triton", calls
# _ensure_expected_torch_flavor's result is branched on, so the walk misses it.
migrating = [c for c in blocks if "_ensure_cuda_torch" in c]
assert len(migrating) == 2, blocks
for calls in migrating:
for migration in (
"_ensure_cuda_torch",
"_ensure_rocm_torch",
"_ensure_xpu_torch",
"_ensure_cpu_torch",
):
assert calls.index(migration) < calls.index("_ensure_xpu_triton"), (migration, calls)
# The final repair pass would otherwise silently undo the first.
src = STACK.read_text(encoding = "utf-8")
windows = src[src.index("# 13w.") : src.index("# 14.")]
assert windows.index("_ensure_expected_torch_flavor") < windows.index(
"_ensure_xpu_triton"
), "the Windows swap must follow that platform's torch migration too"
def test_install_sh_does_not_carry_a_second_copy():
# install.sh runs setup.sh which runs this module, so a copy there could only drift.
assert "replace generic Triton" not in (REPO / "install.sh").read_text(encoding = "utf-8")
class TestCpuRepairSeesAnXpuWheel:
"""Before this, an XPU wheel sets neither cuda nor hip, so it read as CPU and the pin was ignored."""
@staticmethod
def _classify(
ver,
cuda = "",
hip = "",
runtime_xpu = "",
):
src = STACK.read_text(encoding = "utf-8")
start = src.index('def _ensure_cpu_torch() -> "bool | None":')
seg = src[start : src.index("\n\ndef ", start)]
marker = "_is_gpu_build = ("
begin = seg.index(marker) + len(marker)
depth, end = 1, begin
for i in range(begin, len(seg)):
if seg[i] == "(":
depth += 1
elif seg[i] == ")":
depth -= 1
if depth == 0:
end = i
break
expr = "(" + seg[begin:end] + ")"
import re as _re
return (
"gpu"
if eval(
expr,
{
"re": _re,
"_hip": hip,
"_cuda": cuda,
"_ver": ver.lower(),
# torch.version has no word for XPU, so this marker is the only signal.
"_TORCH_RUNTIME_XPU": runtime_xpu,
},
)
else "cpu"
)
def test_xpu_wheel_is_a_gpu_build(self):
assert self._classify("2.9.1+xpu") == "gpu"
def test_an_untagged_xpu_wheel_is_a_gpu_build_through_the_runtime_marker(self):
# A private index can serve XPU torch with no +xpu tag; only the runtime marker knows.
assert self._classify("2.9.1", runtime_xpu = "20250101") == "gpu"
@pytest.mark.parametrize(
"ver,cuda,hip,want",
[
("2.9.1+cu128", "12.8", "", "gpu"),
("2.9.1+rocm6.4", "", "6.4", "gpu"),
("2.9.1+cpu", "", "", "cpu"),
("2.9.1", "", "", "cpu"),
],
)
def test_other_families_are_unchanged(self, ver, cuda, hip, want):
# The XPU arm is additive: a CPU build must still read as CPU, or CPU pins always reinstall.
assert self._classify(ver, cuda, hip) == want
class TestCpuPinSurvivesAWedgedImport:
"""A wedged import torch must not turn an explicit CPU pin into a no-op; that is when repair matters."""
@staticmethod
def _fn(name):
src = STACK.read_text(encoding = "utf-8")
start = src.index(f"def {name}(")
body = src[start : src.index("\n\ndef ", start)]
ns: dict = {
"re": __import__("re"),
"importlib": __import__("importlib.util", fromlist = ["util"]),
"Path": Path,
}
exec(compile(body, str(STACK), "exec"), ns)
return ns[name]
@pytest.mark.parametrize(
"label,want",
[
("2.9.1+xpu", True),
("2.9.1+cu128", True),
("2.9.1+rocm6.4", True),
("2.9.1+cpu", False),
("2.9.1", False),
("", False),
],
)
def test_gpu_label_classification(self, label, want):
# A slow but healthy CPU-only host must not force-reinstall torch on every update.
assert self._fn("_is_gpu_torch_label")(label) is want
def test_timeout_falls_through_to_the_repair(self):
src = STACK.read_text(encoding = "utf-8")
start = src.index('def _ensure_cpu_torch() -> "bool | None":')
body = src[start : src.index("\n\ndef ", start)]
stalled = body.index("if not _ran:")
guard = body.index("_is_gpu_torch_label(_installed_torch_label_on_disk())", stalled)
assert "return" in body[guard : guard + 200]
# The repair must accept the probe-less path, or the host needing the pin never gets it.
repair = body.index("if not _ran or not _importable:")
assert repair > guard
def test_the_disk_read_launches_no_interpreter(self):
# An interpreter here would reintroduce the hang the disk read exists to avoid.
src = STACK.read_text(encoding = "utf-8")
start = src.index("def _installed_torch_label_on_disk() -> str:")
body = src[start : src.index("\n\ndef ", start)]
assert "subprocess" not in body
assert "find_spec" in body