Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: reinstall a missing PyTorch when unsloth studio update finds the package current (#10956)
oobabooga9f8e13cf1a37
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex a39b715b431..0adf6fa9d8f 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -4993,6 +4993,36 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:return _warn_wrong_flavor(expected, _now)+def _missing_torch_needs_dependency_pass() -> bool:+ """Missing torch that the dependency pass can actually reinstall, read from metadata.++ Gated on a live core requirement, so Apple Silicon (unsloth-zoo's torch marker is+ false there) does not run a useless pass on every update.+ """+ if NO_TORCH or _installed_distribution_version("torch") is not None:+ return False+ try:+ from importlib.metadata import PackageNotFoundError, requires+ from packaging.requirements import Requirement+ except ImportError:+ return False+ for package in _core_package_names(os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")):+ try:+ lines = requires(package) or []+ except PackageNotFoundError:+ continue+ for line in lines:+ try:+ req = Requirement(line)+ except Exception: # noqa: BLE001 - ignore malformed requirements+ continue+ if req.name.lower() == "torch" and (+ req.marker is None or req.marker.evaluate({"extra": ""})+ ):+ return True+ return False++def _amd_torch_needs_dependency_pass() -> bool:"""Return True when setup must run the dependency pass to repair non-ROCm torch.@@ -10177,6 +10207,9 @@ if __name__ == "__main__":f"probe={_TORCH_RUNTIME_PROBE!r}")sys.exit(0 if _needs_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)if any(_arg.startswith("-") for _arg in sys.argv[1:]):# Never let a malformed probe call fall through into a multi-gigabyte install._safe_print(f"Unknown argument: {' '.join(sys.argv[1:])}")diff --git a/studio/setup.sh b/studio/setup.shindex 5bcf5f46c20..6b55102b3ce 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -1932,6 +1932,29 @@ sys.exit(0 if windows and installed not in windows[0] else 1)substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..."_SKIP_PYTHON_DEPS=falsefi+ # Failures and timeouts keep the fast path, as for the ROCm probe below.+ _fpe_missing_torch=false+ if command -v timeout >/dev/null 2>&1; then+ timeout -k 5 180 "$VENV_DIR/bin/python" \+ "$SCRIPT_DIR/install_python_stack.py" --missing-torch-needs-dependency-pass \+ >/dev/null 2>&1 && _fpe_missing_torch=true+ elif "$VENV_DIR/bin/python" "$SCRIPT_DIR/install_python_stack.py" \+ --missing-torch-needs-dependency-pass >/dev/null 2>&1; then+ _fpe_missing_torch=true+ fi+ if [ "$_fpe_missing_torch" = 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+ # Silent once another escape forced the pass: torch comes back with it.+ if [ "$_SKIP_PYTHON_DEPS" = true ]; then+ substep "PyTorch is not installed but UV_OFFLINE is set -- left for the next online update"+ fi+ else+ substep "PyTorch is not installed -- forcing dependency pass to reinstall it..."+ _SKIP_PYTHON_DEPS=false+ fi+ fi+ unset _fpe_missing_torch# If the desktop app specifies a minimum required backend version and the installed# package is older than that requirement, force the dependency pass to upgrade it.if [ -n "${UNSLOTH_DESKTOP_BACKEND_VERSION:-}" ]; thendiff --git a/tests/sh/test_setup_missing_torch_fastpath_escape.sh b/tests/sh/test_setup_missing_torch_fastpath_escape.shnew file mode 100755index 00000000000..aa5119e3613--- /dev/null+++ b/tests/sh/test_setup_missing_torch_fastpath_escape.sh@@ -0,0 +1,88 @@+#!/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's handling of the missing-torch probe's exit status.+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++# Exercise the helper shared by online and offline updates.+awk '/^_fast_path_escapes\(\) \{/ {on=1} on {print} on && /^}/ {exit}' "$SETUP_SH" > "$WORK/escapes.sh"+grep -q -- "--missing-torch-needs-dependency-pass" "$WORK/escapes.sh" || {+ echo "FATAL: the missing-torch escape is not in _fast_path_escapes in $SETUP_SH" >&2; exit 1; }++VENV_DIR="$WORK/venv"+mkdir -p "$VENV_DIR/bin"+: > "$WORK/install_python_stack.py"++# Record the probe and return $PROBE_RC; other checks report no repair needed.+cat > "$VENV_DIR/bin/python" <<'STUB'+#!/bin/sh+case "$*" in+ *--missing-torch-needs-dependency-pass*) printf '%s\n' "$*" >> "$PROBE_LOG"; exit "$PROBE_RC" ;;+esac+exit 1+STUB+chmod +x "$VENV_DIR/bin/python"++PROBE_LOG="$WORK/calls.txt"+export PROBE_LOG++run_escapes() {+ (+ PROBE_RC="$1"+ _SKIP_PYTHON_DEPS="${2:-true}"+ _OFFLINE_FAST_PATH="${3:-false}"+ _UV_OFFLINE="${4:-false}"+ export PROBE_RC+ SCRIPT_DIR="$WORK"+ unset UNSLOTH_STUDIO_FULL_DEPS UNSLOTH_DESKTOP_BACKEND_VERSION \+ UNSLOTH_TORCH_INDEX_URL UNSLOTH_TORCH_INDEX_FAMILY+ SUBSTEPS=""+ substep() { SUBSTEPS="$SUBSTEPS|$1"; }+ # Stubbed like substep: awk lifts _fast_path_escapes alone out of setup.sh.+ _uv_offline_requested() { [ "$_UV_OFFLINE" = true ]; }+ # shellcheck disable=SC1090+ . "$WORK/escapes.sh"+ _fast_path_escapes+ echo "$_SKIP_PYTHON_DEPS$SUBSTEPS"+ )+}++echo "=== only a conclusive answer forces the pass ==="+assert_eq "exit 0 forces the dependency pass, and says why" \+ "false|PyTorch is not installed -- forcing dependency pass to reinstall it..." "$(run_escapes 0)"+assert_eq "exit 1 keeps the fast path silently" "true" "$(run_escapes 1)"++echo "=== a probe that cannot answer keeps the fast path ==="+# 2 is an unknown flag: an older install_python_stack.py beside a newer setup.sh.+for rc in 2 126 127 137; do+ assert_eq "exit $rc keeps the fast path" "true" "$(run_escapes "$rc")"+done++echo "=== the probe is asked once, with the module and the flag ==="+: > "$PROBE_LOG"+run_escapes 1 >/dev/null+assert_eq "one call" "1" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"+assert_eq "exactly that call" \+ "$WORK/install_python_stack.py --missing-torch-needs-dependency-pass" "$(cat "$PROBE_LOG")"++echo "=== a pass another escape already forced stays forced ==="+assert_eq "exit 1 does not undo it" "false" "$(run_escapes 1 false)"++echo "=== offline defers the repair, because the pass can only download torch ==="+_deferred="true|PyTorch is not installed but UV_OFFLINE is set -- left for the next online update"+assert_eq "the offline keep defers it" "$_deferred" "$(run_escapes 0 true true false)"+assert_eq "UV_OFFLINE alone defers it" "$_deferred" "$(run_escapes 0 true false true)"+assert_eq "neither set still forces it" \+ "false|PyTorch is not installed -- forcing dependency pass to reinstall it..." \+ "$(run_escapes 0 true false false)"+assert_eq "offline does not undo a pass another escape forced" "false" "$(run_escapes 0 false true false)"++echo ""+echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ]diff --git a/tests/studio/install/test_missing_torch_fastpath_probe.py b/tests/studio/install/test_missing_torch_fastpath_probe.pynew file mode 100644index 00000000000..8a0fe83b81b--- /dev/null+++ b/tests/studio/install/test_missing_torch_fastpath_probe.py@@ -0,0 +1,120 @@+# 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 the missing-torch CLI probe in isolated venvs with synthetic metadata."""++from __future__ import annotations++import os+import subprocess+import sys+import venv+from pathlib import Path++import packaging+import pytest++PACKAGE_ROOT = Path(__file__).resolve().parents[3]+_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"+_FLAG = "--missing-torch-needs-dependency-pass"+++def _site_packages(root: Path) -> Path:+ if sys.platform == "win32":+ return root / "Lib" / "site-packages"+ return (+ root / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "site-packages"+ )+++def _python(root: Path) -> Path:+ return root / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+++def _dist(root: Path, name: str, version: str, *requires: str) -> None:+ info = _site_packages(root) / f"{name.replace('-', '_')}-{version}.dist-info"+ info.mkdir(parents = True)+ lines = ["Metadata-Version: 2.1", f"Name: {name}", f"Version: {version}"]+ lines += [f"Requires-Dist: {req}" for req in requires]+ (info / "METADATA").write_text("\n".join(lines) + "\n", encoding = "utf-8")+++def studio_venv(tmp_path):+ """Expose only packaging from the host, keeping its torch out of the test venv."""+ root = tmp_path / "venv"+ venv.EnvBuilder(with_pip = False).create(root)+ shim = tmp_path / "shim"+ shim.mkdir()+ (shim / "packaging").symlink_to(Path(packaging.__file__).parent, target_is_directory = True)+ return root, shim+++def _probe(studio_venv, **env) -> int:+ root, shim = studio_venv+ child_env = {+ k: v+ for k, v in os.environ.items()+ if k not in ("UNSLOTH_NO_TORCH", "STUDIO_PACKAGE_NAME", "PYTHONHOME")+ }+ child_env["PYTHONPATH"] = str(shim)+ child_env.update(env)+ result = subprocess.run(+ [str(_python(root)), str(_STACK_PATH), _FLAG],+ env = child_env,+ capture_output = True,+ text = True,+ timeout = 120,+ )+ # A crash also exits 1, which would read as "keep the fast path".+ assert "Traceback" not in result.stderr, result.stderr+ return result.returncode+++TORCH_ON_EVERY_PLATFORM = "torch<2.13.0,>=2.4.0"++[email protected](sys.platform == "win32", reason = "setup.sh is the only caller")+class TestMissingTorchProbe:+ def test_core_package_requires_torch_and_none_is_installed_forces_the_pass(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", TORCH_ON_EVERY_PLATFORM)+ _dist(studio_venv[0], "unsloth-zoo", "2026.9.3")+ assert _probe(studio_venv) == 0++ def test_an_installed_torch_keeps_the_fast_path(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", TORCH_ON_EVERY_PLATFORM)+ _dist(studio_venv[0], "torch", "2.12.1+cu130")+ assert _probe(studio_venv) == 1++ def test_the_requirement_through_unsloth_zoo_counts(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4")+ _dist(studio_venv[0], "unsloth-zoo", "2026.9.3", TORCH_ON_EVERY_PLATFORM)+ assert _probe(studio_venv) == 0++ def test_a_platform_the_core_packages_do_not_need_torch_on_keeps_the_fast_path(+ self, studio_venv+ ):+ _dist(studio_venv[0], "unsloth", "2026.9.4", 'torch>=2.4.0; sys_platform == "no-such-os"')+ assert _probe(studio_venv) == 1++ def test_a_torch_behind_an_extra_keeps_the_fast_path(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", 'torch>=2.4.0; extra == "intelgpu"')+ assert _probe(studio_venv) == 1++ def test_a_recorded_no_torch_install_keeps_the_fast_path(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", TORCH_ON_EVERY_PLATFORM)+ (studio_venv[0] / ".unsloth-no-torch").write_text("", encoding = "utf-8")+ assert _probe(studio_venv) == 1++ def test_unsloth_no_torch_keeps_the_fast_path(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", TORCH_ON_EVERY_PLATFORM)+ assert _probe(studio_venv, UNSLOTH_NO_TORCH = "1") == 1++ def test_a_custom_package_is_read_instead_of_unsloth(self, studio_venv):+ _dist(studio_venv[0], "unsloth", "2026.9.4", TORCH_ON_EVERY_PLATFORM)+ _dist(studio_venv[0], "my-unsloth", "1.0", TORCH_ON_EVERY_PLATFORM)+ assert _probe(studio_venv, STUDIO_PACKAGE_NAME = "my-unsloth") == 0+ assert _probe(studio_venv, STUDIO_PACKAGE_NAME = "other-package") == 1++ def test_no_core_package_keeps_the_fast_path(self, studio_venv):+ assert _probe(studio_venv) == 1