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: keep a Windows update from leaving a CPU-only PyTorch (#9857)

Daniel Hand5b153c2f8ec
diff --git a/studio/install_manifest.py b/studio/install_manifest.py
index 269b67386cf..2bb57253569 100644
--- a/studio/install_manifest.py
+++ b/studio/install_manifest.py
@@ -274,6 +274,7 @@ def write_manifest(
steps_total: int = 0,
package_name: str = "unsloth",
no_torch: Optional[bool] = None,
+ expected_torch_tag: Optional[str] = None,
) -> Optional[Path]:
"""Record a completed install. Never raises: no manifest reads as incomplete,
which is the safe answer."""
@@ -301,6 +302,11 @@ def write_manifest(
# exports nothing and would otherwise reinstall torch into a GGUF-only venv.
if no_torch is not None:
payload["no_torch"] = bool(no_torch)
+ # The FLAVOR, never the index URL it came from: a pinned index can carry a token in
+ # its userinfo, query or fragment, and this file lives in the venv and is read back
+ # by verify-install, desktop-capabilities and the setup fast path.
+ if expected_torch_tag:
+ payload["expected_torch_tag"] = str(expected_torch_tag).strip().lower()
path = manifest_path(root)
try:
tmp = path.with_suffix(".json.tmp")
@@ -374,6 +380,29 @@ def recorded_no_torch(root: Optional[Path] = None) -> Optional[bool]:
return None
+def recorded_torch_flavor(root: Optional[Path] = None) -> Optional[str]:
+ """The torch flavor this venv was installed with, or None when unknown.
+
+ None means nothing recorded it: no manifest, or one written before the key
+ existed. Callers must treat None as "unknown" and fall back to their own
+ detection, never as "cpu" -- claiming a flavor nobody selected would let a
+ repair reinstall over a deliberate build.
+
+ There is no marker companion here (unlike no_torch): the manifest is dropped
+ before every dependency pass, so this answers only for the PREVIOUS install,
+ which is exactly the question a repair asks. A run whose own setup script
+ exported the flavor never reaches this.
+ """
+ manifest = read_manifest(root)
+ if manifest is None:
+ return None
+ value = manifest.get("expected_torch_tag")
+ if not isinstance(value, str):
+ return None
+ value = value.strip().lower()
+ return value or None
+
+
def _parse_requirement_line(line: str) -> Optional[Tuple[str, str, str]]:
"""(distribution name, marker, specifier) for a requirement, or None.
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 596d87502b1..36e4c168640 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -266,6 +266,14 @@ _CUDA_TORCH_PKG_SPEC: tuple[str, str, str] = (
# mismatched.
_CPU_TORCH_PKG_SPEC: tuple[str, str, str] = _CUDA_TORCH_PKG_SPEC
+# Byte-identical to the non-XPU arm of install.ps1's $_fixSpecs, NOT _CUDA_TORCH_PKG_SPEC:
+# `studio update` must repair to the same wheels install.ps1 does.
+_TORCH_FLAVOR_REPAIR_PKG_SPEC: tuple[str, str, str] = (
+ "torch>=2.4,<2.11.0",
+ "torchvision>=0.19,<0.26.0",
+ "torchaudio>=2.4,<2.11.0",
+)
+
# torchao's cpp extensions are pinned to ONE torch release AND CUDA major. A torch
# mismatch just skips the cpp kernels (slow Python fallback); a CUDA mismatch fails
# to import ("libcudart.so.12: cannot open shared object file"). The torch pin is a
@@ -2622,9 +2630,13 @@ def _ensure_xpu_triton() -> None:
Lives here, not in install.sh, because install.sh runs setup.sh which runs this file: one
copy covers the fresh install AND `unsloth studio update`, which never touches install.sh.
- Windows is excluded -- studio/setup.ps1 owns the same swap there.
+
+ On Windows setup.ps1 performs the same swap after this script exits, so its handover
+ variable means "someone else will"; a direct run has no such postlude.
"""
- if NO_TORCH or IS_MACOS or IS_WINDOWS:
+ if NO_TORCH or IS_MACOS:
+ return
+ if IS_WINDOWS and os.environ.get("UNSLOTH_EXPECTED_TORCH_TAG", "").strip():
return
pin = _explicit_xpu_torch_index_url()
if pin is None:
@@ -2856,6 +2868,473 @@ def _ensure_cpu_torch() -> None:
)
+def _torch_flavor_tag(version: str) -> str:
+ """Classify a torch.__version__ into the installers' flavor vocabulary.
+
+ +cuNNN -> "cuNNN", +rocm -> "rocm", +xpu -> "xpu", +cpu or untagged -> "cpu".
+ MUST match install.ps1's ConvertTo-TorchFlavorTag and setup.ps1's stale-venv probe,
+ because the tag this returns is compared against one those produced. "" only for an
+ empty version, which means the classification failed rather than "cpu".
+
+ Untagged reads as "cpu" deliberately: PyPI forbids the local +cuNNN label, so an
+ untagged wheel is the PyPI build, which on Windows is CPU-only. A repair off that
+ verdict is self-resolving -- the replacement carries a +cuNNN tag and matches on the
+ next pass -- and _torch_build_is_gpu, not this function, decides whether to FAIL.
+ """
+ value = str(version).strip().lower()
+ if not value:
+ return ""
+ match = re.search(r"\+(cu\d+)", value)
+ if match:
+ return match.group(1)
+ if "+rocm" in value:
+ return "rocm"
+ if "+xpu" in value:
+ return "xpu"
+ return "cpu"
+
+
+def _torch_build_is_gpu() -> bool:
+ """Whether the installed torch can use a GPU at all, on the evidence available.
+
+ Weaker and more forgiving than _torch_flavor_tag, and used only for the FAIL verdict
+ in _ensure_expected_torch_flavor: a wrong family is worth a reinstall, but only a
+ build with no GPU support whatsoever is worth failing the update over.
+
+ torch.version.cuda / .hip count alongside the local label, so an untagged wheel that
+ does carry a CUDA runtime is not called CPU-only. An answer that never arrived (a
+ wedged driver hanging `import torch` -- the host these repairs exist for) falls back
+ to the on-disk label and, failing that, reads as a GPU build: ambiguity must not fail
+ an update by itself.
+ """
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if _ran and _importable and _version:
+ return _is_gpu_torch_label(_version.lower()) or bool(_hip) or bool(_cuda)
+ label = _installed_torch_label_on_disk()
+ return (not label) or _is_gpu_torch_label(label)
+
+
+def _expected_torch_flavor_tag() -> str:
+ """The torch flavor this venv is SUPPOSED to hold, or "" when nothing can say.
+
+ Resolution order, most authoritative first:
+ 1. UNSLOTH_EXPECTED_TORCH_TAG -- the setup script's own answer, exported by
+ setup.ps1 immediately before it hands over, so it describes the index the torch
+ install arm actually used (pin, preserved venv, GPU probe and all).
+ 2. An explicit index pin, when its family is one this vocabulary can name. The
+ manifest records what a PREVIOUS run installed; a pin is the instruction for
+ THIS one, so a freshly selected family has to outrank a stale record. Resolving
+ the manifest first let a cu128 pin lose to a cu124 manifest, and
+ _expected_torch_index_url then rejected the cu128 pin as a family mismatch and
+ repaired from the PUBLIC cu124 index -- undoing both the family and the source
+ the user had just chosen.
+ 3. The flavor the last completed install recorded in the manifest. Read at import
+ (_RECORDED_TORCH_TAG), because install_python_stack() drops the manifest before
+ the dependency pass.
+ 4. A live probe, for a run nothing set up: `python install_python_stack.py` by hand.
+ Only an NVIDIA host, or an explicit pin, can expect a GPU build -- otherwise
+ return "" rather than invent an expectation from an absent GPU.
+ """
+ env = os.environ.get("UNSLOTH_EXPECTED_TORCH_TAG", "").strip().lower()
+ if env:
+ return env
+ pin = _explicit_torch_index_url()
+ if pin is not None:
+ leaf = _torch_index_leaf(pin)
+ # "rocm" names every AMD leaf (rocm6.4, gfx1151); an unreadable one falls through.
+ if _is_pip_rocm_family_leaf(leaf):
+ return "rocm"
+ if _is_cuda_family_leaf(leaf) or leaf in ("xpu", "cpu"):
+ return leaf
+ if _RECORDED_TORCH_TAG:
+ return _RECORDED_TORCH_TAG
+ # An absent NVIDIA GPU with no pin means no CUDA expectation exists to enforce.
+ if _explicit_torch_index_url() is None and not _has_usable_nvidia_gpu():
+ return ""
+ return _torch_index_leaf(_detect_cuda_torch_index_url())
+
+
+def _expected_torch_flavor_is_explicit() -> bool:
+ """Whether the expectation came from someone SAYING so, rather than from a probe.
+
+ True for the setup script's handover, an explicit index pin, and the flavor the last
+ completed install recorded: the first three steps of _expected_torch_flavor_tag.
+ False when only the live hardware probe can answer, which is the one case a
+ visibility mask has any business overruling.
+ """
+ if os.environ.get("UNSLOTH_EXPECTED_TORCH_TAG", "").strip():
+ return True
+ if _explicit_torch_index_url() is not None:
+ return True
+ return bool(_RECORDED_TORCH_TAG)
+
+
+def _expected_torch_index_url(tag: str) -> str:
+ """The wheel index to repair `tag` from.
+
+ Prefers the exact URL the setup script installed from (UNSLOTH_TORCH_INSTALL_INDEX_URL)
+ and then the explicit pin, because an authenticated mirror can only be repaired from
+ the credentialed URL -- neither is reconstructible from a family leaf. Both are only
+ used when their leaf IS this tag: setup.ps1 sends the /cpu index alongside a "rocm"
+ tag on the AMD Windows path, and repairing a cu* mismatch from that URL would install
+ the very CPU wheel this exists to remove. Otherwise rebuild it the way setup.ps1 does
+ when nothing is pinned: <mirror>/<tag>.
+ """
+ url = os.environ.get("UNSLOTH_TORCH_INSTALL_INDEX_URL", "").strip()
+ if url:
+ url = _trim_index_path_slashes(url)
+ if _torch_index_leaf(url) == tag:
+ return url
+ pin = _explicit_torch_index_url()
+ if pin is not None and _torch_index_leaf(pin) == tag:
+ return pin
+ return f"{_PYTORCH_WHL_BASE}/{tag}"
+
+
+def _explicit_cpu_torch_index_pin() -> bool:
+ """Whether this run was pinned to a CPU wheel index, by URL or by family.
+
+ Only a pin counts. setup.ps1's published tag also reads "cpu" for a host whose
+ nvidia-smi probe simply returned nothing, and treating that as an instruction would
+ let a wedged driver downgrade a healthy CUDA venv.
+ """
+ pin = _explicit_torch_index_url()
+ return pin is not None and _torch_index_leaf(pin) == "cpu"
+
+
+# Not a flavor tag, so no `== expected` comparison can accept it, and truthy, so no
+# `if not _now` ambiguity branch can swallow it.
+_TORCH_TAG_UNIMPORTABLE = "unimportable"
+
+
+def _installed_flavor_tag_now(expected: str = "") -> str:
+ """The venv's CURRENT flavor tag, re-probed, or "" when nothing could be read.
+
+ ``expected`` only matters for "cpu": _torch_flavor_tag reads every untagged version
+ as cpu, so a private index serving an untagged CUDA or ROCm wheel would satisfy a
+ CPU expectation here exactly as it did in the pre-repair comparison. The same
+ runtime markers settle it, and the two comparisons have to agree or the repair is
+ accepted on a rule the check that triggered it rejected.
+
+ _torch_build_is_gpu answers a weaker question ("can this torch use a GPU at all")
+ and is deliberately family-blind, so it cannot tell a repair that installed the
+ requested family from one that left a different GPU wheel in place. "" is returned
+ for an unreadable venv rather than "cpu", so ambiguity stays distinguishable from
+ a positive CPU reading and never fails an update on its own.
+ """
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if _ran and _importable and _version:
+ tag = _torch_flavor_tag(_version)
+ if expected == "cpu" and tag == "cpu" and (_hip or _cuda):
+ return "rocm" if _hip else "cuda"
+ return tag
+ if _ran:
+ # The probe ANSWERED, and the answer was that this torch does not import. That is
+ # not the ambiguity the disk fallback exists for: version.py would report the
+ # requested +cu*/+xpu tag from a half-written or DLL-less wheel, the caller would
+ # read tag == expected, and the update would write a completion manifest over a
+ # torch nothing can import. A torch that failed to import BEFORE the repair never
+ # reaches here -- the pre-repair chain returns early on it.
+ return _TORCH_TAG_UNIMPORTABLE
+ label = _installed_torch_label_on_disk()
+ return _torch_flavor_tag(label) if label else ""
+
+
+def _warn_repair_left_torch_unimportable(expected: str) -> bool:
+ """Report a repair whose wheel cannot be imported, and fail. Always returns False.
+
+ Distinct from _warn_wrong_flavor and _warn_still_cpu: the family on disk may well be
+ the requested one, so naming it would send the reader after a wheel that is already
+ correct. What is wrong is that it does not load.
+ """
+ _safe_print("")
+ _safe_print(
+ f" [WARN] PyTorch was reinstalled for {expected} but the result cannot be imported."
+ )
+ _safe_print(" [WARN] The venv is not usable in this state.")
+ _safe_print(" [WARN] Re-run this installer, or reinstall the build for your GPU manually.")
+ _safe_print(" [WARN] irm https://unsloth.ai/install.ps1 | iex")
+ return False
+
+
+def _warn_wrong_flavor(expected: str, installed: str) -> bool:
+ """Report a repair that installed the wrong family, and fail. Always returns False.
+
+ Distinct from _warn_still_cpu because "PyTorch is CPU-only" would be false here and
+ would send the reader after the wrong problem: the venv holds a GPU build, just not
+ the one this host asked for.
+ """
+ _safe_print("")
+ _safe_print(
+ f" [WARN] PyTorch is a {installed} build but {expected} was expected for this machine."
+ )
+ _safe_print(" [WARN] The repair did not install the requested build.")
+ _safe_print(" [WARN] Re-run this installer, or reinstall the build for your GPU manually.")
+ _safe_print(" [WARN] irm https://unsloth.ai/install.ps1 | iex")
+ return False
+
+
+def _warn_still_cpu(expected: str) -> bool:
+ """Report a repair that did not take, and fail the install. Always returns False.
+
+ install.ps1 warns here and exits 0. Failing instead is the entire point: a CPU-only
+ torch on a host that expects a GPU build is precisely the state an update used to
+ report as "dependencies up to date" while the app ran everything on CPU.
+ """
+ _safe_print("")
+ _safe_print(
+ f" [WARN] PyTorch is CPU-only but a {expected} GPU build was expected for this machine."
+ )
+ _safe_print(" [WARN] Training and GPU inference will run on CPU until this is fixed.")
+ _safe_print(
+ " [WARN] Re-run this installer, or reinstall the GPU build manually for your GPU."
+ )
+ _safe_print(" [WARN] irm https://unsloth.ai/install.ps1 | iex")
+ return False
+
+
+def _uninstall_distribution(name: str) -> bool:
+ """Remove one distribution from the venv this script targets. True iff it is gone.
+
+ Same shape as the flash-attn removal below: --python sys.executable so a uv that
+ also needs --system cannot remove from the system Python instead, and a pip
+ fallback for the same interpreter. Output is swallowed; the caller reports.
+ """
+ if USE_UV and shutil.which("uv"):
+ cmd = ["uv", "pip", "uninstall"]
+ if UV_NEEDS_SYSTEM:
+ cmd.append("--system")
+ cmd.extend(["--python", sys.executable, name])
+ else:
+ cmd = [sys.executable, "-m", "pip", "uninstall", "-y", name]
+ removed = subprocess.run(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL)
+ return removed.returncode == 0
+
+
+def _resident_xformers_build_torch() -> "str | None":
+ """The torch build the installed xFormers extension was compiled against.
+
+ Read from ``xformers/cpp_lib.json``, the same file install.ps1's resident probe
+ reads. None when xFormers is absent or carries no build metadata. Never raises, and
+ never imports xformers -- a mismatched _C.pyd logs its own warning on import, which
+ would land in the middle of the installer's output.
+ """
+ try:
+ spec = importlib.util.find_spec("xformers")
+ except Exception:
+ return None
+ locations = list(getattr(spec, "submodule_search_locations", None) or []) if spec else []
+ if not locations:
+ return None
+ try:
+ with open(os.path.join(locations[0], "cpp_lib.json"), encoding = "utf-8") as fh:
+ recorded = json.load(fh).get("version", {}).get("torch")
+ except (OSError, ValueError, AttributeError):
+ return None
+ return recorded.strip() if isinstance(recorded, str) and recorded.strip() else None
+
+
+def _resync_torch_coupled_packages(label_before: str) -> bool:
+ """Re-settle the packages whose compiled extensions are tied to the torch build.
+
+ Returns False when this pass left the venv in a state the caller must re-verify.
+
+ torchao's cpp extensions are tied to the torch release AND its CUDA major, both of
+ which _select_torchao_spec branches on; xFormers is tied to the exact (torch, CUDA)
+ pair, and beside a pair it was not built for its ops vanish behind a log line rather
+ than an error. --no-deps is the whole safety of the torchao call: torchao depends on
+ torch, so resolving dependencies would pull PyPI's CPU wheel back in. Never fatal --
+ both are secondary to the flavor repair that has just succeeded.
+ """
+ _label_after = str(_probe_installed_torch_version() or "")
+ if not _label_after or _label_after == label_before:
+ return True
+ _touched_torch = False
+ # Release OR CUDA major: cu124 to cu130 at one release still changes the build.
+ _release_moved = _label_after.split("+", 1)[0] != str(label_before).split("+", 1)[0]
+ _cuda_moved = _cuda_major_from_torch_version(_label_after) != (
+ _cuda_major_from_torch_version(str(label_before))
+ )
+ if _release_moved or _cuda_moved:
+ try:
+ _spec = _select_torchao_spec(_label_after)
+ if not _exact_distribution_spec_is_installed(_spec):
+ _note(f"torch {_label_after} after repair -- reinstalling {_spec}")
+ _touched_torch = True
+ if not pip_install_try(
+ "Re-matching torchao to the repaired torch",
+ "--force-reinstall",
+ "--no-deps",
+ "--no-cache-dir",
+ _spec,
+ ):
+ # Across a CUDA-major move the resident build is not merely slower:
+ # _select_torchao_spec exists because a torchao compiled for CUDA 12
+ # cannot load its cpp under cu130. Remove it, the way the xFormers arm
+ # below removes a build made for a torch that is gone, rather than
+ # completing the update with a package that may fail on import. A
+ # release-only move keeps the old warning: that one really is the
+ # slow path.
+ if _cuda_moved and _uninstall_distribution("torchao"):
+ _note(
+ f"removed the torchao built for a different CUDA major; "
+ f"install {_spec} by hand to restore its kernels"
+ )
+ else:
+ _safe_print(
+ f" [WARN] could not install {_spec} for the repaired torch; the "
+ f"torchao kernels will fall back to the slow path."
+ )
+ except Exception as e:
+ _safe_print(f" [WARN] could not re-match torchao after the repair: {e}")
+ try:
+ _built_for = _resident_xformers_build_torch()
+ if _built_for and _built_for != _label_after:
+ _note(
+ f"xFormers was built for torch {_built_for}, which is no longer "
+ f"installed -- removing it so attention falls back to torch SDPA"
+ )
+ if not _uninstall_distribution("xformers"):
+ _safe_print(
+ " [WARN] could not remove the mismatched xFormers; its compiled "
+ "operations will stay unavailable until it is uninstalled by hand."
+ )
+ except Exception as e:
+ _safe_print(f" [WARN] could not re-check xFormers after the repair: {e}")
+ return not _touched_torch
+
+
+def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
+ """Enforce that the venv still holds the torch flavor the install selected.
+
+ `unsloth studio update` runs setup.ps1 and this script, never install.ps1, which held
+ the only flavor repair; the dependency steps above resolve torch from PyPI, whose
+ Windows wheel is 2.11.0+cpu. Returns False when the flavor is wrong and could not be
+ repaired, which fails the install: that state used to be reported as success.
+
+ ROCm is delegated to _ensure_rocm_torch -- AMD's Windows wheels live on a
+ per-architecture repo.amd.com index a generic "rocm" tag cannot reconstruct.
+ """
+ if NO_TORCH:
+ return True
+ # rocm/xpu/cpu fall THROUGH: an explicit GPU pin sets _TORCH_BACKEND, and rejecting it
+ # here would skip the invariant on the hosts that asked for that family.
+ if _TORCH_BACKEND not in ("", "cuda", "rocm", "xpu", "cpu"):
+ return True
+ if expected is None:
+ expected = _expected_torch_flavor_tag()
+ # The PIN, not the handover: setup.ps1 also publishes "cpu" when its nvidia-smi probe
+ # comes back empty, and that host must not be downgraded.
+ _cpu_pinned = expected == "cpu" and _explicit_cpu_torch_index_pin()
+ if not (_is_cuda_family_leaf(expected) or expected in ("xpu", "rocm") or _cpu_pinned):
+ return True
+ if _TORCH_BACKEND in ("rocm", "xpu", "cpu") and _TORCH_BACKEND != expected:
+ return True
+ # A pin whose leaf names no flavor was applied verbatim at install time, so acting on
+ # a manifest that predates it overrides an administrator's mirror. Compared rather than
+ # vetoed: the helper's known set predates XPU.
+ _unknown_pin = _explicit_unknown_family_torch_index_url()
+ if _unknown_pin is not None and _torch_index_leaf(_unknown_pin) != expected:
+ return True
+ # CUDA only, and only for an expectation INFERRED from hardware: an emptied mask is a
+ # reason not to conclude cu124 from a probe, not to ignore a stated one.
+ if _is_cuda_family_leaf(expected) and not _expected_torch_flavor_is_explicit():
+ _cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
+ if _cvd is not None and _cvd.strip() in ("", "-1"):
+ return True
+
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ if _ran and _importable and _version:
+ installed_version = _version
+ elif not _ran:
+ # A wedged driver hangs `import torch`; version.py names the wheel without one.
+ installed_version = _installed_torch_label_on_disk()
+ else:
+ # Missing or unimportable is the base install's job, a louder failure than this.
+ return True
+ if not installed_version:
+ return True
+
+ installed = _torch_flavor_tag(installed_version)
+ # _torch_flavor_tag reads untagged as "cpu", so a private index's untagged CUDA build
+ # compares equal under a /cpu pin.
+ if expected == "cpu" and installed == "cpu" and (_hip or _cuda):
+ installed = "rocm" if _hip else "cuda"
+ if installed == expected:
+ return True
+
+ # install.ps1's line, word for word, so a support log from either path reads the same.
+ _safe_print(
+ f" PyTorch flavor mismatch (installed {installed}, need {expected}) -- "
+ f"reinstalling correct build..."
+ )
+ if expected == "rocm":
+ # AMD's Windows wheels live on a per-architecture repo.amd.com index no "rocm" tag
+ # can name, and the handed-over URL still points at /cpu there.
+ _ensure_rocm_torch()
+ # The FAMILY: a transient repo.amd.com failure is non-fatal in there, and the cu124
+ # wheel it leaves passes _torch_build_is_gpu.
+ _now = _installed_flavor_tag_now(expected)
+ if _now == _TORCH_TAG_UNIMPORTABLE:
+ return _warn_repair_left_torch_unimportable(expected)
+ if _now == expected:
+ return True
+ if not _now:
+ # Ambiguity must not fail an update by itself.
+ return True if _torch_build_is_gpu() else _warn_still_cpu(expected)
+ if not _torch_build_is_gpu():
+ return _warn_still_cpu(expected)
+ return _warn_wrong_flavor(expected, _now)
+
+ index_url = _expected_torch_index_url(expected)
+ # XPU floor is 2.6, not 2.4: unsloth/models/_utils.py raises at import below it.
+ _torch_pkg, _vision_pkg, _audio_pkg = (
+ _XPU_TORCH_PKG_SPEC if expected == "xpu" else _TORCH_FLAVOR_REPAIR_PKG_SPEC
+ )
+ # No win_arm64 torchaudio wheel exists on any index ($WinArm64NoAudio in setup.ps1).
+ _trio = [_torch_pkg, _vision_pkg, _audio_pkg]
+ if _is_windows_arm64():
+ _trio = [_torch_pkg, _vision_pkg]
+ _label_before = str(installed_version)
+ # --force-reinstall, not install.ps1's uv-only --reinstall-package: pip_install falls
+ # back to pip, which has no word for it. constrain=False: constraints.txt resolves
+ # against PyPI's torch, which is what put this venv here.
+ pip_install(
+ "PyTorch flavor repair",
+ "--force-reinstall",
+ "--no-cache-dir",
+ *_trio,
+ "--index-url",
+ index_url,
+ constrain = False,
+ )
+
+ # The family: a mirror can answer /cu128 with a cached cu124 wheel, and
+ # _torch_build_is_gpu is family-blind.
+ _now = _installed_flavor_tag_now(expected)
+ if _now == _TORCH_TAG_UNIMPORTABLE:
+ return _warn_repair_left_torch_unimportable(expected)
+ if _now == expected:
+ if _resync_torch_coupled_packages(_label_before):
+ return True
+ # The resync installs --no-deps, but this function's verification is behind us.
+ _after = _installed_flavor_tag_now(expected)
+ if _after == _TORCH_TAG_UNIMPORTABLE:
+ return _warn_repair_left_torch_unimportable(expected)
+ if _after in (expected, ""):
+ return True
+ _safe_print(" [WARN] the post-repair package resync changed the torch build.")
+ return _warn_wrong_flavor(expected, _after)
+ if not _now:
+ # Ambiguity must not fail an update by itself.
+ if expected == "cpu":
+ return True
+ return True if _torch_build_is_gpu() else _warn_still_cpu(expected)
+ if expected != "cpu" and not _torch_build_is_gpu():
+ return _warn_still_cpu(expected)
+ return _warn_wrong_flavor(expected, _now)
+
+
def _amd_torch_needs_dependency_pass() -> bool:
"""Return True when setup must run the dependency pass to repair non-ROCm torch.
@@ -2991,6 +3470,11 @@ def _ensure_rocm_torch() -> None:
_torch_pkg, _vision_pkg, _audio_pkg = _WINDOWS_ROCM_TORCH_PKG_SPECS.get(
gfx_arch, ("torch", "torchvision", "torchaudio")
)
+ # Same win_arm64 exception setup.ps1 applies: no torchaudio wheel exists
+ # there, so asking for one makes the trio unresolvable.
+ _rocm_trio = [_torch_pkg, _vision_pkg, _audio_pkg]
+ if _is_windows_arm64():
+ _rocm_trio = [_torch_pkg, _vision_pkg]
# Nonfatal: a transient AMD-index failure must not abort the install.
# --force-reinstall resolves before uninstalling, so a failed index keeps the
# existing build intact; let the user retry.
@@ -2999,9 +3483,7 @@ def _ensure_rocm_torch() -> None:
"--force-reinstall",
"--index-url",
index_url,
- _torch_pkg,
- _vision_pkg,
- _audio_pkg,
+ *_rocm_trio,
constrain = False,
):
_safe_print(
@@ -3434,6 +3916,9 @@ def _infer_no_torch() -> bool:
NO_TORCH = _infer_no_torch()
+# Read at import: install_python_stack() drops the manifest before its dependency pass.
+_RECORDED_TORCH_TAG = install_manifest.recorded_torch_flavor()
+
# UNSLOTH_TORCH_BACKEND is set by install.sh after get_torch_index_url() ("cuda", "rocm",
# "cpu"; empty = standalone `studio update`, where we re-detect).
_TORCH_BACKEND: str = os.environ.get("UNSLOTH_TORCH_BACKEND", "").lower()
@@ -5274,6 +5759,8 @@ def install_python_stack() -> int:
base_total += 1 # ROCm torch check (step 2b), non-macOS
if not IS_WINDOWS:
base_total += 2 # flash-attn + torch final repair (step 13), Linux
+ else:
+ base_total += 1 # torch flavor invariant (step 13w), Windows
if IS_MAC_ARM and not skip_base:
base_total += 1 # MLX stack, same gate as the step itself
base_requirements = _shared_base_requirements() if skip_base else None
@@ -5685,6 +6172,7 @@ def install_python_stack() -> int:
)
# 13. Final torch repair. Steps above can pull CUDA torch from PyPI, so repair last.
+ torch_flavor_tag = ""
if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:
_progress(_torch_step_label("final"))
_ensure_cuda_torch()
@@ -5695,6 +6183,17 @@ def install_python_stack() -> int:
# CPU pin over an XPU venv would leave XPU triton under a CPU torch.
_ensure_xpu_triton()
+ # 13w. Windows torch flavor invariant, separate from step 13's Linux-shaped repair set
+ # but in the same position: last, after the with-deps steps re-resolved torch.
+ if IS_WINDOWS and not NO_TORCH:
+ _progress(_torch_step_label("flavor"))
+ torch_flavor_tag = _expected_torch_flavor_tag()
+ if not _ensure_expected_torch_flavor(torch_flavor_tag):
+ return 1
+ # A direct run has no setup.ps1 postlude to swap triton back. After the invariant,
+ # because the swap keys off the installed +xpu label.
+ _ensure_xpu_triton()
+
# 14. Final check (silent; third-party conflicts are expected)
subprocess.run(
[sys.executable, "-m", "pip", "check"],
@@ -5724,6 +6223,8 @@ def install_python_stack() -> int:
steps_total = _TOTAL,
package_name = package_name,
no_torch = NO_TORCH,
+ # A platform that never resolves a flavor carries the old record forward.
+ expected_torch_tag = torch_flavor_tag or _RECORDED_TORCH_TAG,
)
is None
):
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index aac61eb140a..39ef29ca706 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1052,7 +1052,9 @@ function Get-RocmPinStaleTags {
# that answer. Mirrors install.ps1's copy.
function Invoke-BoundedPythonProbe {
param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
- $result = [pscustomobject]@{ Ok = $false; Output = ""; Error = "" }
+ # TimedOut separates "never answered" from "answered with a failure": both leave Ok
+ # false, only the second says anything about the installation.
+ $result = [pscustomobject]@{ Ok = $false; Output = ""; Error = ""; TimedOut = $false }
if (-not $PythonExe -or -not $Code) { return $result }
try {
$psi = New-Object System.Diagnostics.ProcessStartInfo
@@ -1070,6 +1072,7 @@ function Invoke-BoundedPythonProbe {
# Synthesised, not read back: waiting on the reader tasks of a wedged child would
# reintroduce the hang this helper exists to bound.
$result.Error = "python did not answer within $TimeoutSec seconds"
+ $result.TimedOut = $true
return $result
}
$result.Output = $outTask.GetAwaiter().GetResult()
@@ -1231,6 +1234,30 @@ function Test-VenvTorchIsRocm {
} catch { return $false }
}
+# The NVIDIA counterpart of the XPU and ROCm on-disk rescues: a wedged display driver hangs or
+# faults `import torch`, and the chain then fell through to a rebuild with a null tag, deleting a
+# healthy CUDA venv with no rollback copy. Returns the FAMILY, since the stale check needs it.
+function Get-VenvTorchCudaTag {
+ param([string]$VenvPath)
+ if (-not $VenvPath) { return $null }
+ try {
+ $verPy = Join-Path $VenvPath "Lib\site-packages\torch\version.py"
+ if (-not (Test-Path -LiteralPath $verPy)) { return $null }
+ $line = (Get-Content -LiteralPath $verPy -TotalCount 40 -ErrorAction Stop |
+ Where-Object { $_ -match "__version__\s*=\s*'[^']*\+(cu[0-9]+)" } |
+ Select-Object -First 1)
+ if (-not $line) { return $null }
+ $m = [regex]::Match($line, "__version__\s*=\s*'[^']*\+(cu[0-9]+)")
+ if ($m.Success) { return $m.Groups[1].Value.ToLowerInvariant() }
+ return $null
+ } catch { return $null }
+}
+
+function Test-VenvTorchIsCuda {
+ param([string]$VenvPath)
+ return [bool](Get-VenvTorchCudaTag -VenvPath $VenvPath)
+}
+
# Same free disk read, plus the supported range: unsloth/models/_utils.py raises at import for an
# XPU device on torch < 2.6, so flavour alone would call a 2.5+xpu venv fine; 2.11 is the trio's
# ceiling. Flavour and range ONLY -- whether the runtime reaches the GPU is a driver question.
@@ -4048,6 +4075,7 @@ $installedTorchTag = $null
# installer-managed repair below raises it, yet only the block a fresh install never enters
# assigns it.
$script:PinChangedForceReinstall = $false
+$script:TorchImportDefinitivelyFailed = $false
if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode) {
$VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"
$installedTorchTag = $null
@@ -4098,6 +4126,18 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$installedTorchTag = "rocm"
substep "PyTorch did not respond but this venv holds a ROCm build -- keeping it." "Yellow"
substep "If training fails, reboot and update the AMD Adrenalin / HIP SDK driver." "Yellow"
+ } elseif (Test-VenvTorchIsCuda -VenvPath $VenvDir) {
+ # Without this the chain fell through with a NULL tag, so the no-wipe escape
+ # below saw no cu* wheel to preserve. Keep the FAMILY, not a generic "cuda".
+ $installedTorchTag = Get-VenvTorchCudaTag -VenvPath $VenvDir
+ substep "PyTorch did not respond but this venv holds a $installedTorchTag build -- keeping it." "Yellow"
+ substep "If training fails, reboot and update the NVIDIA driver." "Yellow"
+ # A half-written torch also leaves a +cu* version.py behind, and the matched
+ # install below would write a completion manifest over it. Force the reinstall.
+ if ($_verProbe -and -not $_verProbe.TimedOut) {
+ $script:TorchImportDefinitivelyFailed = $true
+ substep "PyTorch failed to import rather than timing out -- reinstalling the same family in place." "Yellow"
+ }
} else {
$shouldRebuild = $true
}
@@ -4288,6 +4328,23 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$shouldRebuild = $false
}
+ # A cu* venv is never wiped by a DIRECT update just because nvidia-smi did not answer:
+ # every way that bounded probe comes back empty on a working NVIDIA host collapses
+ # $expectedTorchTag to "cpu", no escape above catches it, and the wipe has no rollback
+ # copy. Narrow on purpose: unpinned only, cu* installed only, and only when the collapse
+ # was for want of an NVIDIA answer. The -and order also keeps the reads legal under
+ # Set-StrictMode, since both are assigned inside `if (-not $shouldRebuild)`.
+ if ($shouldRebuild -and -not $InstallerManagedSetup -and
+ $installedTorchTag -and (Test-CudaFamilyLeaf $installedTorchTag) -and
+ -not $_pinnedIdx -and -not $HasNvidiaSmi -and $expectedTorchTag -eq "cpu") {
+ substep "nvidia-smi did not answer, but this venv holds a $installedTorchTag build -- keeping it." "Yellow"
+ substep "If training runs on CPU, re-run install.ps1: irm https://unsloth.ai/install.ps1 | iex" "Yellow"
+ $shouldRebuild = $false
+ # Keeping the wheel is half the job: the index selection below rescans, sees no
+ # NVIDIA either, and would route the install to the /cpu arm.
+ $script:PreservedInstallerTorchTag = $installedTorchTag
+ }
+
if ($shouldRebuild) {
substep "Stale venv detected ($reason) -- rebuilding..." "Yellow"
# why: mirror install.ps1 env-mode guard so an update against a custom
@@ -4945,7 +5002,13 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
# A torch-index pin change repairs in place: force the dependency pass so the torch install
# below force-reinstalls from the new pin (else the fast path keeps the old wheel).
-if ($script:PinChangedForceReinstall) { $SkipPythonDeps = $false }
+# A torch that will not import needs the same pass for the same reason, and it is the only
+# thing that can act on it: every --force-reinstall that reads the flag lives INSIDE this
+# block, so on a current core package with a valid manifest the fast path announced a
+# reinstall it then skipped, and setup exited successfully over an unusable wheel.
+if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {
+ $SkipPythonDeps = $false
+}
if (-not $SkipPythonDeps) {
@@ -5195,6 +5258,10 @@ if ($XpuIndexUrl) {
if ($installedTorchTag -ne "xpu") { $xpuForce = @("--force-reinstall") }
# A changed pin repairs in place, so the existing +xpu wheel must be replaced too.
if ($script:PinChangedForceReinstall) { $xpuForce = @("--force-reinstall") }
+ # And a +xpu wheel that no longer imports: its on-disk tag is still "xpu", so the check
+ # above sees no flavour change and the range is satisfied, which leaves the resolver
+ # holding the broken wheel and the run writing a completion manifest over it.
+ if ($script:TorchImportDefinitivelyFailed) { $xpuForce = @("--force-reinstall") }
if ($script:UnslothVerbose) {
Fast-Install @_xpuTrio @xpuForce --index-url $XpuIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host
$torchInstallExit = $LASTEXITCODE
@@ -5232,6 +5299,9 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# --force-reinstall on a pin change: a stale +cu / +rocm wheel still satisfies the CPU
# torch>= range, so uv would keep it and only swap companions.
if ($script:PinChangedForceReinstall) { $cpuForce = @("--force-reinstall") }
+ # Same for a wheel that no longer imports. Nothing else here distinguishes it: the tag is
+ # rescued from disk and still reads "cpu", so the range is satisfied and it is kept.
+ if ($script:TorchImportDefinitivelyFailed) { $cpuForce = @("--force-reinstall") }
# A PINNED cpu index installs the bounded trio (parity with _CPU_TORCH_PKG_SPEC): the /cpu
# index serves newer torch, and _ensure_cpu_torch keeps any CPU build, so a bare trio could
# land an unsupported version. Unpinned CPU hosts keep the bare trio (pre-pin behavior).
@@ -5269,7 +5339,9 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# requirement (PEP 440 ignores the +cuXXX tag), so without it a changed CUDA pin (cu126
# -> cu128) never applies.
$cudaForce = @()
- if ($script:PinChangedForceReinstall) { $cudaForce = @("--force-reinstall") }
+ if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {
+ $cudaForce = @("--force-reinstall")
+ }
# An unknown-leaf custom pin (/simple, /current) routes here with $CuTag as that leaf. Bound
# the trio like the fresh custom-pin paths so a mirror can't pull an ABI-newer companion
# against the capped torch. Known cu* leaves keep bare specs.
@@ -5329,6 +5401,33 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# Duplicate metadata repair is the one pass that DOES reinstall unsloth under
# SKIP_STUDIO_BASE, so the CLI wraps this script in its launcher transaction.
+# ── Publish the torch flavor this run settled on ──
+# so install_python_stack.py can enforce it: its dependency steps resolve torch from PyPI, whose
+# Windows wheel is 2.11.0+cpu, and only install.ps1 -- never on the updater's path -- repaired
+# that. Vocabulary is Get-InstalledTorchTag's; an unknown leaf publishes nothing.
+if (-not $NoTorchMode) {
+ $_expectedLeaf = Get-TorchIndexLeaf $TorchInstallIndexUrl
+ # $ROCmIndexUrl first: on the AMD path $TorchInstallIndexUrl still points at /cpu.
+ $_expectedTag = if ($ROCmIndexUrl) { "rocm" }
+ elseif (Test-CudaFamilyLeaf $_expectedLeaf) { $_expectedLeaf }
+ elseif ($_expectedLeaf -eq "cpu" -or $_expectedLeaf -eq "xpu") { $_expectedLeaf }
+ elseif (Test-PipRocmFamilyLeaf $_expectedLeaf) { "rocm" }
+ else { $null }
+ # Remove-Item, NOT `= ""`: PowerShell 7.5 took .NET 9's change and KEEPS a name
+ # assigned an empty string. Deleting also stops a value inherited from the caller's
+ # shell surviving a run that decided it cannot name this host's flavor.
+ if ($_expectedTag) {
+ $env:UNSLOTH_EXPECTED_TORCH_TAG = $_expectedTag
+ } else {
+ Remove-Item Env:\UNSLOTH_EXPECTED_TORCH_TAG -ErrorAction SilentlyContinue
+ }
+ if ($TorchInstallIndexUrl) {
+ $env:UNSLOTH_TORCH_INSTALL_INDEX_URL = $TorchInstallIndexUrl
+ } else {
+ Remove-Item Env:\UNSLOTH_TORCH_INSTALL_INDEX_URL -ErrorAction SilentlyContinue
+ }
+}
+
# Ordered heavy dependency installation -- shared cross-platform script
substep "running ordered dependency installation..."
python "$PSScriptRoot\install_python_stack.py"
diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.py
index 4b04f27a2f6..bad566bd30f 100644
--- a/tests/python/test_install_python_stack.py
+++ b/tests/python/test_install_python_stack.py
@@ -2371,3 +2371,94 @@ class TestRecordlessDistributionRecovery:
assert excinfo.value.code == 1
assert len(attempts) == 1, "a failure with nothing to clear must not be retried"
+
+
+class TestExpectedTorchFlavorResolution:
+ """_expected_torch_flavor_tag / _expected_torch_index_url: the two pure inputs to the
+ Windows flavor invariant. The invariant itself is covered in
+ tests/studio/install/test_cuda_repair.py; these pin the resolution ORDER, which is what
+ decides whether a repair fires against the right index or not at all."""
+
+ _KEYS = (
+ "UNSLOTH_EXPECTED_TORCH_TAG",
+ "UNSLOTH_TORCH_INSTALL_INDEX_URL",
+ "UNSLOTH_TORCH_INDEX_URL",
+ "UNSLOTH_TORCH_INDEX_FAMILY",
+ )
+
+ @contextlib.contextmanager
+ def _env(self, **values):
+ """Set the named vars and REMOVE every other one this resolution reads, so an
+ ambient pin on the developer's box cannot change the answer."""
+ with mock.patch.dict(os.environ, {k: v for k, v in values.items() if v is not None}):
+ for key in self._KEYS:
+ if values.get(key) is None:
+ os.environ.pop(key, None)
+ yield
+
+ def test_the_handover_tag_wins(self):
+ with self._env(UNSLOTH_EXPECTED_TORCH_TAG = "cu124"):
+ with mock.patch.object(ips, "_RECORDED_TORCH_TAG", "cu128"):
+ assert ips._expected_torch_flavor_tag() == "cu124"
+
+ def test_the_handover_tag_is_normalised(self):
+ with self._env(UNSLOTH_EXPECTED_TORCH_TAG = " CU128 "):
+ assert ips._expected_torch_flavor_tag() == "cu128"
+
+ def test_the_manifest_answers_next(self):
+ with self._env():
+ with mock.patch.object(ips, "_RECORDED_TORCH_TAG", "cu128"):
+ assert ips._expected_torch_flavor_tag() == "cu128"
+
+ def test_a_gpuless_host_with_nothing_recorded_says_nothing(self):
+ # Inventing a CUDA expectation from an absent GPU would reinstall CUDA torch
+ # onto a CPU box on every update.
+ with self._env():
+ with (
+ mock.patch.object(ips, "_RECORDED_TORCH_TAG", None),
+ mock.patch.object(ips, "_has_usable_nvidia_gpu", return_value = False),
+ ):
+ assert ips._expected_torch_flavor_tag() == ""
+
+ def test_a_pin_answers_without_probing_the_gpu(self):
+ with self._env(UNSLOTH_TORCH_INDEX_FAMILY = "cu126"):
+ with (
+ mock.patch.object(ips, "_RECORDED_TORCH_TAG", None),
+ mock.patch.object(ips, "_has_usable_nvidia_gpu") as probe,
+ ):
+ assert ips._expected_torch_flavor_tag() == "cu126"
+ probe.assert_not_called()
+
+ def test_a_cpu_pin_resolves_to_cpu_not_to_the_host_gpu(self):
+ with self._env(UNSLOTH_TORCH_INDEX_FAMILY = "cpu"):
+ with mock.patch.object(ips, "_RECORDED_TORCH_TAG", None):
+ assert ips._expected_torch_flavor_tag() == "cpu"
+
+ def test_the_index_url_is_reused_only_for_its_own_family(self):
+ # setup.ps1 hands over the /cpu index alongside a "rocm" tag on AMD Windows, so
+ # repairing from it would install the very CPU wheel the repair exists to remove.
+ with self._env(UNSLOTH_TORCH_INSTALL_INDEX_URL = "https://mirror.local/whl/cu124/"):
+ assert ips._expected_torch_index_url("cu124") == "https://mirror.local/whl/cu124"
+ with self._env(UNSLOTH_TORCH_INSTALL_INDEX_URL = "https://download.pytorch.org/whl/cpu"):
+ assert ips._expected_torch_index_url("cu124") == f"{ips._PYTORCH_WHL_BASE}/cu124"
+
+ def test_a_credentialed_index_survives_intact(self):
+ # Why the URL is forwarded rather than rebuilt: userinfo and a token query are
+ # not reconstructible from a family leaf.
+ url = "https://user:[email protected]/whl/cu128?token=abc"
+ with self._env(UNSLOTH_TORCH_INSTALL_INDEX_URL = url):
+ assert ips._expected_torch_index_url("cu128") == url
+
+ def test_the_pin_supplies_the_index_when_the_setup_script_did_not(self):
+ with self._env(UNSLOTH_TORCH_INDEX_URL = "https://mirror.local/whl/cu126"):
+ assert ips._expected_torch_index_url("cu126") == "https://mirror.local/whl/cu126"
+
+ def test_the_default_index_is_the_pytorch_mirror(self):
+ with self._env():
+ assert ips._expected_torch_index_url("cu124") == f"{ips._PYTORCH_WHL_BASE}/cu124"
+
+ def test_no_index_url_is_ever_persisted_by_the_manifest_write(self):
+ # The manifest lives in the venv, so a token in a pinned URL must not reach it.
+ source = inspect.getsource(ips.install_python_stack)
+ assert "expected_torch_tag = torch_flavor_tag or _RECORDED_TORCH_TAG," in source
+ assert "torch_index_url" not in source
diff --git a/tests/studio/install/test_cuda_repair.py b/tests/studio/install/test_cuda_repair.py
index da6b46a4a59..b237dca729a 100644
--- a/tests/studio/install/test_cuda_repair.py
+++ b/tests/studio/install/test_cuda_repair.py
@@ -1,10 +1,18 @@
"""_ensure_cuda_torch reinstalls CUDA torch when an NVIDIA-host venv carries a ROCm
build (the pre-fix KFD gpu_id false positive), but leaves healthy CUDA / CPU / ROCm /
-macOS / Windows untouched. Fully mocked -- no GPU required."""
+macOS / Windows untouched. Fully mocked -- no GPU required.
+
+Also covers _ensure_expected_torch_flavor, the Windows counterpart: _ensure_cuda_torch
+returns early on Windows because setup.ps1 owns torch there, which left the update path
+with no flavor invariant at all. See the bottom of this file."""
import importlib.util
+import inspect
+import re
+import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
@@ -21,6 +29,8 @@ stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
sys.modules[_STACK_SPEC.name] = stack_mod
_STACK_SPEC.loader.exec_module(stack_mod)
+_SETUP_SRC = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+
# 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
@@ -700,5 +710,1311 @@ class TestPreTuringWheelFamily:
assert _sms("7.0\n", returncode = 1) is None
+# The updater runs setup.ps1 -> install_python_stack.py, never install.ps1, which held the
+# only flavor repair.
+
+_ensure_expected_torch_flavor = stack_mod._ensure_expected_torch_flavor
+_UNSET = object()
+
+
+def _flavor_probe_stdout(version):
+ """The shared probe's marked line for a literal torch.__version__.
+
+ torch.version.cuda / .hip follow the local label, because a real wheel sets them
+ together and _torch_build_is_gpu reads all three.
+ """
+ match = re.search(r"\+(cu\d+)", version)
+ cuda = _dotted_cuda(match.group(1)) if match else ""
+ hip = "6.4" if "+rocm" in version else ""
+ return _MARK + f"{version}|{hip}|{cuda}\n"
+
+
+def _run_flavor_invariant(
+ *,
+ installed = "2.11.0+cpu",
+ repaired = None,
+ expected_env = "cu124",
+ recorded = None,
+ install_index_url = None,
+ backend = "",
+ no_torch = False,
+ nvidia = True,
+ cuda_version = "12.4",
+ torch_rc = 0,
+ probe_timeout = False,
+ disk_label = _UNSET,
+ cvd = None,
+ index_family = None,
+ index_url = None,
+ win_arm64 = False,
+ probe_cuda = None,
+ probe_hip = None,
+):
+ """Invoke _ensure_expected_torch_flavor against a fully mocked venv.
+
+ `installed` is torch.__version__ before the pass. `repaired` is what the mocked
+ pip_install leaves behind: None means the reinstall changed nothing, which is the
+ state that must FAIL the update rather than report success.
+
+ `expected_env` sets UNSLOTH_EXPECTED_TORCH_TAG (setup.ps1's handover), `recorded` the
+ flavor read out of the previous manifest, and leaving both None forces the live probe.
+ `disk_label` overrides the on-disk torch/version.py label the wedged-probe path reads.
+
+ Returns (ok, pip_mock).
+ """
+ state = {"version": installed}
+
+ env = {}
+ if expected_env is not None:
+ env["UNSLOTH_EXPECTED_TORCH_TAG"] = expected_env
+ if install_index_url is not None:
+ env["UNSLOTH_TORCH_INSTALL_INDEX_URL"] = install_index_url
+ if cvd is not None:
+ env["CUDA_VISIBLE_DEVICES"] = cvd
+ if index_family is not None:
+ env["UNSLOTH_TORCH_INDEX_FAMILY"] = index_family
+ if index_url is not None:
+ env["UNSLOTH_TORCH_INDEX_URL"] = index_url
+
+ def _run(cmd, *args, **kwargs):
+ result = MagicMock()
+ exe = str(cmd[0]) if cmd else ""
+ if exe == sys.executable:
+ if probe_timeout:
+ raise subprocess.TimeoutExpired(cmd, 90)
+ result.returncode = torch_rc
+ out = _flavor_probe_stdout(state["version"])
+ if (probe_cuda is not None or probe_hip is not None) and state["version"] == installed:
+ out = _MARK + (f"{state['version']}|{probe_hip or ''}|{probe_cuda or ''}\n")
+ else:
+ result.returncode = 0
+ if len(cmd) > 1 and str(cmd[1]) == "--query-gpu=compute_cap":
+ out = "8.6\n"
+ else:
+ out = f"CUDA Version: {cuda_version}\n" if cuda_version else "No devices\n"
+ result.stdout = out if kwargs.get("text") else out.encode()
+ return result
+
+ def _pip(*args, **kwargs):
+ # The real pip_install invalidates the memoized classification.
+ stack_mod._invalidate_torch_runtime_probe()
+ if repaired is not None:
+ state["version"] = repaired
+
+ def _rocm(*args, **kwargs):
+ # The ROCm arm delegates, so the stand-in must move the venv too.
+ _pip()
+
+ def _which(name, *a, **k):
+ return "/usr/bin/nvidia-smi" if name == "nvidia-smi" else None
+
+ stack_mod._invalidate_torch_runtime_probe()
+
+ with (
+ patch.object(stack_mod, "_TORCH_BACKEND", backend),
+ patch.object(stack_mod, "NO_TORCH", no_torch),
+ patch.object(stack_mod, "_RECORDED_TORCH_TAG", recorded),
+ patch.object(stack_mod.platform, "machine", return_value = "AMD64"),
+ patch.object(stack_mod, "_is_windows_arm64", return_value = win_arm64),
+ patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = nvidia),
+ patch.object(stack_mod.shutil, "which", side_effect = _which),
+ patch.object(stack_mod.os.path, "isfile", return_value = True),
+ patch.object(
+ stack_mod,
+ "_installed_torch_label_on_disk",
+ side_effect = (
+ (lambda: state["version"].lower()) if disk_label is _UNSET else (lambda: disk_label)
+ ),
+ ),
+ patch.object(stack_mod, "pip_install", side_effect = _pip) as mock_pip,
+ patch.object(stack_mod, "_ensure_rocm_torch", side_effect = _rocm) as mock_rocm,
+ patch.object(stack_mod.subprocess, "run", side_effect = _run),
+ patch.dict(stack_mod.os.environ, env, clear = False),
+ ):
+ for name, value in (
+ ("UNSLOTH_EXPECTED_TORCH_TAG", expected_env),
+ ("UNSLOTH_TORCH_INSTALL_INDEX_URL", install_index_url),
+ ("CUDA_VISIBLE_DEVICES", cvd),
+ ("UNSLOTH_TORCH_INDEX_FAMILY", index_family),
+ ("UNSLOTH_TORCH_INDEX_URL", index_url),
+ ):
+ if value is None:
+ stack_mod.os.environ.pop(name, None)
+ ok = _ensure_expected_torch_flavor()
+ mock_pip.rocm_repair = mock_rocm
+ return ok, mock_pip
+
+
+class TestExpectedTorchFlavorRepairs:
+ def test_cpu_torch_under_a_cu124_expectation_is_repaired(self):
+ ok, mock_pip = _run_flavor_invariant(repaired = "2.10.0+cu124")
+ assert ok is True
+ assert mock_pip.call_count == 1
+ call_args = [str(a) for a in mock_pip.call_args.args]
+ assert "--force-reinstall" in call_args
+ assert "--no-cache-dir" in call_args
+ assert _index_url(mock_pip).endswith("/cu124")
+ assert mock_pip.call_args.kwargs["constrain"] is False
+
+ def test_the_repair_uses_install_ps1s_bounded_trio(self):
+ _ok, mock_pip = _run_flavor_invariant(repaired = "2.10.0+cu124")
+ call_args = [str(a) for a in mock_pip.call_args.args]
+ # NOT the <2.12 Linux range: an unbounded trio resolves back to the 2.11 wheel.
+ for spec in ("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0", "torchaudio>=2.4,<2.11.0"):
+ assert spec in call_args
+
+ def test_untagged_pypi_wheel_is_repaired(self):
+ # PyPI forbids +cuNNN, so untagged is its CPU-only Windows build.
+ ok, mock_pip = _run_flavor_invariant(installed = "2.11.0", repaired = "2.10.0+cu124")
+ assert ok is True
+ assert mock_pip.call_count == 1
+
+ def test_wrong_cuda_family_is_repaired_to_the_expected_one(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.9.1+cu118",
+ expected_env = "cu128",
+ repaired = "2.10.0+cu128",
+ )
+ assert ok is True
+ assert _index_url(mock_pip).endswith("/cu128")
+
+ def test_a_wedged_probe_classifies_from_disk_and_still_repairs(self):
+ # A stalled driver hangs `import torch`; version.py on disk still names the wheel.
+ ok, mock_pip = _run_flavor_invariant(
+ probe_timeout = True,
+ repaired = "2.10.0+cu124",
+ )
+ assert ok is True
+ assert mock_pip.call_count == 1
+
+
+class TestExpectedTorchFlavorFailsTheUpdate:
+ def test_a_repair_that_leaves_cpu_torch_fails(self):
+ ok, mock_pip = _run_flavor_invariant(repaired = None)
+ assert ok is False
+ assert mock_pip.call_count == 1
+
+ def test_the_failure_verdict_reads_torch_version_cuda_not_just_the_tag(self):
+ # Untagged but carrying a CUDA runtime is a GPU build: reinstall, do not fail.
+ ok, _mock_pip = _run_flavor_invariant(installed = "2.11.0", repaired = "2.11.0+cu124")
+ assert ok is True
+
+ def test_a_rocm_build_left_behind_is_not_called_cpu_only(self, capsys):
+ ok, _mock_pip = _run_flavor_invariant(repaired = "2.9.1+rocm6.4")
+ assert ok is False
+ out = capsys.readouterr().out
+ assert "rocm build but cu124 was expected" in out
+ assert "CPU-only" not in out
+
+
+class TestExpectedTorchFlavorSkips:
+ def test_expected_cpu_is_a_no_op(self):
+ ok, mock_pip = _run_flavor_invariant(expected_env = "cpu")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ @pytest.mark.parametrize("backend", ["cpu", "auto"])
+ def test_a_non_gpu_backend_is_a_no_op(self, backend):
+ """Decided without resolving the expectation: cpu and unrecognised values are
+ deliberate whatever the handover said, and this exit costs no GPU probe."""
+ ok, mock_pip = _run_flavor_invariant(backend = backend)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ @pytest.mark.parametrize("backend", ["rocm", "xpu"])
+ def test_a_gpu_backend_that_disagrees_with_the_handover_is_a_no_op(self, backend):
+ """An explicit ROCm/XPU pin against a cu124 handover. The pin is the newer and
+ more specific instruction; the handover only describes what the install arm
+ above it happened to do, so the pin wins and this pass stays out of it."""
+ ok, mock_pip = _run_flavor_invariant(backend = backend, expected_env = "cu124")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_backend_cuda_still_runs(self):
+ ok, mock_pip = _run_flavor_invariant(backend = "cuda", repaired = "2.10.0+cu124")
+ assert ok is True
+ assert mock_pip.call_count == 1
+
+ def test_no_torch_mode_is_a_no_op(self):
+ ok, mock_pip = _run_flavor_invariant(no_torch = True)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_matching_flavor_is_a_no_op(self):
+ ok, mock_pip = _run_flavor_invariant(installed = "2.9.1+cu124")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ @pytest.mark.parametrize("cvd", ["", "-1", " ", " -1 "])
+ def test_hidden_cuda_devices_is_a_no_op_for_an_inferred_expectation(self, cvd):
+ ok, mock_pip = _run_flavor_invariant(cvd = cvd, expected_env = None)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ @pytest.mark.parametrize("cvd", ["", "-1", " ", " -1 "])
+ def test_a_mask_does_not_veto_an_explicit_expectation(self, cvd):
+ # A reason not to CONCLUDE cu124 from a probe, not to ignore a stated one.
+ for kwargs in (
+ {"expected_env": "cu124"},
+ {"expected_env": None, "index_family": "cu124"},
+ {"expected_env": None, "recorded": "cu124"},
+ ):
+ ok, mock_pip = _run_flavor_invariant(cvd = cvd, repaired = "2.10.0+cu124", **kwargs)
+ assert ok is True, kwargs
+ assert mock_pip.call_count == 1, kwargs
+
+ def test_an_explicit_visible_device_still_repairs(self):
+ ok, mock_pip = _run_flavor_invariant(cvd = "0", repaired = "2.10.0+cu124")
+ assert ok is True
+ assert mock_pip.call_count == 1
+
+ @pytest.mark.parametrize("tag", ["current", "custom", "simple", "cu"])
+ def test_an_unenforceable_expectation_is_a_no_op(self, tag):
+ # "xpu" and "rocm" are NOT here: both are published and both are enforced.
+ ok, mock_pip = _run_flavor_invariant(expected_env = tag)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_an_empty_handover_tag_falls_through_rather_than_deciding(self):
+ # PowerShell 7.5+ keeps an entry assigned "", which must read as "nobody said".
+ ok, mock_pip = _run_flavor_invariant(
+ expected_env = "",
+ recorded = "cu128",
+ repaired = "2.10.0+cu128",
+ )
+ assert ok is True
+ assert _index_url(mock_pip).endswith("/cu128")
+
+ def test_missing_or_unimportable_torch_is_a_no_op(self):
+ # Reinstalling over an unimportable torch turns a driver fault into a wheel one.
+ ok, mock_pip = _run_flavor_invariant(torch_rc = 1)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_an_unreadable_venv_is_a_no_op(self):
+ ok, mock_pip = _run_flavor_invariant(probe_timeout = True, disk_label = "")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+
+class TestExpectedTorchFlavorResolution:
+ def test_the_manifest_answers_when_the_environment_is_silent(self):
+ ok, mock_pip = _run_flavor_invariant(
+ expected_env = None,
+ recorded = "cu128",
+ repaired = "2.10.0+cu128",
+ )
+ assert ok is True
+ assert _index_url(mock_pip).endswith("/cu128")
+
+ def test_the_environment_wins_over_the_manifest(self):
+ _ok, mock_pip = _run_flavor_invariant(
+ expected_env = "cu124",
+ recorded = "cu128",
+ repaired = "2.10.0+cu124",
+ )
+ assert _index_url(mock_pip).endswith("/cu124")
+
+ def test_the_live_probe_answers_when_nothing_recorded_it(self):
+ _ok, mock_pip = _run_flavor_invariant(
+ expected_env = None,
+ recorded = None,
+ cuda_version = "12.8",
+ repaired = "2.10.0+cu128",
+ )
+ assert _index_url(mock_pip).endswith("/cu128")
+
+ def test_the_live_probe_declines_without_an_nvidia_gpu(self):
+ # Inventing an expectation here reinstalls CUDA torch onto a CPU-only box.
+ ok, mock_pip = _run_flavor_invariant(expected_env = None, recorded = None, nvidia = False)
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_cpu_pin_beats_the_live_probe(self):
+ ok, mock_pip = _run_flavor_invariant(expected_env = None, recorded = None, index_family = "cpu")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_the_setup_scripts_index_url_is_used_when_its_leaf_matches(self):
+ # Credentials are not reconstructible from a family leaf.
+ _ok, mock_pip = _run_flavor_invariant(
+ install_index_url = "https://mirror.local/whl/cu124?token=secret",
+ repaired = "2.10.0+cu124",
+ )
+ assert _index_url(mock_pip) == "https://mirror.local/whl/cu124?token=secret"
+
+ def test_an_index_url_naming_another_family_is_ignored(self):
+ # setup.ps1 hands over /cpu alongside a "rocm" tag on the AMD Windows path.
+ _ok, mock_pip = _run_flavor_invariant(
+ install_index_url = "https://download.pytorch.org/whl/cpu",
+ repaired = "2.10.0+cu124",
+ )
+ assert _index_url(mock_pip) == f"{stack_mod._PYTORCH_WHL_BASE}/cu124"
+
+ def test_a_matching_family_pin_supplies_the_index(self):
+ _ok, mock_pip = _run_flavor_invariant(
+ index_url = "https://mirror.local/whl/cu124",
+ repaired = "2.10.0+cu124",
+ )
+ assert _index_url(mock_pip) == "https://mirror.local/whl/cu124"
+
+
+class TestTorchFlavorTagVocabulary:
+ """_torch_flavor_tag is compared against tags install.ps1 and setup.ps1 produced, so
+ it has to classify identically."""
+
+ @pytest.mark.parametrize(
+ "version,tag",
+ [
+ ("2.9.1+cu124", "cu124"),
+ ("2.11.0+cu130", "cu130"),
+ ("2.9.1+rocm6.4", "rocm"),
+ ("2.11.0+rocm7.2.1", "rocm"),
+ ("2.9.1+xpu", "xpu"),
+ ("2.11.0+cpu", "cpu"),
+ ("2.11.0", "cpu"),
+ ("2.9.1+CU124", "cu124"),
+ ("", ""),
+ ],
+ )
+ def test_tags(self, version, tag):
+ assert stack_mod._torch_flavor_tag(version) == tag
+
+
+class TestUnknownFamilyPinIsNotOverridden:
+ """An explicit index pin whose leaf names no flavor is applied verbatim at install
+ time, so this pass has no standing to second-guess it. The only expectation it could
+ act on comes from the manifest, i.e. from whatever was installed BEFORE the pin was
+ set, and repairing off that stale tag reinstalls from the public pytorch index --
+ overriding a deliberate package source, and failing outright on an air-gapped host.
+ _ensure_cuda_torch already declines on the same test."""
+
+ def test_a_simple_mirror_pin_suppresses_the_manifest_fallback(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = None,
+ recorded = "cu124",
+ index_url = "https://mirror.corp.example/simple",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_readable_cuda_pin_still_repairs(self):
+ """Narrowness: the escape must not disable a normal cu* mirror."""
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.6.0+cu124",
+ expected_env = None,
+ recorded = "cu124",
+ index_url = "https://mirror.corp.example/whl/cu124",
+ )
+ assert ok is True
+ args = mock_pip.call_args[0]
+ assert "https://mirror.corp.example/whl/cu124" in args
+
+
+class TestExpectedXpuFlavorIsEnforced:
+ """setup.ps1 publishes "xpu" for an Arc host and installs the XPU trio before handing
+ over, so declining to act on that expectation would leave the invariant carrying an
+ answer it refuses to use. The exposure is identical to the CUDA one: the dependency
+ steps re-resolve torch from PyPI, and _ensure_xpu_torch cannot clean up afterwards
+ because step 13's whole repair set is gated off Windows."""
+
+ def test_an_xpu_venv_that_lost_torch_to_pypi_is_repaired(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu", repaired = "2.9.1+xpu", expected_env = "xpu"
+ )
+ assert ok is True
+ args = mock_pip.call_args[0]
+ # XPU floor is 2.6, not the CUDA trio's 2.4: unsloth raises at import below it.
+ assert "torch>=2.6,<2.11.0" in args
+ assert "torchvision>=0.21,<0.26.0" in args
+ assert any("xpu" in str(a) for a in args)
+
+ def test_a_healthy_xpu_venv_is_untouched(self):
+ ok, mock_pip = _run_flavor_invariant(installed = "2.9.1+xpu", expected_env = "xpu")
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_an_xpu_repair_that_does_not_take_fails_the_update(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu", repaired = None, expected_env = "xpu"
+ )
+ assert ok is False
+ mock_pip.assert_called_once()
+
+ def test_a_cuda_mask_does_not_cancel_an_xpu_repair(self):
+ """CUDA_VISIBLE_DEVICES hides an NVIDIA GPU, not an Arc one."""
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.9.1+xpu",
+ expected_env = "xpu",
+ cvd = "",
+ )
+ assert ok is True
+ mock_pip.assert_called_once()
+
+ def test_rocm_is_delegated_rather_than_rebuilt_here(self):
+ """AMD's Windows wheels live on a per-architecture repo.amd.com index that a
+ generic "rocm" tag cannot name, and setup.ps1 hands over an index URL that still
+ points at /cpu on that path. _ensure_rocm_torch already detects the arch, maps
+ it, and honours an explicit pin, so the repair is delegated to it rather than
+ rebuilt from a guessed URL -- but it IS repaired, because it runs at step 2b,
+ before the dependency steps that can put PyPI's CPU wheel here."""
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.11.0+rocm7.2",
+ expected_env = "rocm",
+ )
+ mock_pip.rocm_repair.assert_called_once()
+ # Not called directly: this pass must not invent a repo.amd.com URL of its own.
+ mock_pip.assert_not_called()
+ assert ok is True
+
+ def test_a_healthy_rocm_venv_does_not_call_the_repair(self):
+ ok, mock_pip = _run_flavor_invariant(installed = "2.11.0+rocm7.2", expected_env = "rocm")
+ mock_pip.rocm_repair.assert_not_called()
+ mock_pip.assert_not_called()
+ assert ok is True
+
+ def test_a_rocm_repair_that_does_not_take_fails_the_update(self):
+ """The state that used to be written as a successful CPU-only manifest."""
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu", repaired = None, expected_env = "rocm"
+ )
+ mock_pip.rocm_repair.assert_called_once()
+ mock_pip.assert_not_called()
+ assert ok is False
+
+
+class TestTheDelegatedRocmRepairIsVerifiedByFamily:
+ """_torch_build_is_gpu is family-blind, so it cannot judge a ROCm repair.
+
+ A transient repo.amd.com failure is non-fatal inside _ensure_rocm_torch, and the
+ cu124 wheel it leaves behind passes that check, so the update exited 0 and the
+ manifest recorded "rocm" over an environment that never received it.
+ """
+
+ def test_a_repair_that_left_a_cuda_wheel_now_fails(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0+cu124",
+ repaired = "2.6.0+cu124",
+ expected_env = "rocm",
+ backend = "rocm",
+ )
+ assert ok is False
+ mock_pip.rocm_repair.assert_called_once()
+
+ def test_a_repair_that_took_still_passes(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0+cu124",
+ repaired = "2.11.0+rocm7.2",
+ expected_env = "rocm",
+ backend = "rocm",
+ )
+ assert ok is True
+ mock_pip.rocm_repair.assert_called_once()
+
+ def test_a_repair_that_left_cpu_torch_still_reads_as_cpu(self):
+ ok, _mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.11.0+cpu",
+ expected_env = "rocm",
+ backend = "rocm",
+ )
+ assert ok is False
+
+ def test_an_unreadable_venv_does_not_fail_the_update_on_its_own(self):
+ ok, _mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.11.0+cpu",
+ expected_env = "rocm",
+ backend = "rocm",
+ probe_timeout = True,
+ disk_label = "",
+ )
+ assert ok is True
+
+
+class TestAPinnedCpuIndexIsEnforcedToo:
+ """UV_TORCH_BACKEND is honoured by the unpinned dependency steps.
+
+ A venv deliberately built against /cpu can therefore come out of them holding a GPU
+ wheel, and the update would record expected_torch_tag: cpu over it. Only a PIN
+ counts: setup.ps1 also publishes "cpu" for a host whose nvidia-smi probe returned
+ nothing, and acting on that would push a healthy cu124 venv down to CPU.
+ """
+
+ def test_a_gpu_wheel_under_a_pinned_cpu_index_is_repaired(self):
+ pin = "https://download.pytorch.org/whl/cpu"
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0+cu124",
+ repaired = "2.11.0+cpu",
+ expected_env = "cpu",
+ index_url = pin,
+ backend = "cpu",
+ )
+ assert ok is True
+ assert _index_url(mock_pip) == pin
+ assert "--force-reinstall" in [str(a) for a in mock_pip.call_args.args]
+
+ def test_a_published_cpu_tag_with_no_pin_is_still_left_alone(self):
+ # setup.ps1 publishes "cpu" when nvidia-smi answers nothing; the healthy cu124
+ # venv underneath must not be downgraded.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0+cu124",
+ expected_env = "cpu",
+ nvidia = False,
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_cpu_venv_under_a_cpu_pin_is_a_no_op(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = "cpu",
+ index_url = "https://download.pytorch.org/whl/cpu",
+ backend = "cpu",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_cpu_repair_that_did_not_take_fails(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0+cu124",
+ repaired = "2.6.0+cu124",
+ expected_env = "cpu",
+ backend = "cpu",
+ index_url = "https://download.pytorch.org/whl/cpu",
+ )
+ assert ok is False
+ assert mock_pip.call_count == 1
+
+ def test_a_cpu_backend_under_a_gpu_expectation_is_still_left_alone(self):
+ # A deliberate CPU backend must not be dragged up to cu124.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = "cu124",
+ backend = "cpu",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+
+class TestWindowsOnArmKeepsTheNoTorchaudioException:
+ """No win_arm64 torchaudio wheel is published on any index.
+
+ setup.ps1 drops it from all four of its install trios ($WinArm64NoAudio), so asking
+ for it here would turn a repairable venv into a failed install, and the venv the
+ repair rebuilds could not have been installed in the first place.
+ """
+
+ def test_torchaudio_is_dropped_on_windows_arm64(self):
+ ok, mock_pip = _run_flavor_invariant(repaired = "2.10.0+cu124", win_arm64 = True)
+ assert ok is True
+ args = [str(a) for a in mock_pip.call_args.args]
+ assert not any(a.startswith("torchaudio") for a in args)
+ assert any(a.startswith("torch>=") for a in args)
+ assert any(a.startswith("torchvision") for a in args)
+ assert _index_url(mock_pip).endswith("/cu124")
+
+ def test_the_xpu_trio_drops_it_too(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.9.1+xpu",
+ expected_env = "xpu",
+ win_arm64 = True,
+ )
+ assert ok is True
+ args = [str(a) for a in mock_pip.call_args.args]
+ assert not any(a.startswith("torchaudio") for a in args)
+ assert "torch>=2.6,<2.11.0" in args
+
+ def test_x64_windows_still_installs_all_three(self):
+ _ok, mock_pip = _run_flavor_invariant(repaired = "2.10.0+cu124")
+ args = [str(a) for a in mock_pip.call_args.args]
+ assert any(a.startswith("torchaudio") for a in args)
+
+
+class TestTheRequestedFamilyIsVerifiedAfterEveryRepair:
+ """A GPU build is not the same answer as THE GPU build that was asked for.
+
+ A misconfigured mirror can answer a /cu128 request with a cached cu124, rocm or xpu
+ wheel. _torch_build_is_gpu is deliberately family-blind, so the update exited 0 and
+ the manifest recorded the requested tag over a build that never arrived.
+ """
+
+ @pytest.mark.parametrize("landed", ["2.6.0+cu124", "2.11.0+rocm7.2", "2.9.1+xpu"])
+ def test_a_wheel_from_the_wrong_family_fails(self, landed):
+ ok, _mock_pip = _run_flavor_invariant(
+ expected_env = "cu128",
+ repaired = landed,
+ )
+ assert ok is False
+
+ def test_the_requested_family_passes(self):
+ ok, _mock_pip = _run_flavor_invariant(
+ expected_env = "cu128",
+ repaired = "2.6.0+cu128",
+ )
+ assert ok is True
+
+ def test_an_xpu_repair_is_held_to_the_same_rule(self):
+ ok, _mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = "xpu",
+ repaired = "2.6.0+cu124",
+ )
+ assert ok is False
+
+ def test_an_unreadable_venv_still_passes(self):
+ ok, _mock_pip = _run_flavor_invariant(
+ expected_env = "cu128",
+ repaired = "2.6.0+cu128",
+ probe_timeout = True,
+ disk_label = "",
+ )
+ assert ok is True
+
+ def test_a_still_cpu_venv_keeps_its_own_warning(self, capsys):
+ ok, _mock_pip = _run_flavor_invariant(expected_env = "cu124", repaired = None)
+ assert ok is False
+ assert "CPU-only" in capsys.readouterr().out
+
+
+class TestAnUntaggedGpuWheelIsNotACpuMatch:
+ """_torch_flavor_tag reads every untagged version as "cpu".
+
+ Right for PyPI, wrong for a private index serving an untagged CUDA or ROCm build:
+ under a /cpu pin that wheel compared equal to the expectation, skipped the repair,
+ and was recorded as cpu. The runtime probe already carries the markers that tell
+ them apart.
+ """
+
+ def test_an_untagged_cuda_wheel_under_a_cpu_pin_is_repaired(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0",
+ repaired = "2.11.0+cpu",
+ expected_env = "cpu",
+ backend = "cpu",
+ index_url = "https://download.pytorch.org/whl/cpu",
+ probe_cuda = "12.4",
+ )
+ assert ok is True
+ assert mock_pip.call_count == 1
+
+ def test_a_genuinely_untagged_cpu_wheel_is_still_a_match(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.6.0",
+ expected_env = "cpu",
+ backend = "cpu",
+ index_url = "https://download.pytorch.org/whl/cpu",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+
+class TestAnExplicitPinOutranksTheManifest:
+ """Direct `python install_python_stack.py` on Windows, which the invariant supports.
+
+ The manifest records what a PREVIOUS run installed; a pin is the instruction for
+ THIS one. Resolving the manifest first let a freshly set cu128 pin lose to a stale
+ cu124 record, and _expected_torch_index_url then rejected the cu128 pin as a family
+ mismatch and repaired from the PUBLIC cu124 index -- undoing both the family and the
+ source the user had just chosen.
+ """
+
+ def test_a_new_family_pin_beats_a_stale_manifest(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.10.0+cu124",
+ repaired = "2.10.0+cu128",
+ expected_env = None,
+ recorded = "cu124",
+ index_family = "cu128",
+ )
+ assert ok is True
+ assert "cu128" in _index_url(mock_pip)
+ assert "cu124" not in _index_url(mock_pip)
+ assert "--force-reinstall" in [str(a) for a in mock_pip.call_args.args]
+
+ def test_a_pinned_url_beats_a_stale_manifest_and_is_the_repair_source(self):
+ pin = "https://mirror.corp.example/whl/cu128"
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.10.0+cu124",
+ repaired = "2.10.0+cu128",
+ expected_env = None,
+ recorded = "cu124",
+ index_url = pin,
+ )
+ assert ok is True
+ assert _index_url(mock_pip) == pin
+
+ def test_a_rocm_pin_collapses_to_the_flavor_vocabulary(self):
+ # Every AMD leaf (rocm6.4, gfx1151) is "rocm" in the tag vocabulary.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+rocm7.2",
+ expected_env = None,
+ recorded = "cu124",
+ backend = "rocm",
+ index_family = "gfx1151",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_a_cpu_pin_beats_a_gpu_manifest(self):
+ # A deliberate move to CPU must not be reverted by the previous install.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = None,
+ recorded = "cu124",
+ index_family = "cpu",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_an_unrecognised_pin_still_falls_through_to_the_manifest(self):
+ # A /simple mirror names no family; the caller's unknown-pin gate is the guard.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = None,
+ recorded = "cu124",
+ index_url = "https://mirror.corp.example/simple",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+ def test_the_setup_handover_still_wins_over_a_pin(self):
+ # The handover describes the run that just installed; the pin may predate it.
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.10.0+cu124",
+ repaired = "2.10.0+cu126",
+ expected_env = "cu126",
+ index_family = "cu128",
+ )
+ assert ok is True
+ assert "cu126" in _index_url(mock_pip)
+
+
+class TestExplicitlyPinnedGpuFlavorsAreStillEnforced:
+ """An explicit GPU pin sets _TORCH_BACKEND at import, and an XPU pin additionally
+ reads as an "unknown family" to the shared helper, whose known set predates XPU.
+ Between them those two gates skipped the invariant on exactly the hosts that asked
+ for that GPU family on purpose -- so a later dependency install could put PyPI's CPU
+ wheel there and the update would still report success."""
+
+ def test_a_pinned_xpu_backend_is_enforced_when_it_agrees(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.9.1+xpu",
+ backend = "xpu",
+ expected_env = "xpu",
+ )
+ assert ok is True
+ mock_pip.assert_called_once()
+
+ def test_a_pinned_rocm_backend_is_enforced_when_it_agrees(self):
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.11.0+rocm7.2",
+ backend = "rocm",
+ expected_env = "rocm",
+ )
+ assert ok is True
+ mock_pip.rocm_repair.assert_called_once()
+
+ def test_an_xpu_index_pin_repairs_from_that_pin(self):
+ """The pin's leaf IS the expected family, so it is not an unknown pin at all --
+ and it is the right index to repair from."""
+ pin = "https://mirror.corp.example/whl/xpu"
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ repaired = "2.9.1+xpu",
+ backend = "xpu",
+ expected_env = "xpu",
+ index_url = pin,
+ )
+ assert ok is True
+ assert pin in mock_pip.call_args[0]
+
+ def test_an_unknown_pin_is_still_left_alone(self):
+ """Regression guard: narrowing the veto must not reopen the case it closed."""
+ ok, mock_pip = _run_flavor_invariant(
+ installed = "2.11.0+cpu",
+ expected_env = None,
+ recorded = "cu124",
+ index_url = "https://mirror.corp.example/simple",
+ )
+ assert ok is True
+ mock_pip.assert_not_called()
+
+
+class TestSetupPs1CudaOnDiskFallback:
+ """A wedged NVIDIA driver hangs or faults `import torch` exactly as a faulted HIP
+ runtime does. XPU and ROCm both rescue that venv from torch/version.py on disk; CUDA
+ had no such arm, so the probe-failure chain fell through with a NULL tag, the no-wipe
+ escape could not see a cu* wheel to preserve, and a direct update deleted a healthy
+ CUDA environment before aborting."""
+
+ def test_the_classifier_exists_and_keeps_the_family(self):
+ assert "function Get-VenvTorchCudaTag" in _SETUP_SRC
+ assert "function Test-VenvTorchIsCuda" in _SETUP_SRC
+ block = _SETUP_SRC[_SETUP_SRC.index("function Get-VenvTorchCudaTag") :][:1400]
+ # The family, not a flat "cuda": the stale comparison below it is cu126-vs-cu128.
+ assert "cu[0-9]+" in block
+ assert "site-packages\\torch\\version.py" in block
+
+ def test_it_joins_the_probe_failure_chain(self):
+ chain_start = _SETUP_SRC.index("elseif (Test-VenvTorchIsXpu -VenvPath $VenvDir)")
+ chain = _SETUP_SRC[chain_start : _SETUP_SRC.index("$shouldRebuild = $true", chain_start)]
+ assert "Test-VenvTorchIsCuda -VenvPath $VenvDir" in chain
+ assert "$installedTorchTag = Get-VenvTorchCudaTag" in chain
+
+ def test_it_does_not_disturb_the_callers_match_state(self):
+ """A bare -match would clobber $Matches in the caller's scope; the stale-venv
+ block reads $Matches[1] a few lines above."""
+ block = _SETUP_SRC[_SETUP_SRC.index("function Get-VenvTorchCudaTag") :][:1400]
+ assert "[regex]::Match(" in block
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))
+
+
+class TestThePackagesTiedToTheTorchReleaseAreResettled:
+ """A repair that MOVES the torch release invalidates two compiled extensions.
+
+ torchao's cpp extensions are torch-release-specific, and step 4 chose its pin from
+ the torch this repair then replaced: 0.17.0 selected for a 2.11 that the <2.11.0
+ repair spec takes down to 2.10, whose matched build is 0.16.0. Leaving the wrong one
+ installed silently drops to the slow fallback.
+
+ xFormers is stricter: its _C.pyd is linked against one exact (torch, CUDA) pair, and
+ beside any other pair torch.ops.load_library raises, which xformers/_cpp_lib.py
+ downgrades to a log line, so the import "succeeds" with memory-efficient attention,
+ SwiGLU and the sparse ops silently gone. This script never installs xFormers, so
+ removal is the only correct action, and it is what the backend's own resolver
+ already concludes: torch SDPA beats an extension that cannot load.
+ """
+
+ def _resync(
+ self,
+ before,
+ after,
+ *,
+ resident_xformers = None,
+ installed_spec = False,
+ torchao_install_fails = False,
+ ):
+ calls = {"torchao": [], "removed": []}
+
+ def _try(*a, **k):
+ # Returns a BOOL, as the real pip_install_try does. list.append() returns
+ # None, so a stub that only appended reported failure on every call and every
+ # test here silently exercised the could-not-install branch.
+ calls["torchao"].append([str(x) for x in a])
+ return not torchao_install_fails
+
+ with (
+ patch.object(stack_mod, "_probe_installed_torch_version", return_value = after),
+ patch.object(
+ stack_mod,
+ "_exact_distribution_spec_is_installed",
+ return_value = installed_spec,
+ ),
+ patch.object(
+ stack_mod,
+ "_resident_xformers_build_torch",
+ return_value = resident_xformers,
+ ),
+ patch.object(
+ stack_mod,
+ "pip_install_try",
+ side_effect = _try,
+ ),
+ patch.object(
+ stack_mod,
+ "_uninstall_distribution",
+ side_effect = lambda name: calls["removed"].append(name) or True,
+ ),
+ patch.object(stack_mod, "_note", lambda *a, **k: None),
+ ):
+ calls["ok"] = stack_mod._resync_torch_coupled_packages(before)
+ return calls
+
+ def test_a_release_that_moved_re_pins_torchao(self):
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124")
+ assert calls["torchao"], "torchao must be re-selected for the new release"
+ assert any("torchao==0.16.0" in " ".join(c) for c in calls["torchao"])
+
+ def test_a_build_that_did_not_move_at_all_does_nothing(self):
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu124", resident_xformers = "2.11.0+cu128")
+ assert calls["torchao"] == []
+ assert calls["removed"] == []
+ assert calls["ok"] is True
+
+ def test_a_cuda_major_change_alone_re_pins_torchao(self):
+ # _select_torchao_spec branches on cuda>=13, so cu124 -> cu130 moves the build.
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu130")
+ assert calls["torchao"], "the CUDA major moved, so the pin has to be re-selected"
+ assert any("torchao==0.17.0" in " ".join(c) for c in calls["torchao"])
+
+ def test_a_flavor_change_within_one_cuda_major_leaves_torchao_alone(self):
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu128")
+ assert calls["torchao"] == []
+
+ def test_a_flavor_change_alone_still_rechecks_xformers(self):
+ # xFormers links against the exact (torch, CUDA) pair.
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu128", resident_xformers = "2.10.0+cu124")
+ assert calls["torchao"] == [], "the release did not move; torchao is fine"
+ assert calls["removed"] == ["xformers"]
+ assert calls["ok"] is True, "nothing here touched torch"
+
+ def test_the_torchao_reinstall_cannot_drag_torch_back(self):
+ # torchao depends on torch: resolving deps re-pulls the wheel just removed.
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124")
+ assert calls["torchao"], "the release moved, so torchao is re-pinned"
+ assert all("--no-deps" in c for c in calls["torchao"])
+
+ def test_a_pass_that_ran_a_torch_touching_install_asks_to_be_re_verified(self):
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124")
+ assert calls["ok"] is False
+
+ def test_a_pass_that_installed_nothing_does_not(self):
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124", installed_spec = True)
+ assert calls["torchao"] == []
+ assert calls["ok"] is True
+
+ def test_a_torchao_already_matching_is_left_alone(self):
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124", installed_spec = True)
+ assert calls["torchao"] == []
+
+ def test_a_mismatched_xformers_is_removed(self):
+ calls = self._resync("2.11.0", "2.10.0+cu124", resident_xformers = "2.11.0+cu128")
+ assert calls["removed"] == ["xformers"]
+
+ def test_an_xformers_built_for_the_resident_torch_is_kept(self):
+ calls = self._resync("2.11.0", "2.10.0+cu124", resident_xformers = "2.10.0+cu124")
+ assert calls["removed"] == []
+
+ def test_an_absent_xformers_is_not_touched(self):
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124", resident_xformers = None)
+ assert calls["removed"] == []
+
+ def test_a_torchao_that_cannot_be_reinstalled_across_a_cuda_major_is_removed(self):
+ """cu124 to cu130 with the torchao source unreachable.
+
+ _select_torchao_spec exists because a torchao compiled for CUDA 12 cannot load its
+ cpp extension under cu130, so leaving the resident one behind completes the update
+ with a package that may fail on import. Same remedy the xFormers arm applies.
+ """
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu130", torchao_install_fails = True)
+ assert calls["torchao"], "the CUDA major moved, so the pin is re-selected"
+ assert calls["removed"] == ["torchao"]
+
+ def test_a_release_only_move_that_cannot_reinstall_keeps_torchao(self):
+ """No CUDA-major change, so the resident build still loads: this one IS the slow path."""
+ calls = self._resync("2.11.0+cu124", "2.10.0+cu124", torchao_install_fails = True)
+ assert calls["torchao"], "the release moved, so the pin is re-selected"
+ assert calls["removed"] == [], "a same-major torchao is slower, not broken"
+
+ def test_a_torchao_that_reinstalls_cleanly_is_not_removed(self):
+ calls = self._resync("2.10.0+cu124", "2.10.0+cu130")
+ assert calls["torchao"], "the CUDA major moved"
+ assert calls["removed"] == [], "the replacement landed; nothing to remove"
+
+ def test_an_unreadable_torch_after_the_repair_does_nothing(self):
+ calls = self._resync("2.11.0+cu124", None, resident_xformers = "2.11.0+cu128")
+ assert calls["torchao"] == []
+ assert calls["removed"] == []
+ assert calls["ok"] is True
+
+ def test_neither_half_can_fail_the_update(self, capsys):
+ with (
+ patch.object(stack_mod, "_probe_installed_torch_version", return_value = "2.10.0+cu124"),
+ patch.object(
+ stack_mod,
+ "_select_torchao_spec",
+ side_effect = RuntimeError("index down"),
+ ),
+ patch.object(
+ stack_mod,
+ "_resident_xformers_build_torch",
+ side_effect = RuntimeError("unreadable"),
+ ),
+ ):
+ assert stack_mod._resync_torch_coupled_packages("2.11.0+cu124") is True
+ out = capsys.readouterr().out
+ assert "could not re-match torchao" in out
+ assert "could not re-check xFormers" in out
+
+
+class TestTheResidentXformersBuildIsReadFromDisk:
+ def test_the_recorded_torch_is_returned(self, tmp_path):
+ pkg = tmp_path / "xformers"
+ pkg.mkdir()
+ (pkg / "cpp_lib.json").write_text(
+ '{"version": {"torch": "2.10.0+cu128"}}', encoding = "utf-8"
+ )
+ with patch.object(
+ stack_mod.importlib.util,
+ "find_spec",
+ return_value = SimpleNamespace(submodule_search_locations = [str(pkg)]),
+ ):
+ assert stack_mod._resident_xformers_build_torch() == "2.10.0+cu128"
+
+ @pytest.mark.parametrize(
+ "body", ['{"version": {}}', "{not json", '{"version": {"torch": " "}}']
+ )
+ def test_an_unusable_record_reads_as_unknown(self, tmp_path, body):
+ pkg = tmp_path / "xformers"
+ pkg.mkdir()
+ (pkg / "cpp_lib.json").write_text(body, encoding = "utf-8")
+ with patch.object(
+ stack_mod.importlib.util,
+ "find_spec",
+ return_value = SimpleNamespace(submodule_search_locations = [str(pkg)]),
+ ):
+ assert stack_mod._resident_xformers_build_torch() is None
+
+ def test_an_absent_xformers_reads_as_unknown(self):
+ with patch.object(stack_mod.importlib.util, "find_spec", return_value = None):
+ assert stack_mod._resident_xformers_build_torch() is None
+
+ def test_a_find_spec_that_raises_reads_as_unknown(self):
+ with patch.object(stack_mod.importlib.util, "find_spec", side_effect = ValueError("boom")):
+ assert stack_mod._resident_xformers_build_torch() is None
+
+
+class TestTheResyncNoticesItsOwnFailures:
+ """Both halves report failure by return value, not by raising.
+
+ Ignoring that let the update write a completion manifest over an incompatible
+ torchao, or over an xFormers whose removal was blocked, with nothing said.
+ """
+
+ def _resync_with(
+ self,
+ *,
+ torchao_ok = True,
+ uninstall_ok = True,
+ ):
+ with (
+ patch.object(stack_mod, "_probe_installed_torch_version", return_value = "2.10.0+cu124"),
+ patch.object(stack_mod, "_exact_distribution_spec_is_installed", return_value = False),
+ patch.object(stack_mod, "_resident_xformers_build_torch", return_value = "2.11.0+cu128"),
+ patch.object(stack_mod, "pip_install_try", return_value = torchao_ok),
+ patch.object(stack_mod, "_uninstall_distribution", return_value = uninstall_ok),
+ patch.object(stack_mod, "_note", lambda *a, **k: None),
+ ):
+ return stack_mod._resync_torch_coupled_packages("2.11.0+cu124")
+
+ def test_a_torchao_install_that_did_not_take_is_reported(self, capsys):
+ self._resync_with(torchao_ok = False)
+ assert "could not install" in capsys.readouterr().out
+
+ def test_an_xformers_removal_that_was_blocked_is_reported(self, capsys):
+ self._resync_with(uninstall_ok = False)
+ out = capsys.readouterr().out
+ assert "could not remove the mismatched xFormers" in out
+
+ def test_a_clean_pass_says_nothing(self, capsys):
+ self._resync_with()
+ out = capsys.readouterr().out
+ assert "[WARN]" not in out
+
+ def test_a_failure_still_does_not_fail_the_update(self):
+ # The return value reports whether torch may have MOVED, not that all was well.
+ assert self._resync_with(torchao_ok = False, uninstall_ok = False) is False
+
+
+class TestThePostRepairCheckUsesTheSameRuleAsThePreRepairOne:
+ def test_an_untagged_gpu_wheel_does_not_satisfy_a_cpu_expectation(self):
+ # Untagged reads as cpu, so the post-repair check would accept the very wheel
+ # the pre-repair check rejected.
+ with (
+ patch.object(
+ stack_mod,
+ "_probe_torch_runtime",
+ return_value = (True, True, "2.6.0", "", "12.4"),
+ ),
+ ):
+ assert stack_mod._installed_flavor_tag_now("cpu") == "cuda"
+ with patch.object(
+ stack_mod,
+ "_probe_torch_runtime",
+ return_value = (True, True, "2.6.0", "6.4", ""),
+ ):
+ assert stack_mod._installed_flavor_tag_now("cpu") == "rocm"
+
+ def test_a_genuine_untagged_cpu_wheel_still_reads_as_cpu(self):
+ with patch.object(
+ stack_mod,
+ "_probe_torch_runtime",
+ return_value = (True, True, "2.6.0", "", ""),
+ ):
+ assert stack_mod._installed_flavor_tag_now("cpu") == "cpu"
+
+ def test_the_adjustment_is_scoped_to_a_cpu_expectation(self):
+ with patch.object(
+ stack_mod,
+ "_probe_torch_runtime",
+ return_value = (True, True, "2.6.0", "", "12.4"),
+ ):
+ assert stack_mod._installed_flavor_tag_now("cu124") == "cpu"
+ assert stack_mod._installed_flavor_tag_now() == "cpu"
+
+
+class TestTheWindowsXpuTritonSwapReachesADirectRun:
+ """setup.ps1 performs the swap after this script exits; a direct run has no such
+ postlude, and the core install pulls triton-windows over torch's XPU triton."""
+
+ def test_the_handover_variable_gates_it(self):
+ source = inspect.getsource(stack_mod._ensure_xpu_triton)
+ assert "if NO_TORCH or IS_MACOS:" in source, "Windows must no longer be excluded outright"
+ assert (
+ 'IS_WINDOWS and os.environ.get("UNSLOTH_EXPECTED_TORCH_TAG"' in source
+ ), "under setup.ps1 the swap is still that script's job"
+
+ def test_the_windows_branch_runs_it_after_the_invariant(self):
+ source = inspect.getsource(stack_mod.install_python_stack)
+ marker = "if IS_WINDOWS and not NO_TORCH:"
+ assert marker in source
+ block = source[source.index(marker) :][:1200]
+ assert "_ensure_expected_torch_flavor" in block
+ assert "_ensure_xpu_triton()" in block
+ # After, for the reason step 13 puts it last: the swap keys off the +xpu label.
+ assert block.index("_ensure_expected_torch_flavor") < block.index("_ensure_xpu_triton()")
+
+
+class TestTheDelegatedRocmRepairKeepsTheArm64Exception:
+ """_ensure_rocm_torch's Windows branch asked for the full trio unconditionally.
+
+ No win_arm64 torchaudio wheel exists, so the whole trio is unresolvable there. On
+ the delegated path that failure is nonfatal, so the CPU build the repair was meant
+ to replace stays put and the family verification then fails the update -- a worse
+ outcome than the plain trio case, where the failure is at least immediate.
+ """
+
+ def test_the_windows_rocm_install_drops_torchaudio_on_arm64(self):
+ source = inspect.getsource(stack_mod._ensure_rocm_torch)
+ block = source[source.index("_WINDOWS_ROCM_TORCH_PKG_SPECS.get") :][:1200]
+ assert (
+ "_is_windows_arm64()" in block
+ ), "the delegated ROCm repair needs the same exception as the flavor repair"
+ assert "*_rocm_trio" in block, "the trio has to be built, not passed positionally"
+
+ def test_x64_windows_still_asks_for_all_three(self):
+ source = inspect.getsource(stack_mod._ensure_rocm_torch)
+ block = source[source.index("_WINDOWS_ROCM_TORCH_PKG_SPECS.get") :][:1200]
+ assert "_rocm_trio = [_torch_pkg, _vision_pkg, _audio_pkg]" in block
+
+
+class TestADefinitiveImportFailureIsNotADriverHang:
+ """setup.ps1's disk-label rescue treated both the same.
+
+ A wedged driver and a truncated torch both leave a +cu* version.py behind. Keeping
+ the venv is right in both cases -- deleting it does not fix a driver, which is the
+ whole point of the rescue (#8335, #7275) -- but only the first means the
+ installation is sound, and the family-matched install below runs with bare
+ requirements and no reinstall flag, so the second could write a completion manifest
+ over a torch that still cannot import.
+ """
+
+ _SOURCE = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+
+ def test_the_probe_distinguishes_a_timeout_from_an_answer(self):
+ assert "TimedOut = $false" in self._SOURCE
+ assert "$result.TimedOut = $true" in self._SOURCE
+
+ def test_the_cuda_rescue_forces_a_reinstall_on_a_definitive_failure(self):
+ block = self._SOURCE[self._SOURCE.index("Test-VenvTorchIsCuda -VenvPath $VenvDir") :][:2000]
+ assert "$_verProbe -and -not $_verProbe.TimedOut" in block
+ assert "$script:TorchImportDefinitivelyFailed = $true" in block
+
+ def test_the_venv_is_still_kept_either_way(self):
+ # A faulted driver raises at DLL load rather than timing out.
+ start = self._SOURCE.index("Test-VenvTorchIsCuda -VenvPath $VenvDir")
+ # The CUDA arm only: the trailing "no family matched" else SHOULD rebuild.
+ arm = self._SOURCE[start : self._SOURCE.index("} else {", start)]
+ code = "\n".join(line for line in arm.splitlines() if not line.strip().startswith("#"))
+ assert "$shouldRebuild" not in code
+ assert "$script:TorchImportDefinitivelyFailed = $true" in arm
+
+ def test_the_flag_reaches_the_cuda_install(self):
+ assert (
+ "if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {"
+ in self._SOURCE
+ )
+ assert "$script:TorchImportDefinitivelyFailed = $false" in self._SOURCE
+
+
+class TestARepairedTorchThatCannotImport:
+ """The verification after a repair, when the new wheel does not load.
+
+ _probe_torch_runtime answers (ran, importable, ...). A torch that RAN and did not
+ import is a definitive answer, not the ambiguity the on-disk fallback exists for:
+ version.py still reports the requested +cu*/+xpu tag from a half-written or DLL-less
+ wheel, so reading it would accept the repair and write a completion manifest over a
+ torch nothing can import. Only a probe that could not run at all (a hung driver) may
+ fall back to disk.
+ """
+
+ def _probe(self, monkeypatch, *, ran, importable, version):
+ monkeypatch.setattr(
+ stack_mod,
+ "_probe_torch_runtime",
+ lambda: (ran, importable, version, None, "12.4" if "+cu" in (version or "") else None),
+ )
+ monkeypatch.setattr(stack_mod, "_installed_torch_label_on_disk", lambda: version or "")
+
+ def test_a_definitive_import_failure_is_not_read_off_disk(self, monkeypatch):
+ self._probe(monkeypatch, ran = True, importable = False, version = "2.6.0+cu124")
+ assert stack_mod._installed_flavor_tag_now("cu124") == stack_mod._TORCH_TAG_UNIMPORTABLE
+
+ def test_a_probe_that_could_not_run_still_falls_back_to_disk(self, monkeypatch):
+ # The wedged-driver host this fallback exists for.
+ self._probe(monkeypatch, ran = False, importable = False, version = "2.6.0+cu124")
+ assert stack_mod._installed_flavor_tag_now("cu124") == "cu124"
+
+ def test_a_healthy_probe_is_unaffected(self, monkeypatch):
+ self._probe(monkeypatch, ran = True, importable = True, version = "2.6.0+cu124")
+ assert stack_mod._installed_flavor_tag_now("cu124") == "cu124"
+
+ def test_the_sentinel_cannot_be_mistaken_for_a_flavor(self):
+ sentinel = stack_mod._TORCH_TAG_UNIMPORTABLE
+ for tag in ("cpu", "cu124", "cu128", "rocm", "xpu", ""):
+ assert sentinel != tag
+ assert sentinel, "falsy would be swallowed by the ambiguity branch"
+
+ def test_the_update_fails_rather_than_reporting_success(self, monkeypatch):
+ """End to end: a cu124 repair whose wheel will not import must not return True."""
+ lines = []
+ monkeypatch.setattr(stack_mod, "IS_WINDOWS", True)
+ monkeypatch.setattr(stack_mod, "IS_MACOS", False)
+ monkeypatch.setattr(stack_mod, "NO_TORCH", False)
+ monkeypatch.setattr(stack_mod, "_TORCH_BACKEND", "")
+ monkeypatch.setattr(stack_mod, "_RECORDED_TORCH_TAG", None)
+ monkeypatch.setattr(
+ stack_mod, "_safe_print", lambda *a, **k: lines.append(" ".join(map(str, a)))
+ )
+ monkeypatch.setattr(stack_mod, "_has_usable_nvidia_gpu", lambda: True)
+ monkeypatch.setenv("UNSLOTH_EXPECTED_TORCH_TAG", "cu124")
+ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_URL", raising = False)
+ monkeypatch.delenv("UNSLOTH_TORCH_INSTALL_INDEX_URL", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+
+ state = {"ran": True, "importable": True, "version": "2.11.0+cpu"}
+ monkeypatch.setattr(
+ stack_mod,
+ "_probe_torch_runtime",
+ lambda: (state["ran"], state["importable"], state["version"], None, None),
+ )
+ monkeypatch.setattr(stack_mod, "_installed_torch_label_on_disk", lambda: state["version"])
+
+ def _pip(_label, *_a, **_k):
+ # The repair lands the right family, and it does not import.
+ state.update(ran = True, importable = False, version = "2.6.0+cu124")
+
+ monkeypatch.setattr(stack_mod, "pip_install", _pip)
+ assert stack_mod._ensure_expected_torch_flavor() is False
+ assert any("cannot be imported" in ln for ln in lines), lines
diff --git a/tests/studio/install/test_pr5940_followups.py b/tests/studio/install/test_pr5940_followups.py
index 53d3b49ecb0..91b5e480c40 100644
--- a/tests/studio/install/test_pr5940_followups.py
+++ b/tests/studio/install/test_pr5940_followups.py
@@ -793,9 +793,15 @@ def test_install_python_stack_windows_rocm_repair_pins_and_is_nonfatal():
k == -1 or j > k
), "Windows ROCm repair must use the nonfatal pip_install_try wrapping the trio"
window = text[i : i + 700]
+ # The trio is built just above the call now (win_arm64 drops torchaudio), but the
+ # requirement is unchanged: the PINNED companions, never bare names.
+ trio = text[max(0, i - 900) : i + 700]
assert (
- "_torch_pkg" in window and "_vision_pkg" in window and "_audio_pkg" in window
+ "_torch_pkg" in trio and "_vision_pkg" in trio and "_audio_pkg" in trio
), "Windows ROCm repair must pass the pinned companion trio, not bare names"
+ assert "*_rocm_trio" in window or (
+ "_torch_pkg" in window and "_vision_pkg" in window and "_audio_pkg" in window
+ ), "the trio the call receives must be the pinned one"
assert (
"keeping the existing torch build" in window
), "Windows ROCm repair must keep the existing build (nonfatal) when the index fails"
diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.py
new file mode 100644
index 00000000000..cb2e9e1c140
--- /dev/null
+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py
@@ -0,0 +1,454 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Structural cover for the Windows torch-flavor invariant on the update path.
+
+The behavioural tests for _ensure_expected_torch_flavor live in test_cuda_repair.py.
+This file asserts the parts that are not a Python call: that setup.ps1 hands the flavor
+over before it invokes the stack, that setup.ps1 no longer wipes a healthy cu* venv when
+nvidia-smi fails to answer, that the repair specs and the mismatch line stay identical to
+install.ps1's, that the manifest round-trips the flavor, and that none of it reaches the
+Linux/macOS branch of install_python_stack(). Source/AST only -- no Windows required."""
+
+import ast
+import importlib.util
+import json
+import re
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+
+_SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"
+_INSTALL_PS1 = PACKAGE_ROOT / "install.ps1"
+_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"
+
+_SETUP_SRC = _SETUP_PS1.read_text(encoding = "utf-8")
+_INSTALL_SRC = _INSTALL_PS1.read_text(encoding = "utf-8")
+_STACK_SRC = _STACK_PATH.read_text(encoding = "utf-8")
+
+_MANIFEST_SPEC = importlib.util.spec_from_file_location(
+ "studio_install_manifest_flavor", PACKAGE_ROOT / "studio" / "install_manifest.py"
+)
+assert _MANIFEST_SPEC is not None and _MANIFEST_SPEC.loader is not None
+install_manifest = importlib.util.module_from_spec(_MANIFEST_SPEC)
+sys.modules[_MANIFEST_SPEC.name] = install_manifest
+_MANIFEST_SPEC.loader.exec_module(install_manifest)
+
+
+def _line_of(source: str, needle: str) -> int:
+ """1-based line number of the first line containing `needle`."""
+ for number, line in enumerate(source.splitlines(), start = 1):
+ if needle in line:
+ return number
+ raise AssertionError(f"not found in source: {needle!r}")
+
+
+def _publication_block() -> str:
+ """The whole flavor-publication block, delimited by the section that follows it.
+
+ Sliced by its end marker rather than a character count: a count silently
+ truncates the moment a comment inside the block grows, and a test that reads
+ half the block passes for the wrong reason.
+ """
+ start = _SETUP_SRC.index("# ── Publish the torch flavor this run settled on ──")
+ end = _SETUP_SRC.index("# Ordered heavy dependency installation", start)
+ return _SETUP_SRC[start:end]
+
+
+class TestSetupPs1NoWipeEscape:
+ """A direct `studio update` has no rollback copy -- only install.ps1 makes one -- so a
+ wipe there is unrecoverable. Every way the bounded nvidia-smi probe can come back
+ empty on a working NVIDIA box collapses the expected tag to "cpu", and a healthy cu124
+ venv then reads as stale."""
+
+ def test_the_escape_sits_ahead_of_the_wipe(self):
+ escape = _line_of(_SETUP_SRC, "nvidia-smi did not answer, but this venv holds a")
+ wipe = _line_of(_SETUP_SRC, "Remove-Item -LiteralPath $VenvDir -Recurse -Force")
+ stale = _line_of(_SETUP_SRC, "Stale venv detected ($reason) -- rebuilding...")
+ assert escape < stale < wipe, (
+ "the no-wipe escape must be evaluated before the stale-venv branch that deletes "
+ f"the venv (escape={escape}, stale={stale}, wipe={wipe})"
+ )
+
+ def test_the_escape_cancels_the_rebuild(self):
+ body = _SETUP_SRC[_SETUP_SRC.index("nvidia-smi did not answer, but this venv holds a") :][
+ :1200
+ ]
+ assert "$shouldRebuild = $false" in body
+ # Without this the index selection re-runs the same rescan and routes to /cpu.
+ assert "$script:PreservedInstallerTorchTag = $installedTorchTag" in body
+
+ def test_the_escape_is_narrow(self):
+ start = _SETUP_SRC.index("if ($shouldRebuild -and -not $InstallerManagedSetup -and\n")
+ condition = _SETUP_SRC[start : _SETUP_SRC.index("{", start)]
+ for clause in (
+ "-not $InstallerManagedSetup", # install.ps1 repairs in place instead
+ "-not $_pinnedIdx", # a cpu index PIN is deliberate and still rebuilds
+ "Test-CudaFamilyLeaf $installedTorchTag", # only a cu* wheel is preserved
+ "-not $HasNvidiaSmi", # only when the NVIDIA probe gave no answer
+ '$expectedTorchTag -eq "cpu"', # ... and that is why the expectation collapsed
+ ):
+ assert clause in condition, f"the escape must be gated on {clause!r}"
+
+ def test_the_installed_tag_is_tested_before_the_variables_it_implies(self):
+ # $_pinnedIdx and $expectedTorchTag are assigned only inside `if (-not
+ # $shouldRebuild)`, so under Set-StrictMode the other -and order is a fatal read.
+ start = _SETUP_SRC.index("if ($shouldRebuild -and -not $InstallerManagedSetup -and\n")
+ condition = _SETUP_SRC[start : _SETUP_SRC.index("{", start)]
+ assert condition.index("$installedTorchTag -and") < condition.index("$_pinnedIdx")
+ assert condition.index("$installedTorchTag -and") < condition.index("$expectedTorchTag")
+
+ def test_an_xpu_venv_keeps_its_own_escape(self):
+ # Regression guard: the pre-existing XPU escape must not have been folded in.
+ assert "Keeping the installed Intel XPU environment" in _SETUP_SRC
+
+
+class TestSetupPs1PublishesTheFlavor:
+ def test_the_tag_is_exported_before_the_stack_runs(self):
+ export = _line_of(_SETUP_SRC, "$env:UNSLOTH_EXPECTED_TORCH_TAG =")
+ index = _line_of(_SETUP_SRC, "$env:UNSLOTH_TORCH_INSTALL_INDEX_URL =")
+ handoff = _line_of(_SETUP_SRC, 'python "$PSScriptRoot\\install_python_stack.py"')
+ assert export < handoff and index < handoff
+
+ def test_the_rocm_index_decides_before_the_leaf(self):
+ # The AMD Windows path installs from repo.amd.com while $TorchInstallIndexUrl still
+ # points at /cpu, so the leaf alone would publish the wrong flavor.
+ block = _SETUP_SRC[_SETUP_SRC.index("$_expectedTag = if ($ROCmIndexUrl)") :][:600]
+ assert block.startswith('$_expectedTag = if ($ROCmIndexUrl) { "rocm" }')
+ assert "Test-CudaFamilyLeaf $_expectedLeaf" in block
+ assert "Test-PipRocmFamilyLeaf $_expectedLeaf" in block
+ # An unknown leaf publishes nothing rather than a tag nothing can verify.
+ assert "else { $null }" in block
+
+ def test_no_torch_mode_publishes_nothing(self):
+ assert "if (-not $NoTorchMode) {" in _publication_block()
+
+ def test_unsetting_does_not_depend_on_the_powershell_version(self):
+ """`$env:X = ""` is not a portable unset, so it must not be used here.
+
+ Windows PowerShell 5.1 and PowerShell 7.0-7.4 delete the entry when it is
+ assigned an empty string. PowerShell 7.5 took .NET 9's change and KEEPS the
+ name with an empty value; only $null removes it there. Both spellings still
+ read as unset through the two readers on the Python side, which test
+ truthiness rather than presence, so this is about not shipping a line whose
+ meaning depends on which PowerShell the user happens to have installed.
+ Remove-Item behaves identically on every version.
+
+ Deleting rather than blanking also matters on its own: a value inherited
+ from the caller's shell must not survive a run that decided it cannot name
+ this host's flavor, or the stack enforces a stale expectation.
+ """
+ block = _publication_block()
+ for name in (
+ "UNSLOTH_EXPECTED_TORCH_TAG",
+ "UNSLOTH_TORCH_INSTALL_INDEX_URL",
+ ):
+ assert (
+ f"Remove-Item Env:\\{name} -ErrorAction SilentlyContinue" in block
+ ), f"{name} must be removed, not blanked"
+ assert f'$env:{name} = ""' not in block
+ assert f"$env:{name} = if (" not in block
+
+
+class TestInstallPs1Parity:
+ """A venv repaired by `studio update` and one repaired by install.ps1 must land on the
+ same wheels, and a support log from either must read the same."""
+
+ def test_the_repair_trio_matches_install_ps1(self):
+ match = re.search(r'else\s*\{\s*@\((\s*"torch[^)]*?)\)\s*\}', _INSTALL_SRC, re.S)
+ assert match is not None, "install.ps1's flavor-repair spec array moved"
+ ps_specs = tuple(re.findall(r'"([^"]+)"', match.group(1)))
+ py_specs = tuple(
+ re.findall(
+ r'"([^"]+)"',
+ re.search(
+ r"_TORCH_FLAVOR_REPAIR_PKG_SPEC: tuple\[str, str, str\] = \((.*?)\)",
+ _STACK_SRC,
+ re.S,
+ ).group(1),
+ )
+ )
+ assert py_specs == ps_specs, (
+ "_TORCH_FLAVOR_REPAIR_PKG_SPEC must mirror install.ps1's flavor-repair trio "
+ f"(python={py_specs}, install.ps1={ps_specs})"
+ )
+
+ def test_the_mismatch_line_matches_install_ps1(self):
+ assert (
+ "PyTorch flavor mismatch (installed $installedTorchTag, need $expectedTorchTag) "
+ "-- reinstalling correct build..."
+ ) in _INSTALL_SRC
+ assert (
+ "PyTorch flavor mismatch (installed {installed}, need {expected}) -- "
+ ) in _STACK_SRC
+ assert "reinstalling correct build..." in _STACK_SRC
+
+ def test_the_loud_warning_matches_install_ps1(self):
+ for line in (
+ "PyTorch is CPU-only but a",
+ "GPU build was expected for this machine.",
+ "Training and GPU inference will run on CPU until this is fixed.",
+ "Re-run this installer, or reinstall the GPU build manually for your GPU.",
+ ):
+ assert line in _INSTALL_SRC, f"install.ps1 no longer prints {line!r}"
+ assert line in _STACK_SRC, f"install_python_stack.py no longer prints {line!r}"
+
+ def test_the_flavor_vocabulary_matches_convertto_torchflavortag(self):
+ arms = _INSTALL_SRC[_INSTALL_SRC.index("function ConvertTo-TorchFlavorTag") :][:900]
+ assert r"'\+(cu\d+)'" in arms
+ assert r"'\+rocm'" in arms
+ assert r"'\+xpu'" in arms
+ assert r"'\+cpu'" in arms
+ py = _STACK_SRC[_STACK_SRC.index("def _torch_flavor_tag(") :][:1600]
+ assert r'r"\+(cu\d+)"' in py
+ assert '"+rocm" in value' in py
+ assert '"+xpu" in value' in py
+
+
+def _install_stack_ast():
+ tree = ast.parse(_STACK_SRC)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "install_python_stack":
+ return node
+ raise AssertionError("install_python_stack() not found")
+
+
+def _calls_in(node) -> list:
+ """Every plain function name called under `node`, in source order.
+
+ Depth first, not ast.walk: walk is breadth first, so a nested call reads as if it came
+ after its own siblings and the assertions below would encode the wrong order.
+ """
+ names = []
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ names.append(node.func.id)
+ for child in ast.iter_child_nodes(node):
+ names.extend(_calls_in(child))
+ return names
+
+
+def _guards_containing(call_name: str) -> list:
+ """Every TOP-LEVEL `if` in install_python_stack() whose body calls `call_name`.
+
+ Plural on purpose: the four existing repair helpers run at two points (the step-2b
+ check and the step-13 final pass), so a test that took the first match would silently
+ assert about the wrong one. Top level only, or a guard's own nested `if` counts twice.
+ """
+ found = [
+ node
+ for node in _install_stack_ast().body
+ if isinstance(node, ast.If) and call_name in _calls_in(node)
+ ]
+ assert found, f"no guard around {call_name}()"
+ return found
+
+
+class TestStepThirteenWiring:
+ def test_the_flavor_invariant_is_windows_only(self):
+ guards = _guards_containing("_ensure_expected_torch_flavor")
+ assert [ast.unparse(guard.test) for guard in guards] == ["IS_WINDOWS and (not NO_TORCH)"]
+
+ def test_a_failed_invariant_returns_non_zero(self):
+ (guard,) = _guards_containing("_ensure_expected_torch_flavor")
+ returns = [
+ node.value.value
+ for node in ast.walk(guard)
+ if isinstance(node, ast.Return) and isinstance(node.value, ast.Constant)
+ ]
+ assert returns == [1], (
+ "a torch flavor that could not be repaired must fail the install; today that "
+ "state exits 0 and the app silently runs on CPU"
+ )
+
+ def test_the_existing_repair_set_is_untouched(self):
+ # Step 2b (which Windows enters; the four helpers return early there) and the
+ # Linux-only step 13.
+ guards = _guards_containing("_ensure_cuda_torch")
+ assert [ast.unparse(guard.test) for guard in guards] == [
+ "not IS_MACOS and (not NO_TORCH)",
+ "not IS_WINDOWS and (not IS_MACOS) and (not NO_TORCH)",
+ ]
+ for guard in guards:
+ assert _calls_in(guard) == [
+ "_progress",
+ "_torch_step_label",
+ "_ensure_cuda_torch",
+ "_ensure_rocm_torch",
+ "_ensure_xpu_torch",
+ "_ensure_cpu_torch",
+ "_ensure_xpu_triton",
+ ]
+
+ def test_the_invariant_is_wired_in_exactly_once(self):
+ body = ast.unparse(_install_stack_ast())
+ assert body.count("_ensure_expected_torch_flavor(") == 1
+
+
+def _base_total(**flags) -> int:
+ """Re-execute install_python_stack()'s step-total arithmetic under given flags.
+
+ Read out of the function rather than duplicated, so a step added without a matching
+ total fails here instead of drawing a progress bar past 100%.
+ """
+ lines = _STACK_SRC.splitlines()
+ start = next(i for i, line in enumerate(lines) if line.strip().startswith("base_total = 12"))
+ end = next(i for i, line in enumerate(lines) if line.strip().startswith("base_requirements ="))
+ block = textwrap.dedent("\n".join(lines[start:end]))
+ namespace = {
+ "IS_WINDOWS": False,
+ "IS_MACOS": False,
+ "NO_TORCH": False,
+ "IS_MAC_ARM": False,
+ "skip_base": False,
+ }
+ namespace.update(flags)
+ exec(block, namespace) # noqa: S102 -- the source under test, not user input
+ return namespace["base_total"]
+
+
+class TestStepTotals:
+ def test_windows_gained_one_step(self):
+ assert _base_total(IS_WINDOWS = True) == 14
+ assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 12
+
+ @pytest.mark.parametrize(
+ "flags,total",
+ [
+ ({}, 16), # Linux, torch
+ ({"NO_TORCH": True}, 13), # Linux, GGUF-only
+ ({"IS_MACOS": True, "IS_MAC_ARM": True}, 13), # Apple Silicon
+ ({"IS_MACOS": True}, 12), # Intel Mac
+ ],
+ )
+ def test_the_other_platforms_are_unchanged(self, flags, total):
+ assert _base_total(**flags) == total
+
+
+class TestManifestRecordsTheFlavor:
+ def test_round_trip(self, tmp_path):
+ assert (
+ install_manifest.write_manifest(
+ root = tmp_path, req_root = tmp_path, expected_torch_tag = "cu124"
+ )
+ is not None
+ )
+ assert install_manifest.recorded_torch_flavor(tmp_path) == "cu124"
+
+ def test_the_tag_is_normalised(self, tmp_path):
+ install_manifest.write_manifest(
+ root = tmp_path, req_root = tmp_path, expected_torch_tag = " CU128 "
+ )
+ assert install_manifest.recorded_torch_flavor(tmp_path) == "cu128"
+
+ def test_absent_reads_as_unknown_not_cpu(self, tmp_path):
+ # Claiming a flavor nobody selected would let a repair reinstall over a
+ # deliberate build.
+ install_manifest.write_manifest(root = tmp_path, req_root = tmp_path)
+ assert install_manifest.recorded_torch_flavor(tmp_path) is None
+
+ def test_no_manifest_reads_as_unknown(self, tmp_path):
+ assert install_manifest.recorded_torch_flavor(tmp_path) is None
+
+ def test_a_hand_edited_non_string_reads_as_unknown(self, tmp_path):
+ path = install_manifest.manifest_path(tmp_path)
+ path.write_text(json.dumps({"schema": 1, "expected_torch_tag": 124}), encoding = "utf-8")
+ assert install_manifest.recorded_torch_flavor(tmp_path) is None
+
+ def test_the_key_is_additive(self, tmp_path):
+ # MANIFEST_SCHEMA must not move: verify_install rejects a schema it does not know.
+ assert install_manifest.MANIFEST_SCHEMA == 1
+ install_manifest.write_manifest(
+ root = tmp_path, req_root = tmp_path, expected_torch_tag = "cu124", no_torch = False
+ )
+ payload = json.loads(install_manifest.manifest_path(tmp_path).read_text(encoding = "utf-8"))
+ assert payload["schema"] == 1
+ assert payload["no_torch"] is False
+ assert payload["expected_torch_tag"] == "cu124"
+
+ def test_no_index_url_is_ever_written(self, tmp_path):
+ # A pinned index can carry a token; this file sits in the venv and is read back.
+ install_manifest.write_manifest(
+ root = tmp_path, req_root = tmp_path, expected_torch_tag = "cu124"
+ )
+ raw = install_manifest.manifest_path(tmp_path).read_text(encoding = "utf-8")
+ assert "http" not in raw
+
+ def test_the_stack_carries_a_previous_record_forward(self):
+ # A platform that never resolves a flavor must not erase the one already recorded.
+ assert "expected_torch_tag = torch_flavor_tag or _RECORDED_TORCH_TAG," in _STACK_SRC
+
+ def test_the_record_is_read_before_the_manifest_is_dropped(self):
+ # install_python_stack() removes the manifest before its dependency pass.
+ read = _line_of(
+ _STACK_SRC, "_RECORDED_TORCH_TAG = install_manifest.recorded_torch_flavor()"
+ )
+ drop = _line_of(_STACK_SRC, "if not install_manifest.remove_manifest():")
+ assert read < drop
+ assert (
+ "def install_python_stack"
+ not in _STACK_SRC[: _STACK_SRC.index("_RECORDED_TORCH_TAG =")]
+ )
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main([__file__, "-q"]))
+
+
+class TestABrokenTorchForcesItsOwnReinstall:
+ """$script:TorchImportDefinitivelyFailed is raised when the probe reports an import
+ ERROR rather than a timeout, so the wheel on disk is the suspect and not the driver.
+ Every consumer of it lives inside `if (-not $SkipPythonDeps)`, and the XPU and CPU
+ arms did not consult it at all: an unimportable +xpu wheel still reports its on-disk
+ tag as "xpu", so no flavour change is seen, the bounded range is satisfied, and the
+ resolver keeps it. The run then writes a completion manifest over a venv that cannot
+ import torch."""
+
+ def test_the_flag_clears_the_dependency_skip(self):
+ clear = _SETUP_SRC.index(
+ "if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {"
+ )
+ block = _SETUP_SRC[clear : _SETUP_SRC.index("if (-not $SkipPythonDeps) {", clear)]
+ assert "$SkipPythonDeps = $false" in block
+
+ def test_the_clear_runs_before_the_block_that_holds_every_consumer(self):
+ clear = _line_of(_SETUP_SRC, "$script:TorchImportDefinitivelyFailed) {")
+ guard = _line_of(_SETUP_SRC, "if (-not $SkipPythonDeps) {")
+ last = max(
+ number
+ for number, line in enumerate(_SETUP_SRC.splitlines(), start = 1)
+ if "$script:TorchImportDefinitivelyFailed" in line
+ )
+ assert clear < guard < last, (
+ f"clear at {clear}, block opens at {guard}, last consumer at {last}; any "
+ f"other order leaves the reinstall announced but unreachable"
+ )
+
+ @pytest.mark.parametrize("force_var", ["$xpuForce", "$cpuForce"])
+ def test_every_conditional_force_gate_reads_the_flag(self, force_var):
+ # The ROCm arm forces unconditionally, so only these two have a gate to miss.
+ assignments = [
+ line
+ for line in _SETUP_SRC.splitlines()
+ if f"{force_var} = " in line and "force-reinstall" in line
+ ]
+ assert assignments, f"no {force_var} assignment found"
+ guards = "\n".join(
+ line
+ for line in _SETUP_SRC.splitlines()
+ if f'{force_var} = @("--force-reinstall")' in line
+ )
+ assert "$script:TorchImportDefinitivelyFailed" in guards, (
+ f"{force_var} never forces on a definitively unimportable wheel, so the "
+ f"resolver keeps it: its on-disk tag is unchanged and the range is satisfied"
+ )
+
+ def test_the_rocm_arm_needs_no_gate(self):
+ rocm = _SETUP_SRC[_SETUP_SRC.index("if ($ROCmIndexUrl) {") :]
+ rocm = rocm[: rocm.index("if ($XpuIndexUrl) {")]
+ assert (
+ "--force-reinstall" in rocm and "$rocmForce" not in rocm
+ ), "the ROCm arm forces every time, so a broken wheel is already replaced there"
diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.py
index f184597568f..0a40d22c6e8 100644
--- a/tests/studio/test_xpu_triton_swap.py
+++ b/tests/studio/test_xpu_triton_swap.py
@@ -461,20 +461,40 @@ class TestADeadDriverIsNotAFlavourMismatch:
class TestPlatformGuards:
- @pytest.mark.parametrize("flag", ["NO_TORCH", "IS_MACOS", "IS_WINDOWS"])
+ @pytest.mark.parametrize("flag", ["NO_TORCH", "IS_MACOS"])
def test_skipped_where_it_does_not_apply(self, monkeypatch, tmp_path, flag):
- # Windows is setup.ps1's job; macOS has no XPU; --no-torch touches no wheels.
+ 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 performs the same swap after this file exits, and publishes the
+ # handover variable immediately before invoking it.
+ 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):
+ # Bare `python install_python_stack.py` on Windows has no setup.ps1 postlude, so
+ # the core install leaves triton-windows over torch's XPU triton. The absent
+ # handover variable is the signal that nobody else will fix it.
+ 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_both_repair_points():
- # The final repair pass would otherwise silently undo the first.
+
+def test_the_swap_is_wired_in_at_every_repair_point():
+ # The final repair pass would otherwise silently undo the first. The third point is
+ # step 13w, the Windows flavor invariant.
src = STACK.read_text(encoding = "utf-8")
- assert src.count(" _ensure_xpu_triton()") == 2
+ assert src.count(" _ensure_xpu_triton()") == 3
def test_the_swap_runs_after_every_torch_migration():
@@ -502,9 +522,14 @@ def test_the_swap_runs_after_every_torch_migration():
]
if "_ensure_xpu_triton" in calls:
blocks.append(calls)
- assert len(blocks) == 2, f"expected 2 repair blocks, found {len(blocks)}: {blocks}"
+ assert len(blocks) == 3, f"expected 3 repair blocks, found {len(blocks)}: {blocks}"
for calls in blocks:
assert calls[-1] == "_ensure_xpu_triton", calls
+ # Step 13w's migration is _ensure_expected_torch_flavor, which the walk above does
+ # not collect (its result is branched on, not discarded), so it is asserted on source.
+ 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",
@@ -512,6 +537,11 @@ def test_the_swap_runs_after_every_torch_migration():
"_ensure_cpu_torch",
):
assert calls.index(migration) < calls.index("_ensure_xpu_triton"), (migration, calls)
+ 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():