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: repair CPU torch on an NVIDIA host from the Linux fast path (#11127)

Daniel Han38d4a4869ad3
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 4443447870d..4a3b874e8ea 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -3885,7 +3885,7 @@ def _deliberate_cpu_torch() -> bool:
return _explicit_cpu_torch_index_pin() or _expected_torch_flavor_was_pinned("cpu")
-def _ensure_cuda_torch() -> None:
+def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
"""Repair a venv whose torch is a ROCm build on an NVIDIA host.
Counterpart to _ensure_rocm_torch. A venv poisoned by the pre-fix KFD
@@ -3897,6 +3897,9 @@ def _ensure_cuda_torch() -> None:
Also repairs a CUDA torch whose wheel family ships no kernels for the host's
GPUs (a pre-Turing box that the driver-only ladder sent to cu128/cu130).
Healthy CUDA torch and deliberate CPU-only torch are left untouched.
+
+ probe_only returns True where the repair would install and installs nothing, so the
+ fast-path escape that calls it cannot drift from what the repair actually does.
"""
# Respect install.sh's backend: only "" (standalone update) or "cuda" force CUDA wheels.
if _TORCH_BACKEND not in ("", "cuda"):
@@ -3932,6 +3935,8 @@ def _ensure_cuda_torch() -> None:
# reinstall an already-installed torch, so reinstall from the pin (self-resolving).
if not _cuda_pinned:
return
+ if probe_only:
+ return True
index_url = _detect_cuda_torch_index_url()
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
_safe_print(
@@ -4018,6 +4023,8 @@ def _ensure_cuda_torch() -> None:
else:
return # healthy CUDA torch matching the pin, or a deliberate CPU wheel
+ if probe_only:
+ return True
if index_url is None:
index_url = _detect_cuda_torch_index_url()
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
@@ -5181,6 +5188,21 @@ def _missing_torch_needs_dependency_pass() -> bool:
return False
+def _cuda_torch_needs_dependency_pass() -> bool:
+ """Return True when only the dependency pass can put CUDA torch back on this host.
+
+ The repair lives inside that pass, so an install whose GPU was hidden (or whose driver
+ was broken) at install time keeps its CPU wheel on every "up to date" update until the
+ package version happens to move. Answered by the repair in probe mode, so the two can
+ never disagree; Windows heals this at setup.ps1's stale-venv check and macOS has no
+ CUDA, and the repair already excludes both. Never installs, and fails closed.
+ """
+ try:
+ return bool(_ensure_cuda_torch(probe_only = True))
+ except Exception: # noqa: BLE001 - a probe that cannot answer keeps the fast path
+ return False
+
+
def _amd_torch_needs_dependency_pass() -> bool:
"""Return True when setup must run the dependency pass to repair non-ROCm torch.
@@ -11158,6 +11180,9 @@ if __name__ == "__main__":
f"probe={_TORCH_RUNTIME_PROBE!r}"
)
sys.exit(0 if _needs_pass else 1)
+ if sys.argv[1:] == ["--cuda-torch-needs-dependency-pass"]:
+ # Exit 0 forces the dependency pass; exit 1 keeps the fast path.
+ sys.exit(0 if _cuda_torch_needs_dependency_pass() else 1)
if sys.argv[1:] == ["--missing-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _missing_torch_needs_dependency_pass() else 1)
diff --git a/studio/setup.sh b/studio/setup.sh
index 243023efdb0..b2f7bfa7b05 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -2590,6 +2590,32 @@ if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
fi
fi
+# Same for an NVIDIA host left on a CPU wheel (GPU hidden or driver broken when it was
+# installed, a dependency step that resolved torch from PyPI, or a GPU added since). The
+# CUDA repair is inside the pass too, so without this the wheel survives every "up to
+# date" update. setup.ps1 heals this at its stale-venv check; this is the POSIX half.
+if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
+ _setup_cuda_torch_stale=false
+ if command -v timeout >/dev/null 2>&1; then
+ timeout -k 5 180 "$VENV_DIR/bin/python" \
+ "$SCRIPT_DIR/install_python_stack.py" --cuda-torch-needs-dependency-pass \
+ >/dev/null 2>&1 && _setup_cuda_torch_stale=true
+ elif "$VENV_DIR/bin/python" "$SCRIPT_DIR/install_python_stack.py" \
+ --cuda-torch-needs-dependency-pass >/dev/null 2>&1; then
+ _setup_cuda_torch_stale=true
+ fi
+ if [ "$_setup_cuda_torch_stale" = true ]; then
+ # Offline the pass can only fail, and failing it loses the verified install.
+ if [ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; then
+ substep "installed PyTorch cannot use this NVIDIA GPU but UV_OFFLINE is set -- left for the next online update"
+ else
+ substep "installed PyTorch cannot use this NVIDIA GPU -- forcing dependency pass to repair..."
+ substep " (set UNSLOTH_TORCH_BACKEND=cpu to keep a deliberate CPU install)"
+ _SKIP_PYTHON_DEPS=false
+ fi
+ fi
+fi
+
if [ "$_SKIP_PYTHON_DEPS" = false ]; then
install_python_stack
else
diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.py
index f06566103be..985edde47e1 100644
--- a/tests/python/test_cross_platform_parity.py
+++ b/tests/python/test_cross_platform_parity.py
@@ -303,7 +303,7 @@ class TestTorchIndexOverrideParity:
# A pinned cu* index skips ALL host-GPU probing, so the CUDA repair must clear the
# CUDA_VISIBLE_DEVICES hide gate too (else the GPU-less CI case bails).
text = STACK_PY.read_text(encoding = "utf-8")
- m = re.search(r"def _ensure_cuda_torch\(\).*?(?=\ndef )", text, re.DOTALL)
+ m = re.search(r"def _ensure_cuda_torch\(.*?(?=\ndef )", text, re.DOTALL)
assert m, "could not locate _ensure_cuda_torch"
body = m.group(0)
assert "_cuda_pinned" in body, (
diff --git a/tests/sh/test_setup_cuda_fastpath_escape.sh b/tests/sh/test_setup_cuda_fastpath_escape.sh
new file mode 100755
index 00000000000..0850e1baf6d
--- /dev/null
+++ b/tests/sh/test_setup_cuda_fastpath_escape.sh
@@ -0,0 +1,110 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# Test setup.sh wiring for the CUDA escape: exit 0 forces the pass, every other status keeps it.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+. "$SCRIPT_DIR/_harness.sh"
+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"
+WORK=$(mktemp -d)
+trap 'rm -rf "$WORK"' EXIT
+# The CUDA escape block only: several blocks share this guard, so keep the one holding the flag.
+awk '/^if \[ "\$_SKIP_PYTHON_DEPS" = true \] && \[ -x "\$VENV_DIR\/bin\/python" \]; then/ {
+ block = $0; on = 1; next
+ }
+ on { block = block "\n" $0 }
+ on && /^fi$/ { on = 0; if (block ~ /--cuda-torch-needs-dependency-pass/) { print block; exit } }
+ ' "$SETUP_SH" > "$WORK/escape.sh"
+grep -q -- "--cuda-torch-needs-dependency-pass" "$WORK/escape.sh" || {
+ echo "FATAL: CUDA escape block not found in $SETUP_SH" >&2; exit 1; }
+
+VENV_DIR="$WORK/venv"
+mkdir -p "$VENV_DIR/bin"
+: > "$WORK/install_python_stack.py"
+
+# A stand-in interpreter that records its arguments and exits with $PROBE_RC.
+cat > "$VENV_DIR/bin/python" <<'STUB'
+#!/bin/sh
+printf '%s\n' "$*" >> "$PROBE_LOG"
+exit "$PROBE_RC"
+STUB
+chmod +x "$VENV_DIR/bin/python"
+
+# The real offline predicate, extracted the way the other setup.sh harnesses do.
+sed -n '/^_uv_offline_requested()/,/^}/p' "$SETUP_SH" > "$WORK/offline.sh"
+
+run_escape() {
+ (
+ PROBE_RC="$1"
+ _SKIP_PYTHON_DEPS="${2:-true}"
+ _OFFLINE_FAST_PATH="${_OFFLINE_FAST_PATH:-false}"
+ export PROBE_RC PROBE_LOG
+ SCRIPT_DIR="$WORK"
+ substep() { printf '%s\n' "$1" >> "$SUBSTEP_LOG"; }
+ # shellcheck disable=SC1090
+ . "$WORK/offline.sh"
+ # shellcheck disable=SC1090
+ . "$WORK/escape.sh"
+ echo "$_SKIP_PYTHON_DEPS"
+ )
+}
+
+PROBE_LOG="$WORK/calls.txt"
+SUBSTEP_LOG="$WORK/substeps.txt"
+: > "$PROBE_LOG"
+: > "$SUBSTEP_LOG"
+export PROBE_LOG SUBSTEP_LOG
+
+echo "=== only a conclusive answer forces the pass ==="
+assert_eq "exit 0 forces the dependency pass" "false" "$(run_escape 0)"
+assert_eq "exit 1 keeps the fast path" "true" "$(run_escape 1)"
+
+echo "=== every probe failure keeps the fast path ==="
+# Probe errors keep the fast path, including the deadline: 124 on GNU, 143 on BusyBox.
+for rc in 2 124 125 126 127 137 143; do
+ assert_eq "exit $rc keeps the fast path" "true" "$(run_escape "$rc")"
+done
+
+echo "=== the fallback branch, on hosts without timeout ==="
+# PATH holds only the stub bin, so `command -v timeout` fails and the elif runs.
+run_no_timeout() { (PATH="$VENV_DIR/bin"; run_escape "$1"); }
+assert_eq "exit 0 forces the pass without timeout" "false" "$(run_no_timeout 0)"
+assert_eq "exit 1 keeps the fast path without timeout" "true" "$(run_no_timeout 1)"
+: > "$PROBE_LOG"
+run_no_timeout 0 >/dev/null
+assert_eq "and still probes exactly once" "1" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+
+echo "=== the block does nothing it was not asked to ==="
+assert_eq "a pass already forced is left forced" "false" "$(run_escape 1 false)"
+assert_eq "and the probe is not run at all in that case" \
+ "0" "$(: > "$PROBE_LOG"; run_escape 1 false >/dev/null; wc -l < "$PROBE_LOG" | tr -d ' ')"
+: > "$PROBE_LOG"
+run_escape 0 >/dev/null
+assert_eq "the probe is asked exactly once" "1" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+assert_eq "with the module and the flag, and nothing else" \
+ "$WORK/install_python_stack.py --cuda-torch-needs-dependency-pass" \
+ "$(cat "$PROBE_LOG")"
+
+echo "=== a missing interpreter is not probed ==="
+mv "$VENV_DIR/bin/python" "$WORK/python.away"
+: > "$PROBE_LOG"
+assert_eq "no venv python keeps the fast path" "true" "$(run_escape 0)"
+assert_eq "and spawns nothing" "0" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+mv "$WORK/python.away" "$VENV_DIR/bin/python"
+
+echo "=== offline, where the forced pass could only fail ==="
+: > "$SUBSTEP_LOG"
+assert_eq "UV_OFFLINE keeps the fast path" "true" "$(UV_OFFLINE=1 run_escape 0)"
+assert_eq "and says why" "1" \
+ "$(grep -c "UV_OFFLINE is set -- left for the next online update" "$SUBSTEP_LOG")"
+assert_eq "an offline fast path keeps it too" "true" \
+ "$(_OFFLINE_FAST_PATH=true run_escape 0)"
+: > "$SUBSTEP_LOG"
+assert_eq "and online still forces the pass" "false" "$(UV_OFFLINE=0 run_escape 0)"
+assert_eq "with the repair line, not the deferral" "1" \
+ "$(grep -c "forcing dependency pass to repair" "$SUBSTEP_LOG")"
+
+echo ""
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/tests/studio/install/test_cuda_repair.py b/tests/studio/install/test_cuda_repair.py
index 26ac1b5099b..3d39b03ac79 100644
--- a/tests/studio/install/test_cuda_repair.py
+++ b/tests/studio/install/test_cuda_repair.py
@@ -120,6 +120,7 @@ def _run_cuda_repair(
cvd = None,
index_family = None,
index_url = None,
+ probe = False,
):
"""Invoke _ensure_cuda_torch under a fully mocked host; return the pip mock.
@@ -173,7 +174,12 @@ def _run_cuda_repair(
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_FAMILY", None)
if index_url is None:
stack_mod.os.environ.pop("UNSLOTH_TORCH_INDEX_URL", None)
- _ensure_cuda_torch()
+ # probe asks setup.sh's fast-path question instead. Carried on the pip mock so the
+ # scenarios above keep their single return value.
+ if probe:
+ mock_pip.probe_answer = stack_mod._cuda_torch_needs_dependency_pass()
+ else:
+ _ensure_cuda_torch()
return mock_pip
@@ -2726,3 +2732,41 @@ def test_detect_index_url_reads_a_localized_nvidia_smi_banner(monkeypatch, tmp_p
lambda name, *a, **k: "nvidia-smi" if name == "nvidia-smi" else None,
)
assert _detect_cuda_torch_index_url() == f"{stack_mod._PYTORCH_WHL_BASE}/cu130"
+
+
+# setup.sh's fast path skips the dependency pass whole, so the repair above is unreachable on an
+# "up to date" install. --cuda-torch-needs-dependency-pass forces the pass, and answers by asking
+# the repair itself: these assert the two cannot drift apart.
+class TestTheFastPathProbeAgreesWithTheRepair:
+ SCENARIOS = {
+ "cpu wheel on an NVIDIA host": dict(torch_state = "cpu"),
+ "rocm wheel on an NVIDIA host": dict(torch_state = "hip"),
+ "healthy cuda wheel": dict(torch_state = "cuda", cuda_version = "12.8"),
+ "deliberate cpu backend": dict(torch_state = "cpu", backend = "cpu"),
+ "the GPU is masked away": dict(torch_state = "cpu", cvd = ""),
+ "no NVIDIA GPU": dict(torch_state = "cpu", nvidia = False),
+ "a no-torch install": dict(torch_state = "cpu", no_torch = True),
+ "windows, where setup.ps1 owns torch": dict(torch_state = "cpu", is_windows = True),
+ "macos": dict(torch_state = "cpu", is_macos = True),
+ "a deliberate rocm install": dict(torch_state = "hip", rocm_marker = True),
+ }
+
+ @pytest.mark.parametrize("name", sorted(SCENARIOS))
+ def test_the_probe_answers_what_the_repair_would_do(self, name):
+ scenario = self.SCENARIOS[name]
+ repaired = _run_cuda_repair(**scenario).call_count == 1
+ probe = _run_cuda_repair(**scenario, probe = True)
+ assert probe.probe_answer is repaired
+ # A probe that installs would download multi-gigabyte wheels from a fast path.
+ assert probe.call_count == 0
+
+ def test_at_least_one_scenario_answers_each_way(self):
+ answers = {
+ _run_cuda_repair(**scenario, probe = True).probe_answer
+ for scenario in self.SCENARIOS.values()
+ }
+ assert answers == {True, False}
+
+ def test_a_probe_that_cannot_answer_keeps_the_fast_path(self):
+ with patch.object(stack_mod, "_ensure_cuda_torch", side_effect = OSError("no")):
+ assert stack_mod._cuda_torch_needs_dependency_pass() is False