Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
179 changes: 174 additions & 5 deletions install.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }
Expand All @@ -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
}
}

Expand Down Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor upgrade requests while migrating legacy environments

When UNSLOTH_TORCH_UPGRADE=1 migrates a healthy legacy .venv or CWD-relative environment on the new Windows x64/cu130/Python 3.13 route, this unconditional override freezes the old torch trio during the core install, while the later Get-PreviousTorchPin deliberately returns null for an upgrade. The migrated branch never calls Resolve-Cu130TorchRoute, and setup.ps1 subsequently installs bare, already-satisfied package names unless another condition forces reinstall, so a resident 2.11 installation remains on 2.11 instead of opting into the intended 2.13 default; if a reinstall is forced, it may instead select the newest unconstrained release. Skip this preservation for an explicit upgrade and route the migrated environment through the same 2.13 selection used by other existing layouts.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one as is. The legacy migration in install.sh freezes torch the same way (its migrated branch always runs under _UNSLOTH_TORCH_OVERRIDES, whatever UNSLOTH_TORCH_UPGRADE says), and before this PR the Windows migrated branch never went through the 2.13 route either, so nothing that used to upgrade stops upgrading. The migration only fires once, when the old ~/.unsloth/studio/.venv layout exists and the new one does not. The next install with UNSLOTH_TORCH_UPGRADE=1 runs on the migrated venv as a normal existing install, and that path takes the upgrade.

$_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
Expand All @@ -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) {
Expand Down
4 changes: 3 additions & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7238,7 +7238,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
Expand Down
25 changes: 24 additions & 1 deletion studio/backend/core/_msvc_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
Loading