Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
3ee264a
Studio: install torch 2.13 on new Linux cu130 Python 3.13 installs, k…
danielhanchen Sep 28, 2026
797a7ae
Studio: only default to torch 2.13 once PyPI unsloth admits it; freez…
danielhanchen Sep 28, 2026
d5e2e36
Tighten the torch 2.13 route comments
danielhanchen Sep 28, 2026
90bc5a0
Keep only cu130-served torch on repair; never let pip or an inherited…
danielhanchen Sep 28, 2026
c28dca2
Size the preservation window from the local route alone; keep relativ…
danielhanchen Sep 28, 2026
e5df690
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 28, 2026
2590d3f
Keep the old torch window when a uv upload-date cutoff is set
danielhanchen Sep 28, 2026
af7409e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 28, 2026
5b3f79b
Repair to the default range when no resident release is keepable, lea…
danielhanchen Sep 28, 2026
04d17a4
Stand the torch 2.13 gate down offline and on any configured package …
danielhanchen Sep 28, 2026
4070fa6
Drop a duplicated torchaudio comment
danielhanchen Sep 28, 2026
3a51f0d
Give torch 2.13 only to a fresh home: record legacy-layout torch, nev…
danielhanchen Sep 28, 2026
2122d63
Merge main into r12150
danielhanchen Sep 29, 2026
cdc1933
Treat a legacy .venv with a broken interpreter as an existing install
danielhanchen Sep 30, 2026
91ddcdf
Merge main into r12150
danielhanchen Oct 1, 2026
38edbb5
Desktop: manual Repair installation moves to the newest supported PyT…
danielhanchen Oct 1, 2026
cc868cb
Merge origin/main into studio-torch-213-cu130
danielhanchen Oct 2, 2026
bf1cd08
install.sh: an upgrade with the 2.13 route closed keeps a resident to…
danielhanchen Oct 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 77 additions & 2 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4359,6 +4359,9 @@ 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}"
# torchaudio keeps its window: 2.11 is its last release (stable ABI) and pairs with torch 2.13.
_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)"
Expand Down Expand Up @@ -5901,6 +5904,68 @@ _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 a uv
# upload-date cutoff: "newest on PyPI" is then not what uv may pick.
_pypi_unsloth_admits_torch() {
if [ -n "${UV_EXCLUDE_NEWER:-}" ] || [ -n "${UV_EXCLUDE_NEWER_PACKAGE:-}" ]; 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"
Expand Down Expand Up @@ -5969,7 +6034,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" \
Expand Down Expand Up @@ -6918,10 +6983,20 @@ 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"
if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL")" = "yes" ]; then
_PRESERVE_TORCH_CONSTRAINT="torch>=2.4,<${_CU130_TORCH_CEILING}"
if [ "$(_pypi_unsloth_admits_torch "2.13.0")" = "yes" ]; then
TORCH_CONSTRAINT="$_CU130_NEW_INSTALL_TORCH"
TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"
fi
fi
_PREV_TORCH_PIN=""
_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")
if [ -n "$_prev_pin" ]; then
_PREV_TORCH_PIN="$_prev_pin"
TORCH_CONSTRAINT="$_prev_pin"
Expand Down
219 changes: 219 additions & 0 deletions studio/backend/tests/test_cu130_repair_torch_specs.py
Original file line number Diff line number Diff line change
@@ -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"


@pytest.fixture
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)


@pytest.mark.parametrize(
"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.
@pytest.mark.parametrize("resident", [None, "2.15.0", "2.3.1", "2.6.0", "2.8.0"])
def test_no_keepable_release_repairs_to_213(monkeypatch, mod, resident):
_route(monkeypatch, mod, torch = resident)
assert mod._cuda_repair_torch_specs(CU130, mod._CUDA_TORCH_PKG_SPEC) == (
"torch>=2.13.0,<2.14.0",
"torchvision>=0.28.0,<0.29.0",
"torchaudio>=2.4,<2.12.0",
)


@pytest.mark.parametrize(
"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",
]


@pytest.mark.parametrize(
"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",
]
Loading
Loading