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 Windows x64 cu130 Python 3.13 installs, existing installs keep their torch (#13263)

Daniel Han9c4c4a1cee4a
diff --git a/install.ps1 b/install.ps1
index acd1e2bc10a..7e0f794adb8 100644
--- a/install.ps1
+++ b/install.ps1
@@ -7679,6 +7679,7 @@ exit 0
# Reset per run: under `irm | iex` the script scope IS the caller's session.
$script:PrevTorchVer = ""
$script:PrevTorchPin = $null
+ $script:ExistingInstall = $false
function Test-VenvPythonReady {
param([Parameter(Mandatory = $true)][string]$PythonExe)
@@ -8146,6 +8147,37 @@ exit 0
} catch { return $null }
}
+ function Get-TorchVersionFromDisk {
+ param([string]$VenvRoot)
+ $versionPy = Join-Path $VenvRoot "Lib\site-packages\torch\version.py"
+ if (-not (Test-Path -LiteralPath $versionPy -PathType Leaf)) { return $null }
+ try {
+ foreach ($line in [System.IO.File]::ReadAllLines($versionPy)) {
+ if ($line -match "^__version__\s*=\s*'([^']*)'") { return $Matches[1] }
+ }
+ } catch {}
+ return $null
+ }
+
+ # Before anything below moves an environment aside; a broken legacy .venv still counts.
+ $_legacyVenvDir = Join-Path $StudioHome ".venv"
+ $_cwdVenvPy = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE "unsloth_studio\Scripts\python.exe" } else { $null }
+ if ((Test-Path -LiteralPath $VenvPython) -or (Test-DirectoryHasEntries -Path $VenvDir)) {
+ $script:ExistingInstall = $true
+ } elseif ($studioUsesLegacyLayout -and (Test-DirectoryHasEntries -Path $_legacyVenvDir)) {
+ $script:ExistingInstall = $true
+ if (-not $SkipTorch) { $script:PrevTorchVer = Get-TorchVersionFromDisk -VenvRoot $_legacyVenvDir }
+ } elseif ($studioUsesLegacyLayout -and $_cwdVenvPy -and (
+ (Test-Path -LiteralPath $_cwdVenvPy) -or
+ (Test-Path -LiteralPath (Join-Path (Split-Path (Split-Path $_cwdVenvPy -Parent) -Parent) "pyvenv.cfg") -PathType Leaf))) {
+ # A CWD-relative venv whose interpreter is gone is still an earlier install.
+ $script:ExistingInstall = $true
+ if (-not $SkipTorch) {
+ if (Test-Path -LiteralPath $_cwdVenvPy) { $script:PrevTorchVer = Get-InstalledTorchVersionRaw -PythonExe $_cwdVenvPy }
+ if (-not $script:PrevTorchVer) { $script:PrevTorchVer = Get-TorchVersionFromDisk -VenvRoot (Split-Path (Split-Path $_cwdVenvPy -Parent) -Parent) }
+ }
+ }
+
$studioVenvReplacementCommitted = $false
try {
# Replace occupied venvs even when python.exe is missing, as in #9479.
@@ -8175,6 +8207,9 @@ exit 0
# Record the release before the rollback move; only the new-layout replace needs it.
if (-not $SkipTorch) {
$script:PrevTorchVer = Get-InstalledTorchVersionRaw -PythonExe $VenvPython
+ # A missing or broken interpreter still leaves torch's version.py: without it a
+ # 2.13/2.14 install would fall to the <2.12 default on a plain re-run.
+ if (-not $script:PrevTorchVer) { $script:PrevTorchVer = Get-TorchVersionFromDisk -VenvRoot $VenvDir }
}
# And the interpreter's architecture, for the same reason and while it can still be
# read: the move below takes $VenvPython with it, and the Windows-on-ARM rebuild
@@ -10622,9 +10657,10 @@ main()
param(
[string]$TorchVersion,
# Named -Constraint: the Windows port keeps no shell-style constraint variable.
- [Parameter(Mandatory = $true)][string]$Constraint
+ [Parameter(Mandatory = $true)][string]$Constraint,
+ [switch]$Keep
)
- if ($env:UNSLOTH_TORCH_UPGRADE -eq '1') { return $null }
+ if ($env:UNSLOTH_TORCH_UPGRADE -eq '1' -and -not $Keep) { return $null }
$release = ConvertTo-TorchNumericRelease $TorchVersion
if (-not $release) { return $null }
if (-not (Test-TorchReleaseInWindow -Release $release -Constraint $Constraint)) { return $null }
@@ -10634,7 +10670,106 @@ main()
Release = $release
TorchSpec = "torch==$($release.PublicBase)"
VisionSpec = "torchvision==0.$visionMinor.*"
- AudioSpec = "torchaudio==2.$($release.Minor).*"
+ # torchaudio 2.11 is the last release (stable ABI), so newer torch minors pair with it.
+ AudioSpec = "torchaudio==2.$([Math]::Min($release.Minor, 11)).*"
+ }
+ }
+
+ # Port of install.sh's cu130 torch 2.13 route (the only one prebuilt-wheels-cu13 serves).
+ $script:Cu130TorchCeiling = "2.15.0"
+ $script:Cu130NewInstallTorchSpec = "torch>=2.13.0,<2.14.0"
+ $script:Cu130NewInstallVisionSpec = "torchvision>=0.28.0,<0.29.0"
+
+ # Local facts only: decides the keep window, so a PyPI outage cannot shrink it.
+ function Test-Cu130Torch213Platform {
+ param([string]$IndexUrl, [string]$PythonExe)
+ if (-not $IndexUrl -or (Get-TorchIndexLeafName $IndexUrl) -ne "cu130") { return $false }
+ if ((Get-HostMachineArch) -ne "x86_64") { return $false }
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code "import sys, sysconfig; print('%d.%d' % sys.version_info[:2], sysconfig.get_platform())"
+ if (-not $probe.Ok) { return $false }
+ $lines = @($probe.Output -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ })
+ if ($lines.Count -eq 0) { return $false }
+ return ($lines[-1].ToLowerInvariant() -eq "3.13 win-amd64")
+ }
+
+ # An existing home never takes 2.13 unasked; UNSLOTH_TORCH_UPGRADE=1 (Settings > Repair) asks.
+ # The PyPI check reads unsloth's metadata, so a `--package` other than unsloth keeps the default.
+ function Resolve-Cu130TorchRoute {
+ param([string]$IndexUrl, [string]$PythonExe, [Parameter(Mandatory = $true)][string]$DefaultSpec, [bool]$ExistingInstall, [string]$PackageName = "unsloth")
+ $result = [pscustomobject]@{ PreserveSpec = $DefaultSpec; NewInstall = $false }
+ if (-not (Test-Cu130Torch213Platform -IndexUrl $IndexUrl -PythonExe $PythonExe)) { return $result }
+ $result.PreserveSpec = "torch>=2.4,<$($script:Cu130TorchCeiling)"
+ if ($PackageName -eq "unsloth" -and (-not $ExistingInstall -or $env:UNSLOTH_TORCH_UPGRADE -eq '1') -and
+ (Test-PypiUnslothAdmitsTorch -Want "2.13.0")) {
+ $result.NewInstall = $true
+ }
+ return $result
+ }
+
+ # UPGRADE=1 with the route closed must not move a resident 2.13/2.14 down.
+ function Get-UpgradeKeptTorchPin {
+ param(
+ [string]$TorchVersion,
+ [Parameter(Mandatory = $true)][string]$DefaultSpec,
+ [Parameter(Mandatory = $true)][string]$PreserveSpec,
+ [bool]$NewInstallRoute
+ )
+ if ($env:UNSLOTH_TORCH_UPGRADE -ne '1' -or $NewInstallRoute -or $PreserveSpec -eq $DefaultSpec) { return $null }
+ $release = ConvertTo-TorchNumericRelease $TorchVersion
+ if (-not $release -or (Test-TorchReleaseInWindow -Release $release -Constraint $DefaultSpec)) { return $null }
+ return (Get-PreviousTorchPin -TorchVersion $TorchVersion -Constraint $PreserveSpec -Keep)
+ }
+
+ # Exactly one unconditional torch requirement of plain comparisons, else no.
+ function Test-RequiresDistAdmitsTorch {
+ param([string[]]$RequiresDist, [Parameter(Mandatory = $true)][string]$Want)
+ $toTuple = {
+ param([string]$v)
+ $nums = @([regex]::Matches($v, '\d+') | Select-Object -First 3 | ForEach-Object { [long]$_.Value })
+ while ($nums.Count -lt 3) { $nums += [long]0 }
+ return $nums
+ }
+ $compare = {
+ param($a, $b)
+ for ($i = 0; $i -lt 3; $i++) {
+ if ($a[$i] -lt $b[$i]) { return -1 }
+ if ($a[$i] -gt $b[$i]) { return 1 }
+ }
+ return 0
+ }
+ $specs = @($RequiresDist | Where-Object { $_ -match '^torch\s*[<>=!~(]' -and $_ -notmatch 'extra ==' })
+ if ($specs.Count -ne 1) { return $false }
+ $body = ($specs[0] -split ';', 2)[0].Substring("torch".Length).Trim().Trim('(', ')')
+ $wantTuple = & $toTuple $Want
+ foreach ($part in @($body -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })) {
+ if ($part -notmatch '^(<=|>=|==|!=|<|>)\s*([0-9][0-9.]*)$') { return $false }
+ $c = & $compare $wantTuple (& $toTuple $Matches[2])
+ $ok = switch ($Matches[1]) {
+ "<" { $c -lt 0 }
+ "<=" { $c -le 0 }
+ ">" { $c -gt 0 }
+ ">=" { $c -ge 0 }
+ "==" { $c -eq 0 }
+ "!=" { $c -ne 0 }
+ }
+ if (-not $ok) { return $false }
+ }
+ return $true
+ }
+
+ # `studio update` re-resolves under the INSTALLED release's cap, so only a release admitting $Want
+ # opens the route. Any failure, offline mode, upload cutoff or other index answers no.
+ function Test-PypiUnslothAdmitsTorch {
+ param([Parameter(Mandatory = $true)][string]$Want)
+ if (Test-UvEnvFlag -Name "UV_OFFLINE") { return $false }
+ if ($env:UV_EXCLUDE_NEWER -or $env:UV_EXCLUDE_NEWER_PACKAGE) { return $false }
+ if (Test-MirrorConfigured -Tool uv) { return $false }
+ $url = if ($env:UNSLOTH_PYPI_JSON_URL) { $env:UNSLOTH_PYPI_JSON_URL } else { "https://pypi.org/pypi/unsloth/json" }
+ try {
+ $info = (Invoke-RestMethod -Uri $url -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop).info
+ return (Test-RequiresDistAdmitsTorch -RequiresDist @($info.requires_dist) -Want $Want)
+ } catch {
+ return $false
}
}
@@ -10999,7 +11134,23 @@ main()
}
}
} else {
- $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated)" { & $script:UvExe pip install --python $VenvPython --reinstall-package unsloth --reinstall-package unsloth-zoo "$_unslothReleaseInstallSpec" "unsloth-zoo>=2026.10.3" }
+ # As install.sh: freeze the trio for this with-deps resolve, then keep the release for the
+ # flavor repair below, which would otherwise reinstall the default range.
+ $script:TorchOverridesFile = New-UnslothTorchOverridesFile -PythonExe $VenvPython
+ $_migOverrides = @()
+ if ($script:TorchOverridesFile) { $_migOverrides = @("--overrides", $script:TorchOverridesFile) }
+ $baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated)" { & $script:UvExe pip install --python $VenvPython @_migOverrides --reinstall-package unsloth --reinstall-package unsloth-zoo "$_unslothReleaseInstallSpec" "unsloth-zoo>=2026.10.3" }
+ if ($script:TorchOverridesFile) {
+ Remove-UnslothTempFileQuietly -Path $script:TorchOverridesFile
+ $script:TorchOverridesFile = $null
+ }
+ Remove-Item Env:UNSLOTH_KEPT_TORCH -ErrorAction SilentlyContinue
+ $_migTorchVer = Get-InstalledTorchVersionRaw -PythonExe $VenvPython
+ if ($_migTorchVer -and -not $ROCmIndexUrl -and ((Get-TorchIndexLeafName $TorchIndexUrl) -match '^cu\d+$')) {
+ $_migWindow = if (Test-Cu130Torch213Platform -IndexUrl $TorchIndexUrl -PythonExe $VenvPython) { "torch>=2.4,<$($script:Cu130TorchCeiling)" } else { "torch>=2.4,<2.12.0" }
+ $script:PrevTorchPin = Get-PreviousTorchPin -TorchVersion $_migTorchVer -Constraint $_migWindow
+ if ($script:PrevTorchPin) { $env:UNSLOTH_KEPT_TORCH = $script:PrevTorchPin.Release.PublicBase }
+ }
}
if ($baseInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
@@ -11025,21 +11176,39 @@ main()
$_pinTorchSpec = "torch>=2.4,<2.12.0"
$_pinVisionSpec = "torchvision>=0.19,<0.27.0"
$_pinAudioSpec = "torchaudio>=2.4,<2.12.0"
+ $_preserveTorchSpec = $_pinTorchSpec
+ $_cu130NewInstallRoute = $false
+ if (-not $SkipTorch -and -not $ROCmIndexUrl) {
+ $_cu130Route = Resolve-Cu130TorchRoute -IndexUrl $TorchIndexUrl -PythonExe $VenvPython `
+ -DefaultSpec $_pinTorchSpec -ExistingInstall ([bool]$script:ExistingInstall) -PackageName $PackageName
+ $_preserveTorchSpec = $_cu130Route.PreserveSpec
+ $_cu130NewInstallRoute = $_cu130Route.NewInstall
+ }
# Release preservation, after every floor choice. Exported as UNSLOTH_KEPT_TORCH.
$script:PrevTorchPin = $null
# An interrupted run leaks a stale pin, so clear before deciding.
Remove-Item Env:UNSLOTH_KEPT_TORCH -ErrorAction SilentlyContinue
if (-not $SkipTorch -and $script:PrevTorchVer -and -not $ROCmMultiArch) {
- $_routeWindow = $_pinTorchSpec
+ $_routeWindow = $_preserveTorchSpec
# Vet the kept release against the XPU window, or a kept 2.5 becomes an unsatisfiable pin.
if ((Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") { $_routeWindow = (Get-XpuTorchSpecs -Platform (Get-VenvPlatformTag -PythonExe $VenvPython))[0] }
if ($ROCmIndexUrl -and $ROCmTorchFloor) { $_routeWindow = $ROCmTorchFloor }
$script:PrevTorchPin = Get-PreviousTorchPin -TorchVersion $script:PrevTorchVer -Constraint $_routeWindow
+ if (-not $script:PrevTorchPin -and $_routeWindow -eq $_preserveTorchSpec) {
+ $script:PrevTorchPin = Get-UpgradeKeptTorchPin -TorchVersion $script:PrevTorchVer `
+ -DefaultSpec $_pinTorchSpec -PreserveSpec $_preserveTorchSpec -NewInstallRoute $_cu130NewInstallRoute
+ }
if ($script:PrevTorchPin) {
$env:UNSLOTH_KEPT_TORCH = $script:PrevTorchPin.Release.PublicBase
substep "existing install has torch $script:PrevTorchVer -- keeping it (set UNSLOTH_TORCH_UPGRADE=1 to get the newest release)"
}
}
+ # A kept release that fails to reinstall falls back to the pre-route default below, never to 2.13.
+ if (-not $script:PrevTorchPin -and $_cu130NewInstallRoute) {
+ $_pinTorchSpec = $script:Cu130NewInstallTorchSpec
+ $_pinVisionSpec = $script:Cu130NewInstallVisionSpec
+ substep "cu130 + Python 3.13: installing torch 2.13, which the prebuilt flash-attn / causal-conv1d / mamba-ssm wheels are built for"
+ }
if ($SkipTorch) {
substep "skipping PyTorch (--no-torch flag set)." "Yellow"
} elseif ($ROCmIndexUrl) {
diff --git a/install.sh b/install.sh
index 84c813e7c53..77dba3ad87e 100755
--- a/install.sh
+++ b/install.sh
@@ -7260,7 +7260,9 @@ _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" ]; } \
+ # The PyPI check reads unsloth's metadata, so a --package other than unsloth keeps the default.
+ if [ "$(printf '%s' "$PACKAGE_NAME" | tr '[:upper:]' '[:lower:]')" = "unsloth" ] \
+ && { [ "$_EXISTING_INSTALL" = false ] || [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ]; } \
&& [ "$(_pypi_unsloth_admits_torch "2.13.0")" = "yes" ]; then
_CU130_NEW_INSTALL_ROUTE=true
fi
diff --git a/studio/backend/core/_msvc_env.py b/studio/backend/core/_msvc_env.py
index 6baaea50e46..a7044b04a4d 100644
--- a/studio/backend/core/_msvc_env.py
+++ b/studio/backend/core/_msvc_env.py
@@ -197,6 +197,29 @@ def crt_headers_reachable() -> bool:
return _headers_complete(triton_dirs + env_dirs)
+def _triton_windows_spec() -> str:
+ """The triton-windows range for the resident torch, as studio/setup.ps1 installs it.
+
+ Read from package metadata, not `import torch`: this runs before torch is imported. torch 2.13
+ pins triton 3.7 and 2.14 pins 3.8; anything older (or unreadable) keeps the long-standing <3.7.
+ A native ARM64 interpreter gets setup.ps1's Windows-on-ARM floor: no win_arm64 wheel predates it.
+ """
+ import platform # noqa: PLC0415
+
+ if platform.machine().lower() == "arm64":
+ return "triton-windows>=3.8.0.post28"
+ try:
+ from importlib.metadata import version # noqa: PLC0415
+ major, minor = (int(part) for part in version("torch").split("+", 1)[0].split(".")[:2])
+ except Exception: # noqa: BLE001 -- a hint must never raise
+ return "triton-windows<3.7"
+ if (major, minor) == (2, 13):
+ return "triton-windows>=3.7,<3.8"
+ if (major, minor) == (2, 14):
+ return "triton-windows>=3.8,<3.9"
+ return "triton-windows<3.7"
+
+
def gate_torch_compile_on_windows(log: logging.Logger) -> None:
if sys.platform != "win32":
return
@@ -206,7 +229,7 @@ def gate_torch_compile_on_windows(log: logging.Logger) -> None:
os.environ["TORCHDYNAMO_DISABLE"] = "1"
log.warning(
"Triton not found on Windows — torch.compile disabled. "
- 'Install for better performance: pip install "triton-windows<3.7"'
+ f'Install for better performance: pip install "{_triton_windows_spec()}"'
)
return
diff --git a/studio/backend/tests/test_cu130_repair_torch_specs.py b/studio/backend/tests/test_cu130_repair_torch_specs.py
index 47b6933f29e..6c9aaa3fd1a 100644
--- a/studio/backend/tests/test_cu130_repair_torch_specs.py
+++ b/studio/backend/tests/test_cu130_repair_torch_specs.py
@@ -3,9 +3,9 @@
"""`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.
+install.sh and install.ps1 give new Linux x86_64 and Windows x64 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
@@ -36,9 +36,11 @@ def _route(
machine = "x86_64",
py = (3, 13),
torch = None,
+ woa = False,
):
monkeypatch.setattr(mod.sys, "platform", platform)
monkeypatch.setattr(mod.platform, "machine", lambda: machine)
+ monkeypatch.setattr(mod, "_is_windows_arm64", lambda: woa)
monkeypatch.setattr(mod.sys, "version_info", (*py, 0, "final", 0))
monkeypatch.setattr(mod, "_resident_torch_release", lambda: torch)
@@ -53,8 +55,9 @@ def _route(
("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)
[email protected]("host", [{"platform": "linux"}, {"platform": "win32", "machine": "AMD64"}])
+def test_a_resident_release_is_kept(monkeypatch, mod, resident, expected, host):
+ _route(monkeypatch, mod, torch = resident, **host)
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
@@ -75,7 +78,10 @@ def test_no_keepable_release_repairs_to_the_default_range(monkeypatch, mod, resi
("https://download.pytorch.org/whl/cu126", {}),
("https://download.pytorch.org/whl/cpu", {}),
("https://download.pytorch.org/whl/rocm7.2", {}),
- (CU130, {"platform": "win32"}),
+ # Windows on ARM, native or an emulated x64 interpreter: not this route.
+ (CU130, {"platform": "win32", "machine": "ARM64", "woa": True}),
+ (CU130, {"platform": "win32", "machine": "AMD64", "woa": True}),
+ (CU130, {"platform": "win32", "machine": "AMD64", "py": (3, 12)}),
(CU130, {"platform": "darwin"}),
(CU130, {"machine": "aarch64"}),
(CU130, {"py": (3, 12)}),
@@ -128,7 +134,9 @@ def test_both_cuda_repairs_use_the_route_aware_specs(mod):
("linux", "2.12.1", False),
("linux", "2.11.0", False),
("linux", None, False),
- ("win32", "2.13.0", False),
+ ("win32", "2.13.0", True),
+ ("win32", "2.14.0", True),
+ ("win32", "2.11.0", False),
("darwin", "2.13.0", False),
],
)
@@ -136,6 +144,8 @@ 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, "_is_win_arm64_interpreter", lambda: False)
+ monkeypatch.setattr(mod, "_restrict_to_current_user", lambda path: True)
monkeypatch.setattr(mod, "_resident_torch_release", lambda: resident)
monkeypatch.setattr(
mod,
@@ -174,6 +184,69 @@ def test_core_update_freeze_restores_an_unset_override(monkeypatch, mod):
assert "UV_OVERRIDE" not in mod.os.environ
+def _spaced_windows_freeze(monkeypatch, tmp_path, mod):
+ monkeypatch.setattr(mod.sys, "platform", "win32")
+ monkeypatch.setattr(mod, "_is_win_arm64_interpreter", lambda: False)
+ monkeypatch.setattr(mod, "_restrict_to_current_user", lambda path: True)
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: "2.13.0")
+ monkeypatch.setattr(mod, "_resident_torch_trio_pins", lambda: ["torch==2.13.0+cu130"])
+ spaced = tmp_path / "John Smith"
+ spaced.mkdir()
+ monkeypatch.setattr(mod.tempfile, "tempdir", str(spaced))
+ # No 8.3 short name: uv_safe_path hands the spaced path back.
+ monkeypatch.setattr(mod, "_uv_safe_path", lambda path: str(path))
+ monkeypatch.delenv("UV_OVERRIDE", raising = False)
+ return spaced
+
+
+def test_core_update_freeze_never_writes_to_a_shared_windows_directory(monkeypatch, tmp_path, mod):
+ spaced = _spaced_windows_freeze(monkeypatch, tmp_path, mod)
+ public = tmp_path / "Public"
+ public.mkdir()
+ monkeypatch.setenv("PUBLIC", str(public))
+ venv = tmp_path / "venv"
+ venv.mkdir()
+ monkeypatch.setattr(mod.sys, "prefix", str(venv))
+ with mod._FreezeNewTorchForCoreUpdate() as freeze:
+ value = mod.os.environ["UV_OVERRIDE"]
+ assert Path(value).parent == venv and " " not in value
+ assert Path(value).read_text(encoding = "utf-8").split() == ["torch==2.13.0+cu130"]
+ assert mod._TORCH_FREEZE_ACTIVE is True
+ assert not freeze._path.exists()
+ assert list(spaced.iterdir()) == [] and list(public.iterdir()) == []
+
+
+def test_windows_without_a_private_space_free_directory_resolves_as_before(
+ monkeypatch, tmp_path, mod
+):
+ spaced = _spaced_windows_freeze(monkeypatch, tmp_path, mod)
+ public = tmp_path / "Public"
+ public.mkdir()
+ monkeypatch.setenv("PUBLIC", str(public))
+ monkeypatch.setattr(mod.sys, "prefix", str(spaced))
+ with mod._FreezeNewTorchForCoreUpdate() as freeze:
+ assert "UV_OVERRIDE" not in mod.os.environ
+ assert mod._TORCH_FREEZE_ACTIVE is False
+ assert freeze._path is None
+ assert list(spaced.iterdir()) == [] and list(public.iterdir()) == []
+
+
+def test_linux_stops_rather_than_resolving_unfrozen(monkeypatch, tmp_path, mod):
+ spaced = _spaced_windows_freeze(monkeypatch, tmp_path, mod)
+ monkeypatch.setattr(mod.sys, "platform", "linux")
+ monkeypatch.setattr(mod.sys, "prefix", str(spaced))
+ real_isdir = mod.os.path.isdir
+ monkeypatch.setattr(
+ mod.os.path, "isdir", lambda d: str(d).startswith(str(tmp_path)) and real_isdir(d)
+ )
+ with pytest.raises(SystemExit):
+ with mod._FreezeNewTorchForCoreUpdate():
+ pass
+ assert "UV_OVERRIDE" not in mod.os.environ
+ assert mod._TORCH_FREEZE_ACTIVE is False
+ assert list(spaced.iterdir()) == []
+
+
def test_both_core_updates_run_under_the_freeze():
source = _INSTALL_SCRIPT.read_text(encoding = "utf-8")
assert (
@@ -217,3 +290,67 @@ def test_inherited_relative_includes_still_resolve(monkeypatch, tmp_path, mod):
"--constraint=/abs/c.txt",
"-r https://example.com/r.txt",
]
+
+
+def test_core_update_freeze_leaves_windows_on_arm_to_its_own_overrides(monkeypatch, tmp_path, mod):
+ # install.ps1 writes the WoA UV_OVERRIDE; a second trio pin here would conflict with it.
+ monkeypatch.setattr(mod.sys, "platform", "win32")
+ monkeypatch.setattr(mod, "_is_win_arm64_interpreter", lambda: True)
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: "2.14.0")
+ monkeypatch.setattr(mod, "_resident_torch_trio_pins", lambda: ["torch==2.14.0+cu134"])
+ inherited = tmp_path / "woa-overrides.txt"
+ inherited.write_text("torch>=2.4\n", encoding = "utf-8")
+ monkeypatch.setenv("UV_OVERRIDE", str(inherited))
+ with mod._FreezeNewTorchForCoreUpdate():
+ assert mod.os.environ["UV_OVERRIDE"] == str(inherited)
+ assert mod._TORCH_FREEZE_ACTIVE is False
+
+
+def test_an_emulated_x64_venv_on_windows_on_arm_is_frozen(monkeypatch, tmp_path, mod):
+ # The WoA override only exists for a native win-arm64 interpreter.
+ monkeypatch.setattr(mod.sys, "platform", "win32")
+ monkeypatch.setattr(mod, "_is_windows_arm64", lambda: True)
+ monkeypatch.setattr(mod, "_is_win_arm64_interpreter", lambda: False)
+ monkeypatch.setattr(mod, "_restrict_to_current_user", lambda path: True)
+ monkeypatch.setattr(mod, "_resident_torch_release", lambda: "2.13.0")
+ monkeypatch.setattr(mod, "_resident_torch_trio_pins", lambda: ["torch==2.13.0"])
+ monkeypatch.setattr(mod.tempfile, "tempdir", str(tmp_path))
+ monkeypatch.delenv("UV_OVERRIDE", raising = False)
+ with mod._FreezeNewTorchForCoreUpdate():
+ assert mod._TORCH_FREEZE_ACTIVE is True
+
+
+def test_the_windows_override_is_private_before_its_contents_land(monkeypatch, tmp_path, mod):
+ monkeypatch.setattr(mod.sys, "platform", "win32")
+ calls = []
+
+ def run(cmd, **kwargs):
+ if cmd[0] == "whoami":
+ return mod.subprocess.CompletedProcess(
+ cmd, 0, '"host\\me","S-1-5-21-1-2-3-1001"\r\n', ""
+ )
+ calls.append((cmd, Path(cmd[1]).stat().st_size))
+ return mod.subprocess.CompletedProcess(cmd, 0, b"", b"")
+
+ monkeypatch.setattr(mod.subprocess, "run", run)
+ monkeypatch.setattr(mod.tempfile, "tempdir", str(tmp_path))
+ monkeypatch.setattr(mod, "_uv_safe_path", lambda path: str(path))
+ name, safe = mod._write_space_free_override("--index-url https://user:token@example/simple\n")
+ assert safe == name and Path(name).read_text(encoding = "utf-8").startswith("--index-url")
+ assert calls == [(["icacls", name, "/inheritance:r", "/grant:r", "*S-1-5-21-1-2-3-1001:F"], 0)]
+
+
+def test_a_directory_whose_acl_cannot_be_set_is_skipped(monkeypatch, tmp_path, mod):
+ monkeypatch.setattr(mod.sys, "platform", "win32")
+ temp, venv = tmp_path / "temp", tmp_path / "venv"
+ temp.mkdir()
+ venv.mkdir()
+ monkeypatch.setattr(mod.tempfile, "tempdir", str(temp))
+ monkeypatch.setattr(mod.sys, "prefix", str(venv))
+ monkeypatch.setattr(mod, "_uv_safe_path", lambda path: str(path))
+ monkeypatch.setattr(mod, "_restrict_to_current_user", lambda path: Path(path).parent == venv)
+ name, safe = mod._write_space_free_override("torch==2.13.0\n")
+ assert Path(name).parent == venv and list(temp.iterdir()) == []
+ monkeypatch.setattr(mod, "_restrict_to_current_user", lambda path: False)
+ assert mod._write_space_free_override("torch==2.13.0\n") == ("", None)
+ assert list(temp.iterdir()) == [] and list(venv.iterdir()) == [Path(name)]
diff --git a/studio/backend/tests/test_msvc_env_triton_hint.py b/studio/backend/tests/test_msvc_env_triton_hint.py
new file mode 100644
index 00000000000..cab8915bc19
--- /dev/null
+++ b/studio/backend/tests/test_msvc_env_triton_hint.py
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The "install Triton" hint names the triton-windows range setup.ps1 would install for this torch."""
+
+import importlib.metadata
+import platform
+
+import pytest
+
+from core import _msvc_env
+
+
+ "torch_version, spec",
+ [
+ ("2.13.0+cu130", "triton-windows>=3.7,<3.8"),
+ ("2.14.0", "triton-windows>=3.8,<3.9"),
+ ("2.11.0+cu128", "triton-windows<3.7"),
+ ("2.9.1", "triton-windows<3.7"),
+ ],
+)
+def test_spec_follows_the_resident_torch(monkeypatch, torch_version, spec):
+ monkeypatch.setattr(platform, "machine", lambda: "AMD64")
+ monkeypatch.setattr(importlib.metadata, "version", lambda name: torch_version)
+ assert _msvc_env._triton_windows_spec() == spec
+
+
+def test_unreadable_torch_keeps_the_old_range(monkeypatch):
+ def missing(name):
+ raise importlib.metadata.PackageNotFoundError(name)
+
+ monkeypatch.setattr(platform, "machine", lambda: "AMD64")
+ monkeypatch.setattr(importlib.metadata, "version", missing)
+ assert _msvc_env._triton_windows_spec() == "triton-windows<3.7"
+
+
+def test_windows_on_arm_gets_the_first_win_arm64_release(monkeypatch):
+ monkeypatch.setattr(platform, "machine", lambda: "ARM64")
+ monkeypatch.setattr(importlib.metadata, "version", lambda name: "2.11.0")
+ assert _msvc_env._triton_windows_spec() == "triton-windows>=3.8.0.post28"
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index b19559339b2..1d38ec5ab03 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -563,17 +563,26 @@ _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.
+# Mirrors install.sh / install.ps1's cu130 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_native_x86_64() -> bool:
+ """Linux x86_64, or Windows x64 on an x64 machine. An emulated x64 Python on Windows on ARM
+ is excluded: install.ps1 keys its torch 2.13 route on the machine as well as the interpreter."""
+ if platform.machine().lower() not in ("x86_64", "amd64"):
+ return False
+ if sys.platform.startswith("linux"):
+ return True
+ return sys.platform == "win32" and not _is_windows_arm64()
+
+
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 _is_native_x86_64()
and sys.version_info[:2] == (3, 13)
)
@@ -629,14 +638,74 @@ _TORCH_TRIO_LINE = re.compile(r"^\s*torch(vision|audio)?([\s<>=!~;@\[]|$)", re.I
_TORCH_FREEZE_ACTIVE = False
+def _restrict_to_current_user(path: str) -> bool:
+ """On Windows, replace PATH's inherited ACL with one granting only the current user."""
+ if sys.platform != "win32":
+ return True
+ try:
+ who = subprocess.run(
+ ["whoami", "/user", "/fo", "csv", "/nh"], capture_output = True, text = True, timeout = 30
+ )
+ sid = who.stdout.strip().rsplit(",", 1)[-1].strip().strip('"')
+ if who.returncode != 0 or not sid.startswith("S-"):
+ return False
+ granted = subprocess.run(
+ ["icacls", path, "/inheritance:r", "/grant:r", f"*{sid}:F"],
+ capture_output = True,
+ timeout = 30,
+ )
+ return granted.returncode == 0
+ except (OSError, subprocess.SubprocessError):
+ return False
+
+
+def _write_space_free_override(text: str) -> tuple[str, str | None]:
+ """Write TEXT to an overrides file uv can name: (path, space-free path to hand uv, or None).
+
+ Only user-private files: inherited override lines can carry authenticated index URLs.
+ mkstemp's 0600 covers POSIX; a Windows file takes its directory's ACL, so it gets an explicit
+ current-user-only one, and a directory where that fails is skipped.
+ """
+ if sys.platform == "win32":
+ candidates = [None, sys.prefix]
+ else:
+ candidates = [None, "/tmp", "/var/tmp", sys.prefix]
+ for directory in candidates:
+ if directory is not None and (
+ any(ch.isspace() for ch in directory) or not os.path.isdir(directory)
+ ):
+ continue
+ try:
+ fd, name = tempfile.mkstemp(
+ prefix = "unsloth-torch-overrides-", suffix = ".txt", dir = directory
+ )
+ except OSError:
+ continue
+ # Still empty: restrict it before the contents land, as install.ps1 does for its copy.
+ if not _restrict_to_current_user(name):
+ os.close(fd)
+ Path(name).unlink(missing_ok = True)
+ continue
+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:
+ handle.write(text)
+ # %TEMP% under a spaced profile is fine when it has an 8.3 short name.
+ safe = _uv_safe_path(name)
+ if not any(ch.isspace() for ch in safe):
+ return name, safe
+ Path(name).unlink(missing_ok = True)
+ return "", None
+
+
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.
+ the matching prebuilt kernels. install.sh and install.ps1 freeze the trio the same way for
+ every with-deps unsloth install. Scoped to Linux and native Windows x64 with torch >= 2.13,
+ the releases past that ceiling, so every other install resolves exactly as before; a native
+ Windows on ARM interpreter keeps its own UV_OVERRIDE (_woa_overrides_are_load_bearing), an
+ emulated x64 one there is frozen like any x64 install.
"""
def __enter__(self):
@@ -644,7 +713,10 @@ class _FreezeNewTorchForCoreUpdate:
self._previous = os.environ.get("UV_OVERRIDE")
release = _resident_torch_release()
if not (
- sys.platform.startswith("linux")
+ (
+ sys.platform.startswith("linux")
+ or (sys.platform == "win32" and not _is_win_arm64_interpreter())
+ )
and release is not None
and int(release.split(".")[1]) >= 13
):
@@ -669,11 +741,20 @@ class _FreezeNewTorchForCoreUpdate:
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")
+ name, safe = _write_space_free_override("\n".join(lines) + "\n")
+ if safe is None:
+ # uv splits UV_OVERRIDE on whitespace. Windows ran unfrozen before this freeze existed;
+ # on Linux a spaced path always stopped the update, which keeps the resident torch.
+ if sys.platform == "win32":
+ return self
+ _step(
+ "error",
+ "no writable directory without spaces for the torch freeze; set TMPDIR to one",
+ _red,
+ )
+ raise SystemExit(1)
self._path = Path(name)
- os.environ["UV_OVERRIDE"] = _uv_safe_path(self._path)
+ os.environ["UV_OVERRIDE"] = safe
global _TORCH_FREEZE_ACTIVE
_TORCH_FREEZE_ACTIVE = True
return self
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index e06daaf0178..34245c60966 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -8760,6 +8760,18 @@ if ($WinArm64Venv -and $WinArm64EffectiveTorchIndexUrl) {
}
# <3.7 everywhere except Windows on ARM, whose first win_arm64 wheel is 3.8.0.post28.
$_tritonSpec = if ($WinArm64Venv) { "triton-windows>=3.8.0.post28" } else { "triton-windows<3.7" }
+# triton-windows: torch 2.13 -> 3.7, 2.14 -> 3.8, older keeps <3.7.
+function Get-TritonWindowsSpec {
+ param([string]$TorchVersion, [bool]$WinArm64 = $false)
+ if ($WinArm64) { return "triton-windows>=3.8.0.post28" }
+ if ($TorchVersion -match '^2\.(\d+)\.') {
+ switch ([int]$Matches[1]) {
+ 13 { return "triton-windows>=3.7,<3.8" }
+ 14 { return "triton-windows>=3.8,<3.9" }
+ }
+ }
+ return "triton-windows<3.7"
+}
# The win_arm64 index publishes only the trio, so a dependency index rides beside it (the caller's configured one, public PyPI by default). Not gated on $UseUv: pip needs the extra index too.
$WinArm64IndexArgs = if ($WinArm64Venv) {
$_woaResolver = if ($UseUv) { "uv" } else { "pip" }
@@ -8808,7 +8820,7 @@ if ($ROCmIndexUrl) {
if (-not ($ROCmTorchSpec -match 'torch>=2\.11' -and $_keptMinor -lt 11)) {
$ROCmTorchSpec = "torch==$($env:UNSLOTH_KEPT_TORCH)"
$ROCmVisionSpec = "torchvision==0.$($_keptMinor + 15).*"
- $ROCmAudioSpec = "torchaudio==2.$($_keptMinor).*"
+ $ROCmAudioSpec = "torchaudio==2.$([Math]::Min($_keptMinor, 11)).*"
$_rocmKeptActive = $true
}
}
@@ -8972,7 +8984,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
$_keptMinor = [int](($env:UNSLOTH_KEPT_TORCH -split '\.')[1])
$cpuTorchSpec = "torch==$($env:UNSLOTH_KEPT_TORCH)"
$cpuVisionSpec = "torchvision==0.$($_keptMinor + 15).*"
- $cpuAudioSpec = "torchaudio==2.$($_keptMinor).*"
+ $cpuAudioSpec = "torchaudio==2.$([Math]::Min($_keptMinor, 11)).*"
$_cpuKeptActive = $true
}
while ($true) {
@@ -9026,12 +9038,28 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# Release preservation: keep the same release across re-runs (+cuXXX follows this index).
# Not on win_arm64: the kept release is one NVIDIA's channel does not publish.
$_cudaKeptActive = $false
- $_cudaOrigTorch = $cudaTorchSpec; $_cudaOrigVision = $cudaVisionSpec; $_cudaOrigAudio = $cudaAudioSpec
- if (-not $WinArm64Venv -and $env:UNSLOTH_KEPT_TORCH -match '^\d+\.\d+(\.\d+)?$') {
- $_keptMinor = [int](($env:UNSLOTH_KEPT_TORCH -split '\.')[1])
- $cudaTorchSpec = "torch==$($env:UNSLOTH_KEPT_TORCH)"
+ $_cudaKeptRelease = $env:UNSLOTH_KEPT_TORCH
+ $_cudaKeptFromResident = $false
+ # No installer handoff (`studio update`, the startup repair, a re-run of setup): keep the resident
+ # release like install.sh, forced or not. Unpinned, a missing torchvision alone resolves the
+ # newest one and drags torch up with it. UPGRADE=1 asks for newer.
+ if (-not $WinArm64Venv -and -not $_cudaKeptRelease -and $env:UNSLOTH_TORCH_UPGRADE -ne "1") {
+ $_residentProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code "import importlib.metadata as m; print(m.version('torch'))"
+ # Only a release this index publishes, so a CUDA family change never pins an unservable one.
+ # download.pytorch.org win_amd64: cu126 2.6-2.14, cu128 2.7-2.11, cu129 2.8-2.9, cu130 2.9-2.14.
+ $_keptRange = @{ "cu126" = @(6, 14); "cu128" = @(7, 11); "cu129" = @(8, 9); "cu130" = @(9, 14) }[[string]$CuTag]
+ if ($_keptRange -and $_residentProbe.Ok -and ($_residentProbe.Output -match '(?m)^(2\.(\d+)\.\d+)(\+\S*)?\s*$') -and
+ [int]$Matches[2] -ge $_keptRange[0] -and [int]$Matches[2] -le $_keptRange[1]) {
+ $_cudaKeptRelease = $Matches[1]
+ $_cudaKeptFromResident = $true
+ }
+ }
+ if (-not $WinArm64Venv -and $_cudaKeptRelease -match '^\d+\.\d+(\.\d+)?$') {
+ $_keptMinor = [int](($_cudaKeptRelease -split '\.')[1])
+ $cudaTorchSpec = "torch==$_cudaKeptRelease"
$cudaVisionSpec = "torchvision==0.$($_keptMinor + 15).*"
- $cudaAudioSpec = "torchaudio==2.$($_keptMinor).*"
+ # torchaudio 2.11 is the last release (stable ABI), so newer torch minors pair with it.
+ $cudaAudioSpec = "torchaudio==2.$([Math]::Min($_keptMinor, 11)).*"
$_cudaKeptActive = $true
}
while ($true) {
@@ -9089,10 +9117,16 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
foreach ($_woaCutoffName in @($_woaCutoffSaved.Keys)) { Set-Item "Env:$_woaCutoffName" $_woaCutoffSaved[$_woaCutoffName] }
}
if ($torchInstallExit -eq 0 -or -not $_cudaKeptActive) { break }
- substep "[WARN] torch==$($env:UNSLOTH_KEPT_TORCH) not installable from this CUDA index -- using the supported release" "Yellow"
- $cudaTorchSpec = $_cudaOrigTorch; $cudaVisionSpec = $_cudaOrigVision; $cudaAudioSpec = $_cudaOrigAudio
- Remove-Item Env:UNSLOTH_KEPT_TORCH -ErrorAction SilentlyContinue
- $_cudaKeptActive = $false
+ # Nothing forced and the pin was only ours: retry exactly what an unpinned run would have done.
+ if ($_cudaKeptFromResident -and $cudaForce.Count -eq 0) {
+ $cudaTorchSpec = "torch"; $cudaVisionSpec = "torchvision"; $cudaAudioSpec = "torchaudio"
+ $_cudaKeptActive = $false
+ continue
+ }
+ # Otherwise stop, like install_python_stack.py: a second resolve under another range would
+ # download a different torch (usually after a transient failure) and move the release unasked.
+ substep "[WARN] torch==$_cudaKeptRelease could not be reinstalled; re-run, or set UNSLOTH_TORCH_UPGRADE=1 to move to the supported release" "Yellow"
+ break
}
if ($torchInstallExit -ne 0) {
Write-StudioLine "[FAILED] PyTorch CUDA install failed (exit code $torchInstallExit)" -ForegroundColor Red
@@ -9121,7 +9155,13 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
}
}
- # Triton for Windows enables torch.compile (without it training can hang).
+ # Triton for Windows enables torch.compile (without it training can hang). Paired with the
+ # installed torch, read from metadata.
+ $_tritonTorchProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code "import importlib.metadata as m; print(m.version('torch'))"
+ if ($_tritonTorchProbe.Ok) {
+ $_tritonTorchVer = @($_tritonTorchProbe.Output -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ })
+ if ($_tritonTorchVer.Count -gt 0) { $_tritonSpec = Get-TritonWindowsSpec -TorchVersion $_tritonTorchVer[-1] -WinArm64 ([bool]$WinArm64Venv) }
+ }
substep "installing Triton for Windows..."
if ($script:UnslothVerbose) {
Fast-Install $_tritonSpec
diff --git a/tests/sh/test_cu130_torch213_route.sh b/tests/sh/test_cu130_torch213_route.sh
index 181a32b3e40..dfbed61ecfc 100644
--- a/tests/sh/test_cu130_torch213_route.sh
+++ b/tests/sh/test_cu130_torch213_route.sh
@@ -89,7 +89,7 @@ echo "=== preservation never waits on PyPI; only a fresh home takes 2.13 ==="
_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"
+_CU130_TORCH_CEILING="2.15.0"; _CU130_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"; SKIP_TORCH=false; TORCH_INDEX_URL="$CU130"; PACKAGE_NAME="unsloth"
_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"
@@ -114,6 +114,11 @@ for gate in unreachable capped open; do
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"
+PACKAGE_NAME="unsloth-fork"; _run_block false ""; PACKAGE_NAME="unsloth"
+assert_eq "--package other than unsloth: fresh home keeps the old default" "torch>=2.4,<2.12.0" "$TORCH_CONSTRAINT"
+assert_eq "--package other than unsloth: window still wide" "torch>=2.4,<2.15.0" "$_PRESERVE_TORCH_CONSTRAINT"
+PACKAGE_NAME="Unsloth"; _run_block false ""; PACKAGE_NAME="unsloth"
+assert_eq "--package Unsloth is unsloth" "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" ;;
diff --git a/tests/studio/test_cu130_torch213_route.ps1 b/tests/studio/test_cu130_torch213_route.ps1
new file mode 100644
index 00000000000..0be761f04be
--- /dev/null
+++ b/tests/studio/test_cu130_torch213_route.ps1
@@ -0,0 +1,288 @@
+#!/usr/bin/env pwsh
+# 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.ps1 gives new Windows x64 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. The
+# Windows port of tests/sh/test_cu130_torch213_route.sh. Helpers are extracted from install.ps1 by
+# AST; the interpreter, host arch, mirror check and PyPI fetch are stubs.
+# Run: pwsh -NoProfile -File tests/studio/test_cu130_torch213_route.ps1
+
+$ErrorActionPreference = "Stop"
+$root = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path
+$installPath = Join-Path $root "install.ps1"
+$setupPath = Join-Path (Join-Path $root "studio") "setup.ps1"
+
+function Get-FunctionAsts([string]$Path, [string[]]$Names) {
+ $tokens = $null; $errors = $null
+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors)
+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$Path has parse errors" }
+ foreach ($name in $Names) {
+ $fn = $ast.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name
+ }, $true)
+ if ($fn.Count -ne 1) { throw "expected exactly one $name in $Path, found $($fn.Count)" }
+ $fn[0].Extent.Text
+ }
+}
+
+foreach ($text in (Get-FunctionAsts $installPath @(
+ "ConvertTo-TorchNumericRelease", "Test-TorchReleaseInWindow",
+ "Get-PreviousTorchPin", "Get-TorchIndexLeafName", "Test-Cu130Torch213Platform",
+ "Resolve-Cu130TorchRoute", "Get-UpgradeKeptTorchPin", "Test-RequiresDistAdmitsTorch",
+ "Test-PypiUnslothAdmitsTorch", "Get-TorchVersionFromDisk", "Test-UvEnvFlag"))) {
+ Invoke-Expression $text
+}
+foreach ($text in (Get-FunctionAsts $setupPath @("Get-TritonWindowsSpec"))) { Invoke-Expression $text }
+$script:Cu130TorchCeiling = "2.15.0"
+
+# Stubs. Functions shadow cmdlets, so Invoke-RestMethod here never reaches the network.
+$script:HostArch = "x86_64"
+$script:VenvAnswer = "3.13 win-amd64"
+$script:VenvOk = $true
+$script:Mirror = $false
+$script:RequiresDist = @("torch<2.15.0,>=2.4.0", "torchvision; extra == 'colab'", "numpy")
+$script:FetchFails = $false
+$script:Fetches = 0
+function Get-HostMachineArch { return $script:HostArch }
+function Invoke-BoundedPythonProbe { param($PythonExe, $Code, $TimeoutSec)
+ return [pscustomobject]@{ Ok = $script:VenvOk; Output = "noise from sitecustomize`n$($script:VenvAnswer)`n"; Error = "" } }
+function Test-MirrorConfigured { param($Tool) return $script:Mirror }
+function Invoke-RestMethod { param($Uri, [switch]$UseBasicParsing, $TimeoutSec, $ErrorAction)
+ $script:Fetches++
+ $script:LastUri = $Uri
+ if ($script:FetchFails) { throw "network down" }
+ return [pscustomobject]@{ info = [pscustomobject]@{ requires_dist = $script:RequiresDist } } }
+
+$failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" }
+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+function Reset-Stubs {
+ $script:HostArch = "x86_64"; $script:VenvAnswer = "3.13 win-amd64"; $script:VenvOk = $true
+ $script:Mirror = $false; $script:FetchFails = $false; $script:Fetches = 0
+ $script:RequiresDist = @("torch<2.15.0,>=2.4.0", "torchvision; extra == 'colab'", "numpy")
+}
+
+$cu130 = "https://download.pytorch.org/whl/cu130"
+$default = "torch>=2.4,<2.12.0"
+$saved = @{}
+foreach ($n in @("UNSLOTH_TORCH_UPGRADE", "UV_OFFLINE", "UV_EXCLUDE_NEWER", "UV_EXCLUDE_NEWER_PACKAGE", "UNSLOTH_PYPI_JSON_URL")) {
+ $saved[$n] = [Environment]::GetEnvironmentVariable($n)
+ [Environment]::SetEnvironmentVariable($n, $null)
+}
+try {
+ Write-Host "=== platform predicate ==="
+ Reset-Stubs
+ Check "cu130 + x64 host + native 3.13 win-amd64 venv" (Test-Cu130Torch213Platform -IndexUrl $cu130 -PythonExe "py")
+ Check "cu130 with a ?token query still counts" (Test-Cu130Torch213Platform -IndexUrl "$cu130/?token=x" -PythonExe "py")
+ foreach ($leaf in @("cu128", "cu126", "cpu", "xpu", "rocm7.2")) {
+ Check "index $leaf is not the route" (-not (Test-Cu130Torch213Platform -IndexUrl "https://download.pytorch.org/whl/$leaf" -PythonExe "py"))
+ }
+ Check "no index is not the route" (-not (Test-Cu130Torch213Platform -IndexUrl "" -PythonExe "py"))
+ $script:HostArch = "arm64"
+ Check "Windows on ARM host is not the route (emulated x64 included)" (-not (Test-Cu130Torch213Platform -IndexUrl $cu130 -PythonExe "py"))
+ Reset-Stubs
+ foreach ($a in @("3.12 win-amd64", "3.11 win-amd64", "3.14 win-amd64", "3.13 win-arm64", "3.13 win32")) {
+ $script:VenvAnswer = $a
+ Check "venv '$a' is not the route" (-not (Test-Cu130Torch213Platform -IndexUrl $cu130 -PythonExe "py"))
+ }
+ Reset-Stubs
+ $script:VenvOk = $false
+ Check "an interpreter that does not answer is not the route" (-not (Test-Cu130Torch213Platform -IndexUrl $cu130 -PythonExe "py"))
+
+ Write-Host "=== PyPI gate ==="
+ Reset-Stubs
+ Check "newest unsloth admitting 2.13 says yes" (Test-PypiUnslothAdmitsTorch -Want "2.13.0")
+ Check "default URL is public PyPI" ($script:LastUri -eq "https://pypi.org/pypi/unsloth/json")
+ $env:UNSLOTH_PYPI_JSON_URL = "https://mirror.example/pypi/unsloth/json"
+ [void](Test-PypiUnslothAdmitsTorch -Want "2.13.0")
+ Check "UNSLOTH_PYPI_JSON_URL redirects the check" ($script:LastUri -eq "https://mirror.example/pypi/unsloth/json")
+ Remove-Item Env:UNSLOTH_PYPI_JSON_URL
+ $script:RequiresDist = @("torch<2.13.0,>=2.4.0")
+ Check "a release capped below 2.13 says no" (-not (Test-PypiUnslothAdmitsTorch -Want "2.13.0"))
+ Reset-Stubs; $script:FetchFails = $true
+ Check "a failed fetch says no" (-not (Test-PypiUnslothAdmitsTorch -Want "2.13.0"))
+ foreach ($v in @("1", "true", "YES", " on ")) {
+ Reset-Stubs; $env:UV_OFFLINE = $v
+ Check "UV_OFFLINE='$v' says no without fetching" ((-not (Test-PypiUnslothAdmitsTorch -Want "2.13.0")) -and $script:Fetches -eq 0)
+ }
+ Remove-Item Env:UV_OFFLINE
+ Reset-Stubs; $env:UV_OFFLINE = "0"
+ Check "UV_OFFLINE=0 still checks" (Test-PypiUnslothAdmitsTorch -Want "2.13.0")
+ Remove-Item Env:UV_OFFLINE
+ foreach ($n in @("UV_EXCLUDE_NEWER", "UV_EXCLUDE_NEWER_PACKAGE")) {
+ Reset-Stubs; [Environment]::SetEnvironmentVariable($n, "2026-01-01")
+ Check "$n says no without fetching" ((-not (Test-PypiUnslothAdmitsTorch -Want "2.13.0")) -and $script:Fetches -eq 0)
+ [Environment]::SetEnvironmentVariable($n, $null)
+ }
+ Reset-Stubs; $script:Mirror = $true
+ Check "a configured uv index says no without fetching" ((-not (Test-PypiUnslothAdmitsTorch -Want "2.13.0")) -and $script:Fetches -eq 0)
+
+ Write-Host "=== Requires-Dist parsing ==="
+ $rd = @(
+ @{ r = @("torch<2.15.0,>=2.4.0"); ok = $true; n = "range admitting 2.13" }
+ @{ r = @("torch (<2.15.0,>=2.4.0)"); ok = $true; n = "parenthesised range" }
+ @{ r = @("torch<2.15.0,>=2.4.0; sys_platform != 'darwin'"); ok = $true; n = "marker after the range" }
+ @{ r = @("torch<2.13.0,>=2.4.0"); ok = $false; n = "ceiling at 2.13" }
+ @{ r = @("torch>=2.13.1"); ok = $false; n = "floor above 2.13.0" }
+ @{ r = @("torch!=2.13.0,<2.15"); ok = $false; n = "2.13.0 excluded" }
+ @{ r = @("torch==2.13.0"); ok = $true; n = "exact 2.13.0" }
+ @{ r = @("torch<2.15", "torch<2.14; extra == 'x'"); ok = $true; n = "extras are ignored" }
+ @{ r = @("torch<2.15", "torch>=2.4"); ok = $false; n = "two unconditional specs" }
+ @{ r = @("torch"); ok = $false; n = "bare torch" }
+ @{ r = @("torch~=2.13"); ok = $false; n = "unparsed operator" }
+ @{ r = @(); ok = $false; n = "no torch requirement" }
+ @{ r = @("torchvision<0.30"); ok = $false; n = "torchvision is not torch" }
+ )
+ foreach ($t in $rd) {
+ Check ("requires_dist: " + $t.n) ((Test-RequiresDistAdmitsTorch -RequiresDist $t.r -Want "2.13.0") -eq $t.ok)
+ }
+
+ Write-Host "=== route decision ==="
+ Reset-Stubs
+ $r = Resolve-Cu130TorchRoute -IndexUrl $cu130 -PythonExe "py" -DefaultSpec $default -ExistingInstall $false
+ Check "new install takes the route" ($r.NewInstall -and $r.PreserveSpec -eq "torch>=2.4,<2.15.0")
+ $r = Resolve-Cu130TorchRoute -IndexUrl $cu130 -PythonExe "py" -DefaultSpec $default -ExistingInstall $true
+ Check "existing install does not take the route but gets the wide window" ((-not $r.NewInstall) -and $r.PreserveSpec -eq "torch>=2.4,<2.15.0")
+ Check "existing install never asks PyPI" ($script:Fetches -eq 1)
+ $env:UNSLOTH_TORCH_UPGRADE = "1"
+ $r = Resolve-Cu130TorchRoute -IndexUrl $cu130 -PythonExe "py" -DefaultSpec $default -ExistingInstall $true
+ Check "UNSLOTH_TORCH_UPGRADE=1 opts an existing install in" ($r.NewInstall)
+ Remove-Item Env:UNSLOTH_TORCH_UPGRADE
+ Reset-Stubs
+ $r = Resolve-Cu130TorchRoute -IndexUrl $cu130 -PythonExe "py" -DefaultSpec $default -ExistingInstall $false -PackageName "unsloth-fork"
+ Check "--package other than unsloth: no route, window still wide, no fetch" ((-not $r.NewInstall) -and $r.PreserveSpec -eq "torch>=2.4,<2.15.0" -and $script:Fetches -eq 0)
+ $script:FetchFails = $true
+ $r = Resolve-Cu130TorchRoute -IndexUrl $cu130 -PythonExe "py" -DefaultSpec $default -ExistingInstall $false
+ Check "PyPI down: no route, window still wide" ((-not $r.NewInstall) -and $r.PreserveSpec -eq "torch>=2.4,<2.15.0")
+ Reset-Stubs
+ $r = Resolve-Cu130TorchRoute -IndexUrl "https://download.pytorch.org/whl/cu128" -PythonExe "py" -DefaultSpec $default -ExistingInstall $false
+ Check "cu128: default window, no route, no fetch" ((-not $r.NewInstall) -and $r.PreserveSpec -eq $default -and $script:Fetches -eq 0)
+
+ Write-Host "=== preservation under the route window ==="
+ $wide = "torch>=2.4,<2.15.0"
+ foreach ($v in @("2.11.0+cu130", "2.12.1+cu130", "2.13.0+cu130", "2.14.0+cu130")) {
+ $pin = Get-PreviousTorchPin -TorchVersion $v -Constraint $wide
+ Check "existing $v is kept" ($null -ne $pin -and $pin.TorchSpec -eq "torch==$(($v -split '\+')[0])")
+ }
+ $pin = Get-PreviousTorchPin -TorchVersion "2.13.0+cu130" -Constraint $wide
+ Check "kept 2.13 pairs torchvision 0.28 and torchaudio 2.11" ($pin.VisionSpec -eq "torchvision==0.28.*" -and $pin.AudioSpec -eq "torchaudio==2.11.*")
+ $pin = Get-PreviousTorchPin -TorchVersion "2.10.0+cu130" -Constraint $wide
+ Check "kept 2.10 still pairs torchaudio 2.10" ($pin.AudioSpec -eq "torchaudio==2.10.*")
+ Check "2.15 is outside the window" ($null -eq (Get-PreviousTorchPin -TorchVersion "2.15.0+cu130" -Constraint $wide))
+ Check "the old window would have dropped a 2.13 install" ($null -eq (Get-PreviousTorchPin -TorchVersion "2.13.0+cu130" -Constraint $default))
+
+ Write-Host "=== UNSLOTH_TORCH_UPGRADE=1 with the route closed ==="
+ $env:UNSLOTH_TORCH_UPGRADE = "1"
+ Check "upgrade drops the ordinary pin" ($null -eq (Get-PreviousTorchPin -TorchVersion "2.13.0+cu130" -Constraint $wide))
+ $pin = Get-UpgradeKeptTorchPin -TorchVersion "2.13.0+cu130" -DefaultSpec $default -PreserveSpec $wide -NewInstallRoute $false
+ Check "route closed: a resident 2.13 is kept, not moved down to 2.11" ($pin.TorchSpec -eq "torch==2.13.0")
+ $pin = Get-UpgradeKeptTorchPin -TorchVersion "2.14.0+cu130" -DefaultSpec $default -PreserveSpec $wide -NewInstallRoute $false
+ Check "route closed: a resident 2.14 is kept" ($pin.TorchSpec -eq "torch==2.14.0")
+ Check "route closed: a resident 2.11 still upgrades within the default range" (
+ $null -eq (Get-UpgradeKeptTorchPin -TorchVersion "2.11.0+cu130" -DefaultSpec $default -PreserveSpec $wide -NewInstallRoute $false))
+ Check "route open: nothing is kept, 2.13 installs" (
+ $null -eq (Get-UpgradeKeptTorchPin -TorchVersion "2.14.0+cu130" -DefaultSpec $default -PreserveSpec $wide -NewInstallRoute $true))
+ Check "off the route: nothing is kept" (
+ $null -eq (Get-UpgradeKeptTorchPin -TorchVersion "2.13.0+cu128" -DefaultSpec $default -PreserveSpec $default -NewInstallRoute $false))
+ Remove-Item Env:UNSLOTH_TORCH_UPGRADE
+ Check "without upgrade the helper never pins" (
+ $null -eq (Get-UpgradeKeptTorchPin -TorchVersion "2.13.0+cu130" -DefaultSpec $default -PreserveSpec $wide -NewInstallRoute $false))
+
+ Write-Host "=== legacy torch version read off disk ==="
+ $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("cu130route." + [guid]::NewGuid())
+ try {
+ # The helper joins a Windows-style relative path; on a POSIX host that is one file name.
+ $versionPy = Join-Path $tmp "Lib\site-packages\torch\version.py"
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $versionPy) | Out-Null
+ Set-Content -LiteralPath $versionPy -Value @("from typing import Optional", "__version__ = '2.13.0+cu130'", "git_version = 'abc'")
+ Check "version.py gives the release" ((Get-TorchVersionFromDisk -VenvRoot $tmp) -eq "2.13.0+cu130")
+ Check "missing version.py gives nothing" ($null -eq (Get-TorchVersionFromDisk -VenvRoot (Join-Path $tmp "nope")))
+ } finally {
+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue
+ }
+
+ Write-Host "=== setup.ps1 triton-windows pairing ==="
+ Check "torch 2.11 keeps triton-windows <3.7" ((Get-TritonWindowsSpec -TorchVersion "2.11.0+cu130") -eq "triton-windows<3.7")
+ Check "torch 2.12 keeps triton-windows <3.7" ((Get-TritonWindowsSpec -TorchVersion "2.12.1+cu130") -eq "triton-windows<3.7")
+ Check "torch 2.13 pairs triton-windows 3.7" ((Get-TritonWindowsSpec -TorchVersion "2.13.0+cu130") -eq "triton-windows>=3.7,<3.8")
+ Check "torch 2.14 pairs triton-windows 3.8" ((Get-TritonWindowsSpec -TorchVersion "2.14.0+cu130") -eq "triton-windows>=3.8,<3.9")
+ Check "unknown torch keeps <3.7" ((Get-TritonWindowsSpec -TorchVersion "") -eq "triton-windows<3.7")
+ Check "Windows on ARM is unchanged" ((Get-TritonWindowsSpec -TorchVersion "2.14.0+cu134" -WinArm64 $true) -eq "triton-windows>=3.8.0.post28")
+
+ Write-Host "=== wiring ==="
+ $install = Get-Content -LiteralPath $installPath -Raw
+ $setup = Get-Content -LiteralPath $setupPath -Raw
+ Check "the route is decided before preservation" ($install -match '(?s)Resolve-Cu130TorchRoute -IndexUrl \$TorchIndexUrl.*?\$_routeWindow = \$_preserveTorchSpec')
+ Check "the route skips ROCm and --no-torch" ($install -match 'if \(-not \$SkipTorch -and -not \$ROCmIndexUrl\) \{\s*\$_cu130Route = Resolve-Cu130TorchRoute')
+ Check "2.13 applies only when nothing was kept" ($install -match '(?s)if \(-not \$script:PrevTorchPin -and \$_cu130NewInstallRoute\) \{\s*\$_pinTorchSpec = \$script:Cu130NewInstallTorchSpec\s*\$_pinVisionSpec = \$script:Cu130NewInstallVisionSpec')
+ Check "the generic CUDA install uses the hoisted specs" ($install -match '\$_torchSpecs = @\(\$_pinTorchSpec, \$_pinVisionSpec, \$_pinAudioSpec\)')
+ Check "every earlier layout counts as an existing install" (
+ ([regex]::Matches($install, '\$script:ExistingInstall = \$true')).Count -eq 3)
+ Check "an occupied venv whose interpreter cannot answer keeps its torch from disk" ($install -match '(?s)\$script:PrevTorchVer = Get-InstalledTorchVersionRaw -PythonExe \$VenvPython\s*#[^\n]*\n\s*#[^\n]*\n\s*if \(-not \$script:PrevTorchVer\) \{ \$script:PrevTorchVer = Get-TorchVersionFromDisk -VenvRoot \$VenvDir \}')
+ Check "the CWD-relative legacy venv records its torch before it is migrated" ($install -match '(?s)\$_cwdVenvPy -and \(\s*\(Test-Path -LiteralPath \$_cwdVenvPy\) -or\s*\(Test-Path -LiteralPath \(Join-Path [^\n]*"pyvenv\.cfg"\) -PathType Leaf\)\)\) \{.*?\$script:ExistingInstall = \$true.*?\$script:PrevTorchVer = Get-InstalledTorchVersionRaw -PythonExe \$_cwdVenvPy \}\s*if \(-not \$script:PrevTorchVer\) \{ \$script:PrevTorchVer = Get-TorchVersionFromDisk')
+ Check "a migrated venv freezes its trio for the core install" ($install -match '(?s)\$script:TorchOverridesFile = New-UnslothTorchOverridesFile -PythonExe \$VenvPython\s*\$_migOverrides = @\(\)\s*if \(\$script:TorchOverridesFile\) \{ \$_migOverrides = @\("--overrides", \$script:TorchOverridesFile\) \}.*?-Label "install unsloth \(migrated\)" \{ & \$script:UvExe pip install --python \$VenvPython @_migOverrides ')
+ Check "a migrated CUDA venv keeps its release for the flavor repair" ($install -match '(?s)\$_migTorchVer = Get-InstalledTorchVersionRaw -PythonExe \$VenvPython.*?\$script:PrevTorchPin = Get-PreviousTorchPin -TorchVersion \$_migTorchVer -Constraint \$_migWindow.*?\$env:UNSLOTH_KEPT_TORCH = \$script:PrevTorchPin\.Release\.PublicBase')
+ $probeRe = [regex]::Match($setup, "_residentProbe\.Output -match '([^']+)'").Groups[1].Value
+ foreach ($t in @(@("2.11.0+cu130", "2.11.0"), @("2.14.0", "2.14.0"), @("2.13.0+cu130`r", "2.13.0"), @("2.14.0rc1", $null), @("2.15.0.dev20261001+cu130", $null), @("2.14.0a0+git1234", $null))) {
+ $got = if ($t[0] -match $probeRe) { $Matches[1] } else { $null }
+ Check ("resident probe reads '" + $t[0].Trim() + "' as " + $(if ($t[1]) { $t[1] } else { "no release" })) ($got -eq $t[1])
+ }
+ # setup.ps1's own CUDA torch block, run with the installer and the probe stubbed.
+ $blockStart = $setup.IndexOf(' $_cudaKeptActive = $false')
+ $blockEnd = $setup.IndexOf(' if ($torchInstallExit -ne 0) {', $blockStart)
+ $torchBlock = [scriptblock]::Create($setup.Substring($blockStart, $blockEnd - $blockStart))
+ function Invoke-SetupTorchBlock {
+ param([string]$Resident, [string]$CuTag = "cu130", [string[]]$Force = @(), [int[]]$Exits = @(0), [string]$Handoff = "", [string]$Upgrade = "")
+ $script:FastInstallCalls = @()
+ $script:FastInstallExits = [System.Collections.Generic.Queue[int]]::new([int[]]$Exits)
+ $script:ProbeCalls = 0
+ function Fast-Install { $script:FastInstallCalls += ,(@($args | Where-Object { $_ -notmatch '^--index-url$|^https://' }) -join " "); $global:LASTEXITCODE = $script:FastInstallExits.Dequeue(); "" }
+ function Invoke-BoundedPythonProbe { param($PythonExe, $Code) $script:ProbeCalls++; [pscustomobject]@{ Ok = [bool]$Resident; Output = $Resident } }
+ function substep { }
+ $env:UNSLOTH_KEPT_TORCH = $Handoff; $env:UNSLOTH_TORCH_UPGRADE = $Upgrade
+ $WinArm64Venv = $false; $WinArm64NoAudio = $false; $WinArm64IndexArgs = @(); $PinnedTorchIndexUrl = $null
+ $WinArm64TorchIndexUrl = $null; $TorchInstallIndexUrl = "https://download.pytorch.org/whl/$CuTag"; $script:UnslothVerbose = $false
+ $cudaTorchSpec = "torch"; $cudaVisionSpec = "torchvision"; $cudaAudioSpec = "torchaudio"; $cudaForce = $Force
+ . $torchBlock
+ Remove-Item Env:UNSLOTH_KEPT_TORCH, Env:UNSLOTH_TORCH_UPGRADE -ErrorAction SilentlyContinue
+ return [pscustomobject]@{ Calls = $script:FastInstallCalls; Exit = $torchInstallExit; Probes = $script:ProbeCalls }
+ }
+ $kept13 = "torch==2.13.0 torchvision==0.28.* torchaudio==2.11.*"
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130"
+ Check "setup keeps a healthy resident 2.13 when nothing is forced (a missing torchvision cannot pull 2.14)" ($r.Calls.Count -eq 1 -and $r.Calls[0] -eq $kept13)
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130" -Exits 1, 0
+ Check "an unforced resident pin that fails retries exactly the unpinned run" ($r.Calls.Count -eq 2 -and $r.Calls[1] -eq "torch torchvision torchaudio" -and $r.Exit -eq 0)
+ $r = Invoke-SetupTorchBlock -Resident "2.10.0+cu128" -Force "--force-reinstall"
+ Check "a forced repair keeps the resident release" ($r.Calls.Count -eq 1 -and $r.Calls[0] -eq "torch==2.10.0 torchvision==0.25.* torchaudio==2.10.* --force-reinstall")
+ $r = Invoke-SetupTorchBlock -Resident "2.10.0+cu128" -Force "--force-reinstall" -Exits 1, 0
+ Check "a forced kept pin that fails stops instead of resolving another release" ($r.Calls.Count -eq 1 -and $r.Exit -eq 1)
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130" -Handoff "2.11.0" -Exits 1, 0
+ Check "a failed installer handoff stops instead of resolving another release" ($r.Calls.Count -eq 1 -and $r.Calls[0] -like "torch==2.11.0 *" -and $r.Exit -eq 1 -and $r.Probes -eq 0)
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130" -Upgrade "1"
+ Check "UNSLOTH_TORCH_UPGRADE=1 resolves unpinned and never probes" ($r.Calls[0] -eq "torch torchvision torchaudio" -and $r.Probes -eq 0)
+ $r = Invoke-SetupTorchBlock -Resident "2.6.0+cu126"
+ Check "a resident release the cu130 index does not publish is not pinned" ($r.Calls[0] -eq "torch torchvision torchaudio")
+ $r = Invoke-SetupTorchBlock -Resident "2.7.1+cu128" -CuTag "cu128"
+ Check "cu128 keeps a resident 2.7" ($r.Calls[0] -eq "torch==2.7.1 torchvision==0.22.* torchaudio==2.7.*")
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130" -CuTag "cu128" -Force "--force-reinstall"
+ Check "a resident 2.13 is not pinned against cu128, which stops at 2.11" ($r.Calls[0] -eq "torch torchvision torchaudio --force-reinstall" -and $r.Probes -eq 1)
+ $r = Invoke-SetupTorchBlock -Resident "2.14.0rc1"
+ Check "a prerelease resident torch is never pinned" ($r.Calls[0] -eq "torch torchvision torchaudio")
+ $r = Invoke-SetupTorchBlock -Resident "2.13.0+cu130" -CuTag "rocm7.2"
+ Check "a non-CUDA leaf is never pinned" ($r.Calls[0] -eq "torch torchvision torchaudio")
+ Check "setup.ps1 never falls back to the default range after a kept pin" ($setup -notmatch 'not installable from this CUDA index -- using the supported release')
+ Check "setup.ps1 re-reads torch before installing triton" ($setup -match '(?s)\$_tritonTorchProbe = Invoke-BoundedPythonProbe.*?\$_tritonSpec = Get-TritonWindowsSpec -TorchVersion.*?substep "installing Triton for Windows\.\.\."')
+ Check "setup.ps1 pairs every kept torch 2.12+ with torchaudio 2.11" (
+ ([regex]::Matches($setup, 'torchaudio==2\.\$\(\[Math\]::Min\(\$_keptMinor, 11\)\)\.\*')).Count -eq 3 -and
+ $setup -notmatch 'torchaudio==2\.\$\(\$_keptMinor\)\.\*')
+} finally {
+ foreach ($n in $saved.Keys) { [Environment]::SetEnvironmentVariable($n, $saved[$n]) }
+}
+
+if ($failures -gt 0) {
+ Write-Host "$failures check(s) failed" -ForegroundColor Red
+ exit 1
+}
+Write-Host "All checks passed"
diff --git a/tests/studio/test_unsloth_torch_override.ps1 b/tests/studio/test_unsloth_torch_override.ps1
index 6e56640c350..b776cb09531 100644
--- a/tests/studio/test_unsloth_torch_override.ps1
+++ b/tests/studio/test_unsloth_torch_override.ps1
@@ -73,8 +73,8 @@ foreach ($label in @("install unsloth (no-torch)", "install unsloth (migrated no
Write-Host "the generated temp file never outlives the run"
$removals = [regex]::Matches($installText, 'Remove-UnslothTempFileQuietly -Path \$script:TorchOverridesFile')
-# One in-flow removal per with-deps install, plus the outer-finally sweep.
-Check "in-flow removal after each with-deps install, plus a final sweep" ($removals.Count -eq 3)
+# One in-flow removal per with-deps install (local, release, migrated), plus the outer-finally sweep.
+Check "in-flow removal after each with-deps install, plus a final sweep" ($removals.Count -eq 4)
Check "no unguarded Remove-Item on the tracked overrides path survives" (
$installText -notmatch 'Remove-Item -LiteralPath \$script:TorchOverridesFile')
$outer = @($ast.FindAll({ param($n)