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.

Studio: share one torch classification probe across the repair paths (#8779)

Daniel Han7fd3eeba75c5
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index d37847cdc55..4aff0312257 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -319,30 +319,106 @@ def _select_torchao_spec(torch_version: str | None) -> str:
return _TORCHAO_DEFAULT_SPEC
-def _probe_installed_torch_version() -> str | None:
- """Return torch.__version__ from the target venv (sys.executable), or None if
- torch is absent/unimportable. Cross-platform (unlike probe_torch_wheel_env,
- which is Linux-only); mirrors the subprocess probe in _ensure_cuda_torch.
+# Memoized `import torch` classification of the target venv, reset by pip_install() and
+# pip_install_try(), the only things here that change what is installed. None means
+# "not probed yet".
+_TORCH_RUNTIME_PROBE: "tuple[bool, bool, str | None, str, str] | None" = None
+
+# Prefix on the probe's own stdout line. Import chatter can arrive before the answer, and
+# an atexit handler or a CUDA teardown notice can arrive after it, so "the last non-empty
+# line" is not reliably ours; "the last line starting with this" is.
+_TORCH_PROBE_MARKER = "UNSLOTH_TORCH_PROBE|"
+
+
+def _invalidate_torch_runtime_probe() -> None:
+ """Forget the memoized torch classification after a pip operation."""
+ global _TORCH_RUNTIME_PROBE
+ _TORCH_RUNTIME_PROBE = None
+
+
+def _probe_torch_runtime() -> "tuple[bool, bool, str | None, str, str]":
+ """Classify the venv's torch with ONE `import torch` subprocess per install run.
+
+ Returns ``(ran, importable, version, hip, cuda)``:
+ ran -- the subprocess finished; False on OSError/timeout, which is the
+ wedged-GPU-driver case where callers fall back to their on-disk
+ classifiers rather than trusting an absent answer
+ importable -- ...and it exited 0, so `import torch` actually works. A False here
+ with `ran` True is the "installed but broken" signal the repair
+ paths use to force a reinstall.
+ version -- torch.__version__ verbatim, or None when no line of ours came back.
+ None is NOT "": an empty __version__ is a broken torch the pins
+ repair, while a missing line means we learned nothing and must leave
+ the venv alone, which is what the per-path probes did on empty stdout.
+ hip -- torch.version.hip ("" when absent)
+ cuda -- torch.version.cuda ("" when absent)
+
+ The four repair paths run back to back at both repair points, and each used to spawn
+ its own `import torch` for these same facts: up to nine interpreter starts per Linux
+ update. The real cost was the timeout, not the seconds and hundreds of MB -- each
+ probe was bounded at 90s INDEPENDENTLY, so a stalled GPU driver (exactly the host
+ these paths exist to rescue) could hang an update for many minutes before the first
+ on-disk fallback ran. One probe per repair point bounds that at a single 90s wait.
"""
+ global _TORCH_RUNTIME_PROBE
+ if _TORCH_RUNTIME_PROBE is not None:
+ return _TORCH_RUNTIME_PROBE
try:
probe = subprocess.run(
[
sys.executable,
"-c",
- "import torch, sys; sys.stdout.write(getattr(torch, '__version__', ''))",
+ (
+ "import torch; "
+ "v = getattr(torch, '__version__', '') or ''; "
+ # torch.version is not guaranteed to exist. Reaching through it
+ # unguarded raises, which reads as "torch cannot import" and
+ # force-reinstalls a working venv.
+ "_v = getattr(torch, 'version', None); "
+ "h = getattr(_v, 'hip', '') or ''; "
+ "c = getattr(_v, 'cuda', '') or ''; "
+ f"print('{_TORCH_PROBE_MARKER}' + '|'.join((v, h, c)))"
+ ),
],
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
text = True,
+ # The probes this replaced each decoded with errors="replace". text=True alone
+ # decodes strictly, and a UnicodeDecodeError is a ValueError, so an undecodable
+ # byte in torch's import chatter would escape the except below and take the
+ # installer down instead of falling back to the on-disk classifier. Reachable
+ # wherever the console code page and the child's output disagree.
+ errors = "replace",
timeout = 90,
**_windows_hidden_subprocess_kwargs(),
)
except (OSError, subprocess.TimeoutExpired):
+ _TORCH_RUNTIME_PROBE = (False, False, None, "", "")
+ return _TORCH_RUNTIME_PROBE
+ # Our own marked line, last one wins: chatter can land on either side of it.
+ _marked = [
+ line.strip()
+ for line in (probe.stdout or "").splitlines()
+ if line.strip().startswith(_TORCH_PROBE_MARKER)
+ ]
+ version: "str | None" = None
+ hip = cuda = ""
+ if _marked:
+ _fields = _marked[-1][len(_TORCH_PROBE_MARKER) :].split("|")
+ version, hip, cuda = (_fields + ["", ""])[:3]
+ _TORCH_RUNTIME_PROBE = (True, probe.returncode == 0, version, hip, cuda)
+ return _TORCH_RUNTIME_PROBE
+
+
+def _probe_installed_torch_version() -> str | None:
+ """Return torch.__version__ from the target venv (sys.executable), or None if
+ torch is absent/unimportable. Cross-platform (unlike probe_torch_wheel_env,
+ which is Linux-only); shares the one probe with the torch repair paths.
+ """
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if not _ran or not _importable:
return None
- if probe.returncode != 0:
- return None
- lines = [line.strip() for line in (probe.stdout or "").splitlines() if line.strip()]
- return lines[-1] if lines else None
+ return _version or None
def _installed_distribution_version(name: str) -> str | None:
@@ -373,28 +449,11 @@ def _installed_torch_is_windows_rocm() -> bool:
"""
if not IS_WINDOWS:
return False
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import sys, torch; "
- "hip = getattr(getattr(torch, 'version', None), 'hip', None) or ''; "
- "ver = getattr(torch, '__version__', '').lower(); "
- "sys.stdout.write('yes' if (hip or 'rocm' in ver or 'rocmsdk' in ver) else '')"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- text = True,
- timeout = 90,
- **_windows_hidden_subprocess_kwargs(),
- )
- except (OSError, subprocess.TimeoutExpired):
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if not _ran or not _importable:
return False
- lines = [line.strip() for line in (probe.stdout or "").splitlines() if line.strip()]
- return probe.returncode == 0 and bool(lines and lines[-1] == "yes")
+ _ver = (_version or "").lower()
+ return bool(_hip) or "rocm" in _ver or "rocmsdk" in _ver
# constraints.txt caps new anyio resolutions at <4.14 (#6483), but an install
@@ -2291,31 +2350,12 @@ def _ensure_cuda_torch() -> None:
return
# Classify the installed torch: "hip" (ROCm poisoning signature), "cuda" (healthy),
- # or "cpu". A non-zero exit means torch is missing/un-importable: without a pin the
- # base install owns it, but a pinned CUDA index reinstalls it below.
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import torch, re; "
- "hip = getattr(torch.version, 'hip', '') or ''; "
- "cuda = getattr(torch.version, 'cuda', '') or ''; "
- "ver = getattr(torch, '__version__', '').lower(); "
- "m = re.search(r'\\+(cu\\d+)', ver); "
- "marker = 'hip' if (hip or 'rocm' in ver) else ('cuda' if cuda else 'cpu'); "
- "print('|'.join((marker, m.group(1) if m else '', ver.split('+', 1)[0], "
- "('cu' + cuda.replace('.', '')) if cuda else '')))"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- except (OSError, subprocess.TimeoutExpired):
+ # or "cpu". Un-importable means missing or broken: without a pin the base install
+ # owns it, but a pinned CUDA index reinstalls it below.
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if not _ran:
return
- if probe.returncode != 0:
+ if not _importable:
# torch present but can't import. Without a pin the base install owns it; but an
# explicit CUDA pin forces this pass (failed probe) and the base update won't
# reinstall an already-installed torch, so reinstall from the pin (self-resolving).
@@ -2339,17 +2379,18 @@ def _ensure_cuda_torch() -> None:
constrain = False,
)
return
- # Last non-empty line: stray sitecustomize/import-hook output must not mask the marker.
- _marker_lines = [
- line.strip() for line in probe.stdout.decode(errors = "replace").splitlines() if line.strip()
- ]
- if not _marker_lines:
+ if _version is None:
+ # Nothing readable came back, so classify nothing: this is where the per-path
+ # probe returned when its stdout held no line.
return
# marker | +cuXXX local tag | release | family from torch.version.cuda. The last is the
# only CUDA clue an untagged wheel gives: PyPI forbids the local +cuXXX version.
- _marker, _installed_cu, _installed_release, _runtime_cu = (
- _marker_lines[-1].split("|") + ["", "", ""]
- )[:4]
+ _ver = _version.lower()
+ _cu_match = re.search(r"\+(cu\d+)", _ver)
+ _marker = "hip" if (_hip or "rocm" in _ver) else ("cuda" if _cuda else "cpu")
+ _installed_cu = _cu_match.group(1) if _cu_match else ""
+ _installed_release = _ver.split("+", 1)[0]
+ _runtime_cu = ("cu" + _cuda.replace(".", "")) if _cuda else ""
# Reinstall on a ROCm build on an NVIDIA host (poisoning signature), when a CUDA index
# is pinned but the venv has the wrong family (CPU or a different cuXXX), or when the
# installed family ships no kernels for this host's GPUs. A healthy match, or a CPU
@@ -2429,29 +2470,9 @@ def _ensure_xpu_torch() -> None:
if pin is None:
return
- # A non-zero exit means torch is missing or un-importable; the pin installs it below
- # either way. Bounded like every other probe here.
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- # Flavour AND range: a migrated 2.5+xpu venv is broken, not correct, so the
- # tag alone is not enough. Range matches _XPU_TORCH_PKG_SPEC.
- "import torch; "
- "ver = getattr(torch, '__version__', '').lower(); "
- "rel = ver.split('+')[0].split('.'); "
- "n = tuple(int(x) for x in rel[:2] if x.isdigit()); "
- "ok = '+xpu' in ver and len(n) == 2 and (2, 6) <= n < (2, 11); "
- "print('ok' if ok else 'repair')"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- except (OSError, subprocess.TimeoutExpired):
+ # Un-importable either way installs from the pin below. One shared probe bounds it.
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if not _ran:
# Inconclusive, so ask the disk, which answers without loading SYCL. An unsupported or
# missing wheel does need the reinstall (the resolver keeps a too-old +xpu wheel because
# it satisfies the base range). A supported one means the Intel DRIVER is stalled, and
@@ -2465,22 +2486,16 @@ def _ensure_xpu_torch() -> None:
)
)
return
- probe = None
- _lines = (
- [
- line.strip()
- for line in probe.stdout.decode(errors = "replace").splitlines()
- if line.strip()
- ]
- if probe is not None
- else []
- )
- if probe is None:
_why = "torch could not be probed"
- elif probe.returncode == 0:
- if not _lines:
+ elif _importable:
+ if _version is None:
return # unreadable -- the base install step handles a missing torch
- if _lines[-1] == "ok":
+ # Flavour AND range: a migrated 2.5+xpu venv is broken, not correct, so the tag
+ # alone is not enough. Range matches _XPU_TORCH_PKG_SPEC.
+ _ver = _version.lower()
+ _rel = _ver.split("+")[0].split(".")
+ _n = tuple(int(x) for x in _rel[:2] if x.isdigit())
+ if "+xpu" in _ver and len(_n) == 2 and (2, 6) <= _n < (2, 11):
return # already the pinned family, in the supported range
_why = "torch is not a supported XPU build"
else:
@@ -2762,37 +2777,16 @@ def _ensure_cpu_torch() -> None:
if pin is None:
return
- # Classify the installed torch family. A non-zero exit means torch is missing or
- # un-importable: the explicit CPU pin reinstalls it below.
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import torch, re; "
- "hip = getattr(torch.version, 'hip', '') or ''; "
- "cuda = getattr(torch.version, 'cuda', '') or ''; "
- "ver = getattr(torch, '__version__', '').lower(); "
- # '+xpu' too: an XPU wheel sets neither torch.version.cuda nor .hip, so
- # without it a working Intel build reads as "cpu" and a CPU pin over it does
- # nothing. Local label, since torch.version.xpu is None on some builds.
- "gpu = bool(hip) or 'rocm' in ver or bool(cuda) or bool(re.search(r'\\+cu\\d+', ver)) or '+xpu' in ver; "
- "print('gpu' if gpu else 'cpu')"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- except (OSError, subprocess.TimeoutExpired):
+ # Classify the torch family. Un-importable means missing or broken, and the
+ # explicit CPU pin reinstalls it below.
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if not _ran:
# A hung import is the wedged-driver case this pin exists to rescue, so returning here
# made the pin a no-op on exactly that host. Classify off disk instead, and only go on
# for a GPU label: a merely slow CPU-only box must not reinstall torch every update.
if not _is_gpu_torch_label(_installed_torch_label_on_disk()):
return
- probe = None
- if probe is None or probe.returncode != 0:
+ if not _ran or not _importable:
# torch present but can't import. The explicit CPU pin forces this pass (failed
# probe) and the base update won't reinstall an already-installed torch, so
# reinstall from the pin (self-resolving, no loop).
@@ -2813,12 +2807,19 @@ def _ensure_cpu_torch() -> None:
constrain = False,
)
return
- _lines = [
- line.strip() for line in probe.stdout.decode(errors = "replace").splitlines() if line.strip()
- ]
- if not _lines:
+ if _version is None:
return # unreadable -- the base install step handles a missing torch
- if _lines[-1] != "gpu":
+ # '+xpu' too: an XPU wheel sets neither torch.version.cuda nor .hip, so without it a
+ # working Intel build reads as "cpu" and the CPU pin over it does nothing.
+ _ver = _version.lower()
+ _is_gpu_build = (
+ bool(_hip)
+ or "rocm" in _ver
+ or bool(_cuda)
+ or bool(re.search(r"\+cu\d+", _ver))
+ or "+xpu" in _ver
+ )
+ if not _is_gpu_build:
return # already a CPU build
_safe_print(
@@ -2861,26 +2862,8 @@ def _ensure_rocm_torch() -> None:
# setup.ps1 sets this after installing AMD wheels; skip only when torch is actually
# importable as ROCm (a wiped venv leaves a stale env-var that must not suppress it).
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
- _torch_ok = False
- try:
- _probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import torch; "
- "hip=getattr(torch.version,'hip','') or ''; "
- "import sys; "
- "sys.exit(0 if (hip or 'rocm' in torch.__version__.lower()) else 1)"
- ),
- ],
- stdout = subprocess.DEVNULL,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- _torch_ok = _probe.returncode == 0
- except (OSError, subprocess.TimeoutExpired):
- pass
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ _torch_ok = _ran and _importable and (bool(_hip) or "rocm" in (_version or "").lower())
if _torch_ok:
_rocm_windows_torch_installed = True
# ROCm torch is already installed, but bnb still needs the ROCm build
@@ -2902,28 +2885,11 @@ def _ensure_rocm_torch() -> None:
gfx_arch = _detect_windows_gfx_arch()
if not gfx_arch and _win_rocm_pin is None:
return # no AMD GPU visible via hipinfo
- # Probe whether torch already links against HIP.
- _torch_already_rocm = False
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import torch; "
- "hip=getattr(torch.version,'hip','') or ''; "
- "ver=torch.__version__; "
- "print('yes' if hip or 'rocm' in ver.lower() else '')"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- if probe.returncode == 0 and probe.stdout.decode().strip() == "yes":
- _torch_already_rocm = True
- except (OSError, subprocess.TimeoutExpired):
- pass
+ # Whether torch already links against HIP.
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ _torch_already_rocm = (
+ _ran and _importable and (bool(_hip) or "rocm" in (_version or "").lower())
+ )
# "Is ROCm" is not "is the RIGHT ROCm": wheels are per-family, so a host whose arch
# now resolves elsewhere (dGPU added, or the #7776 repick) would keep the old family
# forever. setup.ps1 force-reinstalls every run, so this only bites standalone
@@ -3011,41 +2977,15 @@ def _ensure_rocm_torch() -> None:
# Explicit pin or inferred gfx: the index drives the install.
ver = (0, 0)
- # Probe whether torch links against HIP, capturing the installed ROCm tag for pin-mismatch
- # detection. Emit ONE "<hip_marker>|<version>" line: marker (HIP version, "rocm" sentinel,
- # or empty for CPU/CUDA) before "|", wheel version after.
- try:
- probe = subprocess.run(
- [
- sys.executable,
- "-c",
- (
- "import torch; "
- "hip=getattr(torch.version,'hip','') or ''; "
- "ver=getattr(torch,'__version__','').lower(); "
- # HIP version if present, else a "rocm" sentinel when only the
- # version string flags ROCm; empty marker = CPU/CUDA torch.
- "marker=hip if hip else ('rocm' if 'rocm' in ver else ''); "
- "print(marker + '|' + ver)"
- ),
- ],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- timeout = 90,
- )
- except (OSError, subprocess.TimeoutExpired):
- probe = None
- # Last non-empty line, split on the FIRST "|" so the empty HIP field is preserved.
- _marker_lines = (
- [ln.strip() for ln in probe.stdout.decode(errors = "replace").splitlines() if ln.strip()]
- if (probe is not None and probe.returncode == 0)
- else []
- )
- _hip_marker, _sep, _installed_torch_ver = (
- _marker_lines[-1].partition("|") if _marker_lines else ("", "", "")
- )
- # A "|"-delimited line is required; without it treat HIP as absent -> reinstall.
- has_hip_torch = bool(_sep) and _hip_marker != ""
+ # Whether torch links against HIP, capturing the installed ROCm tag for pin-mismatch
+ # detection. Marker is the HIP version, else a "rocm" sentinel when only the version
+ # string flags ROCm; empty = CPU/CUDA torch, or un-probeable, which reinstalls.
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ _installed_torch_ver = (_version or "").lower() if (_ran and _importable) else ""
+ _hip_marker = ""
+ if _ran and _importable:
+ _hip_marker = _hip if _hip else ("rocm" if "rocm" in _installed_torch_ver else "")
+ has_hip_torch = _hip_marker != ""
# An explicit ROCm pin whose family differs from the installed torch must reinstall, else a
# rocm7.2/gfx* pin over an older +rocm6.4/7.1 build never applies. Version-tag heuristic
@@ -4120,6 +4060,9 @@ def pip_install_try(
"""Like pip_install but returns False on failure instead of exiting.
For optional installs that have a follow-up fallback.
"""
+ # Same reason as pip_install: this installs torch too (the Windows AMD ROCm trio),
+ # so the memoized classification must not survive it.
+ _invalidate_torch_runtime_probe()
constraint_args_pip: list[str] = []
constraint_args_uv: list[str] = []
if constrain and CONSTRAINTS.is_file():
@@ -4157,6 +4100,9 @@ def pip_install(
constrain: bool = True,
) -> None:
"""Build and run a pip install command (uses uv when available, falls back to pip)."""
+ # Any pip operation can change which torch is installed, so the memoized
+ # classification must not outlive it.
+ _invalidate_torch_runtime_probe()
constraint_args_pip: list[str] = []
constraint_args_uv: list[str] = []
if constrain and CONSTRAINTS.is_file():
diff --git a/tests/studio/install/test_cuda_repair.py b/tests/studio/install/test_cuda_repair.py
index a5ee4c16e6a..da6b46a4a59 100644
--- a/tests/studio/install/test_cuda_repair.py
+++ b/tests/studio/install/test_cuda_repair.py
@@ -21,10 +21,42 @@ stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
sys.modules[_STACK_SPEC.name] = stack_mod
_STACK_SPEC.loader.exec_module(stack_mod)
+# The probe prints its answer behind this marker, so chatter on either side of it cannot
+# be mistaken for the answer. Mocked stdout has to carry it too.
+_MARK = stack_mod._TORCH_PROBE_MARKER
+
_ensure_cuda_torch = stack_mod._ensure_cuda_torch
_detect_cuda_torch_index_url = stack_mod._detect_cuda_torch_index_url
+def _dotted_cuda(tag):
+ """ "cu128" -> "12.8", the torch.version.cuda form. Minor is the last digit."""
+ digits = tag[2:] if tag.startswith("cu") else tag
+ if not digits.isdigit() or len(digits) < 2:
+ return ""
+ return f"{digits[:-1]}.{digits[-1]}"
+
+
+def _torch_probe_line(torch_state, cuda_version):
+ """Render the shared probe's "<version>|<hip>|<cuda>" line for a test's
+ "<marker>|<installed_cu>|<release>|<runtime_cu>" shorthand.
+
+ _ensure_cuda_torch now derives the marker from torch.__version__ /
+ torch.version.hip / torch.version.cuda rather than reading a pre-computed
+ marker, so the mock has to emit a self-consistent build: a "cuda" marker
+ means torch.version.cuda is set, which always yields a runtime family.
+ """
+ marker, installed_cu, release, runtime_cu = (torch_state.split("|") + ["", "", ""])[:4]
+ release = release or "2.9.1"
+ if marker == "hip":
+ return _MARK + f"{release}+rocm6.4|6.4|"
+ if marker == "cuda":
+ version = f"{release}+{installed_cu}" if installed_cu else release
+ cuda = _dotted_cuda(runtime_cu) or _dotted_cuda(installed_cu) or cuda_version
+ return _MARK + f"{version}||{cuda}"
+ return _MARK + f"{release}||"
+
+
def _make_run(
torch_state = "hip",
cuda_version = "12.8",
@@ -32,7 +64,7 @@ def _make_run(
smi_rc = 0,
compute_caps = ("8.6",),
):
- """subprocess.run side_effect: torch-classify probe (sys.executable, bytes
+ """subprocess.run side_effect: the shared torch probe (sys.executable, text
stdout) vs the nvidia-smi version / compute-capability probes (smi path,
text=True), keyed on the executable."""
@@ -41,7 +73,8 @@ def _make_run(
exe = str(cmd[0]) if cmd else ""
if exe == sys.executable:
result.returncode = torch_rc
- result.stdout = (torch_state + "\n").encode()
+ out = _torch_probe_line(torch_state, cuda_version) + "\n"
+ result.stdout = out if kwargs.get("text") else out.encode()
return result
result.returncode = smi_rc
if len(cmd) > 1 and str(cmd[1]) == "--query-gpu=compute_cap":
@@ -96,6 +129,10 @@ def _run_cuda_repair(
return smi_path
return None
+ # The torch classification is memoized for the life of an install run, so each
+ # scenario has to start from a clean slate.
+ stack_mod._invalidate_torch_runtime_probe()
+
with (
patch.object(stack_mod, "_TORCH_BACKEND", backend),
patch.object(stack_mod, "IS_MACOS", is_macos),
@@ -557,13 +594,19 @@ class TestPreTuringWheelFamily:
)
mock_pip.assert_not_called()
- def test_untagged_cuda_build_is_left_alone(self):
+ def test_untagged_cuda_build_uses_the_runtime_family(self):
+ # An untagged build still reports torch.version.cuda, so _family falls back to
+ # the runtime value and the architecture policy applies.
+ # The "family unknown, leave it alone" branch needs BOTH the tag and
+ # torch.version.cuda empty, which reads as a CPU build, so an untagged CUDA
+ # build is always classifiable.
mock_pip = _run_cuda_repair(
torch_state = "cuda||2.11.0",
cuda_version = "13.0",
compute_caps = ("7.0",),
)
- mock_pip.assert_not_called()
+ assert mock_pip.call_count == 1
+ assert "cu126" in _index_url(mock_pip)
def test_non_x86_host_keeps_the_driver_family(self):
# No aarch64 CUDA family ships sm_<80 kernels, so cu126 cannot help there.
diff --git a/tests/studio/install/test_rocm_gfx_spoof_7331.py b/tests/studio/install/test_rocm_gfx_spoof_7331.py
index f60fe6a47dd..cfd907546da 100644
--- a/tests/studio/install/test_rocm_gfx_spoof_7331.py
+++ b/tests/studio/install/test_rocm_gfx_spoof_7331.py
@@ -60,9 +60,18 @@ _STACK_SPEC.loader.exec_module(stack_mod)
_INSTALL_SH = PACKAGE_ROOT / "install.sh"
-# torch probe stdout: "<hip marker>|<version>". Empty marker = CPU/CUDA torch.
-_CPU_TORCH = b"|2.10.0+cpu\n"
-_ROCM63_TORCH = b"6.3.42134|2.9.1+rocm6.3\n" # what the reporter ended up with
+# torch probe stdout: "<version>|<hip>|<cuda>". An empty HIP field = CPU/CUDA torch.
+_CPU_TORCH = "2.10.0+cpu||\n"
+_ROCM63_TORCH = "2.9.1+rocm6.3|6.3.42134|\n" # what the reporter ended up with
+
+
[email protected](autouse = True)
+def _reset_torch_runtime_probe():
+ """The torch classification is memoized for the life of an install run, so one
+ test's mocked probe must not leak into the next."""
+ stack_mod._invalidate_torch_runtime_probe()
+ yield
+ stack_mod._invalidate_torch_runtime_probe()
def _run_install(
diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.py
index e1e2612723a..5e0a3e953c8 100644
--- a/tests/studio/install/test_rocm_support.py
+++ b/tests/studio/install/test_rocm_support.py
@@ -47,6 +47,10 @@ stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
sys.modules[_STACK_SPEC.name] = stack_mod
_STACK_SPEC.loader.exec_module(stack_mod)
+# The probe prints its answer behind this marker, so chatter on either side of it cannot
+# be mistaken for the answer. Mocked stdout has to carry it too.
+_MARK = stack_mod._TORCH_PROBE_MARKER
+
_detect_rocm_version = stack_mod._detect_rocm_version
_ensure_rocm_torch = stack_mod._ensure_rocm_torch
_has_rocm_gpu = stack_mod._has_rocm_gpu
@@ -57,6 +61,15 @@ _detect_windows_gfx_arch = stack_mod._detect_windows_gfx_arch
_install_bnb_windows_rocm = stack_mod._install_bnb_windows_rocm
[email protected](autouse = True)
+def _reset_torch_runtime_probe():
+ """The torch classification is memoized for the life of an install run, so one
+ test's mocked probe must not leak into the next."""
+ stack_mod._invalidate_torch_runtime_probe()
+ yield
+ stack_mod._invalidate_torch_runtime_probe()
+
+
def _extract_sh_function_body(source: str, name: str) -> str:
"""Return a shell function body from `source` by brace matching."""
needle = f"{name}() {{"
@@ -619,7 +632,7 @@ class TestEnsureRocmTorch:
"""Strix Halo without /dev/kfd must still get AMD gfx1151 wheels (unslothai#7301)."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"|2.10.0+cpu\n"
+ mock_probe.stdout = _MARK + "2.10.0+cpu||\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -644,7 +657,7 @@ class TestEnsureRocmTorch:
the AMD gfx wheels."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"|2.10.0+cpu\n"
+ mock_probe.stdout = _MARK + "2.10.0+cpu||\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -671,7 +684,7 @@ class TestEnsureRocmTorch:
(Strix override / generic branch) decides instead."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"|2.10.0+cpu\n"
+ mock_probe.stdout = _MARK + "2.10.0+cpu||\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -695,7 +708,7 @@ class TestEnsureRocmTorch:
and leave CPU torch in place -- the per-arch install runs."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"|2.10.0+cpu\n"
+ mock_probe.stdout = _MARK + "2.10.0+cpu||\n"
with patch.dict(os.environ, {"UNSLOTH_ROCM_GFX_ARCH": "gfx1151"}):
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
@@ -720,7 +733,7 @@ class TestEnsureRocmTorch:
mock_probe = MagicMock()
mock_probe.returncode = 0
# Single-line probe: empty HIP marker before "|" for a CUDA build.
- mock_probe.stdout = b"|2.10.0+cu126\n"
+ mock_probe.stdout = _MARK + "2.10.0+cu126||\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -733,7 +746,7 @@ class TestEnsureRocmTorch:
Returns the pip_install_try mock so callers can assert on the reinstall.
"""
- probe = MagicMock(returncode = 0, stdout = b"yes\n")
+ probe = MagicMock(returncode = 0, stdout = _MARK + "2.10.0+rocm7.1|7.1|\n")
pip_try = MagicMock(return_value = True)
with patch.dict(os.environ, {}, clear = False):
os.environ.pop("UNSLOTH_ROCM_TORCH_INSTALLED", None)
@@ -837,7 +850,7 @@ class TestEnsureRocmTorch:
"""If torch already has HIP, should skip ROCm reinstall."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.1.12345|2.10.0+rocm7.1\n" # HIP marker + version
+ mock_probe.stdout = _MARK + "2.10.0+rocm7.1|7.1.12345|\n" # HIP marker + version
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -854,7 +867,7 @@ class TestEnsureRocmTorch:
and the reinstall fires."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"|2.10.0+cpu\n"
+ mock_probe.stdout = _MARK + "2.10.0+cpu||\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
with patch.object(stack_mod, "pip_install_try", return_value = True):
@@ -874,7 +887,7 @@ class TestEnsureRocmTorch:
"""CPU-only torch on ROCm host should trigger reinstall."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # empty = no GPU backend
+ mock_probe.stdout = "\n" # empty = no GPU backend
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -893,7 +906,7 @@ class TestEnsureRocmTorch:
"""ROCm 6.3 should select rocm6.3 tag."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n"
+ mock_probe.stdout = "\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -908,7 +921,7 @@ class TestEnsureRocmTorch:
"""ROCm version too old (below 6.0) should skip."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n"
+ mock_probe.stdout = "\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -939,7 +952,7 @@ class TestEnsureRocmTorch:
"""ROCm 7.2 should select rocm7.2 tag (now in mapping with torch 2.11.0)."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n"
+ mock_probe.stdout = "\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -959,7 +972,7 @@ class TestEnsureRocmTorch:
"""ROCm 7.14 caps to rocm7.2 on pytorch.org; Strix must use AMD gfx index."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.14.60850|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.14.60850|\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -986,7 +999,7 @@ class TestEnsureRocmTorch:
# Strix and routes the install to the Strix-only AMD index.
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.14.60850|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.14.60850|\n"
buf = io.StringIO()
with patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "1"}, clear = False):
for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
@@ -1016,7 +1029,7 @@ class TestEnsureRocmTorch:
# Negative control: device 2 really is the Strix, so the reroute must still fire.
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.14.60850|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.14.60850|\n"
with patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "2"}, clear = False):
for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
os.environ.pop(_v, None)
@@ -1110,7 +1123,7 @@ Agent 4
pinned torch index."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall
+ mock_probe.stdout = "\n" # cpu torch -> reinstall
env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx1151"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
@@ -1188,7 +1201,7 @@ Agent 4
mock_probe = MagicMock()
mock_probe.returncode = 0
# HIP marker present (has_hip_torch=True) + installed +rocm6.4 wheel.
- mock_probe.stdout = b"6.4.12345|2.10.0+rocm6.4\n"
+ mock_probe.stdout = _MARK + "2.10.0+rocm6.4|6.4.12345|\n"
env = {"UNSLOTH_TORCH_INDEX_FAMILY": "rocm7.2"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_URL", None)
@@ -1212,7 +1225,7 @@ Agent 4
The gfx probe may run for the bnb-skip flag but must not alter the pinned index."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"6.4.12345|2.10.0+rocm6.4\n"
+ mock_probe.stdout = _MARK + "2.10.0+rocm6.4|6.4.12345|\n"
env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx1151"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
@@ -1237,7 +1250,7 @@ Agent 4
(no false reinstall of a correct ROCm venv)."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.2.12345|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.2.12345|\n"
env = {"UNSLOTH_TORCH_INDEX_FAMILY": "rocm7.2"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_URL", None)
@@ -1271,7 +1284,7 @@ Agent 4
specs for that arch, so re-flagging would reinstall-loop on every update."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"6.4.12345|2.10.0+rocm6.4\n"
+ mock_probe.stdout = _MARK + "2.10.0+rocm6.4|6.4.12345|\n"
env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx110X-all"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
@@ -1297,7 +1310,7 @@ Agent 4
is not the per-arch build the user pinned (Strix stays off the generic wheel)."""
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.2.12345|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.2.12345|\n"
env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx1151"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
@@ -1371,7 +1384,7 @@ Agent 4
not repair a broken installed torch, so returning would strand it (Codex P2)."""
mock_probe = MagicMock()
mock_probe.returncode = 1 # torch present but cannot import
- mock_probe.stdout = b""
+ mock_probe.stdout = ""
env = {"UNSLOTH_TORCH_INDEX_URL": "https://mirror.local/cpu"}
with patch.dict(stack_mod.os.environ, env, clear = False):
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
@@ -1505,7 +1518,7 @@ class TestGfx906LegacyReroute:
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall
+ mock_probe.stdout = "\n" # cpu torch -> reinstall
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1535,7 +1548,7 @@ class TestGfx906LegacyReroute:
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"7.2.12345|2.11.0+rocm7.2\n"
+ mock_probe.stdout = _MARK + "2.11.0+rocm7.2|7.2.12345|\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1560,7 +1573,7 @@ class TestGfx906LegacyReroute:
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"6.3.42131|2.7.0+rocm6.3\n"
+ mock_probe.stdout = _MARK + "2.7.0+rocm6.3|6.3.42131|\n"
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1586,7 +1599,7 @@ class TestGfx906LegacyReroute:
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall
+ mock_probe.stdout = "\n" # cpu torch -> reinstall
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1611,7 +1624,7 @@ class TestGfx906LegacyReroute:
monkeypatch.setenv("UNSLOTH_ROCM_GFX_ARCH", "gfx906")
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall
+ mock_probe.stdout = "\n" # cpu torch -> reinstall
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1638,7 +1651,7 @@ class TestGfx906LegacyReroute:
monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://download.pytorch.org/whl/rocm6.3")
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall from the pinned index
+ mock_probe.stdout = "\n" # cpu torch -> reinstall from the pinned index
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1664,7 +1677,7 @@ class TestGfx906LegacyReroute:
monkeypatch.setenv("UNSLOTH_ROCM_GFX_ARCH", "gfx906")
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall
+ mock_probe.stdout = "\n" # cpu torch -> reinstall
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -1694,7 +1707,7 @@ class TestGfx906LegacyReroute:
monkeypatch.setenv("UNSLOTH_TORCH_INDEX_URL", "https://download.pytorch.org/whl/rocm6.3")
mock_probe = MagicMock()
mock_probe.returncode = 0
- mock_probe.stdout = b"\n" # cpu torch -> reinstall from the pinned index
+ mock_probe.stdout = "\n" # cpu torch -> reinstall from the pinned index
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = mock_probe):
_ensure_rocm_torch()
@@ -4681,9 +4694,11 @@ class TestRocmTorchInstalledEnvVar:
@staticmethod
def _ok_torch_probe(*a, **kw):
- # Probe returns 0 when torch imports as ROCm.
+ # The shared probe exits 0 when torch imports and reports the build on stdout;
+ # a non-empty HIP version is what marks it as ROCm.
rv = MagicMock()
rv.returncode = 0
+ rv.stdout = _MARK + "2.10.0+rocm7.1|7.1|\n"
return rv
@patch.object(stack_mod, "_install_bnb_windows_rocm")
@@ -4748,7 +4763,7 @@ class TestWindowsRocmTorchaoGuard:
def test_installed_torch_is_windows_rocm_accepts_rocm_probe(self):
rv = MagicMock()
rv.returncode = 0
- rv.stdout = "yes"
+ rv.stdout = _MARK + "2.10.0+rocm7.1|7.1|"
with (
patch.object(stack_mod, "IS_WINDOWS", True),
patch.object(stack_mod.subprocess, "run", return_value = rv),
diff --git a/tests/studio/install/test_torch_probe_classification_parity.py b/tests/studio/install/test_torch_probe_classification_parity.py
new file mode 100644
index 00000000000..8af9f715198
--- /dev/null
+++ b/tests/studio/install/test_torch_probe_classification_parity.py
@@ -0,0 +1,281 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The shared torch probe must classify exactly as the five probes it replaced.
+
+Consolidating those probes moved their classification out of a subprocess `-c` string
+and into ordinary Python in the repair paths. That is meant to be a translation and
+nothing more, but a translation is precisely the kind of change that can be subtly
+wrong while every existing test still passes, because the existing tests feed the
+repair paths a *mocked* probe answer and therefore exercise the new derivation only,
+never the old one.
+
+So this compares the two directly. The old expressions are reproduced verbatim from
+the merge base as reference implementations, cited by line. The new derivations are
+pulled out of the live module with `ast` rather than copied, so they cannot drift from
+what actually ships: if someone edits the derivation, this test reads the edit. If
+someone renames the locals it asserts on, extraction fails loudly, which is the right
+outcome, because a rename means the equivalence needs re-checking rather than assuming.
+
+Both sides then run over the same matrix of torch states and must agree on every one.
+
+Scope, stated honestly. This proves the classification is a faithful translation. It
+does not prove the memoisation is safe, which is a separate property resting on
+`pip_install` / `pip_install_try` being the only things that change the installed
+torch, and it does not exercise real AMD, Intel or Windows hosts.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"
+
+_STACK_SPEC = importlib.util.spec_from_file_location(
+ "studio_install_python_stack_parity_probe", _STACK_PATH
+)
+assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None
+stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
+sys.modules[_STACK_SPEC.name] = stack_mod
+_STACK_SPEC.loader.exec_module(stack_mod)
+
+_SOURCE = _STACK_PATH.read_text(encoding = "utf-8")
+_TREE = ast.parse(_SOURCE, str(_STACK_PATH))
+
+
+# The torch states the classification has to agree on. Each is
+# (torch.__version__, torch.version.hip, torch.version.cuda) as the probe reports them.
+_TORCH_STATES = [
+ # CUDA, tagged
+ ("2.9.1+cu128", "", "12.8"),
+ ("2.7.1+cu118", "", "11.8"),
+ ("2.11.0+cu130", "", "13.0"),
+ ("2.10.0+cu126", "", "12.6"),
+ # CUDA, untagged wheel: torch.version.cuda is the only clue
+ ("2.11.0", "", "13.0"),
+ ("2.9.1", "", "12.8"),
+ # ROCm, by hip
+ ("2.10.0+rocm7.1", "7.1.12345", ""),
+ ("2.9.1+rocm6.3", "6.3.42134", ""),
+ ("2.11.0+rocm7.2", "7.14.60850", ""),
+ # ROCm, flagged by the version string only
+ ("2.9.1+rocm6.4", "", ""),
+ ("2.10.0+rocmsdk20250901", "", ""),
+ # XPU, in and out of the supported range
+ ("2.6.0+xpu", "", ""),
+ ("2.9.1+xpu", "", ""),
+ ("2.10.0+xpu", "", ""),
+ ("2.5.1+xpu", "", ""),
+ ("2.11.0+xpu", "", ""),
+ ("3.0.0+xpu", "", ""),
+ # CPU
+ ("2.9.1+cpu", "", ""),
+ ("2.10.0", "", ""),
+ # macOS arm64
+ ("2.9.1", "", ""),
+ # Degenerate
+ ("", "", ""),
+ ("2.9.1", "7.1", "12.8"), # both set: hip must win
+ # Case. Every consumer lowercases before matching, and these are the only states
+ # that can tell a missing .lower() apart: each substring test below has to be the
+ # deciding one, so nothing else may independently mark the build as a GPU.
+ # Without them a dropped .lower() passes the whole matrix, which it did.
+ ("2.9.1+ROCM6.4", "", ""),
+ ("2.10.0+XPU", "", ""),
+ ("2.9.1+CU128", "", ""),
+ ("2.10.0+ROCMSDK20250901", "", ""),
+]
+
+
+def _fn(name):
+ for node in ast.walk(_TREE):
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return node
+ raise AssertionError(f"{name} not found in {_STACK_PATH.name}")
+
+
+def _run_assignments(fn_name, wanted, env):
+ """Execute the live assignments for `wanted`, in source order, against `env`.
+
+ Straight-line derivations over the probe's outputs, so running them outside their
+ guards is faithful as long as the guard variables are bound in env.
+ """
+ found = set()
+ for node in ast.walk(_fn(fn_name)):
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):
+ continue
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ names = [t.id for t in targets if isinstance(t, ast.Name)]
+ if not any(n in wanted for n in names):
+ continue
+ if node.value is None:
+ continue
+ exec(compile(ast.Module([node], []), "<live>", "exec"), env) # noqa: S102
+ found.update(n for n in names if n in wanted)
+ missing = set(wanted) - found
+ assert not missing, (
+ f"{fn_name}: could not extract {sorted(missing)} from the live source. "
+ f"If these were renamed, the equivalence needs re-checking rather than assuming."
+ )
+ return env
+
+
+def _if_test_containing(fn_name, needle, env):
+ """Evaluate the live `if` condition that contains `needle`."""
+ for node in ast.walk(_fn(fn_name)):
+ if isinstance(node, ast.If) and needle in ast.unparse(node.test):
+ return eval(compile(ast.Expression(node.test), "<live>", "eval"), env) # noqa: S307
+ raise AssertionError(f"{fn_name}: no `if` test containing {needle!r}")
+
+
+# Reference implementations: the probe expressions as they stood at the merge base.
+# Reproduced verbatim, only re-indented from the `-c` strings they lived in.
+
+
+def _old_cuda_fields(ver, hip, cuda):
+ """merge base studio/install_python_stack.py:2339-2346 (_ensure_cuda_torch)."""
+ ver = ver.lower()
+ m = re.search(r"\+(cu\d+)", ver)
+ marker = "hip" if (hip or "rocm" in ver) else ("cuda" if cuda else "cpu")
+ return (
+ marker,
+ m.group(1) if m else "",
+ ver.split("+", 1)[0],
+ ("cu" + cuda.replace(".", "")) if cuda else "",
+ )
+
+
+def _old_cpu_is_gpu(ver, hip, cuda):
+ """merge base :2773-2780 (_ensure_cpu_torch)."""
+ ver = ver.lower()
+ return (
+ bool(hip)
+ or "rocm" in ver
+ or bool(cuda)
+ or bool(re.search(r"\+cu\d+", ver))
+ or "+xpu" in ver
+ )
+
+
+def _old_xpu_ok(ver, hip, cuda):
+ """merge base :2442-2447 (_ensure_xpu_torch)."""
+ ver = ver.lower()
+ rel = ver.split("+")[0].split(".")
+ n = tuple(int(x) for x in rel[:2] if x.isdigit())
+ return "+xpu" in ver and len(n) == 2 and (2, 6) <= n < (2, 11)
+
+
+def _old_rocm_marker(ver, hip, cuda):
+ """merge base :3023-3027 (_ensure_rocm_torch)."""
+ ver = ver.lower()
+ return hip if hip else ("rocm" if "rocm" in ver else "")
+
+
+def _old_windows_rocm_yes(ver, hip, cuda):
+ """merge base :382-385 (_installed_torch_is_windows_rocm)."""
+ ver = ver.lower()
+ return bool(hip or "rocm" in ver or "rocmsdk" in ver)
+
+
+ "ver,hip,cuda", _TORCH_STATES, ids = [s[0] or "empty" for s in _TORCH_STATES]
+)
+class TestClassificationIsAFaithfulTranslation:
+ def test_cuda_marker_tag_release_and_runtime_family(self, ver, hip, cuda):
+ env = {"re": re, "_version": ver, "_hip": hip, "_cuda": cuda}
+ _run_assignments(
+ "_ensure_cuda_torch",
+ {"_ver", "_cu_match", "_marker", "_installed_cu", "_installed_release", "_runtime_cu"},
+ env,
+ )
+ new = (env["_marker"], env["_installed_cu"], env["_installed_release"], env["_runtime_cu"])
+ assert new == _old_cuda_fields(ver, hip, cuda)
+
+ def test_cpu_gpu_predicate(self, ver, hip, cuda):
+ env = {"re": re, "_version": ver, "_hip": hip, "_cuda": cuda}
+ _run_assignments("_ensure_cpu_torch", {"_ver", "_is_gpu_build"}, env)
+ assert env["_is_gpu_build"] == _old_cpu_is_gpu(ver, hip, cuda)
+
+ def test_xpu_supported_range(self, ver, hip, cuda):
+ env = {"re": re, "_version": ver, "_hip": hip, "_cuda": cuda}
+ _run_assignments("_ensure_xpu_torch", {"_ver", "_rel", "_n"}, env)
+ assert _if_test_containing("_ensure_xpu_torch", "+xpu", env) == _old_xpu_ok(ver, hip, cuda)
+
+ def test_rocm_hip_marker(self, ver, hip, cuda):
+ env = {
+ "re": re,
+ "_version": ver,
+ "_hip": hip,
+ "_cuda": cuda,
+ "_ran": True,
+ "_importable": True,
+ }
+ _run_assignments("_ensure_rocm_torch", {"_installed_torch_ver", "_hip_marker"}, env)
+ assert env["_hip_marker"] == _old_rocm_marker(ver, hip, cuda)
+ assert env["_installed_torch_ver"] == ver.lower()
+
+ def test_windows_rocm_verdict(self, ver, hip, cuda):
+ probe = (True, True, ver, hip, cuda)
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(stack_mod, "IS_WINDOWS", True)
+ mp.setattr(stack_mod, "_probe_torch_runtime", lambda: probe)
+ got = stack_mod._installed_torch_is_windows_rocm()
+ assert got == _old_windows_rocm_yes(ver, hip, cuda)
+
+
+def test_the_extraction_actually_reads_the_live_source():
+ """If extraction silently found nothing, every parity test above would be vacuous."""
+ env = {"re": re, "_version": "2.9.1+cu128", "_hip": "", "_cuda": "12.8"}
+ _run_assignments(
+ "_ensure_cuda_torch",
+ {"_ver", "_cu_match", "_marker", "_installed_cu", "_installed_release", "_runtime_cu"},
+ env,
+ )
+ assert env["_marker"] == "cuda"
+ assert env["_installed_cu"] == "cu128"
+ assert env["_runtime_cu"] == "cu128"
+
+
+def test_probe_survives_undecodable_import_chatter():
+ """errors="replace" is invisible to a mock, so this runs a real subprocess.
+
+ text=True alone decodes strictly and UnicodeDecodeError is a ValueError, so it
+ escapes the except below the call and takes the installer down instead of falling
+ back to the on-disk classifier.
+ """
+ emit = (
+ "import sys\n"
+ "sys.stdout.buffer.write(b'chatter \\xff\\xfe\\n')\n"
+ f"print('{stack_mod._TORCH_PROBE_MARKER}' + '|'.join(('2.9.1+cu128', '', '12.8')))\n"
+ )
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(stack_mod.sys, "executable", sys.executable)
+ mp.setattr(stack_mod, "_TORCH_RUNTIME_PROBE", None)
+ real_run = stack_mod.subprocess.run
+
+ def _run(cmd, **kwargs):
+ return real_run([sys.executable, "-c", emit], **kwargs)
+
+ mp.setattr(stack_mod.subprocess, "run", _run)
+ ran, importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+
+ assert (ran, importable) == (True, True)
+ assert (version, hip, cuda) == ("2.9.1+cu128", "", "12.8")
+
+
+def test_no_unreachable_code_in_the_shared_probe():
+ """The hardening pass replaced the parser in place; the old one must not linger."""
+ body = _fn("_probe_torch_runtime").body
+ returns = [i for i, node in enumerate(body) if isinstance(node, ast.Return)]
+ assert not returns or returns[0] == len(body) - 1, (
+ "statements follow the first top-level return in _probe_torch_runtime, "
+ "so a previous implementation was left behind"
+ )
diff --git a/tests/studio/install/test_torch_probe_memoization.py b/tests/studio/install/test_torch_probe_memoization.py
new file mode 100644
index 00000000000..98a18613635
--- /dev/null
+++ b/tests/studio/install/test_torch_probe_memoization.py
@@ -0,0 +1,218 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The torch classification probe runs once per install run, not once per repair path.
+
+_ensure_cuda_torch / _ensure_xpu_torch / _ensure_rocm_torch / _ensure_cpu_torch all need
+the same few facts about the installed torch, and the installer calls the four of them
+back to back at two separate repair points. Each used to spawn its own `import torch`,
+so a single update paid for up to nine interpreter starts and, on a stalled GPU driver,
+up to nine independent 90s timeouts. These tests pin the shared-probe contract: one
+subprocess per run, invalidated whenever pip changes what is installed.
+"""
+
+import importlib.util
+import os
+import subprocess
+import sys
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"
+_STACK_SPEC = importlib.util.spec_from_file_location("studio_install_python_stack", _STACK_PATH)
+assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None
+stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
+sys.modules[_STACK_SPEC.name] = stack_mod
+_STACK_SPEC.loader.exec_module(stack_mod)
+
+
[email protected](autouse = True)
+def _reset_torch_runtime_probe():
+ stack_mod._invalidate_torch_runtime_probe()
+ yield
+ stack_mod._invalidate_torch_runtime_probe()
+
+
+_MARK = stack_mod._TORCH_PROBE_MARKER
+
+
+def _probe_result(
+ fields = "2.9.1+cu128||12.8",
+ returncode = 0,
+ raw = None,
+):
+ """A probe stdout carrying our marked line, plus whatever chatter is asked for."""
+ return MagicMock(
+ returncode = returncode,
+ stdout = raw if raw is not None else (f"{_MARK}{fields}\n" if fields else ""),
+ )
+
+
+class TestProbeParsing:
+ def test_cuda_build_fields(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result()):
+ ran, importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (ran, importable) == (True, True)
+ assert (version, hip, cuda) == ("2.9.1+cu128", "", "12.8")
+
+ def test_rocm_build_fields(self):
+ out = _probe_result("2.10.0+rocm7.1|7.1.12345|")
+ with patch.object(stack_mod.subprocess, "run", return_value = out):
+ _ran, _importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (version, hip, cuda) == ("2.10.0+rocm7.1", "7.1.12345", "")
+
+ def test_cpu_build_fields(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result("2.9.1||")):
+ _ran, _importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (version, hip, cuda) == ("2.9.1", "", "")
+
+ def test_last_line_wins_over_import_chatter(self):
+ # sitecustomize / import hooks can print before the marker line.
+ out = _probe_result(raw = f"some import warning\n{_MARK}2.9.1+cu128||12.8\n")
+ with patch.object(stack_mod.subprocess, "run", return_value = out):
+ _ran, _importable, version, _hip, cuda = stack_mod._probe_torch_runtime()
+ assert (version, cuda) == ("2.9.1+cu128", "12.8")
+
+ def test_unimportable_torch_is_distinguished_from_a_stalled_probe(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result("", 1)):
+ ran, importable, _version, _hip, _cuda = stack_mod._probe_torch_runtime()
+ # ran=True lets callers force a repair; a stalled probe (ran=False) must not.
+ assert (ran, importable) == (True, False)
+
+ def test_timeout_reports_not_ran(self):
+ boom = subprocess.TimeoutExpired(cmd = "python", timeout = 90)
+ with patch.object(stack_mod.subprocess, "run", side_effect = boom):
+ ran, importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (ran, importable, version, hip, cuda) == (False, False, None, "", "")
+
+ def test_chatter_after_the_marker_does_not_win(self):
+ """An atexit handler, a CUDA teardown notice or a "Segmentation fault" line can
+ arrive AFTER the answer, so "the last non-empty line" is not reliably ours."""
+ out = _probe_result(raw = f"{_MARK}2.9.1+cu128||12.8\ndestroying CUDA context\n")
+ with patch.object(stack_mod.subprocess, "run", return_value = out):
+ _ran, _importable, version, _hip, cuda = stack_mod._probe_torch_runtime()
+ assert (version, cuda) == ("2.9.1+cu128", "12.8")
+
+ def test_no_marked_line_reports_an_unknown_version(self):
+ """Exit 0 with nothing of ours on stdout means we learned nothing. None, not "",
+ because the XPU and CPU pins act on an empty version and must not act on this."""
+ out = _probe_result(raw = "only chatter, no answer\n")
+ with patch.object(stack_mod.subprocess, "run", return_value = out):
+ ran, importable, version, _hip, _cuda = stack_mod._probe_torch_runtime()
+ assert (ran, importable, version) == (True, True, None)
+
+ def test_an_empty_version_is_reported_as_empty_not_unknown(self):
+ """A torch whose __version__ is empty IS broken, and an XPU pin repairs it.
+ Collapsing that into the unknown case silently skips the repair."""
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result("||")):
+ _ran, _importable, version, _hip, _cuda = stack_mod._probe_torch_runtime()
+ assert version == ""
+
+ def test_a_torch_without_a_version_module_still_classifies(self, tmp_path):
+ """torch.version is not guaranteed to exist. Reaching through it unguarded raises
+ inside the child, which reads as "torch cannot import" and force-reinstalls a
+ working venv. Runs the real subprocess against a real package on PYTHONPATH,
+ since a mock cannot show which attribute the child touched."""
+ pkg = tmp_path / "torch"
+ pkg.mkdir()
+ (pkg / "__init__.py").write_text("__version__ = '1.13.1'\n", encoding = "utf-8")
+ with patch.dict(os.environ, {"PYTHONPATH": str(tmp_path)}):
+ ran, importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (ran, importable, version) == (True, True, "1.13.1")
+ assert (hip, cuda) == ("", "")
+
+ def test_oserror_reports_not_ran(self):
+ with patch.object(stack_mod.subprocess, "run", side_effect = OSError("no exe")):
+ ran, _importable, _version, _hip, _cuda = stack_mod._probe_torch_runtime()
+ assert ran is False
+
+ def test_undecodable_import_chatter_does_not_escape(self):
+ """The probes this replaced all decoded with errors="replace".
+
+ text=True on its own decodes strictly, and UnicodeDecodeError is a ValueError, so
+ one undecodable byte from torch's import chatter would sail past the except above
+ and take the whole installer down rather than falling back to the on-disk
+ classifier. Runs the real subprocess: a mock cannot show which decoder was used.
+ """
+ emit = (
+ "import sys; sys.stdout.buffer.write("
+ r"b'noise \xff\xfe\n' + " + repr(_MARK) + r".encode() + b'2.9.1+cu128||12.8\n')"
+ )
+ real_run = subprocess.run # bound before the patch, or the stand-in calls itself
+
+ def _emit(_cmd, **kwargs):
+ return real_run([sys.executable, "-c", emit], **kwargs)
+
+ with (
+ patch.object(stack_mod, "_windows_hidden_subprocess_kwargs", lambda: {}),
+ patch.object(stack_mod.subprocess, "run", _emit),
+ ):
+ ran, importable, version, hip, cuda = stack_mod._probe_torch_runtime()
+ assert (ran, importable) == (True, True)
+ assert (version, hip, cuda) == ("2.9.1+cu128", "", "12.8")
+
+
+class TestMemoization:
+ def test_repeated_calls_spawn_one_interpreter(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result()) as mock_run:
+ for _ in range(5):
+ stack_mod._probe_torch_runtime()
+ assert mock_run.call_count == 1
+
+ def test_a_stalled_probe_is_not_retried(self):
+ # The whole point: nine 90s waits become one.
+ boom = subprocess.TimeoutExpired(cmd = "python", timeout = 90)
+ with patch.object(stack_mod.subprocess, "run", side_effect = boom) as mock_run:
+ for _ in range(5):
+ stack_mod._probe_torch_runtime()
+ assert mock_run.call_count == 1
+
+ def test_pip_install_invalidates_the_cache(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result()):
+ first = stack_mod._probe_torch_runtime()
+ assert first[2] == "2.9.1+cu128"
+
+ # A repair path reinstalls torch; the next classification must see the new build.
+ with (
+ patch.object(stack_mod, "USE_UV", False),
+ patch.object(stack_mod, "CONSTRAINTS", Path("/nonexistent/constraints.txt")),
+ patch.object(
+ stack_mod.subprocess, "run", return_value = MagicMock(returncode = 0, stdout = b"")
+ ),
+ ):
+ stack_mod.pip_install("torch repair", "torch")
+
+ out = _probe_result("2.10.0+rocm7.1|7.1.12345|")
+ with patch.object(stack_mod.subprocess, "run", return_value = out) as mock_run:
+ second = stack_mod._probe_torch_runtime()
+ assert mock_run.call_count == 1
+ assert second[2] == "2.10.0+rocm7.1"
+
+ def test_explicit_invalidation_forces_a_reprobe(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result()) as mock_run:
+ stack_mod._probe_torch_runtime()
+ stack_mod._invalidate_torch_runtime_probe()
+ stack_mod._probe_torch_runtime()
+ assert mock_run.call_count == 2
+
+
+class TestConsumersShareTheProbe:
+ def test_probe_installed_torch_version_uses_the_shared_result(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result()) as mock_run:
+ assert stack_mod._probe_installed_torch_version() == "2.9.1+cu128"
+ # Second consumer, same run: no new interpreter.
+ assert stack_mod._probe_installed_torch_version() == "2.9.1+cu128"
+ assert mock_run.call_count == 1
+
+ def test_probe_installed_torch_version_is_none_when_unimportable(self):
+ with patch.object(stack_mod.subprocess, "run", return_value = _probe_result("", 1)):
+ assert stack_mod._probe_installed_torch_version() is None
+
+ def test_probe_installed_torch_version_is_none_when_stalled(self):
+ boom = subprocess.TimeoutExpired(cmd = "python", timeout = 90)
+ with patch.object(stack_mod.subprocess, "run", side_effect = boom):
+ assert stack_mod._probe_installed_torch_version() is None
diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.py
index d2b680ed4c0..f184597568f 100644
--- a/tests/studio/test_xpu_triton_swap.py
+++ b/tests/studio/test_xpu_triton_swap.py
@@ -442,20 +442,21 @@ class TestADeadDriverIsNotAFlavourMismatch:
assert mod.__dict__["_xpu_wheel_supported_on_disk"]() is supported
def test_the_disk_check_and_the_probe_agree_on_the_bounds(self):
- # Two copies of the range in different languages; a drifted floor installs an
+ # Two copies of the range in different places; a drifted floor installs an
# environment that raises at import.
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) <= _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):
# Asserted on the source because _ensure_xpu_torch sits above the extracted slice: the
- # early return must come BEFORE probe is set to None, or the repair runs anyway.
+ # early return must come BEFORE the repair reason is set, or the repair runs anyway.
src = STACK.read_text(encoding = "utf-8")
start = src.index("def _ensure_xpu_torch() -> None:")
body = src[start : src.index("def _installed_torch_version_label", start)]
guard = body.index("_xpu_wheel_supported_on_disk()")
- assert guard < body.index("probe = None"), "the guard runs after the repair is armed"
+ 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"
@@ -535,16 +536,28 @@ class TestCpuRepairSeesAnXpuWheel:
hip = "",
):
src = STACK.read_text(encoding = "utf-8")
- # The probe body is a concatenation of string literals inside the subprocess call.
start = src.index("def _ensure_cpu_torch() -> None:")
seg = src[start : src.index("\n\ndef ", start)]
- line = next(l for l in seg.splitlines() if l.strip().startswith('"gpu = '))
- expr = line.strip().removeprefix('"gpu = ').removesuffix('; "')
+ # Read the predicate from the module source, so an edit to it is what this test
+ # sees rather than a copy that can drift.
+ 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
+ # Re-wrapped in parentheses: the predicate spans several indented lines.
+ expr = "(" + seg[begin:end] + ")"
import re as _re
return (
"gpu"
- if eval(expr, {"re": _re, "hip": hip, "cuda": cuda, "ver": ver.lower()})
+ if eval(expr, {"re": _re, "_hip": hip, "_cuda": cuda, "_ver": ver.lower()})
else "cpu"
)
@@ -607,12 +620,14 @@ class TestCpuPinSurvivesAWedgedImport:
src = STACK.read_text(encoding = "utf-8")
start = src.index("def _ensure_cpu_torch() -> None:")
body = src[start : src.index("\n\ndef ", start)]
- exc = body.index("except (OSError, subprocess.TimeoutExpired):")
- guard = body.index("_is_gpu_torch_label(_installed_torch_label_on_disk())", exc)
- # ...and the repair below must accept the probe-less path, or the fall-through
- # dereferences None instead of reinstalling.
- assert "probe = None" in body[guard : guard + 300]
- assert "if probe is None or probe.returncode != 0:" in body
+ stalled = body.index("if not _ran:")
+ guard = body.index("_is_gpu_torch_label(_installed_torch_label_on_disk())", stalled)
+ # A merely slow CPU-only host returns; a GPU label on disk falls through...
+ assert "return" in body[guard : guard + 200]
+ # ...and the repair below must accept the probe-less path, or the one host that
+ # needs the pin enforced is the one host that 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.