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: torch 2.13 for new Linux cu130 Python 3.13 installs, existing installs keep their torch (#12150)

Daniel Haneaef459e86fb
diff --git a/install.sh b/install.sh
index dbaa864ab1d..016d08b757c 100755
--- a/install.sh
+++ b/install.sh
@@ -4153,6 +4153,8 @@ mkdir -p "$STUDIO_HOME"
_MIGRATED=false
# Empty so an inherited value can never masquerade as a probed torch version.
_PREV_TORCH_VER=""
+# Any earlier environment in this home, readable or not: only a home without one takes a new-install torch default.
+_EXISTING_INSTALL=false
# Replace occupied venvs even when bin/python is missing or dangling, as in the repair loop reported in #9479.
if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
@@ -4166,6 +4168,7 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
echo " Move it aside or choose an empty UNSLOTH_STUDIO_HOME." >&2
exit 1
fi
+ _EXISTING_INSTALL=true
# Record the existing venv's torch BEFORE the replacement moves it aside: a re-run rebuilds the venv for clean state, but must keep the torch release the user already has. Last line only, so sitecustomize or import-hook noise on stdout cannot corrupt the version. Disk first, no interpreter: `import torch` can block forever on a wedged Intel driver, and this runs before setup.sh's bounded probes. version.py carries the same label; the interpreter stays as the fallback for a layout without one.
_PREV_TORCH_VER=""
for _prev_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
@@ -4191,6 +4194,12 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
elif [ "$_STUDIO_HOME_REDIRECT" != "env" ] && [ -x "$STUDIO_HOME/.venv/bin/python" ]; then
# Old layout: validate before migrating (env-mode skips it); no-torch checks Python only.
substep "found legacy Unsloth environment, validating..."
+ _EXISTING_INSTALL=true
+ for _prev_tv in "$STUDIO_HOME"/.venv/lib/python*/site-packages/torch/version.py; do
+ [ -f "$_prev_tv" ] || continue
+ _PREV_TORCH_VER=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_prev_tv" | head -n 1)
+ break
+ done
_legacy_ok=false
if [ "$SKIP_TORCH" = true ]; then
if "$STUDIO_HOME/.venv/bin/python" -c "import sys; print(sys.executable)" >/dev/null 2>&1; then
@@ -4226,6 +4235,14 @@ torch.testing.assert_close(torch.unique(E), torch.tensor((20,), device=E.device,
_invalid_venv="$STUDIO_HOME/.venv.invalid.$(date +%Y%m%d%H%M%S 2>/dev/null || echo time).$$"
mv "$STUDIO_HOME/.venv" "$_invalid_venv" 2>/dev/null || true
fi
+elif [ "$_STUDIO_HOME_REDIRECT" != "env" ] && _dir_has_entries "$STUDIO_HOME/.venv"; then
+ # A legacy .venv whose interpreter is missing or dangling is still an earlier install: keep the old torch range, not the new-install one.
+ _EXISTING_INSTALL=true
+ for _prev_tv in "$STUDIO_HOME"/.venv/lib/python*/site-packages/torch/version.py; do
+ [ -f "$_prev_tv" ] || continue
+ _PREV_TORCH_VER=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_prev_tv" | head -n 1)
+ break
+ done
fi
if [ "$SKIP_TORCH" = true ] && [ "$MAC_INTEL" = true ] && [ -z "$_USER_PYTHON" ] && [ -x "$VENV_DIR/bin/python" ]; then
@@ -4447,6 +4464,8 @@ fi
# Companions bounded to torch's window: torchaudio 2.11 dropped its torch pin, so it can drift.
TORCHVISION_CONSTRAINT="torchvision>=0.19,<${_TORCHVISION_CEILING}"
TORCHAUDIO_CONSTRAINT="torchaudio>=2.4,<${_TORCHAUDIO_CEILING}"
+_CU130_TORCH_CEILING="2.15.0"
+_CU130_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"
# ── Resolve repo root (for --local installs) ──
_REPO_ROOT="$(cd "$(dirname "$0" 2>/dev/null || echo ".")" && pwd)"
@@ -6005,12 +6024,77 @@ _torch_release_in_window() {
echo "no"
}
+# "yes" when $1 is the cu130 index on Linux/WSL x86_64 with a Python 3.13 venv: the only route the torch 2.13/2.14 prebuilt wheels cover.
+_cu130_torch213_route() {
+ [ "$(_cu130_torch213_platform "$1")" = "yes" ] || { echo "no"; return; }
+ _pypi_unsloth_admits_torch "2.13.0"
+}
+
+# The local half of the route, with no network: it alone decides the preservation window, so a
+# PyPI outage on a re-run can never shrink it and downgrade an existing 2.13/2.14 install.
+_cu130_torch213_platform() {
+ [ "$(_torch_index_url_leaf "$1")" = "cu130" ] || { echo "no"; return; }
+ case "$OS" in linux|wsl) ;; *) echo "no"; return ;; esac
+ case "$_ARCH" in x86_64|amd64) ;; *) echo "no"; return ;; esac
+ _ctr_py=$("$VENV_DIR/bin/python" -c "import sys; print('%d.%d' % sys.version_info[:2])" 2>/dev/null || echo "")
+ [ "$_ctr_py" = "3.13" ] && echo "yes" || echo "no"
+}
+
+# "yes" only when the newest unsloth on PyPI admits torch $1: `studio update` runs the INSTALLED release's setup,
+# which re-resolves under its own cap and would downgrade a newer torch. Any failure answers "no", as does anything
+# making public PyPI's newest release not what uv will pick: an upload cutoff, offline mode, another package index.
+_pypi_unsloth_admits_torch() {
+ _pua_off=$(printf '%s' "${UV_OFFLINE:-}" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
+ case "$_pua_off" in 1|t|true|y|yes|on) echo "no"; return ;; esac
+ if [ -n "${UV_EXCLUDE_NEWER:-}${UV_EXCLUDE_NEWER_PACKAGE:-}" ] || _mirror_configured uv; then
+ echo "no"
+ return
+ fi
+ _pua_url="${UNSLOTH_PYPI_JSON_URL:-https://pypi.org/pypi/unsloth/json}"
+ _pua_out=$(_run_bounded --secs 20 "$VENV_DIR/bin/python" - "$_pua_url" "$1" 2>/dev/null <<'PY' || true
+import json, re, sys, urllib.request
+url, want = sys.argv[1], sys.argv[2]
+def rel(v):
+ return tuple(int(x) for x in re.findall(r"\d+", v)[:3]) + (0,) * (3 - len(re.findall(r"\d+", v)[:3]))
+try:
+ with urllib.request.urlopen(url, timeout = 15) as r:
+ reqs = json.load(r)["info"].get("requires_dist") or []
+ specs = [q for q in reqs if re.match(r"^torch\s*[<>=!~(]", q) and "extra ==" not in q]
+ if len(specs) != 1:
+ raise ValueError(specs)
+ ops = {"<": lambda a, b: a < b, "<=": lambda a, b: a <= b, ">": lambda a, b: a > b,
+ ">=": lambda a, b: a >= b, "==": lambda a, b: a == b, "!=": lambda a, b: a != b}
+ body = specs[0].split(";", 1)[0][len("torch"):].strip().strip("()")
+ ok = True
+ for part in filter(None, (p.strip() for p in body.split(","))):
+ m = re.fullmatch(r"(<=|>=|==|!=|<|>)\s*([0-9][0-9.]*)", part)
+ if m is None:
+ raise ValueError(part)
+ ok = ok and ops[m.group(1)](rel(want), rel(m.group(2)))
+ print("yes" if ok else "no")
+except Exception:
+ print("no")
+PY
+)
+ [ "$(printf '%s' "$_pua_out" | tail -n 1)" = "yes" ] && echo "yes" || echo "no"
+}
+
+# torchaudio 2.11 is the last release (stable ABI), so newer torch minors pair with it.
+_torchaudio_for_torch_minor() {
+ if [ "$1" -ge 12 ] 2>/dev/null; then
+ echo "torchaudio==2.11.*"
+ else
+ echo "torchaudio==2.$1.*"
+ fi
+}
+
# Keep the previous torch RELEASE when inside the window; UNSLOTH_TORCH_UPGRADE=1 opts out.
_previous_torch_pin() {
_ptp_ver="$1"
_ptp_con="$2"
[ -n "$_ptp_ver" ] || { echo ""; return; }
- [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] && { echo ""; return; }
+ # $3 = keep: an upgrade with no newer release to move to still keeps the resident one.
+ [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] && [ "${3:-}" != "keep" ] && { echo ""; return; }
_ptp_base="${_ptp_ver%%+*}"
# Base must be a plain numeric release; nightly/dev builds never become a pin.
case "$_ptp_base" in
@@ -6073,7 +6157,7 @@ _install_torch_default_index() {
case "$_itdi_base" in
2.*)
_itdi_tv="torchvision==0.$((_itdi_minor + 15)).*"
- _itdi_ta="torchaudio==2.${_itdi_minor}.*"
+ _itdi_ta=$(_torchaudio_for_torch_minor "$_itdi_minor")
;;
esac
if ! run_install_cmd_retry "install PyTorch (kept release)" uv pip install --python "$_VENV_PY" "$(_torch_spec_with_extra "$TORCH_CONSTRAINT")" "$(_torch_spec_with_extra "$_itdi_tv")" "$_itdi_ta" \
@@ -7029,16 +7113,40 @@ case "$_torch_index_leaf" in
;;
esac
fi # _torch_index_pinned guard (Radeon + Strix reroute)
+# Only this route has prebuilt kernel wheels for torch 2.13/2.14 (prebuilt-wheels-cu13, cp313), so new installs get 2.13;
+# preservation keeps a wider window so an existing 2.4-2.14 install stays on its release.
+_PRESERVE_TORCH_CONSTRAINT="$TORCH_CONSTRAINT"
+_CU130_NEW_INSTALL_ROUTE=false
+if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL")" = "yes" ]; then
+ _PRESERVE_TORCH_CONSTRAINT="torch>=2.4,<${_CU130_TORCH_CEILING}"
+ # An existing home never takes 2.13 unasked, even when its torch could not be read or kept.
+ if { [ "$_EXISTING_INSTALL" = false ] || [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ]; } \
+ && [ "$(_pypi_unsloth_admits_torch "2.13.0")" = "yes" ]; then
+ _CU130_NEW_INSTALL_ROUTE=true
+ fi
+fi
_PREV_TORCH_PIN=""
+# The pre-route default: a kept release that fails to reinstall falls back here, never to 2.13.
_PREV_FALLBACK_CONSTRAINT="$TORCH_CONSTRAINT"
if [ "$SKIP_TORCH" = false ]; then
- _prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$TORCH_CONSTRAINT")
+ _prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT")
+ # UNSLOTH_TORCH_UPGRADE=1 (Settings > Repair) with the 2.13 route closed (PyPI unreachable, a
+ # mirror, an older release) must not move a resident release above the default range down.
+ if [ -z "$_prev_pin" ] && [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] \
+ && [ "$_CU130_NEW_INSTALL_ROUTE" = false ] && [ -n "$_PREV_TORCH_VER" ] \
+ && [ "$(_torch_release_in_window "${_PREV_TORCH_VER%%+*}" "$TORCH_CONSTRAINT")" != "yes" ]; then
+ _prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT" keep)
+ fi
if [ -n "$_prev_pin" ]; then
_PREV_TORCH_PIN="$_prev_pin"
TORCH_CONSTRAINT="$_prev_pin"
substep "existing install has torch $_PREV_TORCH_VER -- keeping it (set UNSLOTH_TORCH_UPGRADE=1 to get the newest release)"
fi
fi
+if [ -z "$_PREV_TORCH_PIN" ] && [ "$_CU130_NEW_INSTALL_ROUTE" = true ]; then
+ TORCH_CONSTRAINT="$_CU130_NEW_INSTALL_TORCH"
+ TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"
+fi
_TAURI_TORCH_INDEX_FAMILY=$(_tauri_torch_index_family "$TORCH_INDEX_URL")
if [ "$_amd_gpu_radeon" = true ] && [ "$SKIP_TORCH" = false ]; then
diff --git a/studio/backend/tests/test_cu130_repair_torch_specs.py b/studio/backend/tests/test_cu130_repair_torch_specs.py
new file mode 100644
index 00000000000..47b6933f29e
--- /dev/null
+++ b/studio/backend/tests/test_cu130_repair_torch_specs.py
@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`studio update` torch repairs on the cu130 torch 2.13 route keep the resident release.
+
+install.sh gives new Linux x86_64 cu130 Python 3.13 installs torch 2.13; a repair on that
+route must not move an existing install to another torch, and every other route must get
+exactly the specs it got before.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_INSTALL_SCRIPT = Path(__file__).resolve().parents[2] / "install_python_stack.py"
+CU130 = "https://download.pytorch.org/whl/cu130"
+
+
+def mod(monkeypatch):
+ sys.modules.pop("install_python_stack", None)
+ monkeypatch.syspath_prepend(str(_INSTALL_SCRIPT.parent))
+ import install_python_stack
+
+ return install_python_stack
+
+
+def _route(
+ monkeypatch,
+ mod,
+ *,
+ platform = "linux",
+ machine = "x86_64",
+ py = (3, 13),
+ torch = None,
+):
+ monkeypatch.setattr(mod.sys, "platform", platform)
+ monkeypatch.setattr(mod.platform, "machine", lambda: machine)
+ monkeypatch.setattr(mod.sys, "version_info", (*py, 0, "final", 0))
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: torch)
+
+
+ "resident, expected",
+ [
+ ("2.11.0", ("torch==2.11.0", "torchvision==0.26.*", "torchaudio==2.11.*")),
+ ("2.10.0", ("torch==2.10.0", "torchvision==0.25.*", "torchaudio==2.10.*")),
+ ("2.12.1", ("torch==2.12.1", "torchvision==0.27.*", "torchaudio==2.11.*")),
+ ("2.13.0", ("torch==2.13.0", "torchvision==0.28.*", "torchaudio==2.11.*")),
+ ("2.14.0", ("torch==2.14.0", "torchvision==0.29.*", "torchaudio==2.11.*")),
+ ],
+)
+def test_a_resident_release_is_kept(monkeypatch, mod, resident, expected):
+ _route(monkeypatch, mod, torch = resident)
+ assert mod._cuda_repair_torch_specs(CU130, mod._CUDA_TORCH_PKG_SPEC) == expected
+ assert mod._cuda_repair_torch_specs(CU130, mod._TORCH_FLAVOR_REPAIR_PKG_SPEC) == expected
+
+
+# 2.4-2.8 are older than anything the cu130 index serves, so pinning them would fail the repair.
[email protected]("resident", [None, "2.15.0", "2.3.1", "2.6.0", "2.8.0"])
+def test_no_keepable_release_repairs_to_the_default_range(monkeypatch, mod, resident):
+ # 2.13 without a kept release would bypass install.sh's PyPI gate and any uv upload cutoff.
+ _route(monkeypatch, mod, torch = resident)
+ for default in (mod._CUDA_TORCH_PKG_SPEC, mod._TORCH_FLAVOR_REPAIR_PKG_SPEC):
+ assert mod._cuda_repair_torch_specs(CU130, default) is default
+
+
+ "index_url, kwargs",
+ [
+ ("https://download.pytorch.org/whl/cu128", {}),
+ ("https://download.pytorch.org/whl/cu126", {}),
+ ("https://download.pytorch.org/whl/cpu", {}),
+ ("https://download.pytorch.org/whl/rocm7.2", {}),
+ (CU130, {"platform": "win32"}),
+ (CU130, {"platform": "darwin"}),
+ (CU130, {"machine": "aarch64"}),
+ (CU130, {"py": (3, 12)}),
+ (CU130, {"py": (3, 11)}),
+ (None, {}),
+ ],
+)
+def test_every_other_route_is_unchanged(monkeypatch, mod, index_url, kwargs):
+ _route(monkeypatch, mod, torch = "2.13.0", **kwargs)
+ for default in (mod._CUDA_TORCH_PKG_SPEC, mod._TORCH_FLAVOR_REPAIR_PKG_SPEC):
+ assert mod._cuda_repair_torch_specs(index_url, default) is default
+
+
+def test_resident_release_reads_metadata_and_rejects_non_releases(monkeypatch, mod):
+ import importlib.metadata as md
+
+ for raw, want in (
+ ("2.13.0+cu130", "2.13.0"),
+ ("2.11.0", "2.11.0"),
+ ("2.14.0.dev20260801+cu130", None),
+ ("2.13.0a0+git1234", None),
+ ):
+ monkeypatch.setattr(md, "version", lambda _name, raw = raw: raw)
+ assert mod._resident_torch_release() == want, raw
+
+ def missing(_name):
+ raise md.PackageNotFoundError("torch")
+
+ monkeypatch.setattr(md, "version", missing)
+ assert mod._resident_torch_release() is None
+
+
+def test_both_cuda_repairs_use_the_route_aware_specs(mod):
+ import re
+
+ source = _INSTALL_SCRIPT.read_text(encoding = "utf-8")
+ calls = re.findall(r"_cuda_repair_torch_specs\(\s*index_url,\s*(\w+)\s*\)", source)
+ assert sorted(calls) == [
+ "_CUDA_TORCH_PKG_SPEC",
+ "_CUDA_TORCH_PKG_SPEC",
+ "_TORCH_FLAVOR_REPAIR_PKG_SPEC",
+ ]
+
+
+ "platform, resident, pinned",
+ [
+ ("linux", "2.13.0", True),
+ ("linux", "2.14.0", True),
+ ("linux", "2.12.1", False),
+ ("linux", "2.11.0", False),
+ ("linux", None, False),
+ ("win32", "2.13.0", False),
+ ("darwin", "2.13.0", False),
+ ],
+)
+def test_core_update_freezes_only_torch_past_the_released_ceiling(
+ monkeypatch, tmp_path, mod, platform, resident, pinned
+):
+ monkeypatch.setattr(mod.sys, "platform", platform)
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: resident)
+ monkeypatch.setattr(
+ mod,
+ "_resident_torch_trio_pins",
+ lambda: ["torch==2.13.0+cu130", "torchvision==0.28.0+cu130", "torchaudio==2.11.0+cu130"],
+ )
+ inherited = tmp_path / "overrides.txt"
+ inherited.write_text("Torch<2.13\ntorchvision>=0.1\nnumpy<3\n", encoding = "utf-8")
+ monkeypatch.setenv("UV_OVERRIDE", str(inherited))
+ with mod._FreezeNewTorchForCoreUpdate() as freeze:
+ value = mod.os.environ["UV_OVERRIDE"]
+ assert mod._TORCH_FREEZE_ACTIVE is pinned
+ if pinned:
+ # One file: the inherited trio lines would make uv's resolution unsatisfiable.
+ assert Path(value).read_text(encoding = "utf-8").split() == [
+ "torch==2.13.0+cu130",
+ "torchvision==0.28.0+cu130",
+ "torchaudio==2.11.0+cu130",
+ "numpy<3",
+ ]
+ else:
+ assert value == str(inherited)
+ assert mod.os.environ["UV_OVERRIDE"] == str(inherited)
+ assert mod._TORCH_FREEZE_ACTIVE is False
+ if pinned:
+ assert not freeze._path.exists()
+
+
+def test_core_update_freeze_restores_an_unset_override(monkeypatch, mod):
+ monkeypatch.setattr(mod.sys, "platform", "linux")
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: "2.13.0")
+ monkeypatch.setattr(mod, "_resident_torch_trio_pins", lambda: ["torch==2.13.0+cu130"])
+ monkeypatch.delenv("UV_OVERRIDE", raising = False)
+ with mod._FreezeNewTorchForCoreUpdate():
+ assert mod.os.environ["UV_OVERRIDE"].endswith(".txt")
+ assert "UV_OVERRIDE" not in mod.os.environ
+
+
+def test_both_core_updates_run_under_the_freeze():
+ source = _INSTALL_SCRIPT.read_text(encoding = "utf-8")
+ assert (
+ source.count(
+ 'with _FreezeNewTorchForCoreUpdate():\n pip_install(\n "Updating core packages"'
+ )
+ == 2
+ )
+
+
+def test_a_uv_failure_under_the_freeze_never_falls_back_to_pip(monkeypatch, mod):
+ import subprocess
+
+ monkeypatch.setattr(mod, "USE_UV", True)
+ monkeypatch.setattr(mod, "_TORCH_FREEZE_ACTIVE", True)
+ monkeypatch.setattr(
+ mod.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 1, b"no solution")
+ )
+ ran = []
+ monkeypatch.setattr(mod, "run", lambda *a, **k: ran.append(a))
+ with pytest.raises(SystemExit):
+ mod._pip_install_once("Updating core packages", "unsloth")
+ assert ran == []
+
+
+def test_inherited_relative_includes_still_resolve(monkeypatch, tmp_path, mod):
+ monkeypatch.setattr(mod.sys, "platform", "linux")
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: "2.13.0")
+ monkeypatch.setattr(mod, "_resident_torch_trio_pins", lambda: ["torch==2.13.0+cu130"])
+ (tmp_path / "nested.txt").write_text("numpy<3\n", encoding = "utf-8")
+ inherited = tmp_path / "overrides.txt"
+ inherited.write_text(
+ "-r nested.txt\n--constraint=/abs/c.txt\n-r https://example.com/r.txt\n", encoding = "utf-8"
+ )
+ monkeypatch.setenv("UV_OVERRIDE", str(inherited))
+ with mod._FreezeNewTorchForCoreUpdate():
+ merged = Path(mod.os.environ["UV_OVERRIDE"]).read_text(encoding = "utf-8").splitlines()
+ assert merged == [
+ "torch==2.13.0+cu130",
+ f"-r {(tmp_path / 'nested.txt').resolve()}",
+ "--constraint=/abs/c.txt",
+ "-r https://example.com/r.txt",
+ ]
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 84fd7739517..db63eddaad9 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1201,7 +1201,7 @@ export const en = {
action: "Repair install",
confirmTitle: "Repair this installation?",
confirmDescription:
- "Stops the server and reruns the installer, which reinstalls PyTorch for this machine's GPU. Chats and settings are kept. This can take several minutes.",
+ "Stops the server and reruns the installer, which reinstalls PyTorch for this machine's GPU at the newest supported release. Chats and settings are kept. This can take several minutes.",
confirmAction: "Repair now",
},
resetPreferences: {
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index ad6670847ab..f68169b8bb5 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -513,6 +513,133 @@ _TORCH_FLAVOR_REPAIR_PKG_SPEC: tuple[str, str, str] = (
"torchaudio>=2.4,<2.12.0",
)
+# The install.sh _cu130_torch213_route: a repair keeps a resident 2.9-2.14 release.
+_CU130_PRESERVE_TORCH_CEILING_MINOR = 15
+_CU130_FIRST_TORCH_MINOR = 9 # download.pytorch.org/whl/cu130 starts at torch 2.9.0
+
+
+def _is_cu130_torch213_route(index_url: str | None) -> bool:
+ return (
+ bool(index_url)
+ and _torch_index_leaf(index_url) == "cu130"
+ and sys.platform.startswith("linux")
+ and platform.machine().lower() in ("x86_64", "amd64")
+ and sys.version_info[:2] == (3, 13)
+ )
+
+
+def _resident_torch_release() -> str | None:
+ """The installed torch's plain X.Y.Z release from its metadata, never importing it."""
+ try:
+ from importlib.metadata import version as _dist_version
+ release = _dist_version("torch").split("+", 1)[0]
+ except Exception:
+ return None
+ return release if re.fullmatch(r"2\.\d+\.\d+", release) else None
+
+
+def _cuda_repair_torch_specs(
+ index_url: str | None, default: tuple[str, str, str]
+) -> tuple[str, str, str]:
+ """``default``, except that the cu130 torch 2.13 route keeps a resident release it serves.
+
+ Never installs 2.13 itself: whether a release admits it is install.sh's PyPI decision."""
+ if not _is_cu130_torch213_route(index_url):
+ return default
+ release = _resident_torch_release()
+ if release is not None:
+ minor = int(release.split(".")[1])
+ if _CU130_FIRST_TORCH_MINOR <= minor < _CU130_PRESERVE_TORCH_CEILING_MINOR:
+ # torchaudio 2.11 is the last release (stable ABI), so newer minors pair with it.
+ audio_minor = min(minor, 11)
+ return (
+ f"torch=={release}",
+ f"torchvision==0.{minor + 15}.*",
+ f"torchaudio==2.{audio_minor}.*",
+ )
+ return default
+
+
+def _resident_torch_trio_pins() -> list[str]:
+ """``name==version`` for the installed torch, torchvision and torchaudio (local tag kept)."""
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
+
+ pins = []
+ for name in ("torch", "torchvision", "torchaudio"):
+ try:
+ pins.append(f"{name}=={_dist_version(name)}")
+ except PackageNotFoundError:
+ pass
+ return pins
+
+
+_OVERRIDE_INCLUDE = re.compile(r"^(\s*(?:-r|-c|--requirement|--constraint)(?:\s+|=))(\S+)(.*)$")
+_TORCH_TRIO_LINE = re.compile(r"^\s*torch(vision|audio)?([\s<>=!~;@\[]|$)", re.IGNORECASE)
+# True while _FreezeNewTorchForCoreUpdate's UV_OVERRIDE is the only thing keeping the trio.
+_TORCH_FREEZE_ACTIVE = False
+
+
+class _FreezeNewTorchForCoreUpdate:
+ """Pin the resident torch trio via UV_OVERRIDE while unsloth / unsloth-zoo re-resolve.
+
+ A released unsloth declares a torch ceiling (2026.9.11: <2.13.0), and a with-deps upgrade
+ honours it: on a torch 2.13 install `studio update` swapped torch for PyPI's 2.12.1 and lost
+ the matching prebuilt kernels. install.sh freezes the trio the same way for every with-deps
+ unsloth install (_build_unsloth_torch_overrides). Scoped to Linux with torch >= 2.13, the
+ releases past that ceiling, so every other install resolves exactly as before.
+ """
+
+ def __enter__(self):
+ self._path = None
+ self._previous = os.environ.get("UV_OVERRIDE")
+ release = _resident_torch_release()
+ if not (
+ sys.platform.startswith("linux")
+ and release is not None
+ and int(release.split(".")[1]) >= 13
+ ):
+ return self
+ pins = _resident_torch_trio_pins()
+ if not pins:
+ return self
+ # uv applies every override for a package, so an inherited torch line would conflict:
+ # fold the inherited files in without their trio entries, as install.sh does.
+ lines = list(pins)
+ for inherited in (self._previous or "").split():
+ try:
+ text = Path(inherited).read_text(encoding = "utf-8")
+ except OSError:
+ continue
+ base = Path(inherited).parent
+ for line in text.splitlines():
+ if _TORCH_TRIO_LINE.match(line):
+ continue
+ # A relative -r / -c resolves against its own file, which is no longer this one.
+ include = _OVERRIDE_INCLUDE.match(line)
+ if include and "://" not in include[2] and not os.path.isabs(include[2]):
+ line = f"{include[1]}{(base / include[2]).resolve()}{include[3]}"
+ lines.append(line)
+ fd, name = tempfile.mkstemp(prefix = "unsloth-torch-overrides-", suffix = ".txt")
+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:
+ handle.write("\n".join(lines) + "\n")
+ self._path = Path(name)
+ os.environ["UV_OVERRIDE"] = _uv_safe_path(self._path)
+ global _TORCH_FREEZE_ACTIVE
+ _TORCH_FREEZE_ACTIVE = True
+ return self
+
+ def __exit__(self, *exc):
+ global _TORCH_FREEZE_ACTIVE
+ _TORCH_FREEZE_ACTIVE = False
+ if self._path is not None:
+ if self._previous is None:
+ os.environ.pop("UV_OVERRIDE", None)
+ else:
+ os.environ["UV_OVERRIDE"] = self._previous
+ self._path.unlink(missing_ok = True)
+ return False
+
+
# torchao's cpp is built for ONE torch release AND CUDA major. Either mismatch costs the
# kernels, never the import: torchao/__init__.py has caught the dlopen failure since 0.12 and
# import_fixes.py filters that warning. Match torchao to the installed torch (pytorch/ao#2919):
@@ -4352,7 +4479,9 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
index_url = _detect_cuda_torch_index_url()
if index_url is None:
return False
- _torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
+ _torch_pkg, _vision_pkg, _audio_pkg = _cuda_repair_torch_specs(
+ index_url, _CUDA_TORCH_PKG_SPEC
+ )
_safe_print(
f" torch cannot import but an explicit CUDA index is pinned -- reinstalling "
f"CUDA torch from {_strip_index_url_credentials(index_url)}"
@@ -4439,7 +4568,7 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
index_url = _detect_cuda_torch_index_url()
if index_url is None:
return False
- _torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
+ _torch_pkg, _vision_pkg, _audio_pkg = _cuda_repair_torch_specs(index_url, _CUDA_TORCH_PKG_SPEC)
_safe_print(
f" {_why} -- reinstalling CUDA torch from {_strip_index_url_credentials(index_url)}\n"
f" (set UNSLOTH_TORCH_BACKEND=rocm or cpu to keep a deliberate "
@@ -5584,7 +5713,9 @@ def _ensure_expected_torch_flavor(expected: "str | None" = None) -> bool:
return _warn_wrong_flavor(expected, installed)
# 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
+ _XPU_TORCH_PKG_SPEC
+ if expected == "xpu"
+ else _cuda_repair_torch_specs(index_url, _TORCH_FLAVOR_REPAIR_PKG_SPEC)
)
# Keyed on the INTERPRETER, not the machine: an emulated x64 venv installs win_amd64 wheels.
_trio = [_torch_pkg, _vision_pkg, _audio_pkg]
@@ -9882,10 +10013,27 @@ def _pip_install_once(
)
_safe_print(_red(" Install uv and re-run, or re-run install.ps1."))
_report_failed_command(label, result)
+ if _TORCH_FREEZE_ACTIVE:
+ _step("error", f"{label} failed and pip cannot stand in for it", _red)
+ _safe_print(
+ _red(
+ " torch is held on its installed release through UV_OVERRIDE, which pip "
+ "ignores: a pip fallback would downgrade it to the released cap."
+ )
+ )
+ _report_failed_command(label, result)
_safe_print(_red(f" uv failed, falling back to pip..."))
if result.stdout:
_safe_print(_redact_install_output(result.stdout))
+ elif _TORCH_FREEZE_ACTIVE:
+ _step("error", f"{label} needs uv to keep the installed torch", _red)
+ _safe_print(
+ _red(
+ " Install uv and re-run, or set UNSLOTH_TORCH_UPGRADE=1 and re-run install.sh."
+ )
+ )
+ sys.exit(1)
elif _woa_overrides_are_load_bearing():
_step("error", f"{label} needs uv on the Windows on ARM stack", _red)
_safe_print(
@@ -11881,16 +12029,17 @@ def install_python_stack() -> int:
# Local dev install: update the released core packages, then overlay the
# checkout as an editable install (--no-deps so torch is not re-resolved).
_progress("base packages")
- pip_install(
- "Updating core packages",
- "--no-cache-dir",
- "--upgrade-package",
- "unsloth",
- "--upgrade-package",
- "unsloth-zoo",
- "unsloth",
- "unsloth-zoo",
- )
+ with _FreezeNewTorchForCoreUpdate():
+ pip_install(
+ "Updating core packages",
+ "--no-cache-dir",
+ "--upgrade-package",
+ "unsloth",
+ "--upgrade-package",
+ "unsloth-zoo",
+ "unsloth",
+ "unsloth-zoo",
+ )
_overlay_local_core_packages(local_repo)
elif package_name != "unsloth":
# Custom package name (for testing): install directly.
@@ -11908,16 +12057,17 @@ def install_python_stack() -> int:
if (desktop_min_ver and package_name == "unsloth")
else package_name
)
- pip_install(
- "Updating core packages",
- "--no-cache-dir",
- "--upgrade-package",
- "unsloth",
- "--upgrade-package",
- "unsloth-zoo",
- unsloth_spec,
- "unsloth-zoo",
- )
+ with _FreezeNewTorchForCoreUpdate():
+ pip_install(
+ "Updating core packages",
+ "--no-cache-dir",
+ "--upgrade-package",
+ "unsloth",
+ "--upgrade-package",
+ "unsloth-zoo",
+ unsloth_spec,
+ "unsloth-zoo",
+ )
# The package just installed may ship a newer copy of this file. Raised rather than rerun
# here, so the pass lock is released first; the rerun repeats the cheap steps above.
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index 56ffba01415..932a50960c9 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -1199,6 +1199,7 @@ pub async fn start_managed_repair(
install_state,
install_diagnostics,
install_repair_group_id,
+ force_installer,
)
})
.await
diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rs
index 4e38165d4ef..bfa85139f9c 100644
--- a/studio/src-tauri/src/install.rs
+++ b/studio/src-tauri/src/install.rs
@@ -566,6 +566,7 @@ fn spawn_script(
script: &Path,
args: &[String],
state: &InstallState,
+ extra_env: &[(&str, &str)],
) -> Result<
(
Option<std::process::ChildStdout>,
@@ -618,6 +619,9 @@ fn spawn_script(
"UNSLOTH_DESKTOP_BACKEND_VERSION",
crate::preflight::expected_backend_version(),
);
+ for (name, value) in extra_env {
+ cmd.env(name, value);
+ }
// We decode this child as UTF-8 below, so its Python descendants must emit
// UTF-8 or the log fills with U+FFFD. The .ps1 entry points set these too;
@@ -852,14 +856,18 @@ pub fn run_install(
state: InstallState,
diagnostics: DiagnosticsState,
) -> Result<(), String> {
- run_install_with_event_mode(app, state, diagnostics, InstallEventMode::Full, None)
+ run_install_with_event_mode(app, state, diagnostics, InstallEventMode::Full, None, false)
}
+/// `upgrade_torch` is Settings' manual "Repair installation": the user asked for a reinstall,
+/// so the installer may move to the newest supported PyTorch instead of keeping the resident one.
+/// The startup auto-repair passes false and keeps it.
pub(crate) fn run_install_for_repair(
app: AppHandle,
state: InstallState,
diagnostics: DiagnosticsState,
repair_group_id: String,
+ upgrade_torch: bool,
) -> Result<(), String> {
run_install_with_event_mode(
app,
@@ -867,15 +875,27 @@ pub(crate) fn run_install_for_repair(
diagnostics,
InstallEventMode::Repair,
Some(repair_group_id),
+ upgrade_torch,
)
}
+/// Extra environment for the installer child. UNSLOTH_TORCH_UPGRADE=1 is install.sh's and
+/// install.ps1's opt-out from keeping an existing install's torch release.
+fn installer_env(upgrade_torch: bool) -> Vec<(&'static str, &'static str)> {
+ if upgrade_torch {
+ vec![("UNSLOTH_TORCH_UPGRADE", "1")]
+ } else {
+ Vec::new()
+ }
+}
+
fn run_install_with_event_mode(
app: AppHandle,
state: InstallState,
diagnostics: DiagnosticsState,
event_mode: InstallEventMode,
repair_group_id: Option<String>,
+ upgrade_torch: bool,
) -> Result<(), String> {
let attempt = match repair_group_id.as_deref() {
Some(group_id) => diagnostics::begin_repair_child(&diagnostics, group_id, "install"),
@@ -920,7 +940,8 @@ fn run_install_with_event_mode(
&format!("Using script: {}", script.display()),
);
- let (stdout, stderr) = match spawn_script(&script, &args, &state) {
+ let extra_env = installer_env(upgrade_torch);
+ let (stdout, stderr) = match spawn_script(&script, &args, &state, &extra_env) {
Ok(handles) => handles,
Err(msg) => {
diagnostics::finish_attempt(
@@ -1528,6 +1549,12 @@ mod tests {
assert!(capped.is_char_boundary(capped.len()));
}
+ #[test]
+ fn only_a_manual_repair_asks_the_installer_for_a_newer_torch() {
+ assert_eq!(installer_env(true), vec![("UNSLOTH_TORCH_UPGRADE", "1")]);
+ assert!(installer_env(false).is_empty());
+ }
+
#[test]
fn repair_install_mode_uses_repair_elevation_event() {
assert_eq!(
diff --git a/tests/sh/test_cu130_torch213_route.sh b/tests/sh/test_cu130_torch213_route.sh
new file mode 100644
index 00000000000..181a32b3e40
--- /dev/null
+++ b/tests/sh/test_cu130_torch213_route.sh
@@ -0,0 +1,182 @@
+#!/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
+# install.sh gives new Linux x86_64 cu130 Python 3.13 installs torch 2.13 (the only route the
+# prebuilt-wheels-cu13 release covers) while an existing 2.4-2.14 install keeps its release.
+# Helpers are extracted from install.sh and sourced; the venv python is a stub.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+. "$SCRIPT_DIR/_harness.sh"
+INSTALL_SH="${1:-$SCRIPT_DIR/../../install.sh}"
+_FUNC_FILE=$(mktemp)
+{
+ for fn in _mirror_uv_project_config _mirror_configured _run_bounded _pypi_unsloth_admits_torch _torch_index_url_leaf _cu130_torch213_route _cu130_torch213_platform _torchaudio_for_torch_minor _torch_release_in_window _previous_torch_pin _dir_has_entries; do
+ sed -n "/^${fn}()/,/^}/p" "$INSTALL_SH"
+ echo ""
+ done
+} > "$_FUNC_FILE"
+# shellcheck disable=SC1090
+. "$_FUNC_FILE"
+rm -f "$_FUNC_FILE"
+unset UNSLOTH_TORCH_UPGRADE
+
+VENV_DIR=$(mktemp -d)
+mkdir -p "$VENV_DIR/bin"
+# Answers the version probe (-c) with $1 and runs anything else (the PyPI gate) on a real python.
+_stub_python() {
+ printf '#!/bin/sh\nif [ "$1" = "-c" ]; then echo %s; else exec python3 "$@"; fi\n' "$1" > "$VENV_DIR/bin/python"
+ chmod +x "$VENV_DIR/bin/python"
+}
+CU130="https://download.pytorch.org/whl/cu130"
+_pypi_fixture() {
+ printf '{"info": {"requires_dist": ["numpy", "%s", "torchvision"]}}' "$1" > "$VENV_DIR/pypi.json"
+ export UNSLOTH_PYPI_JSON_URL="file://$VENV_DIR/pypi.json"
+}
+_pypi_fixture "torch<2.15.0,>=2.4.0"
+
+echo "=== route: only cu130 + Linux/WSL + x86_64 + Python 3.13 ==="
+_stub_python 3.13
+OS=linux; _ARCH=x86_64
+assert_eq "linux x86_64 cu130 py3.13" "yes" "$(_cu130_torch213_route "$CU130")"
+assert_eq "trailing slash and query" "yes" "$(_cu130_torch213_route "$CU130/?token=x")"
+OS=wsl
+assert_eq "wsl counts as linux" "yes" "$(_cu130_torch213_route "$CU130")"
+OS=linux
+for leaf in cu128 cu126 cu124 cu118 cpu rocm7.2 xpu gfx1151; do
+ assert_eq "leaf $leaf stays on the old window" "no" "$(_cu130_torch213_route "https://download.pytorch.org/whl/$leaf")"
+done
+OS=macos
+assert_eq "macOS never" "no" "$(_cu130_torch213_route "$CU130")"
+OS=linux; _ARCH=aarch64
+assert_eq "aarch64 never (no wheels)" "no" "$(_cu130_torch213_route "$CU130")"
+_ARCH=x86_64
+for py in 3.11 3.12 3.14; do
+ _stub_python "$py"
+ assert_eq "Python $py never (cp313 wheels only)" "no" "$(_cu130_torch213_route "$CU130")"
+done
+rm -f "$VENV_DIR/bin/python"
+assert_eq "no venv python never" "no" "$(_cu130_torch213_route "$CU130")"
+
+echo "=== route: only once the PyPI release admits torch 2.13 ==="
+_stub_python 3.13
+assert_eq "release admits 2.13" "yes" "$(_cu130_torch213_route "$CU130")"
+_pypi_fixture "torch<2.13.0,>=2.4.0"
+assert_eq "release still capped below 2.13" "no" "$(_cu130_torch213_route "$CU130")"
+_pypi_fixture "torch>=2.4.0"
+assert_eq "uncapped release" "yes" "$(_cu130_torch213_route "$CU130")"
+_pypi_fixture "torch<2.15.0,>=2.4.0 ; extra == \\\"x\\\""
+assert_eq "extra-only torch is no evidence" "no" "$(_cu130_torch213_route "$CU130")"
+export UNSLOTH_PYPI_JSON_URL="http://127.0.0.1:9/unreachable"
+assert_eq "unreachable index keeps the old window" "no" "$(_cu130_torch213_route "$CU130")"
+_pypi_fixture "torch<2.15.0,>=2.4.0"
+assert_eq "UV_EXCLUDE_NEWER keeps the old window" "no" "$(UV_EXCLUDE_NEWER=2026-06-01T00:00:00Z _cu130_torch213_route "$CU130")"
+assert_eq "UV_EXCLUDE_NEWER_PACKAGE keeps the old window" "no" "$(UV_EXCLUDE_NEWER_PACKAGE=unsloth=2026-06-01T00:00:00Z _cu130_torch213_route "$CU130")"
+assert_eq "empty cutoff is no cutoff" "yes" "$(UV_EXCLUDE_NEWER= _cu130_torch213_route "$CU130")"
+for off in 1 true TRUE yes on " 1 "; do
+ assert_eq "UV_OFFLINE='$off' keeps the old window" "no" "$(UV_OFFLINE="$off" _cu130_torch213_route "$CU130")"
+done
+for off in 0 false no ""; do
+ assert_eq "UV_OFFLINE='$off' is online" "yes" "$(UV_OFFLINE="$off" _cu130_torch213_route "$CU130")"
+done
+assert_eq "UV_DEFAULT_INDEX keeps the old window" "no" "$(UV_DEFAULT_INDEX=https://mirror.example/simple _cu130_torch213_route "$CU130")"
+assert_eq "UV_INDEX_URL keeps the old window" "no" "$(UV_INDEX_URL=https://mirror.example/simple _cu130_torch213_route "$CU130")"
+_UVCFG="$VENV_DIR/uv.toml"; printf '[[index]]\nurl = "https://mirror.example/simple"\ndefault = true\n' > "$_UVCFG"
+assert_eq "uv.toml index keeps the old window" "no" "$(UV_CONFIG_FILE="$_UVCFG" _cu130_torch213_route "$CU130")"
+
+echo "=== preservation never waits on PyPI; only a fresh home takes 2.13 ==="
+# Runs install.sh's own block (route, kept pin, new-install default) with substep stubbed.
+_PRESERVE_BLOCK=$(sed -n '/^_PRESERVE_TORCH_CONSTRAINT="\$TORCH_CONSTRAINT"$/,/^ TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"$/p' "$INSTALL_SH"; echo fi)
+assert_eq "block found in install.sh" "yes" "$(printf '%s' "$_PRESERVE_BLOCK" | grep -q _CU130_NEW_INSTALL_ROUTE && echo yes)"
+substep() { :; }
+_CU130_TORCH_CEILING="2.15.0"; _CU130_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"; SKIP_TORCH=false; TORCH_INDEX_URL="$CU130"
+_run_block() { # $1 existing-install flag, $2 previous torch version
+ _EXISTING_INSTALL="$1"; _PREV_TORCH_VER="$2"
+ TORCH_CONSTRAINT="torch>=2.4,<2.12.0"; TORCHVISION_CONSTRAINT="torchvision>=0.19,<0.27.0"
+ eval "$_PRESERVE_BLOCK"
+}
+for gate in unreachable capped open; do
+ case "$gate" in
+ unreachable) export UNSLOTH_PYPI_JSON_URL="http://127.0.0.1:9/unreachable" ;;
+ capped) _pypi_fixture "torch<2.13.0,>=2.4.0" ;;
+ open) _pypi_fixture "torch<2.15.0,>=2.4.0" ;;
+ esac
+ _run_block true "2.13.0+cu130"
+ assert_eq "PyPI $gate: existing 2.13 kept" "torch==2.13.0" "$TORCH_CONSTRAINT"
+ assert_eq "PyPI $gate: kept pin falls back to the old default" "torch>=2.4,<2.12.0" "$_PREV_FALLBACK_CONSTRAINT"
+ _run_block true "2.11.0+cu130"
+ assert_eq "PyPI $gate: existing 2.11 kept" "torch==2.11.0" "$TORCH_CONSTRAINT"
+ _run_block true ""
+ assert_eq "PyPI $gate: existing home with unreadable torch stays on the old default" "torch>=2.4,<2.12.0" "$TORCH_CONSTRAINT"
+ _run_block false ""
+ want="torch>=2.4,<2.12.0"; [ "$gate" = open ] && want="torch>=2.13.0,<2.14.0"
+ assert_eq "PyPI $gate: fresh home default" "$want" "$TORCH_CONSTRAINT"
+done
+UNSLOTH_TORCH_UPGRADE=1; _run_block true "2.11.0+cu130"; unset UNSLOTH_TORCH_UPGRADE
+assert_eq "UNSLOTH_TORCH_UPGRADE=1 moves an existing home to 2.13" "torch>=2.13.0,<2.14.0" "$TORCH_CONSTRAINT"
+for gate in unreachable capped; do
+ case "$gate" in
+ unreachable) export UNSLOTH_PYPI_JSON_URL="http://127.0.0.1:9/unreachable" ;;
+ capped) _pypi_fixture "torch<2.13.0,>=2.4.0" ;;
+ esac
+ UNSLOTH_TORCH_UPGRADE=1
+ _run_block true "2.13.0+cu130"
+ assert_eq "upgrade with PyPI $gate keeps a resident 2.13" "torch==2.13.0" "$TORCH_CONSTRAINT"
+ _run_block true "2.10.0+cu128"
+ assert_eq "upgrade with PyPI $gate still moves 2.10 to the default" "torch>=2.4,<2.12.0" "$TORCH_CONSTRAINT"
+ unset UNSLOTH_TORCH_UPGRADE
+done
+_pypi_fixture "torch<2.15.0,>=2.4.0"
+_stub_python 3.12
+_run_block false ""
+assert_eq "Python 3.12 keeps the old window" "torch>=2.4,<2.12.0" "$_PRESERVE_TORCH_CONSTRAINT"
+_stub_python 3.13
+assert_eq "legacy layout records its torch before migrating" "yes" \
+ "$(grep -q '"\$STUDIO_HOME"/.venv/lib/python\*/site-packages/torch/version.py' "$INSTALL_SH" && echo yes)"
+
+echo "=== a home with any earlier environment is an existing install ==="
+# install.sh's own detection block; the legacy branches that run an interpreter are not reached here.
+_DETECT_BLOCK=$(awk '/^_EXISTING_INSTALL=false$/{p=1} p&&/^if \[ "\$SKIP_TORCH" = true \] && \[ "\$MAC_INTEL" = true \]/{exit} p' "$INSTALL_SH")
+assert_eq "detection block found in install.sh" "yes" "$(printf '%s' "$_DETECT_BLOCK" | grep -q _EXISTING_INSTALL=true && echo yes)"
+_detect() ( # $1 home; prints existing flag and recorded torch
+ STUDIO_HOME="$1"; VENV_DIR="$1/unsloth_studio"; _STUDIO_HOME_REDIRECT=""; SKIP_TORCH=false
+ eval "$_DETECT_BLOCK"
+ echo "$_EXISTING_INSTALL $_PREV_TORCH_VER"
+)
+_H=$(mktemp -d)
+assert_eq "empty home is new" "false " "$(_detect "$_H/empty")"
+mkdir -p "$_H/dangling/.venv/bin" "$_H/dangling/.venv/lib/python3.13/site-packages/torch"
+ln -s /nonexistent/python3 "$_H/dangling/.venv/bin/python"
+echo "__version__ = '2.11.0+cu130'" > "$_H/dangling/.venv/lib/python3.13/site-packages/torch/version.py"
+assert_eq "legacy .venv with a dangling python keeps its torch" "true 2.11.0" "$(_detect "$_H/dangling" | sed 's/+.*//')"
+mkdir -p "$_H/nopython/.venv/lib"
+assert_eq "legacy .venv without python or torch is still existing" "true " "$(_detect "$_H/nopython")"
+rm -rf "${_H:?}"
+
+echo "=== preservation window keeps every existing 2.4-2.14 release ==="
+PRESERVE='torch>=2.4,<2.15.0'
+for v in 2.4.0+cu121 2.10.0+cu128 2.11.0+cu130 2.12.1+cu130 2.13.0+cu130 2.14.0+cu130 2.11.0; do
+ assert_eq "keeps $v" "torch==${v%%+*}" "$(_previous_torch_pin "$v" "$PRESERVE")"
+done
+assert_eq "2.15 is outside the window" "" "$(_previous_torch_pin '2.15.0+cu130' "$PRESERVE")"
+assert_eq "nightly never pins" "" "$(_previous_torch_pin '2.14.0.dev20260801+cu130' "$PRESERVE")"
+UNSLOTH_TORCH_UPGRADE=1
+assert_eq "UNSLOTH_TORCH_UPGRADE=1 opts out" "" "$(_previous_torch_pin '2.11.0+cu130' "$PRESERVE")"
+unset UNSLOTH_TORCH_UPGRADE
+# The new-install spec must never be the preservation window: that would upgrade 2.11 users.
+assert_eq "new-install spec alone would drop a kept 2.11" "" "$(_previous_torch_pin '2.11.0+cu130' 'torch>=2.13.0,<2.14.0')"
+assert_eq "kept pin is evaluated against the preservation window" "yes" \
+ "$(grep -q '_prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT")' "$INSTALL_SH" && echo yes)"
+assert_eq "new-install spec is torch 2.13" "yes" \
+ "$(grep -q '^_CU130_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"$' "$INSTALL_SH" && echo yes)"
+
+echo "=== torchaudio pairing for a kept minor ==="
+assert_eq "2.10 -> 2.10" "torchaudio==2.10.*" "$(_torchaudio_for_torch_minor 10)"
+assert_eq "2.11 -> 2.11" "torchaudio==2.11.*" "$(_torchaudio_for_torch_minor 11)"
+assert_eq "2.12 -> 2.11" "torchaudio==2.11.*" "$(_torchaudio_for_torch_minor 12)"
+assert_eq "2.13 -> 2.11" "torchaudio==2.11.*" "$(_torchaudio_for_torch_minor 13)"
+assert_eq "2.14 -> 2.11" "torchaudio==2.11.*" "$(_torchaudio_for_torch_minor 14)"
+assert_eq "2.9 -> 2.9" "torchaudio==2.9.*" "$(_torchaudio_for_torch_minor 9)"
+
+rm -rf "${VENV_DIR:?}"
+summary
diff --git a/tests/sh/test_previous_torch_pin.sh b/tests/sh/test_previous_torch_pin.sh
index a71f13536c5..bc0fc20310d 100644
--- a/tests/sh/test_previous_torch_pin.sh
+++ b/tests/sh/test_previous_torch_pin.sh
@@ -139,7 +139,7 @@ assert_eq "flavor repair routed through the kept-release helper" "yes" "$(grep -
# The kept-release install must pair the companions with the kept minor:
# torchaudio no longer exact-pins torch, so unconstrained it resolves a newer
# mismatched build (verified: torch==2.9.0 pulled torchaudio 2.11.0 on cu130).
-assert_eq "kept-release install pairs torchvision/torchaudio to the kept minor" "yes" "$(grep -q 'torchaudio==2.\${_itdi_minor}.\*' "$INSTALL_SH" && grep -q 'torchvision==0.\$((_itdi_minor + 15)).\*' "$INSTALL_SH" && echo yes)"
+assert_eq "kept-release install pairs torchvision/torchaudio to the kept minor" "yes" "$(grep -q '_itdi_ta=\$(_torchaudio_for_torch_minor "\$_itdi_minor")' "$INSTALL_SH" && grep -q 'torchvision==0.\$((_itdi_minor + 15)).\*' "$INSTALL_SH" && echo yes)"
# The Radeon direct-wheel path must also honor the pin: an exact-first kept-trio
# attempt (exact patch, else the kept minor's newest patch, with paired
# vision/audio) runs BEFORE the newest-trio search, and the newest-trio search