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.

Trim comments in the installer entry scripts (#15333)

Daniel Hanac954363a56b
diff --git a/install.ps1 b/install.ps1
index 55af28469c7..dd7155fbf1b 100644
--- a/install.ps1
+++ b/install.ps1
@@ -16,18 +16,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-# Remove-Item's -ErrorAction does not cover every failure. For a path the FileSystem provider
-# cannot resolve it raises a terminating PSArgumentException ("An object at the specified path
-# ... does not exist"), which -ErrorAction SilentlyContinue cannot suppress, so an unguarded
-# removal during a rollback aborts the rest of the cleanup it belongs to (#11290). Guard on
-# existence and catch everything, so a missing or unresolvable temp path is never fatal. Used
-# for the temp files whose names can come from an 8.3 alias.
-#
-# Top level, NOT inside Install-UnslothStudio: a nested function lives in its parent's local
-# scope and is gone once the parent returns, and the outer finally below runs after exactly
-# that. Defined there, the finally's two calls raise CommandNotFoundException and leave the
-# overrides file -- which carries the caller's UV_OVERRIDE lines -- on disk.
-# tests/studio/test_unsloth_torch_override.ps1 pins the placement.
+# Remove-Item can throw a terminating error for an unresolvable path that -ErrorAction
+# cannot suppress, so guard and catch everything (temp names can be 8.3 aliases).
+# Top level, NOT inside Install-UnslothStudio: the outer finally runs after that function
+# returns (tests/studio/test_unsloth_torch_override.ps1 pins the placement).
function Remove-UnslothTempFileQuietly {
param([string]$Path)
if (-not $Path) { return }
@@ -40,38 +32,27 @@ function Remove-UnslothTempFileQuietly {
function Install-UnslothStudio {
$ErrorActionPreference = "Stop"
- # First: Exit-InstallFailure restores the marker long before the selection runs, and
- # under `irm | iex` the script scope is the caller's session.
+ # First: under `irm | iex` the script scope is the caller's session.
$script:StudioUvMarkerSaved = $false
$script:StudioUvMarkerExisted = $false
$script:StudioUvMarkerPrevious = $null
- # One flag for both rollbacks: clearing them separately leaves a window either way
- # round, where an interruption restores one half of a committed install.
+ # One flag for both rollbacks, so an interruption cannot restore only half.
$script:StudioInstallCommitted = $false
- # The user's PowerShell profile has already run by the time this does, and the documented
- # piped web entry point documented in the README has no script file to re-launch
- # with -NoProfile, so each way a profile can reach in here is cut individually below.
- #
- # Off, not Latest: this script predates strict mode, testing environment variables that are
- # legitimately unset and reading $script: state only some branches assign. Scoped to here
- # and below, so the caller keeps its own.
+ # The user's PowerShell profile has already run, and the piped web entry cannot re-launch
+ # with -NoProfile, so each way a profile can reach in is cut below. Strict mode Off: this
+ # script reads legitimately unset variables. Scoped to here and below.
Set-StrictMode -Off
- # A profile that sets 'None' -- the startup-time tweak people copy -- is fatal on PowerShell
- # 7, which loads NO modules at startup: Test-Path, Write-Host, Select-Object,
- # ConvertFrom-Json, Get-FileHash, Invoke-WebRequest, Expand-Archive, Start-Process and
- # Get-Content stop resolving, while 5.1 preloads Utility and Management and survives. First
- # of the four, because the proxy handoff below calls ConvertTo-Json from Utility too.
+ # A profile setting 'None' is fatal on PowerShell 7, which preloads no modules. First,
+ # because the proxy handoff below needs ConvertTo-Json.
$PSModuleAutoLoadingPreference = 'All'
- # Proxy keys are kept rather than dropped: on a locked-down corporate host such an entry may
- # be the sole route to python.org and the uv release. IsMatch, not -match, so the filter
- # leaves no $Matches behind for the rest of the install.
+ # Keep proxy keys: on locked-down hosts they may be the only route out. IsMatch, not
+ # -match, so no $Matches leaks.
$_UnslothKeptDefaults = @{}
foreach ($_UnslothDefaultKey in @($PSDefaultParameterValues.Keys)) {
- # IgnoreCase: 'invoke-webrequest:proxy' is valid PowerShell and binds the same
- # parameter, so a case-sensitive filter drops a working proxy on a technicality.
+ # IgnoreCase: 'invoke-webrequest:proxy' binds the same parameter.
if ($_UnslothDefaultKey -is [string] -and
[regex]::IsMatch(
$_UnslothDefaultKey,
@@ -80,23 +61,16 @@ function Install-UnslothStudio {
$_UnslothKeptDefaults[$_UnslothDefaultKey] = $PSDefaultParameterValues[$_UnslothDefaultKey]
}
}
- # One profile entry such as 'Start-Process:WindowStyle' or 'Invoke-WebRequest:TimeoutSec'
- # silently rebinds every process launch and download here. Assigning with no scope qualifier
- # shadows the caller's table for this scope and below only.
+ # A profile default like 'Start-Process:WindowStyle' would rebind every launch here.
+ # No scope qualifier: shadows the caller's table for this scope only.
$PSDefaultParameterValues = $_UnslothKeptDefaults
- # Windows PowerShell 5.1 redraws the Invoke-WebRequest progress bar on every read, and the
- # redraw, not the link, sets the rate: on a windows-latest runner the python.org installer
- # (27.8 MB) took 41.34s with the bar on against 0.08s with it off, and the uv archive the
- # same. That is the multi-minute "slow download" users report. -UseBasicParsing does NOT
- # avoid it and PowerShell 7 never had the cost; only this preference does. Same scoping rule
- # as the table above: no qualifier, so the caller's own preference survives a piped web run.
+ # 5.1 redraws the Invoke-WebRequest progress bar on every read, which dominates download
+ # time (41s vs 0.08s for python.org's installer). Unqualified, so the caller keeps theirs.
$ProgressPreference = 'SilentlyContinue'
- # The kept proxies travel to studio/setup.ps1 (launched -NoProfile by unsloth_cli, and it
- # downloads the VC++ runtime and the uv installer) as JSON in _UNSLOTH_PS_PROXY_DEFAULTS,
- # since a PowerShell variable does not cross a process boundary. Credentials do not travel:
- # a PSCredential does not serialize, and an environment variable is the wrong place for one.
+ # Kept proxies go to studio/setup.ps1 as JSON in _UNSLOTH_PS_PROXY_DEFAULTS (variables do
+ # not cross processes). Credentials do not travel.
$_UnslothProxyHandoff = @{}
foreach ($_UnslothDefaultKey in @($_UnslothKeptDefaults.Keys)) {
$_UnslothDefaultValue = $_UnslothKeptDefaults[$_UnslothDefaultKey]
@@ -106,9 +80,7 @@ function Install-UnslothStudio {
} elseif ($_UnslothDefaultValue -is [string] -or $_UnslothDefaultValue -is [bool]) {
$_UnslothProxyHandoff[$_UnslothDefaultKey] = $_UnslothDefaultValue
} elseif ($_UnslothDefaultValue -is [scriptblock]) {
- # A script block is the supported form for a DYNAMIC default, e.g.
- # { [uri]$env:CORP_PROXY }, evaluated per call by Invoke-WebRequest. Evaluate here
- # and hand over the RESULT: executable code must not cross into the child.
+ # Evaluate a script-block default here and hand over the result, never the code.
try {
$_UnslothDefaultResolved = & $_UnslothDefaultValue
if ($_UnslothDefaultResolved -is [uri]) {
@@ -120,27 +92,19 @@ function Install-UnslothStudio {
} catch { }
}
}
- # A FUNCTION-local, not $script: or an environment variable: under a piped web run this runs
- # in the caller's own session, and the value can carry credentials (http://user:secret@proxy
- # is the ordinary corporate form) that must not outlive the install on any of the dozens of
- # return paths. Module-qualified serializer, as in the probe: a profile alias or function
- # named ConvertTo-Json would otherwise reshape this record or throw out of the prologue.
+ # Function-local: under a piped run this is the caller's session and the value may carry
+ # credentials. Module-qualified so a profile alias cannot replace ConvertTo-Json.
$UnslothProxyHandoffJson =
if ($_UnslothProxyHandoff.Count -gt 0) {
$_UnslothProxyHandoff | Microsoft.PowerShell.Utility\ConvertTo-Json -Compress
}
else { $null }
- # PowerShell 7 only, and $false is its default: a profile that flips it on turns every
- # non-zero native exit into a terminating error, which with "Stop" above would throw out of
- # the setup handoff instead of reaching Exit-InstallFailure. Harmless on 5.1, where the
- # variable does not exist.
+ # PowerShell 7 only: if a profile enables it, native non-zero exits would throw past
+ # Exit-InstallFailure.
$PSNativeCommandUseErrorActionPreference = $false
- # Reset per invocation, for the reason at $script:IsIntelXpu further down: under
- # a piped web run, $script: is the caller's session scope, so a second run in the same
- # console would start on the first run's state. These two are the only ones no later
- # statement re-assigns unconditionally.
+ # Reset per invocation: under `irm | iex` $script: is the caller's session.
$script:UvExe = 'uv'
$script:UvInstallDestDir = $null
$script:StudioPrivateUvDir = $null
@@ -152,22 +116,9 @@ function Install-UnslothStudio {
$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq "1")
- # Same fix as studio/setup.ps1, for the same reason. This script also calls
- # Expand-Archive and Get-ExecutionPolicy, which resolve via PSModulePath.
- # The desktop app reaches here as Tauri -> Rust -> powershell.exe
- # (studio/src-tauri/src/install.rs), and PowerShell only rewrites
- # PSModulePath for a direct pwsh -> powershell.exe hop, so the Rust process
- # in between leaves Windows PowerShell 5.1 leading with PowerShell 7's
- # module directories and unable to load its own copy of that module.
- #
- # Not restored afterwards, deliberately. $env: is the process environment,
- # so running this script in an interactive console leaves the reordering in
- # place for that session. A try/finally would not change that for the case
- # it is raised about: the interactive path ends by running Unsloth in the
- # foreground, so the finally would not fire until the user stops the server.
- # Narrowing the trigger instead would risk skipping the fix on some chain
- # this list does not anticipate, and the cost of that is the install failing
- # outright, against a session-lived module precedence change here.
+ # Same fix as studio/setup.ps1: via Tauri -> Rust -> powershell.exe, 5.1 inherits
+ # PowerShell 7's module paths first and cannot load its own modules. Deliberately not
+ # restored: an interactive run ends with Unsloth in the foreground.
if ($PSVersionTable.PSEdition -ne 'Core' -and $env:SystemRoot) {
$_UnslothSystemModules = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\Modules'
if (Test-Path $_UnslothSystemModules) {
@@ -180,14 +131,12 @@ function Install-UnslothStudio {
}
}
- # Same UTF-8 invariant as studio/setup.ps1, same ordering constraint: this
- # rebuilds [Console]::Out, so it precedes the first write.
+ # Same UTF-8 invariant as studio/setup.ps1; must precede the first write.
$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false
try {
[Console]::OutputEncoding = $_UnslothUtf8NoBom
} catch {
- # No console: the setter drops the cached writer before throwing, so
- # bind UTF-8 ones explicitly. Same fallback as studio/setup.ps1.
+ # No console: the setter drops the cached writer before throwing, so bind UTF-8 writers.
try {
$_UnslothStdout = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardOutput()), $_UnslothUtf8NoBom
$_UnslothStdout.AutoFlush = $true
@@ -201,19 +150,13 @@ function Install-UnslothStudio {
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
- # Resolved once: it picks the output sink in Write-StudioLine and must not
- # change mid-run. Same probe as studio/setup.ps1.
+ # Resolved once: it picks the sink in Write-StudioLine. Same probe as studio/setup.ps1.
$script:StudioStdoutRedirected = $false
try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }
- # Write-Host is written by 5.1's console host with its own writer on the OEM
- # code page, not the UTF-8 [Console]::Out rebound above. The desktop app
- # spawns this script with CREATE_NO_WINDOW and decodes the pipe as UTF-8
- # (from_utf8_lossy, studio/src-tauri/src/install.rs), so the banner emoji,
- # the U+2500 rule and every warning arrived as U+FFFD. One sink instead: the
- # console handle when redirected, Write-Host when interactive, since it is
- # the only one that colorizes. Defined above the first write, for the same
- # ordering reason as the encoding block.
+ # 5.1's Write-Host uses the OEM code page, and the desktop app decodes the pipe as UTF-8,
+ # so write to the console handle when redirected and Write-Host (colour) when interactive.
+ # Defined before the first write.
function Write-StudioLine {
param([string]$Message = "", [string]$ForegroundColor)
if ($script:StudioStdoutRedirected) {
@@ -325,10 +268,8 @@ function Install-UnslothStudio {
}
$script:WoaTorchAudio = $false
- # Wheels PyPI has no win_arm64 build of: pyarrow 25.0.1 (cp311-cp314) and sqlite-vec 0.1.9.
- # Built from their release tags on a windows-11-arm runner and Authenticode signed by
- # .github/workflows/woa-wheelhouse.yml, which publishes them here. Set
- # UNSLOTH_WOA_WHEELHOUSE to override with a mirror or a local directory.
+ # Wheels PyPI lacks for win_arm64 (pyarrow, sqlite-vec), built and signed by
+ # .github/workflows/woa-wheelhouse.yml. UNSLOTH_WOA_WHEELHOUSE overrides.
$script:WoaWheelhouse = if ($env:UNSLOTH_WOA_WHEELHOUSE) {
$env:UNSLOTH_WOA_WHEELHOUSE.Trim().TrimEnd('/')
} else {
@@ -738,60 +679,26 @@ function Install-UnslothStudio {
return @{ NoIndex = $noIndex; DefaultIndex = $defaultIndex; ExtraIndexes = @($extras | Where-Object { $_ }) }
}
- # uv's own boolish set, for every UV_* switch this script reads out of the caller's
- # environment. Verified against uv 0.10.7, crates/uv-static/src/lib.rs
- # parse_boolish_environment_variable, which restates clap's str_to_bool: true is
- # y, yes, t, true, on, 1; false is n, no, f, false, off, 0; case-insensitive, and
- # anything else aborts uv rather than being guessed at.
- #
- # `-notin @("", "0", "false")`, which each of these sites used to spell inline, read
- # off, no, n and f as TRUE, the exact opposite of uv's answer for them.
- #
- # Trimmed where uv is not: uv aborts on a padded value, so the resolve fails whatever
- # this returns, and trimming keeps the answer identical to setup.sh's
- # _uv_offline_requested and install_python_stack.py's _uv_env_flag, which is the
- # property worth having. ToLowerInvariant, not ToLower: a Turkish-locale host
- # lowercases "I" to a dotless i and would stop matching.
+ # uv's boolish set (uv 0.10.7 parse_boolish_environment_variable): y/yes/t/true/on/1 vs
+ # n/no/f/false/off/0, case-insensitive. Trimmed to match setup.sh and
+ # install_python_stack.py. ToLowerInvariant for Turkish locales.
function Test-UvEnvFlag {
param([string]$Name)
$value = [string][Environment]::GetEnvironmentVariable($Name)
return (@("1", "t", "true", "y", "yes", "on") -contains $value.Trim().ToLowerInvariant())
}
- # pip's rule, kept separate on purpose: PIP_NO_INDEX is pip's variable and uv never
- # reads it, so uv's parser has no authority over it. pip routes it through
- # ConfigOptionParser._update_defaults -> strtobool (pip/_internal/utils/misc.py): true
- # is y, yes, t, true, on, 1; false is n, no, f, false, off, 0; case-insensitive and
- # untrimmed, with anything else exiting pip on "is not a valid value". An empty value
- # never reaches strtobool, because _get_ordered_configuration_items drops falsy values
- # first, so PIP_NO_INDEX="" is simply not set.
- #
- # The literals coincide with uv's today. They are restated rather than shared anyway,
- # so that the day either project changes its mind this is a one-function edit instead
- # of a silent behaviour change in the other resolver.
+ # pip's own rule for PIP_NO_INDEX (strtobool; empty means unset). Same literals as uv's
+ # today, restated so either can change independently.
function Test-PipEnvFlag {
param([string]$Name)
$value = [string][Environment]::GetEnvironmentVariable($Name)
return (@("1", "t", "true", "y", "yes", "on") -contains $value.Trim().ToLowerInvariant())
}
- # UV_NO_INDEX is OURS, not uv's, and the distinction is not pedantic: uv 0.10.7 defines
- # no such environment variable. `--no-index` exists only as a command-line flag, it is
- # absent from `uv pip install --help`'s environment list beside UV_OFFLINE and
- # UV_NO_CONFIG, and grepping the 0.10.7 tree for the name returns nothing. uv will
- # ignore it however it is spelled. So this is not "what uv was told"; it is the
- # operator telling US they want no registry index, and what we do about it is shape the
- # arguments we pass.
- #
- # Read with uv's boolish set deliberately, not by inheritance. A caller sets this
- # beside UV_OFFLINE and UV_NO_CONFIG, which uv really does read, and one spelling
- # across all three is the entire point. It is a choice, and the test says so.
- #
- # Deliberately NOT turned into a `--no-index` argument. That would make our behaviour
- # and uv's actually agree, which is the honest long-term answer, but it would also turn
- # a resolve that works today into one with no index at all. That is a behaviour change
- # for existing users and belongs in its own change, not riding along with a truthiness
- # fix.
+ # UV_NO_INDEX is OURS: uv defines no such environment variable (--no-index is a
+ # command-line flag only). Read with uv's boolish set for consistency with UV_OFFLINE/UV_NO_CONFIG;
+ # not turned into --no-index, which would change behaviour for existing users.
function Test-NoIndexRequested {
return (Test-UvEnvFlag "UV_NO_INDEX")
}
@@ -846,9 +753,7 @@ function Install-UnslothStudio {
# This script resolves with uv, so uv's policy is the one that counts: the UV_* variables uv actually defines, and its configuration files. pip's PIP_* variables are pip's alone; uv never reads them. UV_NO_INDEX is neither -- see Test-NoIndexRequested.
function Test-WoaResolveReachesPyPI {
- # Two different questions, kept apart. UV_OFFLINE really does stop uv reaching a
- # network. UV_NO_INDEX is our own convention and uv ignores it, so this arm is us
- # honouring an operator's stated intent, not a prediction about uv.
+ # UV_OFFLINE really stops uv; UV_NO_INDEX is our convention and uv ignores it.
if (Test-UvEnvFlag "UV_OFFLINE") { return $false }
if (Test-NoIndexRequested) { return $false }
$extraIsPyPI = $false
@@ -1245,8 +1150,7 @@ function Install-UnslothStudio {
$script:WoaNvidiaSmiPath = $null
function Get-WoaNvidiaSmiPath {
- # Memoised because the two callers each probe, and without this the whole candidate list
- # would be walked twice with a bounded process spawn per entry.
+ # Memoised: both callers probe, and each candidate costs a bounded process spawn.
if ($script:WoaNvidiaSmiProbed) { return $script:WoaNvidiaSmiPath }
$script:WoaNvidiaSmiProbed = $true
$exe = $null
@@ -1254,22 +1158,8 @@ function Install-UnslothStudio {
if ($exe) { $script:WoaNvidiaSmiPath = $exe; return $exe }
$found = @(Get-NvidiaSmiCandidatePaths)
if ($found.Count -eq 0) { return $null }
- # The first candidate that ANSWERS, not the first that exists.
- #
- # Both callers immediately probe what this returns, and treat a non-answer as "no NVIDIA
- # here": Test-WoaNvidiaPresent returns false and Get-WoaDriverCudaVersion returns null,
- # which between them decide whether the native ARM64 CUDA stack is installed at all. So
- # handing back a broken copy does not cost a retry, it declines the whole route.
- #
- # That was survivable when two locations were searched and is not now that the list is
- # longer: every location added is another chance that the first entry is a stale copy
- # sitting in front of a working one. Same reason the main detection loop stopped taking
- # the first listing candidate.
- # Same two-budget shape as the main detection loop, and for the same reasons. Each probe
- # below is a bounded process spawn, and the list can now be eleven entries, so a wedged
- # driver would otherwise hold Initialize-WoaNativeCudaTorch for minutes before the
- # install even starts. The soft budget only applies once something has answered; only the
- # hard one may end the scan with nothing, because that decides the whole ARM64 route.
+ # The first candidate that ANSWERS: a broken copy would decline the whole ARM64 CUDA route.
+ # Soft and hard budgets as in the main detection loop; only the hard one may end empty.
$woaDeadline = (Get-Date).AddSeconds(30)
$woaHardDeadline = (Get-Date).AddSeconds(60)
$woaListing = $null
@@ -1280,11 +1170,8 @@ function Install-UnslothStudio {
$listing = Invoke-NvidiaSmiBounded $p @('-L')
if (-not ($LASTEXITCODE -eq 0 -and $listing -match '(?m)^\s*GPU\s+\d+')) { continue }
if (-not $woaListing) { $woaListing = $p }
- # Two passes, because listing a GPU is not enough here. Get-WoaDriverCudaVersion
- # asks this same binary for the CUDA banner, and a null answer does not merely
- # lose a version: it skips the CUDA-major compatibility guard in
- # Initialize-WoaNativeCudaTorch, which is what stops a native wheel newer than
- # the installed driver being chosen. So prefer a candidate that answers BOTH.
+ # Prefer a candidate that also reports the CUDA version: without it the CUDA-major guard
+ # in Initialize-WoaNativeCudaTorch is skipped.
if ((Get-Date) -gt $woaDeadline) { break }
$banner = Invoke-NvidiaSmiBounded $p
if ($banner -match 'CUDA(?: UMD)? Version:\s+\d+\.\d+') {
@@ -1293,14 +1180,12 @@ function Install-UnslothStudio {
}
} catch {}
}
- # One that listed a GPU but never named a version is still better than one that did not
- # answer at all: the callers' presence check works, and the version check declines.
+ # A GPU listing without a version still beats no answer.
if ($woaListing) {
$script:WoaNvidiaSmiPath = $woaListing
return $woaListing
}
- # Nothing answered. Hand back the first that exists, which is what this did before, so a
- # host where the probe cannot run is no worse off than it was.
+ # Nothing answered: fall back to the first that exists.
$script:WoaNvidiaSmiPath = $found[0]
return $found[0]
}
@@ -1604,33 +1489,21 @@ function Install-UnslothStudio {
[int]$Code = 1
)
if ($Code -eq 0) { $Code = 1 }
- # Here rather than at any one failure site: the largest writes are the venv and the torch
- # install, and both exit through this function long before studio setup is reached, so a
- # disk that filled during them used to surface as a bare exit code (#11313). Below 64 MB
- # nothing useful unpacks, which makes it the cause rather than a coincidence. Folded into
- # $Message as well as printed, because under --tauri nothing reaches the UI except the
- # single line handed to Write-TauriLog.
+ # Name a full disk here, since big writes exit through this function (#11313); below
+ # 64 MB is the cause. Folded into $Message because --tauri shows only that line.
$_diskSuffix = ""
try {
- # Probed, not called outright: the early exits above happen before this file has
- # defined the helper, and a command-not-found here would replace the real failure
- # with a confusing one.
+ # Probed: early exits happen before the helper is defined.
if ($StudioHome -and (Get-Command Get-StudioFreeSpaceBytes -CommandType Function -ErrorAction SilentlyContinue)) {
$_diskFree = Get-StudioFreeSpaceBytes -Path $StudioHome
if ($null -ne $_diskFree -and $_diskFree -lt 64MB) {
$_diskMb = [math]::Round($_diskFree / 1MB)
- # What to advise depends on what actually happened to the old environment,
- # not on what was asked for. A discard that failed left a tree behind, and
- # deleting it is very likely what makes the retry fit; telling that user
- # there is nothing left to reclaim sends them away from the one thing that
- # would help. install.sh chooses between the same four.
+ # Advice depends on what happened to the old environment (same four cases as install.sh).
$_diskRemedy = if ($script:StudioVenvDiscardLeftover) {
"Free some space and re-run. The previous environment could not be removed and is still at $($script:StudioVenvDiscardLeftover); deleting it will reclaim that space."
} elseif ($script:StudioVenvDiscardSucceeded) {
"Free some space and re-run. The previous environment was already discarded by --no-rollback, so the installer has nothing further of its own to reclaim."
} elseif ($script:StudioNoRollback) {
- # Asked for, but nothing was there to discard: a first install, or a
- # failure before the replacement began.
"Free some space and re-run."
} else {
"Free some space and re-run. --no-rollback (UNSLOTH_INSTALL_NO_ROLLBACK=1) drops the previous environment instead of keeping a copy of it during the install."
@@ -1654,8 +1527,8 @@ function Install-UnslothStudio {
if (Get-Command Restore-StudioUvCacheMarker -CommandType Function -ErrorAction SilentlyContinue) {
Restore-StudioUvCacheMarker -StudioRoot $StudioHome
}
- # Most failures return before the lock try/finally, and under `irm | iex`
- # these variables are the caller's own. Defined later, so probed like above.
+ # Most failures return before the lock try/finally, and under `irm | iex` these are the
+ # caller's variables. Probed like above.
if (Get-Command Restore-StudioTempEnvironment -CommandType Function -ErrorAction SilentlyContinue) {
Restore-StudioTempEnvironment
}
@@ -1666,24 +1539,13 @@ function Install-UnslothStudio {
}
# ── Usable temporary storage ──
- # Windows picks the temp directory from TMP, then TEMP, then the profile, and
- # never checks it exists or is writable. The desktop app passes on whatever it
- # inherited (studio/src-tauri/src/install.rs sets neither); one report had it at
- # C:\Windows\TEMP, unwritable, which broke the install when the native helper was
- # still compiled through it (issue #9140). Nothing compiles now, but the Python,
- # uv and VC++ downloads still stage through it. Probe it once and, if it cannot
- # hold a file, point BOTH variables at a directory we own: every child process
- # and every
- # [System.IO.Path]::GetTempPath() call reads the process environment block.
+ # Usable temporary storage. Windows never checks TMP/TEMP exist or are writable
+ # (#9140), and downloads stage there. If it cannot hold a file, point BOTH at a
+ # directory we own; children and GetTempPath() read the process environment.
function Test-StudioDirectoryUsable {
param(
[string]$Path,
- # Only for a directory this installer OWNS. Probing the host's own
- # inherited TMP/TEMP must not bring it into existence: -Force creates
- # the whole parent chain, so a stale or mistyped TMP would have the
- # installer silently materialize a tree at a path nobody chose, and
- # then trust it. Absent means unusable, which is what the private
- # fallback is for.
+ # Only for a directory we OWN: -Force would materialize a stale inherited TMP path.
[switch]$CreateIfMissing
)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
@@ -1692,34 +1554,22 @@ function Install-UnslothStudio {
if (-not $CreateIfMissing) { return $false }
New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop | Out-Null
}
- # Anything an earlier run could not delete. Bounded self-healing: the
- # probe below cannot clean up after itself when deletion is what
- # failed, so each such run used to leave one more file behind forever.
+ # Remove probes earlier runs could not delete.
try {
$cutoff = (Get-Date).AddDays(-1)
foreach ($old in @(Get-ChildItem -LiteralPath $Path -File -Filter "unsloth-probe-*.tmp" -ErrorAction Stop)) {
- # Shape, not prefix. This runs in the HOST's temp directory,
- # where a name that merely starts the same way belongs to
- # somebody else; the probe below only ever writes eight hex
- # characters, so anything else is not ours to delete.
+ # Shape, not prefix: this is the host's temp directory.
if ($old.Name -notmatch '^unsloth-probe-[0-9a-f]{8}\.tmp$') { continue }
if ($old.LastWriteTime -lt $cutoff) {
Remove-Item -LiteralPath $old.FullName -Force -ErrorAction SilentlyContinue
}
}
} catch {}
- # Write, read back, delete -- not Test-Path: the failures that matter
- # (write without read, a scanner deleting the file) pass an existence check.
+ # Write, read back, delete: Test-Path misses the failures that matter.
$probe = Join-Path $Path ("unsloth-probe-" + [guid]::NewGuid().ToString('N').Substring(0, 8) + ".tmp")
[System.IO.File]::WriteAllText($probe, "unsloth")
$readBack = [System.IO.File]::ReadAllText($probe)
- # Deleting has to work too, and be VERIFIED. csc.exe writes its source
- # and its output into this directory and then cleans up, so one that
- # accepts a file and will not give it back is the shape that produced
- # #9140; a suppressed Remove-Item said nothing either way. Retried a
- # couple of times first, because a scanner holding the file for a
- # moment is not the same as a directory that denies deletion, and only
- # the second should cost a healthy host its own temp.
+ # Deletion must work and be verified (the #9140 shape); retry briefly for scanners.
$probeGone = $false
foreach ($attempt in 1..3) {
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
@@ -1735,38 +1585,21 @@ function Install-UnslothStudio {
function Remove-StudioStalePrivateTempDirectories {
param([Parameter(Mandatory = $true)][string]$Root)
- # These outlive the install (an autostarted Unsloth inherits one as its own
- # %TEMP%), so bound the pile by age instead of deleting one still in use.
+ # These outlive the install (autostarted Unsloth's %TEMP%), so prune by age.
try {
$cutoff = (Get-Date).AddDays(-1)
foreach ($stale in @(Get-ChildItem -LiteralPath $Root -Directory -Filter "ust-*" -ErrorAction Stop)) {
- # SHAPE, not prefix. The delete below is recursive and this is the
- # only ownership test there is, so it has to name a directory the
- # allocator could actually have made: "ust-" + $PID + "-" + 8 hex.
- # A prefix match takes "ust-legacy" or "ust-user-cache" too, and
- # since neither has a parseable PID the liveness check is skipped
- # for exactly the names least likely to be ours. scripts/uninstall.ps1
- # already requires this shape; the two had drifted apart.
+ # SHAPE, not prefix, before a recursive delete: "ust-" + PID + "-" + 8 hex, as
+ # scripts/uninstall.ps1 requires.
if ($stale.Name -notmatch '^ust-[0-9]+-[0-9a-f]{8}$') { continue }
if ($stale.LastWriteTime -ge $cutoff) { continue }
- # Before any owner logic, because the allocator never makes a link:
- # anything here that IS one is not ours, reading owner.pid out of it
- # would read through it, and unlinking is safe whatever owns the
- # target. Not Remove-Item: on 5.1 without -Recurse it throws a
- # NullReferenceException on a junction that -ErrorAction
- # SilentlyContinue does not suppress (measured on windows-latest), and
- # -Recurse has walked THROUGH the link on some 5.1 builds.
- # Directory.Delete with recursive:$false cannot follow it.
+ # Reparse points are never ours: unlink without following. Not Remove-Item, which can
+ # throw unsuppressibly or walk through a junction on 5.1.
if ($stale.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
try { [System.IO.Directory]::Delete($stale.FullName, $false) } catch {}
continue
}
- # Age alone is not proof it is unused, and this sweep runs before the
- # runtime mutex, so it could delete a live process's %TEMP%. owner.pid
- # names the process that INHERITED this directory (the autostarted
- # Unsloth, which outlives the installer); the PID in the name is only
- # the installer's and is already gone. If the owner is alive, leave it.
- # PID reuse only ever costs a directory its cleanup.
+ # owner.pid names the process that inherited this dir; if it is alive, keep the dir.
$ownerPid = 0
$ownerFile = Join-Path $stale.FullName "owner.pid"
$recorded = $null
@@ -1778,20 +1611,12 @@ function Install-UnslothStudio {
if (-not [string]::IsNullOrWhiteSpace($recorded)) {
$null = [int]::TryParse($recorded, [ref]$ownerPid)
}
- # Whether the owner was RECORDED, or only guessed from the name.
- # The name carries the installer's PID, and an installer that was
- # killed between Start-Process and the owner.pid write leaves a dead
- # PID in the name while the Unsloth it started is very much alive on
- # that directory as its own %TEMP%. Guessing therefore proves much
- # less than reading, and the two are not treated alike below.
+ # A recorded owner proves more than the installer PID in the name.
$ownerRecorded = ($ownerPid -gt 0)
if ($ownerPid -le 0) {
$null = [int]::TryParse(($stale.Name -split '-')[1], [ref]$ownerPid)
}
- # No recorded owner: unknown, not abandoned. Still collected, so the
- # pile stays bounded, but only once it has gone a whole week without
- # a single entry being created in it, which an Unsloth actually using
- # it as %TEMP% would not manage.
+ # No recorded owner: collect only after a week with no new entries.
if (-not $ownerRecorded -and $stale.LastWriteTime -ge (Get-Date).AddDays(-7)) {
continue
}
@@ -1800,8 +1625,7 @@ function Install-UnslothStudio {
try {
$null = Get-Process -Id $ownerPid -ErrorAction Stop
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
- # The only answer that means "abandoned"; any other failure
- # says nothing about the owner, so keep the directory.
+ # Only this failure means "abandoned"; others keep the directory.
$ownerLives = $false
} catch {
$ownerLives = $true
@@ -1817,9 +1641,7 @@ function Install-UnslothStudio {
param([Parameter(Mandatory = $true)][int]$OwnerProcessId)
# Only meaningful if this run redirected the temp; otherwise it is the host's.
if ($null -eq $script:StudioTempOverride) { return }
- # Only a directory this run created. The other override shape just pins the
- # absolute spelling of the host's own temp, and dropping a file in there
- # would be litter in somebody else's directory.
+ # Only a directory this run created; never litter the host's temp.
if (-not $script:StudioTempOverride.Owned) { return }
$owned = $script:StudioTempOverride.Path
if ([string]::IsNullOrWhiteSpace($owned)) { return }
@@ -1829,10 +1651,7 @@ function Install-UnslothStudio {
}
function Get-StudioPrivateTempRoots {
- # Only under paths scripts/uninstall.ps1 already reclaims (LOCALAPPDATA\
- # "Unsloth Studio", ~\.unsloth\.cache): anywhere else would survive an
- # uninstall, and a leftover directly under ~\.unsloth would be worse, since
- # that is removed only when empty.
+ # Only under paths scripts/uninstall.ps1 already reclaims.
$roots = @()
if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
$roots += (Join-Path $env:LOCALAPPDATA "Unsloth Studio\temp")
@@ -1851,15 +1670,11 @@ function Install-UnslothStudio {
function New-StudioPrivateTempDirectory {
foreach ($root in @(Get-StudioPrivateTempRoots)) {
- # Short leaf: the .NET Framework compiler 5.1 shells out to is still
- # bound by the legacy path limit.
+ # Short leaf: 5.1's .NET Framework compiler is bound by the legacy path limit.
$leaf = "ust-" + $PID + "-" + [guid]::NewGuid().ToString('N').Substring(0, 8)
$candidate = Join-Path $root $leaf
- # Which of these did not exist BEFORE the probe touched anything. Only
- # those may be unwound below: a pre-provisioned "Unsloth Studio\temp"
- # with custom ACLs, or an empty junction pointing somewhere else, is
- # configuration this installer did not create and must not remove
- # merely for being empty and correctly named.
+ # Only directories absent BEFORE the probe may be unwound; pre-provisioned ones are
+ # configuration we did not create.
$preAbsent = @{}
$walk = $candidate
for ($seen = 0; $seen -lt 4; $seen++) {
@@ -1871,13 +1686,8 @@ function Install-UnslothStudio {
Remove-StudioStalePrivateTempDirectories -Root $root
return $candidate
}
- # The probe creates the candidate before it tests it, and -Force builds
- # the whole chain, so a root that fails leaves "Unsloth Studio\temp\ust-x"
- # behind; on a host where every root fails that is a data directory tree
- # conjured by an install that then gave up. Walk back up, but only through
- # the directories this path is made of and only while each one is EMPTY,
- # so a tree that already held something is never touched and neither is
- # ~\.unsloth itself, which is shared and is not ours to remove.
+ # A failed root leaves the -Force chain behind; walk back up through our own empty
+ # components only, never ~\.unsloth itself.
$ours = @("temp", "Unsloth Studio", ".cache")
$unwind = $candidate
for ($depth = 0; $depth -lt 4; $depth++) {
@@ -1885,9 +1695,7 @@ function Install-UnslothStudio {
if (-not $preAbsent[$unwind]) { break }
if (-not (Test-Path -LiteralPath $unwind -PathType Container)) { break }
$item = Get-Item -LiteralPath $unwind -Force -ErrorAction Stop
- # A relocation junction is somebody's configuration even when the
- # probe created it, and unlinking it is not "taking back what we
- # made". Leave it and stop.
+ # A relocation junction is somebody's configuration; leave it and stop.
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { break }
if (@(Get-ChildItem -LiteralPath $unwind -Force -ErrorAction Stop).Count -gt 0) { break }
[System.IO.Directory]::Delete($unwind, $false)
@@ -1905,37 +1713,21 @@ function Install-UnslothStudio {
function Initialize-StudioTempEnvironment {
if ($script:StudioTempChecked) { return }
$script:StudioTempChecked = $true
- # TMP wins over TEMP, so only fall through when TMP is unset. IsNullOrEmpty,
- # not IsNullOrWhiteSpace: GetTempPath takes the first of TMP/TEMP that is
- # merely non-empty, so a whitespace-only TMP is what Windows and every child
- # will use, and treating it as unset would probe a healthy TEMP and change
- # nothing.
+ # TMP wins over TEMP. IsNullOrEmpty, not IsNullOrWhiteSpace: GetTempPath takes the first
+ # non-empty one, so a whitespace TMP is what Windows uses.
$inherited = if (-not [string]::IsNullOrEmpty($env:TMP)) { $env:TMP } else { $env:TEMP }
- # Resolve BEFORE probing, not after. Test-Path is relative to PowerShell's
- # location while the .NET file APIs are relative to the process working
- # directory, and Set-Location moves only the first, so probing a relative
- # value can check one directory and write to another.
- # Whitespace-only is left exactly as it is, so the probe below rejects it.
- # Resolving it first would turn " " or a tab into the working directory
- # plus that name, which is creatable on some filesystems, and the installer
- # would manufacture a junk directory and then trust it as the host's temp.
+ # Resolve BEFORE probing: Test-Path and .NET resolve relative paths differently. Leave
+ # whitespace-only as is so the probe rejects it.
$absolute = $inherited
if (-not [string]::IsNullOrWhiteSpace($inherited)) {
try { $absolute = [System.IO.Path]::GetFullPath($inherited) } catch { $absolute = $inherited }
}
if (Test-StudioDirectoryUsable -Path $absolute) {
- # A host whose temp was fixed since the last run never allocates another
- # private directory, and the allocator is the only thing that sweeps.
- # Without this, whatever an earlier degraded run left behind ages in
- # place until an uninstall. Each root that does not exist is a no-op.
+ # The allocator is the only sweeper, so sweep here too when the temp is healthy.
foreach ($root in @(Get-StudioPrivateTempRoots)) {
Remove-StudioStalePrivateTempDirectories -Root $root
}
- # Pin what was probed. A relative value (temp, or the drive-relative
- # C:temp) is resolved by whoever reads it, and the install relocates
- # out of a Windows system directory further down, so the same value
- # could later name somewhere else, or nowhere. An already-absolute
- # value normalizes to itself and is left alone.
+ # Pin the absolute spelling: a relative value could later name somewhere else.
if (-not [string]::Equals($absolute, $inherited, [System.StringComparison]::Ordinal)) {
$script:StudioTempOverride = [pscustomobject]@{
TmpSet = ($null -ne $env:TMP)
@@ -1955,8 +1747,7 @@ function Install-UnslothStudio {
Write-StudioLine "[WARN] No writable temporary directory was found; downloads may fail." -ForegroundColor Yellow
return
}
- # Absent is not empty: restoring an absent variable as "" would change how
- # every later child resolves its own temp directory.
+ # Absent is not empty: restoring an absent variable as "" changes children's temp.
$script:StudioTempOverride = [pscustomobject]@{
TmpSet = ($null -ne $env:TMP)
TmpValue = $env:TMP
@@ -1978,8 +1769,7 @@ function Install-UnslothStudio {
else { Remove-Item Env:\TMP -ErrorAction SilentlyContinue }
if ($override.TempSet) { $env:TEMP = $override.TempValue }
else { Remove-Item Env:\TEMP -ErrorAction SilentlyContinue }
- # The directory stays: an autostarted Unsloth inherited it as its own %TEMP%,
- # and the host's real one is broken. The next run sweeps the old ones.
+ # The directory stays: an autostarted Unsloth inherited it as %TEMP%.
}
# ── Parse flags ──
@@ -1990,15 +1780,11 @@ function Install-UnslothStudio {
$SkipTorch = $false
$SkipAutostart = $false
$IsolateUvCache = $false
- # Script-scoped: Start-StudioVenvRollback reads it, and tests/studio/test_install_rollback_lifecycle.ps1
- # extracts that function on its own.
+ # Script-scoped: tests/studio/test_install_rollback_lifecycle.ps1 extracts
+ # Start-StudioVenvRollback on its own.
$script:StudioNoRollback = $false
- # Set later by the cross-volume cache notice and read later still by Start-StudioVenvRollback.
- # Initialised here rather than beside the other rollback state, which is reset AFTER that
- # notice runs and would therefore clear it. Under `irm | iex` the script scope IS the caller's
- # session, so a stale value from a previous run has to be cleared somewhere.
- # Bounded WMI answer, taken at most once per run. Reset here for the same reason as the rest
- # of this block: under `irm | iex` the script scope IS the caller's session.
+ # Initialised here, before the cache notice that sets it (the later reset would clear it).
+ # Reset per run: under `irm | iex` the script scope is the caller's session.
$script:StudioVolumeList = $null
# Set by the --no-rollback discard when the environment it is about to delete reports XPU,
# read by the Intel scan once that tree is gone.
@@ -2201,9 +1987,7 @@ function Install-UnslothStudio {
Write-Verbose "Unsloth: path identity is inexact ($Reason); first install, taking every runtime lock."
return
}
- # This used to promise "installation is unaffected", which it cannot know:
- # the same security software that blocks a type can be acting on the rest of
- # the run. Only the narrower claim is true, that the installer can continue.
+ # Only claim that the installer can continue.
Write-StudioLine "[WARN] Could not resolve a path exactly ($Reason)." -ForegroundColor Yellow
Write-StudioLine " Continuing with the lexical resolver, which cannot recover a path's" -ForegroundColor Yellow
Write-StudioLine " stored casing or expand an 8.3 name, so paths are compared as written." -ForegroundColor Yellow
@@ -2238,21 +2022,16 @@ function Install-UnslothStudio {
if ([string]::IsNullOrWhiteSpace($target)) { return $null }
if ($target.StartsWith('\??\')) {
$target = $target.Substring(4)
- # \??\UNC\server\share is the device spelling of \\server\share. Left as
- # "UNC\server\share" it reads as RELATIVE and gets combined with the
- # link's local parent, inventing a path; a wrong identity is a wrong mutex.
+ # \??\UNC\server\share is the device spelling of \\server\share; left as is it reads as
+ # relative and yields a wrong mutex identity.
if ($target.StartsWith('UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
$target = '\\' + $target.Substring(4)
} elseif ($target.StartsWith('Volume{', [System.StringComparison]::OrdinalIgnoreCase)) {
- # A mounted folder reports \??\Volume{GUID}\..., the same trap:
- # "Volume{...}\..." is not rooted either. \\?\ is the extended-length
- # spelling of that device path, so it keeps naming the volume.
+ # Same for \??\Volume{GUID}\...: \\?\ keeps naming the volume.
$target = '\\?\' + $target
}
}
- # "\real" is rooted as far as IsPathRooted is concerned but names no drive,
- # so GetFullPath would resolve it against the PROCESS current drive. Windows
- # resolves a drive-less target on the LINK's own volume, so anchor it there.
+ # A drive-less "\real" resolves on the LINK's volume, not the process's current drive.
if ($target.Length -ge 1 -and ($target[0] -eq '\' -or $target[0] -eq '/') -and
-not ($target.Length -ge 2 -and ($target[1] -eq '\' -or $target[1] -eq '/'))) {
$linkRoot = $null
@@ -2282,19 +2061,12 @@ function Install-UnslothStudio {
return $target
}
- # Compiler-free stand-in for the native resolver. Normalized, not exact: it
- # cannot expand an 8.3 alias or recover stored casing, so callers are told the
- # answer is inexact. Never throws; an identity nobody can establish must not
- # stop an install.
+ # Compiler-free stand-in for the native resolver: normalized, not exact (no 8.3
+ # expansion or casing). Never throws.
$script:StudioSubstMap = $null
function Get-StudioSubstTarget {
param([Parameter(Mandatory = $true)][string]$Path)
- # A SUBST drive is a DOS device mapping and no 5.1 API reports it: measured
- # on windows-latest, Get-PSDrive.DisplayRoot and Win32_LogicalDisk.ProviderName
- # are empty, GetFullPath and Resolve-Path hand X:\ straight back, and
- # (Get-Item X:\).Target reports the target's tail under the SUBST letter.
- # `subst` with no arguments prints the mapping in full ("X:\: => D:\real\dir"),
- # so that is what this reads, once.
+ # No 5.1 API reports SUBST mappings; `subst` with no arguments prints them, read once.
if ($null -eq $script:StudioSubstMap) {
$script:StudioSubstMap = @{}
try {
@@ -2321,9 +2093,7 @@ function Install-UnslothStudio {
param([Parameter(Mandatory = $true)][string]$Path)
$current = $null
try { $current = [System.IO.Path]::GetFullPath($Path) } catch { return $Path }
- # Fold a SUBST drive BEFORE walking components: the Python runtime gate
- # resolves it, so leaving it would give the two sides different mutex names
- # for one directory and hide a running Unsloth from the in-use scan.
+ # Fold SUBST first: the Python runtime gate resolves it, and both must name one mutex.
$substituted = Get-StudioSubstTarget -Path $current
if ($substituted) {
try { $current = [System.IO.Path]::GetFullPath($substituted) } catch {}
@@ -2331,9 +2101,7 @@ function Install-UnslothStudio {
# Hashtable, not a generic HashSet: already case-insensitive, and a
# locked-down host (the kind that got here) can forbid generic types.
$visited = @{}
- # A link on a PARENT component is the ordinary Windows shape (redirected
- # profiles), so walk from the root and restart at each one. Capped with a
- # visited set, because reparse points can point at each other.
+ # Links on parent components are ordinary; walk from the root, capped against loops.
for ($hop = 0; $hop -lt 32; $hop++) {
if ($visited.ContainsKey($current)) { break }
$visited[$current] = $true
@@ -2917,12 +2685,8 @@ function Install-UnslothStudio {
}
}
- # Tell Explorer a shortcut was rewritten, through a child interpreter. Used only where the
- # type cannot be defined in this shell, which is where the refresh silently did not happen
- # before. Returns $true when the child reported success.
- #
- # Cosmetic either way: the worst case is a stale icon on a shortcut that works. Nothing here
- # may fail the install, so every path returns rather than throws.
+ # Tell Explorer a shortcut changed via a child interpreter, where the type cannot be
+ # defined in this shell. Cosmetic; never fails the install.
function Invoke-StudioPythonShellIconRefresh {
param([string[]]$Paths = @(), [string]$Exe = "", [switch]$DestinationValidated)
if (-not ($env:OS -eq "Windows_NT")) { return $false }
@@ -2994,14 +2758,8 @@ function Install-UnslothStudio {
if ($resolved.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
$resolved = '\\' + $resolved.Substring(8)
} elseif ($resolved.StartsWith('\\?\', [System.StringComparison]::OrdinalIgnoreCase)) {
- # Every extended spelling, INCLUDING \\?\Volume{GUID}\, because this string
- # is hashed into the runtime mutex name and unsloth_cli/_studio_runtime_gate.py
- # strips \\?\ unconditionally (_resolved_windows_path). Keeping the prefix
- # here made the installer and a running Unsloth compute different names for
- # one directory, so neither would exclude the other. Rootedness does matter
- # while a link target is being anchored, and Resolve-StudioLinkTarget keeps
- # the extended form for exactly that; nothing after this point anchors
- # anything, and Combine only drops its left side for a ROOTED right side.
+ # Strip every extended prefix, including \\?\Volume{GUID}\: this is hashed into the
+ # runtime mutex name and unsloth_cli/_studio_runtime_gate.py strips \\?\ unconditionally.
$resolved = $resolved.Substring(4)
}
foreach ($segment in $missingSegments) {
@@ -3055,27 +2813,18 @@ function Install-UnslothStudio {
return $null
}
- # Free space for the disk-full diagnosis (#11313), answering $null rather than guessing: a
- # number this cannot produce is a diagnosis it does not print.
- # A Windows volume can be mounted at a DIRECTORY, and then the drive root is the wrong answer:
- # GetPathRoot reduces C:\studio to C:\, so two paths on different volumes compare equal.
- # Win32_Volume lists mount points by the path they are mounted at, so the longest Name that
- # prefixes a path names the volume really holding it; anywhere CIM cannot answer, callers fall
- # back to the drive-root logic, which is right for a lettered volume.
- # Known limit: Name exposes ONE access path, so a volume reached through a second one falls
- # back to the drive root, the pre-existing answer. Closing it needs a Win32_MountPoint join on
- # every install, for a diagnostic. Split out so the matching is testable without a mount point.
+ # Free space for the disk-full diagnosis (#11313), or $null. A volume can be mounted at a
+ # directory, so take the longest Win32_Volume Name prefixing the path; otherwise callers
+ # fall back to the drive root.
function Select-StudioVolumeForPath {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
[Parameter(Mandatory = $true)][AllowEmptyCollection()][object[]]$Volumes)
if ([string]::IsNullOrWhiteSpace($Path)) { return $null }
- # Unrooted means GetFullPath would anchor it to the current directory and invent a match
- # on whichever volume that happens to be. No answer is the honest one.
+ # Unrooted would anchor to the current directory and invent a match.
if (-not [System.IO.Path]::IsPathRooted($Path)) { return $null }
$full = [System.IO.Path]::GetFullPath($Path)
- # Name carries a trailing separator and GetFullPath does not, so a path that IS the mount
- # point would miss its own volume. Appending one also keeps C:\studiofoo from matching a
- # volume mounted at C:\studio.
+ # Append a separator so the mount point matches itself and C:\studiofoo does not match
+ # C:\studio.
if (-not $full.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
$full += [System.IO.Path]::DirectorySeparatorChar
}
@@ -3088,25 +2837,19 @@ function Install-UnslothStudio {
return $best
}
- # Junctions and symlinks lie about which volume a path is on, so a studio home behind one is
- # otherwise measured on the link's host drive. The lexical fallback keeps a resolver that
- # cannot answer from costing the caller its measurement entirely.
+ # Junctions lie about which volume a path is on; resolve first, lexical fallback.
function Resolve-StudioVolumeQueryPath {
param([Parameter(Mandatory = $true)][string]$Path)
try {
$final = Get-StudioFinalPath -Path $Path
- # Get-StudioFinalPath strips \\?\ deliberately, so a volume with no drive letter comes
- # back as Volume{GUID}\..., which is NOT rooted: GetFullPath would then anchor it to
- # the current directory and name an unrelated volume. Keep the caller's own path.
+ # Volume{GUID}\... is not rooted, so keep the caller's path then.
if ($final -and [System.IO.Path]::IsPathRooted($final)) { return $final }
return $Path
} catch { return $Path }
}
- # Bounded out of process, as Invoke-BoundedVideoControllerScan documents: a degraded WMI
- # repository blocks a CIM query indefinitely, and neither -ErrorAction nor try/catch bounds a
- # query that never returns. Cached, timeouts included, so a broken repository costs once, and
- # -Fresh for the free-space caller, whose cached FreeSpace would be a pre-failure snapshot.
+ # Out of process and bounded: a degraded WMI repository blocks CIM queries forever.
+ # Cached (timeouts too); -Fresh for the free-space caller.
function Get-StudioVolumeList {
param([switch]$Fresh)
if (-not $Fresh -and $null -ne $script:StudioVolumeList) { return $script:StudioVolumeList }
@@ -3204,11 +2947,7 @@ function Install-UnslothStudio {
Write-StudioLine " The desktop app uses the Windows profile .unsloth\studio root." -ForegroundColor Red
Write-StudioLine " Run install.ps1 without --tauri for custom-root shell installs," -ForegroundColor Yellow
Write-StudioLine " or unset the env var for default desktop installs." -ForegroundColor Yellow
- # Belt and braces: only Initialize-StudioTempEnvironment redirects
- # TMP/TEMP and it now runs after this throw, so there is nothing to
- # restore today. The call is a no-op when nothing was overridden, and
- # under `irm | iex` those variables are the caller's own, so this stays
- # correct if anything above starts redirecting them again.
+ # No-op today (nothing redirected TMP/TEMP yet), kept so this stays correct if that changes.
Restore-StudioTempEnvironment
throw "$envOverrideVar is not supported with --tauri."
}
@@ -3227,10 +2966,8 @@ function Install-UnslothStudio {
if ($envOverride) {
try {
- # BEFORE the create: this is the only moment anyone can still tell. The lock runs
- # thousands of lines below and asks whether the root existed, which by then is yes for
- # every env-mode root, so its ownership branch would never fire for the roots it was
- # written for.
+ # BEFORE the create: the lock later asks whether the root pre-existed, and after the
+ # create every env-mode root does.
$script:StudioEnvRootPath = $envOverride
$script:StudioEnvRootExisted = [System.IO.Directory]::Exists($envOverride)
# .NET API: New-Item -Path treats brackets as wildcards (no -LiteralPath on PS 5.1).
@@ -3300,13 +3037,8 @@ function Install-UnslothStudio {
(Test-Path -LiteralPath (Join-Path $StudioHome ".venv")) -or
($env:USERPROFILE -and (Test-Path -LiteralPath (Join-Path $env:USERPROFILE "unsloth_studio"))))
- # Records which cache this install used, so an update reuses it rather than guessing:
- # Set-StudioUvCacheForLaunch repoints the backend at the Studio cache even in shared
- # mode, so one on-demand install makes an empty Studio cache look full. Never fatal.
- # uv resolves a relative cache-dir against its working directory, which UV_WORKING_DIR
- # moves and which may itself be relative to where the installer was run. $PWD.Path
- # explicitly: GetFullPath resolves against the .NET process directory, which
- # Set-Location does not move. Mirrors _absolutize_uv_cache_dir in install.sh.
+ # Records which uv cache this install used so an update reuses it. Absolutized against
+ # $PWD.Path (not the .NET process dir), as _absolutize_uv_cache_dir in install.sh.
function Resolve-StudioUvCachePath {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Cache)
if ([string]::IsNullOrEmpty($Cache)) { return $Cache }
@@ -3320,9 +3052,7 @@ function Install-UnslothStudio {
$Cache = [System.IO.Path]::GetFullPath((Join-Path $base $Cache))
} catch { return $Cache }
}
- # A trailing separator names the same directory but compares unequal, and that
- # comparison picks `studio` over `shared` in the selector. Never past the root, which
- # is a real directory. Mirrors the trim in _absolutize_uv_cache_dir.
+ # Trim trailing separators (never past the root), as in _absolutize_uv_cache_dir.
try {
$root = [System.IO.Path]::GetPathRoot($Cache)
while ($Cache.Length -gt $root.Length -and
@@ -3333,17 +3063,12 @@ function Install-UnslothStudio {
return $Cache
}
- # Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's
- # own marker all land inside it, so an install that dies in between used to leave a directory
- # the uninstaller could only identify by guessing at leftovers. Never fatal.
- # A sentinel this list may trust: a regular file, never a link. Test-Path follows one, and a
- # planted link would otherwise short-circuit the emptiness test below.
+ # Claim the root before anything lands in it, so the uninstaller need not guess. Never
+ # fatal. A trusted sentinel must be a regular file, never a link.
function Test-StudioPlainFile {
param([string]$Path, [string]$Container)
try {
- # The container too: -L / the ReparsePoint attribute answers for the named file only,
- # so a linked `share` or `unsloth_studio` holding a genuine marker would otherwise
- # read as proof that the whole workspace around it is ours.
+ # Check the container too: a linked parent holding a genuine marker proves nothing.
if (-not [string]::IsNullOrWhiteSpace($Container)) {
$dir = Get-Item -LiteralPath $Container -Force -ErrorAction SilentlyContinue
if ($dir -and (($dir.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)) { return $false }
@@ -3354,16 +3079,9 @@ function Install-UnslothStudio {
} catch { return $false }
}
- # Only a root this run may take over: in env mode $StudioHome is a user-chosen workspace, so
- # an empty one, or one already carrying an unambiguous marker, and nothing else, or a run
- # that aborts at the venv-step guard leaves somebody's project marked. Shorter than that
- # guard's list on purpose: it only refuses to overwrite, this authorizes a delete.
- #
- # The emptiness test is inline, not Test-DirectoryHasEntries, which is defined below this
- # function's first caller: the name error would land in the catch and skip the claim in
- # silence. An unreadable root counts as occupied, so failure means "do not claim".
- # Above its earliest reader, not beside the lock helpers: Write-StudioRootOwnerMarker filters
- # this name out of its emptiness test thousands of lines earlier, and a $null filters nothing.
+ # Only a root this run may take over (empty, or with an unambiguous marker); this
+ # authorizes a delete. Emptiness test inline (the helper is defined later); unreadable
+ # counts as occupied. Defined above its earliest reader.
$script:StudioInstallLockFileName = ".unsloth-install.lock"
function Write-StudioRootOwnerMarker {
@@ -3395,17 +3113,11 @@ function Install-UnslothStudio {
# .NET API: New-Item -Path treats brackets as wildcards.
[System.IO.Directory]::CreateDirectory($Root) | Out-Null
}
- # Delete first, then confirm it: WriteAllText follows a file link and truncates its
- # TARGET, and the delete can fail on a root we cannot write while that target stays
- # writable. No marker is fine; the venv writes its own later.
- # Get-Item -Force, not Test-Path: the latter follows a dangling link and answers
- # false, after which WriteAllText follows the link and writes outside the root.
+ # Delete first, then confirm with Get-Item -Force: WriteAllText follows a file link and
+ # Test-Path follows a dangling one.
Remove-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue
- # CreateNew, not check-then-write: the pair left a window to plant a link at the name
- # and have the write truncate its target. Residual, stated rather than implied away: a
- # DANGLING link is still followed and creates a zero-byte file at its target, which
- # cannot destroy an existing one. FILE_FLAG_OPEN_REPARSE_POINT is the complete answer
- # and .NET does not expose it here.
+ # CreateNew closes the check-then-write race. A dangling link is still followed (it can
+ # only create an empty file).
$markerStream = $null
try {
$markerStream = [System.IO.File]::Open($marker,
@@ -3435,9 +3147,7 @@ function Install-UnslothStudio {
# Under "Stop", Test-Path inside an ACL-denied directory throws.
$existing = Test-Path -LiteralPath $markerFile -ErrorAction SilentlyContinue
if ($existing) {
- # UTF8, not the default: Windows PowerShell 5.1 decodes a BOM-less file
- # with the active ANSI code page, and the update writes this one BOM-less
- # UTF-8, so a non-ASCII path came back as mojibake and was restored that way.
+ # UTF8: 5.1 decodes BOM-less files with the ANSI code page.
$previous = Get-Content -LiteralPath $markerFile -Raw -Encoding UTF8 `
-ErrorAction SilentlyContinue
# One we cannot read is one we cannot put back, so leave it alone.
@@ -3482,11 +3192,8 @@ function Install-UnslothStudio {
$script:StudioUvMarkerSaved = $false
}
- # uv --no-cache neither reads nor writes a cache: on uv 0.10.7 a caller's UV_CACHE_DIR stays
- # completely empty, CACHEDIR.TAG included, so nothing this install did belongs in the marker
- # whichever branch chose the directory. Lowercased, since uv takes it case-insensitively; not
- # trimmed, since uv rejects a padded value outright. The literals are clap's
- # BoolishValueParser set, `y` and `t` included. Mirrors _uv_no_cache_requested in install.sh.
+ # uv --no-cache neither reads nor writes a cache, so nothing belongs in the marker.
+ # Lowercased, not trimmed; clap's boolish set. Mirrors _uv_no_cache_requested.
function Test-StudioUvNoCache {
return (([string]$env:UV_NO_CACHE).ToLowerInvariant() -in @("1", "y", "yes", "t", "true", "on"))
}
@@ -3517,10 +3224,8 @@ function Install-UnslothStudio {
"git", "interpreter", "osv", "python", "sdists", "simple", "wheels"))
}
- # Readable is not usable: uv writes CACHEDIR.TAG into the root and renames distributions
- # into the buckets, aborting on either, and an ACL answers a different question than a real
- # create. So create and delete for real, in the root and in EVERY <kind>-v<N> bucket: uv
- # mutates interpreter-v4 too. Mirrors the probe loop in _configure_uv_cache.
+ # Readable is not usable: create and delete for real in the root and in EVERY
+ # <kind>-v<N> bucket. Mirrors the probe loop in _configure_uv_cache.
function Test-StudioUvCacheWritable {
param([Parameter(Mandatory = $true)][string]$Cache)
$probeDirs = [System.Collections.Generic.List[string]]::new()
@@ -3558,11 +3263,8 @@ function Install-UnslothStudio {
return $true
}
- # Warm means package BYTES: wheels-* is metadata only on uv 0.10, so a bare `--dry-run`
- # used to read as warm. Stricter than the probe above, deliberately: the KIND must be one uv
- # fills, since `archive-v0.backup` holds bytes uv cannot reuse. Missing a future kind here
- # costs a fallback; missing one in the PROBE would let an unwritable cache through.
- # [ref] $Blocked: unreadable is not empty, and the caller's message says why.
+ # Warm means package BYTES in a bucket kind uv fills (wheels-* is metadata only on
+ # uv 0.10). [ref] $Blocked: unreadable is not empty.
function Test-StudioUvCachePopulated {
param(
[Parameter(Mandatory = $true)][string]$Cache,
@@ -3608,10 +3310,7 @@ function Install-UnslothStudio {
$probe = Join-Path $Cache (".unsloth-write-probe." + [guid]::NewGuid().ToString("N").Substring(0, 8))
[System.IO.File]::WriteAllText($probe, "")
} catch { return $false }
- # NTFS carries DELETE as its own ACE, so a root can grant create and deny unlink. But
- # GONE is the answer, not the cmdlet's error: -ErrorAction Stop throws for a probe
- # something else already removed, where `rm -f` exits 0, and an indexer holding the
- # handle makes one delete fail and the next succeed. Retry, then ask the filesystem.
+ # A root can grant create and deny delete; retry, then ask whether the probe is GONE.
for ($attempt = 0; $attempt -lt 3; $attempt++) {
if ($attempt -gt 0) { Start-Sleep -Seconds 1 }
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
@@ -3711,17 +3410,8 @@ function Install-UnslothStudio {
# directory, so scanning it as written inspects a same-named directory beside us.
if ($defaultCache) { $defaultCache = Resolve-StudioUvCachePath -Cache $defaultCache }
- # The cache THIS install last recorded outranks uv's default while it is still
- # warm, or a rerun abandons a Studio cache holding Torch and CUDA the moment one
- # unrelated wheel makes uv's default read as warm. Content cannot decide it, because
- # the repoint below leaves backend bytes in the losing cache; that is what the marker
- # is for. Same order as _configure_uv_cache and _with_studio_uv_cache.
- # An install from before the marker has a populated Studio cache and nothing
- # recording it, so it is worth keeping. But it goes LAST, behind uv's default: an
- # install old enough to have no marker is old enough that `shared` was reachable,
- # and in that mode the launch repoint leaves backend wheels in the Studio cache
- # while Torch and CUDA sit in the default. Ahead of the default it picked those
- # leftovers. Mirrors install.sh and unsloth_cli/commands/studio.py.
+ # The recorded cache outranks uv's default while still warm. An unmarked (pre-marker)
+ # Studio cache goes LAST. Same order as install.sh and unsloth_cli/commands/studio.py.
$recorded = Read-StudioUvCacheMarker -StudioRoot $StudioRoot
# A marker naming a directory that is gone is a stale pointer, not a decision, so
# it lands in the same place.
@@ -3731,14 +3421,9 @@ function Install-UnslothStudio {
foreach ($candidate in @($recorded, $defaultCache, $unmarkedStudio)) {
if ([string]::IsNullOrWhiteSpace([string]$candidate)) { continue }
if ($chosenCache) { continue }
- # SilentlyContinue: under "Stop" a Test-Path inside an ACL-denied directory
- # THROWS, and that escapes to the outer catch and kills the whole loop, so one
- # unreachable marker would also cost us uv's default. install.sh's
- # `[ -d ] && [ -r ]` just reads false and moves on.
+ # SilentlyContinue: under "Stop" Test-Path in an ACL-denied dir throws and kills the loop.
if (-not (Test-Path -LiteralPath $candidate -PathType Container -ErrorAction SilentlyContinue)) { continue }
- # Per candidate: the scan can report blocked and still return $true, so a
- # shared flag pins the NEXT candidate's name into $blockedCache and suppresses
- # the message naming the cache actually refused.
+ # Per candidate, so the message names the cache actually refused.
$candidateBlocked = $false
$populated = Test-StudioUvCachePopulated -Cache $candidate -Blocked ([ref]$candidateBlocked)
if ($candidateBlocked) {
@@ -3766,18 +3451,10 @@ function Install-UnslothStudio {
} else {
$selectedCache = $studioCache
$script:StudioUvCacheMode = "studio"
- # A fallback we cannot write is not a fallback. The certain failure and the merely
- # suspect cache can both be on the table, and landing on the certain one turns a
- # working install into "failed to create cache directory".
- # Root AND buckets: the root can be writable while a bucket uv renames into is
- # not, which is what the candidate probe rejected a cache for. Anything usable
- # beats landing there: the populated cache that only failed the probe first, then
- # uv's own default, which at worst costs the downloads this cache never saved.
+ # The fallback must be usable (root AND buckets); otherwise prefer the populated cache
+ # that only failed the probe, then uv's default.
if (-not (Test-StudioUvCacheUsable -Cache $studioCache)) {
- # A cache that is WARM and merely failed the probe beats a cold one we can
- # write, including when it is the Studio cache itself: the probe refuses a
- # whole cache for one bucket-shaped entry uv may never touch, where a cold
- # cache guarantees the downloads and offline guarantees failure.
+ # A warm cache that merely failed the probe beats a cold one.
if ($warnCache) {
$selectedCache = $warnCache
if ($warnCache -ne $studioCache) {
@@ -3820,12 +3497,8 @@ function Install-UnslothStudio {
function Set-StudioUvCacheForLaunch {
param([Parameter(Mandatory = $true)][string]$StudioRoot)
if ($script:StudioUvCacheMode -ne "shared") { return }
- # Only to a cache the backend can fill: repointing at one we cannot write hands the
- # autostarted backend a cache uv aborts on, after an install that succeeded. Keeping the
- # shared one is honest, it is the cache this install just filled. Mirrors
+ # Only repoint the launch to a cache the backend can fill (root AND buckets). Mirrors
# _prepare_studio_uv_cache_for_launch.
- # Root AND buckets, the same rule the selection used: a root-only check repoints into
- # the very cache the candidate probe rejected for a bucket uv cannot rename into.
$launchCache = Join-Path (Join-Path $StudioRoot "cache") "uv"
if (-not (Test-StudioUvCacheUsable -Cache $launchCache)) { return }
Set-Item -LiteralPath Env:UV_CACHE_DIR -Value $launchCache
@@ -3849,32 +3522,13 @@ function Install-UnslothStudio {
function Enable-StudioVirtualTerminal {
if ($env:NO_COLOR) { return $false }
- # A redirected stdout is not a console, so there is no virtual terminal to speak of.
- # install.rs spawns us with a pipe, so that is the path the desktop app is on, and it is
- # decided here before anything else is consulted.
+ # A redirected stdout is not a console: the desktop app's pipe has no virtual terminal.
if ($script:StudioStdoutRedirected) { return $false }
- # Windows PowerShell's console host already does the GetStdHandle / GetConsoleMode /
- # SetConsoleMode sequence this function used to do by hand, at startup, and reports
- # the outcome through this property, and it is STRICTER than what this replaced:
- # ConsoleHostUserInterface.TryTurnOnVirtualTerminal re-reads the mode after setting it, because
- # older systems accept the call and ignore the flag. The deleted code trusted SetConsoleMode's
- # return value. So the property cannot read True while VT is actually off.
- #
- # Measured on Windows PowerShell 5.1.26100 attached to a real console: the property answers True,
- # the native call answers True, and the console mode read BEFORE touching it is already 0x7 --
- # which contains 0x4, ENABLE_VIRTUAL_TERMINAL_PROCESSING. The SetConsoleMode this replaced was
- # re-setting a bit the host had already set. It was a no-op. The measurement and the lane that
- # produced it are in PR #10984; the record that travels with this repo is in
- # tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD).
- #
- # This removes three of the script's native imports, and with them the only reason the
- # console path (including `irm | iex`) ever reached the type emitter at all -- for colour.
- #
- # [bool] rather than a bare return: the property is virtual with a base of $false, so a host
- # that does not override it answers $false already -- but a host with no UI at all yields $null,
- # and the cast makes that $false too. The try/catch is for Set-StrictMode in a caller's profile,
- # where reading an absent property raises PropertyNotFoundException rather than returning $null.
+ # The console host already enables VT at startup and verifies it, so this property cannot
+ # read True while VT is off (measured in PR #10984; see
+ # tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)). [bool] maps a no-UI host's
+ # $null to $false; try/catch covers a caller's Set-StrictMode.
try { return [bool]$Host.UI.SupportsVirtualTerminal } catch { return $false }
}
$script:StudioVtOk = Enable-StudioVirtualTerminal
@@ -3906,25 +3560,16 @@ function Install-UnslothStudio {
}
Write-StudioLine ""
- # Here so its warning lands under the banner. The native path resolver used to
- # reach it first, because compiling wrote to %TEMP%; it no longer writes
- # anything. Nothing between the banner and here touches the temporary
- # directory, so the fix-up still lands before its first user.
+ # Here so its warning lands under the banner, before the temp dir's first user.
Initialize-StudioTempEnvironment
# ── Helper: refresh PATH from registry (deduplicating entries) ──
# Merge order: venv Scripts (if active) > Machine > User > current $env:Path.
- # Dedup compares both raw and expanded forms (%VAR% vs literal).
- # Every prefix an active conda session has put on PATH, deepest first: CONDA_PREFIX is
- # the active environment, CONDA_PREFIX_1.. the ones it was stacked on, and CONDA_EXE
- # names the installation root, which is on PATH for the whole session.
+ # Active conda prefixes, deepest first: CONDA_PREFIX, CONDA_PREFIX_1.., and CONDA_EXE's root.
function Get-ActiveCondaPrefixes {
$prefixes = New-Object System.Collections.Generic.List[string]
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_PREFIX)) { $prefixes.Add($env:CONDA_PREFIX) }
- # Enumerated from CONDA_SHLVL, not a fixed list: a hard-coded tail of three dropped
- # everything past the fourth stacked environment, which sorted its PATH entries
- # after Machine and User and inverted the ordering the stack established. The
- # ceiling stops a bad value spinning.
+ # Enumerated from CONDA_SHLVL with a ceiling, not a fixed list.
$levels = 0
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_SHLVL)) {
[void][int]::TryParse($env:CONDA_SHLVL, [ref]$levels)
@@ -3937,9 +3582,7 @@ function Install-UnslothStudio {
}
if (-not [string]::IsNullOrWhiteSpace($env:_CONDA_ROOT)) { $prefixes.Add($env:_CONDA_ROOT) }
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_EXE)) {
- # ...\<root>\Scripts\conda.exe -> ...\<root>. Regex rather than Split-Path, which
- # is provider-aware and does not treat a backslash as a separator on the
- # non-Windows PowerShell the tests run under.
+ # Regex, not Split-Path, which is provider-aware on non-Windows test hosts.
$scripts = $env:CONDA_EXE -replace '[\\/][^\\/]*$', ''
$root = $scripts -replace '[\\/][^\\/]*$', ''
if ($root -and $root -ne $env:CONDA_EXE) { $prefixes.Add($root) }
@@ -3969,9 +3612,7 @@ function Install-UnslothStudio {
$machine = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
$user = [System.Environment]::GetEnvironmentVariable("Path", "User")
$venvScripts = if ($env:VIRTUAL_ENV) { Join-Path $env:VIRTUAL_ENV "Scripts" } else { $null }
- # An activated conda environment lives ONLY in the process PATH, so rebuilding as
- # machine + user + previous demotes it, and under `irm | iex` that PATH is the
- # caller's own prompt. Restored by position; the dedup below drops the copies.
+ # An activated conda env lives only in the process PATH, so keep it in front.
$condaFront = @()
if (Test-ActiveCondaEnvironment) {
$prefixes = Get-ActiveCondaPrefixes
@@ -3982,9 +3623,7 @@ function Install-UnslothStudio {
}
}
} else {
- # A hook exporting CONDA_DEFAULT_ENV and no directory: nothing names which
- # entries are conda's, and guessing from the name would promote a stranger,
- # so the caller's PATH is kept whole and in front.
+ # Only CONDA_DEFAULT_ENV, no directory: keep the caller's PATH whole and in front.
$condaFront = @($env:Path)
}
}
@@ -4009,9 +3648,7 @@ function Install-UnslothStudio {
}
# ── Helper: is a conda environment ACTIVE in this session? ──
- # CONDA_PREFIX separates "conda is installed" from "we are inside one of its
- # environments". CONDA_DEFAULT_ENV is read too: a hook that exports only that one still
- # leaves the caller inside conda's PATH ordering.
+ # CONDA_PREFIX or CONDA_DEFAULT_ENV, not merely conda being installed.
function Test-ActiveCondaEnvironment {
foreach ($condaVar in @($env:CONDA_PREFIX, $env:CONDA_DEFAULT_ENV)) {
if (-not [string]::IsNullOrWhiteSpace($condaVar)) { return $true }
@@ -4019,10 +3656,8 @@ function Install-UnslothStudio {
return $false
}
- # The position a PERSISTENT PATH write may actually use. A prepend outlives the conda
- # activation it was made under, so conda ends up resolving binaries and DLLs out of our
- # directory, which is what corrupts an Anaconda base on its next `conda update` (#5871).
- # An append registers the same directory without demoting anything.
+ # Persistent writes must append under an active conda env: a prepend outlives the
+ # activation and corrupts Anaconda base (#5871).
function Resolve-UserPathPosition {
param(
[ValidateSet('Append','Prepend')]
@@ -4044,11 +3679,7 @@ function Install-UnslothStudio {
# conda environment cannot be demoted by any call site. Announced once per run: the
# installer makes several of these writes and one note is information, five is noise.
$resolvedPosition = Resolve-UserPathPosition -Position $Position
- # A downgraded request has to be able to MOVE an entry, not just decline to add one. After a
- # previous non-conda run our directory is already at the FRONT of the User PATH, and the
- # append-idempotent early return below would leave that ordering in place while this very
- # substep announced that conda keeps priority -- the #5871 demotion, still armed, reported as
- # fixed. Only a genuine Append request keeps the cheap no-op.
+ # A downgraded request must MOVE an existing front entry, or the #5871 demotion stays armed.
$positionDowngraded = ($resolvedPosition -ne $Position)
if ($positionDowngraded) {
if (-not $script:CondaPathPositionNoted) {
@@ -4162,10 +3793,7 @@ function Install-UnslothStudio {
'DarkGray' { 'DarkGray' }
default { 'DarkGreen' }
}
- # One composed record: two calls are two records, and a redirected
- # consumer splits the label from the value at the boundary.
- # Write-StudioLine picks the sink, so this stays a single line on
- # both of them.
+ # One composed record so a redirected consumer cannot split label from value.
Write-StudioLine (" {0}{1}" -f $padded, $Value) -ForegroundColor $fc
}
}
@@ -4823,9 +4451,8 @@ function Install-UnslothStudio {
# ── END SHARED WITH studio/setup.ps1 ──
- # Redact index-URL credentials (userinfo + ?query= + #fragment) from captured installer
- # output before printing on failure; uv/pip errors echo the failing --index-url verbatim.
- # Mirrors the other installers. Verbose mode streams uncaptured, so it isn't redacted.
+ # Redact index-URL credentials (userinfo, query, fragment) from captured output before
+ # printing on failure. Verbose mode streams uncaptured, so it isn't redacted.
function Redact-InstallOutput {
param([string]$Text)
if (-not $Text) { return $Text }
@@ -4866,12 +4493,8 @@ function Install-UnslothStudio {
Write-TauriLog "OUTPUT_CLEAR" $Label
$collected = [System.Text.StringBuilder]::new()
if ($script:UnslothVerbose) {
- # Merge stderr into stdout so progress/warning output stays visible
- # without flipping $? on successful native commands (PS 5.1 treats
- # stderr records as errors that set $? = $false even on exit code 0).
- # Redact per record: uv echoes index URLs (credentials and all) in
- # its errors, and verbose mode must not bypass the quiet path's
- # redaction. ForEach-Object/Out-Host leave $LASTEXITCODE untouched.
+ # Merge stderr into stdout without flipping $? (5.1 treats stderr records as errors).
+ # Redact per record, verbose mode included.
if ($NoMirror -or -not $env:_UNSLOTH_MIRROR_SPARE) {
& $Command 2>&1 | ForEach-Object {
Write-UvDownloadMarker "$_"
@@ -4967,24 +4590,13 @@ function Install-UnslothStudio {
}
# ── Managed CLI invocation, Application Control safe ──
- # Windows materializes the `unsloth` console script as a generated, unsigned .exe.
- # AppLocker, WDAC and Smart App Control deny it while the venv's python.exe, a copy
- # of the signed CPython binary, still runs, so setup died at "running unsloth studio
- # setup" (#8490). Everything here goes through the interpreter instead; the console
- # script is still installed and hardlinked, so an unaffected machine sees no change.
- #
- # Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs. Two
- # halves, both load bearing:
- # argv[0] BEFORE the import, because unsloth_cli/__init__ decides at import time
- # whether it is the console script (UTF-8 streams, the -np<N> rewrite) and typer
- # reads it for the program name in usage text.
- # sys.path[:1] drops the working directory `python -c` adds and a console script
- # does not, so a stray `unsloth_cli` folder cannot shadow the managed package. It
- # is a no-op under -P or PYTHONSAFEPATH. -I would drop it too, but -I implies -E,
- # and discarding PYTHONPATH, PYTHONWARNINGS and user site-packages diverges from
- # the console script on machines with no policy at all.
- # Written into every generated bin\unsloth.cmd and required by every ownership
- # check that accepts one. Mirrored in scripts/uninstall.ps1 and studio/setup.ps1.
+ # The generated unsigned unsloth.exe is denied by AppLocker/WDAC/Smart App Control while
+ # the venv's signed python.exe runs (#8490), so go through the interpreter.
+ # Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs: argv[0] is
+ # set BEFORE the import (unsloth_cli reads it at import time), and sys.path[:1] drops the
+ # cwd entry `python -c` adds. Not -I: it implies -E.
+ # Marker written into every bin\unsloth.cmd; mirrored in scripts/uninstall.ps1 and
+ # studio/setup.ps1.
$script:UnslothCmdShimMarker = "unsloth-studio-managed-launcher"
$script:UnslothCliTrampoline = "import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"
@@ -5006,9 +4618,7 @@ function Install-UnslothStudio {
return $false
}
- # Print guidance; returns the failure reason as its only pipeline output, matching
- # Write-PathAccessDenied. Never suggests turning a security policy off: the fix is
- # for whoever owns the policy, and Unsloth already stopped needing the blocked file.
+ # Never suggests turning a security policy off.
function Write-ApplicationControlBlocked {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
@@ -5020,10 +4630,7 @@ function Install-UnslothStudio {
return "Windows Application Control blocked the managed Python runtime at $Path."
}
- # One pre-quoted command line, not an argument array: Start-Process joins
- # -ArgumentList with spaces and quotes nothing, so the trampoline as an array
- # element reaches python as a dozen arguments. It holds no double quote and no
- # backslash, so wrapping it is unambiguous under CommandLineToArgvW.
+ # One pre-quoted command line: Start-Process joins -ArgumentList unquoted.
function Get-ManagedUnslothCliCommandLine {
param([string[]]$Arguments = @())
@@ -5036,21 +4643,16 @@ function Install-UnslothStudio {
return (@("-X", "utf8", "-c", $quoted) + $safeArgs) -join " "
}
- # Run the managed `unsloth` CLI through the interpreter. The exit code is published
- # in $script:ManagedUnslothCliExit rather than returned, because the child's stdout
- # shares this function's output stream and capturing it would stop the install
- # streaming to the console and the Tauri log. $null means the interpreter never
- # started under Application Control, which is not an exit code.
+ # Exit code goes to $script:ManagedUnslothCliExit, since stdout must keep streaming.
+ # $null means the interpreter never started under Application Control.
function Invoke-ManagedUnslothCli {
param(
[Parameter(Mandatory = $true)][string]$Python,
[string[]]$Arguments = @()
)
- # -X utf8, not the env var, so the child decodes whatever the console code page
- # is. No -I: it would discard PYTHONPATH and friends, which the console script
- # honors, and the trampoline already drops the -c working-directory entry.
- # Same form as the desktop's build_managed_cli_command.
+ # -X utf8, not the env var. No -I (see the trampoline). Same as
+ # build_managed_cli_command in the desktop app.
$pythonArgs = @("-X", "utf8", "-c", $script:UnslothCliTrampoline) + $Arguments
$script:ManagedUnslothCliExit = $null
try {
@@ -5094,13 +4696,8 @@ function Install-UnslothStudio {
$psi.RedirectStandardError = $true
$proc = [System.Diagnostics.Process]::Start($psi)
try {
- # Drain both pipes BEFORE waiting. With two redirected streams and no
- # reader, a child that fills a pipe buffer blocks writing while we block
- # waiting, and neither side moves. It is reachable here: the trampoline
- # no longer passes -I, so PYTHONPROFILEIMPORTTIME=1 in the environment
- # reaches this child and produces ~24 KB of stderr against a 4 KB buffer.
- # Reading them sequentially would not help, since the child can fill one
- # while we block on the other; async is the only correct answer.
+ # Drain both pipes asynchronously BEFORE waiting, or a child filling one buffer deadlocks
+ # (PYTHONPROFILEIMPORTTIME can produce ~24 KB of stderr).
$stdout = $proc.StandardOutput.ReadToEndAsync()
$stderr = $proc.StandardError.ReadToEndAsync()
if ($proc.WaitForExit(20000)) {
@@ -5127,12 +4724,8 @@ function Install-UnslothStudio {
}
}
- # Which launcher should the printed instructions name? The .cmd, when the .exe
- # cannot be used: either a policy denies it, or it is not there at all. The second
- # case is real -- antivirus quarantine takes the unsigned .exe, and the hardlink and
- # its copy fallback can both fail -- and Test-ShimLaunchBlocked answers $false for a
- # missing file, since nothing refused to start it. Naming a path that does not exist
- # is the one outcome worse than naming a blocked one.
+ # Name the .cmd when the .exe is blocked OR missing (removed after install); a missing file is
+ # not "blocked".
function Test-UnslothCmdShimPreferred {
param(
[Parameter(Mandatory = $true)][string]$ShimExe,
@@ -5144,10 +4737,8 @@ function Install-UnslothStudio {
return (Test-ShimLaunchBlocked -Path $ShimExe)
}
- # Relative path from $From (a directory) to $To, or $null with no common root
- # (different volumes, UNC vs local). Longhand because Path.GetRelativePath is .NET
- # Core only and Uri.MakeRelativeUri percent-encodes the spaces, '#' and '%' that
- # appear in real profile paths.
+ # Relative path or $null across roots. Longhand: GetRelativePath is .NET Core only and
+ # MakeRelativeUri percent-encodes.
function Get-RelativeShimPath {
param(
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$From,
@@ -5173,16 +4764,9 @@ function Install-UnslothStudio {
return (@($up + $down) -join '\')
}
- # The `unsloth.cmd` companion to the shim .exe. A pure function of the two paths, so
- # a re-run reproduces it byte for byte, and %~dp0 keeps profile paths containing
- # spaces, '$', brackets and apostrophes out of the file. CRLF and ASCII, no BOM:
- # cmd.exe reads a BOM as part of the first command.
- #
- # Scope, stated plainly: this answers EXE-and-DLL enforcement of the unsigned
- # console script, which is issue #8490. A machine that also enforces AppLocker's
- # Script collection denies .cmd and .ps1 alike, and install.ps1 itself would not
- # have run there. The interpreter route is what carries such a machine; the shim
- # is the convenience on top of it.
+ # Pure function of two paths, so re-runs are byte-identical. %~dp0 keeps special path
+ # characters out of the file. CRLF, ASCII, no BOM (cmd reads a BOM as a command).
+ # Covers EXE/DLL enforcement (#8490); AppLocker Script rules block .cmd too.
function Get-UnslothCmdShimContent {
param(
[Parameter(Mandatory = $true)][string]$ShimDir,
@@ -5200,10 +4784,7 @@ function Install-UnslothStudio {
"rem Runs the Unsloth CLI through the managed interpreter. The generated",
"rem unsloth.exe beside it is unsigned, and Windows Application Control",
"rem denies it on managed machines; this file is the way through.",
- # The ownership marker, and the only reason a .cmd may stand in for the other
- # sentinels. It gates a recursive delete, so it has to be something nobody
- # writes by accident: `from unsloth_cli import app` is a plausible line in
- # anyone's hand-rolled wrapper, this is not.
+ # The ownership marker; it gates a recursive delete, so it must be unmistakable.
"rem $script:UnslothCmdShimMarker",
# With delayed expansion on (cmd /V:ON, or the machine-wide default) a '!'
# is eaten out of every argument. exit /b ends the scope, so nothing leaks.
@@ -5223,19 +4804,14 @@ function Install-UnslothStudio {
[Parameter(Mandatory = $true)][string]$PythonPath
)
- # Probes inside the try too: this runs under the venv rollback guard, so a throw
- # here would undo a successful install over an optional launcher.
+ # Probes inside the try: a throw under the rollback guard would undo the install.
$shimCmd = Join-Path $ShimDir "unsloth.cmd"
try {
if (Test-Path -LiteralPath $shimCmd -PathType Container) {
substep "cannot write $shimCmd, a directory is in the way" "Yellow"
return
}
- # A run killed between the write and the rename leaves its temp file behind,
- # and the next run has a different PID and would never look at it. Swept
- # before the unchanged-content return below, which is the path an interrupted
- # install takes on its way out. Only this file's own temps, only ones no
- # live process is still writing.
+ # Sweep temps from killed runs (not live ones) before the unchanged-content return.
Get-ChildItem -LiteralPath $ShimDir -Filter "unsloth.cmd.*.tmp" -File `
-ErrorAction SilentlyContinue | ForEach-Object {
$ownerPid = 0
@@ -5246,15 +4822,11 @@ function Install-UnslothStudio {
}
$content = Get-UnslothCmdShimContent -ShimDir $ShimDir -PythonPath $PythonPath
$desired = (New-Object System.Text.UTF8Encoding($false)).GetBytes($content)
- # Bytes, not ReadAllText: that strips a BOM before comparing and PowerShell's
- # -eq is case insensitive, so a BOM-prefixed file (which cmd.exe reads as part
- # of the first command) would be declared unchanged and left broken forever.
+ # Bytes, not ReadAllText: that strips a BOM and -eq is case insensitive.
if (Test-Path -LiteralPath $shimCmd -PathType Leaf) {
$existing = [System.IO.File]::ReadAllBytes($shimCmd)
if (@(Compare-Object $existing $desired -SyncWindow 0).Count -eq 0) { return }
- # This directory is the installer's own, so the file is replaced either
- # way, but a file that carries neither our marker nor our trampoline was
- # written by something else and its owner deserves to read that it went.
+ # Warn when replacing a file that is not ours.
if (-not (Test-UnslothCmdShimFile -Path $shimCmd)) {
substep "replacing an unrecognised $shimCmd" "Yellow"
}
@@ -5272,10 +4844,8 @@ function Install-UnslothStudio {
}
}
- # Is this bin\unsloth.cmd one we wrote? The name alone is a plausible wrapper for
- # anything built on unsloth, and callers use the answer to decide whether a
- # user-chosen directory may be deleted. Mirrored in scripts/uninstall.ps1
- # (_IsUnslothCmdShim) and studio/setup.ps1.
+ # Ownership check that gates deleting a user-chosen directory. Mirrored in
+ # scripts/uninstall.ps1 (_IsUnslothCmdShim) and studio/setup.ps1.
function Test-UnslothCmdShimFile {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
@@ -5368,11 +4938,8 @@ function Install-UnslothStudio {
if ((Test-Path -LiteralPath $_studioIdFile) -and `
((Get-Item -LiteralPath $_studioIdFile).Length -gt 0)) {
$_studioRootId = ([System.IO.File]::ReadAllText($_studioIdFile)).Trim()
- # Same contract as the backend and the desktop app: 64
- # lowercase hex. -cnotmatch because -notmatch is case
- # insensitive and would take uppercase the backend rejects.
- # Anything else lands in a single-quoted assignment in the
- # generated launcher, so a planted quote would be code.
+ # 64 lowercase hex, as the backend and desktop app require. -cnotmatch (case sensitive);
+ # anything else would be code in the single-quoted launcher assignment.
if ($_studioRootId -cnotmatch '^[0-9a-f]{64}$') {
$_studioRootId = ""
}
@@ -5381,10 +4948,8 @@ function Install-UnslothStudio {
$_idBytes = New-Object byte[] 32
[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($_idBytes)
$_studioRootId = -join ($_idBytes | ForEach-Object { $_.ToString('x2') })
- # Publish no-clobber: the desktop app mints this same id, so
- # -Force could replace one a running backend already reported.
- # Two-arg File.Move throws when the destination exists (the
- # 3-arg overwrite overload is .NET Core only), so we adopt it.
+ # No-clobber: the desktop app mints the same id. Two-arg File.Move throws on an existing
+ # destination, so adopt it.
$_idTmp = $_studioIdFile + ".$PID.tmp"
[System.IO.File]::WriteAllText($_idTmp, $_studioRootId)
try {
@@ -5397,9 +4962,7 @@ function Install-UnslothStudio {
if ($_adoptedRootId -cmatch '^[0-9a-f]{64}$') {
$_studioRootId = $_adoptedRootId
} else {
- # Zero-length or malformed is an interrupted write
- # or a planted value, not an id: replace it with one
- # atomic rename, no unlink.
+ # Malformed is an interrupted write or a planted value: replace atomically.
Move-Item -LiteralPath $_idTmp -Destination $_studioIdFile -Force
}
} finally {
@@ -5656,17 +5219,9 @@ try {
exit 0
"@
- # Write UTF-8 with BOM for reliable decoding by Windows PowerShell 5.1,
- # even when install.ps1 is executed from PowerShell 7.
- #
- # Content-compared first, like the .cmd shim: the launcher is regenerated by
- # every reinstall and by every `unsloth studio update` (--shortcuts-only),
- # and rewriting identical bytes moves its timestamp for no reason. A re-run
- # has to be a true no-op on disk.
+ # UTF-8 with BOM for 5.1. Content-compared first so a re-run is a no-op on disk.
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
- # Bytes including the BOM, not ReadAllText: that decodes and discards the
- # preamble, so a BOM-less launcher written by an older installer would be
- # called unchanged and never gain the BOM 5.1 needs to decode it.
+ # Compare bytes including the BOM, so an older BOM-less launcher gets rewritten.
$desiredLauncher = $utf8Bom.GetPreamble() + $utf8Bom.GetBytes($launcherContent)
$launcherUnchanged = $false
if (Test-Path -LiteralPath $launcherPs1 -PathType Leaf) {
@@ -5682,25 +5237,10 @@ exit 0
if (-not $launcherUnchanged) {
[System.IO.File]::WriteAllBytes($launcherPs1, $desiredLauncher)
}
- # WriteAllBytes replaces the unnamed data stream and leaves any other NTFS stream on
- # an existing file alone, so a launcher that somehow acquired a mark of the web keeps
- # it across the rewrite. The shortcut loads this under RemoteSigned, which refuses a
- # marked unsigned script, so clear the mark on the file we just authored. A no-op on
- # every ordinary install, where the stream was never there.
- #
- # Outside the content check on purpose: a launcher whose bytes already match still
- # has to lose the mark, and clearing an absent stream neither writes nor restamps
- # the file, so an unchanged re-run stays a no-op on disk either way.
- #
- # -Confirm:$false: Unblock-File declares SupportsShouldProcess at the default
- # Medium impact, so a profile setting $ConfirmPreference to Medium or Low would
- # prompt here, even for a launcher that never had the stream. ErrorAction does
- # not suppress a ShouldProcess prompt, and a noninteractive host turns it into
- # an error that skips shortcut setup entirely.
+ # Clear any mark-of-the-web (RemoteSigned refuses marked unsigned scripts), outside the
+ # content check. -Confirm:$false: a profile's $ConfirmPreference would otherwise prompt.
Unblock-File -LiteralPath $launcherPs1 -Confirm:$false -ErrorAction SilentlyContinue
- # No .vbs launcher is written: the .lnk shortcuts point straight at
- # powershell.exe running launch-studio.ps1 with a hidden window (selected
- # below), with no script engine in between.
+ # No .vbs launcher: the .lnk shortcuts run powershell.exe on launch-studio.ps1 hidden.
# tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
# Drop any launch-studio.vbs left by an install that predates that change.
@@ -5776,28 +5316,21 @@ exit 0
return
}
- # Gates the heavy refresh below: on a reinstall that changed nothing, purging
- # caches and killing a shell process is wasted work.
+ # Gates the heavy refresh below.
# tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
$firstInstall = -not (
($desktopLink -and (Test-Path -LiteralPath $desktopLink)) -or
($startMenuLink -and (Test-Path -LiteralPath $startMenuLink))
)
- # Launch transport for the shortcuts: powershell.exe runs launch-studio.ps1
- # with a hidden window, deliberately without a .vbs/WScript.Shell wrapper.
- #
- # RemoteSigned, not Bypass, and install.rs makes the same call for the app's own
- # launch. This launcher is written locally, so RemoteSigned loads it either way.
+ # Shortcuts run powershell.exe on launch-studio.ps1 hidden, without a .vbs wrapper.
+ # RemoteSigned, not Bypass, as install.rs does; a locally written launcher loads either way.
# tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
$powershellForLnk = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
$shortcutTarget = $powershellForLnk
$shortcutArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File `"$launcherPs1`""
- # A launcher on a share is a REMOTE script to PowerShell and RemoteSigned refuses an
- # unsigned one, so a roaming profile would get a shortcut that exits without starting
- # Unsloth. Bypass for that case only, and without the hidden window: a console beats
- # nothing launching. A mapped drive (H:, Z:) is the same share and the same zone, and
- # DriveInfo on the root reports Network for both.
+ # A launcher on a share (UNC or mapped drive) is remote to RemoteSigned, so use Bypass
+ # without the hidden window for that case only.
$launcherIsRemote = $launcherPs1 -like "\\*"
if (-not $launcherIsRemote) {
try {
@@ -5818,11 +5351,7 @@ exit 0
if (-not $linkPath -or [string]::IsNullOrWhiteSpace($linkPath)) { continue }
try {
$shortcut = $wshell.CreateShortcut($linkPath)
- # CreateShortcut returns an existing .lnk populated, so the
- # incumbent's fields are readable before anything is assigned.
- # Save() rewrites even when every field matches, moving the
- # timestamp on a no-op reinstall. IconLocation carries the ",0"
- # index back, so compare against the string we would set.
+ # Save() rewrites even when unchanged, so compare first (IconLocation carries ",0").
$shortcutUnchanged = (Test-Path -LiteralPath $linkPath -PathType Leaf) -and
($shortcut.TargetPath -eq $shortcutTarget) -and
($shortcut.Arguments -eq $shortcutArgs) -and
@@ -5882,31 +5411,18 @@ exit 0
# Regen .lnk + launcher only; used by `unsloth studio update`.
if ($ShortcutsOnly) {
- # `unsloth studio update` reaches the installer only here, and returns before
- # the lock try/finally, so undo the temp redirection on every way out,
- # including the throw below. Under `irm | iex` these variables belong to the
- # caller's own session, so leaving them redirected outlives the install.
+ # Returns before the lock try/finally, so undo the temp redirection on every way out.
try {
if ($TauriMode) { return }
- # The launcher runs the interpreter, so that is what has to be there. Checking
- # unsloth.exe instead would refuse to regenerate shortcuts on exactly the
- # machines that need them, where the console script is present but denied.
+ # Check the interpreter, which the launcher runs, not the possibly denied unsloth.exe.
$ShortcutPython = Join-Path $VenvDir "Scripts\python.exe"
if (-not (Test-Path -LiteralPath $ShortcutPython)) {
Write-StudioLine "[ERROR] managed Python missing at $ShortcutPython; run install.ps1 first." -ForegroundColor Red
# throw (not Exit-InstallFailure) so non-Tauri callers see rc != 0.
throw "managed Python missing"
}
- # `unsloth studio update` reaches the installer only through here, so without
- # this an install predating the .cmd never gets one -- and that population is
- # exactly the one that needs the escape hatch.
- # No-op when the bytes already match, and never fatal.
- # Created, not required: installers older than the shim directory never made
- # one, and those are precisely the installs that reach this branch through
- # `unsloth studio update` and never see the full installer again. Requiring
- # it here left them without the escape hatch forever. Directory creation is
- # idempotent, and a failure to create it must not fail an update, so the
- # write stays inside the same non-fatal helper.
+ # Older installs only reach the installer through `unsloth studio update`, so create the
+ # shim directory and .cmd here too. Idempotent and never fatal.
$ShortcutShimDir = Join-Path $StudioHome "bin"
try {
[System.IO.Directory]::CreateDirectory($ShortcutShimDir) | Out-Null
@@ -5915,11 +5431,8 @@ exit 0
}
if (Test-Path -LiteralPath $ShortcutShimDir -PathType Container) {
Write-UnslothCmdShim -ShimDir $ShortcutShimDir -PythonPath $ShortcutPython
- # An installer older than the shim directory put the venv's Scripts dir on
- # PATH instead, so the .cmd we just wrote would sit somewhere nothing looks.
- # Add-ToUserPath is idempotent and a no-op for every modern install, so this
- # only moves a machine that update is the sole route back into the installer
- # for. Env mode never writes the registry.
+ # Older installers put Scripts on PATH instead; add the shim dir (idempotent). Env mode
+ # never writes the registry.
if ($StudioRedirectMode -ne 'env') {
if (Add-ToUserPath -Directory $ShortcutShimDir -Position 'Prepend') {
substep "added $ShortcutShimDir to PATH"
@@ -5934,13 +5447,9 @@ exit 0
}
# ── Leave Windows system directories before installing ──
- # "Run as administrator" starts in C:\Windows\System32, so a piped web run installs
- # from there and `unsloth studio setup` refuses only after PyTorch has downloaded,
- # then rolls back. Relocating is safe: nothing here reads the caller's directory
- # ($RepoRoot from $PSCommandPath, $StudioHome from the environment), so only
- # --with-llama-cpp-dir needs a rebase first. Not restored at the end, same reason as
- # the PSModulePath fix at the top: the interactive path ends running Unsloth in the
- # foreground, so a finally would not fire until it stops.
+ # "Run as administrator" starts in System32, where setup refuses after the PyTorch
+ # download. Relocating is safe (nothing reads the caller's directory except
+ # --with-llama-cpp-dir, rebased first). Not restored, like the PSModulePath fix.
$SystemRootDir = if ($env:SystemRoot) { $env:SystemRoot } else { "C:\Windows" }
$SystemRootDir = [System.IO.Path]::GetFullPath($SystemRootDir).TrimEnd('\')
# Separator included, or siblings like C:\Windows.old and C:\WindowsStudio match too.
@@ -5964,10 +5473,8 @@ exit 0
$InSystemDir = Test-UnderSystemRoot $CurrentDir
if ($InSystemDir) {
if ($WithLlamaCppDir) {
- # Anchor to the directory the user typed it against, including the partially
- # qualified forms (C:llama.cpp, \llama.cpp). Not [System.IO.Path]::GetFullPath,
- # which resolves against [Environment]::CurrentDirectory, a separate location
- # that Set-Location never updates.
+ # Anchor to the directory the user typed against; GetFullPath uses the .NET current
+ # directory, which Set-Location never updates.
try {
$WithLlamaCppDir =
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($WithLlamaCppDir)
@@ -5992,10 +5499,8 @@ exit 0
continue
}
}
- # $StudioHome came from USERPROFILE far above, so a SYSTEM account would keep
- # installing into C:\Windows\System32\config\systemprofile while we report having
- # escaped. Rebasing it would orphan the install (the runtime resolvers recompute
- # the root from USERPROFILE), so stop instead.
+ # A SYSTEM account's $StudioHome is under System32; rebasing would orphan the install, so
+ # stop.
$StudioHomeFull = ""
try { $StudioHomeFull = [System.IO.Path]::GetFullPath($StudioHome).TrimEnd('\') } catch {}
if ($SafeDir -and (Test-UnderSystemRoot $StudioHomeFull)) {
@@ -6043,12 +5548,7 @@ exit 0
}
# ── Check winget ──
- # winget is only needed to install Python or uv. If both are
- # already on PATH (Windows ARM64 GitHub-hosted runners, manual
- # python.org + Astral uv installs, corporate locked-down hosts
- # without the Store, etc.) the script can proceed without it.
- # We defer the hard failure to the Python / uv install branches
- # below, where winget is actually invoked.
+ # Only needed to install Python or uv, so the hard failure is deferred to those branches.
function Enter-StudioNamedMutex {
param([Parameter(Mandatory = $true)][string]$Name)
$mutex = [System.Threading.Mutex]::new($false, $Name)
@@ -6067,11 +5567,8 @@ exit 0
function Get-StudioPathHash {
param([Parameter(Mandatory = $true)][string]$Path)
- # Unchanged whenever the native resolver answered. When it could not, this
- # hashes the normalized spelling, so two ALIASES of one root (a junction and
- # its target, an 8.3 name and its long form) name different mutexes and do not
- # exclude each other. That needs two installs racing into one directory through
- # different spellings, and beats refusing to install, which is what this did.
+ # Hashes the normalized spelling when the native resolver could not answer, so two aliases
+ # of one root may not exclude each other; better than refusing to install.
$canonical = (Get-StudioFinalPath -Path $Path).ToUpperInvariant()
$bytes = [System.Text.Encoding]::UTF8.GetBytes($canonical)
$sha256 = [System.Security.Cryptography.SHA256]::Create()
@@ -6101,9 +5598,7 @@ exit 0
)) {
return $true
}
- # Different spellings only prove different directories when both resolved
- # exactly; otherwise they may be aliases of one. $null is the caller's
- # "identity unresolved" signal and makes it take both runtime locks.
+ # Different spellings prove different directories only when both resolved exactly.
if (-not $leftInfo.Exact -or -not $rightInfo.Exact) {
if ($script:StudioInstallIsFresh -ne $true) {
Write-StudioLine "[WARN] Could not resolve Unsloth path identity; using the runtime lock." -ForegroundColor Yellow
@@ -6190,11 +5685,8 @@ exit 0
try { $Mutex.ReleaseMutex() } catch {} finally { $Mutex.Dispose() }
}
- # Mutex AND file, because they exclude different things. The mutex is named from a hash of the
- # resolved path, so two spellings of one directory fail to exclude each other whenever the
- # resolver is inexact; a file inside the destination has no such problem, because the
- # filesystem resolves the alias. Both are kept: a released installer only knows the mutex, so
- # dropping it would stop an old run and a new one seeing each other during an upgrade.
+ # Mutex AND file: the mutex misses aliases when the resolver is inexact, the file does not;
+ # released installers only know the mutex.
function Enter-StudioInstallLock {
param([Parameter(Mandatory = $true)][string]$Path)
@@ -6205,13 +5697,8 @@ exit 0
# Race-safe: concurrent creators both succeed, and only one opens the file exclusively
# below. A throw here surfaces as the caller's install-lock error.
$existedBefore = [System.IO.Directory]::Exists($Path)
- # An env-mode root is created thousands of lines above, so the check just above answers
- # yes for every one of them; that site recorded what it found, so prefer its answer for
- # this same directory.
- #
- # One direction only. It may say "I created this root, so treat it as new", never the
- # opposite: a record claiming the root existed cannot be true while the root is absent
- # now, so it is a leftover from an earlier run in the same session.
+ # Prefer the env-mode root's own record of whether it pre-existed; only ever in the
+ # "created" direction.
if ($script:StudioEnvRootPath -and
$script:StudioEnvRootPath.Equals($Path, [System.StringComparison]::OrdinalIgnoreCase) -and
-not $script:StudioEnvRootExisted) {
@@ -6219,38 +5706,23 @@ exit 0
}
$null = [System.IO.Directory]::CreateDirectory($Path)
$lockPath = Join-Path $Path $script:StudioInstallLockFileName
- # A link planted at the lock path is not a lock, it is a way to point our exclusive
- # handle at somebody else's file: File.Open follows it, so the target would be held
- # open with FileShare.None for the whole install even though nothing is written to it.
- # Remove the link itself, never its target, then let the open below create a real
- # file. Get-Item -Force rather than Test-Path, which follows a dangling link and
- # answers false; Write-StudioRootOwnerMarker guards the same hazard the same way.
+ # A link at the lock path would point our exclusive handle at someone else's file: remove
+ # the link itself (checked with Get-Item -Force), never its target.
$existingLock = $null
try {
$existingLock = Get-Item -LiteralPath $lockPath -Force -ErrorAction SilentlyContinue
} catch { $existingLock = $null }
if ($existingLock -and
($existingLock.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
- # A detected link that will NOT go must stop the install, not be shrugged off.
- #
- # Not an empty catch: a link that can be inspected but not deleted would carry on
- # into File.Open, which follows it, and a zero-byte target passes the length check
- # too. The throw reaches the outer handler, which drops the mutex and reports a
- # lock-creation failure rather than a phantom second installer.
+ # A link that will not go stops the install with a lock-creation error.
try {
Remove-Item -LiteralPath $lockPath -Force -ErrorAction Stop
} catch {
throw "A link is planted at the install lock path $lockPath and cannot be removed."
}
}
- # A HARD link carries no reparse attribute, so the check above cannot see it and
- # File.Open follows it. The discriminator is the opened stream's Length: nothing is
- # ever written here, so ours is always zero bytes and a planted alias worth denying
- # access to is not. Read from the handle, which also closes the check-to-open window.
- #
- # At most one repair, and CreateNew rather than OpenOrCreate: the mutex only serialises
- # identical spellings, so if somebody re-created the entry in between, this must fail
- # rather than hand out a second lock.
+ # Hard links carry no reparse attribute: ours is always zero bytes, so check the opened
+ # stream's Length. One repair at most, via CreateNew.
$repaired = $false
while ($true) {
if ($repaired) { $mode = [System.IO.FileMode]::CreateNew }
@@ -6262,13 +5734,8 @@ exit 0
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None)
} catch [System.IO.IOException] {
- # Only a sharing or lock violation means "another installer holds it"; a
- # storage fault reported that way would send the user hunting a second
- # installer that does not exist. HResult's low 16 bits carry the Win32 code: 32
- # ERROR_SHARING_VIOLATION, 33 ERROR_LOCK_VIOLATION. Off Windows .NET implements
- # FileShare with flock and reports errno 11 (EAGAIN) instead, measured rather
- # than assumed. 80, 183 and 17 are how the CreateNew reopen reports losing the
- # race, which means the same thing to the caller.
+ # Only sharing/lock violations (32, 33; EAGAIN 11 off Windows; 80/183/17 for a lost
+ # CreateNew race) mean another installer holds it.
$code = $_.Exception.HResult -band 0xFFFF
$lost = $repaired -and ($code -eq 80 -or $code -eq 183 -or $code -eq 17)
if (-not $lost -and $code -ne 32 -and $code -ne 33 -and $code -ne 11) { throw }
@@ -6276,11 +5743,8 @@ exit 0
Exit-StudioInstallMutex -Mutex $mutex
return $null
}
- # The reparse test above ran on the PATHNAME, so a link can be swapped in before
- # this open, and a zero-byte target slips past the Length test below. Re-read now
- # the handle is held. This narrows the window rather than closing it: closing it
- # needs FILE_FLAG_OPEN_REPARSE_POINT, and removing native imports is the point of
- # this workstream. The residual needs a root another user can already write to.
+ # Re-check after opening: narrows, not closes, the swap window (that needs
+ # FILE_FLAG_OPEN_REPARSE_POINT).
if ($stream.Length -eq 0) {
$entry = $null
try { $entry = Get-Item -LiteralPath $lockPath -Force -ErrorAction Stop } catch { $entry = $null }
@@ -6295,17 +5759,8 @@ exit 0
# A file this run just created cannot be non-empty. Fail loudly, not in a loop.
throw "The install lock file at $lockPath is not empty after being replaced."
}
- # Move the entry ASIDE rather than delete it, and let the reopen create a real file
- # at the freed name.
- #
- # Deleting a planted hard link costs only its own directory entry, which is why it
- # looked safe, but an ORDINARY non-empty file at this name loses its contents
- # merely because somebody started the installer. Refusing instead lets a planted
- # hard link block every install. The discriminator is the link count and .NET does
- # not expose it here, so there is no cheap way to tell them apart. A rename needs
- # no discrimination: the planted link leaves the lock
- # path either way, and the ordinary file keeps its bytes under a name that says
- # what happened to it.
+ # Move the entry ASIDE rather than delete it: an ordinary non-empty file keeps its bytes,
+ # and a planted hard link still leaves the lock path.
$stream.Dispose()
$stream = $null
$displaced = "$lockPath.displaced-" + (Get-Date -Format "yyyyMMddHHmmss") +
@@ -6313,9 +5768,7 @@ exit 0
try {
Move-Item -LiteralPath $lockPath -Destination $displaced -Force -ErrorAction Stop
} catch {
- # Same discrimination and the same codes as the open below: only a sharing or
- # lock violation is a concurrent install. The code is dug out of the exception
- # chain because a cmdlet failure arrives wrapped.
+ # Same codes as the open below; dug out of the wrapped exception.
$mvCode = 0
$mvEx = $_.Exception
while ($mvEx) {
@@ -6331,22 +5784,9 @@ exit 0
}
$repaired = $true
}
- # Residual, stated plainly: a hard link to a genuinely EMPTY file is indistinguishable
- # from our own and is used as the lock. Nothing is written to it, so the only thing
- # denied for the install is access to a zero-byte file.
- # Nothing is written to the handle on purpose: holding it open exclusively IS the
- # lock, and File.Open follows a link, so a planted lock file would have its TARGET
- # truncated merely by starting the installer.
- # The lock is now the first thing that can create the root, so without this marker a
- # run that died before the first real write leaves a root scripts/uninstall.ps1's
- # _IsStudioRoot refuses to remove as somebody else's.
- #
- # Only when this call created the directory: a UNSLOTH_STUDIO_HOME pointed at one the
- # user already had must never be claimed, or uninstall would delete it.
- #
- # Through the helper, not a bare WriteAllText, which follows a planted link just as
- # File.Open does. The helper removes the entry and confirms its absence first, with
- # Get-Item -Force so a dangling link is not mistaken for nothing there.
+ # Nothing is written: holding the handle IS the lock. Mark a root this call created, via
+ # the link-safe helper, so scripts/uninstall.ps1's _IsStudioRoot can remove it; never a
+ # pre-existing UNSLOTH_STUDIO_HOME.
if (-not $existedBefore) {
Write-StudioRootOwnerMarker -Root $Path
}
@@ -6414,13 +5854,8 @@ exit 0
}
}
- # QueryFullProcessImageNameW answers for processes whose MainModule is not
- # readable here: PROCESS_QUERY_LIMITED_INFORMATION is granted where the
- # PROCESS_VM_READ that MainModule needs is refused, and it needs no WMI.
- # Without it a host can find NO running processes and overwrite a venv Unsloth
- # has open, so the ladder still ends at Get-Process and Win32_Process. Every
- # rung reports a real executable image; a command line or working directory
- # mentioning the path is never proof.
+ # QueryFullProcessImageNameW works where MainModule is unreadable; without it a venv in
+ # use could be overwritten. Only real executable images count as proof.
$script:StudioProcessImageTable = $null
# PID -> image path for every visible process, via ctypes in one child, so no type is defined
# in this script. $null leaves the WMI rung exactly as it was.
@@ -6552,12 +5987,8 @@ exit 0
} catch {
throw "Could not resolve managed Unsloth process path '$VenvPath': $($_.Exception.Message)"
}
- # No root-relative fallback here: without the native helper EVERY path is
- # inexact, so it compared path tails across unrelated drives and an ordinary
- # D:\env\python.exe matched a protected C:\env, aborting a legitimate install
- # as "still in use". The alias it was written for, SUBST, is folded in
- # Get-StudioLexicalPath instead. A volume reached by GUID still cannot be
- # matched to the same volume by drive letter without the native resolver.
+ # No root-relative fallback: with every path inexact it matched tails across drives.
+ # SUBST is folded in Get-StudioLexicalPath instead.
# Block only confirmed executable identities: a command line or working
# directory that merely mentions the path is not proof of an open file.
@@ -6677,9 +6108,8 @@ exit 0
}
Write-TauriLog "STEP" "Checking system dependencies"
- # -CommandType Application, as for Resolve-UvExecutable below: winget installs Python AND uv,
- # so a profile "function winget {...}" or "Set-Alias winget ..." would otherwise receive both
- # installs. The resolved path is pinned so the five call sites cannot be re-resolved later.
+ # -CommandType Application so a profile alias or function named winget cannot intercept.
+ # Pinned so later call sites cannot re-resolve.
$script:WingetExe = (
Get-Command winget -CommandType Application -All -ErrorAction SilentlyContinue |
Where-Object { $_.Source } | Select-Object -First 1 -ExpandProperty Source
@@ -6720,9 +6150,7 @@ exit 0
[string]$RecordedTag = $null
)
if ((Get-HostMachineArch) -ne "arm64") { return $false }
- # The interpreter may be gone: a reinstall moves the environment to its rollback path
- # BEFORE the x64 Python is chosen, so probing $VenvPython here would answer "no
- # mismatch" for every existing install. $RecordedTag is the tag read before that move.
+ # Use $RecordedTag: the venv may already have moved aside for rollback.
$tag = $null
if (Test-Path -LiteralPath $VenvPython -PathType Leaf) {
$tag = Get-PythonPlatformTag $VenvPython
@@ -6816,10 +6244,7 @@ exit 0
# does with UV_OFFLINE_MIN_VERSION: an offline install makes no TLS connections.
$UvOfflineMinVersion = "0.8.16"
- # PowerShell ranks aliases and functions above anything on PATH, so a profile carrying
- # "Set-Alias uv ..." or "function uv {...}" captures every bare uv call here and the version
- # probe reads a good uv as broken. $null when nothing named uv resolves to an executable, so
- # the caller's "not installed yet" branch keeps its meaning.
+ # Profile aliases/functions outrank PATH, so resolve a real executable. $null means none.
function Resolve-UvExecutable {
# @(): a one-element return unrolls to a bare string, and indexing THAT gives its
# first character.
@@ -6828,9 +6253,7 @@ exit 0
return $null
}
- # Every uv this machine offers, in the order the bare token would pick them: alias first,
- # then PATH. A LIST rather than one answer, so the version gate can move past an alias
- # pointing at a stale uv and still find a current one.
+ # Every uv in bare-token order (alias, then PATH), so the version gate can skip a stale one.
function Get-UvExecutableCandidates {
# An ALIAS pointing at a real executable FIRST, because PowerShell resolves aliases
# ahead of PATH. Followed only as far as an Application, returning the resolved path so
@@ -6857,10 +6280,7 @@ exit 0
if (-not $found.Contains($app.Source)) { $found.Add($app.Source) }
}
if ($found.Count -gt 0) { return @($found) }
- # Anything else named uv is a function, a cmdlet, or an alias to one, and handing back
- # the bare token would let a wrapper answering `--version` pass the gate and then
- # receive every install command. An empty list means "not installed yet", so uv gets
- # installed and the gate re-probes.
+ # Never hand back the bare token: a wrapper could pass the gate and receive every command.
return @()
}
@@ -6900,13 +6320,9 @@ exit 0
}
function Get-UvExecutableVerdict {
- # "ok", "failed" or "unknown". Only the binary itself answering non-zero is "failed".
- # A launch that throws or a wait that times out is "unknown", because the probe got no
- # verdict: Start-Process -NoNewWindow with redirected streams does not behave in a
- # Windows container or on the arm64 image the way it does in a desktop session, and
- # treating that as a broken binary turned three clean-machine CI legs into hard install
- # failures. The digest already proved these bytes are astral's pinned release, so no
- # verdict publishes, as the pre-pin code did. Every path says why.
+ # "ok", "failed" or "unknown". Only a non-zero exit is "failed"; a throw or timeout
+ # (seen in Windows containers and on arm64) is no verdict, and the digest already
+ # verified the bytes.
param([string]$Path)
if (-not $Path -or -not (Test-Path -LiteralPath $Path)) { return "failed" }
# Redirected: uv's version line is not part of this installer's output.
@@ -6920,10 +6336,8 @@ exit 0
substep "uv did not answer --version within 20s; installing it unprobed." "Yellow"
return "unknown"
}
- # The timed overload can return before the exit code is cached, which is how
- # arm64 and the Windows containers reported an EMPTY code and had a working uv
- # read as broken. The parameterless wait settles it and returns at once, since
- # the process has already exited. No code at all is still no verdict.
+ # The timed overload can return before the exit code is cached; the parameterless wait
+ # settles it.
try { $proc.WaitForExit() } catch {}
$code = $null
try { $code = $proc.ExitCode } catch {}
@@ -6948,9 +6362,8 @@ exit 0
}
}
- # Fallback for hosts without winget. Same archive, destination and user-PATH
- # prepend as astral's install.ps1, but it fetches a data file with a pinned
- # SHA-256 instead of running remote script text in-process.
+ # Fallback for hosts without winget: same archive and destination as astral's install.ps1,
+ # but a pinned SHA-256 instead of running remote script text.
# tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
# Bumping the version means bumping all 3 hashes, and each Wheel/WheelSha256 from https://pypi.org/pypi/uv/<ver>/json:
# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/uv-<arch>-pc-windows-msvc.zip.sha256
@@ -6994,9 +6407,7 @@ exit 0
$destDir = Join-Path $userHome ".local\bin"
}
- # astral's sources in astral's order, each exclusive when set: a host that sets one
- # usually cannot reach the public endpoints at all, so trying those first would stall.
- # The pin still applies, so a source serving a different build fails the digest.
+ # astral's sources in astral's order, each exclusive when set; the pin still applies.
$uvBase = if ($env:UV_DOWNLOAD_URL) {
@("$($env:UV_DOWNLOAD_URL.TrimEnd('/'))")
} elseif ($env:INSTALLER_DOWNLOAD_URL) {
@@ -7019,9 +6430,7 @@ exit 0
$zip = Join-Path $work $asset
try {
[System.IO.Directory]::CreateDirectory($work) | Out-Null
- # Digest per mirror, not once after the loop: a proxy answering 200 with its own
- # body is a successful download by every measure Invoke-WebRequest has, and checking
- # afterwards spends the only attempt on it.
+ # Digest per mirror: a proxy can answer 200 with its own body.
$downloaded = $false
$script:UvReleaseUnfetched = $true
foreach ($base in $uvBase) {
@@ -7054,19 +6463,15 @@ exit 0
substep "uv.exe was not present in $asset." "Yellow"
return $false
}
- # Run it where it landed, before the destination is touched. A host can have a
- # working older uv while AppLocker, WDAC or endpoint protection refuses this one, and
- # copying first would leave the user with neither. A policy scoped to the destination
- # path is not covered here: the caller's fallback handles it.
+ # Run the staged uv before touching the destination, so a policy-blocked new uv cannot
+ # replace a working old one.
if ((Get-UvExecutableVerdict -Path $stagedUv) -eq "failed") {
substep "the downloaded uv $UvPinnedVersion could not run on this machine." "Yellow"
return $false
}
- # uvw.exe is the windowless launcher and has no console to answer a probe on, so
- # the staged uv.exe above stands for the set: it came from the same verified
- # archive. Copy-Item under Stop so a locked or ACL-denied destination fails the
- # install rather than leaving half a set behind quietly.
+ # uvw.exe has no console to probe; the staged uv.exe stands for the verified set. Copy
+ # under Stop so a half-copied set fails the install.
$ok = $true
foreach ($exe in @("uv.exe", "uvx.exe", "uvw.exe")) {
$src = Join-Path $srcRoot $exe
@@ -7079,8 +6484,7 @@ exit 0
break
}
if ($exe -eq "uv.exe") {
- # Copy-Item is non-terminating under some callers preference, so compare
- # against the archive we verified: a stale uv.exe must not pass for ours.
+ # Compare against the verified archive: a stale uv.exe must not pass for ours.
$copied = $false
try {
$copied = (Test-Path -LiteralPath $dst) -and
@@ -7195,11 +6599,8 @@ exit 0
if (-not $env:UV_NATIVE_TLS) { $env:UV_NATIVE_TLS = "1" }
}
- # Ahead of the cache setup, which is the first thing to write inside the root and returns
- # early for a preset UV_CACHE_DIR. Here rather than inside it: the claim has nothing to do
- # with the uv cache, and that function is lifted out and run on its own by
- # tests/python/test_windows_python_venv_hardening.py, where a call into the rest of the
- # installer is a command-not-found.
+ # Ahead of the cache setup (which returns early for a preset UV_CACHE_DIR) and outside
+ # it: tests/python/test_windows_python_venv_hardening.py runs that function standalone.
Write-StudioRootOwnerMarker -Root $StudioHome
# Never the shared cache: new wheels would land on the profile drive.
if ($script:StudioKeepsTools -and
@@ -7330,15 +6731,12 @@ exit 0
$_Migrated = $false
$script:StudioVenvRollbackDir = $null
$script:StudioVenvRollbackTarget = $VenvDir
- # Set only by the Windows-on-ARM architecture rebuild, which promises the user the old
- # environment survives the run. Every other rollback is deleted once the replacement
- # commits, which is right: it is the same architecture and the same packages.
+ # Only the Windows-on-ARM rebuild preserves its rollback; others are deleted on commit.
$script:StudioVenvRollbackPreserve = $false
# The existing interpreter's platform tag, read before any rollback move takes it away.
$script:PrevVenvPlatformTag = $null
$script:StudioVenvRollbackActive = $false
- # Set only by --no-rollback, so a branch that needs the previous tree can tell
- # "already deleted on purpose" from "not moved aside yet".
+ # Distinguishes "deleted on purpose" (--no-rollback) from "not moved aside yet".
$script:StudioVenvRollbackDiscarded = $false
# Set by the discard itself, so the disk-full remedy describes what happened rather than what
# was requested.
@@ -7369,15 +6767,11 @@ exit 0
}
}
- # uv creates only into a path that is absent or an empty directory. The .NET
- # API counts hidden entries and reads wildcards in the path literally.
+ # uv creates only into an absent or empty directory; the .NET API counts hidden entries.
function Test-DirectoryHasEntries {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
- # Still an existing path to CreateDirectory, which answers
- # ERROR_ALREADY_EXISTS for a file or a link whose target is gone, so
- # uv refuses it too. -PathType Container follows the link and cannot
- # see a dangling one; Get-Item sees the link itself.
+ # Get-Item sees a file or dangling link, which uv also refuses.
return ($null -ne (Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue))
}
try {
@@ -7391,19 +6785,14 @@ exit 0
return $false
}
- # Move-Item into an existing directory nests the source inside it rather than
- # renaming it, and uv then refuses that target as in #9479. A migration branch
- # already means $VenvDir is absent or empty, so clear it: Directory.Delete is
- # non-recursive, and on a reparse point it unlinks without following.
+ # Move-Item into an existing dir nests the source (#9479), so clear the empty target first:
+ # Directory.Delete is non-recursive and unlinks reparse points without following.
function Clear-MigrationTargetDirectory {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return }
$item = Get-Item -LiteralPath $Path -Force
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
- # Not Remove-Item: on Windows PowerShell 5.1 it trips a reparse-tag
- # mismatch on a directory symlink (PowerShell/PowerShell#621).
- # Directory.Delete throws on a link to a file or a dangling one,
- # hence the File.Delete fallback.
+ # Not Remove-Item (5.1 reparse-tag bug, PowerShell#621); File.Delete for file/dangling links.
try { [System.IO.Directory]::Delete($Path) }
catch {
try { [System.IO.File]::Delete($Path) }
@@ -7436,21 +6825,16 @@ exit 0
return $null
}
- # Test-Path follows a link, so a dangling one reads as absent. A rollback holds
- # whatever Test-DirectoryHasEntries called occupied, so ask the path itself.
+ # Test-Path follows links, so a dangling one reads as absent; ask the path itself.
function Test-StudioPathPresent {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
if (-not $Path) { return $false }
return ($null -ne (Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue))
}
- # A wedged torch import or a hanging Intel driver init -- what the XPU probes below exist to
- # detect -- would block a bare `& python -c ...` forever. ProcessStartInfo, not &, so stderr
- # cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import cannot
- # deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure
- # (timeout, crash, exception) reads as .Ok = $false; .Error carries WHICH one, since stderr
- # used to be drained and discarded, leaving a driver-level DLL load error and a missing torch
- # indistinguishable. Defined above the Intel scan: PowerShell binds a function when it runs.
+ # Bounded probe: a wedged torch import or Intel driver init would hang `& python`.
+ # ProcessStartInfo, both streams drained async, kill at the deadline. .Error says which
+ # failure. Defined above the Intel scan (functions bind when they run).
function Invoke-BoundedPythonProbe {
param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
$result = [pscustomobject]@{ Ok = $false; Output = ""; Error = "" }
@@ -7499,28 +6883,18 @@ exit 0
$script:StudioVenvRollbackTarget = $ExistingDir
$script:StudioVenvRollbackActive = $true
$script:StudioVenvRollbackPartial = $false
- # Publish the rollback state before the atomic rename so interruption
- # cannot land after Move-Item but before cleanup knows where the old venv went.
+ # Publish the rollback state before the rename so an interruption cannot lose the old venv.
try {
Move-Item -LiteralPath $ExistingDir -Destination $candidate -ErrorAction Stop
} catch {
- # A collision or ordinary rename failure leaves the original in place.
- # On Windows an open handle inside the tree fails the rename *partway*
- # instead: entries walked before the locked one land at $candidate while
- # the rest stay at $ExistingDir. Reading only $ExistingDir scores that
- # split tree as "the rename never happened" and drops the sole reference
- # to where the other half went, so the caller can neither restore nor
- # report it. Clear the state only when the destination is genuinely
- # absent; when both paths exist keep it active so Restore-StudioVenvRollback
- # can reverse the partial move, and name both locations either way.
+ # An open handle can fail the rename partway, splitting the tree. Clear the state only when
+ # the destination is absent; otherwise keep it so Restore-StudioVenvRollback can merge.
$candidateExists = Test-Path -LiteralPath $candidate
if ((Test-Path -LiteralPath $ExistingDir) -and (-not $candidateExists)) {
$script:StudioVenvRollbackActive = $false
$script:StudioVenvRollbackDir = $null
} elseif ($candidateExists -and (Test-Path -LiteralPath $ExistingDir)) {
- # Flag the split: both paths now hold halves of the *same* previous
- # environment, so restoration must merge them rather than clear the
- # destination first the way the committed-replacement path does.
+ # Both paths hold halves of the same environment: restore must merge.
$script:StudioVenvRollbackPartial = $true
Write-StudioLine "[WARN] Moving the existing environment aside stopped partway -- files are in both places." -ForegroundColor Yellow
Write-StudioLine " still in place: $ExistingDir" -ForegroundColor Yellow
@@ -7530,17 +6904,12 @@ exit 0
}
throw
}
- # --no-rollback / UNSLOTH_INSTALL_NO_ROLLBACK: drop the old environment now instead of at
- # commit, for the disk-constrained cross-volume case. The rename still happens first, so
- # uv never builds into an occupied path. Clearing the state before the delete is what the
- # commit path does too: an interrupt must not restore a half-deleted backup.
+ # --no-rollback: drop the old environment now (disk-constrained case). Rename first so uv
+ # never builds into an occupied path; clear state before deleting.
if ($script:StudioNoRollback) {
$discard = $script:StudioVenvRollbackDir
- # The Intel scan rescues an adapter WMI cannot classify by asking the PREVIOUS
- # environment's torch whether XPU works, and deleting that tree takes the only
- # interpreter that can answer. Opting out must cost disk, never hardware, so the
- # verdict is taken first and the scan reads it. Wrapped, because a probe that cannot
- # run must not cost the rename.
+ # Take the XPU verdict from the old environment's torch before deleting it. Wrapped so a
+ # failed probe cannot cost the rename.
try {
$_discardPy = Join-Path $discard "Scripts\python.exe"
if (Test-Path -LiteralPath $_discardPy -ErrorAction SilentlyContinue) {
@@ -7556,9 +6925,7 @@ exit 0
# Distinct from "never started". Inactive alone cannot tell the two apart, and the
# ARM64 migration below reads it to decide whether it still has a tree to move.
$script:StudioVenvRollbackDiscarded = $true
- # The helper already names the reason it could not delete. What it must not do is
- # report success anyway: a tree left behind by an open handle, a reparse point or a
- # long path frees none of the space this flag exists to free.
+ # Never report success when the tree survived.
if (Remove-StudioVenvTreeWithRetry -Path $discard -Label "previous environment" -LinkAware) {
$script:StudioVenvDiscardSucceeded = $true
substep "previous environment discarded (--no-rollback); a failed install cannot be undone"
@@ -7575,10 +6942,7 @@ exit 0
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Label,
- # Only the --no-rollback discard asks for this. Test-StudioPathPresent is the stricter
- # check and arguably the right default, but making it the default would change what
- # this reports on installs that never passed the flag, and this change is meant to be
- # invisible to them.
+ # Opt-in so installs without --no-rollback report exactly as before.
[switch]$LinkAware
)
$lastError = $null
@@ -7588,10 +6952,7 @@ exit 0
} catch {
$lastError = $_.Exception.Message
}
- # Under -LinkAware, Test-Path is not enough: it follows a directory reparse point, so
- # a dangling one that could not be unlinked reads as absent and this would report a
- # removal that did not happen. The discard acts on that answer by clearing the
- # rollback state and telling the user the environment is gone.
+ # Test-Path follows a dangling reparse point and would report a removal that did not happen.
$stillThere = if ($LinkAware) { Test-StudioPathPresent -Path $Path } else { Test-Path -LiteralPath $Path }
if (-not $stillThere) { return $true }
if ($attempt -lt 3) { Start-Sleep -Milliseconds (250 * $attempt) }
@@ -7659,12 +7020,8 @@ exit 0
Move-Item -LiteralPath $entry.FullName -Destination $entryTarget -ErrorAction Stop
continue
}
- # Same relative path on both sides: the move stopped inside this subtree.
- # Recurse so the halves reunite -- Move-Item -Force would overwrite the
- # half that never moved, which is exactly the data this path protects.
- # A junction on either side is a leaf, not a subtree: recursing through one
- # moves files to wherever it points, outside $StudioHome. Keep both instead.
- # Get-Item both sides: Get-ChildItem has reported Attributes inconsistently.
+ # Same relative path on both sides: recurse to reunite halves instead of overwriting.
+ # Junctions are leaves, never recursed through. Get-Item both sides for reliable Attributes.
$entryItem = Get-Item -LiteralPath $entry.FullName -Force -ErrorAction Stop
$targetItem = Get-Item -LiteralPath $entryTarget -Force -ErrorAction Stop
$linked = (($entryItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) -or
@@ -7704,10 +7061,7 @@ exit 0
}
substep "restoring previous environment after failed install..." "Yellow"
if ($script:StudioVenvRollbackPartial) {
- # $target is not an incomplete *new* environment here -- it is the half of
- # the previous one the interrupted move left behind. Removing it first,
- # the way the branch below does, would delete files that exist nowhere
- # else and "restore" a corrupted venv. Merge the halves instead.
+ # $target is the other half of the previous environment here: merge, never delete.
$merged = $false
try {
$merged = Merge-StudioVenvRollbackTree -Source $backup -Destination $target
@@ -7761,11 +7115,8 @@ exit 0
$script:StudioVenvRollbackPreserve = $false
if (-not (Test-StudioPathPresent -Path $backup)) { return }
if ($preserve) {
- # The architecture rebuild told the user this tree would still be here to copy
- # packages out of, so keep the promise instead of the disk space. Renamed out of
- # the rollback namespace: Remove-StaleStudioVenvRollbacks globs
- # unsloth_studio.rollback.*, and a preserved copy left under that name would be
- # swept by the next run as soon as this PID stopped existing.
+ # Keep the ARM64 tree as promised, renamed out of unsloth_studio.rollback.* so the next
+ # run's sweep does not delete it.
$stamp = Get-Date -Format "yyyyMMddHHmmss"
$kept = Join-Path $StudioHome "unsloth_studio.arm64.$stamp"
$suffix = 0
@@ -7871,14 +7222,9 @@ exit 0
try {
# Replace occupied venvs even when python.exe is missing, as in #9479.
if ((Test-Path -LiteralPath $VenvPython) -or (Test-DirectoryHasEntries -Path $VenvDir)) {
- # why: matching guard to the .venv branch below -- in env-mode
- # $StudioHome is a user-chosen workspace, so refuse to nuke an
- # existing $StudioHome\unsloth_studio that lacks Unsloth sentinels.
- # -PathType Leaf rejects a directory at the sentinel path. Accept the
- # in-VENV ownership marker so partial-install retries are not blocked.
- # The .cmd counts too, and for the same reason the uninstaller accepts it: a
- # policy's quarantine can take the unsigned .exe and leave a root that is still
- # ours. Content-checked, never by name -- this guard gates a recursive delete.
+ # why: matching guard to the .venv branch below. Env mode: refuse to replace an existing
+ # $StudioHome\unsloth_studio without Unsloth sentinels (the in-venv marker and a
+ # content-checked .cmd count). This gates a recursive delete.
if (
$StudioRedirectMode -eq 'env' -and
# Test-StudioPlainFile, not Test-Path: the claim refuses to write a marker through a
@@ -7900,9 +7246,7 @@ exit 0
# 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
- # decision is made after the x64 Python is chosen, which is after that point.
+ # Record the interpreter's arch now, before the move takes $VenvPython away.
if ((Get-HostMachineArch) -eq "arm64" -and (Test-Path -LiteralPath $VenvPython -PathType Leaf)) {
$script:PrevVenvPlatformTag = Get-PythonPlatformTag $VenvPython
}
@@ -7984,49 +7328,30 @@ exit 0
}
}
- # Re-check what is about to be REUSED, not only what was selected: see
- # Test-StudioVenvArchMismatch. Preserved through the ordinary rollback helper, so the
- # previous environment is restored if anything later in this run fails, and cleared from
- # $VenvDir so the branch below creates a fresh one on the x64 interpreter.
+ # Re-check the venv about to be REUSED (Test-StudioVenvArchMismatch); preserved through the
+ # rollback helper and cleared so a fresh x64 venv is built.
if (Test-StudioVenvArchMismatch -VenvPython $VenvPython -SelectedPython $DetectedPython `
-RecordedTag $script:PrevVenvPlatformTag) {
substep "windows on arm: the existing environment runs native ARM64 Python, which cannot" "Yellow"
substep "resolve pyarrow or hf-transfer -- rebuilding it on x64 Python $($DetectedPython.Version)." "Yellow"
- # Stated, not implied: the new environment is built from scratch on a different
- # architecture, so the ARM64 wheels in the old one cannot be carried into it and
- # anything the user pip-installed there is not reinstalled. The old tree is kept
- # under $StudioHome as unsloth_studio.arm64.* rather than deleted with the ordinary
- # rollback, so it can still be read: $script:StudioVenvRollbackPreserve below.
- # Only when there is a tree to keep. Under --no-rollback it is either already gone or
- # about to be, and the arms below say which; printing this as well leaves the user
- # looking for an unsloth_studio.arm64.* that was never written, and told that packages
- # they are about to lose are recoverable.
+ # Tell the user packages are not carried over and the old tree is kept as
+ # unsloth_studio.arm64.*, unless --no-rollback already discarded it.
if (-not ($script:StudioVenvRollbackDiscarded -or $script:StudioNoRollback)) {
substep "the ARM64 environment is kept under $StudioHome as unsloth_studio.arm64.*;" "Yellow"
substep "re-install any extra packages you had added to it, or set UNSLOTH_ALLOW_ARM64_PYTHON=1 to keep it." "Yellow"
}
try {
if ($script:StudioVenvRollbackDiscarded) {
- # --no-rollback already deleted it. There is nothing to move and nothing to
- # keep, and calling Start-StudioVenvRollback here would try to rename a
- # directory that is gone, throw, and take the whole migration out through
- # Exit-InstallFailure -- after the environment had already been destroyed.
+ # --no-rollback already deleted it; a second rollback would throw.
substep "the previous ARM64 environment was discarded by --no-rollback, so there is" "Yellow"
substep "nothing to copy packages out of; the x64 environment is built fresh." "Yellow"
} elseif ($script:StudioVenvRollbackActive) {
- # The ordinary reinstall already moved this environment aside; a second
- # Start-StudioVenvRollback would try to move a directory that is no longer
- # there and throw, taking every architecture migration out through
- # Exit-InstallFailure. The tree is already where this branch wants it, so
- # all that is left is to mark it kept rather than swept.
+ # Already moved aside by the ordinary reinstall; just mark it kept.
$script:StudioVenvRollbackPreserve = $true
} else {
Start-StudioVenvRollback -ExistingDir $VenvDir
if ($script:StudioVenvRollbackDiscarded) {
- # --no-rollback discarded it inside that call, so there is no tree to
- # preserve and setting the flag would mark one that does not exist. The
- # user asked for no old environments kept and that is what they get; say
- # so here, where a moment ago the message promised the opposite.
+ # Discarded under --no-rollback, so there is nothing to preserve.
substep "the previous ARM64 environment was discarded by --no-rollback rather than kept;" "Yellow"
substep "the x64 environment is built fresh, and extra packages are not recoverable." "Yellow"
} else {
@@ -8063,9 +7388,7 @@ exit 0
if ($_woaMigPlatform -ne "win-arm64") {
$_woaMigLabel = if ($_woaMigPlatform) { $_woaMigPlatform } else { "unknown" }
substep "windows on arm: the migrated environment is $_woaMigLabel, not win-arm64 --" "Yellow"
- # Varied, not printed flat: the call below discards under --no-rollback, and telling
- # the user the previous environment is recoverable when it is about to be deleted is
- # the same promise the ARM64 mismatch branch above already had to stop making.
+ # Under --no-rollback do not claim the previous environment is recoverable.
if ($script:StudioNoRollback) {
substep "rebuilding it as ARM64; --no-rollback discards the previous one rather than keeping it." "Yellow"
} else {
@@ -8490,10 +7813,8 @@ exit 0
}
# ── Helper: run amd-smi without triggering a UAC elevation prompt ──
- # amd-smi on Windows auto-elevates to read GPU/APU memory, surfacing a confusing
- # DiskPart UAC prompt mid-install (Unsloth backend amd.py hits the same).
- # __COMPAT_LAYER=RunAsInvoker forces it (and helpers it spawns) to run
- # un-elevated; on failure the WMI name -> gfx fallback still resolves the arch.
+ # __COMPAT_LAYER=RunAsInvoker stops amd-smi auto-elevating; WMI fallback still resolves
+ # the arch.
function Invoke-AmdSmiNoElevate {
param(
[Parameter(Mandatory = $true, Position = 0)][string]$Exe,
@@ -8535,9 +7856,8 @@ exit 0
}
# ── A driverless nvidia-smi exits 0 listing no GPU, so require a "GPU <n>:" row. ──
- # 124 is what Invoke-NvidiaSmiBounded reports when it had to kill the probe. Recorded
- # so the banner below can skip a second query: detection already waited out the full
- # bound on this binary, and asking a hung nvidia-smi again only doubles the stall.
+ # 124 means Invoke-NvidiaSmiBounded killed the probe; recorded so the banner skips a
+ # second query.
$script:NvidiaSmiWedged = $false
# Reset per run: streamed execution shares the caller's script scope.
$script:NvidiaPresenceOnly = $false
@@ -8554,20 +7874,11 @@ exit 0
return ($LASTEXITCODE -eq 0 -and $out -match '(?m)^GPU\s+\d+:')
}
- # Interpreter for the shared inventory's Python rung, deliberately NOT part of the shared
- # region: the two files find Python in different places. Here it is the early read-only
- # ladder from the process-image rung, which never installs anything.
+ # Deliberately NOT in the shared region: the two files find Python differently.
function Get-NvidiaProbePythonExe {
if ("$($env:UNSLOTH_EARLY_PYTHON_PROBE)".Trim() -eq "0") { return "" }
- # The interpreter this run installed comes FIRST, and Get-StudioEarlyPython is the
- # fallback rather than the source.
- #
- # That ladder memoises, including a miss: on a fresh host with no Python of its own it
- # is first called by the install-lock path, finds nothing, and caches $null for the rest
- # of the run. The inventory is not read until much later, by which point this install
- # has created a managed interpreter and then a venv, so asking the cache would decline
- # on exactly the fresh install where nvidia-smi is also most likely to be missing. The
- # host would take CPU wheels while holding a working NVIDIA card.
+ # This run's venv interpreter comes FIRST: Get-StudioEarlyPython may have cached a miss
+ # before the venv existed.
if (-not [string]::IsNullOrWhiteSpace($VenvPython) -and
(Test-Path -LiteralPath $VenvPython -PathType Leaf)) {
return $VenvPython
@@ -8896,46 +8207,16 @@ main()
}
} catch {}
if (-not $HasNvidiaSmi) {
- # Two passes, not one, and the reason is the ordering this change introduces. Listing a
- # GPU is not the same as being able to report a CUDA version: a partially installed or
- # stale utility can answer -L and still print a banner Get-TorchIndexUrl cannot parse,
- # and that path falls back to cu126. Taking the first binary that merely lists a GPU
- # could therefore hand a cu128-capable host cu126 purely because of which directory is
- # searched first. So prefer a candidate that answers BOTH questions, and only settle for
- # one that just lists a GPU if none does.
- #
- # One deadline across the whole loop, not just the per-call one. Each candidate gets its own
- # bounded runner, and on a host with a wedged driver every one of them waits out that bound
- # before failing. The list is longer than it was, so what used to be two stalls could now be
- # ten, and all of it is spent in front of the driver-library fallback that would have answered
- # in milliseconds. The bound is on TIME rather than on the number of candidates because the
- # cost being controlled is time: a machine where every probe answers at once still gets to
- # try them all, and one where they hang stops early.
- #
- # Get-Date rather than a Stopwatch: Constrained Language Mode refuses the method calls, and
- # this runs on hosts that enforce it.
- # Enumerated BEFORE the clock starts. Discovery is Test-Path calls, but on a machine with a
- # filesystem filter driver or slow storage it is not free, and charging it to the probe
- # budget is how a slow disk turns into no GPU.
+ # Prefer a candidate that also prints a parseable CUDA banner, or a stale binary could
+ # pick cu126 on a cu128 host. One time budget across the loop (Get-Date: CLM refuses
+ # Stopwatch). Candidates are enumerated before the clock starts.
$smiCandidates = @(Get-NvidiaSmiCandidatePaths)
- # Two budgets, because "stop early" means two different things here.
- #
- # The soft one applies ONLY once a usable answer is already in hand: there is a working
- # nvidia-smi, and continuing just looks for a better CUDA banner. Giving that up costs at
- # most a wheel family.
- #
- # The hard one is the only thing allowed to end the search with NOTHING found, because that
- # outcome is CPU-only PyTorch on a machine with a GPU. The first version of this had a single
- # budget and broke out of the loop after one slow failure, so a host whose System32 copy is
- # broken and whose legacy NVSMI copy works lost its GPU entirely. That is strictly worse than
- # the stall it was added to prevent.
+ # Two budgets: the soft one only once a usable answer exists; only the hard one may end
+ # with nothing, since that means CPU-only PyTorch on a GPU host.
$probeDeadline = (Get-Date).AddSeconds(30)
$probeHardDeadline = (Get-Date).AddSeconds(60)
$firstListing = $null
- # Captured beside the path, because $script:NvidiaSmiWedged describes the LAST binary probed
- # and the one this loop settles on can be an earlier one. Captured rather than assumed to be
- # false: it is false today because a candidate only becomes $firstListing when its -L probe
- # succeeded, and that is a property of Test-NvidiaSmiHasGpu rather than of this loop.
+ # Captured with the path: $script:NvidiaSmiWedged describes the LAST binary probed.
$firstListingWedged = $false
foreach ($p in $smiCandidates) {
# Only give up early when there is already something to fall back on.
@@ -8949,11 +8230,7 @@ main()
$firstListing = $p
$firstListingWedged = $script:NvidiaSmiWedged
}
- # Rechecked here, not only at the top. The listing probe that just returned can have
- # spent most of its own bound, and the banner probe below has a full bound of its
- # own, so a candidate starting just inside the deadline could add nearly twice the
- # per-probe timeout after it. There is already a usable answer in $firstListing at
- # this point, so stopping costs at most a wheel family.
+ # Rechecked here so a late candidate cannot nearly double the budget.
if ((Get-Date) -gt $probeDeadline) { break }
$banner = Invoke-NvidiaSmiBounded $p
if ($banner -match 'CUDA(?: UMD)? Version:\s+\d+\.\d+') {
@@ -8963,16 +8240,12 @@ main()
}
if (-not $HasNvidiaSmi -and $firstListing) {
$HasNvidiaSmi = $true; $NvidiaSmiExe = $firstListing
- # Restored for the binary actually selected. A later candidate that timed out leaves the
- # flag set for ITS path, and the guard downstream reads the flag to decide whether to ask
- # the selected binary for the name, the compute capability and the driver version. Left
- # alone, a working nvidia-smi would be treated as wedged and all three queries skipped
- # because a different binary elsewhere on the machine hung.
+ # Restore the wedged flag for the selected binary, not the last one probed.
$script:NvidiaSmiWedged = $firstListingWedged
}
}
- # Must stay above its callers: PowerShell does not hoist. WMI can hang and -OperationTimeoutSec
- # is not enforced for local COM, so the query runs out of process with a wall-clock kill.
+ # Must stay above its callers (no hoisting). WMI can hang and the timeout is not enforced
+ # for local COM, so query out of process with a wall-clock kill.
function Invoke-BoundedVideoControllerScan {
param([int]$TimeoutSec = 15)
# Cached even when Ok = $false: that is the hang case, and a retry would hang again.
@@ -9002,8 +8275,8 @@ main()
return $result
}
- # Mirrors install_llama_prebuilt.py's windows_intel_gpu_in_registry(), but as the fallback, not
- # registry-first: stale keys here would install XPU torch on a host with no Arc.
+ # Mirrors windows_intel_gpu_in_registry(), but as a fallback: stale keys could install XPU
+ # torch without an Arc.
function Get-IntelRegistryAdapterNames {
$names = @()
$classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
@@ -9099,9 +8372,8 @@ main()
return $false
}
- # Keeps the promotion additive: a hybrid host already gets AMD or Intel wheels.
- # Must match the Intel route's pattern exactly (asserted by test_nvidia_adapter_presence.ps1); a
- # function, not a $script: variable, since an unset $null pattern matches every string.
+ # Must match the Intel route's pattern exactly (test_nvidia_adapter_presence.ps1); a
+ # function, since an unset $null pattern matches everything.
function Get-XpuCapableNameRegex { return "(?i)Intel.*(Arc|Data Center GPU)" }
function Test-IntelXpuRuntimeProven {
@@ -9287,17 +8559,8 @@ main()
}
} catch {}
}
- # nvidia-smi was already resolved above and never asked which card it found, so the
- # banner said "NVIDIA GPU detected" on every NVIDIA host alike. compute_cap is the
- # counterpart of the gfx arch shown for AMD, and the driver version the counterpart of
- # the HIP SDK line; one query returns all three. Honour the same visible-device index
- # the AMD probes do.
- #
- # A mask of "" or -1 hides every device, so it selects nothing to name. It is also not
- # a UUID, and letting it reach the prefix match below would spend a second probe that
- # can never match and then name row 0 anyway. $HasNvidiaSmi still drives wheel
- # selection here, as it does on main, so only the naming is skipped: the banner keeps
- # the vendor-only wording rather than claiming a card CUDA does not expose.
+ # Name the card in the banner (name, compute_cap, driver in one query), honouring the
+ # visible-device mask. A mask of "" or -1 hides every device: keep vendor-only wording.
$nvMaskHidesAll = $false
if ($null -ne $env:CUDA_VISIBLE_DEVICES) {
$nvMask = ($env:CUDA_VISIBLE_DEVICES -replace '\s', '')
@@ -9305,17 +8568,12 @@ main()
}
if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not $nvMaskHidesAll) {
try {
- # Through the bounded runner, like every other nvidia-smi call here: a
- # wedged driver blocks nvidia-smi indefinitely, and a bare `&` call has
- # nothing to time it out. -StdoutOnly because driver warnings on stderr
- # would corrupt this machine-readable CSV.
+ # Bounded runner; -StdoutOnly so stderr warnings cannot corrupt the CSV.
$nvOut = Invoke-NvidiaSmiBounded $NvidiaSmiExe @('--query-gpu=name,compute_cap,driver_version', '--format=csv,noheader') -StdoutOnly
$nvRows = @($nvOut -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if ($nvRows.Count -gt 0) {
- # nvidia-smi ignores CUDA_VISIBLE_DEVICES, so the mask is resolved against
- # its physical rows here. A non-numeric token is a GPU UUID, or a MIG id
- # (MIG-<GPU-UUID>/<gi>/<ci>) embedding one; NVIDIA allows the UUID to be
- # abbreviated to any unique leading portion, so it is matched on prefix.
+ # nvidia-smi ignores CUDA_VISIBLE_DEVICES. Non-numeric tokens are (possibly abbreviated)
+ # GPU UUIDs or MIG ids, matched by prefix.
$nvIdx = 0
$nvTok = if ($env:CUDA_VISIBLE_DEVICES) { ($env:CUDA_VISIBLE_DEVICES -split ',')[0].Trim() } else { '' }
# True while nothing has IDENTIFIED a device: a plain ordinal.
@@ -9326,9 +8584,7 @@ main()
if ($nvTok -match '^\d+$') {
$nvIdx = [int]$nvTok
} elseif ($nvTok -like 'MIG-*' -and $nvTok -notlike 'MIG-GPU-*') {
- # R470 and later give each MIG instance its OWN opaque UUID, which
- # carries nothing of the parent, so --query-gpu=uuid can never match
- # it. `nvidia-smi -L` nests the instances under their GPU.
+ # R470+ MIG instances have opaque UUIDs; `nvidia-smi -L` nests them under their GPU.
$nvListOut = Invoke-NvidiaSmiBounded $NvidiaSmiExe @('-L') -StdoutOnly
$cur = 0
$nvByOrdinal = $false
@@ -9345,9 +8601,7 @@ main()
$nvUuids = @($nvUuidOut -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$nvByOrdinal = $false
$nvFound = $false
- # NVIDIA accepts an abbreviation only when it is a UNIQUE leading portion, so
- # a prefix matching two cards selects NO device. Collect, do not stop at the
- # first hit, or the banner names one of them.
+ # A prefix matching two cards selects NO device, so collect every match.
$nvMatches = @()
for ($i = 0; $i -lt $nvUuids.Count; $i++) {
if ($nvUuids[$i].StartsWith($nvTok, [System.StringComparison]::OrdinalIgnoreCase)) { $nvMatches += $i }
@@ -9356,15 +8610,9 @@ main()
if (-not $nvFound) { $nvUnresolved = $true }
}
$nvRow = if ($nvIdx -lt $nvRows.Count) { $nvRows[$nvIdx] } else { $nvRows[0] }
- # A numeric entry is a CUDA ordinal, and CUDA's default
- # CUDA_DEVICE_ORDER=FASTEST_FIRST puts the fastest card at 0 and leaves the
- # rest unspecified, while nvidia-smi always lists in PCI order. So an ordinal
- # identifies an nvidia-smi row only when the order is pinned to PCI_BUS_ID, or
- # when the cards are interchangeable and every row gives the same answer
- # anyway. Compared on name and compute_cap, not the driver, which is host-wide.
- # CUDA stops enumerating at the first invalid index, so an ordinal past the last
- # row exposes NO device. The row pick below clamps to 0 so the driver still
- # reads, but row 0 is not the selected card -- nothing is.
+ # CUDA's default FASTEST_FIRST order differs from nvidia-smi's PCI order, so an ordinal
+ # names a row only under PCI_BUS_ID or when all rows agree. An ordinal past the last row
+ # exposes no device.
if ($nvByOrdinal -and $nvIdx -ge $nvRows.Count) { $nvUnresolved = $true }
$nvAmbiguous = $nvUnresolved
if ($nvByOrdinal -and -not $nvAmbiguous) {
@@ -9403,9 +8651,7 @@ main()
$HasROCm = $false
$HipSdkInstalled = $false # HIP SDK binary found (independent of device accessibility)
$ROCmGpuLabel = $null
- # Marketing name on its own ("AMD Radeon RX 9060 XT"), never decorated. Kept apart from
- # $ROCmGpuLabel because that one doubles as the input to the name -> arch tables below;
- # this one only ever reaches the banner.
+ # Banner-only name, kept apart from $ROCmGpuLabel, which feeds the arch tables.
$ROCmGpuName = $null
$ROCmVersion = $null
$ROCmGfxArch = $null
@@ -9484,18 +8730,10 @@ main()
# Once the arch is printed, keep the ROCm wheel path.
$HasROCm = $true
$_hipAllArches = @([regex]::Matches($hipOut, "(?im)^\s*gcnArchName\s*:\s*(\S+)") | ForEach-Object { ($_.Groups[1].Value -split ':')[0].Trim().ToLower() })
- # hipinfo prints "Name:" per device alongside gcnArchName. Anchored so
- # gcnArchName cannot match. Only trusted when the two lists line up, so a
- # format change can mislabel nothing -- the arch (which picks the wheel)
- # never reads this.
+ # Names are trusted only when they line up with the arch list; the arch never reads them.
$_hipAllNames = @([regex]::Matches($hipOut, "(?im)^\s*Name\s*:\s*(.+?)\s*$") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_hipAllArches.Count -gt 0) {
- # Entry 0, NOT the visible-device token, and the same choice
- # studio/setup.ps1 already makes: hipinfo is itself a HIP
- # application, so HIP/ROCR_VISIBLE_DEVICES has already filtered
- # its output and renumbered the survivors from 0. Indexing that
- # by the physical token applies the mask twice and lands on the
- # wrong card, which the banner now shows by name.
+ # Entry 0, as setup.ps1 does: hipinfo already applied HIP/ROCR_VISIBLE_DEVICES.
$ROCmGfxArch = $_hipAllArches[0]
$ROCmGpuLabel = "AMD ROCm ($ROCmGfxArch)"
if ($_hipAllNames.Count -eq $_hipAllArches.Count) {
@@ -9608,18 +8846,14 @@ main()
$wmiAmdNames = @($usePeers | ForEach-Object { $_.Name })
} catch {}
}
- # GPU name -> gfx arch for AMD generations no ROCm wheel covers: Polaris 10/20/30
- # (unslothai#8529). Kept apart from $nameArchTable on purpose: it only WORDS a
- # message, never selects a wheel index. The (?!0) guards stop "RX 570" swallowing
- # an "RX 5700"; Polaris 11/12 (RX 460/550/560, a different die) is left out.
+ # Name -> gfx for generations no ROCm wheel covers (Polaris, unslothai#8529). Wording
+ # only, never wheel selection. (?!0) stops "RX 570" matching "RX 5700".
$unsupportedNameArchTable = @(
@{ P = "RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100"; A = "gfx803" } # Polaris 10/20/30
)
# ── Arch resolution: env-var override → name inference ──────────────
- # Runs even when the probe can't confirm a runtime ($HasROCm false): the
- # WMI-name gfx arch drives both ROCm llama.cpp and torch. repo.amd.com
- # wheels bundle their own runtime (no HIP SDK), so a mapped arch installs
- # ROCm torch directly below -- no wasted CPU base.
+ # Runs even without a confirmed runtime: repo.amd.com wheels bundle their own runtime,
+ # so a mapped arch installs ROCm torch directly.
if (-not $ROCmGfxArch) {
# 1. Manual override: set UNSLOTH_ROCM_GFX_ARCH=gfx1151 before running.
if ($env:UNSLOTH_ROCM_GFX_ARCH) {
@@ -9654,27 +8888,17 @@ main()
break
}
}
- # 3. Still nothing: the card may be a generation ROCm never covered rather
- # than one we failed to recognise (unslothai#8529). Reporting only --
- # $ROCmGfxArch stays null, so CPU fallback is reached by the same path.
- # Gated on NO adapter being covered: $wmiGpu takes index 0, so on a host
- # pairing an RX 5700 with an RX 7900 the label is the 5700 and the "no
- # SDK or override can help" wording below would be false (masking to the
- # 7900 and setting gfx1100 installs). Such a host keeps the arch-unknown
- # arm, which says exactly that. studio/setup.ps1 already scores every
- # adapter before it reaches its own lookup.
+ # 3. Still nothing: the card may be a generation ROCm never covered (unslothai#8529).
+ # Reporting only; gated on NO adapter being covered, since $wmiGpu is adapter 0 and a mixed host
+ # (RX 5700 + RX 7900) would get false "nothing can help" wording. setup.ps1 scores every adapter.
if (-not $ROCmGfxArch) {
- # HIP/ROCR only: CUDA_VISIBLE_DEVICES masks NVIDIA devices and says
- # nothing about which Radeon was chosen.
+ # HIP/ROCR only: CUDA_VISIBLE_DEVICES masks NVIDIA devices, not Radeons.
$unsupMasked = @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES) |
Where-Object { $null -ne $_ }
$coveredPeer = $false
if ($unsupMasked) {
- # A masked-out peer cannot answer for the card the user named, but the
- # label is only that card when there is nothing else to select: both
- # sources above keep adapter 0, so HIP_VISIBLE_DEVICES=1 beside a
- # supported peer would blame the wrong GPU. Stay quiet, rather than
- # guess an order Win32_VideoController does not promise matches HIP's.
+ # Both sources keep adapter 0, so a mask beside a supported peer would blame the wrong GPU;
+ # stay quiet rather than assume WMI order matches HIP's.
$coveredPeer = ($wmiAmdNames.Count -gt 1)
} else {
foreach ($peerName in $wmiAmdNames) {
@@ -9695,7 +8919,7 @@ main()
}
}
}
- # Run whenever the HIP SDK is present: hipconfig --version works without a ROCm device.
+ # hipconfig --version works without a ROCm device.
if ($HasROCm -or $HipSdkInstalled) {
$hipConfigExe = Get-Command hipconfig -ErrorAction SilentlyContinue
if (-not $hipConfigExe) {
@@ -9745,10 +8969,8 @@ main()
$drvDate = $null
try {
if ($amd.DriverDate -is [datetime]) {
- # Get-CimInstance returns DriverDate already parsed.
$drvDate = $amd.DriverDate
} elseif ($amd.DriverDate) {
- # Get-WmiObject style WMI datetime string.
$drvDate = [Management.ManagementDateTimeConverter]::ToDateTime([string]$amd.DriverDate)
}
} catch {}
@@ -9757,7 +8979,7 @@ main()
substep " Your current driver predates it; native Windows GPU is unaffected. Get it from AMD:" "Cyan"
substep " https://www.amd.com/en/resources/support-articles/release-notes/RN-RAD-WIN-26-2-2.html" "Cyan"
substep " Then reboot and run this installer inside an Ubuntu-24.04 WSL distro." "Cyan"
- # wsl.exe absent means WSL is not installed; point at the command that provisions it.
+ # No wsl.exe: point at the command that provisions WSL.
$hasWsl = $false
try { $hasWsl = [bool](Get-Command wsl.exe -ErrorAction SilentlyContinue) } catch {}
if (-not $hasWsl) {
@@ -9768,8 +8990,7 @@ main()
}
# ── AMD gfx arch → AMD pip index family (repo.amd.com/rocm/whl/<family>) ──
- # Hoisted above the Intel scan, which needs it: an arch missing here gets CPU torch, so it
- # must not outrank a usable Arc card. The AMD reroute below consumes it too.
+ # Hoisted above the Intel scan: an unmapped arch gets CPU torch and must not outrank a usable Arc.
$archFamilyMap = @{
"gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4
"gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)
@@ -9782,8 +9003,8 @@ main()
"gfx1030" = "gfx103X-all"
"gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100
}
- # RDNA arches route to AMD's multi-arch index, one pinned tag (unslothai#11815, #11614, #11814).
- # gfx1033 (miscomputes) and CDNA stay on the family map. In sync with _WINDOWS_MULTIARCH_GFX in studio/install_python_stack.py.
+ # RDNA arches use AMD's multi-arch index (unslothai#11815, #11614, #11814); gfx1033 (miscomputes)
+ # and CDNA stay per-family. In sync with _WINDOWS_MULTIARCH_GFX in studio/install_python_stack.py.
$multiArchGfx = @(
"gfx1010", "gfx1011", "gfx1012", # RDNA 1
"gfx1030", "gfx1031", "gfx1032", "gfx1034", "gfx1035", "gfx1036", # RDNA 2, gfx1033 stays per-family
@@ -9797,37 +9018,25 @@ main()
$MultiArchTorchVersion = "2.11.0"
$MultiArchTorchvisionVersion = "0.26.0"
$MultiArchTorchaudioVersion = "2.11.0"
- # "AMD gets GPU wheels here", NOT "an AMD GPU is present": $HasROCm / $ROCmGfxArch are
- # true on unmapped arches too, and those install CPU torch.
+ # "AMD gets GPU wheels here", not "AMD GPU present": unmapped arches install CPU torch.
$AmdHasGpuWheels = [bool]($ROCmGfxArch -and ($archFamilyMap.ContainsKey($ROCmGfxArch) -or $multiArchGfx -contains $ROCmGfxArch))
# ── Intel GPU detection (Arc / Data Center GPU Max / Flex) ──
- # Runs BEFORE the report chain, not inside its final else: a WMI-named-only AMD adapter
- # would take that chain and hide a discrete Arc card. $HasIntelGpu is "an Intel adapter is
- # present"; $script:IsIntelXpu is "XPU wheels suit it" -- only Arc / Data Center parts
- # qualify, UHD / HD / Iris Xe do not.
+ # Before the report chain: a WMI-named-only AMD adapter would otherwise hide a discrete Arc.
+ # $script:IsIntelXpu = XPU wheels suit it (Arc / Data Center only, not UHD / Iris Xe).
$HasIntelGpu = $false
$IntelGpuLabel = $null
- # Reset every invocation: under a piped web run $script: is the caller's session scope, so a
- # second run would inherit a stale $true and reroute a now-NVIDIA host to the xpu index.
+ # Reset each run: under `irm | iex` $script: is the caller's session and could carry a stale $true.
$script:IsIntelXpu = $false
- # $AmdHasGpuWheels keeps a wheel-served AMD host out of the XPU reroute below; an AMD host
- # with no wheels is heading for CPU torch, so a neighbouring Arc card wins.
+ # A wheel-served AMD host skips the XPU reroute; one headed for CPU torch lets Arc win.
if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {
try {
- # Bounded, registry as the fallback when WMI does not answer; same match either way.
$_gpuScan = Invoke-BoundedVideoControllerScan
- # @() wraps the WHOLE if, not each branch: a one-element array unrolls on its way
- # out, making $_gpuNames a String on a single-adapter host and turning the += below
- # into string concatenation.
+ # @() wraps the WHOLE if: a one-element array unrolls to a String and += would concatenate.
$_gpuNames = @(if ($_gpuScan.Ok) { $_gpuScan.Names } else { Get-IntelRegistryAdapterNames })
- # One definition for both the reconciliation gate and the classification below.
$_xpuNameRe = "(?i)Intel.*(Arc|Data Center GPU)"
- # On non-English Windows the WMI name carries no ASCII "Intel" for the
- # classification below. The registry helper resolves the PCI vendor id, so use it to
- # RE-LABEL an adapter WMI already reported, never to add one (an unmatched entry is a
- # driver record outliving its card). Gated on the absence of an XPU match, not of any
- # Intel name: a hybrid laptop reports "Intel UHD" next to a localized Arc.
+ # Non-English Windows names carry no ASCII "Intel": use the registry's PCI vendor id to RE-LABEL
+ # a WMI-reported adapter, never add one. Gated on no XPU match (hybrid: "Intel UHD" + localized Arc).
if ($_gpuScan.Ok -and -not ($_gpuNames | Where-Object { $_ -match $_xpuNameRe })) {
foreach ($_reg in @(Get-IntelRegistryAdapterNames)) {
foreach ($_wmiName in $_gpuNames) {
@@ -9843,15 +9052,9 @@ main()
if ($xpuGpu) { $script:IsIntelXpu = $true }
}
} catch {}
- # A migrated env's torch can only CONFIRM the match, never veto it: an unavailable
- # runtime means a stale driver, not unsuitable hardware, and the /cpu fallback could not
- # displace the installed +xpu wheel anyway (PEP 440 ignores the local label). Bounded,
- # and a timeout reads as "no XPU" -- the WMI verdict stands.
- # A rerun has already moved the old venv to $script:StudioVenvRollbackDir and put an
- # empty one in its place, so probing $VenvPython would ask an interpreter with no torch.
- # Ask the preserved environment instead -- that is the migrated runtime this rescues.
- # --no-rollback deleted that environment, so the answer was taken before it went. Same
- # verdict, same effect: opting out of the rollback copy must not narrow the device set.
+ # A migrated env's torch can only CONFIRM the match: an unavailable runtime means a stale driver,
+ # and /cpu cannot displace an installed +xpu wheel anyway. A rerun already moved the old venv aside
+ # (or --no-rollback deleted it), so ask the preserved environment's verdict, not $VenvPython.
if ($script:StudioPreservedXpuVerdict) {
$HasIntelGpu = $true
$script:IsIntelXpu = $true
@@ -9872,19 +9075,14 @@ main()
}
}
- # One banner string for the AMD arms below. The arch alone ("AMD ROCm (gfx1200)") named a
- # target nobody shopping for a GPU recognises, while every probe above already had the
- # marketing name in hand and threw it away; the backend then prints it at startup, so the
- # installer was the only place it went missing.
+ # Banner includes the marketing name: the bare arch ("gfx1200") means nothing to most users.
$ROCmGpuDisplay =
if ($ROCmGpuName -and $ROCmGfxArch) { "$ROCmGpuName ($ROCmGfxArch)" }
elseif ($ROCmGpuName) { $ROCmGpuName }
elseif ($ROCmGfxArch) { "AMD ROCm ($ROCmGfxArch)" }
else { $ROCmGpuLabel }
- # Same shape for every vendor: the device on the step line, its compute target in
- # parentheses, the runtime below. Intel has no counterpart to gfx1200 / sm_89 that any
- # probe here already resolves, so it gets the name alone rather than an invented one.
+ # Same shape per vendor: device, compute target in parentheses. Intel gets the name alone.
$NvidiaGpuDisplay =
if ($NvidiaGpuName -and $NvidiaSmArch) { "$NvidiaGpuName ($NvidiaSmArch)" }
elseif ($NvidiaGpuName) { $NvidiaGpuName }
@@ -9895,23 +9093,17 @@ main()
step "gpu" $NvidiaGpuDisplay
if ($NvidiaDriverVersion) { substep "Driver: $NvidiaDriverVersion" }
} elseif ($script:IsIntelXpu) {
- # Ranks above every AMD branch: only true when AMD gets no GPU wheel ($AmdHasGpuWheels
- # gates the scan above), so those branches would all end on CPU.
+ # Above every AMD branch: true only when AMD gets no GPU wheel, so those would end on CPU.
step "gpu" $IntelGpuDisplay "Green"
- # The reroute below prints the index: only it knows the mirror URL and any pin.
} elseif ($HasROCm -and -not $ROCmUnsupportedGfxArch) {
- # Guarded like the HIP SDK arm below: amd-smi can report a GPU with no gfx token
- # and only a market name, setting $HasROCm without an arch. Calling that card
- # "AMD ROCm" contradicts the wheel note this run also prints.
+ # amd-smi can set $HasROCm with only a market name and no gfx arch.
step "gpu" $ROCmGpuDisplay
$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }
substep "HIP SDK: $hipSdkPath"
if ($ROCmVersionFull) { substep "hipconfig: $ROCmVersionFull" }
} elseif ($HipSdkInstalled -and $ROCmGpuLabel -and -not $ROCmUnsupportedGfxArch) {
- # HIP SDK installed but ROCm can't see the device (driver issue, not SDK issue).
- # Excludes cards already known to be out of scope: the #8529 reporters installed
- # the HIP SDK BECAUSE this arm said to, so unguarded it hides the arm below from
- # exactly the users it is for.
+ # HIP SDK present but ROCm cannot see the device. Excludes known out-of-scope cards (#8529),
+ # whose owners installed the SDK because this arm told them to.
$sdkVer = if ($ROCmVersionFull) { " (HIP $ROCmVersionFull)" } else { "" }
step "gpu" "AMD GPU detected -- not ROCm-accessible$sdkVer" "Yellow"
substep "Detected: $ROCmGpuLabel" "Yellow"
@@ -9920,8 +9112,7 @@ main()
substep " Ensure the ROCm compute driver is installed alongside the display driver:" "Yellow"
substep " https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" "Yellow"
} elseif ($ROCmGfxArch) {
- # Known arch: Unsloth setup installs AMD's bundled-runtime ROCm PyTorch wheels
- # (repo.amd.com), which ship their own runtime -- HIP SDK optional.
+ # Known arch: AMD's ROCm wheels bundle their runtime, so the HIP SDK is optional.
step "gpu" $ROCmGpuDisplay "Cyan"
substep "Detected: $ROCmGpuLabel" "Cyan"
substep "GPU PyTorch uses AMD's bundled-runtime ROCm wheels -- HIP SDK not required (optional)." "Cyan"
@@ -9961,7 +9152,6 @@ main()
if ($HasIntelGpu) { substep "Detected: $IntelGpuLabel (not XPU-capable)" "Yellow" }
substep "Training and GPU inference require an NVIDIA, AMD ROCm, or Intel Arc GPU." "Yellow"
}
- # On an AMD GPU (no NVIDIA), surface the optional WSL-ROCm driver hint.
if (-not $HasNvidiaSmi -and ($ROCmGfxArch -or $ROCmGpuLabel)) { Show-AmdWslDriverHint }
# Trim the URL PATH only: a whole-URL TrimEnd corrupts a token ending in "/".
@@ -9975,18 +9165,15 @@ main()
return $value.Substring(0, $idx).TrimEnd('/') + $value.Substring($idx)
}
- # Index leaf (cpu / cu128 / xpu / gfx1201), ?query and #fragment stripped so a
- # token-authenticated mirror still classifies by family.
+ # Index leaf (cpu / cu128 / xpu / gfx1201), ?query/#fragment stripped for token mirrors.
function Get-TorchIndexLeafName {
param([string]$Url)
if ([string]::IsNullOrWhiteSpace($Url)) { return "" }
return ((($Url -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1]).ToLowerInvariant()
}
- # Classify the physical NVIDIA inventory for a cu126 fallback: "cu126" when it
- # covers every GPU, "uncovered" for an incompatible mix, empty when no fallback is
- # needed or the inventory is unreadable. CUDA_VISIBLE_DEVICES is ignored because
- # the wheel must support the host. Mirrors _nvidia_cu126_verdict in install.sh.
+ # "cu126" when cu126 covers every physical GPU, "uncovered" for an incompatible mix, empty
+ # when unneeded/unreadable. Ignores CUDA_VISIBLE_DEVICES. Mirrors _nvidia_cu126_verdict in install.sh.
function Get-NvidiaCu126Verdict {
# Floor is per-release, not fixed: only 2.11 dropped sm_70 from cu128.
param([string]$SmiExe, [int]$LegacyFloorSm = 75, [string[]]$ComputeCaps = @())
@@ -10032,17 +9219,15 @@ main()
}
# ── Choose the correct PyTorch index URL based on driver CUDA version ──
- # Mirrors Get-PytorchCudaTag in setup.ps1.
function Get-TorchIndexUrl {
$baseUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/') } else { "https://download.pytorch.org/whl" }
- # An explicit pin skips ALL GPU probing. Matches install.sh / install_python_stack.py.
+ # An explicit pin skips ALL GPU probing, as in install.sh / install_python_stack.py.
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL)) {
return (Trim-IndexPathSlashes $env:UNSLOTH_TORCH_INDEX_URL)
}
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_FAMILY)) {
return "$baseUrl/$($env:UNSLOTH_TORCH_INDEX_FAMILY.Trim().Trim('/'))"
}
- # The native win_arm64 CUDA index was probed and paired up front; nothing below it applies.
if ($script:WoaNativeCudaTorch -and $script:WoaTorchIndexUrl) {
return $script:WoaTorchIndexUrl
}
@@ -10077,7 +9262,6 @@ main()
}
} elseif ($null -ne $script:NvidiaPresenceDriverRelease -and
$script:NvidiaPresenceDriverRelease -lt 450) {
- # Pre-R450: no offered CUDA wheel can run.
substep "an NVIDIA GPU is present but its driver ($script:NvidiaPresenceDriverRelease series) predates R450 and carries no usable CUDA runtime; installing CPU wheels. Update the NVIDIA driver and re-run to get CUDA" "Yellow"
return "$baseUrl/cpu"
} else {
@@ -10104,8 +9288,7 @@ main()
}
# ── Torch flavor helpers (to repair a stale CPU / wrong-CUDA wheel) ──
- # torch.__version__ -> flavor tag (cuXXX / rocm / cpu); untagged wheel = cpu,
- # matching setup.ps1's stale-venv parse.
+ # Untagged wheel = cpu, matching setup.ps1's stale-venv parse.
function ConvertTo-TorchFlavorTag {
param([string]$TorchVersion)
if (-not $TorchVersion) { return $null }
@@ -10120,7 +9303,7 @@ main()
param([string]$TorchIndexUrl, [string]$ROCmIndexUrl)
if (-not [string]::IsNullOrWhiteSpace($ROCmIndexUrl)) { return 'rocm' }
if ([string]::IsNullOrWhiteSpace($TorchIndexUrl)) { return $null }
- # Drop query/fragment first so .../cu128?token=x classifies as cu128 (else it reinstalls every run).
+ # Drop query/fragment first, else .../cu128?token=x reinstalls every run.
$leaf = (($TorchIndexUrl -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1].ToLowerInvariant()
if ($leaf -match '^cu\d+$') { return $leaf }
if ($leaf -eq 'cpu') { return 'cpu' }
@@ -10131,8 +9314,7 @@ main()
return $null
}
- # sysconfig platform of $PythonExe's venv, lowercased ("" when it cannot be asked). Windows
- # on ARM has no torchaudio wheel on any index, so every XPU spec list is built from this.
+ # Windows on ARM has no torchaudio wheel, so XPU spec lists key off the venv platform.
function Get-VenvPlatformTag {
param([string]$PythonExe)
if (-not $PythonExe) { return "" }
@@ -10141,8 +9323,7 @@ main()
} catch { return "" }
}
- # The XPU trio for $Platform: floor 2.6 (unsloth/models/_utils.py raises at import for an
- # XPU device below it) and no torchaudio on win-arm64.
+ # XPU floor 2.6: unsloth/models/_utils.py raises at import below it.
function Get-XpuTorchSpecs {
param([string]$Platform)
$specs = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0")
@@ -10150,8 +9331,7 @@ main()
return $specs + @("torchaudio>=2.6,<2.11.0")
}
- # Installed torch flavor tag in $PythonExe's venv, or $null if absent. Bounded, so a wedged
- # "import torch" cannot stall the flavor repair.
+ # Bounded so a wedged "import torch" cannot stall the flavor repair.
function Get-InstalledTorchTag {
param([string]$PythonExe)
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
@@ -10162,10 +9342,7 @@ main()
return ConvertTo-TorchFlavorTag $torchVer
}
- # Full installed torch version in $PythonExe's venv ("2.10.0+cu130"), or $null. Separate
- # from Get-InstalledTorchTag because the xFormers pin below needs the RELEASE as well as
- # the flavor: xFormers publishes one wheel per exact torch patch (2.9.0 -> 0.0.33.post1,
- # 2.9.1 -> 0.0.33.post2, 2.10.0 -> 0.0.34), not per minor.
+ # Full version: xFormers publishes one wheel per exact torch patch, not per minor.
function Get-InstalledTorchVersion {
param([string]$PythonExe)
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
@@ -10177,72 +9354,47 @@ main()
}
# ── xFormers must match the torch BUILD, not just the torch version ──
- # xformers/_C.pyd is linked against one exact (torch, CUDA) pair. Loaded beside any
- # other pair torch.ops.load_library raises, and xformers/_cpp_lib.py turns that into a
- # log warning rather than an error -- so the import "succeeds" and memory-efficient
- # attention, SwiGLU and the sparse ops are all silently gone. PyPI publishes only the
- # CUDA-12.8 flavour, which is why a cu130 install that lets pip resolve xformers ends up
- # reporting "xFormers was built for PyTorch 2.10.0+cu128 (you have 2.10.0+cu130)".
- #
- # Resolve from the same index the torch install used, so UNSLOTH_TORCH_INDEX_URL /
- # UNSLOTH_TORCH_INDEX_FAMILY / UNSLOTH_PYTORCH_MIRROR keep working unchanged. Every row
- # below was HEAD-verified live on download.pytorch.org and its xformers/cpp_lib.json read
- # back, e.g. cu130/xformers-0.0.34 reports {"torch": "2.10.0+cu130"}. Keep in step with
- # _XFORMERS_WHEEL_VERSIONS in studio/backend/utils/wheel_utils.py and the matrix in
- # tests/python/test_windows_xformers_wheel_match.py.
- #
- # Deliberately NOT a floor-and-let-pip-pick: the cu130 index also serves
- # xformers-0.0.35, whose extension is built for torch 2.10.0 while its metadata only
- # asks for torch>=2.10, so a resolver is free to pair it with a torch it cannot load.
- #
- # torch 2.7.0 (xFormers 0.0.30) is deliberately absent: it predates the stable-ABI
- # switch, publishes one wheel per interpreter and stops at cp312, and this installer
- # defaults to Python 3.13 -- so the row would resolve to a wheel that does not exist.
+ # _C.pyd links one exact (torch, CUDA) pair; a mismatch only logs a warning and silently drops
+ # memory-efficient attention. PyPI ships only cu128, so resolve from the torch index. Rows were
+ # verified live on download.pytorch.org; keep in step with _XFORMERS_WHEEL_VERSIONS in
+ # studio/backend/utils/wheel_utils.py and tests/python/test_windows_xformers_wheel_match.py.
+ # Not a floor: cu130 serves 0.0.35 built for 2.10.0 but declaring torch>=2.10. torch 2.7.0
+ # (0.0.30) is absent: its per-interpreter wheels stop at cp312 and we default to Python 3.13.
$script:XformersWheelVersions = @{
"2.7.1" = @{ "cu126" = "0.0.31.post1"; "cu128" = "0.0.31.post1" }
"2.8.0" = @{ "cu126" = "0.0.32.post2"; "cu128" = "0.0.32.post2"; "cu129" = "0.0.32.post2" }
"2.9.0" = @{ "cu126" = "0.0.33.post1"; "cu128" = "0.0.33.post1"; "cu130" = "0.0.33.post1" }
"2.9.1" = @{ "cu126" = "0.0.33.post2"; "cu128" = "0.0.33.post2"; "cu130" = "0.0.33.post2" }
"2.10.0" = @{ "cu126" = "0.0.34"; "cu128" = "0.0.34"; "cu130" = "0.0.34" }
- # Stable-ABI era: 0.0.35 targets torch 2.10+ and upstream guarantees it works on
- # any later release, so one row per torch covers 2.11 onward with the same wheel.
+ # Stable-ABI era: 0.0.35 works on any later torch release.
"2.11.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
"2.12.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
"2.13.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
}
- # The stable-ABI era in one place: every torch STRICTLY ABOVE the floor resolves to this
- # wheel, which is compiled against the floor release and works on any later one by
- # upstream's own guarantee. The exact rows above still win.
- #
- # An exact-key table alone refuses the PATCH releases -- 2.10.1, 2.11.1, 2.12.1 are all
- # supported builds, and none of them can be listed here, because they are published
- # after this script ships. Each one silently left the machine with no xFormers.
+ # Every torch STRICTLY above the floor uses the stable-ABI wheel; exact rows above still win.
+ # Needed for patch releases (2.10.1, ...) published after this script ships.
$script:XformersStableAbiFloor = "2.10.0"
$script:XformersStableAbiVersion = "0.0.35"
$script:XformersStableAbiFamilies = @("cu126", "cu128", "cu130")
- # "2.12.1" -> [version]2.12.1, or $null for a dev/rc/nightly string, which names no
- # released torch and must not be swept into the era comparison.
+ # $null for dev/rc/nightly strings, which name no released torch.
function ConvertTo-TorchReleaseVersion {
param([string]$Release)
if (-not $Release -or -not [regex]::IsMatch($Release, '^\d+(\.\d+)*$')) { return $null }
try { return [version]$Release } catch { return $null }
}
- # xFormers version built for exactly ($TorchVersion, $CudaTag), or $null when that pair
- # has no published wheel -- in which case we install nothing rather than a mismatch.
+ # $null when the pair has no wheel: install nothing rather than a mismatch.
function Get-XformersWheelVersion {
param([string]$TorchVersion, [string]$CudaTag)
if (-not $TorchVersion -or -not $CudaTag) { return $null }
- # "2.10.0+cu130" -> "2.10.0"; a dev/rc suffix has no wheel and must miss the table.
$release = ($TorchVersion -split '\+', 2)[0].Trim()
if ($script:XformersWheelVersions.ContainsKey($release)) {
$byFamily = $script:XformersWheelVersions[$release]
if ($byFamily.ContainsKey($CudaTag)) { return $byFamily[$CudaTag] }
return $null
}
- # Not listed: above the stable-ABI floor the answer is known without a row.
$parsed = ConvertTo-TorchReleaseVersion $release
if ($null -eq $parsed) { return $null }
if ($parsed -gt [version]$script:XformersStableAbiFloor -and $script:XformersStableAbiFamilies -contains $CudaTag) {
@@ -10251,11 +9403,8 @@ main()
return $null
}
- # The torch build the SELECTED wheel records in its cpp_lib.json, which is what
- # Get-InstalledXformersBuild reads back. For an exact-era wheel that is the resident
- # torch; for the stable-ABI wheel it is the floor release it was compiled against, so
- # comparing against the resident torch marked a perfectly good 0.0.35 as mismatched and
- # force-reinstalled it on every run.
+ # The torch build recorded in the selected wheel's cpp_lib.json: the resident torch for exact
+ # rows, the floor for the stable-ABI wheel (else a good 0.0.35 reinstalls every run).
function Get-XformersExpectedTorchBuild {
param([string]$Version, [string]$TorchVersion, [string]$CudaTag)
if ($Version -eq $script:XformersStableAbiVersion) {
@@ -10264,10 +9413,8 @@ main()
return $TorchVersion
}
- # The interpreter tag in the wheel FILENAME: 0.0.31..0.0.34 ship one cp39-abi3 wheel,
- # 0.0.35 switched to py39-none (a packaging change -- the extension never bound the
- # CPython ABI). Unknown releases return $null so a direct URL is never guessed.
- # Mirrors _XFORMERS_FILENAME_PYTHON_TAGS in studio/backend/utils/wheel_utils.py.
+ # Filename interpreter tag: cp39-abi3 for 0.0.31..0.0.34, py39-none for 0.0.35; unknown returns
+ # $null so no URL is guessed. Mirrors _XFORMERS_FILENAME_PYTHON_TAGS in wheel_utils.py.
function Get-XformersFilenamePythonTag {
param([string]$Version)
$parsed = ConvertTo-TorchReleaseVersion (($Version -split '[^0-9.]', 2)[0].TrimEnd('.'))
@@ -10277,12 +9424,8 @@ main()
return $null
}
- # What the RESIDENT xformers actually is: "<version> <torch-it-was-built-for>", e.g.
- # "0.0.34 2.10.0+cu128", or $null when xformers is absent or carries no build metadata.
- # BOTH halves are needed. The version alone cannot tell cu126 from cu128 from cu130 --
- # all three publish the same version string -- and the build tag alone cannot tell
- # 0.0.34 from 0.0.35, which report the same torch. Read from disk rather than
- # "import xformers" so a mismatched .pyd cannot log its own warning into the probe.
+ # "<version> <torch-it-was-built-for>", or $null. Both halves: cu126/128/130 share a version
+ # and 0.0.34/0.0.35 share a torch. Read from disk so a bad .pyd cannot log into the probe.
function Get-InstalledXformersBuild {
param([string]$PythonExe)
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
@@ -10294,15 +9437,12 @@ main()
return $build
}
- # Post-install XPU runtime check. A +xpu wheel installing is not proof the GPU is usable: on
- # an old Intel compute driver torch.xpu.is_available() is False and Unsloth then dies at
- # import. Warn, never fall back -- a driver update fixes it.
+ # A +xpu wheel is not proof: on an old compute driver xpu.is_available() is False and Unsloth
+ # dies at import. Warn, never fall back; a driver update fixes it.
function Assert-XpuRuntimeReady {
param([string]$PythonExe)
- # No interpreter to ask means something bigger already broke; do not blame the driver.
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $true }
- # Line-anchored so a stdout banner ahead of the answer hides nothing. Every failure,
- # timeout included, reads as not-ready and warns rather than hanging the installer.
+ # Line-anchored; every failure, timeout included, warns rather than hanging.
$probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'
if ($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$') { return $true }
substep "[WARN] PyTorch XPU is installed but torch.xpu.is_available() is False." "Yellow"
@@ -10469,8 +9609,7 @@ main()
(-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_FAMILY))
$TorchIndexUrl = Get-TorchIndexUrl
- # Intel XPU reroute. Must run AFTER the Get-TorchIndexUrl call above, or that call overwrites
- # it. An explicit pin still wins, like the AMD ROCm reroute below.
+ # Must run AFTER Get-TorchIndexUrl above, which would overwrite it. A pin still wins.
if ($script:IsIntelXpu -and -not $TorchIndexPinned -and -not $SkipTorch) {
$XpuBaseUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/') } else { "https://download.pytorch.org/whl" }
$TorchIndexUrl = "$XpuBaseUrl/xpu"
@@ -10478,12 +9617,9 @@ main()
}
# ── GPU arch → newest compatible Windows ROCm wheel release ──
- # Wheels bundle their own ROCm runtime; the installed HIP SDK version does
- # not constrain which release to use. Always picks the newest release that
- # supports the GPU architecture.
# ── AMD Windows ROCm: arch-aware pip index (repo.amd.com) ──
- # Wheels bundle their own ROCm runtime and support all Python versions.
- # Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped / mirror installs.
+ # Wheels bundle their own runtime, so the HIP SDK version does not matter; newest release for the
+ # arch wins. UNSLOTH_ROCM_WINDOWS_MIRROR overrides for air-gapped installs.
$ROCmIndexUrl = $null
$ROCmTorchFloor = $null
$PinnedRocmVisionSpec = $null
@@ -10491,17 +9627,9 @@ main()
$ROCmMultiArch = $false
if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $TorchIndexUrl -like "*/cpu" -and -not $SkipTorch) {
$amdIndexBase = if ($env:UNSLOTH_ROCM_WINDOWS_MIRROR) { $env:UNSLOTH_ROCM_WINDOWS_MIRROR.TrimEnd('/') } else { "https://repo.amd.com/rocm/whl" }
- # $archFamilyMap is defined above the Intel scan (the scan needs it too).
- # gfx120X (RDNA 4) and gfx1151/gfx1150 (Strix) have a null-pointer bug in
- # torch._C._grouped_mm on torch <2.11.0 (rocm7.12 and rocm7.1 respectively).
- # TheRock issues #5284 and #3284. Force torch>=2.11.0 so pip never resolves
- # to the broken 2.10.0 wheels even though they exist on the AMD index.
- # The <2.12.0 ceiling matches the Linux install_python_stack.py constraint
- # for the same arches: AMD actively publishes new versions on their index,
- # so without a ceiling a future 2.12.0+rocmX.Y wheel would be pulled in
- # automatically before it has been validated on these architectures.
- # Bump the ceiling here (and in install_python_stack.py) when 2.12.x is
- # confirmed working on gfx120X / Strix.
+ # gfx120X and gfx1151/gfx1150 have a null-pointer bug in torch._C._grouped_mm below 2.11.0
+ # (TheRock #5284, #3284), so floor 2.11. The <2.12.0 ceiling matches install_python_stack.py;
+ # bump both once 2.12.x is validated on these arches.
$torchFloorMap = @{
"gfx1201" = "torch>=2.11.0,<2.12.0"; "gfx1200" = "torch>=2.11.0,<2.12.0"
"gfx1151" = "torch>=2.11.0,<2.12.0"; "gfx1150" = "torch>=2.11.0,<2.12.0"
@@ -10602,18 +9730,14 @@ main()
substep "PyTorch (training and Transformers inference) runs on CPU on this GPU." "Yellow"
} else {
if ($HipSdkInstalled -and -not $HasROCm -and -not $ROCmUnsupportedGfxArch) {
- # Guarded like the gpu step above: an installed HIP SDK is the SYMPTOM on
- # these cards, so it must not outrank the arm saying why it cannot help.
+ # Guarded like the gpu step: an installed HIP SDK is the symptom here and must not outrank the arm.
substep "Installing CPU-only PyTorch (HIP SDK found but GPU not ROCm-accessible)." "Yellow"
} elseif ($ROCmUnsupportedGfxArch) {
- # Same words as the $ROCmGfxArch arm above, for a card whose arch we know
- # from its name rather than from a probe (unslothai#8529).
substep "Installing CPU PyTorch -- Unsloth has no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch." "Yellow"
substep "Unsloth training and GPU inference are unavailable on CPU torch." "Yellow"
substep "Neither the HIP SDK nor UNSLOTH_ROCM_GFX_ARCH can give this GPU ROCm." "Yellow"
if ((Get-HostMachineArch) -eq "arm64") {
- # No Windows ARM64 Vulkan bundle exists, and studio/setup.ps1 throws on the
- # variable, so the usual advice would abort the next update instead of helping.
+ # No Windows ARM64 Vulkan bundle exists and setup.ps1 throws on the variable.
substep "GGUF chat would need Vulkan here, and no Windows ARM64 Vulkan bundle is published: build llama.cpp from source, or run this on x64." "Yellow"
} else {
substep 'For GPU GGUF chat through Vulkan, set $env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan"' "Yellow"
@@ -10637,34 +9761,23 @@ main()
}
# ── Install PyTorch first, then unsloth separately ──
- # Two steps: `uv pip install unsloth --torch-backend=cpu` resolves to the pre-CLI
- # unsloth==2024.8, so install torch from the explicit index first. --upgrade-package (not
- # --upgrade) so upgrading unsloth cannot re-resolve torch from PyPI and strip the +cuXXX.
# ── Helper: find no-torch-runtime.txt ──
- # uv splits -r/-c/--overrides on whitespace with no way to quote, so the path must be
- # space-free (#6503, #10722, #11012). Requirements only: relocating is safe because
- # no-torch-runtime.txt has no relative includes, while uv resolves an override's relative
- # references against its own directory, so New-UnslothTorchOverridesFile keeps its own
- # handling. Mirrors uv_safe_path in studio/backend/utils/uv_path_safety.py. Returns whether
- # it made a copy, so the caller never deletes the user's own file.
+ # `uv pip install unsloth --torch-backend=cpu` resolves to the pre-CLI unsloth==2024.8. Use
+ # --upgrade-package so upgrading unsloth cannot re-resolve torch from PyPI and drop +cuXXX.
+ # uv splits -r/-c/--overrides on whitespace (#6503, #10722, #11012), so the requirements path
+ # must be space-free. Mirrors uv_safe_path in uv_path_safety.py. Returns whether it copied.
function Get-UvSafeRequirementsPath {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not $Path.Contains(" ")) { return @{ Path = $Path; Temporary = $false } }
$short = $null
try { $short = (New-Object -ComObject Scripting.FileSystemObject).GetFile($Path).ShortPath } catch { }
- # Space-free is not sufficient: a volume can hand back an 8.3 name that does not resolve,
- # and uv then fails to open the file it was pointed at (#11290).
+ # An 8.3 name may not resolve, and uv then cannot open it (#11290).
if ($short -and -not $short.Contains(" ") -and (Test-Path -LiteralPath $short -PathType Leaf -ErrorAction SilentlyContinue)) {
return @{ Path = $short; Temporary = $false }
}
- # No 8.3 name: copy to a space-free directory instead. Several candidates, because %TEMP%
- # can carry the space itself (the #11012 case) and 8.3 creation is commonly disabled on
- # non-system volumes. Each is used only once confirmed space-free and writable.
- # Produced one at a time and guarded. Under this script's ErrorActionPreference = "Stop" a
- # single throwing element in an array literal is evaluated before the loop starts and
- # aborts the install outright, and these calls do throw on a relative or malformed TMP:
- # GetPathRoot returns "" and Join-Path then rejects the empty path.
+ # No 8.3 name: copy to a space-free, writable directory (%TEMP% itself may hold the space).
+ # Built one at a time: under "Stop" a throwing element in an array literal aborts the install.
$candidates = @()
foreach ($produce in @(
{ [System.IO.Path]::GetTempPath() },
@@ -10682,15 +9795,11 @@ main()
if ($dir.Contains(" ")) {
$dirShort = $null
try { $dirShort = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($dir).ShortPath } catch { }
- # Space-free is not sufficient: an 8.3 name that does not resolve would be copied
- # into and then handed to uv, which cannot open it (#11290).
+ # An 8.3 name that does not resolve is unusable (#11290).
if (-not $dirShort -or $dirShort.Contains(" ") -or -not (Test-Path -LiteralPath $dirShort -PathType Container -ErrorAction SilentlyContinue)) { continue }
$dir = $dirShort
}
- # Declared before the try so the catch can clean up a Copy-Item that failed partway
- # and left a partial destination, but built inside it: a candidate naming an unmapped
- # drive makes Join-Path throw DriveNotFoundException, which under Stop would abort the
- # install rather than move on to the next candidate.
+ # Declared outside the try for cleanup; built inside, since Join-Path on an unmapped drive throws.
$tmp = $null
try {
$tmp = Join-Path $dir ("unsloth-reqs-" + [guid]::NewGuid().ToString("N") + ".txt")
@@ -10706,9 +9815,8 @@ main()
}
}
- # Nowhere usable. Say so, because uv's message for a split path names a fragment of the
- # install root and reads as a missing requirements file (#11012). The original is still
- # returned, so the install behaves as it does today rather than failing somewhere new.
+ # uv's split-path error reads as a missing requirements file (#11012), so warn; return the
+ # original so the install behaves as before.
substep "[WARN] the requirements path contains a space and no space-free location was" "Yellow"
substep "available; uv splits such a path, so this install may fail. Set TMP and TEMP" "Yellow"
substep "to a path without spaces and run the installer again." "Yellow"
@@ -10732,8 +9840,8 @@ main()
$pins = & $PythonExe -I -c "from importlib.metadata import version, PackageNotFoundError`nfor _p in ('torch', 'torchvision', 'torchaudio'):`n try:`n print(_p + '==' + version(_p))`n except PackageNotFoundError:`n pass" 2>$null
$lines = @($pins | Where-Object { $_ -match '^torch' })
if ($lines.Count -eq 0 -or $lines[0] -notmatch '^torch==') { return $null }
- # --overrides replaces any UV_OVERRIDE env file, so fold caller files in, minus their trio.
- # REBASED as they are folded: uv resolves relative references against the containing file.
+ # --overrides replaces any UV_OVERRIDE file, so fold caller files in, minus their trio,
+ # REBASED since uv resolves relative references against the containing file.
if ($env:UV_OVERRIDE) {
foreach ($ovFile in ($env:UV_OVERRIDE -split '\s+' | Where-Object { $_ })) {
if (-not (Test-Path -LiteralPath $ovFile -PathType Leaf)) { continue }
@@ -10744,11 +9852,9 @@ main()
}
}
$f = [System.IO.Path]::GetTempFileName()
- # Track it the moment it exists: WriteAllText can throw and the outer cleanup would have
- # no path to remove, leaving a partial copy, authenticated URLs included, on disk.
+ # Track it at once: a throwing WriteAllText would otherwise leave credentials on disk.
$script:TorchOverridesFile = $f
- # This copy can hold credentials in a direct URL, and New-Item takes the directory's
- # inherited ACL, not the source file's. Twin of install.sh's umask 077 plus chmod 600.
+ # May hold credentials, and New-Item inherits the directory ACL; twin of install.sh's chmod 600.
try {
$_acl = Get-Acl -LiteralPath $f
$_acl.SetAccessRuleProtection($true, $false)
@@ -10757,8 +9863,7 @@ main()
$_me, "FullControl", "Allow")))
Set-Acl -LiteralPath $f -AclObject $_acl
} catch { } # best effort, and a no-op off Windows
- # UTF-8 without a BOM, not -Encoding ascii, which rewrites a non-ASCII path as "?".
- # WriteAllText adds no trailing newline: terminate it or two requirements join.
+ # UTF-8 without BOM (ascii rewrites non-ASCII as "?"), newline-terminated.
try {
[System.IO.File]::WriteAllText($f, (($lines -join "`n") + "`n"), (New-Object System.Text.UTF8Encoding($false)))
} catch {
@@ -10770,22 +9875,15 @@ main()
if ($f.Contains(" ")) {
$short = $null
try { $short = (New-Object -ComObject Scripting.FileSystemObject).GetFile($f).ShortPath } catch { }
- # Space-free is not sufficient. A volume can hand back an 8.3 name that does not resolve,
- # and this path is then both uv's --overrides argument and the file the caller deletes:
- # uv fails to open it, and Remove-Item raises a terminating PSArgumentException that
- # -ErrorAction SilentlyContinue on every one of these probes is the idiom at line 3277
- # and is load-bearing: under this script's "Stop", Test-Path inside an ACL-denied
- # directory THROWS UnauthorizedAccessException instead of returning false, and none of
- # these guards sits inside a try. Bare, the check aborts the install on a path whose
- # only crime is being unreadable, in functions whose contract is to fall through.
- # -ErrorAction SilentlyContinue cannot suppress (#11290). Require a real file.
+ # An unresolvable 8.3 name makes uv fail and Remove-Item raise a terminating error;
+ # require a real file.
+ # -ErrorAction SilentlyContinue is load-bearing: under "Stop", Test-Path in an ACL-denied
+ # directory throws, and none of these guards sits inside a try.
if (-not $short -or $short.Contains(" ") -or -not (Test-Path -LiteralPath $short -PathType Leaf -ErrorAction SilentlyContinue)) {
- # No usable short name: skip the freeze rather than fail.
substep "[WARN] the torch overrides path has a space and no usable 8.3 short name;" "Yellow"
substep "installing unsloth without freezing the installed PyTorch." "Yellow"
Remove-UnslothTempFileQuietly -Path $f
- # Tracked above: clear it so the outer sweep is not handed a path this branch
- # has already deleted.
+ # Already deleted: clear it so the outer sweep skips it.
$script:TorchOverridesFile = $null
return $null
}
@@ -10857,9 +9955,7 @@ main()
# (tests/test_installer_zoo_floor_parity.py enforces that).
$baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (migrated no-torch)" { & $script:UvExe pip install --python $VenvPython --no-deps --reinstall-package unsloth --reinstall-package unsloth-zoo "$_unslothReleaseInstallSpec" "$_unslothZooInstallSpec" }
if ($baseInstallExit -eq 0) {
- # Resolve pydantic WITH deps so pip pins pydantic-core
- # to the matching version (no-torch-runtime.txt below
- # is --no-deps). All transitive deps are torch-free.
+ # pydantic WITH deps so pydantic-core matches; no-torch-runtime.txt is --no-deps.
$baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { & $script:UvExe pip install --python $VenvPython pydantic }
}
if ($baseInstallExit -eq 0) {
@@ -10911,8 +10007,8 @@ main()
}
}
} elseif ($TorchIndexUrl -or $ROCmIndexUrl) {
- # Bounded default trio (torch 2.11 line), hoisted so release preservation uses it as the
- # route window. torchaudio 2.11 dropped its torch pin, so a bare companion can drift.
+ # Bounded default trio, hoisted so release preservation uses it as the route window.
+ # torchaudio 2.11 dropped its torch pin, so a bare companion can drift.
$_pinTorchSpec = "torch>=2.4,<2.12.0"
$_pinVisionSpec = "torchvision>=0.19,<0.27.0"
$_pinAudioSpec = "torchaudio>=2.4,<2.12.0"
@@ -10974,11 +10070,8 @@ main()
# Explicit CPU index: under a ROCm pin $TorchIndexUrl IS the mirror that failed.
$CpuFallbackIndexUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { "$($env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/'))/cpu" } else { "https://download.pytorch.org/whl/cpu" }
substep "ROCm PyTorch install failed (exit $torchInstallExit); using a CPU base, Unsloth setup retries ROCm." "Yellow"
- # --force-reinstall: a failed ROCm install can leave an unpinned ROCm
- # torch (e.g. 2.10.0+rocm on gfx110X/gfx90a) that still satisfies the CPU
- # torch>= range, so without it uv would keep the ROCm build and only swap
- # the companions -- a mismatched venv the flavor-repair block won't fix.
- # No kept-release attempt: the ROCm attempts resolve or clear the pin first.
+ # --force-reinstall: a failed ROCm install can leave a ROCm torch inside the CPU range, which
+ # uv would keep while swapping companions.
$torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { & $script:UvExe pip install --python $VenvPython --force-reinstall "torch>=2.4,<2.12.0" "torchvision>=0.19,<0.27.0" "torchaudio>=2.4,<2.12.0" --default-index $CpuFallbackIndexUrl }
if ($torchInstallExit -ne 0) {
Write-StudioLine "[ERROR] Failed to install PyTorch (ROCm and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red
@@ -10988,20 +10081,13 @@ main()
$ROCmIndexUrl = $null
$ROCmTorchFloor = $null
}
- # Keyed off the index leaf alone, like the bitsandbytes gate below: a FAMILY=xpu or URL
- # pin lands here on a host whose Intel scan never ran (a mixed NVIDIA box), and requiring
- # $script:IsIntelXpu sent it to the generic branch and its 2.4 floor.
+ # Keyed off the index leaf: a FAMILY=xpu pin on a mixed NVIDIA box never ran the Intel scan.
} elseif ((Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") {
# ── Intel Arc / XPU PyTorch install ──
- # XPU wheels carry their own oneAPI runtime (intel-sycl-rt et al.), published under
- # PEP 503 at https://download.pytorch.org/whl/xpu.
Write-TauriLog "STEP" "Installing PyTorch (Intel XPU)"
substep "installing PyTorch from $(Remove-IndexUrlCredentials $TorchIndexUrl)..."
- # Bound the trio like every other index: the xpu index serves torch past our ceiling
- # (up to 2.13.0), and torchaudio dropped its exact torch pin. The floor is 2.6, not
- # the usual 2.4: unsloth/models/_utils.py raises at import for an XPU device below
- # that. Windows on ARM has no torchaudio wheel on any index, so drop that pin here
- # rather than abort -- the pin-only route reaches this branch on an arm64 interpreter.
+ # Bound the trio: the xpu index serves torch past our ceiling. Floor 2.6 (unsloth raises below it
+ # on XPU); win-arm64 has no torchaudio, so drop that pin.
$VenvPlatform = Get-VenvPlatformTag -PythonExe $VenvPython
$_xpuSpecs = Get-XpuTorchSpecs -Platform $VenvPlatform
$_xpuCpuSpecs = @("torch>=2.4,<2.12.0", "torchvision>=0.19,<0.27.0", "torchaudio>=2.4,<2.12.0")
@@ -11009,7 +10095,6 @@ main()
substep "windows on arm: skipping torchaudio (upstream publishes no win_arm64 wheel)."
$_xpuCpuSpecs = @("torch>=2.4,<2.12.0", "torchvision>=0.19,<0.27.0")
}
- # The kept trio follows $_xpuSpecs' shape so win-arm64 still omits torchaudio.
if ($script:PrevTorchPin) {
$_keptTorch = $script:PrevTorchPin.TorchSpec; $_keptVision = $script:PrevTorchPin.VisionSpec; $_keptAudio = $script:PrevTorchPin.AudioSpec
$_keptXpuSpecs = @($_keptTorch, $_keptVision)
@@ -11025,7 +10110,6 @@ main()
$torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (Intel XPU)" { & $script:UvExe pip install --python $VenvPython --force-reinstall @_xpuSpecs --default-index $TorchIndexUrl }
}
if ($torchInstallExit -ne 0) {
- # Transient XPU-index failure: fall back to CPU base.
$CpuFallbackIndexUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { "$($env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/'))/cpu" } else { "https://download.pytorch.org/whl/cpu" }
substep "XPU PyTorch install failed (exit $torchInstallExit); using a CPU base." "Yellow"
$torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { & $script:UvExe pip install --python $VenvPython --force-reinstall @_xpuCpuSpecs --default-index $CpuFallbackIndexUrl }
@@ -11037,26 +10121,18 @@ main()
$script:IsIntelXpu = $false
$TorchIndexUrl = $CpuFallbackIndexUrl
} else {
- # A WMI name match says XPU-capable, not that the runtime initializes: on a stale
- # driver unsloth/device_type.py raises NotImplementedError at import. The helper
- # warns and deliberately does NOT fall back to CPU.
+ # A name match is not a working runtime: warn on a stale driver, never fall back to CPU.
Assert-XpuRuntimeReady -PythonExe $VenvPython | Out-Null
}
} else {
Write-TauriLog "STEP" "Installing PyTorch"
- # Windows on ARM lacks only torchaudio (whl/cpu win_arm64: torch 42,
- # torchvision 60, torchaudio 0), so drop that pin instead of aborting. Ask the
- # interpreter, not PROCESSOR_ARCHITECTURE; reached when no x64 Python exists.
+ # Windows on ARM lacks only torchaudio; ask the interpreter, not PROCESSOR_ARCHITECTURE.
$VenvPlatform = ""
try {
$VenvPlatform = (& $VenvPython -c "import sysconfig; print(sysconfig.get_platform())" 2>$null | Out-String).Trim().ToLowerInvariant()
} catch { $VenvPlatform = "" }
substep "installing PyTorch ($(Remove-IndexUrlCredentials $TorchIndexUrl))..."
- # Bound the companions to the capped torch on EVERY index, cu<digits>
- # families included: torchaudio 2.11 dropped its exact torch pin from
- # the wheel metadata, so a bare companion next to torch<2.11 can
- # resolve a mismatched 2.11.0 build. Mirrors install.sh.
- # The hoisted trio, so the vetted route window and the installed specs cannot drift.
+ # Bound companions on EVERY index: torchaudio 2.11 dropped its exact torch pin. Mirrors install.sh.
$_torchSpecs = @($_pinTorchSpec, $_pinVisionSpec, $_pinAudioSpec)
$_torchExtraArgs = @()
if ($VenvPlatform -eq "win-arm64") {
@@ -11076,10 +10152,10 @@ main()
$_torchSpecs += if ($script:WoaAudioWheelVersion) { "torchaudio==$($script:WoaAudioWheelVersion)" } else { "torchaudio>=2.4" }
substep "windows on arm: this index publishes torchaudio; installing the full trio."
}
- # NVIDIA's index publishes only the trio; the shared dependencies come from the index the caller's resolver policy names, public PyPI by default, or the wheelhouse alone under no-index.
+ # NVIDIA's index publishes only the trio; dependencies come from the caller's index policy.
$_woaDependencyIndexArgs = @(Get-WoaDependencyIndexArgs)
$_torchExtraArgs = @("--index-strategy", "unsafe-best-match") + $_woaDependencyIndexArgs
- # Invoke-InstallCommand clears UV_FIND_LINKS beside the other inherited index settings, so the staged wheelhouse is named on the command line.
+ # Invoke-InstallCommand clears UV_FIND_LINKS, so name the wheelhouse on the command line.
if ($script:WoaDir) {
$_torchExtraArgs += @("--find-links", (Get-UvSafePath (Join-Path $script:WoaDir "wheels")))
}
@@ -11088,7 +10164,6 @@ main()
} elseif ($_woaDependencyIndexArgs -notcontains "https://pypi.org/simple") {
substep "windows on arm: torch's dependencies resolve from the configured index, not public PyPI."
}
- # Only a prerelease channel needs this. The URL spelling is a second signal.
if ($script:WoaTorchIsPrerelease -or ($script:WoaTorchIndexUrl -match 'nightly')) {
$_torchExtraArgs = @("--prerelease=allow") + $_torchExtraArgs
substep "windows on arm: allowing prerelease torch (this index publishes win_arm64 CUDA wheels as nightlies)."
@@ -11123,7 +10198,8 @@ main()
$_woaOverrideSwapped = $true
}
if ($script:WoaNativeCudaTorch -and $VenvPlatform -eq "win-arm64") {
- # The probe read the index page, which carries no upload dates, and the pin is exact: an upload cutoff would reject the selected wheel. Only this one command.
+ # The probe read the index page, which has no upload dates, and the pin is
+ # exact, so drop upload cutoffs for this one command.
foreach ($_woaCutoffName in @("UV_EXCLUDE_NEWER", "UV_EXCLUDE_NEWER_PACKAGE")) {
$_woaCutoffValue = [string][Environment]::GetEnvironmentVariable($_woaCutoffName)
if ($_woaCutoffValue) {
@@ -11132,7 +10208,8 @@ main()
substep "windows on arm: $_woaCutoffName is not applied to the exact CUDA pin (the index carries no upload dates)."
}
}
- # Our own UV_NO_INDEX convention (uv defines no such variable) means the operator wants no registry index, and we honour it by naming none. The CUDA trio is published nowhere else, so it yields for this one command: torch from the index the probe chose, dependencies from the wheelhouse. Saved and restored, because the rest of the run still reads it.
+ # UV_NO_INDEX is our convention; the CUDA trio lives only on NVIDIA's index, so it yields for
+ # this command (deps still from the wheelhouse), then is restored.
$_woaNoIndexValue = [string][Environment]::GetEnvironmentVariable("UV_NO_INDEX")
if (Test-NoIndexRequested) {
$_woaCutoffSaved["UV_NO_INDEX"] = $_woaNoIndexValue
@@ -11157,12 +10234,9 @@ main()
Write-TauriLog "STEP" "Installing unsloth"
substep "installing unsloth (this may take a few minutes)..."
if ($SkipTorch) {
- # No-torch: install unsloth + unsloth-zoo with --no-deps, then
- # runtime deps (typer, safetensors, transformers, etc.) with --no-deps.
# --no-deps: this spec IS the zoo floor here. Kept equal to pyproject.toml's.
$baseInstallExit = Invoke-InstallCommandRetry -Label "install unsloth (no-torch)" { & $script:UvExe pip install --python $VenvPython --no-deps --upgrade-package unsloth --upgrade-package unsloth-zoo "$_unslothReleaseInstallSpec" "$_unslothZooInstallSpec" }
if ($baseInstallExit -eq 0) {
- # Same pydantic-with-deps trick as the migrated branch.
$baseInstallExit = Invoke-InstallCommandRetry -Label "install pydantic" { & $script:UvExe pip install --python $VenvPython pydantic }
}
if ($baseInstallExit -eq 0) {
@@ -11217,7 +10291,7 @@ main()
}
}
} else {
- # Fallback: GPU detection failed to produce a URL -- let uv resolve torch
+ # Fallback: GPU detection produced no URL, so uv resolves torch.
Write-TauriLog "STEP" "Installing unsloth"
substep "installing unsloth (this may take a few minutes)..."
if ($StudioLocalInstall) {
@@ -11249,17 +10323,9 @@ main()
}
# ── Intel XPU: bitsandbytes must carry XPU kernels ──
- # unsloth/bnb_availability.py binds cgemv_4bit_inference_fp16/bf16 for device_type "xpu" and
- # only bitsandbytes' XPU library exports those, so a wheel without it turns 4-bit QLoRA off.
- # 0.48.2 is the first win_amd64 build carrying that library, but the floor is 0.50.0, the AMD
- # paths' floor: <=0.49.2 NaNs at 4-bit decode on AMD, and an Arc card can sit next to a
- # Radeon. unsloth's own floor (>=0.45.5) lets a MIGRATED venv keep an older wheel, so run
- # after that install for the last word. --no-deps (torch/numpy are in), and never the curated
- # unsloth[intel-gpu-torch*] extra: it pins torch to a single +xpu wheel URL, unpinning the
- # bounded trio, and carries a preview bitsandbytes wheel uv refuses.
- # Keyed off the index leaf, not $script:IsIntelXpu: a FAMILY=xpu pin on a non-Intel host
- # skips the XPU branch above yet still installs +xpu torch. The CPU fallback there rewrites
- # $TorchIndexUrl, so a failed XPU install reads as "cpu" here. Best-effort: a failure warns.
+ # Floor 0.50.0 (AMD's: <=0.49.2 NaNs at 4-bit decode, and an Arc can sit beside a Radeon); runs
+ # after the unsloth install so a migrated venv cannot keep an older wheel. --no-deps, and not the
+ # intel-gpu-torch extra (pins a single +xpu URL). Keyed off the index leaf; best-effort.
if (-not $SkipTorch -and (Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") {
substep "installing bitsandbytes with Intel XPU kernels..."
$bnbXpuExit = Invoke-InstallCommandRetry -Label "install bitsandbytes (Intel XPU)" { & $script:UvExe pip install --python $VenvPython --no-deps "bitsandbytes>=0.50.0" }
@@ -11300,15 +10366,14 @@ sys.exit(2 if conflict else (0 if installed else 1))
substep "[WARN] installed $PackageName version could not be determined" "Yellow"
}
- # ── PEP 440 ignores the +cpu/+cuXXX local label, so uv keeps a stale torch+cpu against a CUDA
- # index. Reinstall the triplet when a GPU build is expected; --no-torch is a no-op. ──
+ # ── PEP 440 ignores +cpu/+cuXXX, so uv keeps a stale torch+cpu against a CUDA index:
+ # reinstall the triplet when a GPU build is expected. ──
if (-not $SkipTorch) {
$expectedTorchTag = Get-ExpectedTorchFlavorTag -TorchIndexUrl $TorchIndexUrl -ROCmIndexUrl $ROCmIndexUrl
if ($expectedTorchTag -and $expectedTorchTag -ne 'cpu') {
$installedTorchTag = Get-InstalledTorchTag -PythonExe $VenvPython
if ($installedTorchTag -and $installedTorchTag -ne $expectedTorchTag) {
if ($expectedTorchTag -eq 'rocm' -and $ROCmIndexUrl) {
- # A migrated venv can keep a stale CPU torch the fresh ROCm path would replace.
$rocmSpec = if ($ROCmTorchFloor) { $ROCmTorchFloor } else { "torch" }
$visionSpec = if ($PinnedRocmVisionSpec) { $PinnedRocmVisionSpec } elseif ($ROCmGfxArch -and $torchvisionFloorMap -and $torchvisionFloorMap.ContainsKey($ROCmGfxArch)) { $torchvisionFloorMap[$ROCmGfxArch] } else { "torchvision" }
$audioSpec = if ($PinnedRocmAudioSpec) { $PinnedRocmAudioSpec } elseif ($ROCmGfxArch -and $torchaudioFloorMap -and $torchaudioFloorMap.ContainsKey($ROCmGfxArch)) { $torchaudioFloorMap[$ROCmGfxArch] } else { "torchaudio" }
@@ -11334,7 +10399,6 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
$installedTorchTag = Get-InstalledTorchTag -PythonExe $VenvPython
} elseif ($expectedTorchTag -ne 'rocm') {
- # CUDA: reinstall the triplet with the default 2.11-line trio.
$_fixTorchSpec = "torch>=2.4,<2.12.0"; $_fixVisionSpec = "torchvision>=0.19,<0.27.0"; $_fixAudioSpec = "torchaudio>=2.4,<2.12.0"
$_cudaKept = $false
if ($script:PrevTorchPin) {
@@ -11343,7 +10407,6 @@ sys.exit(2 if conflict else (0 if installed else 1))
$_cudaKept = $true
}
substep "PyTorch flavor mismatch (installed $installedTorchTag, need $expectedTorchTag) -- reinstalling correct build..." "Yellow"
- # A migrated win-arm64 venv lands here; torchaudio is unpublished for it.
$_fixSpecs = @($_fixTorchSpec, $_fixVisionSpec, $_fixAudioSpec)
$_origFixSpecs = if ($_cudaKept) { @($_origFixTorchSpec, $_origFixVisionSpec, $_origFixAudioSpec) } else { $_fixSpecs }
if ($expectedTorchTag -eq 'xpu') {
@@ -11371,7 +10434,6 @@ sys.exit(2 if conflict else (0 if installed else 1))
$installedTorchTag = Get-InstalledTorchTag -PythonExe $VenvPython
}
}
- # Safety net (incl. AMD): GPU build expected but still CPU -> warn loudly.
if ($installedTorchTag -eq 'cpu') {
Write-StudioLine ""
Write-StudioLine " [WARN] PyTorch is CPU-only but a $expectedTorchTag GPU build was expected for this machine." -ForegroundColor Yellow
@@ -11382,59 +10444,30 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
# ── Pin xFormers to the wheel built for the torch that is actually installed ──
- # See $script:XformersWheelVersions above for why a version floor is not enough.
- # Runs AFTER the flavor repair so it reads the final torch, and keys off THAT torch
- # rather than off $TorchIndexUrl, which the repair does not always reconcile (it is
- # skipped when the expected tag is 'cpu' or unrecognised, so a migrated venv can hold
- # a +cu128 torch while the index leaf says /cpu, and /cpu serves no usable xFormers).
- # xFormers is an optional accelerator, so every failure here warns and the install
- # continues on torch SDPA; and when no wheel matches we install NOTHING, because
- # installing a mismatched one is the bug being fixed. UNSLOTH_SKIP_XFORMERS=1 opts out.
+ # After the flavor repair, keyed off the installed torch, not $TorchIndexUrl (a migrated venv can
+ # hold +cu128 under a /cpu leaf). Optional: failures warn, no match installs nothing.
+ # UNSLOTH_SKIP_XFORMERS=1 opts out.
if (-not $SkipTorch -and $env:UNSLOTH_SKIP_XFORMERS -ne "1") {
$_xfTorchVersion = Get-InstalledTorchVersion -PythonExe $VenvPython
$_xfCudaTag = ConvertTo-TorchFlavorTag $_xfTorchVersion
- # cu<digits> only: cpu / rocm / xpu torch has no xFormers wheel on any index.
- # IsMatch, not -match, so this does not clobber $Matches for the enclosing scope.
+ # cu<digits> only. IsMatch, not -match, so $Matches is not clobbered.
if ($_xfTorchVersion -and [regex]::IsMatch([string]$_xfCudaTag, '^cu\d+$')) {
$_xfVersion = Get-XformersWheelVersion -TorchVersion $_xfTorchVersion -CudaTag $_xfCudaTag
if (-not $_xfVersion) {
- # "not in the table", which also covers families we have no row for (cu118,
- # cu124) as well as torch releases upstream never built against.
substep "no matching xFormers wheel for torch $_xfTorchVersion -- skipping it (attention falls back to torch SDPA)."
} elseif ((Get-InstalledXformersBuild -PythonExe $VenvPython) -eq "$_xfVersion $(Get-XformersExpectedTorchBuild -Version $_xfVersion -TorchVersion $_xfTorchVersion -CudaTag $_xfCudaTag)") {
substep "xFormers $_xfVersion already matches torch $_xfTorchVersion."
} else {
- # How to fetch it, in two cases.
- #
- # An EXPLICIT index pin is authoritative and stays whole. Its final component
- # is not required to be the CUDA family: a documented full-URL override can be
- # an authenticated PEP 503 mirror, and comparing its leaf threw exactly that
- # index away -- the one that had just supplied the resident CUDA torch --
- # leaving an air-gapped host unable to reach any wheel at all.
- #
- # Otherwise install the DIRECT wheel URL rather than resolving a version off
- # an index. --default-index does not make an index exclusive (uv's --index /
- # UV_INDEX are used "in addition to" it), and cu126 / cu128 / cu130 publish
- # the SAME version string, so a machine with UV_INDEX set -- PyPI's CUDA-12.8
- # build, say -- could satisfy a pinned 0.0.35 from the wrong family and
- # recreate the silent extension failure this whole step exists to prevent.
- # A URL cannot be resolved anywhere else. UNSLOTH_PYTORCH_MIRROR is still
- # honoured, as it is everywhere else in this script.
+ # An explicit full-URL pin is authoritative, even a non-family mirror root (air-gapped hosts).
+ # Otherwise use the DIRECT wheel URL: --default-index is not exclusive (UV_INDEX adds to it) and
+ # cu126/128/130 share a version, so an index could serve the wrong family.
$_xfIndexUrl = $null
$_xfWheelUrl = $null
$_xfPyTag = Get-XformersFilenamePythonTag $_xfVersion
$_xfWheelName = if ($_xfPyTag) { "xformers-$_xfVersion-$_xfPyTag-win_amd64.whl" } else { $null }
- # A FULL-URL override only. UNSLOTH_TORCH_INDEX_FAMILY also sets
- # $TorchIndexPinned, and routing that through the index reintroduced the very
- # hole above: cu126 / cu128 / cu130 share a version string, so a machine-level
- # UV_INDEX could satisfy the pin with the wrong family. A family pin names a
- # leaf we can build a direct URL from, so it takes the URL path.
+ # Full-URL override only: a FAMILY pin can build a direct URL, so it takes that path.
if ($TorchIndexUrl -and -not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL)) {
- # Even here, prefer a URL. When the override already names a CUDA leaf
- # (.../cu130, the documented shape) the wheel can be addressed under it
- # directly, which no UV_INDEX can substitute for. Only an override whose
- # leaf is not a family -- a bare PEP 503 mirror root -- has to be resolved,
- # and that one gets the machine-level indexes cleared below.
+ # A CUDA leaf still gets a direct URL; only a bare mirror root resolves, with machine indexes cleared.
$_xfOverrideLeaf = Get-TorchIndexLeafName $TorchIndexUrl
if ($_xfWheelName -and [regex]::IsMatch($_xfOverrideLeaf, '^cu\d+$')) {
$_xfWheelUrl = Join-UrlPath $TorchIndexUrl $_xfWheelName
@@ -11446,31 +10479,21 @@ sys.exit(2 if conflict else (0 if installed else 1))
if ($_xfWheelName) {
$_xfWheelUrl = Join-UrlPath $_xfBase "$_xfCudaTag/$_xfWheelName"
} else {
- # Unknown filename shape: fall back to the index rather than guessing
- # a URL that 404s.
+ # Unknown filename shape: use the index rather than guess a URL that 404s.
$_xfIndexUrl = Join-UrlPath $_xfBase $_xfCudaTag
}
}
$_xfSource = if ($_xfWheelUrl) { $_xfWheelUrl } else { $_xfIndexUrl }
substep "installing xFormers $_xfVersion for torch $_xfTorchVersion ($(Remove-IndexUrlCredentials $_xfSource))..."
- # --no-deps: the wheel declares torch==<exact release>, and acting on that can
- # pull a PyPI (CUDA 12.8) torch over the CUDA build just installed.
- # --reinstall-package: cu126 / cu128 / cu130 all publish the SAME xformers
- # version string, so a wrong-CUDA wheel is invisible to a version check and
- # would otherwise be left in place on an upgrade of a broken install.
- # Go through $script:UvExe when something has resolved one, so this call
- # cannot be captured by a profile alias named uv. That variable is not set
- # on this branch; Get-Variable rather than a bare read so the lookup is
- # also safe under a profile's Set-StrictMode.
+ # --no-deps: the wheel's torch==<release> could pull a PyPI torch over the CUDA build.
+ # --reinstall-package: wrong-CUDA wheels share the version string.
+ # $script:UvExe (via Get-Variable, StrictMode-safe) avoids a profile alias named uv.
$_xfUv = Get-Variable -Name 'UvExe' -Scope Script -ValueOnly -ErrorAction SilentlyContinue
if (-not $_xfUv) { $_xfUv = 'uv' }
$_xfExit = if ($_xfWheelUrl) {
Invoke-InstallCommandRetry -Label "install xFormers" { & $_xfUv pip install --python $VenvPython --no-deps --reinstall-package xformers $_xfWheelUrl }
} else {
- # --default-index does not make an index exclusive: uv reads UV_INDEX and
- # UV_EXTRA_INDEX_URL "in addition to" it, and every CUDA family publishes the
- # SAME xformers version, so a machine-level index could satisfy the pin from
- # the wrong one. Cleared for this call only, and restored after.
+ # UV_INDEX / UV_EXTRA_INDEX_URL add to --default-index; clear them for this call only.
$_xfSavedIndex = $env:UV_INDEX
$_xfSavedExtra = $env:UV_EXTRA_INDEX_URL
try {
@@ -11490,19 +10513,8 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
# ── CI only: overlay a source checkout over the package just installed ──
- # Mirrors install.sh. Not a consumer knob: no switch, absent from the usage text,
- # ignored unless UNSLOTH_CI_SOURCE_OVERLAY names a directory with a pyproject.toml.
- #
- # The clean-machine legs run THIS script from a branch but install unsloth from
- # PyPI, the consumer path, so everything Python-side (studio/setup.ps1,
- # install_python_stack.py and every requirements/constraints file they reach via
- # Path(__file__)) would be the released wheel's and a branch could not be
- # validated. The `studio setup` handoff below goes through the CLI, and an
- # editable overlay makes _PACKAGE_ROOT in unsloth_cli/commands/studio.py resolve to
- # the working tree by PEP 660 __file__, so setup.ps1 comes from this ref. NOT
- # --local: that also installs `unsloth-zoo @ git+https://...`, which genuinely needs
- # the git these legs remove; editable + --no-deps resolves and clones nothing, so it
- # survives git, cmake and MSVC all missing.
+ # Clean-machine legs install unsloth from PyPI; the overlay makes setup.ps1 and friends come from
+ # this ref. Not --local: it git-clones unsloth-zoo, and these legs remove git.
if ($env:UNSLOTH_CI_SOURCE_OVERLAY) {
$CiOverlayRoot = $env:UNSLOTH_CI_SOURCE_OVERLAY
if (-not (Test-Path -LiteralPath (Join-Path $CiOverlayRoot "pyproject.toml"))) {
@@ -11517,7 +10529,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
}
- # setup.ps1 is fetched live while `unsloth` comes from PyPI, so it can predate ARM64 support. Tested by capability, not version.
+ # setup.ps1 is fetched live, not from PyPI; it may predate ARM64 support, so test by capability.
if ($script:WoaNativeCudaTorch) {
$WoaStudioSetup = $null
try {
@@ -11537,21 +10549,11 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
# ── Run studio setup ──
- # setup.ps1 will handle installing Git, CMake, Visual Studio Build Tools,
- # CUDA Toolkit, and other dependencies automatically via winget. Node.js is
- # NOT installed via winget -- setup.ps1 uses an isolated Node it manages and
- # never touches the system Node/npm.
+ # setup.ps1 installs Git, CMake, VS Build Tools and CUDA via winget; Node is isolated, not winget.
Write-TauriLog "STEP" "Running studio setup"
step "setup" "running unsloth studio setup..."
- # Tested, never executed: pip generates the console script whatever the policy says
- # about running it, so it stays the cheapest "this wheel shipped the CLI" signal.
- #
- # Cheapest, but no longer required. A policy DENIES this file and leaves it on disk,
- # so it answers there, but antivirus QUARANTINES it, deleting it out of a venv that
- # is otherwise perfectly able to run. Nothing after this point executes it -- the
- # setup handoff, the shortcuts and bin\unsloth.cmd all go through $VenvPython -- so
- # failing here would refuse to install or repair Unsloth for exactly the machines
- # this change is for. Ask the interpreter instead, and only then give up.
+ # Tested, never executed. Not required: it can be removed from an otherwise working venv, and
+ # nothing later runs it (everything uses $VenvPython), so fall back to asking the interpreter.
$UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"
if (-not (Test-Path -LiteralPath $UnslothExe)) {
$cliImportable = $false
@@ -11571,8 +10573,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
return (Exit-InstallFailure "unsloth CLI was not installed correctly")
}
}
- # This is the file the handoff actually starts, so it gets its own check rather
- # than being discovered as a launch failure halfway through setup.
+ # The file the handoff starts gets its own check, not a mid-setup launch failure.
if (-not (Test-Path -LiteralPath $VenvPython)) {
Write-TauriLog "ERROR" "managed Python is missing"
Write-StudioLine "[ERROR] The managed Python interpreter is missing." -ForegroundColor Red
@@ -11580,13 +10581,11 @@ sys.exit(2 if conflict else (0 if installed else 1))
Write-StudioLine " Re-run the installer to rebuild the environment." -ForegroundColor Yellow
return (Exit-InstallFailure "managed Python is missing at $VenvPython")
}
- # `irm | iex` runs in the caller's shell, so every handoff variable is saved and restored.
- # Captures sit above the try, or a finally reached first reads the unset $hadPrevious* as
- # "there was nothing here" and clears a value it never set.
+ # `irm | iex` runs in the caller's shell, so save/restore every handoff variable. Captures sit
+ # above the try so a finally never clears a value it never set.
$previousSkipStudioBase = $env:SKIP_STUDIO_BASE
$hadPreviousSkipStudioBase = ($null -ne $previousSkipStudioBase)
- # Propagate UNSLOTH_STUDIO_HOME only for env-override installs; otherwise
- # an inherited value would put llama.cpp in the wrong place.
+ # UNSLOTH_STUDIO_HOME only for env-override installs, or llama.cpp lands in the wrong place.
$previousUnslothStudioHome = $env:UNSLOTH_STUDIO_HOME
$hadPreviousUnslothStudioHome = ($null -ne $previousUnslothStudioHome)
$previousTauriMode = $env:UNSLOTH_TAURI_MODE
@@ -11597,8 +10596,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
$hadPreviousProxyHandoff = ($null -ne $previousProxyHandoff)
$previousRocmGfxHandoff = $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF
$hadPreviousRocmGfxHandoff = ($null -ne $previousRocmGfxHandoff)
- # SKIP_STUDIO_FRONTEND is the one with teeth: a leaked "1" makes the next direct
- # `unsloth studio setup` skip the frontend build, leaving a source install with no web UI.
+ # A leaked SKIP_STUDIO_FRONTEND=1 would skip the next source setup's frontend build.
$previousStudioPackageName = $env:STUDIO_PACKAGE_NAME
$hadPreviousStudioPackageName = ($null -ne $previousStudioPackageName)
$previousNoTorch = $env:UNSLOTH_NO_TORCH
@@ -11611,8 +10609,6 @@ sys.exit(2 if conflict else (0 if installed else 1))
$hadPreviousStudioLocalInstall = ($null -ne $previousStudioLocalInstall)
$previousStudioLocalRepo = $env:STUDIO_LOCAL_REPO
$hadPreviousStudioLocalRepo = ($null -ne $previousStudioLocalRepo)
- # Cleared unconditionally before, which the --with-llama-cpp-dir bail reaches without
- # having set them. UNSLOTH_LOCAL_LLAMA_CPP_DIR is a user-facing input this script reads.
$previousLocalLlamaCppDir = $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR
$hadPreviousLocalLlamaCppDir = ($null -ne $previousLocalLlamaCppDir)
$previousInstallRollbackManaged = $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED
@@ -11631,16 +10627,13 @@ sys.exit(2 if conflict else (0 if installed else 1))
$env:SKIP_STUDIO_BASE = "1"
$env:STUDIO_PACKAGE_NAME = $PackageName
$env:UNSLOTH_NO_TORCH = if ($SkipTorch) { "true" } else { "false" }
- # The torch family THIS run settled on, for setup.ps1's preserve guard (full rationale there,
- # at $InstallerTorchTag): "a GPU wheel is in the venv" is not on its own evidence that this
- # installer put it there -- the migrated-venv arm above installs unsloth only and never
- # touches torch. Empty means "no answer": --no-torch, or a custom index whose leaf names no
- # flavor. Always assigned so a previous run in the same session cannot leak a value; 7.5+
- # keeps it present and blank, 5.1 / 7.0-7.4 remove it, and setup.ps1 treats both as unknown.
+ # The torch family THIS run chose, for setup.ps1's preserve guard: the migrated-venv arm never
+ # touches torch. Empty = unknown; always assigned so a previous session value cannot leak.
$env:UNSLOTH_INSTALLER_TORCH_TAG = if ($SkipTorch) { "" } else {
[string](Get-ExpectedTorchFlavorTag -TorchIndexUrl $TorchIndexUrl -ROCmIndexUrl $ROCmIndexUrl)
}
- # Windows on ARM: whether this run's index paired a torchaudio, whether that torch is a prerelease (the URL alone misses a quiet mirror), and WHICH index. Not UNSLOTH_WOA_TORCH_INDEX_URL, which a later run would read as a pin.
+ # Windows on ARM: torchaudio pairing, prerelease flag and index. Not UNSLOTH_WOA_TORCH_INDEX_URL,
+ # which a later run would read as a pin.
$env:UNSLOTH_WOA_HAS_TORCHAUDIO = if ($script:WoaNativeCudaTorch -and $script:WoaTorchAudio) { "1" } else { "0" }
$env:UNSLOTH_WOA_TORCH_PRERELEASE = if ($script:WoaNativeCudaTorch -and $script:WoaTorchIsPrerelease) { "1" } else { "0" }
if ($script:WoaNativeCudaTorch -and $script:WoaTorchIndexUrl) {
@@ -11648,7 +10641,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
} else {
Remove-Item Env:UNSLOTH_WOA_SELECTED_TORCH_INDEX -ErrorAction SilentlyContinue
}
- # Wheelhouse wheels discarded because PyPI serves the same version: the managed copy is gone, so this is the only record install_python_stack.py has that they resolve.
+ # Discarded wheelhouse wheels PyPI also serves, recorded for install_python_stack.py.
$_woaProvidedPairs = @()
foreach ($_woaProvidedKey in @($script:WoaPyPIProvided.Keys | Sort-Object)) {
foreach ($_woaProvidedVer in @($script:WoaPyPIProvided[$_woaProvidedKey] | Where-Object { $_ } | Select-Object -Unique)) {
@@ -11656,10 +10649,9 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
}
$env:UNSLOTH_WOA_PYPI_PROVIDED = ($_woaProvidedPairs -join " ")
- # Tauri desktop app bundles its own frontend — skip Node/npm/frontend build
+ # Tauri bundles its own frontend: skip Node/npm/frontend build.
$env:SKIP_STUDIO_FRONTEND = if ($TauriMode) { "1" } else { "0" }
- # Always set STUDIO_LOCAL_INSTALL explicitly to avoid stale values from
- # a previous --local run in the same PowerShell session.
+ # Always set, so a previous --local run in this session cannot leak.
if ($StudioLocalInstall) {
$env:STUDIO_LOCAL_INSTALL = "1"
$env:STUDIO_LOCAL_REPO = $RepoRoot
@@ -11667,9 +10659,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
$env:STUDIO_LOCAL_INSTALL = "0"
Remove-Item Env:STUDIO_LOCAL_REPO -ErrorAction SilentlyContinue
}
- # Use 'studio setup' (not 'studio update') because 'update' pops
- # SKIP_STUDIO_BASE, which would cause redundant package reinstallation
- # and bypass the fast-path version check from PR #4667.
+ # 'studio setup', not 'update': update pops SKIP_STUDIO_BASE and bypasses the fast path (#4667).
$env:UNSLOTH_TAURI_MODE = if ($TauriMode) { "1" } else { "0" }
if ($StudioRedirectMode -eq 'env') {
$env:UNSLOTH_STUDIO_HOME = $StudioHome
@@ -11686,36 +10676,21 @@ sys.exit(2 if conflict else (0 if installed else 1))
$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = (Resolve-Path -LiteralPath $WithLlamaCppDir).Path
}
$env:UNSLOTH_INSTALL_ROLLBACK_MANAGED = "1"
- # Hand the venv interpreter to setup.ps1 so it reuses the Python we already
- # resolved and built the venv with, instead of re-probing the system (which
- # can trip over an unsupported `python` 3.14 or a Store stub on PATH even
- # though the venv is fine). setup.ps1 Test-Path-guards this before use.
+ # Reuse the venv Python rather than re-probe (a 3.14 or Store stub on PATH can trip it).
$env:UNSLOTH_SETUP_PYTHON = Join-Path $VenvDir "Scripts\python.exe"
- # Installer already owns the runtime mutex; the child inherits it rather
- # than deadlocking trying to reacquire it.
+ # The installer holds the runtime mutex; the child inherits it rather than deadlock.
$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
- # The proxy defaults kept out of the discarded profile table, for the duration of the child
- # only. setup.ps1 runs with -NoProfile and downloads on its own; see the prologue.
- #
- # Set even when there is nothing to hand over: its ABSENCE is how the CLI recognises a
- # standalone update and goes looking through the user's profiles. An empty object says "the
- # installer looked, and there is none".
+ # Proxy defaults for the -NoProfile child only. Always set: its absence means a standalone
+ # update, and an empty object means "none".
$env:_UNSLOTH_PS_PROXY_DEFAULTS =
if ($UnslothProxyHandoffJson) { $UnslothProxyHandoffJson } else { '{}' }
- # Forward the arch this run resolved. Both scripts scan WMI, so a scan that answers here but
- # not there leaves setup expecting cpu torch against the ROCm wheels just installed: it
- # reports "needs repair", the installer rolls back, and the app retries that forever.
- #
- # PRIVATE, not UNSLOTH_ROCM_GFX_ARCH: install_llama_prebuilt.py reads that one back as
- # _manual to decide whether a forwarded --rocm-gfx outranks its own probe, and this scan is
- # the weaker of the two anyway (first AMD adapter, no visible-device mask, no shadowing-iGPU
- # repick, all of which setup.ps1 applies). So setup consumes it only after its own probes
- # come up empty, and nested installers never see it.
+ # Forward the resolved arch, or setup expects cpu torch against ROCm wheels and the app retries
+ # rollback forever. PRIVATE, not UNSLOTH_ROCM_GFX_ARCH (install_llama_prebuilt.py reads that as a
+ # manual override); setup uses it only when its own probes come up empty.
if ($ROCmGfxArch) {
$env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF = $ROCmGfxArch
} else {
- # Cleared, not left alone: an inherited value from an outer process is not this run's
- # answer, and handing it down would forward an arch nothing here detected.
+ # Clear an inherited value: nothing here detected it.
Remove-Item Env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF -ErrorAction SilentlyContinue
}
Invoke-ManagedUnslothCli -Python $VenvPython -Arguments $studioArgs
@@ -11781,8 +10756,6 @@ sys.exit(2 if conflict else (0 if installed else 1))
} else {
Remove-Item Env:STUDIO_LOCAL_REPO -ErrorAction SilentlyContinue
}
- # ...and the copy this function holds goes with it, rather than sitting in the frame for
- # the rest of a long install.
$UnslothProxyHandoffJson = $null
if ($hadPreviousLocalLlamaCppDir) {
$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = $previousLocalLlamaCppDir
@@ -11808,9 +10781,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
else { Remove-Item "Env:$($_woaPair[0])" -ErrorAction SilentlyContinue }
}
}
- # $null, not a code: Application Control refused to create the process, so there is
- # no exit code to report. Checked first because in PowerShell $null -ne 0 is true,
- # and the branch below would print "exit code " with nothing after it.
+ # $null: Application Control refused the process. Checked first since $null -ne 0 is true.
if ($null -eq $setupExit) {
return (Exit-InstallFailure (Write-ApplicationControlBlocked -Path $VenvPython))
}
@@ -11833,7 +10804,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
Clear-TauriInstallError "studio setup completed"
# ── Shim dir holds only unsloth.exe; the venv Scripts python.exe would hijack the system. ──
- # Remove the legacy venv Scripts PATH entry that older installers wrote.
+ # Remove the legacy Scripts PATH entry older installers wrote.
$LegacyScriptsDir = Join-Path $VenvDir "Scripts"
try {
$legacyKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
@@ -11873,7 +10844,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
Write-StudioLine " Move or remove it manually, then re-run the installer." -ForegroundColor Yellow
throw "Cannot create unsloth launcher: $ShimExe is a directory."
}
- # try/catch: if unsloth.exe is locked (Unsloth running), keep the old shim.
+ # Locked unsloth.exe (Unsloth running): keep the old shim.
$shimUpdated = $false
try {
if (Test-Path -LiteralPath $ShimExe) { Remove-Item -LiteralPath $ShimExe -Force -ErrorAction Stop }
@@ -11893,25 +10864,17 @@ sys.exit(2 if conflict else (0 if installed else 1))
} else {
Write-StudioLine "[WARN] Could not create unsloth launcher at $ShimExe" -ForegroundColor Yellow
Write-StudioLine " $($_.Exception.Message)" -ForegroundColor Yellow
- # The interpreter, not $UnslothExe: this arm is reached on machines whose
- # policy denies the generated console script, where that advice cannot work.
+ # The interpreter: this arm runs where policy denies the console script.
Write-StudioLine " Until the next successful install, start Unsloth with:" -ForegroundColor Yellow
Write-StudioLine " & '$VenvPython' -I -m unsloth_cli studio -p 8888" -ForegroundColor Yellow
}
}
- # Companion launcher for machines whose policy denies the generated .exe. PATHEXT
- # resolves .EXE ahead of .CMD, so bare `unsloth` still picks the .exe wherever it
- # runs; where it is denied, `unsloth.cmd` is what the user has left.
+ # For machines whose policy denies the .exe; PATHEXT still prefers .EXE elsewhere.
Write-UnslothCmdShim -ShimDir $ShimDir -PythonPath $VenvPython
- # Add to PATH only when a launcher exists. Either one counts: if the .exe could not
- # be hardlinked or copied, or a policy's quarantine removed it, the .cmd beside it
- # is a working launcher and its directory still belongs on PATH. Env-mode:
- # session-only export, no registry change (workspace path may be deleted later).
- # Test-UnslothCmdShimFile, not Test-Path: Write-UnslothCmdShim warns and leaves an
- # unwritable file alone, so a foreign bin\unsloth.cmd in a custom root can survive
- # this run. Counting it would put its directory on PATH and advertise someone
- # else's command as the policy-safe launcher.
+ # PATH only when a launcher exists; the .cmd alone counts (the .exe may have been removed).
+ # Env-mode: session-only. Test-UnslothCmdShimFile, not Test-Path, so a foreign unsloth.cmd that
+ # survived this run is not advertised.
$ShimCmd = Join-Path $ShimDir "unsloth.cmd"
$ShimUsable = (Test-Path -LiteralPath $ShimExe -PathType Leaf) -or
(Test-UnslothCmdShimFile -Path $ShimCmd)
@@ -11935,8 +10898,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
}
- # Env-mode session export AFTER Refresh-SessionPath; otherwise a legacy
- # User PATH entry (Machine > User > current $env:Path) would win.
+ # After Refresh-SessionPath, or a legacy User PATH entry would win.
if ($StudioRedirectMode -eq 'env' -and $ShimUsable) {
$env:Path = "$ShimDir;$env:Path"
step "path" "exported $ShimDir for this session (no registry PATH change in env-override mode)"
@@ -11948,17 +10910,13 @@ sys.exit(2 if conflict else (0 if installed else 1))
return
}
- # New-StudioShortcuts gates the .lnk shortcuts on env-mode internally.
New-StudioShortcuts -ManagedPythonPath $VenvPython -DestinationValidated
- # Compare content hashes so hardlinks and identical copies do not false-trigger.
try {
$_pathCmd = Get-Command unsloth -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($_pathCmd) {
$_pathExe = $_pathCmd.Source
- # This installer's own unsloth.cmd is not a foreign 'unsloth'. It only wins
- # when the .exe beside it is gone, and hashing it against a PE would always
- # differ and always warn.
+ # Our own unsloth.cmd is not foreign; hashing it against a PE would always warn.
$_ourCmdShim = Join-Path $ShimDir "unsloth.cmd"
$_isOurCmdShim = $_pathExe -and
($_pathExe.TrimEnd('\', '/') -ieq $_ourCmdShim.TrimEnd('\', '/'))
@@ -11972,8 +10930,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
substep $UnslothExe
substep "to use this install, call the absolute path above,"
substep "or put its dir earlier on PATH."
- # That absolute path is the generated console script, which is exactly
- # what an Application Control policy denies; name the launcher that works.
+ # That path is the console script a policy denies; name the launcher that works.
if (Test-ShimLaunchBlocked -Path $ShimExe) {
substep "(Windows blocks that file here; use $_ourCmdShim instead)"
}
@@ -11989,21 +10946,17 @@ sys.exit(2 if conflict else (0 if installed else 1))
Write-StudioLine ""
$reply = Read-Host " Start Unsloth Studio now? [Y/n]"
if ([string]::IsNullOrWhiteSpace($reply) -or $reply -match '^[Yy]') {
- # Keep both locks until the process exists: a second installer can
- # then take them, but its scan sees Unsloth before it mutates.
+ # Keep both locks until the process exists, so a second installer's scan sees Unsloth.
$_runtimeGateHandoff = $env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF
try {
$env:_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF = "1"
- # Through the interpreter, not the generated console script: the
- # autostart must not be the one step an Application Control policy
- # can still refuse after a clean install.
+ # Through the interpreter, so autostart is not refused by Application Control.
Set-StudioUvCacheForLaunch -StudioRoot $StudioHome
$studioAutoStartProcess = Start-Process -FilePath $VenvPython `
-ArgumentList (Get-ManagedUnslothCliCommandLine -Arguments @("studio", "-p", "8888")) `
-NoNewWindow -PassThru
- # This inherits the private %TEMP% and outlives the installer, so it,
- # not $PID, is the owner the next sweep must see.
+ # It inherits the private %TEMP% and outlives the installer, so it is the owner the next sweep sees.
if ($null -ne $studioAutoStartProcess) {
Set-StudioPrivateTempOwner -OwnerProcessId $studioAutoStartProcess.Id
}
@@ -12016,9 +10969,7 @@ sys.exit(2 if conflict else (0 if installed else 1))
}
} else {
step "launch" "to start later, run:"
- # PATHEXT resolves .EXE before .CMD, so bare `unsloth` picks the generated
- # console script, which a denying machine cannot run. Probed, not assumed:
- # an unaffected machine must see the line it has always seen.
+ # PATHEXT prefers the .exe a denying machine cannot run. Probed, so others see unchanged text.
if (Test-UnslothCmdShimPreferred -ShimExe $ShimExe -ShimCmd $ShimCmd) {
substep "unsloth.cmd studio -p 8888"
substep "(the generated unsloth.exe is not usable on this machine;"
@@ -12034,15 +10985,11 @@ sys.exit(2 if conflict else (0 if installed else 1))
step "launch" "manual commands:"
# Single-quote printed paths so $-vars in custom roots survive a copy-paste.
$_actLiteral = "'" + ((Join-Path $VenvDir "Scripts\Activate.ps1") -replace "'", "''") + "'"
- # Activating the venv puts Scripts\unsloth.exe first and PATHEXT prefers .EXE,
- # so every bare `unsloth` below is unusable where the policy denies it. Same
- # probe, same reason: unaffected machines must see unchanged text.
+ # Activation puts Scripts\unsloth.exe first; same probe so unaffected machines see unchanged text.
$_shimBlocked = Test-UnslothCmdShimPreferred -ShimExe $ShimExe -ShimCmd $ShimCmd
$_bareLaunch = if ($_shimBlocked) { "unsloth.cmd studio -p 8888" } else { "unsloth studio -p 8888" }
if ($StudioRedirectMode -eq 'env') {
- # Env-mode skips registry PATH; print the absolute shim path. The .cmd
- # beside it goes through the interpreter, so it is the one that works where
- # the policy denies the generated .exe -- named only when it is needed.
+ # Env-mode skips registry PATH: print the absolute shim path, the .cmd only when needed.
$_shimLeaf = if ($_shimBlocked) { "bin\unsloth.cmd" } else { "bin\unsloth.exe" }
$_shim = Join-Path $StudioHome $_shimLeaf
$_shimLiteral = "'" + ($_shim -replace "'", "''") + "'"
@@ -12090,7 +11037,7 @@ $script:TorchOverridesFile = $null
try {
Install-UnslothStudio @args
} finally {
- # The resolver variables exported for the native ARM64 stack are process-scoped, so restore the caller's: their own `uv pip` would otherwise keep resolving with Studio's overrides and wheelhouse.
+ # Restore the caller's resolver variables, or their own `uv pip` keeps Studio's overrides.
if ($script:WoaResolverEnvSaved) {
foreach ($_woaEnvName in @($script:WoaResolverEnvSaved.Keys)) {
$_woaEnvValue = $script:WoaResolverEnvSaved[$_woaEnvName]
diff --git a/install.sh b/install.sh
index 1d70757e820..b1bfcf21cdd 100755
--- a/install.sh
+++ b/install.sh
@@ -4,7 +4,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -e
# ── Why the installer lives in a function ──
-# Under a piped web install, sh is the pipe READER. This file is ~150KB, so a top-level `exit` left most of it unread, the write end failed, and curl tacked "(56) Failure writing output to destination" onto our own error message. Wrapping the body forces sh to parse to the closing brace first, so the pipe always drains. The body is deliberately NOT reindented, and `exit` still exits the shell from inside a function. Do not add `exec < /dev/null`: for a piped shell that closes the script's own source.
+# Body is wrapped in a function so a piped sh reads the whole file before running; an early
+# exit otherwise breaks curl's pipe. Do not add `exec < /dev/null` (closes the piped source).
_unsloth_main() {
# ── Output style (aligned with studio/setup.sh) ──
@@ -40,7 +41,6 @@ _NO_TORCH_FLAG=false
_SKIP_AUTOSTART=false
_ISOLATE_UV_CACHE=false
_NO_ROLLBACK=false
-# Set by the discard itself, so the disk-full remedy can describe what happened rather than what was requested.
_VENV_DISCARDED=false
_VENV_DISCARD_LEFTOVER=""
_INSTALL_SYSTEMD=false
@@ -81,7 +81,6 @@ for arg in "$@"; do
esac
done
-# Env-var equivalents for piped installs; an explicit flag still wins.
case "${UNSLOTH_NO_TORCH:-}" in 1|true|TRUE|yes|YES|on|ON) _NO_TORCH_FLAG=true ;; esac
case "${UNSLOTH_SKIP_AUTOSTART:-}" in 1|true|TRUE|yes|YES|on|ON) _SKIP_AUTOSTART=true ;; esac
case "${UNSLOTH_ISOLATE_UV_CACHE:-}" in 1|true|TRUE|yes|YES|on|ON) _ISOLATE_UV_CACHE=true ;; esac
@@ -93,7 +92,6 @@ if [ "$_VERBOSE" = true ]; then
export UNSLOTH_VERBOSE=1
fi
-# Custom Unsloth roots are unsupported with --tauri unless override == legacy default.
if [ "$TAURI_MODE" = true ]; then
_tauri_canonical_root() (
_tcr_path=$1
@@ -189,12 +187,11 @@ _redact_install_output() {
"$@"
}
-# Large downloads become markers the app consumes and does not display; forwarding uv's own chatter would put dozens of lines in front of the user.
: "${UNSLOTH_DL_MARKER_MIN_BYTES:=52428800}"
-# $1 is the child's output sink: a log file for the quiet path, empty to pass it along stdout for the verbose one. Markers go to stderr to stay clear of the verbose path's redactor, since sed block-buffers and a marker queued behind it would arrive only once the download it announces had finished.
+# Markers go to stderr: the verbose path's sed redactor block-buffers and would delay them.
_uv_download_markers() {
- # Minimal images ship without awk, which the uv version probe below also allows for. This pipe now carries every install command, so a missing awk must cost the markers and nothing else: without this the pipeline closes and the child dies of SIGPIPE.
+ # Minimal images lack awk; without this the pipe closes and the child dies of SIGPIPE.
if ! command -v awk >/dev/null 2>&1; then
if [ -n "$1" ]; then cat >> "$1"; else cat; fi
return
@@ -226,7 +223,6 @@ _uv_download_markers() {
}
run_install_cmd() {
- # Nothing armed (outside mainland China): the plain runner, set -e and all.
if [ -z "${_UNSLOTH_MIRROR_SPARE:-}" ]; then
_run_install_cmd_once "$@"
return
@@ -296,12 +292,11 @@ _run_install_cmd_once() {
done
shift "$_ric_n"
fi
- # For --default-index, clear inherited uv index vars so a uv.toml cannot outrank the CLI pin.
+ # Clear inherited uv index vars so a uv.toml cannot outrank the --default-index pin.
case " $* " in
*" --default-index "*) set -- env -u UV_DEFAULT_INDEX -u UV_INDEX_URL -u UV_INDEX -u UV_EXTRA_INDEX_URL -u UV_TORCH_BACKEND -u UV_FIND_LINKS -u UV_CONFIG_FILE UV_NO_CONFIG=1 "$@" ;;
esac
if _is_verbose; then
- # Stream through the redactor; the rc file carries the exit code (no pipefail in sh).
_rcf=$(mktemp)
tauri_stream_log stdout "OUTPUT_CLEAR" "$_label"
_log=""
@@ -327,7 +322,6 @@ _run_install_cmd_once() {
_log=$(mktemp)
_rcf=$(mktemp)
tauri_stream_log stderr "OUTPUT_CLEAR" "$_label"
- # rc file because the marker filter is a pipe, and plain sh reports only its last stage.
{
if "$@" 2>&1; then
_cmd_rc=0
@@ -351,12 +345,11 @@ _run_install_cmd_once() {
return $_rc
}
-# Returns the last exit code so the set -e rollback trap still fires.
: "${UNSLOTH_INSTALL_RETRIES:=3}"
: "${UNSLOTH_INSTALL_RETRY_DELAY:=3}"
run_install_cmd_retry() {
_ricr_label="$1"
- # Default 3, bounds 1..100 retries and 0..3600s delay; 0?* rejects octal delays.
+ # Bounds 1..100 retries and 0..3600s delay; 0?* rejects octal delays.
case "$UNSLOTH_INSTALL_RETRIES" in
''|*[!0-9]*|0) _ricr_max=3 ;;
*) if [ "${#UNSLOTH_INSTALL_RETRIES}" -le 3 ] && [ "$UNSLOTH_INSTALL_RETRIES" -ge 1 ] 2>/dev/null && [ "$UNSLOTH_INSTALL_RETRIES" -le 100 ] 2>/dev/null; then _ricr_max=$UNSLOTH_INSTALL_RETRIES; else _ricr_max=3; fi ;;
@@ -381,13 +374,13 @@ run_install_cmd_retry() {
done
}
-# True when the runtime target is gfx906 (MI50/Radeon VII): the prebuilt AMD bitsandbytes wheel carries no gfx906 kernels, and force-reinstalling it would clobber a user's source-built bnb, the only 4-bit path on this arch, on every `studio update`. _gfx906_target is set during torch-index resolution; an explicit UNSLOTH_ROCM_GFX_ARCH is honored too so a pinned-index install still skips, normalized (gfx906:sramecc-:xnack- to gfx906) so a copied HIP gcnArchName counts.
+# gfx906: the prebuilt AMD bnb wheel has no gfx906 kernels and would clobber a source-built bnb.
_is_gfx906_bnb_skip() {
[ "${_gfx906_target:-false}" = true ] && return 0
_bnb_gfx_env=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
_bnb_gfx_env=${_bnb_gfx_env%%:*}
[ "$_bnb_gfx_env" = "gfx906" ] && return 0
- # A pinned index (UNSLOTH_TORCH_INDEX_URL/_FAMILY) skips the reroute block that sets _gfx906_target, so a real gfx906 host with a pinned rocm6.3 index and no UNSLOTH_ROCM_GFX_ARCH would otherwise clobber a source-built bnb. Probe here in that gap; skip only when gfx906 is the SOLE distinct arch, mirroring the reroute block's de-dup rule.
+ # A pinned index skips the reroute that sets _gfx906_target, so probe here (sole-arch rule).
if [ -z "$_bnb_gfx_env" ] && [ "${_torch_index_pinned:-false}" = true ]; then
_bnb_gfx_probe=$(_probe_amd_gfx_arch | awk 'NF && !seen[$0]++')
[ "$_bnb_gfx_probe" = "gfx906" ] && return 0
@@ -395,7 +388,7 @@ _is_gfx906_bnb_skip() {
return 1
}
-# `pip install unsloth` resolves its unconditional bitsandbytes dep to a generic CUDA wheel (no gfx906 kernels) once we skip the prebuilt one. Snapshot bnb before the unsloth install, then drop a freshly pulled wheel afterwards while leaving a pre-existing source build in place.
+# pip install unsloth pulls a generic bnb; drop a freshly pulled wheel but keep a source build.
_gfx906_bnb_installed() {
"$_VENV_PY" -c "import importlib.util as u, sys; sys.exit(0 if u.find_spec('bitsandbytes') else 1)" >/dev/null 2>&1
}
@@ -413,11 +406,12 @@ _gfx906_bnb_prune() {
|| "$_VENV_PY" -m pip uninstall -y bitsandbytes >/dev/null 2>&1 || true
}
-# Install bitsandbytes on AMD ROCm hosts. bnb <= 0.49.2 NaNs at 4-bit decode shape on every AMD GPU; the fix (bnb #1887) ships in continuous-release_main and, on PyPI, first in 0.50.0. Keep this floor in step with the amd extra in pyproject.toml and studio/install_python_stack.py.
+# bnb <= 0.49.2 NaNs at 4-bit decode on AMD (bnb #1887). Keep this floor in step with the amd extra
+# in pyproject.toml and studio/install_python_stack.py.
_BNB_ROCM_PYPI_FALLBACK="bitsandbytes>=0.50.0"
-# Intel XPU: separate constant, same floor by coincidence. 0.50.0 manylinux is the first with libbitsandbytes_xpu2025.so / _xpu2026.so; studio/setup.ps1's XPU pass uses the same floor.
+# Intel XPU: 0.50.0 is the first with xpu libs; studio/setup.ps1 uses the same floor.
_BNB_XPU_SPEC="bitsandbytes>=0.50.0"
-# bitsandbytes ships no ROCm binary in its aarch64 wheel at any version: the PyPI 0.50.0 and continuous-release_main aarch64 wheels both carry only libbitsandbytes_cpu.so plus CUDA variants. So neither install path below gives aarch64 a 4-bit backend, and the messages must not claim one.
+# bnb aarch64 wheels carry no ROCm binary at any version, so messages must not claim 4-bit.
_bnb_rocm_arch_has_binary() {
case "$_ARCH" in
aarch64|arm64) return 1 ;;
@@ -442,7 +436,7 @@ _install_bnb_rocm() {
_bnb_whl_url=""
;;
esac
- # uv rejects the pre-release wheel: filename version (1.33.7rc0) does not match metadata (0.50.x.dev0). pip accepts it, so bootstrap pip and use it.
+ # uv rejects this pre-release wheel (filename/metadata version mismatch); pip accepts it.
if ! "$_venv_py" -m pip --version >/dev/null 2>&1; then
if ! run_maybe_quiet "$_venv_py" -m ensurepip --upgrade; then
run_maybe_quiet uv pip install --python "$_venv_py" pip || \
@@ -493,7 +487,6 @@ if [ "$_next_is_llama_cpp_dir" = true ]; then
exit 1
fi
-# Validate --package: a leading letter/digit stops uv parsing it as a flag.
case "$PACKAGE_NAME" in
[!a-zA-Z0-9]*)
echo "❌ ERROR: --package name must start with a letter or digit." >&2
@@ -567,7 +560,6 @@ _tauri_torch_index_family() {
rocm[0-9]*.[0-9]*) echo "$_diag_family" ;;
*) echo "auto" ;;
esac ;;
- # AMD arch-specific index (Strix Halo/Point; torch 2.11+rocm7.13 has the real fix).
*repo.amd.com/rocm/whl/gfx*|*rocm/whl/gfx*) echo "rocm7.13" ;;
"") echo "none" ;;
*) echo "auto" ;;
@@ -586,7 +578,6 @@ _tauri_gpu_branch() {
return
fi
case "$_diag_family" in
- # Require a digit after cu so /current or /custom is not branded CUDA.
cu[0-9]*) echo "cuda" ;;
rocm*)
if [ "$_diag_radeon" = true ]; then
@@ -602,7 +593,7 @@ _tauri_gpu_branch() {
esac
}
-PYTHON_VERSION="" # resolved after platform detection
+PYTHON_VERSION=""
_resolve_studio_destinations() {
_override_var=""
@@ -663,16 +654,8 @@ _resolve_studio_destinations() {
_STUDIO_HOME_REDIRECT=default
}
-# Records which cache this install used, so an update reuses it rather than guessing: the launch below repoints the backend at the Studio cache even in shared mode, so one on-demand install makes an empty Studio cache look full. Never fatal. A relative UV_CACHE_DIR names a different directory in each phase of one install, since uv resolves it against its working directory and setup.sh changes into its own before the dependency pass, so make it absolute once, here.
-# Takes $1, defaulting to UV_CACHE_DIR, and prints it. The scan resolves uv's answer on this
-# same base, so two different bases cannot miss a warm cache.
-# True for a name uv itself creates: <kind>-v<N>, whole suffix numeric. `archive-v0.backup`
-# is not uv's. One rule for the probe and the warmth scan; tightening one is how they drift.
-# uv --no-cache neither reads nor writes a cache: on uv 0.10.7 a caller's UV_CACHE_DIR stays
-# completely empty, CACHEDIR.TAG included. So nothing this install did belongs in the marker,
-# whichever branch chose the directory. Lowercased, since uv takes it case-insensitively; not
-# trimmed, since uv rejects a padded value outright. The literals are clap's BoolishValueParser
-# set, `y` and `t` included. Mirrors _uv_no_cache_requested() in unsloth_cli/commands/studio.py.
+# uv --no-cache neither reads nor writes a cache, so nothing is recorded. Values are clap's
+# BoolishValueParser set. Mirrors _uv_no_cache_requested() in unsloth_cli/commands/studio.py.
_uv_no_cache_requested() {
case "$(printf '%s' "${UV_NO_CACHE:-}" | tr '[:upper:]' '[:lower:]')" in
1|y|yes|t|true|on) return 0 ;;
@@ -685,9 +668,7 @@ _uv_is_bucket_name() {
*-v[0-9]*) ;;
*) return 1 ;;
esac
- # '' too: `##*-v` strips through the LAST `-v`, so `archive-v1-v` leaves an empty suffix
- # that no `*[!0-9]*` matches. It read as a bucket, and one read-only directory named that
- # way condemned a warm cache. Test-StudioUvBucketName rejects it, so the two had split.
+ # '' too: `##*-v` on `archive-v1-v` leaves an empty suffix; Test-StudioUvBucketName rejects it.
case "${1##*-v}" in
''|*[!0-9]*) return 1 ;;
esac
@@ -714,9 +695,7 @@ _absolutize_uv_cache_dir() {
_uv_cache_path="$_uv_cache_base/$_uv_cache_path"
;;
esac
- # A trailing slash names the same directory but compares unequal, and that comparison is
- # what picks `studio` over `shared` below: `$STUDIO_HOME/cache/uv/` would be called shared
- # and get the repoint `studio` avoids. Stops at the root, which is a real directory.
+ # Strip trailing slashes: the studio-vs-shared comparison below is a string compare.
while [ "$_uv_cache_path" != / ]; do
case "$_uv_cache_path" in
*/) _uv_cache_path="${_uv_cache_path%/}" ;;
@@ -732,10 +711,7 @@ _absolutize_uv_cache_dir() {
_uv_cache_root_is_writable() {
mkdir -p "$1" 2>/dev/null || return 1
_uv_root_probe=$(mktemp "$1/.unsloth-write-probe.XXXXXX" 2>/dev/null) || return 1
- # Creating is not enough: an ACL granting create but denying unlink leaves uv's renames
- # to fail later. But GONE is the answer, not rm's exit status -- a scanner holding the
- # handle makes one delete fail and the next succeed, and condemning the cache on the first
- # failure sends the install to a fallback that may be worse. Retry, then believe the fs.
+ # Retry the unlink and trust whether the file is gone: a held handle can make rm fail once.
_uv_root_tries=0
while :; do
rm -f "$_uv_root_probe" 2>/dev/null || true
@@ -751,15 +727,11 @@ _uv_cache_root_is_writable() {
return 0
}
-# The root AND every bucket uv would rename into. _uv_cache_root_is_writable answers only for
-# the directory itself, which is not enough once uv has made buckets in it: a `sudo` run leaves
-# one root-owned, and a dangling link is an existing path to mkdir(2), so uv aborts on a cache
-# whose root we can write perfectly well.
+# Also check every bucket: a root-owned bucket from an elevated run makes uv abort.
_uv_cache_is_writable() {
_uv_cache_root_is_writable "$1" || return 1
_uv_w_bad=0
- # Measured, not assumed: default APFS folds, ext4 does not, and an existing `Python-V0`
- # beside `python-v0` is one entry on the first and two on the second. Root already writable.
+ # Case folding is filesystem-dependent (APFS folds, ext4 does not), so measure it.
_uv_w_fold=0
_uv_w_probe="$1/.unsloth-case-probe.$$-A"
if mkdir "$_uv_w_probe" 2>/dev/null; then
@@ -773,14 +745,12 @@ _uv_cache_is_writable() {
for _uv_w_dir in "$1"/*; do
_uv_w_name="${_uv_w_dir##*/}"
if ! _uv_is_bucket_name "$_uv_w_name"; then
- # Only the NAME is folded here; file or dangling link is the rejection below.
[ "$_uv_w_fold" = 1 ] || continue
case "$_uv_w_name" in *[[:upper:]]*) ;; *) continue ;; esac
_uv_w_lower=$(printf '%s' "$_uv_w_name" | tr '[:upper:]' '[:lower:]')
_uv_is_bucket_name "$_uv_w_lower" || continue
fi
if [ ! -d "$_uv_w_dir" ]; then
- # A file, or a symlink dangling or not, is an existing path to mkdir(2).
if [ -e "$_uv_w_dir" ] || [ -L "$_uv_w_dir" ]; then
_uv_w_bad=1
fi
@@ -798,16 +768,15 @@ _uv_cache_is_writable() {
return 0
}
+# Records which cache this install used so an update reuses it. UV_CACHE_DIR is made absolute
+# because setup.sh changes directory.
_record_uv_cache_choice() {
- # In place, before anything reads it: every branch records, so this is the one point every phase of the install and the marker are made to agree on one directory.
UV_CACHE_DIR=$(_absolutize_uv_cache_dir)
_uv_marker_dir="$STUDIO_HOME/cache"
_uv_marker_file="$_uv_marker_dir/uv-cache-dir"
_uv_marker_value="$UV_CACHE_DIR"
- # Remembered so a failed install can put it back.
if [ "$_UV_MARKER_SAVED" != true ]; then
if [ -e "$_uv_marker_file" ] || [ -L "$_uv_marker_file" ]; then
- # One we cannot read is one we cannot put back, so leave it alone.
_UV_MARKER_PREVIOUS=$(cat "$_uv_marker_file" 2>/dev/null) || return 0
_UV_MARKER_EXISTED=true
else
@@ -818,7 +787,7 @@ _record_uv_cache_choice() {
fi
(
mkdir -p "$_uv_marker_dir" 2>/dev/null &&
- # Unlinked first: a redirection follows a symlink and truncates its target.
+ # Unlink first: a redirection follows a symlink and truncates its target.
rm -f "$_uv_marker_file" 2>/dev/null &&
# And only once gone: rm can fail on a link in an undeletable directory.
! { [ -e "$_uv_marker_file" ] || [ -L "$_uv_marker_file" ]; } &&
@@ -840,9 +809,7 @@ _restore_uv_cache_marker() {
_configure_uv_cache() {
_uv_studio_cache="$STUDIO_HOME/cache/uv"
- # A CALLER's UV_CACHE_DIR outranks everything below; our own default must not, and the
- # variable cannot tell them apart because the block above already exported it. Without the
- # flag this matched on every writable install, so nothing below ever ran.
+ # Only a caller's UV_CACHE_DIR outranks selection; the flag tells it apart from our default.
if [ "${_UV_CACHE_DIR_INSTALLER_DEFAULT:-false}" != true ]; then
case "${UV_CACHE_DIR-}" in
*[![:space:]]*)
@@ -851,7 +818,6 @@ _configure_uv_cache() {
if _uv_no_cache_requested; then
step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR); uv caching is off (UV_NO_CACHE), so nothing is recorded"
else
- # Recorded like any other choice; a caller still outranks the marker.
_record_uv_cache_choice
step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR)"
fi
@@ -869,7 +835,6 @@ _configure_uv_cache() {
return 0
fi
- # Nothing to select either: probing would touch a cache the caller told uv to leave alone.
if _uv_no_cache_requested; then
UV_CACHE_DIR="$_uv_studio_cache"
_UV_CACHE_MODE=studio
@@ -878,7 +843,7 @@ _configure_uv_cache() {
return 0
fi
- # Ask uv so uv.toml / UV_CONFIG_FILE / platform defaults count; -u so a blank inherited value cannot override them; last line so a notice ahead of the path does not become the path.
+ # Ask uv so uv.toml / UV_CONFIG_FILE count; take the last line so a notice is not the path.
_uv_default_cache=$(env -u UV_CACHE_DIR uv cache dir 2>/dev/null \
| sed -e 's/[[:space:]]*$//' -e '/^$/d' | tail -n 1) || _uv_default_cache=""
if [ -z "$_uv_default_cache" ]; then
@@ -888,22 +853,12 @@ _configure_uv_cache() {
_uv_default_cache="${HOME}/.cache/uv"
fi
fi
- # A relative cache-dir comes back verbatim and uv resolves it against its working
- # directory, so scanning it as written inspects a same-named directory beside us.
if [ -n "$_uv_default_cache" ]; then
_uv_default_cache=$(_absolutize_uv_cache_dir "$_uv_default_cache")
fi
- # The cache THIS install last recorded outranks uv's default while it is still warm, or a
- # rerun abandons a Studio cache holding Torch and CUDA the moment one unrelated wheel makes
- # uv's default read as warm. Content cannot decide it, because the repoint below leaves
- # backend bytes in the losing cache; that is what the marker is for. Same precedence as
- # unsloth_cli/commands/studio.py:_with_studio_uv_cache.
- # install.ps1 writes this with -Encoding utf8, which under PowerShell 5.1 means BOM and
- # CRLF, and a WSL install shares $STUDIO_HOME with the Windows one. The other two readers
- # already defend. Untreated, a CR fails [ -d ] and abandons the warm cache in silence, and
- # a BOM makes the value non-absolute so $PWD gets prepended.
- # Trailing CR only, like Read-StudioUvCacheMarker's Trim(): `tr -d` ate CRs inside the path.
+ # The recorded cache outranks uv's default while warm (same as studio.py _with_studio_uv_cache).
+ # Strip BOM and trailing CR: install.ps1 writes it with PowerShell 5.1 utf8 under WSL.
_uv_recorded=$(cat "$STUDIO_HOME/cache/uv-cache-dir" 2>/dev/null) || _uv_recorded=""
_uv_cr=$(printf '\r')
_uv_recorded="${_uv_recorded%"$_uv_cr"}"
@@ -916,24 +871,14 @@ _configure_uv_cache() {
*) _uv_recorded="" ;;
esac
- # An install from before the marker has a populated $STUDIO_HOME/cache/uv and nothing
- # recording it, so it is worth keeping rather than abandoning for uv's default. But it goes
- # LAST, behind uv's default, because content cannot prove whose it is: the marker arrived in
- # b66d2a4c8 on 2026-09-06 and the early block only in e12963071 the day after, so an install
- # old enough to have no marker is old enough that `shared` was reachable, and in that mode
- # the launch repoint leaves backend wheels in the Studio cache while Torch and CUDA sit in
- # the default. Ordering it ahead of the default picked those leftovers and redownloaded
- # gigabytes. Behind it, a warm Studio cache still wins whenever the default is cold, which
- # is the install this was added for. A marker naming a directory that is gone is a stale
- # pointer rather than a decision, so it lands in the same place.
+ # A pre-marker $STUDIO_HOME/cache/uv goes LAST, behind uv's default: its content may be
+ # leftover backend wheels while Torch and CUDA live in the default.
_uv_unmarked_studio=""
if [ -z "$_uv_recorded" ] || [ ! -d "$_uv_recorded" ]; then
_uv_unmarked_studio="$_uv_studio_cache"
fi
- # Readable is not usable: uv writes CACHEDIR.TAG into the root and renames distributions
- # into the buckets, aborting on either. Nested entries are deliberately NOT probed: that
- # walks hundreds of thousands of files, and a denied leaf keeps a warm cache warm.
+ # Root and buckets must be writable; nested entries are not probed (too many files).
_uv_scan_blocked=false
_uv_blocked_cache=""
_uv_warn_cache=""
@@ -943,17 +888,14 @@ _configure_uv_cache() {
_uv_cand_populated=false
_uv_cand_writable=true
if [ -d "$_uv_candidate" ] && [ -r "$_uv_candidate" ]; then
- # The globs below ARE the scan, so a caller's set -f reads every cache as empty.
+ # The globs below are the scan, so a caller's set -f would read every cache as empty.
_uv_glob=on
case $- in *f*) _uv_glob=off ;; esac
set +f
- # Root and every bucket, through the one helper the fallback and the launch
- # repoint also use, so a cache rejected here cannot be handed back later.
_uv_cache_is_writable "$_uv_candidate" || _uv_cand_writable=false
- # Warm means package BYTES: wheels-* is metadata only (.msgpack/.http on uv
- # 0.10), so a bare `--dry-run` used to read as warm. -L to match Get-ChildItem.
+ # Warm means package bytes: wheels-* holds metadata only. -L to match Get-ChildItem.
for _uv_bucket in \
"$_uv_candidate"/archive-* \
"$_uv_candidate"/builds-* \
@@ -961,24 +903,19 @@ _configure_uv_cache() {
"$_uv_candidate"/wheels-* \
"$_uv_candidate"/sdists-*; do
[ -d "$_uv_bucket" ] || continue
- # Stricter than the probe above, deliberately: the KIND must be one uv fills,
- # since `archive-*` also matches `archive-v0.backup`, whose bytes uv cannot
- # reuse. Missing a future kind here costs a fallback; missing one in the PROBE
- # would let an unwritable cache through, so that stays on the open pattern.
+ # Stricter than the probe: only kinds uv fills count (`archive-v0.backup` does not).
_uv_bucket_base="${_uv_bucket##*/}"
_uv_is_bucket_name "$_uv_bucket_base" || continue
case "${_uv_bucket_base%-v*}" in
archive|builds|built-wheels|wheels|sdists) ;;
*) continue ;;
esac
- # Unreadable is not empty; remembered so the message below says why.
if [ ! -r "$_uv_bucket" ] || [ ! -x "$_uv_bucket" ]; then
_uv_scan_blocked=true
[ -n "$_uv_blocked_cache" ] || _uv_blocked_cache="$_uv_candidate"
continue
fi
- # `|| true`: head closes the pipe, so find dies on SIGPIPE on a large bucket,
- # and under pipefail that cleared the path it had already printed.
+ # `|| true`: head closes the pipe and find's SIGPIPE under pipefail would drop the path.
_uv_artifact=$(find -L "$_uv_bucket" -type f \
! -name CACHEDIR.TAG ! -name .git ! -name .gitignore \
! -name '.unsloth-write-probe.*' \
@@ -1002,8 +939,6 @@ _configure_uv_cache() {
if [ -n "$_uv_chosen_cache" ]; then
UV_CACHE_DIR="$_uv_chosen_cache"
- # studio, not shared, when the choice IS the Studio cache: the launch repoint below
- # only has to move a cache that is not already ours.
if [ "$_uv_chosen_cache" = "$_uv_studio_cache" ]; then
_UV_CACHE_MODE=studio
else
@@ -1012,18 +947,8 @@ _configure_uv_cache() {
else
UV_CACHE_DIR="$_uv_studio_cache"
_UV_CACHE_MODE=studio
- # A fallback we cannot write is not a fallback. The early block has ALREADY given up
- # on $STUDIO_HOME/cache/uv, which is the only reason the selection is running, and the
- # root can be writable while a bucket uv renames into is not, which the probe rejected
- # a candidate for. Landing there turns a working install into a uv error, so anything
- # usable beats it: the populated cache that only failed the probe first, since the
- # certain failure and the merely suspect cache are both on the table, then uv's own
- # default, which at worst costs the downloads this cache was never going to save.
+ # An unwritable Studio cache is no fallback: prefer the warm suspect cache, then uv's default.
if ! _uv_cache_is_writable "$_uv_studio_cache"; then
- # A cache that is WARM and merely failed the probe beats a cold one we can write:
- # the probe refuses a whole cache for one bucket-shaped entry uv may never touch,
- # where a cold cache guarantees the downloads, and offline guarantees failure. That
- # holds when the refused cache is the Studio cache itself.
if [ -n "$_uv_warn_cache" ]; then
UV_CACHE_DIR="$_uv_warn_cache"
if [ "$_uv_warn_cache" != "$_uv_studio_cache" ]; then
@@ -1048,12 +973,8 @@ _configure_uv_cache() {
studio)
if [ -n "$_uv_chosen_cache" ]; then
step "uv cache" "reusing this install's Unsloth Studio cache ($UV_CACHE_DIR)"
- # Never about the directory we are falling back TO: the Studio cache is itself a
- # candidate now, so it can be the one refused, and naming it claims a fallback
- # that did not happen.
elif [ "$_uv_scan_blocked" = true ] && [ "$_uv_blocked_cache" != "$UV_CACHE_DIR" ]; then
step "uv cache" "using new Unsloth Studio-owned cache ($UV_CACHE_DIR); part of $_uv_blocked_cache could not be read, so cached packages may download again" "$C_WARN"
- # Warm and still here means the write probe refused it.
elif [ -n "$_uv_warn_cache" ] && [ "$_uv_warn_cache" != "$UV_CACHE_DIR" ]; then
step "uv cache" "using new Unsloth Studio-owned cache ($UV_CACHE_DIR); $_uv_warn_cache is populated but not writable, so cached packages may download again" "$C_WARN"
else
@@ -1065,12 +986,7 @@ _configure_uv_cache() {
_prepare_studio_uv_cache_for_launch() {
[ "${_UV_CACHE_MODE:-}" = shared ] || return 0
- # Only to a cache the backend can fill. shared is reachable exactly when the early block
- # failed its write probe on $STUDIO_HOME/cache/uv, so repointing unconditionally hands the
- # autostarted backend a cache uv aborts on, after an install that succeeded. Keeping the
- # shared one is honest: it is the cache this install just filled.
- # Root AND buckets, the same rule the selection used: a root-only check repoints into the
- # very cache the candidate probe rejected for a bucket uv cannot rename into.
+ # Repoint the backend only to a cache whose root AND buckets are writable.
_uv_launch_cache="$STUDIO_HOME/cache/uv"
_uv_cache_is_writable "$_uv_launch_cache" || return 0
UV_CACHE_DIR="$_uv_launch_cache"
@@ -1087,17 +1003,8 @@ fi
_UNSLOTH_LOGIN_PATH="$PATH"
VENV_DIR="$STUDIO_HOME/unsloth_studio"
-# Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's own
-# marker all land inside $STUDIO_HOME, so an install that dies in between used to leave a
-# directory the uninstaller could only identify by guessing at leftovers. Never fatal.
-#
-# Only a root this run may take over: in env mode $STUDIO_HOME is a user-chosen workspace, so an
-# empty one, or one already carrying an unambiguous marker, and nothing else, or a run that
-# aborts at the venv-step guard leaves somebody's project marked. Shorter than that guard's list
-# on purpose: it only refuses to overwrite, this authorizes a delete, so no bin/unsloth.
-# A sentinel this list may trust: a regular file, never a link, never inside a linked directory
-# ($2). -f follows a link and -L answers for the named file only, so a planted marker or a linked
-# `share` holding a genuine one would otherwise short-circuit the emptiness test below.
+# Claim the root before writing into it, but only one this run may take over (env mode is a
+# user workspace). A sentinel counts only as a regular non-link file outside linked dirs.
_claim_sentinel() {
[ -f "$1" ] || return 1
[ -L "$1" ] && return 1
@@ -1107,18 +1014,13 @@ _claim_sentinel() {
_claim_studio_root() {
_claim_marker="$STUDIO_HOME/.unsloth-studio-owned"
- # Already ours and the right shape: leave it. A run killed between the unlink and the write
- # would lose the only proof this root is ours.
+ # Leave a valid marker alone: a kill between unlink and write would lose the proof.
_claim_sentinel "$_claim_marker" && return 0
if [ "$_STUDIO_HOME_REDIRECT" = "env" ] \
&& ! _claim_sentinel "$VENV_DIR/.unsloth-studio-owned" "$VENV_DIR" \
&& ! _claim_sentinel "$STUDIO_HOME/share/studio.conf" "$STUDIO_HOME/share"; then
if [ -d "$STUDIO_HOME" ]; then
- # Not enumerable: without read the globs cannot expand and an occupied workspace
- # reads as empty. Fail closed like _dir_has_entries.
{ [ -r "$STUDIO_HOME" ] && [ -x "$STUDIO_HOME" ]; } || return 0
- # The globs ARE the emptiness check, so a caller's `sh -f` would make every workspace
- # look empty. Saved and restored like _dir_has_entries.
_claim_glob=on
case $- in *f*) _claim_glob=off ;; esac
set +f
@@ -1131,9 +1033,7 @@ _claim_studio_root() {
fi
fi
mkdir -p "$STUDIO_HOME" 2>/dev/null || true
- # Unlink first, then confirm it: the redirection follows a symlink here and truncates its
- # TARGET, and rm can fail on a root we cannot write while that target stays writable. No
- # marker is fine; the venv writes its own later.
+ # Unlink first: the redirection would follow a symlink and truncate its target.
rm -f "$_claim_marker" 2>/dev/null || true
if [ -e "$_claim_marker" ] || [ -L "$_claim_marker" ]; then return 0; fi
printf '' > "$_claim_marker" 2>/dev/null || true
@@ -1150,8 +1050,6 @@ if [ -z "${UV_CACHE_DIR:-}" ]; then
UV_CACHE_DIR="$STUDIO_HOME/cache/uv"
export UV_CACHE_DIR
_UV_CACHE_DIR_INSTALLER_DEFAULT=true
- # The same question the selection asks later, through the same helper, so the two answers
- # cannot drift apart.
if ! _uv_cache_root_is_writable "$UV_CACHE_DIR"; then
echo "[WARN] Cannot write to $UV_CACHE_DIR -- using uv's default cache." >&2
echo "[WARN] Wheels will be copied into the venv rather than hardlinked, costing extra disk." >&2
@@ -1162,11 +1060,10 @@ fi
_VENV_ROLLBACK_DIR=""
_VENV_ROLLBACK_TARGET="$VENV_DIR"
_VENV_ROLLBACK_ACTIVE=false
-# The marker travels with the environment. See _record_uv_cache_choice.
_UV_MARKER_SAVED=false
_UV_MARKER_EXISTED=false
_UV_MARKER_PREVIOUS=""
-# One flag for both rollbacks: two leave a window either way round, where a signal restores half a committed install.
+# One flag for both rollbacks so a signal cannot restore half a committed install.
_STUDIO_INSTALL_COMMITTED=false
_start_studio_venv_replacement() {
@@ -1181,18 +1078,19 @@ _start_studio_venv_replacement() {
_VENV_ROLLBACK_DIR="$_candidate"
_VENV_ROLLBACK_TARGET="$_existing_dir"
_VENV_ROLLBACK_ACTIVE=true
- # Publish the rollback state before the atomic rename so a signal cannot land after mv but before the exit handlers know where the old venv went.
+ # Publish rollback state before the rename so a signal after mv still finds the old venv.
if ! mv "$_existing_dir" "$_candidate"; then
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
return 1
fi
- # --no-rollback / UNSLOTH_INSTALL_NO_ROLLBACK: drop the old environment now instead of at commit, for the disk-constrained cross-volume case. The rename still happens first, so uv never builds into an occupied path. Clearing the state before the delete is what the commit path does too: a signal must not restore a half-deleted backup.
+ # --no-rollback: drop the old env now. Clear rollback state first so a signal cannot restore
+ # a half-deleted backup.
if [ "${_NO_ROLLBACK:-false}" = true ]; then
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
rm -rf "$_candidate" 2>/dev/null || true
- # -f exempts a missing path from the exit status, not a real unlink failure: an immutable entry, a busy mount point, a sticky-bit parent. Reporting "discarded" there promises space that was never freed, in the one situation this flag exists for. The state above stays cleared either way -- re-arming the rollback would hand an interrupt a half-deleted backup -- so say what is actually on disk.
+ # rm -f can fail (immutable, busy mount): report what is on disk; never re-arm rollback.
if [ -e "$_candidate" ] || [ -L "$_candidate" ]; then
_VENV_DISCARD_LEFTOVER="$_candidate"
substep "could not discard the previous environment at $_candidate" "$C_WARN"
@@ -1210,7 +1108,7 @@ _free_space_kb() { # path
df -Pk "$1" 2>/dev/null | awk 'NR == 2 { print $4 }'
}
-# Sets _DISK_FULL_SUFFIX to a one-line diagnosis, or empty. Below 64 MiB nothing useful can be unpacked, so a full disk is the cause rather than a coincidence (#11313). Callers fold the suffix into the ERROR_DEFAULT message as well as printing it, because under --tauri the desktop app reads that message and a diagnosis printed only beside it is one the UI never shows.
+# Below 64 MiB a full disk is the cause. Fold the suffix into ERROR_DEFAULT: --tauri UI shows only that.
_set_disk_full_suffix() {
_DISK_FULL_SUFFIX=""
_DISK_FULL_REMEDY=""
@@ -1220,13 +1118,12 @@ _set_disk_full_suffix() {
[ -n "$_dfs_free" ] || return 0
[ "$_dfs_free" -lt 65536 ] 2>/dev/null || return 0
_DISK_FULL_MB=$((_dfs_free / 1024))
- # What to advise depends on what actually happened to the old environment, not on what was asked for. A discard that failed left a tree behind, and deleting that tree is very likely what makes the retry fit; telling that user there is nothing left to reclaim sends them away from the one thing that would help.
+ # A failed discard left a tree behind; deleting it is likely what makes a retry fit.
if [ -n "${_VENV_DISCARD_LEFTOVER:-}" ]; then
_DISK_FULL_REMEDY="Free some space and re-run. The previous environment could not be removed and is still at $_VENV_DISCARD_LEFTOVER; deleting it will reclaim that space."
elif [ "${_VENV_DISCARDED:-false}" = true ]; then
_DISK_FULL_REMEDY="Free some space and re-run. The previous environment was already discarded by --no-rollback, so the installer has nothing further of its own to reclaim."
elif [ "${_NO_ROLLBACK:-false}" = true ]; then
- # Asked for, but nothing was there to discard: a first install, or a failure before the replacement began. Naming the flag again would describe a re-run that changes nothing.
_DISK_FULL_REMEDY="Free some space and re-run."
else
_DISK_FULL_REMEDY="Free some space and re-run. --no-rollback (UNSLOTH_INSTALL_NO_ROLLBACK=1) drops the previous environment instead of keeping a copy of it during the install."
@@ -1234,16 +1131,15 @@ _set_disk_full_suffix() {
_DISK_FULL_SUFFIX=": $STUDIO_HOME has only $_DISK_FULL_MB MB free, so the disk is full, which is very likely the cause. $_DISK_FULL_REMEDY"
}
-# uv creates only into a path that is absent or an empty directory. Everything else is occupied, hidden entries and non-resolving symlinks included.
+# uv creates only into an absent path or empty dir; hidden entries and dangling links count.
_dir_has_entries() { # dir
if [ ! -d "$1" ]; then
- # Still an existing path to mkdir(2), which answers EEXIST for a file or for a symlink "dangling or not", so uv refuses it too. -d follows the link and -e misses a dangling one, hence the -L.
+ # -L too: mkdir(2) gives EEXIST for a dangling symlink, which -e misses.
{ [ -e "$1" ] || [ -L "$1" ]; } && return 0
return 1
fi
- # Not enumerable: the globs cannot expand without read, and the tests below fail on every name without search, so it would read as empty. Fail closed like install.ps1's catch; the rename only needs write on the parent.
+ # Unreadable dirs cannot be enumerated and would look empty; fail closed like install.ps1.
{ [ -r "$1" ] && [ -x "$1" ]; } || return 0
- # The globs are the whole check, so a caller's set -f would make every directory look empty. Mirrors _path_has_dir, which saves the flag too.
_dhe_glob=on
case $- in *f*) _dhe_glob=off ;; esac
set +f
@@ -1281,10 +1177,8 @@ _discard_venv_for_recreate() { # venv dir
}
_restore_studio_venv_replacement() {
- # The flag the marker restore consults too, so a signal mid-commit cannot split them.
[ "${_STUDIO_INSTALL_COMMITTED:-false}" = true ] && return 0
[ "$_VENV_ROLLBACK_ACTIVE" = true ] || return 0
- # -e/-L, not -d: a rollback holds whatever _dir_has_entries called occupied, and -d would drop a file or a dangling link and strand the original.
[ -n "$_VENV_ROLLBACK_DIR" ] \
&& { [ -e "$_VENV_ROLLBACK_DIR" ] || [ -L "$_VENV_ROLLBACK_DIR" ]; } || {
_VENV_ROLLBACK_ACTIVE=false
@@ -1306,7 +1200,6 @@ _studio_venv_rollback_must_be_preserved() {
_rollback_metadata=${_rollback_name#unsloth_studio.rollback.}
_rollback_stamp=${_rollback_metadata%%.*}
_rollback_process=${_rollback_metadata#*.}
- # Preserve anything outside the installer's timestamp.PID[.suffix] format.
[ "$_rollback_process" != "$_rollback_metadata" ] || return 0
case "$_rollback_stamp" in
time) ;;
@@ -1331,7 +1224,6 @@ _prune_stale_studio_venv_rollbacks() {
echo "⚠️ Refusing to remove rollback symlink $_stale_rollback" >&2
continue
fi
- # A concurrent installer may have moved its live venv aside. The PID in the generated name keeps this successful run from deleting its rescue copy.
_studio_venv_rollback_must_be_preserved "$_stale_rollback" && continue
if rm -rf "$_stale_rollback"; then
substep "removed stale environment rollback ${_stale_rollback##*/}"
@@ -1342,15 +1234,14 @@ _prune_stale_studio_venv_rollbacks() {
}
_commit_studio_venv_replacement() {
- # First and alone, because a signal can land between any two statements. A first install rolls nothing back and still commits.
+ # First and alone, because a signal can land between any two statements.
_STUDIO_INSTALL_COMMITTED=true
_UV_MARKER_SAVED=false
if [ "$_VENV_ROLLBACK_ACTIVE" = true ]; then
_rollback_to_remove="$_VENV_ROLLBACK_DIR"
- # The new environment is already committed. Clear the restore state before deletion so an interrupt cannot replace it with a half-deleted backup.
+ # Clear restore state before deleting so an interrupt cannot restore a half-deleted backup.
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
- # Same shapes as the restore, or such a backup is never cleaned up.
if [ -n "$_rollback_to_remove" ] \
&& { [ -e "$_rollback_to_remove" ] || [ -L "$_rollback_to_remove" ]; }; then
if ! rm -rf "$_rollback_to_remove"; then
@@ -1358,7 +1249,7 @@ _commit_studio_venv_replacement() {
fi
fi
fi
- # Only prune older orphaned copies after the replacement has succeeded, so an interrupted install never discards the last known-good environment.
+ # Prune only after success so an interrupted install keeps the last known-good env.
_prune_stale_studio_venv_rollbacks
}
@@ -1367,17 +1258,15 @@ _cleanup_install_temporaries() {
[ -n "${_UV_INSTALL_NAME_TOOL_SHIM_DIR:-}" ] && rm -rf "$_UV_INSTALL_NAME_TOOL_SHIM_DIR" 2>/dev/null || true
[ -n "${_UV_VENV_CAPTURE_DIR:-}" ] && rm -rf "$_UV_VENV_CAPTURE_DIR" 2>/dev/null || true
[ -n "${_UNSLOTH_TORCH_OVERRIDES:-}" ] && rm -f "$_UNSLOTH_TORCH_OVERRIDES" 2>/dev/null || true
- # The pinned uv path's own cleanup only runs when that function returns, so a Ctrl-C left the unpacked archive behind plus a staging file inside a directory that is on PATH.
+ # The pinned uv path's cleanup runs only on return; a Ctrl-C would leave staging files on PATH.
[ -n "${_UIP_WORK:-}" ] && rm -rf "$_UIP_WORK" 2>/dev/null || true
[ -n "${_UIP_STAGE:-}" ] && rm -f "$_UIP_STAGE" 2>/dev/null || true
[ -n "${_UIP_STAGE2:-}" ] && rm -f "$_UIP_STAGE2" 2>/dev/null || true
[ -n "${_ROCM_TAG_MEMO_DIR:-}" ] && rm -rf "$_ROCM_TAG_MEMO_DIR" 2>/dev/null || true
[ -n "${_ric_log:-}" ] && rm -f "$_ric_log" 2>/dev/null || true
- # The probe's ceiling is held by this shell, so a cancel during one would otherwise leave the
- # candidate (and, under monitor mode, its whole group) running with nobody left to stop it.
+ # This shell holds the probe's ceiling; kill the probe on cancel or it runs on.
if [ -n "${_UV_PROBE_TARGET:-}" ] && [ -n "${_UV_PROBE_PID:-}" ]; then
- # Two seconds, not the ceiling's five: a cancel that waited that long on a binary
- # ignoring TERM would read as an installer ignoring the cancel.
+ # Two seconds so a cancel does not look ignored.
_uv_probe_terminate "$_UV_PROBE_TARGET" "$_UV_PROBE_PID" 2
_UV_PROBE_TARGET=""
_UV_PROBE_PID=""
@@ -1387,19 +1276,14 @@ _cleanup_install_temporaries() {
_on_install_exit() {
_status=$?
if [ "$_status" -ne 0 ]; then
- # Restoring comes first, and nothing below it may be able to prevent it. Putting the
- # diagnosis ahead of this put a pair of writes under `set -e` in front of the only code
- # that puts the user's environment back: a closed --tauri stdout, or a redirected stderr,
- # fails the write, and the trap then aborts with the previous environment still moved
- # aside. A diagnostic must never be able to cost someone their install.
- # Measured here and reported further down, which is not the same thing as doing both in one place. The restore immediately below deletes the half-built replacement, and that can free gigabytes: ask afterwards and a disk that really was full reads as healthy, so the early failure it just caused goes back to being a bare exit code. `|| true` because a measurement must not be able to abort the restore either.
+ # Restore must come first and nothing may prevent it (a failed write under set -e would abort).
+ # Disk is measured before the restore, which can free gigabytes; `|| true` so it cannot abort.
if [ "${_DISK_FULL_REPORTED:-false}" != true ] && command -v _set_disk_full_suffix >/dev/null 2>&1; then
_set_disk_full_suffix || true
fi
_restore_studio_venv_replacement
- # Separate from the venv restore: an install can fail before one is in flight.
_restore_uv_cache_marker
- # Every earlier failure lands here, and the largest writes -- the venv and the torch install -- are all earlier, so a disk that filled during them used to surface as a bare exit code (#11313). Written only after the restore, and every write `|| true`, because a closed --tauri stdout must not abort the trap before the environment is back.
+ # Written after the restore, every write `|| true`: a closed --tauri stdout must not abort the trap.
if [ "${_DISK_FULL_REPORTED:-false}" != true ] && [ -n "${_DISK_FULL_SUFFIX:-}" ]; then
tauri_log "ERROR_DEFAULT" "unsloth studio install failed (exit code $_status)$_DISK_FULL_SUFFIX" || true
echo " $STUDIO_HOME has only $_DISK_FULL_MB MB free -- the disk is full, which is very likely the cause." >&2 || true
@@ -1412,7 +1296,6 @@ _on_install_exit() {
_on_install_signal() {
_signal_status="$1"
- # EXIT is disabled to avoid a second cleanup pass. Ignore further termination signals until the old environment is back in place.
trap - EXIT
trap '' HUP INT TERM
_restore_studio_venv_replacement
@@ -1465,9 +1348,9 @@ _is_pkg_installed() {
}
# ── Helper: human-readable apt distro label for the sudo package prompt (#6207) ──
-# Reads /etc/os-release so the Accept? prompt can say which distro we detected and that packages come from that distro's official apt repos, not a tarball.
+# Distro label for the elevation prompt (#6207), read from /etc/os-release.
_apt_distro_description() {
- # Plain ( ... ) subshell, not $(), so case/;; stays bash-3.2-safe on macOS: bash 3.2 misparses case arms inside command substitution and errors on `;;`.
+ # Plain ( ... ) subshell, not $(): bash 3.2 misparses case `;;` inside command substitution.
(
if [ ! -r /etc/os-release ]; then
printf 'a debian-like system'
@@ -1493,13 +1376,12 @@ _apt_distro_description() {
}
# ── Helper: can the controlling terminal actually be opened for reading? ──
-# `test -r` only checks permission bits, which look fine in containers and systemd units where open() then fails with ENXIO, so probe with a real open. The subshell is required: in dash a failed redirection on the special builtin `:` exits the whole script.
+# `test -r` passes in containers where open() fails with ENXIO, so probe with a real open.
+# Subshell required: in dash a failed redirection on `:` exits the script.
_can_read_tty() {
( : </dev/tty ) >/dev/null 2>&1
}
-# Checkout copy only for a trusted --local run: a piped install's _REPO_ROOT is the caller's cwd,
-# and -I keeps that cwd off sys.path for the installed-package lookup.
_resolve_systemd_install_script() {
if [ "$_REPO_IS_CHECKOUT" = "1" ] && [ -f "$_REPO_ROOT/studio/systemd/install_user_service.sh" ]; then
printf '%s\n' "$_REPO_ROOT/studio/systemd/install_user_service.sh"
@@ -1511,7 +1393,6 @@ _resolve_systemd_install_script() {
2>/dev/null || true
}
-# Only with UNSLOTH_INSTALL_SYSTEMD set; without it the install is unchanged.
_install_systemd_user_service() {
case "$OS" in
linux|wsl) ;;
@@ -1525,7 +1406,6 @@ _install_systemd_user_service() {
set -- --unsloth-exe "$VENV_DIR/bin/unsloth" \
--host "${UNSLOTH_SYSTEMD_HOST:-127.0.0.1}" --port "${UNSLOTH_SYSTEMD_PORT:-8888}" --enable --start
- # The user manager runs with the passwd HOME, so any non-default home has to be spelled out.
[ "$_STUDIO_HOME_REDIRECT" != "default" ] && set -- "$@" --studio-home "$STUDIO_HOME"
if bash "$_sd_script" "$@" >/dev/null; then
@@ -1542,15 +1422,12 @@ _install_systemd_user_service() {
}
# ── Helper: install packages via apt, escalating to sudo only if needed ──
-# Usage: _smart_apt_install pkg1 pkg2 pkg3 ...
_smart_apt_install() {
_PKGS="$*"
- # Step 1: Try installing without sudo (works when already root)
apt-get update -y </dev/null >/dev/null 2>&1 || true
apt-get install -y $_PKGS </dev/null >/dev/null 2>&1 || true
- # Step 2: Check which packages are still missing
_STILL_MISSING=""
for _pkg in $_PKGS; do
if ! _is_pkg_installed "$_pkg"; then
@@ -1563,18 +1440,17 @@ _smart_apt_install() {
return 0
fi
- # Optional callers never elevate, in any mode: nothing on the consumer path builds anything, so neither the terminal sudo prompt below nor the Tauri NEED_SUDO dialog (whose Cancel leaves the user not installed) may gate the run over unused tools. The caller falls through to prebuilt llama.cpp. Required packages such as curl still escalate.
+ # Optional installs never elevate: no prompt or Tauri NEED_SUDO over unused build tools.
if [ "${_SMART_APT_OPTIONAL:-false}" = true ]; then
return 2
fi
if [ "$TAURI_MODE" = true ]; then
- # Report needed packages and exit — Rust handles elevation.
+ # Rust handles elevation.
tauri_log "NEED_SUDO" "$_STILL_MISSING"
exit 2
fi
- # Step 3: Escalate -- need elevated permissions for remaining packages
if command -v sudo >/dev/null 2>&1; then
_ad_desc="$(_apt_distro_description)"
echo ""
@@ -1588,7 +1464,6 @@ _smart_apt_install() {
echo ""
if _can_read_tty; then
printf " Accept? [Y/n] "
- # The device opened, so a failed read is EOF, not consent: decline, as the autostart prompt below does. Enter is still yes (a successful read of an empty line).
read -r REPLY </dev/tty || REPLY="n"
case "$REPLY" in
[nN]*)
@@ -1598,7 +1473,6 @@ _smart_apt_install() {
exit 1
;;
esac
- # Mirror the headless branch: on a sudoers denial, a wrong password or an apt error, say what to run by hand instead of letting set -e abort on a bare sudo/apt message.
if sudo apt-get update -y </dev/null &&
sudo apt-get install -y $_STILL_MISSING </dev/null; then
:
@@ -1611,7 +1485,7 @@ _smart_apt_install() {
exit 1
fi
else
- # Nobody can answer a prompt or type a password here. -n makes sudo refuse rather than prompt into a closed stdin, which is how #7307 died. Probe with the real commands: `sudo -l` answers whether they are AUTHORIZED, not whether running them needs authentication. -k ignores any cached timestamp, so only a real NOPASSWD rule gets through; per sudo(8), -k alongside a command ignores the cached credentials and "will not update" them, so other sessions keep theirs.
+ # -n -k: only a real NOPASSWD rule passes, without prompting into a closed stdin.
echo " No terminal to confirm on; trying passwordless sudo."
if sudo -n -k apt-get update -y </dev/null &&
sudo -n -k apt-get install -y $_STILL_MISSING </dev/null; then
@@ -1620,7 +1494,6 @@ _smart_apt_install() {
echo ""
echo " Could not install these packages: $_STILL_MISSING"
echo " Detected ${_ad_desc}."
- # Either sudo refused, or apt failed on a bad repo, dpkg lock or network outage. sudo exits 1 on an auth/config problem and when the command cannot be executed, but otherwise passes the command's own status through, so state both causes.
echo " Either sudo needs a password here, or apt-get itself"
echo " failed; see the error above. With no terminal to"
echo " authenticate on, this cannot be done unattended."
@@ -1639,7 +1512,8 @@ _smart_apt_install() {
}
# ── Helper: the studio_install_id contract ──
-# 64 lowercase hex, as in the backend (_STUDIO_INSTALL_ID_RE) and the desktop app (is_valid_studio_root_id). Nothing else is an id: no backend reports it, and the launcher holds it in a single-quoted assignment, so a planted value with a quote in it would be launcher code. Subshell bodies scope LC_ALL=C to the check: the classes below must mean the same bytes in any inherited locale.
+# Install id is 64 lowercase hex (backend _STUDIO_INSTALL_ID_RE). It is baked into a single-quoted
+# launcher assignment, so anything else is rejected. LC_ALL=C keeps character classes stable.
_css_install_id_is_valid() (
LC_ALL=C
export LC_ALL
@@ -1649,21 +1523,17 @@ _css_install_id_is_valid() (
[ "${#1}" -eq 64 ]
)
-# Echoes the id at $1 when it satisfies the contract, nothing otherwise. Returns 1 when the path could not be READ, a different answer: a failed read may still be sitting on a valid id.
_css_read_valid_install_id() (
LC_ALL=C
export LC_ALL
- # Regular files only: a FIFO here (or a symlink to one, or to a device) would park the installer on the open, waiting for a writer forever.
[ -f "$1" ] || return 0
- # -s answers "no id" from stat, without a read, so an empty file we also cannot read is replaced as it was pre-validation instead of failing the install. A real id is 64 bytes and never reaches this.
[ -s "$1" ] || return 0
- # A NUL cannot live in a shell variable, so command substitution drops it and <32 hex>\\0<32 hex> would read back valid while the backend, which keeps the byte, reports "". Catch it by mapping NULs to a real character.
+ # Shell variables drop NULs, so detect them separately or an id with NUL reads as valid.
if [ -n "$({ tr -dc '\000' < "$1" | tr '\000' 'N'; } 2>/dev/null)" ]; then
return 0
fi
- # Group the redirect, or the shell's own "cannot open" escapes 2>/dev/null. A failed read is reported, never flattened into "no id": permissions or a transient NFS/FUSE fault must not license a rewrite.
+ # Group the redirect so the shell's own error is silenced; a failed read must not license a rewrite.
_cvi_id=$({ cat "$1"; } 2>/dev/null) || return 1
- # Trim what the backend's .strip() trims, SURROUNDING whitespace only. Deleting interior whitespace would mint a 64-hex token out of bytes the backend reads otherwise, leaving the launcher holding an id it never reports.
_cvi_id=${_cvi_id#"${_cvi_id%%[![:space:]]*}"}
_cvi_id=${_cvi_id%"${_cvi_id##*[![:space:]]}"}
if _css_install_id_is_valid "$_cvi_id"; then
@@ -1676,13 +1546,11 @@ create_studio_shortcuts() {
_css_exe="$1"
_css_os="$2"
- # Validate exe
if [ ! -x "$_css_exe" ]; then
echo "[WARN] Cannot create shortcuts: unsloth not found at $_css_exe"
return 0
fi
- # Resolve absolute path
_css_exe_dir=$(cd "$(dirname "$_css_exe")" && pwd)
_css_exe="$_css_exe_dir/$(basename "$_css_exe")"
@@ -1693,11 +1561,10 @@ create_studio_shortcuts() {
mkdir -p "$_css_data_dir"
- # Per-install opaque id for launcher + backend, under $STUDIO_HOME/share/ for studio_root.
_css_id_dir="$STUDIO_HOME/share"
mkdir -p "$_css_id_dir"
_css_id_file="$_css_id_dir/studio_install_id"
- # Reuse an existing id only when it matches the contract above, so a re-run over a normal install is a no-op and a pre-populated custom root cannot reach the launcher. Unreadable is not malformed: in a shared root the id can be a good one owned by someone else and already reported by a running backend, so regenerating would break that install.
+ # Reuse a valid id; unreadable is not malformed (another user's backend may report it).
if ! _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file"); then
echo "[WARN] Cannot create launcher: cannot read $_css_id_file" >&2
return 1
@@ -1713,11 +1580,12 @@ create_studio_shortcuts() {
echo "[WARN] Cannot create launcher: no entropy source for studio_install_id" >&2
return 1
fi
- # Publish no-clobber: the desktop app mints this same id, so a plain mv could replace one a running backend already reported. ln fails with EEXIST instead and we adopt the winner; its lock is not shareable portably (no flock(1) on macOS). The id is in the temp name because $$ is the parent's pid inside a subshell in some shells.
+ # Publish no-clobber via ln (EEXIST) since the desktop app mints the same id; $$ is unreliable
+ # in subshells, so the id is in the temp name.
_css_id_tmp="$_css_id_file.$$.$(printf '%.8s' "$_css_new_id").tmp"
if printf '%s' "$_css_new_id" > "$_css_id_tmp"; then
if ! ln "$_css_id_tmp" "$_css_id_file" 2>/dev/null; then
- # A usable incumbent wins, but only a valid one: zero-length or malformed is an interrupted write or a planted value, so replace it with one rename (no unlink, the path never vanishes). Also covers filesystems without hard links (exFAT/FAT32). -d because renaming onto a directory moves the temp inside it instead of replacing it.
+ # Replace an invalid incumbent with one rename. -d: renaming onto a directory moves inside it.
if _css_incumbent=$(_css_read_valid_install_id "$_css_id_file") \
&& [ -z "$_css_incumbent" ] && [ ! -d "$_css_id_file" ]; then
mv "$_css_id_tmp" "$_css_id_file" 2>/dev/null || true
@@ -1728,7 +1596,6 @@ create_studio_shortcuts() {
if [ -f "$_css_id_file" ]; then
chmod 600 "$_css_id_file" 2>/dev/null || true
fi
- # Bake what is on disk, not what we meant to write: that is what the backend reports from /api/health, whoever won the race. An unwritable or non-regular path leaves this empty and no launcher is generated.
_css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file") || true
unset _css_new_id _css_id_tmp _css_incumbent
fi
@@ -2135,9 +2002,7 @@ LAUNCHER_EOF
"$_css_launcher" > "$_css_launcher.tmp" \
&& mv "$_css_launcher.tmp" "$_css_launcher"
- # Env-mode bakes an absolute DATA_DIR; otherwise keep $HOME/.local/share/unsloth.
if [ "$_STUDIO_HOME_REDIRECT" = "env" ]; then
- # Two-stage escape: single-quote embedding, then backslash/&/| for the sed below.
_sq_escaped=$(printf '%s' "$DATA_DIR" | sed "s/'/'\\\\''/g")
_sed_safe=$(printf '%s' "$_sq_escaped" | sed 's/[\\&|]/\\&/g')
sed "s|@@DATA_DIR@@|$_sed_safe|g" "$_css_launcher" > "$_css_launcher.tmp" \
@@ -2156,7 +2021,6 @@ LAUNCHER_EOF
_css_quoted_id_file=$(printf '%s' "$_css_id_file" | sed "s/'/'\\\\''/g")
printf '%s\n' "STUDIO_INSTALL_ID_FILE='$_css_quoted_id_file'"
if [ "$_STUDIO_HOME_REDIRECT" = "env" ]; then
- # An override resolving to the legacy default shares ~/.unsloth/llama.cpp.
_css_legacy_studio="$HOME/.unsloth/studio"
if [ -d "$_css_legacy_studio" ]; then
_css_legacy_studio=$(CDPATH= cd -P -- "$_css_legacy_studio" 2>/dev/null && pwd -P) \
@@ -2180,7 +2044,6 @@ LAUNCHER_EOF
_css_quoted_home=$(printf '%s' "$STUDIO_HOME" | sed "s/'/'\\\\''/g")
_css_quoted_llama=$(printf '%s' "$_css_llama_path" | sed "s/'/'\\\\''/g")
printf '%s\n' "export UNSLOTH_STUDIO_HOME='$_css_quoted_home'"
- # UNSLOTH_LLAMA_CPP_PATH is user-controlled; only default it if unset.
printf '%s\n' 'if [ -z "${UNSLOTH_LLAMA_CPP_PATH:-}" ]; then'
printf '%s\n' " export UNSLOTH_LLAMA_CPP_PATH='$_css_quoted_llama'"
printf '%s\n' 'fi'
@@ -2193,21 +2056,18 @@ LAUNCHER_EOF
_css_script_dir=$(cd "$(dirname "$0")" 2>/dev/null && pwd) || true
fi
- # Try to find rounded-512.png from installed package (site-packages) or local repo
_css_found_icon=""
_css_venv_dir=$(dirname "$(dirname "$_css_exe")")
- # Check site-packages. `studio` is a top-level package in the wheel (see top_level.txt), not a subpackage of `unsloth`, so the old site-packages/unsloth/studio/... glob never matched and every install fell through to the network download below. Read it out of frontend/dist rather than frontend/public: Vite copies public/ into dist/ at build time, so the file is in both in a checkout, but only dist/ ships in the wheel.
+ # `studio` is a top-level package in the wheel, and only frontend/dist ships.
for _sp in "$_css_venv_dir"/lib/python*/site-packages/studio/frontend/dist; do
if [ -f "$_sp/rounded-512.png" ]; then
_css_found_icon="$_sp/rounded-512.png"
fi
done
- # Check local repo (when running from clone)
if [ -z "$_css_found_icon" ] && [ -n "$_css_script_dir" ] && [ -f "$_css_script_dir/studio/frontend/public/rounded-512.png" ]; then
_css_found_icon="$_css_script_dir/studio/frontend/public/rounded-512.png"
fi
- # Copy or download rounded-512.png (used for both Linux icon and macOS icns)
if [ -n "$_css_found_icon" ]; then
cp "$_css_found_icon" "$_css_icon_png" 2>/dev/null || true
cp "$_css_found_icon" "$_css_gem_png" 2>/dev/null || true
@@ -2216,7 +2076,6 @@ LAUNCHER_EOF
cp "$_css_icon_png" "$_css_gem_png" 2>/dev/null || true
fi
- # Validate PNG header (first 4 bytes: \x89PNG)
_css_validate_png() {
[ -f "$1" ] || return 1
_hdr=$(od -An -tx1 -N4 "$1" 2>/dev/null | tr -d ' ')
@@ -2229,7 +2088,6 @@ LAUNCHER_EOF
rm -f "$_css_gem_png"
fi
- # Prefer the pre-built Tauri icon.icns (1024x1024, all required sizes, @2x variants) over the sips-generated icon for the macOS .app bundle; it ships in the pip package at studio/src-tauri/icons/icon.icns.
_css_tauri_icns=""
for _sp in "$_css_venv_dir"/lib/python*/site-packages/studio/src-tauri/icons; do
if [ -f "$_sp/icon.icns" ]; then
@@ -2240,7 +2098,6 @@ LAUNCHER_EOF
_css_tauri_icns="$_css_script_dir/studio/src-tauri/icons/icon.icns"
fi
- # The higher-resolution Tauri icon.png (1024x1024) for the Linux .desktop icon, better than the 512px rounded variant.
_css_tauri_png=""
for _sp in "$_css_venv_dir"/lib/python*/site-packages/studio/src-tauri/icons; do
if [ -f "$_sp/icon.png" ]; then
@@ -2266,7 +2123,6 @@ LAUNCHER_EOF
mkdir -p "$_css_app_dir"
_css_desktop="$_css_app_dir/unsloth-studio.desktop"
- # Escape backslashes and double-quotes for .desktop Exec= field
_css_exec_escaped=$(printf '%s' "$_css_launcher" | sed 's/\\/\\\\/g; s/"/\\"/g')
# Prefer the higher-resolution Tauri icon.png, but persist it under the installed data directory so local-checkout shortcuts survive repo moves.
_css_desktop_icon="$_css_icon_png"
@@ -2294,17 +2150,14 @@ Categories=Development;Science;
DESKTOP_EOF
chmod +x "$_css_desktop"
- # Copy to ~/Desktop if it exists
if [ -d "$HOME/Desktop" ]; then
cp "$_css_desktop" "$HOME/Desktop/unsloth-studio.desktop" 2>/dev/null || true
chmod +x "$HOME/Desktop/unsloth-studio.desktop" 2>/dev/null || true
- # Mark as trusted so GNOME/Nautilus allows launching via double-click
if command -v gio >/dev/null 2>&1; then
gio set "$HOME/Desktop/unsloth-studio.desktop" metadata::trusted true 2>/dev/null || true
fi
fi
- # Best-effort update database
update-desktop-database "$_css_app_dir" 2>/dev/null || true
_css_created=1
@@ -2314,7 +2167,6 @@ DESKTOP_EOF
_css_contents="$_css_app/Contents"
_css_macos_dir="$_css_contents/MacOS"
_css_res_dir="$_css_contents/Resources"
- # Recreate bundle if root or any subpath is a symlink (mkdir -p follows them).
if [ -L "$_css_app" ] || [ -L "$_css_contents" ] \
|| [ -L "$_css_macos_dir" ] || [ -L "$_css_res_dir" ]; then
rm -rf "$_css_app" 2>/dev/null || {
@@ -2325,13 +2177,12 @@ DESKTOP_EOF
echo "[ERROR] $_css_app exists but is not a directory; remove manually and re-run install" >&2
return 1
fi
- # Older installs linked the Desktop shortcut with `ln -sf`, which followed the existing link and planted a self-referential copy one level inside the bundle.
+ # Old `ln -sf` shortcuts planted a self-referential link inside the bundle.
if [ -L "$_css_app/Unsloth Studio.app" ]; then
rm -f "$_css_app/Unsloth Studio.app" 2>/dev/null || true
fi
mkdir -p "$_css_macos_dir" "$_css_res_dir"
- # Info.plist
cat > "$_css_contents/Info.plist" << 'PLIST_EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -2366,7 +2217,6 @@ DESKTOP_EOF
</plist>
PLIST_EOF
- # Single-quoted heredoc + sed so $-vars in $_css_data_dir do not expand at launch.
_css_sq_dir=$(printf '%s' "$_css_data_dir" | sed "s/'/'\\\\''/g")
_css_sed_dir=$(printf '%s' "$_css_sq_dir" | sed 's/[\\&|]/\\&/g')
# A script-only bundle may be started under Rosetta (#9467), and a translated shell hands the x86_64 slice of a universal2 venv python its arm64 wheels. LSArchitecturePriority asks Launch Services for arm64, and arch -arm64 also covers a bundle id whose Rosetta choice Launch Services already cached. hw.optional.arm64 is absent on Intel, so Intel keeps the plain exec.
@@ -2404,7 +2254,6 @@ STUB_EOF
rm -rf "$_css_tmpdir"
fi
fi
- # Last-resort fallback: copy PNG as icon
if [ ! -f "$_css_res_dir/AppIcon.icns" ] && [ -f "$_css_icon_png" ]; then
cp "$_css_icon_png" "$_css_res_dir/AppIcon.icns" 2>/dev/null || true
fi
@@ -2412,7 +2261,7 @@ STUB_EOF
# Touch so Finder indexes it
touch "$_css_app"
- # Symlink on Desktop. -n is required: without it a re-run follows the existing link into the bundle and creates the new one inside it, as the CLI shim guards.
+ # -n is required: without it a re-run creates the link inside the bundle.
if [ -d "$HOME/Desktop" ]; then
ln -sfn "$_css_app" "$HOME/Desktop/Unsloth Studio" 2>/dev/null || true
fi
@@ -2428,7 +2277,6 @@ STUB_EOF
fi
_css_wsl_args="${_css_wsl_args}-- bash -l -c \"exec \\\"$_css_launcher\\\"\""
- # Detect whether Windows Terminal (wt.exe) is available (better UX)
_css_use_wt=false
if command -v wt.exe >/dev/null 2>&1; then
_css_use_wt=true
@@ -2442,10 +2290,8 @@ STUB_EOF
_css_sc_args="$_css_wsl_args"
fi
- # Escape single quotes for PowerShell single-quoted string embedding
_css_sc_args_ps=$(printf '%s' "$_css_sc_args" | sed "s/'/''/g")
- # Per-distro name so the WSL launcher never clobbers a native "Unsloth Studio.lnk".
if [ -n "$_css_distro" ]; then
_css_lnk_name="Unsloth Studio (WSL - ${_css_distro}).lnk"
else
@@ -2453,7 +2299,6 @@ STUB_EOF
fi
_css_lnk_name_ps=$(printf '%s' "$_css_lnk_name" | sed "s/'/''/g")
- # The generated script prefers this to its download.
_css_wsl_ico_win=""
for _sp in "$_css_venv_dir"/lib/python*/site-packages/studio/frontend/dist; do
if [ -f "$_sp/unsloth.ico" ] && command -v wslpath >/dev/null 2>&1; then
@@ -2463,53 +2308,14 @@ STUB_EOF
_css_wsl_ico_win_ps=$(printf '%s' "$_css_wsl_ico_win" | sed "s/'/''/g")
# Create shortcuts via a temp PowerShell script to avoid escaping issues.
- #
- # On the WINDOWS side of the interop, not in WSL's /tmp. wslpath maps a WSL path to a
- # \\wsl.localhost\<distro>\... UNC path, and PowerShell treats a script on a UNC path as
- # remote: RemoteSigned refuses an unsigned one, which is the only reason this launch used to
- # relax the execution policy. A script under the Windows %TEMP% is on a local volume, so it
- # is MyComputer-zone and RemoteSigned loads it unsigned, and the relaxed policy stops being
- # necessary. Behaviour is otherwise identical: same generated script, same launch.
+ # Written to Windows %TEMP%, not WSL /tmp: a UNC path is remote and RemoteSigned refuses it.
_css_win_temp=""
if command -v wslpath >/dev/null 2>&1 && command -v cmd.exe >/dev/null 2>&1; then
- # cmd.exe rather than powershell.exe: one fewer interpreter start, and it cannot be the
- # thing a policy blocks. The trailing CR is cmd's, not ours.
- #
- # /d, because without it cmd runs the AutoRun command out of
- # HKCU\Software\Microsoft\Command Processor before anything else, on the same stdout.
- # Clink sets one, so Cmder does, and so do plenty of corporate images; its banner would
- # be glued to the front of the path, wslpath would reject that and the whole shortcut
- # would be skipped. Those users got a shortcut before this block existed, so leaving
- # AutoRun enabled would be a regression that only shows up on their machines.
- #
- # Last line rather than the whole stream for whatever still prints (an AutoRun invoked
- # some other way, a login banner), and trailing blanks go because Win32 strips them
- # from a path while [ -d ] does not. The || is not dead code: this file runs under
- # set -e, where a failed substitution would end the install.
- #
- # Quoted inside cmd, and the quotes stripped back off here. cmd expands %TEMP% BEFORE
- # it parses metacharacters, so an unquoted `echo %TEMP%` on a profile holding a valid
- # path character like & ("C:\Users\A&B\AppData\Local\Temp") turns into two commands:
- # the echo prints a truncated path and the rest is run as a command. & is legal in a
- # Windows account name, so this is reachable. Inside double quotes it is literal.
- # Three candidates, most preferred first, each on its own line. %TEMP% can be
- # redirected onto a share, and a script there is a REMOTE script: RemoteSigned refuses
- # an unsigned one, so the shortcut would silently stop being created for exactly the
- # roaming-profile users who had one before. Rather than relax the policy back to Bypass,
- # fall through to a directory that is local by construction. install.ps1:3419-3432
- # solves the same problem for the launcher, which cannot move, by relaxing the policy;
- # this script CAN move, so it does that instead.
- #
- # The & separators are ours and deliberate: each value is quoted, so an & inside a value
- # stays literal and only these three separators split the line.
+ # cmd /d skips AutoRun banners; values are quoted because cmd expands %TEMP% before parsing &.
+ # Candidates in order; a redirected network %TEMP% is remote, so fall through to a local dir.
_css_win_temp_list=$(cmd.exe /d /c 'echo "%TEMP%"&echo "%LOCALAPPDATA%\Temp"&echo "%SystemRoot%\Temp"' 2>/dev/null \
| tr -d '\r') || _css_win_temp_list=""
- # Mapped network drives too, not only UNC spellings. Z:\Temp is the same share and the
- # same remote zone as \\server\share\Temp -- install.ps1:3419-3431 treats
- # DriveType.Network as remote for exactly this reason -- and a candidate on one would
- # otherwise be accepted and then refused by RemoteSigned at launch. `net use` lists the
- # mapped letters; if it cannot be read the set is empty and only the UNC check applies,
- # which is the previous behaviour rather than a new failure.
+ # Mapped network drives are the remote zone too, so exclude them like UNC paths.
_css_net_drives=$(cmd.exe /d /c 'net use' 2>/dev/null | tr -d '\r' \
| awk '/\\\\/ { for (i = 1; i <= NF; i++) if ($i ~ /^[A-Za-z]:$/) print substr($i, 1, 1) }' \
| tr 'a-z' 'A-Z') || _css_net_drives=""
@@ -2519,20 +2325,13 @@ STUB_EOF
'
for _css_cand in $_css_win_temp_list; do
IFS=$_css_old_ifs
- # Quotes off FIRST, blanks second. Win32 strips trailing spaces from a path while
- # [ -d ] does not, so they have to go; but with the closing quote still the last
- # character there is no trailing blank to find, and trimming first silently did
- # nothing for a %TEMP% like "C:\Temp ".
_css_cand=${_css_cand#\"}
_css_cand=${_css_cand%\"}
_css_cand=$(printf '%s' "$_css_cand" | sed 's/[[:space:]]*$//')
case "$_css_cand" in
- # Unexpanded (the variable is unset), or a UNC path. A dotted FQDN, a DFS root
- # and an IP literal all arrive in this same \\server\share form, and all three
- # are the remote zone.
+ # Unexpanded variable, or a UNC path, which is the remote zone.
""|'%'*'%'*|'\\'*) continue ;;
esac
- # Drive letter against the mapped-network set, before anything else looks at it.
_css_cand_letter=$(printf '%s' "$_css_cand" | cut -c1 | tr 'a-z' 'A-Z')
_css_is_net=0
for _css_nd in $_css_net_drives; do
@@ -2549,10 +2348,7 @@ STUB_EOF
_css_win_temp=""
fi
fi
- # No fallback to WSL's /tmp. That would put the script back on a UNC path and need Bypass
- # again, and this whole branch is best-effort already: the population where %TEMP% cannot be
- # read through interop is very nearly the population where interop is broken, which lands on
- # the same "couldn't create the Windows shortcut" notice below.
+ # No fallback to WSL /tmp: it is a UNC path again, and this branch is best-effort.
_css_ps1_tmp=""
if [ -n "$_css_win_temp" ]; then
_css_ps1_tmp=$(mktemp "$_css_win_temp/unsloth-shortcut-XXXXXX.ps1" 2>/dev/null) || _css_ps1_tmp=""
@@ -2693,26 +2489,14 @@ WSLPS1_EOF
if [ -n "$_css_ps1_tmp" ]; then
printf '%s\n' "$_css_ps1_body" > "$_css_ps1_tmp"
- # Convert WSL path to Windows path for powershell.exe
_css_ps1_win=$(wslpath -w "$_css_ps1_tmp" 2>/dev/null)
if [ -n "$_css_ps1_win" ]; then
- # RemoteSigned, not Bypass: the script above was written to the Windows %TEMP%
- # on a local volume, so it is not a remote script and RemoteSigned loads it
- # unsigned. Pairing a relaxed policy with a PowerShell launch is a scored shape,
- # and this one was buying nothing once the path stopped being a UNC path.
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File "$_css_ps1_win" >/dev/null 2>&1 && _css_created=1
fi
rm -f "$_css_ps1_tmp"
else
- # No Windows directory is reachable as a Linux path. That is a real configuration --
- # [automount] enabled=false leaves interop working while exposing no drive -- and
- # before the move off /tmp those users still got a shortcut, so losing it here would
- # be a regression rather than a gap. Hand the script to powershell on STDIN instead:
- # there is no file, so there is no zone and no execution policy to satisfy (policy
- # applies to -File, not to -Command), and nothing has to be mounted.
- #
- # Our own pipe, not the installer's: `curl | sh` leaves this script's stdin pointing
- # at the download, and powershell reading that would drink the rest of it (#7548).
+ # No Windows dir is reachable (automount off): pipe the script on stdin, where no execution
+ # policy applies. Use our own pipe: a piped install's stdin is the download (#7548).
printf '%s\n' "$_css_ps1_body" | powershell.exe -NoProfile -Command - >/dev/null 2>&1 && _css_created=1
fi
fi
@@ -2743,9 +2527,7 @@ elif grep -qi microsoft /proc/version 2>/dev/null; then
fi
step "platform" "$OS"
-# Regen launcher/shortcuts only; used by `unsloth studio update`.
if [ "$_SHORTCUTS_ONLY" = true ]; then
- # Tauri owns its own shortcuts.
if [ "$TAURI_MODE" != true ]; then
VENV_ABS_BIN="$VENV_DIR/bin"
if [ ! -x "$VENV_ABS_BIN/unsloth" ]; then
@@ -2760,10 +2542,9 @@ fi
# ── Architecture detection & Python version ──
_ARCH=$(uname -m)
MAC_INTEL=false
-# Rosetta is a property of the shell, not of the machine, so it is tracked apart from MAC_INTEL: torch and the Python version rightly follow the x86_64 shell, but anything that reasons about the HARDWARE (the /usr/bin CLT shims in _has_working_git) must see an Apple Silicon Mac here.
+# Rosetta is tracked apart from MAC_INTEL: hardware checks must still see Apple Silicon.
_MAC_ROSETTA=false
if [ "$OS" = "macos" ] && [ "$_ARCH" = "x86_64" ]; then
- # Apple Silicon under Rosetta reports x86_64; hw.optional.arm64 stays "1".
if [ "$(sysctl -in hw.optional.arm64 2>/dev/null || echo 0)" = "1" ]; then
_MAC_ROSETTA=true
echo ""
@@ -2800,7 +2581,6 @@ if [ "$_NO_TORCH_FLAG" = true ] || [ "$MAC_INTEL" = true ]; then
SKIP_TORCH=true
fi
-# Apple Silicon: override mlx-vlm / mlx-lm's transformers pin (see overrides file).
if [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
_OVERRIDES_FILE="$(cd "$(dirname "$0" 2>/dev/null || echo ".")" && pwd)/studio/backend/requirements/single-env/overrides-darwin-arm64.txt"
if [ -f "$_OVERRIDES_FILE" ]; then
@@ -2836,7 +2616,7 @@ elif [ "$OS" = "macos" ]; then
fi
tauri_diag_marker "$_TAURI_INITIAL_GPU_BRANCH" "none"
-# AMD GPU name from the Windows host via WMI (discrete cards are not in /proc/cpuinfo).
+# Discrete AMD cards are not in /proc/cpuinfo, so ask the Windows host via WMI.
_WSL_AMD_GPU_NAME_CACHE=""
_wsl_amd_gpu_name() {
if [ -n "$_WSL_AMD_GPU_NAME_CACHE" ]; then
@@ -2865,16 +2645,14 @@ _run_bounded() {
fi
}
-# True when CUDA_VISIBLE_DEVICES is "" or "-1"; nvidia-smi ignores it.
_cvd_hides_nvidia() {
[ "${CUDA_VISIBLE_DEVICES+set}" = "set" ] || return 1
_cvd_trim=$(printf '%s' "$CUDA_VISIBLE_DEVICES" | tr -d '[:space:]')
[ -z "$_cvd_trim" ] || [ "$_cvd_trim" = "-1" ]
}
-# NVIDIA inventory from the driver's own libraries (NVML, then the CUDA driver API) for a host whose nvidia-smi is absent, stale or hangs (#9255): "<cuda major>.<minor> <cap>,<cap>" or exit 1. Inline rather than studio/nvidia_probe.py, which is not on disk yet when the torch index is chosen; the two read the same calls.
-# Memoised for the run: the presence check and the torch index must read the same answer,
-# and a wedged driver pays its deadline once.
+# NVIDIA inventory via NVML / CUDA driver API when nvidia-smi is absent or hangs. Inline because
+# studio/nvidia_probe.py is not on disk yet. Memoised so all callers agree.
_NVIDIA_LIBRARY_INVENTORY_STATE=""
_NVIDIA_LIBRARY_INVENTORY_VALUE=""
_nvidia_library_inventory() {
@@ -2883,15 +2661,12 @@ _nvidia_library_inventory() {
found) printf '%s\n' "$_NVIDIA_LIBRARY_INVENTORY_VALUE"; return 0 ;;
none) return 1 ;;
esac
- # The system python3, else the managed venv's once it exists. No interpreter yet is
- # not an answer to remember: the venv arrives later in this run.
if command -v python3 >/dev/null 2>&1; then _nli_py=python3
elif [ -n "${VENV_DIR:-}" ] && [ -x "$VENV_DIR/bin/python" ]; then _nli_py="$VENV_DIR/bin/python"
else return 1
fi
_NVIDIA_LIBRARY_INVENTORY_STATE="none"
_NVIDIA_LIBRARY_INVENTORY_VALUE=""
- # One deadline per reader: a shared bound let slow NVML starve the CUDA driver API reader.
for _nli_reader in nvml cuda; do
case "$_nli_reader" in nvml) _nli_secs=30 ;; *) _nli_secs=20 ;; esac
_NVIDIA_LIBRARY_INVENTORY_VALUE=$(_run_bounded --secs "$_nli_secs" "$_nli_py" -I - "$_nli_reader" 2>/dev/null <<'PY'
@@ -2974,7 +2749,6 @@ PY
printf '%s\n' "$_NVIDIA_LIBRARY_INVENTORY_VALUE"
}
-# Driver CUDA version without cuInit (cuDriverGetVersion, else /proc as in nvidia_probe.py _DRIVER_MAJOR_CUDA); picks a family only.
_nvidia_driver_cuda_version() {
[ "${UNSLOTH_NVIDIA_LIBRARY_PROBE:-1}" != "0" ] || return 1
if command -v python3 >/dev/null 2>&1; then _ndv_py=python3
@@ -2999,7 +2773,6 @@ print(f"{v.value // 1000}.{v.value % 1000 // 10}")
[0-9]*.[0-9]*) printf '%s\n' "$_ndv_ver"; return 0 ;;
esac
fi
- # "NVRM version: NVIDIA UNIX Open Kernel Module for x86_64 590.48.01 Release Build ..."
_ndv_drv=$(awk 'NR == 1 { for (i = 1; i <= NF; i++) if ($i ~ /^[0-9]+\.[0-9]+(\.[0-9]+)?$/) { split($i, v, "."); print v[1]; exit } }' \
/proc/driver/nvidia/version 2>/dev/null) || _ndv_drv=""
case "$_ndv_drv" in ''|*[!0-9]*) return 1 ;; esac
@@ -3013,7 +2786,6 @@ print(f"{v.value // 1000}.{v.value % 1000 // 10}")
}
# ── NVIDIA usable-GPU helper ──
-# nvidia-smi -L primary, /proc/driver/nvidia/gpus/ fallback, driver library last; a hidden GPU is NOT usable.
_has_usable_nvidia_gpu() {
_nv_smi_wedged=""
if _cvd_hides_nvidia; then
@@ -3058,16 +2830,7 @@ _nv_idx_from_uuid() {
END { if (hits == 1) print idx }' || true
}
-# Resolves the banner's NVIDIA fields into _nv_name / _nv_sm / _nv_driver, each empty
-# when it could not be read. compute_cap is the counterpart of the gfx arch shown for
-# AMD and the driver version the counterpart of the hipconfig line, so one query gets
-# all three.
-#
-# Bounded, and fed the executable _has_usable_nvidia_gpu already resolved into $_nvsmi.
-# Both matter: a wedged driver blocks nvidia-smi indefinitely (the reason _run_bounded
-# exists), and detection also succeeds via /usr/bin/nvidia-smi off PATH or via
-# /proc/driver/nvidia/gpus with no nvidia-smi at all -- re-resolving with `command -v`
-# would silently skip the name on exactly those hosts.
+# Bounded, and reuses the resolved $_nvsmi: detection may have succeeded without PATH nvidia-smi.
_nv_banner_fields() {
_nv_name=""; _nv_sm=""; _nv_driver=""; _nv_row=""; _nv_cc=""; _nv_ambiguous=""
[ -n "${_nvsmi:-}" ] || return 0
@@ -3077,9 +2840,6 @@ _nv_banner_fields() {
# nvidia-smi ignores CUDA_VISIBLE_DEVICES, so its rows are the physical devices and
# the mask has to be resolved against them by hand.
_nv_idx=0
- # Set while nothing has IDENTIFIED a device: an ordinal, or a failed identity lookup
- # that fell back to one. Only an ordinal is order-dependent, so only it needs the
- # CUDA_DEVICE_ORDER check below.
_nv_by_ordinal=1
_nv_vis="${CUDA_VISIBLE_DEVICES:-}"
# Only the FIRST entry selects the device, and only IT decides the form of the mask.
@@ -3090,7 +2850,6 @@ _nv_banner_fields() {
case "$_nv_tok" in
'') ;;
*[!0-9]*)
- # A non-numeric mask names a device rather than indexing one.
_nv_by_ordinal=""
case "$_nv_tok" in
MIG-GPU-*)
@@ -3099,10 +2858,7 @@ _nv_banner_fields() {
_nv_tok="${_nv_tok#MIG-}"; _nv_tok="${_nv_tok%%/*}"
_nv_idx=$(_nv_idx_from_uuid "$_nv_tok") ;;
MIG-*)
- # R470 and later give each MIG instance its OWN opaque UUID, which
- # carries nothing of the parent, so --query-gpu=uuid can never match
- # it. `nvidia-smi -L` nests the instances under their GPU, which is
- # the documented way to map one back to the card it lives on.
+ # R470+ MIG UUIDs are opaque; nvidia-smi -L nests them under their GPU.
_nv_idx=$(_run_bounded "$_nvsmi" -L 2>/dev/null | awk -v want="$_nv_tok" '
/^GPU[[:space:]]+[0-9]+:/ { cur = $2 + 0 }
index($0, want) > 0 { print cur; exit }' || true) ;;
@@ -3127,16 +2883,8 @@ _nv_banner_fields() {
_nv_row=$(printf '%s\n' "$_nv_all" \
| awk -v idx="$_nv_idx" 'NF { a[n++]=$0 } END { if(idx>=n) idx=0; if(n>0) print a[idx+0] }')
[ -n "$_nv_row" ] || return 0
- # A numeric entry is a CUDA ordinal, and CUDA's default CUDA_DEVICE_ORDER=FASTEST_FIRST
- # puts the fastest card at 0 and leaves the rest "unspecified", while nvidia-smi always
- # lists in PCI order. So an ordinal identifies an nvidia-smi row only when the order is
- # pinned to PCI_BUS_ID, or when the cards are interchangeable and every row gives the
- # same answer anyway. Otherwise naming one is a guess, and the AMD path above already
- # refuses that rather than name a card the mask did not select. Compared on name and
- # compute_cap, not the driver, which is host-wide and identical on every row.
- # CUDA stops enumerating at the first invalid index, so an ordinal past the last
- # row exposes NO device at all. The awk above clamps to row 0 so the driver still
- # reads, but row 0 is not the selected card -- nothing is.
+ # CUDA's default FASTEST_FIRST order differs from nvidia-smi's PCI order, so an ordinal names a row
+ # only under PCI_BUS_ID or identical cards. An out-of-range ordinal exposes no device.
_nv_rowcount=$(printf '%s\n' "$_nv_all" | awk 'NF { n++ } END { print n+0 }')
if [ -n "$_nv_by_ordinal" ] && [ "$_nv_idx" -ge "$_nv_rowcount" ]; then
_nv_ambiguous=1
@@ -3154,15 +2902,10 @@ _nv_banner_fields() {
_nv_driver=$(printf '%s' "$_nv_row" | awk -F, 'NF>=3 { gsub(/^[[:space:]]+|[[:space:]]+$/,"",$NF); print $NF }')
_nv_cc=$(printf '%s' "$_nv_row" | awk -F, 'NF>=3 { gsub(/^[[:space:]]+|[[:space:]]+$/,"",$(NF-1)); print $(NF-1) }')
_nv_name=$(printf '%s' "$_nv_row" | awk -F, 'NF>=3 { out=$1; for(i=2;i<=NF-2;i++) out=out","$i; gsub(/^[[:space:]]+|[[:space:]]+$/,"",out); print out }')
- # Short row: keep field 1 only. Taking the whole row would print the compute
- # capability as part of the device name ("RTX 4090, 8.9").
[ -n "$_nv_name" ] || _nv_name=$(printf '%s' "$_nv_row" | awk -F, '{ gsub(/^[[:space:]]+|[[:space:]]+$/,"",$1); print $1 }')
- # An nvidia-smi too old for a field answers with a placeholder rather than failing
- # (the 470 branch has no compute_cap at all). "[N/A]" is not a name.
+ # Old nvidia-smi prints placeholders for unknown fields (470 has no compute_cap).
case "$_nv_name" in '[N/A]'|'[Not Supported]'|'[Unknown Error]') _nv_name="" ;; esac
case "$_nv_driver" in '[N/A]'|'[Not Supported]'|'[Unknown Error]') _nv_driver="" ;; esac
- # Keep the driver, drop the identity: the banner falls back to "NVIDIA GPU detected"
- # rather than claiming a card that may not be the one CUDA will use.
if [ -n "$_nv_ambiguous" ]; then _nv_name=""; _nv_cc=""; fi
case "$_nv_cc" in
[0-9]*.[0-9]*) _nv_sm="sm_$(printf '%s' "$_nv_cc" | awk -F. '{ print ($1*10)+$2 }')" ;;
@@ -3173,7 +2916,6 @@ _nv_banner_fields() {
# Strix Halo ROCm-on-WSL needs Ubuntu 24.04: re-run in one, else CPU. Never create a distro.
_maybe_reroute_strixhalo_to_2404() {
[ "${OS:-}" = "wsl" ] || return 0
- # An explicit index pin skips every GPU-driven reroute; whitespace-only does not gate.
_rr_pin=$(printf '%s' "${UNSLOTH_TORCH_INDEX_URL:-}${UNSLOTH_TORCH_INDEX_FAMILY:-}" | tr -d '[:space:]')
[ -n "$_rr_pin" ] && return 0
[ "${SKIP_TORCH:-false}" = "false" ] || return 0
@@ -3181,21 +2923,17 @@ _maybe_reroute_strixhalo_to_2404() {
[ "${UNSLOTH_WSL_REROUTED:-0}" = "1" ] && return 0
[ -e /dev/dxg ] || return 0
if _has_usable_nvidia_gpu; then return 0; fi
- # Strix APUs show in /proc/cpuinfo; discrete cards don't, so also try WMI. Either reroutes.
if ! grep -qiE 'Ryzen AI Max|Radeon 80[0-9][05]S|Strix Halo' /proc/cpuinfo 2>/dev/null \
&& ! _wsl_amd_gpu_name >/dev/null 2>&1; then
return 0
fi
- # Already ROCm-on-WSL? leave a working GPU alone, whatever the version.
if [ -e /opt/rocm/lib/librocdxg.so ] || [ -e /opt/rocm/lib64/librocdxg.so ]; then
return 0
fi
_rr_ver=""
[ -r /etc/os-release ] && _rr_ver=$(. /etc/os-release 2>/dev/null; printf '%s' "${VERSION_ID:-}")
case "$_rr_ver" in 24.04) return 0 ;; esac
- # Without a 24.04 reroute target, stay CPU-only AND skip the origin-distro ROCm bootstrap.
command -v wsl.exe >/dev/null 2>&1 || { UNSLOTH_SKIP_ROCM_WSL_SETUP=1; return 0; }
- # Whole-line match so "Ubuntu-24.04-test" cannot masquerade; no match is fine.
_rr_distros=$(wsl.exe -l -q 2>/dev/null | tr -d '\000\r')
_rr_target=$(printf '%s\n' "$_rr_distros" | grep -ixF "Ubuntu-24.04" | head -n1) || true
[ -n "$_rr_target" ] || {
@@ -3208,7 +2946,7 @@ _maybe_reroute_strixhalo_to_2404() {
echo ""
substep "ROCm-on-WSL (GPU) needs Ubuntu 24.04; this distro is Ubuntu ${_rr_ver:-unknown}." "$C_WARN"
substep "Found an existing $_rr_target distro -- continuing the GPU install there." "$C_OK"
- # A --local checkout cannot be replayed by a piped web install (the repo is not in the target distro), so tell the user to re-run there rather than silently run a different install.
+ # A --local checkout cannot be replayed in another distro; tell the user instead.
if [ "$STUDIO_LOCAL_INSTALL" = true ]; then
substep "This is a --local install; re-run it from $_rr_target instead:" "$C_WARN"
substep " wsl -d $_rr_target -- bash -lc 'cd <your checkout> && ./install.sh --local'" "$C_WARN"
@@ -3219,9 +2957,7 @@ _maybe_reroute_strixhalo_to_2404() {
_rr_q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
_rr_exports="set -o pipefail; export UNSLOTH_WSL_REROUTED=1"
- # An automatic path belongs to the origin distro; only an override is portable, and the
- # variable alone cannot tell them apart. Forwarding our own default pins the child to
- # `custom`, which skips its adaptive selection and outranks its --isolated-uv-cache.
+ # Forward only a user override of UV_CACHE_DIR; our own default would pin the child to `custom`.
_rr_uv_cache=""
if [ "${_UV_CACHE_DIR_INSTALLER_DEFAULT:-false}" != true ]; then
case "${UV_CACHE_DIR-}" in
@@ -3258,20 +2994,18 @@ _maybe_reroute_strixhalo_to_2404() {
else
_rr_cmd="curl -fsSL https://unsloth.ai/install.sh | sh"
fi
- # pipefail so a failed download in a piped web install is not masked by sh exiting 0 on empty input, which would wrongly report success and exit 0 the parent installer.
+ # pipefail so a failed download is not masked by sh exiting 0 on empty input.
_rr_rc=0
wsl.exe -d "$_rr_target" -- bash -lc "$_rr_exports; $_rr_cmd" || _rr_rc=$?
if [ "$_rr_rc" -eq 0 ]; then
exit 0
fi
- # Tauri child exit 2 ([TAURI:NEED_SUDO]) asks the desktop app to elevate.
if [ "$TAURI_MODE" = true ] && [ "$_rr_rc" -eq 2 ]; then
exit 2
fi
substep "Could not auto-continue in $_rr_target; run it yourself:" "$C_WARN"
substep " wsl -d $_rr_target -- bash -lc 'curl -fsSL https://unsloth.ai/install.sh | sh'"
substep "Continuing CPU-only in Ubuntu ${_rr_ver:-this distro} for now." "$C_WARN"
- # Reroute failed; keep the later bootstrap from installing ROCm into this distro.
UNSLOTH_SKIP_ROCM_WSL_SETUP=1
return 0
}
@@ -3280,10 +3014,11 @@ _maybe_reroute_strixhalo_to_2404 || true
# ── Check system dependencies ──
tauri_log "STEP" "Checking system dependencies"
-# Without the Xcode CLT, macOS still ships /usr/bin/git as a stub that errors and pops a GUI dialog, so `command -v git` is not enough: only running it tells the truth.
+# Without the Xcode CLT /usr/bin/git is a stub, so `command -v git` is not enough.
_has_working_git() {
command -v git >/dev/null 2>&1 || return 1
- # Executing the probe is the problem on macOS: /usr/bin/git is a Command Line Tools shim, so `git --version` against it raises the "install the command line developer tools" GUI dialog, the probe firing the dialog it exists to detect. Answer from the resolved path instead when it is that exact shim and no toolchain is selected. Narrow on purpose: only /usr/bin/git is a shim, and a Homebrew, MacPorts or Xcode.app git earlier on PATH is a real binary and is still probed by executing it. Intel macOS can also ship a working /usr/bin/git after CLT masking, so MAC_INTEL must probe that path; only Apple Silicon treats it as the known dialog shim without execution, and _MAC_ROSETTA puts an x86_64 shell on an arm64 machine back on the non-executing branch. $OS is the platform detected above, not a fresh `uname`: this can run with a scrubbed PATH where uname is not resolvable, and a failed probe there would fall through to executing the shim. _CLT_GIT_SHIM is overridable so the branch is testable without a /usr/bin write.
+ # On Apple Silicon, running the /usr/bin/git CLT shim pops a GUI dialog, so answer from the path.
+ # Intel Macs may have a working /usr/bin/git and still probe it. _CLT_GIT_SHIM is a test hook.
if [ "${OS:-}" = "macos" ] &&
{ [ "${MAC_INTEL:-false}" != true ] || [ "${_MAC_ROSETTA:-false}" = true ]; } &&
[ "$(command -v git)" = "${_CLT_GIT_SHIM:-/usr/bin/git}" ] &&
@@ -3293,7 +3028,7 @@ _has_working_git() {
git --version >/dev/null 2>&1
}
-# macOS system-dependency check. A function so tests/sh can sed-extract it; the old inline form was untestable, which is why this gate shipped broken. The consumer install needs no developer toolchain: uv is a prebuilt binary, CPython is uv-managed, llama.cpp/whisper.cpp/Node are prebuilt downloads, and triton is skipped on macOS. Only `--local` needs git, for the unsloth-zoo git+https URL.
+# A function so tests/sh can sed-extract it. Consumer installs need no toolchain; only --local needs git.
_check_macos_deps() {
_clt_missing=false
xcode-select -p >/dev/null 2>&1 || _clt_missing=true
@@ -3311,34 +3046,31 @@ _check_macos_deps() {
fi
if [ "$_clt_missing" = true ]; then
- # Not fatal, and no GUI dialog: firing xcode-select --install and exiting is what stranded clean Macs.
step "deps" "no Xcode Command Line Tools (not required)" "$C_WARN"
substep "Unsloth installs prebuilt binaries and wheels, so no compiler is needed."
substep "Install them only for a llama.cpp source build: xcode-select --install"
elif command -v cmake >/dev/null 2>&1; then
step "deps" "all system dependencies found"
else
- # cmake is only for a source build, so its absence is not fatal.
step "deps" "using prebuilt llama.cpp (cmake not found)" "$C_WARN"
substep "Install cmake only if you want a source build: brew install cmake"
fi
return 0
}
-# Linux/WSL system-dependency check, split like macOS and a function for the same reason. Only a download transport is required: cmake, gcc and the libcurl headers exist solely for a llama.cpp source build the consumer path never does, since unslothai/llama.cpp publishes linux-x64/arm64 prebuilts for cpu, cuda12, cuda13, rocm and vulkan. Requiring them turned every non-apt distro into a hard exit 1 over unused tooling. git follows macOS: --local only.
+# Only a download transport is required: llama.cpp ships prebuilts, so build tools are optional.
_check_linux_deps() {
_transport_missing=false
if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
_transport_missing=true
fi
- # Wanted, never required: git fetches the triton_kernels git+https requirement (a training speedup), the rest serve the optional source build. Warn, never stop.
+ # Optional: git for triton_kernels, the rest for a source build. Warn, never stop.
_optional_missing=""
command -v cmake >/dev/null 2>&1 || _optional_missing="$_optional_missing cmake"
_has_working_git || _optional_missing="$_optional_missing git"
command -v gcc >/dev/null 2>&1 || _optional_missing="$_optional_missing build-essential"
command -v curl-config >/dev/null 2>&1 || _optional_missing="$_optional_missing libcurl4-openssl-dev"
- # Parameter expansion, not `sed`: sed may be absent on a minimal image, and a failed `$(... | sed ...)` yields "", which reads as "all found" on a machine that has none.
_optional_missing="${_optional_missing# }"
if [ "$STUDIO_LOCAL_INSTALL" = true ] && ! _has_working_git; then
@@ -3350,7 +3082,6 @@ _check_linux_deps() {
return 1
fi
- # The one fatal case: nothing can be downloaded. apt is the only distro family we can drive unattended.
if [ "$_transport_missing" = true ]; then
if command -v apt-get >/dev/null 2>&1; then
echo ""
@@ -3370,10 +3101,8 @@ _check_linux_deps() {
fi
fi
- # Try apt for the optional set too; failing only costs the features warned about below.
if [ -n "$_optional_missing" ] && command -v apt-get >/dev/null 2>&1; then
step "deps" "installing optional build tools: $_optional_missing" "$C_DIM"
- # Subshell because _smart_apt_install exits rather than returns, so `|| true` alone would not catch it. _SMART_APT_OPTIONAL suppresses every escalation path, so no install hinges on a prompt for tools nothing here needs.
( _SMART_APT_OPTIONAL=true; _smart_apt_install $_optional_missing ) || true
_optional_missing=""
command -v cmake >/dev/null 2>&1 || _optional_missing="$_optional_missing cmake"
@@ -3421,7 +3150,7 @@ _bwrap_install_command() {
fi
}
-# Wanted, never required: bubblewrap runs Python and Terminal tool calls in an OS sandbox, and without it they run with software safeguards. Optional like the build tools, so it never asks for sudo: installed when the installer already runs as root, otherwise the one command is printed.
+# Optional: without bubblewrap, tool calls run with software safeguards. Never elevates.
_check_linux_tool_sandbox() {
_bw_restrict=""
_bw_sysctl="${_BW_USERNS_SYSCTL:-/proc/sys/kernel/apparmor_restrict_unprivileged_userns}"
@@ -3434,7 +3163,7 @@ _check_linux_tool_sandbox() {
if ! command -v bwrap >/dev/null 2>&1; then
step "sandbox" "bubblewrap not installed: tool calls run with software safeguards" "$C_WARN"
_bw_cmd="$(_bwrap_install_command)"
- # One copy-paste on Ubuntu 23.10+: installing bwrap alone still leaves it blocked there.
+ # Ubuntu 23.10+ blocks bwrap via AppArmor even when installed.
case "$_bw_restrict:$_bw_cmd" in
1:*apt-get*) _bw_cmd="$_bw_cmd && $_BWRAP_APPARMOR_FIX" ;;
esac
@@ -3445,14 +3174,12 @@ _check_linux_tool_sandbox() {
fi
return 0
fi
- # The runtime's namespaces, not --unshare-all: that adds the network namespace, which tool calls never get.
if bwrap --unshare-user --unshare-pid --unshare-ipc --unshare-uts --unshare-cgroup --ro-bind / / true </dev/null >/dev/null 2>&1; then
step "sandbox" "bubblewrap works: tool calls run in an OS sandbox"
return 0
fi
if [ "$_bw_restrict" = 1 ]; then
step "sandbox" "AppArmor blocks bubblewrap: tool calls run with software safeguards" "$C_WARN"
- # Ubuntu ships this profile disabled in apparmor-profiles; it lets /usr/bin/bwrap create the namespace and strips its children's capabilities.
substep "To enable it, load Ubuntu's own bwrap profile:"
substep " $_BWRAP_APPARMOR_FIX"
else
@@ -3792,7 +3519,6 @@ UV_MIN_VERSION="0.13.4"
# The floor before this raised it. An offline host may keep a uv between the two, since those installs worked without touching the network; below it the installer rejected the uv outright and still has to, or it proceeds on a uv missing flags it is about to be handed (--default-index, --torch-backend).
UV_OFFLINE_MIN_VERSION="0.8.16"
-# Large bytecode-compiled installs can exceed uv's 60s default; use 180s ("0" disables).
: "${UV_COMPILE_BYTECODE_TIMEOUT:=180}"
export UV_COMPILE_BYTECODE_TIMEOUT
@@ -3801,7 +3527,6 @@ export UV_HTTP_RETRIES
: "${UV_HTTP_TIMEOUT:=180}"
export UV_HTTP_TIMEOUT
-# macOS: trust the Keychain via UV_SYSTEM_CERTS (uv >= 0.11) / UV_NATIVE_TLS; 0 opts out.
if [ "$OS" = "macos" ]; then
: "${UV_SYSTEM_CERTS:=1}"
: "${UV_NATIVE_TLS:=$UV_SYSTEM_CERTS}"
@@ -3837,15 +3562,15 @@ version_ge() {
return 0
}
-# Patch releases the stack cannot run, space separated. 3.13.8: python/cpython#139783 makes inspect.getsourcelines() drop a function body when a decorator is followed by a comment, which is the shape torch 2.11's nn/modules/rnn.py has, and _overload_method reads its own source at import time, so `import torch` dies with IndentationError. 3.13.9 was an expedited release carrying only that fix.
+# 3.13.8: python/cpython#139783 breaks inspect.getsourcelines, so `import torch` fails.
PYTHON_SKIP="3.13.8"
-# Every entry above is skipped for one reason: it cannot `import torch`. A --no-torch install never imports it, so refusing the interpreter there would fail a GGUF-only setup on a locked-down host over a package it will not install. SKIP_TORCH is set well before any of this runs.
+# Skips exist only because torch cannot import; --no-torch installs ignore them.
_python_skip_applies() {
[ "$SKIP_TORCH" != true ]
}
-_python_is_skipped() { # full x.y.z version
+_python_is_skipped() {
_python_skip_applies || return 1
for _bad in $PYTHON_SKIP; do
[ "$1" = "$_bad" ] && return 0
@@ -3853,17 +3578,16 @@ _python_is_skipped() { # full x.y.z version
return 1
}
-# uv picks the patch itself for a bare "3.13", so name a range it cannot satisfy with a skipped release rather than checking afterwards. uv accepts a PEP 440 specifier as a python request, and the exclusions come straight from PYTHON_SKIP so there is one list to maintain. Spelled "!=3.13.8" rather than ">=3.13.9" on purpose: a host that is offline, or whose uv is too old to know 3.13.9, may still have a perfectly good cached 3.13.7, and a floor would refuse it and fail the install outright. Measured on uv 0.10.7 with only 3.13.7 and 3.13.8 installed and --offline: "3.13" gives 3.13.8, ">=3.13.9,<3.14" errors, ">=3.13,<3.14,!=3.13.8" gives 3.13.7.
+# Exclude skipped patches with a PEP 440 range ("!=3.13.8", not ">=3.13.9") so an offline
+# host can still use a cached 3.13.7.
_python_request() { # requested version -> what uv is asked for
_python_skip_applies || { echo "$1"; return 0; }
case "$1" in
- # An explicit patch is the caller's own choice, and a path or a uv download name is not a version at all. Pass those through untouched.
[0-9]*.[0-9]*.*|*/*|*\\*) echo "$1"; return 0 ;;
[0-9]*.[0-9]*) ;;
*) echo "$1"; return 0 ;;
esac
_req_minor=${1#*.}
- # Only a plain X.Y gets a range. "3.13rc1", or a relative path like "3.13/bin/python" that slipped past the globs above, would otherwise reach the arithmetic below, and dash aborts the whole install on "Illegal number".
case "$_req_minor" in
''|*[!0-9]*) echo "$1"; return 0 ;;
esac
@@ -3897,12 +3621,11 @@ UV_PINNED_VERSION="0.13.5"
# unpinned-host fallback runs it.
UV_INSTALLER_SH_SHA256="1c6e7f025499664633ac2dce43a210800510e9ef0625c52e034a8afdf8bf177a"
-# Echoes the glibc minor version (the N in 2.N), or nothing when this is not a glibc host or the version cannot be read. "not musl" is not the same as "a glibc new enough to run the GNU build": astral's installer checks a minimum and drops to its musl-static archive below it, so a host we cannot positively confirm has to reach the fallback rather than take a binary that will not exec.
+# Prints the glibc minor or nothing; an unconfirmed host must fall back to astral's musl build.
_uv_glibc_minor() {
_ugm_line=$( (ldd --version 2>/dev/null || true) | head -1 )
case "$_ugm_line" in *[Mm]usl*) return 1 ;; esac
_ugm_ver=$(printf '%s\n' "$_ugm_line" | awk '{print $NF}')
- # getconf is the fallback for an ldd that prints no version, and for hosts with no ldd.
case "$_ugm_ver" in
2.[0-9]*) : ;;
*) _ugm_ver=$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $NF}') ;;
@@ -3915,15 +3638,12 @@ _uv_glibc_minor() {
return 0
}
-# Prints "<asset> <sha256>" for this host, or nothing when the host is not pinned.
_uv_pinned_asset() {
_upa_os=$(uname -s 2>/dev/null || echo unknown)
_upa_arch=$(uname -m 2>/dev/null || echo unknown)
case "$_upa_os" in
Linux)
- # A 64-bit kernel under a 32-bit userland reports x86_64 from uname but cannot load a 64-bit binary, so ask the userland, not the kernel.
[ "$(getconf LONG_BIT 2>/dev/null || echo 0)" = "64" ] || return 1
- # Rejects musl, an unreadable libc, and a glibc below astral's floor for the triple.
_upa_glibc=$(_uv_glibc_minor) || return 1
case "$_upa_arch" in
x86_64|amd64)
@@ -3936,7 +3656,7 @@ _uv_pinned_asset() {
esac
;;
Darwin)
- # Under Rosetta 2 a translated shell reports x86_64 on an Apple Silicon Mac. astral reads the same sysctl and ships the native build; matching it keeps the uv the user ends up with identical to the one they had before.
+ # Under Rosetta, astral ships the native arm64 build; match it.
if [ "$_upa_arch" = "x86_64" ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then
_upa_arch=arm64
fi
@@ -3967,7 +3687,6 @@ _uv_pinned_wheel() {
esac
}
-# A wheel is a zip, which GNU tar cannot read and minimal Linux images often have no unzip for.
_uv_unzip() {
if command -v unzip >/dev/null 2>&1 && unzip -qo "$1" -d "$2" >/dev/null 2>&1; then return 0; fi
case "$(tar --version 2>/dev/null)" in
@@ -3977,7 +3696,6 @@ _uv_unzip() {
python3 -m zipfile -e "$1" "$2" >/dev/null 2>&1
}
-# Echoes the SHA-256 of "$1", or nothing when the host has no digest tool.
_uv_sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" 2>/dev/null | awk '{print $1}'
@@ -3986,19 +3704,16 @@ _uv_sha256() {
fi
}
-# Liveness probe for a fresh binary, hang-proof: no stdin (a prompting build reads EOF) and a
-# ceiling, held by `timeout -k` where it exists and by a watchdog on stock macOS, which has none.
+# Hang-proof liveness probe: no stdin and a ceiling (timeout -k, or a watchdog on macOS).
_uv_signal_target() {
- # bash reads a bare negative pid as a signal spec, dash refuses the `--` that fixes bash, and
- # only a shell that made a process group produces a negative target: the sign picks the form.
+ # bash reads a bare negative pid as a signal spec and dash refuses `--`; the sign picks the form.
case "$2" in
-*) kill "-$1" -- "$2" 2>/dev/null || : ;;
*) kill "-$1" "$2" 2>/dev/null || : ;;
esac
}
-# TERM, then KILL what ignored it, as `timeout -k` does where it exists.
-# $1 target (a group when one was made, else the pid), $2 pid to watch, $3 seconds of grace.
+# TERM, then KILL, as `timeout -k` does. $1 target, $2 pid to watch, $3 grace seconds.
_uv_probe_terminate() {
_upt_grace=0
_uv_signal_target TERM "$1"
@@ -4006,29 +3721,23 @@ _uv_probe_terminate() {
sleep 1
_upt_grace=$((_upt_grace + 1))
done
- # Only if it is still there: the loop also ends when TERM worked, and the KILL would go out
- # anyway, to a number this shell no longer owns.
if kill -0 "$2" 2>/dev/null; then _uv_signal_target KILL "$1"; fi
unset _upt_grace
}
_uv_probe_exec() {
_upe_secs="${_UV_PROBE_SECONDS:-20}"
- # KILL after TERM (TERM can be ignored): `timeout -k` where supported, else the watchdog below.
if command -v timeout >/dev/null 2>&1 && timeout -k 1 5 true >/dev/null 2>&1; then
timeout -k 5 "$_upe_secs" "$1" --version >/dev/null 2>&1 </dev/null
return $?
fi
- # Monitor mode gives the probe a process group of its own, so the signals below reach what IT
- # started, as `timeout`'s do. Off again at once.
+ # Monitor mode gives the probe its own process group so signals reach its children.
_upe_monitor=off
case "$-" in *m*) _upe_monitor=on ;; esac
[ "$_upe_monitor" = on ] || set -m 2>/dev/null || :
"$1" --version >/dev/null 2>&1 </dev/null &
_upe_pid=$!
[ "$_upe_monitor" = on ] || set +m 2>/dev/null || :
- # The group only where it is provably not this shell's own, else the single pid as before.
- # Parameter expansion, not `tr`: this branch has to hold on a bare PATH.
_upe_target="$_upe_pid"
if command -v ps >/dev/null 2>&1; then
_upe_pgid=$(ps -o pgid= -p "$_upe_pid" 2>/dev/null)
@@ -4040,8 +3749,7 @@ _uv_probe_exec() {
*) [ "$_upe_pgid" = "$_upe_self" ] || _upe_target="-$_upe_pgid" ;;
esac
fi
- # Published for _cleanup_install_temporaries: the installer's HUP/INT/TERM handlers run it,
- # so a cancel during the wait kills the probe instead of orphaning it.
+ # Published so the HUP/INT/TERM handlers kill the probe instead of orphaning it.
_UV_PROBE_TARGET="$_upe_target"
_UV_PROBE_PID="$_upe_pid"
_upe_waited=0
@@ -4071,11 +3779,9 @@ _uv_install_pinned() {
[ -n "$_uip_spec" ] || return 1
_uip_asset=${_uip_spec%% *}
_uip_want=${_uip_spec##* }
- # Unverified is worth less than astral's own release flow, so decline instead.
command -v tar >/dev/null 2>&1 || return 1
if [ -z "$(_uv_sha256 /dev/null)" ]; then return 1; fi
- # astral's destination priority, so an existing uv is replaced in place and the PATH lines below still find it.
_uip_dest=""
for _uip_candidate in "${_STUDIO_UV_DIR:-}" "${UV_INSTALL_DIR:-}" "${UV_UNMANAGED_INSTALL:-}" "${XDG_BIN_HOME:-}"; do
if [ -n "$_uip_candidate" ]; then _uip_dest="$_uip_candidate"; break; fi
@@ -4086,11 +3792,10 @@ _uv_install_pinned() {
_uip_dest="$HOME/.local/bin"
fi
- # 2>/dev/null: this is a speculative attempt whose failure falls back to astral's installer, so an unusable $TMPDIR must not print a line the user cannot act on.
_uip_work=$(mktemp -d 2>/dev/null) || return 1
_UIP_WORK="$_uip_work"
_uip_rc=1
- # astral's mirrors and precedence; each serves the identical asset, so one pin holds. A configured mirror is EXCLUSIVE, as it is for astral: a restricted network sets one because the public hosts are unreachable, and download() has no timeout, so trying them first would hang rather than fall through.
+ # A configured mirror is exclusive, as for astral; download() has no timeout.
if [ -n "${UV_DOWNLOAD_URL:-}" ]; then
_uip_bases="${UV_DOWNLOAD_URL%/}"
elif [ -n "${INSTALLER_DOWNLOAD_URL:-}" ]; then
@@ -4113,12 +3818,11 @@ https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"
fi
_UIP_UNFETCHED=true
for _uip_base in $_uip_bases; do
- # 2>/dev/null: curl -sS prints its own errors and these attempts are speculative, so an unreachable mirror stays off the console when the install still succeeds.
if ! download "$_uip_base/$_uip_asset" "$_uip_work/$_uip_asset" 2>/dev/null; then continue; fi
_UIP_UNFETCHED=false
_uip_got=$(_uv_sha256 "$_uip_work/$_uip_asset")
if [ "$_uip_got" != "$_uip_want" ]; then
- # Not tauri_log: [TAURI:WARN] is a marker install.sh has never emitted, and the app forwards unknown markers to its progress UI verbatim. Verbose only, since the next mirror or the fallback still runs.
+ # Not tauri_log: the app shows unknown [TAURI:*] markers verbatim in its progress UI.
if _is_verbose; then
echo "uv archive digest mismatch from $_uip_base, trying the next source" >&2
fi
@@ -4130,20 +3834,19 @@ https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"
esac
mkdir -p "$_uip_dest" 2>/dev/null || break
_uip_placed=0
- # uv first, and either half failing aborts the placement: the two ship as a set, and a pinned uvx beside the host's older uv is a pairing we never built or tested. Stage both, then publish both: the renames sit next to each other so the pair is replaced as one, and a failure anywhere before them leaves the destination untouched.
+ # uv and uvx ship as a set: stage both, then publish both, or touch nothing.
_uip_ready=1
for _uip_exe in uv uvx; do
- # `mv f d` moves f INTO d and reports success, and a searchable directory passes -x too, so a directory called uv at the destination would look like a published binary and skip the fallback.
if [ -d "$_uip_dest/$_uip_exe" ]; then _uip_ready=0; break; fi
_uip_src=$(find "$_uip_work" -type f -name "$_uip_exe" 2>/dev/null | head -1)
if [ -z "$_uip_src" ] || [ ! -f "$_uip_src" ]; then _uip_ready=0; break; fi
- # cp onto a symlinked destination writes through it and would rewrite, say, the Homebrew binary `~/.local/bin/uv` points at; rename replaces the link. mktemp, not a fixed name, so two installers racing here cannot publish each other's file.
+ # Rename, not cp: cp writes through a symlinked destination. mktemp avoids racing installers.
_uip_stage=$(mktemp "$_uip_dest/.$_uip_exe.XXXXXX" 2>/dev/null) || { _uip_ready=0; break; }
if [ "$_uip_exe" = "uv" ]; then _UIP_STAGE="$_uip_stage"; else _UIP_STAGE2="$_uip_stage"; fi
if ! cp -f "$_uip_src" "$_uip_stage" 2>/dev/null; then _uip_ready=0; break; fi
- # 0755, not +x: the staging file carries the umask default and +x only adds execute where read was allowed, so umask 077 would leave uv unusable for every other account. astral ships these 0755.
+ # 0755, not +x: under umask 077, +x leaves uv unusable for other accounts.
chmod 0755 "$_uip_stage" 2>/dev/null || true
- # Validate BEFORE publishing: the rename destroys the incumbent, and a missing loader or a noexec mount would leave the host with neither. The staging file is on the destination filesystem, so this answers noexec too.
+ # Validate before publishing: the rename destroys the incumbent (noexec, missing loader).
if [ "$_uip_exe" = "uv" ] && ! _uv_probe_exec "$_uip_stage"; then _uip_ready=0; break; fi
done
if [ "$_uip_ready" = "1" ] &&
@@ -4157,7 +3860,6 @@ https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"
# The staged binary already answered --version above, before it replaced anything.
if [ "$_uip_placed" = "1" ] && [ -x "$_uip_dest/uv" ]; then
export PATH="$_uip_dest:$PATH"
- # Where uv landed, for the profile write below: UV_INSTALL_DIR and friends can put it outside ~/.local/bin, and that directory has to reach a new shell too.
_UNSLOTH_UV_BIN_DIR="$_uip_dest"
_uip_rc=0
fi
@@ -4167,7 +3869,7 @@ https://github.com/astral-sh/uv/releases/download/$UV_PINNED_VERSION"
_UIP_WORK=""
_UIP_STAGE=""
_UIP_STAGE2=""
- # Nothing is unwound on the failure path on purpose: the fallback installs over whatever is at the destination, and deleting there would take out a working uv the host already had.
+ # Nothing is unwound on failure: deleting could remove a working uv the host already had.
return "$_uip_rc"
}
@@ -4185,7 +3887,7 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv || [ "$_STUDIO_UV_STAL
# Raising the floor pulled every 0.8.16-0.13.3 host into this block, and those installs used to succeed without touching the network, so a download failure must not be fatal for them. An unreadable version counts as present: that is a minimal image without awk, not an old uv.
_uv_present_before=false
if command -v uv >/dev/null 2>&1; then
- # `|| _uv_prev_ver=`: on an image with no awk the pipeline exits 127 and set -e would kill the install here, which is exactly the host this block exists to keep working.
+ # `|| _uv_prev_ver=`: without awk the pipeline exits 127 and set -e would kill the install.
_uv_prev_ver=$(uv --version 2>/dev/null | awk '{print $2}' 2>/dev/null) \
|| _uv_prev_ver=""
if [ -z "$_uv_prev_ver" ] || _uv_version_ok uv "$UV_OFFLINE_MIN_VERSION"; then
@@ -4194,7 +3896,6 @@ if ! command -v uv >/dev/null 2>&1 || ! _uv_version_ok uv || [ "$_STUDIO_UV_STAL
fi
substep "installing uv package manager..."
_uv_refreshed=true
- # download() exits the shell outright when neither curl nor wget is present, which an `if` cannot catch, so probe first: a minimal image with uv copied in but no downloader must keep the install it had before the floor moved.
if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then
# Pinned release first: fetch a digest-checked data file rather than download-run-delete a remote script. See tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
if _uv_install_pinned || { [ "$_UIP_UNFETCHED" = true ] && _mirror_switch uvbin && _uv_install_pinned; }; then
@@ -4264,14 +3965,11 @@ tauri_log "STEP" "Creating virtual environment"
mkdir -p "$STUDIO_HOME"
_MIGRATED=false
-# Empty so an inherited value can never masquerade as a probed torch version.
_PREV_TORCH_VER=""
-# Any earlier environment in this home, readable or not: only a home without one takes a new-install torch default.
_EXISTING_INSTALL=false
# The release being replaced, shown next to the new one at the end (#9910).
_PREV_PACKAGE_VERSION=""
-# Replace occupied venvs even when bin/python is missing or dangling, as in the repair loop reported in #9479.
if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
# why: matching guard to the .venv branch below -- in env-mode $STUDIO_HOME is user-chosen, so refuse to nuke an existing unsloth_studio that lacks Unsloth sentinels; accept the in-VENV marker so partial-install retries are not blocked. The root marker goes through _claim_sentinel, not -f: the claim refuses to write one through a link, so reading one through a link here would undo that. The older sentinels keep -f, since bin/unsloth is legitimately a symlink into the venv.
if [ "$_STUDIO_HOME_REDIRECT" = "env" ] \
@@ -4284,7 +3982,8 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
exit 1
fi
_EXISTING_INSTALL=true
- # Record the existing venv's torch BEFORE the replacement moves it aside: a re-run rebuilds the venv for clean state, but must keep the torch release the user already has. Last line only, so sitecustomize or import-hook noise on stdout cannot corrupt the version. Disk first, no interpreter: `import torch` can block forever on a wedged Intel driver, and this runs before setup.sh's bounded probes. version.py carries the same label; the interpreter stays as the fallback for a layout without one.
+ # Record the old torch before the venv moves aside. Read version.py first: `import torch` can
+ # hang on a wedged Intel driver.
_PREV_TORCH_VER=""
for _prev_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
[ -f "$_prev_tv" ] || continue
@@ -4302,14 +4001,12 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then
else
substep "preserving existing environment for rollback..."
fi
- # A bare call still aborts under `set -e`, but shows only mv's own stderr. install.ps1 reports this step; say the same here and name the directory.
if ! _start_studio_venv_replacement "$VENV_DIR"; then
echo "ERROR: could not move $VENV_DIR aside to reinstall." >&2
echo " Check that $STUDIO_HOME is writable, or move $VENV_DIR yourself and re-run." >&2
exit 1
fi
elif [ "$_STUDIO_HOME_REDIRECT" != "env" ] && [ -x "$STUDIO_HOME/.venv/bin/python" ]; then
- # Old layout: validate before migrating (env-mode skips it); no-torch checks Python only.
substep "found legacy Unsloth environment, validating..."
_EXISTING_INSTALL=true
for _prev_tv in "$STUDIO_HOME"/.venv/lib/python*/site-packages/torch/version.py; do
@@ -4336,7 +4033,7 @@ torch.testing.assert_close(torch.unique(E), torch.tensor((20,), device=E.device,
fi
if [ "$_legacy_ok" = true ]; then
echo "✅ Legacy environment is healthy — migrating..."
- # `mv` into an existing directory nests the environment inside it ($VENV_DIR/.venv) rather than renaming it, and uv then refuses that target as in #9479. This branch already means $VENV_DIR is absent or empty, so clear it: rmdir cannot take one that gained an entry since the check, and unlinking a symlink never touches its target.
+ # `mv` into an existing directory nests it (#9479), so clear the empty target first.
if [ -L "$VENV_DIR" ]; then
rm -f "$VENV_DIR"
elif [ -d "$VENV_DIR" ] && ! rmdir "$VENV_DIR" 2>/dev/null; then
@@ -4353,7 +4050,6 @@ torch.testing.assert_close(torch.unique(E), torch.tensor((20,), device=E.device,
mv "$STUDIO_HOME/.venv" "$_invalid_venv" 2>/dev/null || true
fi
elif [ "$_STUDIO_HOME_REDIRECT" != "env" ] && _dir_has_entries "$STUDIO_HOME/.venv"; then
- # A legacy .venv whose interpreter is missing or dangling is still an earlier install: keep the old torch range, not the new-install one.
_EXISTING_INSTALL=true
for _prev_tv in "$STUDIO_HOME"/.venv/lib/python*/site-packages/torch/version.py; do
[ -f "$_prev_tv" ] || continue
@@ -4371,12 +4067,12 @@ if [ "$SKIP_TORCH" = true ] && [ "$MAC_INTEL" = true ] && [ -z "$_USER_PYTHON" ]
fi
fi
-# uv unconditionally invokes install_name_tool after downloading managed CPython on macOS. On a consumer Mac without developer tools, Apple's /usr/bin shim opens the Command Line Tools installer even though uv treats patch failure as a warning, and there is no supported uv opt-out yet (astral-sh/uv#14893). Do not execute install_name_tool or xcrun to probe it: either probe can launch the same dialog. A selected standalone CLT and full Xcode have stable on-disk locations.
+# uv runs install_name_tool on macOS, which pops the CLT dialog without dev tools
+# (astral-sh/uv#14893). Do not execute it or xcrun to probe.
_macos_has_selected_install_name_tool() {
_uvv_developer_dir=$(xcode-select -p 2>/dev/null) || return 1
[ -n "$_uvv_developer_dir" ] && [ -d "$_uvv_developer_dir" ] || return 1
- # DEVELOPER_DIR may select a custom path or symlink, so do not require Apple's standard directory names. Reject only candidates that are the base-system /usr/bin dialog shim itself; comparing file identity does not execute the tool.
for _uvv_tool in \
"$_uvv_developer_dir/usr/bin/install_name_tool" \
"$_uvv_developer_dir/Toolchains/XcodeDefault.xctoolchain/usr/bin/install_name_tool"; do
@@ -4390,7 +4086,7 @@ _macos_has_selected_install_name_tool() {
return 1
}
-# Run one uv venv command with its argv unchanged. If no real selected macOS tool is present, put a non-success shim ahead of /usr/bin only for uv's process. Returning nonzero is intentional: uv must retain its warning path rather than being told that an unpatched dylib was successfully modified.
+# Without a real install_name_tool, shim a failing one for uv only, so uv keeps its warning path.
_run_uv_venv() { # label, uv-venv args...
_uvv_label="$1"
shift
@@ -4426,7 +4122,8 @@ _run_uv_venv() { # label, uv-venv args...
return "$_uvv_status"
}
-# Apple Silicon venv. The arch-explicit arm64 CPython stops uv reusing a cached x86_64 (Rosetta) build: torch ships no macOS x86_64 wheels since 2.2.2, so an x86_64 venv cannot resolve torch. only-managed stops uv walking PATH and EXECUTING every interpreter it finds to read its version, which without CLT pops the "command line developer tools" dialog via Apple's /usr/bin/python3 shim. Spelled --python-preference, not the --managed-python alias: same effect, accepted since uv 0.4.30 rather than 0.8.16. It also drops uv's system-interpreter fallback, so a host that is offline or has UV_PYTHON_DOWNLOADS=never is left with nothing to resolve; retry unflagged for them, since the dialog is worth removing and a failed install is not.
+# arm64 CPython so uv does not reuse a cached x86_64 (Rosetta) build; torch has no macOS x86_64
+# wheels. only-managed avoids executing /usr/bin/python3 (CLT dialog); retry unflagged offline.
_uv_venv_arm64() { # label
_run_uv_venv "$1" "$VENV_DIR" \
--python-preference only-managed \
@@ -4435,11 +4132,10 @@ _uv_venv_arm64() { # label
--python "cpython-${PYTHON_VERSION}-macos-aarch64-none"
}
-# Fedora sets python-downloads = "manual", so uv venv cannot fetch a matching interpreter. Install it only after that hint, then retry. An explicit install still honors "never"; UV_PYTHON_DOWNLOADS=automatic would not.
+# Fedora sets python-downloads = "manual"; install the interpreter explicitly, then retry.
_uv_venv_requested() { # label
_uvvr_label="$1"
_uvvr_req="$(_python_request "$PYTHON_VERSION")"
- # Capture the hint while streaming Unsloth output live. If capture setup fails, use the original venv path. The global directory is owned by trap cleanup.
_UV_VENV_CAPTURE_DIR=""
if ! command -v tee >/dev/null 2>&1 \
|| ! _UV_VENV_CAPTURE_DIR=$(mktemp -d "${TMPDIR:-/tmp}/unsloth-uv-venv.XXXXXX") \
@@ -4451,7 +4147,6 @@ _uv_venv_requested() { # label
fi
_uvvr_out="$_UV_VENV_CAPTURE_DIR/out"
_uvvr_err="$_UV_VENV_CAPTURE_DIR/err"
- # BSD tee supports -u; GNU tee is already unbuffered.
tee -u /dev/null </dev/null >/dev/null 2>&1 && _uvvr_tee_u=-u || _uvvr_tee_u=
tee $_uvvr_tee_u "$_uvvr_out" < "$_UV_VENV_CAPTURE_DIR/out_pipe" &
_uvvr_tee_out=$!
@@ -4493,7 +4188,6 @@ if [ ! -x "$VENV_DIR/bin/python" ]; then
fi
fi
-# Mark the freshly-created venv as Unsloth-owned (env-mode deletion guard's primary sentinel).
if [ -x "$VENV_DIR/bin/python" ]; then
: > "$VENV_DIR/.unsloth-studio-owned" 2>/dev/null || true
fi
@@ -4508,9 +4202,8 @@ if [ -z "$_USER_PYTHON" ] && [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
_info=$(_inspect_venv)
_VENV_ARCH=${_info%% *}
_PY_VER=${_info##* }
- # An unexecutable x86_64 venv python (no Rosetta) yields no arch; read the Mach-O header.
if [ -z "$_VENV_ARCH" ] && [ -x "$VENV_DIR/bin/python" ]; then
- # uv symlinks bin/python to the base interpreter, so dereference with file -L (lipo already follows the link). Trailing || true keeps the installer alive under set -e when neither tool is present. file -L FIRST, lipo only as the fallback: lipo is a Command Line Tools shim, so on a Mac without CLT merely running it raises the developer-tools dialog, and 2>/dev/null hides its stderr but not a GUI dialog. file is base-system and always answers, and both spellings feed the same case below, so the branch taken is unchanged.
+ # file -L first: lipo is a CLT shim and running it can pop a GUI dialog.
_archs=$(file -L "$VENV_DIR/bin/python" 2>/dev/null \
|| lipo -archs "$VENV_DIR/bin/python" 2>/dev/null || true)
case "$_archs" in
@@ -4527,7 +4220,6 @@ if [ -z "$_USER_PYTHON" ] && [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
if [ -x "$VENV_DIR/bin/python" ]; then
: > "$VENV_DIR/.unsloth-studio-owned" 2>/dev/null || true
fi
- # Re-inspect: the recreated arm64 venv may still be 3.13.8.
_info=$(_inspect_venv)
_VENV_ARCH=${_info%% *}
_PY_VER=${_info##* }
@@ -4565,7 +4257,7 @@ if [ -x "$VENV_DIR/bin/python" ]; then
substep "${VENV_DIR}"
fi
-# Default range admits torch 2.11 (verified on cpu/cu126/cu128/cu130/rocm7.1+/mac arm64). Bump all three ceilings when the next minor is validated; the curated ROCm floors below stay literal.
+# Bump all three ceilings when the next minor is validated; ROCm floors below stay literal.
_TORCH_CEILING="2.12.0"
_TORCHVISION_CEILING="0.27.0"
_TORCHAUDIO_CEILING="2.12.0"
@@ -4587,25 +4279,23 @@ _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)"
-# Whether the scripts next to install.sh may be trusted. A piped web install has $0 = "sh", so _REPO_ROOT is just the caller's cwd and a file planted there would run. Marker files cannot decide this (whoever can plant a helper can plant those), so require the explicit --local intent AND a run from the file itself; else fetch the official copy.
+# Trust adjacent scripts only for an explicit --local run from the file itself; a piped install's
+# _REPO_ROOT is the caller's cwd, where a planted file would run.
_REPO_IS_CHECKOUT=0
case "$0" in
*/install.sh|install.sh)
[ "$STUDIO_LOCAL_INSTALL" = true ] && [ -r "$0" ] && _REPO_IS_CHECKOUT=1 ;;
esac
-# Honor UNSLOTH_ZOO_REF so the Studio venv tracks the requested zoo (the Docker publish workflow forwards one ref to both builds). Unset means main.
_ZOO_REF="${UNSLOTH_ZOO_REF:-main}"
_ZOO_GIT_SPEC="unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo@${_ZOO_REF}"
# ── Helper: find no-torch-runtime.txt (local repo or site-packages) ──
_find_no_torch_runtime() {
- # Local copy only for a --local checkout run: a piped install's _REPO_ROOT is the caller's cwd.
if [ "$_REPO_IS_CHECKOUT" = "1" ] && [ -f "$_REPO_ROOT/studio/backend/requirements/no-torch-runtime.txt" ]; then
echo "$_REPO_ROOT/studio/backend/requirements/no-torch-runtime.txt"
return
fi
- # Check inside installed package
_rt=$(find "$VENV_DIR" -path "*/studio/backend/requirements/no-torch-runtime.txt" -print -quit 2>/dev/null || echo "")
if [ -n "$_rt" ]; then
echo "$_rt"
@@ -4614,7 +4304,6 @@ _find_no_torch_runtime() {
}
# ── AMD ROCm GPU detection helper ──
-# WSL2 ROCDXG: rocminfo needs HSA_ENABLE_DXG_DETECTION=1 and /opt/rocm/bin on PATH; seed both.
_ensure_rocm_probe_env() {
export HSA_ENABLE_DXG_DETECTION="${HSA_ENABLE_DXG_DETECTION:-1}"
if ! command -v rocminfo >/dev/null 2>&1 && [ -x /opt/rocm/bin/rocminfo ]; then
@@ -4622,13 +4311,9 @@ _ensure_rocm_probe_env() {
fi
}
-# Whether this run was TOLD to install ROCm torch, whatever else the host has: the automatic
-# profile stops probing AMD once CUDA is usable, leaving a mixed host no route (#10450). One
-# torch install serves one vendor, so this SWAPS the stack.
+# True when the run was told to install ROCm torch even with CUDA usable (#10450).
# Mirrors install_python_stack._rocm_torch_explicitly_requested; keep the two in step.
_rocm_torch_explicitly_requested() {
- # Trimmed, because the Python twin reads the same variable through .strip(): untrimmed,
- # " true " exports an authoritative CUDA backend the Python half then cannot override.
case "$(printf '%s' "${UNSLOTH_FORCE_ROCM_TORCH:-}" \
| sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')" in
1|true|yes|on) return 0 ;;
@@ -4636,13 +4321,7 @@ _rocm_torch_explicitly_requested() {
esac
}
-# Whether ROCm can see an AMD GPU. A usable NVIDIA card wins by default; a diagnosis that
-# has already established the run opens AMD nodes passes "ignore-nvidia" to skip that, and an
-# explicit UNSLOTH_FORCE_ROCM_TORCH request relaxes it for every caller.
-# The veto is inside this function rather than in a wrapper, because every tests/sh harness
-# lifts probes one function at a time by name (sed -n '/^_name()/,/^}/p'), and a wrapper
-# whose helper is not also lifted calls nothing: the ROCm branch would then fall silently
-# through to the CPU wheel index.
+# The NVIDIA veto lives inside this function because tests/sh lifts probes one function at a time.
_has_amd_rocm_gpu() {
_ensure_rocm_probe_env
if [ "${1:-}" != "ignore-nvidia" ] && _has_usable_nvidia_gpu && \
@@ -4658,20 +4337,16 @@ _has_amd_rocm_gpu() {
elif [ -e /dev/kfd ] && \
awk '/vendor_id/ && $2 == 4098 { found = 1 } END { exit !found }' \
/sys/class/kfd/kfd/topology/nodes/*/properties 2>/dev/null; then
- # vendor_id 4098 = 0x1002 (AMD) marks a GPU node: the KFD CPU node reports vendor_id 0, so any 4098 node is an AMD GPU, and NVIDIA's open kernel module (driver 560+) registers KFD nodes as vendor_id 4318 (0x10DE), so this never false-positives on NVIDIA-only hosts. The prior check also required a gpu_id line, but gpu_id is a SIBLING sysfs file, not a line in properties, so it never matched and the fallback silently missed every ROCm-less AMD host.
+ # vendor_id 4098 (0x1002) is AMD; KFD CPU nodes report 0 and NVIDIA's open module 4318.
return 0
fi
return 1
}
-# AMD silicon this host can point at WITHOUT trusting a declared arch:
-# _infer_linux_amd_gfx_arch returns UNSLOTH_ROCM_GFX_ARCH before it looks at hardware, so it
-# cannot answer "is there a card" and a stale one would hand a working CUDA stack to no GPU.
+# Hardware-only check: _infer_linux_amd_gfx_arch returns a declared arch before probing.
_amd_hardware_corroborated() {
_amd_gpu_present_via_pci && return 0
- # WSL enumerates no PCI display device, and neither /dev/dxg (an NVIDIA passthrough creates
- # it too) nor a leftover librocdxg names a vendor: beside an NVIDIA card the runtime must
- # name an agent itself, hence "physical" mode.
+ # On WSL neither /dev/dxg nor librocdxg names a vendor, hence "physical" mode.
if [ -e /dev/dxg ] || grep -qi microsoft /proc/version 2>/dev/null; then
for _ahc_d in /opt/rocm/lib /opt/rocm/lib64 /opt/rocm-*/lib /opt/rocm-*/lib64; do
{ [ -e "$_ahc_d/librocdxg.so" ] || [ -e "$_ahc_d/librocdxg.so.1" ]; } || continue
@@ -4683,11 +4358,9 @@ _amd_hardware_corroborated() {
return 1
}
-# Whether ANY index this installer can pick carries kernels for this arch. An arch in neither
-# (gfx1010, RDNA 1) must never depose a card that can.
+# Whether any index carries kernels for this arch (gfx1010 has none).
# Mirrors _gfx_has_a_wheel_route / _GENERIC_ROCM_WHEEL_GFX in install_python_stack.py.
_amd_gfx_has_wheel_route() {
- # A per-arch index carries its arch whatever the generic tag resolves to, so it answers first.
_amd_arch_index_family_for_gfx "$1" >/dev/null 2>&1 && return 0
case "$1" in
gfx900|gfx906|gfx908|gfx90a|gfx942|gfx950) : ;;
@@ -4697,9 +4370,8 @@ _amd_gfx_has_wheel_route() {
_amd_generic_tag_carries_gfx "$1"
}
-# Whether the generic wheel THIS host resolves carries kernels for an arch whose only route is
-# that wheel. Tag comes from the installed ROCm version, so a stale /opt/rocm resolves a wheel
-# predating the card; unreadable answers NO. Mirrors _GENERIC_WHEEL_GFX_MIN_ROCM (python twin).
+# Whether the generic wheel for this host's ROCm version covers the arch; unreadable is NO.
+# Mirrors _GENERIC_WHEEL_GFX_MIN_ROCM.
_amd_generic_tag_carries_gfx() {
case "$1" in
gfx950|gfx1150|gfx1151) _agtc_min_major=7; _agtc_min_minor=0 ;;
@@ -4718,9 +4390,7 @@ _amd_generic_tag_carries_gfx() {
return 1
}
-# True when a set mask exposes NO GPU at either layer. ROCr filters BENEATH HIP, and
-# CUDA_VISIBLE_DEVICES is HIP's alias, read only when HIP is unset. ${VAR+x} not ${VAR:-}: a
-# SET-but-empty mask hides every device. Mirrors _visible_masks_select_no_gpu.
+# ${VAR+x}: a set-but-empty mask hides every device. Mirrors _visible_masks_select_no_gpu.
_amd_visible_masks_select_no_gpu() {
if [ -n "${HIP_VISIBLE_DEVICES+x}" ]; then
_avm_hip=HIP_VISIBLE_DEVICES
@@ -4738,14 +4408,8 @@ _amd_visible_masks_select_no_gpu() {
return 1
}
-# One mask layer applied to a per-DEVICE list, in mask order, never deduplicated. Survivors are
-# the PREFIX of resolvable ordinals, since CUDA and HIP stop at the first entry naming no device.
-# A third argument of "rocr" also ends the prefix at a REPEATED ordinal, which ROCr terminates on
-# (ROCR-Runtime, core/inc/amd_filter_device.h); clr documents no such rule for HIP.
+# Survivors are the prefix of resolvable ordinals; ROCr also stops at a repeated ordinal.
_amd_mask_survivors() {
- # The mask arrives through the environment, not `awk -v`: an assignment operand is
- # ESCAPE-PROCESSED, so HIP_VISIBLE_DEVICES='\061' became the ordinal 1 here while the Python
- # twin rejects it at int().
printf '%s\n' "$1" | _ams_vis="$2" _ams_layer="${3:-}" awk '
BEGIN { vis = ENVIRON["_ams_vis"]; layer = ENVIRON["_ams_layer"] }
NF { vals[n++] = $0 }
@@ -4763,16 +4427,13 @@ _amd_mask_survivors() {
}'
}
-# The single arch the runtime will hand torch, empty when the masks resolve nothing. Resolved
-# here, not by a probe: rocminfo honours only ROCR_VISIBLE_DEVICES and amd-smi neither. The
-# layers COMPOSE, ROCr filtering and renumbering beneath HIP, and the FIRST survivor wins.
+# ROCr filters and renumbers beneath HIP; the first survivor wins.
_amd_runtime_gfx_target() {
_argt_list="$1"
if [ -n "${ROCR_VISIBLE_DEVICES:-}" ]; then
_argt_list=$(_amd_mask_survivors "$_argt_list" "$ROCR_VISIBLE_DEVICES" rocr)
[ -n "$_argt_list" ] || return 0
fi
- # CUDA_VISIBLE_DEVICES is the HIP alias and clr reads it only when HIP itself is unset.
_argt_hip="${HIP_VISIBLE_DEVICES:-}"
if [ -z "${HIP_VISIBLE_DEVICES+x}" ]; then
_argt_hip="${CUDA_VISIBLE_DEVICES:-}"
@@ -4784,9 +4445,7 @@ _amd_runtime_gfx_target() {
printf '%s\n' "$_argt_list" | awk 'NF { print; exit }'
}
-# The AMD integrated GPUs that shadow a discrete card by enumerating ahead of it. Mirror of
-# _SHADOWING_INTEGRATED_GFX, held to it by tests/studio/install/test_rocm_arch_table_parity.py:
-# one installer having this table and not the other is the shape of #7264 / #7277 / #7293.
+# Mirror of _SHADOWING_INTEGRATED_GFX, held to it by tests/studio/install/test_rocm_arch_table_parity.py.
_amd_gfx_is_shadowing_integrated() {
case "$1" in
gfx90c|gfx1013|gfx1033|gfx1035|gfx1036|gfx1103|gfx1153) return 0 ;;
@@ -4848,29 +4507,16 @@ _amd_prefer_discrete_gfx() {
printf '%s' "$_apdg_pick"
}
-# Whether the request has something to swap TO: a corroborated card whose arch an index can
-# serve. Presence is not that bar -- gfx1010 is present with no route, and gfx906 drops when a
-# second AMD arch is present.
_amd_request_has_a_wheel_route() {
- # The card this run hands torch, published for get_torch_index_url's miscomputing-arch gate,
- # which has only the unmasked inventory to judge on. Cleared on ENTRY so a previous call can
- # never answer for this one.
_AMD_REQUEST_TARGET_GFX=""
- # Only a PROBE-resolved target may clear a safety gate, or a declared gfx1030 would exempt a
- # physical gfx1033 from the Van Gogh gate. Declared still routes (the Strix workaround
- # declares gfx1100 on a gfx1151), it just cannot vouch for the machine.
+ # Only a probe-resolved target may clear a safety gate; a declared one just routes.
_AMD_REQUEST_TARGET_SOURCE=""
- # A mask exposing no device is a deliberate no-GPU selection, not a detection miss.
_amd_visible_masks_select_no_gpu && return 1
- # A DECLARED arch decides when there is one, since get_torch_index_url installs from it.
- # Corroborated first, because the variable answers on a host with no AMD GPU at all.
+ # A declared arch decides, but only after hardware corroborates there is an AMD GPU.
_arwr_decl=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" \
| tr '[:upper:]' '[:lower:]' | sed 's/:.*$//' | tr -d '[:space:]')
if [ -n "$_arwr_decl" ]; then
_amd_hardware_corroborated || _kfd_gfx_targets 2>/dev/null | grep -q . || return 1
- # The arch names what to BUILD for, not whether the runtime exposes a device to build it
- # for. Asked only when a mask is set AND the device list is knowable: an unknowable one
- # leaves the declared arch alone rather than declining on no evidence.
if [ -n "${HIP_VISIBLE_DEVICES+x}" ] || [ -n "${ROCR_VISIBLE_DEVICES+x}" ] || \
[ -n "${CUDA_VISIBLE_DEVICES+x}" ]; then
_arwr_dd=$(_amd_ordered_gfx_devices 2>/dev/null | sed 's/:.*$//' \
@@ -4891,25 +4537,18 @@ _amd_request_has_a_wheel_route() {
_arwr_all=$(_probe_amd_gfx_arch physical 2>/dev/null || true)
[ -n "$_arwr_all" ] || _arwr_all=$(_kfd_gfx_targets 2>/dev/null || true)
if [ -z "$_arwr_all" ]; then
- # Runtime-less but inferable, which a pure-AMD host is already served on. Requiring a working
- # ROCm runtime would answer differently for the same silicon by whether an NVIDIA card sits
- # beside it.
_amd_hardware_corroborated || return 1
_arwr_all=$(_infer_linux_amd_gfx_arch 2>/dev/null || true)
fi
_arwr_archs=$(printf '%s\n' "$_arwr_all" | sed 's/:.*$//' \
| tr '[:upper:]' '[:lower:]' | awk 'NF')
[ -n "$_arwr_archs" ] || return 1
- # The PHYSICAL count, before any mask narrows the list: gfx906's rocm6.3 tag opens only when
- # it is the sole arch, and the reroute granting it inspects the unmasked inventory.
+ # Physical count before masks: gfx906's rocm6.3 tag requires it to be the sole arch.
_arwr_count=$(printf '%s\n' "$_arwr_archs" | sort -u | wc -l | tr -d ' ')
- # The one card this run will hand torch; empty when the masks named something unresolvable.
- # Fails CLOSED, since a wrong yes replaces a working CUDA stack with kernel-less wheels.
+ # Fails closed: a wrong yes replaces a working CUDA stack with kernel-less wheels.
_arwr_devs=$(_amd_ordered_gfx_devices 2>/dev/null | sed 's/:.*$//' \
| tr '[:upper:]' '[:lower:]' | awk 'NF')
if [ -z "$_arwr_devs" ]; then
- # rocminfo is the only per-device source the masks index. amd-smi enumerates in KFD DISCOVERY
- # order while the kernel topology IS HIP's and ROCr's: take it when it describes this machine.
_arwr_kfd=$(_kfd_gfx_targets 2>/dev/null | sed 's/:.*$//' \
| tr '[:upper:]' '[:lower:]' | awk 'NF')
if [ -n "$_arwr_kfd" ] && \
@@ -4921,16 +4560,11 @@ _amd_request_has_a_wheel_route() {
if [ -n "$_arwr_devs" ]; then
_arwr_sel=$(_amd_runtime_gfx_target "$_arwr_devs")
elif [ "$_arwr_count" -eq 1 ]; then
- # One arch on the whole host: every ordinal names it, so ordering cannot change the answer.
_arwr_sel=$(_amd_runtime_gfx_target "$_arwr_archs")
else
- # Unlike adapters with no order the ordinals fit: which card the runtime hands torch is
- # unanswerable here, so fail closed.
return 1
fi
[ -n "$_arwr_sel" ] || return 1
- # Enumeration order is not a choice of card. The flat inventory only stands in where the
- # count is 1 and no preference can apply anyway.
_arwr_pref="$_arwr_devs"
[ -n "$_arwr_pref" ] || _arwr_pref="$_arwr_archs"
_arwr_sel=$(_amd_prefer_discrete_gfx "$_arwr_pref" "$_arwr_sel")
@@ -4941,9 +4575,7 @@ _amd_request_has_a_wheel_route() {
return 0
}
-# One place answers "does the NVIDIA card still win here", so index selection and the per-arch
-# reroutes cannot disagree: the reroutes probe afresh at top level, so get_torch_index_url
-# clearing its own _nvidia_detected never reached them (#10450).
+# Single answer to "does NVIDIA win" so index selection and reroutes agree (#10450).
_nvidia_gpu_wins_over_amd() {
_has_usable_nvidia_gpu || return 1
if _rocm_torch_explicitly_requested && _amd_request_has_a_wheel_route; then
@@ -5012,15 +4644,11 @@ _amd_gpu_present_via_pci() {
return 1
}
-# The nodes the enumeration below looks at. Extracted so a test can name its own set:
-# the paths are absolute, so a harness cannot otherwise reach this rule at all.
_amd_candidate_nodes() {
printf '%s\n' /dev/kfd /dev/dri/renderD*
}
-# The PCI vendor a render node reports, or a non-zero exit when sysfs will not say.
-# Mirrors utils/hardware/amd.py::_render_node_vendor, including the distinction that
-# matters: unreadable is not the same answer as "not AMD".
+# Unreadable is not the same answer as "not AMD". Mirrors utils/hardware/amd.py::_render_node_vendor.
_amd_render_node_vendor() {
_arnv_file="/sys/class/drm/${1##*/}/device/vendor"
[ -r "$_arnv_file" ] || return 1
@@ -5028,26 +4656,15 @@ _amd_render_node_vendor() {
printf '%s' "$_arnv_vendor"
}
-# Prints the AMD device nodes that exist but this user cannot open, one per line. On a
-# stock distribution /dev/kfd and /dev/dri/renderD* are root:render mode 0660, so an
-# account outside that group passes every -e test and then cannot open the device: HIP
-# counts no devices, the Vulkan loader enumerates none, and the install looks like a host
-# with no GPU (#10466). -r and -w, matching what the runtimes need; root prints nothing.
-# AMD-owned nodes only: render nodes are root:render for EVERY vendor, so an NVIDIA-only
-# box has the same closed list and none of the problem, and the group advice would be wrong
-# there. sysfs is world-readable, so ownership is answered without testing the access.
+# AMD device nodes that exist but this user cannot open (root:render 0660). AMD-owned only:
+# render nodes are root:render for every vendor.
_amd_nodes_closed_to_this_user() {
_anctu_amd_in_topology=""
_amd_candidate_nodes | while IFS= read -r _node; do
[ -e "$_node" ] || continue
{ [ -r "$_node" ] && [ -w "$_node" ]; } && continue
if [ "$_node" = /dev/kfd ]; then
- # vendor_id 4098 = 0x1002, the same AMD guard _has_amd_rocm_gpu uses: NVIDIA's
- # open kernel module registers KFD nodes of its own. A topology that could not
- # be READ is not one that named another vendor, and only the second is evidence,
- # so where it is unknown DRM confirms the same silicon independently. Dropping
- # the node there left the installer naming only the render node's group, which
- # where the two differ (video against render) leaves KFD shut.
+ # An unreadable KFD topology is not evidence of another vendor; DRM confirms instead.
# Mirrors utils/hardware/amd.py::amd_nodes_closed_to_this_user.
_anctu_kfd_state=0
_kfd_topology_amd_state || _anctu_kfd_state=$?
@@ -5059,12 +4676,7 @@ _amd_nodes_closed_to_this_user() {
elif _node_vendor=$(_amd_render_node_vendor "$_node"); then
[ "$_node_vendor" = "0x1002" ] || continue
else
- # A vendor sysfs will not name is not a vendor that is not AMD, and a
- # container mapping /dev/dri while hiding those attributes is the shape this
- # diagnosis exists for: dropping the node printed no repair at all, while
- # _amd_render_node_present reads the same unknown as PRESENT and withdraws the
- # missing-node sentence. The world-readable KFD topology answers instead.
- # Mirrors utils/hardware/amd.py::amd_nodes_closed_to_this_user.
+ # Unknown sysfs vendor is not "not AMD"; the world-readable KFD topology answers instead.
if [ -z "$_anctu_amd_in_topology" ]; then
if _kfd_topology_has_an_amd_gpu; then
_anctu_amd_in_topology=yes
@@ -5078,10 +4690,6 @@ _amd_nodes_closed_to_this_user() {
done
}
-# Whether SOME AMD render node on this host is open to this account: the mirror of the
-# enumeration above, same vendor guard. A node this account can already open means the
-# closed ones do not stop every GPU backend on the box, only the card behind them.
-# Mirrors utils/hardware/amd.py::an_amd_render_node_is_open.
_an_amd_render_node_is_open() {
for _anro_node in /dev/dri/renderD*; do
[ -e "$_anro_node" ] || continue
@@ -5094,13 +4702,8 @@ _an_amd_render_node_is_open() {
return 1
}
-# Whether KFD enumerates an AMD GPU node, the AMD-presence signal that survives a host with
-# no render node at all. vendor_id 4098 = 0x1002; the KFD CPU node reports 0 and NVIDIA's
-# open kernel module registers 4318. Exit 0 = the topology names an AMD GPU, 1 = it was READ
-# and names none, 2 = it could not be read at all. The third is not the second: a container
-# can map /dev/kfd while hiding /sys/class/kfd, and collapsing the two drops the node from
-# the closed list on exactly that host.
-# Mirrors utils/hardware/amd.py::_kfd_topology_has_an_amd_gpu and _kfd_topology_amd_state.
+# Exit 0 = KFD names an AMD GPU, 1 = read and none, 2 = unreadable (masked /sys/class/kfd).
+# Mirrors utils/hardware/amd.py::_kfd_topology_amd_state.
_kfd_topology_amd_state() {
_ktas=$(awk '
FNR == 1 { read_one = 1 }
@@ -5114,41 +4717,22 @@ _kfd_topology_amd_state() {
esac
}
-# Whether the /dev/kfd that EXISTS here is one the AMD driver put there: the branch below
-# claims the AMD kernel stack is loaded, and a node merely existing does not establish that.
-# A tri-state, not the stricter "require vendor 4098": state 1 (read, no AMD agent) is the
-# only reading that CONTRADICTS the claim, while state 2 (unreadable -- the container that
-# masks /sys/class/kfd) leaves it unproven, so that host keeps the diagnosis it has today.
_kfd_node_is_amds() {
_kina_state=0
_kfd_topology_amd_state || _kina_state=$?
[ "$_kina_state" -ne 1 ]
}
-# Whether this host has AMD silicon behind a /dev/kfd that is not there. Mirrors
-# utils/hardware/amd.py::_amd_nodes_the_runtime_lacks question for question; the two halves
-# must agree or one stays silent on a host the other diagnoses.
-#
-# The topology settles it whenever it can be READ. Where it cannot (state 2: --device
-# /dev/dri with /sys/class/kfd masked) a CONFIRMED AMD render node stands in, because that
-# host had no diagnosis at all -- amd-smi answers through libdrm and silences the PCI
-# branches, and a node that does not EXIST never reaches the closed-node list. Confirmed,
-# not merely present, or an NVIDIA-only box masked the same way would claim an AMD card.
+# AMD silicon behind a missing /dev/kfd; if KFD is unreadable, a render node must be CONFIRMED AMD.
_amd_silicon_behind_a_missing_kfd() {
if _kfd_topology_has_an_amd_gpu; then return 0; fi
- # Captured rather than tested inline: this runs under set -e, where a bare non-zero
- # command ends the installer instead of answering the question.
_asbmk_state=0
_kfd_topology_amd_state || _asbmk_state=$?
[ "$_asbmk_state" -eq 2 ] || return 1
_a_confirmed_amd_render_node_exists
}
-# Whether DRM names an AMD render node outright, with the vendor actually READ. The strict
-# counterpart to _amd_render_node_present, which counts an unreadable vendor as present on
-# purpose: this is used as INDEPENDENT evidence of AMD silicon, so an unknown vendor would
-# let an NVIDIA-only host claim one. Mirrors
-# utils/hardware/amd.py::_a_confirmed_amd_render_node_exists.
+# Strict: an unreadable vendor does not count. Mirrors amd.py::_a_confirmed_amd_render_node_exists.
_a_confirmed_amd_render_node_exists() {
for _acarne_node in /dev/dri/renderD*; do
[ -e "$_acarne_node" ] || continue
@@ -5164,13 +4748,7 @@ _kfd_topology_has_an_amd_gpu() {
[ "$_kthag" -eq 0 ]
}
-# Whether any AMD render node is PRESENT, whatever this account can do with it: ROCr opens
-# one to reach amdgpu, so a container given --device /dev/kfd alone still cannot start ROCm
-# and no group creates the node (docker/run.sh passes both devices for that reason).
-# A vendor that cannot be READ is not a vendor that is absent -- calling it absence sent
-# the user to recreate a container with the device it already has -- so unknown counts as
-# present, keeping the closed-node diagnosis reachable. Mirrors
-# utils/hardware/amd.py::_amd_render_node_exists.
+# Unknown vendor counts as present. Mirrors utils/hardware/amd.py::_amd_render_node_exists.
_amd_render_node_present() {
_arnp_unknown=false
for _arnp_node in /dev/dri/renderD*; do
@@ -5186,11 +4764,7 @@ _amd_render_node_present() {
[ "$_arnp_unknown" = true ]
}
-# A value as a single shell word, for a command the user is going to paste. NSS names are
-# not identifiers -- winbind hands back DOMAIN\user, and a group name may carry whitespace
-# or a metacharacter -- so an unquoted one is de-escaped, split or expanded by the shell,
-# and usermod then names an account that is not the one holding the node shut. The safe set
-# is Python shlex.quote's, so the two halves quote identically.
+# NSS names can hold backslashes or spaces; quote like Python shlex.quote for paste-safe commands.
_shell_quote() {
case "$1" in
"") printf "''" ;;
@@ -5200,34 +4774,16 @@ _shell_quote() {
esac
}
-# How to open the given nodes, one classified line each, read from the nodes themselves:
-# join:NAME membership WOULD open it -- the group has read and write on the node
-# gid:N no group entry for that GID, the container case docker/run.sh documents,
-# where --group-add passes the host's numeric gids and no name matches.
-# usermod cannot take a bare GID (shadow 4.13: "group '993' does not exist",
-# exit 6), so these are reported rather than prescribed.
-# mode:PATH the mode denies the group too (a udev rule leaving one root:render 0600),
-# so no membership opens it.
-# "render,video" is not universally right and sometimes no group is the answer at all.
+# One line per node: join:NAME, gid:N (no group entry, usermod cannot take a GID), mode:PATH.
_amd_node_repairs() {
for _anr_node in $1; do
- # acl(5): with an access ACL present the mode's group bits are the ACL MASK, not
- # the owning group's grant, so the group digit below is an upper bound and
- # prescribing membership from it is a promise this cannot keep. ls marks such a
- # node with a trailing "+"; getfacl is not installed everywhere this runs.
- #
+ # With an ACL (ls shows "+") the group bits are the mask, so they cannot prescribe membership.
# shellcheck disable=SC2012 # not parsing a file LIST: this reads column 11 of the
- # mode string for one explicitly named node, and the ACL "+" marker is precisely
- # what find -printf cannot report. The rule is about globbing ls output for names.
+ # mode string for one named node; find -printf cannot report the ACL "+".
case "$(ls -ld "$_anr_node" 2>/dev/null | cut -c11)" in
+) printf 'acl:%s\n' "$_anr_node"; continue ;;
esac
- # The group NAME goes LAST, because it is the one field NSS controls and the only
- # one that can carry the separator: winbind hands back DOMAIN\group, and an LDAP
- # directory can return anything at all. With it anywhere else a name carrying a
- # pipe shifts every field after it, so the mode, the GID and the uid this branches
- # on would all be read out of the name. Everything before it comes from the kernel
- # or from the node list this was called with.
+ # The group name goes last: NSS controls it and it may contain the separator.
stat -c '%a|%g|%u|%n|%G' "$_anr_node" 2>/dev/null || true
done | awk -F'|' -v self="$(id -u 2>/dev/null || echo -1)" \
-v mygids=" $(id -G 2>/dev/null) " '
@@ -5311,12 +4867,10 @@ _amd_node_repairs() {
}'
}
-# rocminfo names each agent twice, so "gfx1201\ngfx1201" is one device, not two.
_amd_probe_arches() {
printf '%s\n' "$1" | sed 's/:.*$//' | tr '[:upper:]' '[:lower:]' | awk 'NF' | sort -u
}
-# The wheels must work on every AMD GPU in the box, so every agent has to land in the same family: routing on whichever the kernel enumerated first puts gfx1151 wheels on a 9070 XT.
_amd_agreed_index_family() {
_aif_family=""
for _aif_a in $(_amd_probe_arches "$1"); do
@@ -5328,7 +4882,7 @@ _amd_agreed_index_family() {
printf '%s\n' "$_aif_family"
}
-# setup.sh takes UNSLOTH_ROCM_GFX_ARCH over its own visibility-aware selection, so naming an arbitrary member of an agreed family (gfx1200 beside gfx1201) overrules a correct choice.
+# setup.sh prefers UNSLOTH_ROCM_GFX_ARCH, so do not name an arbitrary family member.
_amd_sole_index_arch() {
_sia=$(_amd_probe_arches "$1")
[ -n "$_sia" ] || return 1
@@ -5337,7 +4891,7 @@ _amd_sole_index_arch() {
printf '%s\n' "$_sia"
}
-# Map a gfx arch to the AMD pip index family (mirrors install.ps1 $archFamilyMap).
+# Mirrors install.ps1 $archFamilyMap.
_amd_arch_index_family_for_gfx() {
case "$1" in
gfx1201|gfx1200) echo gfx120X-all ;;
@@ -5352,7 +4906,7 @@ _amd_arch_index_family_for_gfx() {
esac
}
-# Map a GPU marketing name to gfx arch (kept in sync with install.ps1 nameArchTable).
+# Kept in sync with install.ps1 nameArchTable.
_infer_amd_gfx_arch_from_gpu_name() {
case "$1" in
*9070*|*9080*|*"R9700"*) echo gfx1201 ;;
@@ -5371,7 +4925,8 @@ _infer_amd_gfx_arch_from_gpu_name() {
esac
}
-# GPU name to gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1 and Polaris 10/20/30 (#8529). SEPARATE from _infer_amd_gfx_arch_from_gpu_name on purpose: messaging only, nothing here may route to a wheel index. ORDER IS LOAD-BEARING: `case` has no negative lookahead, so a *"RX 570"* arm would swallow an "RX 5700 XT", hence RDNA 1 arms FIRST and Polaris last. Names from LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14 professional parts LLVM omits; nothing is guessed, so Polaris 11/12 (a different die) is left out. Case-sensitive, unlike the regex copies: every source here (WMI, amd-smi, lspci) spells these names as pci.ids does.
+# Messaging only, never routes (#8529). ORDER IS LOAD-BEARING: RDNA 1 arms before Polaris,
+# since *"RX 570"* would match "RX 5700 XT". Polaris 11/12 deliberately left out.
_infer_unsupported_amd_gfx_arch_from_gpu_name() {
case "$1" in
*"Radeon Pro V520"*|*"Radeon Pro 5600M"*) echo gfx1011 ;; # RDNA 1
@@ -5382,7 +4937,6 @@ _infer_unsupported_amd_gfx_arch_from_gpu_name() {
esac
}
-# Linux counterpart: first AMD display-class lspci line naming a generation ROCm does not cover. Messaging only, never fed into index selection.
_infer_linux_unsupported_amd_gfx_arch() {
command -v lspci >/dev/null 2>&1 || return 1
if [ -n "${_LSPCI_MEMO:-}" ] && [ -f "$_LSPCI_MEMO" ]; then
@@ -5407,13 +4961,12 @@ EOF
return 1
}
-# Best-effort gfx inference when ROCm tools cannot see the GPU (unslothai#7301). Mirrors install.ps1 arch resolution on Windows ($HasROCm false, $ROCmGfxArch set).
+# Best-effort gfx inference when ROCm tools cannot see the GPU (unslothai#7301).
_infer_linux_amd_gfx_arch() {
if [ -n "${UNSLOTH_ROCM_GFX_ARCH:-}" ]; then
printf '%s\n' "$(printf '%s' "$UNSLOTH_ROCM_GFX_ARCH" | tr '[:upper:]' '[:lower:]')"
return 0
fi
- # On WSL /proc/cpuinfo and lspci still report the host APU, but without the ROCDXG bridge (librocdxg over /dev/dxg) the AMD wheels cannot reach the GPU; keep the CPU fallback there unless that runtime is present. The explicit override above still wins. Mirrors install_python_stack.py.
_gpu_evidence=""
# Krackan Point 2 names overlap the gfx1152 patterns below, so both scans test them first (mirrors install_python_stack.py).
_krackan2_ere='820M|Krackan ?(Point ?)?2|AI 5 (PRO )?330'
@@ -5422,12 +4975,10 @@ _infer_linux_amd_gfx_arch() {
{ [ -e "$_d/librocdxg.so" ] || [ -e "$_d/librocdxg.so.1" ]; } && _rocdxg=1 && break
done
[ -n "${_rocdxg:-}" ] || return 1
- # WSL enumerates no PCI display device; /dev/dxg + librocdxg IS the GPU evidence there.
_gpu_evidence=1
elif _amd_gpu_present_via_pci; then
_gpu_evidence=1
fi
- # /proc/cpuinfo leaks the HOST CPU model into VMs/containers that received no AMD GPU, so the CPU-model text alone is not GPU evidence: require an AMD display device (PCI vendor 0x1002, class 0x03*) before trusting it. The lspci fallback below needs no gate; an AMD display line IS evidence.
if [ -n "$_gpu_evidence" ] && grep -qiE 'Ryzen AI Max|Radeon 80[0-9][05]S|Strix Halo' /proc/cpuinfo 2>/dev/null; then
echo gfx1151
return 0
@@ -5484,7 +5035,8 @@ EOF
return 1
}
-# gfx arch named by an HSA_OVERRIDE_GFX_VERSION value ($1), or nothing if it is not a readable major.minor.stepping triple. ROCr builds gfx<major><minor><stepping in hex>, which is why 9.0.10 is gfx90a: 11.0.0 to gfx1100, 11.5.1 to gfx1151, 10.3.0 to gfx1030. Kept in sync with _hsa_override_gfx_arch in studio/install_python_stack.py.
+# ROCr builds gfx<major><minor><stepping hex> (9.0.10 -> gfx90a).
+# Kept in sync with _hsa_override_gfx_arch in studio/install_python_stack.py.
_hsa_override_gfx_arch() {
printf '%s' "${1:-}" | awk '
{
@@ -5498,7 +5050,8 @@ _hsa_override_gfx_arch() {
}'
}
-# gfx arches the KERNEL sees, one line per AMD GPU node, from KFD topology sysfs. amdkfd writes gfx_target_version itself, so it is immune to HSA_OVERRIDE_GFX_VERSION (which ROCr applies in userland): the ground truth for #7331. Encoding is major*10000 + minor*100 + stepping in hex: 110000 to gfx1100, 110501 to gfx1151, 90010 to gfx90a. CPU nodes carry no gfx_target_version and drop out; vendor_id 4098 keeps NVIDIA's open-driver KFD nodes out. Kept in sync with _kfd_gfx_targets in studio/install_python_stack.py.
+# KFD gfx_target_version is immune to HSA_OVERRIDE_GFX_VERSION (#7331).
+# Kept in sync with _kfd_gfx_targets in studio/install_python_stack.py.
_kfd_gfx_targets() {
[ -d /sys/class/kfd/kfd/topology/nodes ] || return 0
for _kfd_node in /sys/class/kfd/kfd/topology/nodes/*/properties; do
@@ -5518,7 +5071,7 @@ _kfd_gfx_targets() {
return 0
}
-# Pair each rocminfo GPU gfx id with its marketing name, not the CPU-first global name (#7307). Blank names keep device ordinals; no GPU keeps the old fallback. Keep in sync with studio/setup.sh.
+# Pair each GPU gfx id with its own marketing name. Keep in sync with studio/setup.sh.
_rocminfo_gpu_records() {
awk '
# Split at the first colon so embedded colons survive.
@@ -5585,10 +5138,8 @@ _amd_smi_hip_order() {
'
}
-# amd-smi enumerates in KFD discovery order while HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES index HIP/ROCr order, and the two disagree on real hardware (MI350X SPX/NPS1), so an untranslated ordinal here can fetch a prebuilt for another card's arch. `amd-smi list -e` is the map AMD publishes for this (HIP_ID, ROCm 6.4.0+), the same field utils/hardware/amd.py get_hip_id_by_gpu_index reads. Keep in sync with studio/setup.sh.
-# `gfx|marketing name` records to one arch per adapter, ordinals intact. An unreadable arch
-# keeps its slot as `unknown`: dropping it would shift every later device under a mask.
-# Prints nothing when NO adapter has an arch, so the caller falls through to the next probe.
+# amd-smi uses KFD discovery order, masks use HIP order; `amd-smi list -e` maps them.
+# Unknown arches keep their slot so later ordinals do not shift. Keep in sync with studio/setup.sh.
_gfx_arch_slots() {
awk -F'|' '
NF { rec[n++] = $1; if ($1 != "") any = 1 }
@@ -5599,7 +5150,7 @@ _gfx_arch_slots() {
'
}
-# One `gfx|marketing name` per adapter, in `GPU: N` order, so the mask picks both halves of one device. Was: arch indexed, name always adapter 0's, and on amd-smi 6.1.1, which has no TARGET_GRAPHICS_VERSION, that name is what --rocm-gfx is inferred from. Keep in sync with studio/setup.sh.
+# One record per adapter in `GPU: N` order. Keep in sync with studio/setup.sh.
_amd_smi_gpu_records() {
awk '
function value(line, v) {
@@ -5632,7 +5183,8 @@ _amd_smi_gpu_records() {
}
-# Physical gfx arch when the ISA probe is an HSA_OVERRIDE_GFX_VERSION spoof (#7331): $1 = the arch inferred from the product name, $2 = the probed gfx token list. Prints the physical arch, or nothing to mean "believe the probe" (the default). Requires ALL of: the override is set; the product name inferred a spoofable RDNA 3.5 APU arch and the probe reported a DIFFERENT one; the probe saw exactly ONE distinct arch (rocminfo repeats the token per agent, so this is a pre-filter, not the safety property); the variable names EXACTLY the arch that was reported, since ROCr can only spoof to the target the variable names; and a source the override cannot reach agrees with the product name, KFD sysfs first, then rocminfo re-run with the variable unset. That keeps a mixed Strix APU plus discrete AMD GPU host out of reach. Corroboration is REQUIRED, with deliberately no "the variable names the reported arch, so assume a spoof" fallback: that shape is identical on a host telling the truth (a real gfx1100 dGPU in a Ryzen AI Max chassis whose owner set the override for unrelated reasons), and rerouting a working machine to the wrong wheels is worse than #7331 itself. Kept in sync with _hsa_spoofed_physical_gfx in studio/install_python_stack.py.
+# Physical arch under an HSA_OVERRIDE_GFX_VERSION spoof (#7331), or nothing. Requires corroboration
+# (KFD, then unspoofed rocminfo). Kept in sync with _hsa_spoofed_physical_gfx in install_python_stack.py.
_hsa_spoofed_physical_gfx() {
_hsp_inferred="${1:-}"
_hsp_probed_all="${2:-}"
@@ -5641,39 +5193,33 @@ _hsa_spoofed_physical_gfx() {
gfx1151|gfx1150|gfx1152) : ;;
*) return 0 ;;
esac
- # Exactly one DISTINCT arch, else the single-arch premise fails. Deduplicated because the caller passes raw `rocminfo | grep -oE gfx...`, which repeats the token per Name/ISA line, and counting lines would never fire on #7331's own host.
_hsp_n=$(printf '%s\n' "$_hsp_probed_all" | awk 'NF && !seen[$0]++ { n++ } END { print n + 0 }')
[ "${_hsp_n:-0}" -ne 1 ] && return 0
_hsp_probed=$(printf '%s\n' "$_hsp_probed_all" | awk 'NF { print; exit }')
[ -n "$_hsp_probed" ] || return 0
[ "$_hsp_probed" = "$_hsp_inferred" ] && return 0
- # Only the arch the variable names can be a spoof of that variable's doing.
[ "$(_hsa_override_gfx_arch "$HSA_OVERRIDE_GFX_VERSION")" = "$_hsp_probed" ] || return 0
echo " [WARN] HSA_OVERRIDE_GFX_VERSION=$HSA_OVERRIDE_GFX_VERSION is set; ROCm reports" >&2
echo " [WARN] $_hsp_probed but this host's product name is $_hsp_inferred. Checking for a spoof." >&2
- # The kernel, which the override cannot reach. Decisive either way: if it answers at all, no weaker source gets to overrule it.
_hsp_kfd=$(_kfd_gfx_targets | awk 'NF')
if [ -n "$_hsp_kfd" ]; then
if [ "$_hsp_kfd" = "$_hsp_inferred" ]; then
echo " [WARN] KFD topology sysfs reports $_hsp_inferred -- $_hsp_probed is a spoof." >&2
printf '%s\n' "$_hsp_inferred"
else
- # On a real gfx1100 card in a Ryzen AI Max chassis this is the CORRECT outcome.
echo " [WARN] The kernel does not corroborate a spoof; keeping $_hsp_probed." >&2
fi
- # Several GPU nodes: the single-arch premise was wrong (the spoof collapsed a mixed host into one apparent arch). Decline.
return 0
fi
- # 2. The runtime, asked again without the override (ROCr getenv()s it while building agent names, so stripping it retracts the spoofed name) and without the visible masks, so a mask cannot hide the second GPU that would veto the correction. A re-probe that still answers $_hsp_probed is evidence FOR the probe: the name did not move, so it is real silicon, which is what keeps a genuine gfx1100 dGPU in a Ryzen AI Max chassis on its own wheels.
+ # Re-probe without the override and masks; an unchanged name means real silicon.
_hsp_re=""
if command -v rocminfo >/dev/null 2>&1; then
_hsp_re=$( (unset HSA_OVERRIDE_GFX_VERSION ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; \
rocminfo 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' | awk 'NF && !seen[$0]++' || true)
fi
- # rocminfo FAILS on the very host this exists for: strip the override on a ROCm stack predating the physical arch and ROCr has no ISA entry for it, so hsa_init errors and no agent is listed. amd-smi reads the driver and is override-immune, and _detect_amd_gfx_codes falls through to it, so mirror that here.
if [ -z "$_hsp_re" ] && command -v amd-smi >/dev/null 2>&1; then
_hsp_re=$( (unset HSA_OVERRIDE_GFX_VERSION ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; \
amd-smi list 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' | awk 'NF && !seen[$0]++' || true)
@@ -5693,21 +5239,8 @@ _hsa_spoofed_physical_gfx() {
return 0
}
-# Reads the AMD gfx arch for wheel-index decisions: a user-set
-# UNSLOTH_ROCM_GFX_ARCH is authoritative (lowercased), else rocminfo, then
-# amd-smi. rocminfo/amd-smi honor ROCR/HIP_VISIBLE_DEVICES, so a container mask
-# (e.g. ROCR_VISIBLE_DEVICES=-1) would hide a GPU that the env-independent KFD
-# detection still sees -- the tool probes run with the masks cleared. Prints the
-# gfx token(s) or nothing when unreadable, and always returns 0 (a failing probe
-# as the last command would trip set -e in callers' assignments). Shared by
-# get_torch_index_url's gfx gate and the runtime-less reroute gate so the two
-# can never disagree on what "readable" means.
-# $1: unset strip the visible-device masks only (#7314).
-# physical also strip HSA_OVERRIDE_GFX_VERSION, which ROCr applies in userland so
-# rocminfo reports the SPOOFED ISA while it is set (unslothai#7331).
-# Mirrors _detect_amd_gfx_codes(ignore_hsa_override = True).
-# Neither mode answers which device the runtime SELECTS, and no probe here applies both mask
-# families. _runtime_gfx_target() in install_python_stack.py answers that.
+# Prints gfx token(s) or nothing and always returns 0 (set -e). Tool probes run with masks cleared
+# (#7314); "physical" also strips HSA_OVERRIDE_GFX_VERSION (unslothai#7331).
# shellcheck disable=SC2086 # $_pg_strip is a LIST of names for unset; quoting it would
# unset one variable whose name contains spaces.
_probe_amd_gfx_arch() {
@@ -5716,7 +5249,6 @@ _probe_amd_gfx_arch() {
physical) _pg_strip="ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES HSA_OVERRIDE_GFX_VERSION" ;;
*) _pg_strip="ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES" ;;
esac
- # "physical" ignores the declared arch: a stale UNSLOTH_ROCM_GFX_ARCH=gfx1030 on a real Van Gogh would answer the miscomputing gate with a healthy arch. It stays authoritative for ordinary routing.
if [ "${1:-}" = "physical" ]; then
_pg=""
else
@@ -5734,18 +5266,16 @@ _probe_amd_gfx_arch() {
printf '%s\n' "$_pg"
}
-# One gfx per GPU in ROCr enumeration order, the order a mask indexes. _probe_amd_gfx_arch
-# cannot serve: rocminfo names a target in BOTH "Name:" and "ISA Info", so a flat grep returns
-# two rows per card. Twin of install_python_stack._detect_amd_gfx_codes(dedup = False).
+# One gfx per GPU in ROCr order. Twin of install_python_stack._detect_amd_gfx_codes(dedup = False).
_amd_ordered_gfx_devices() {
_ensure_rocm_probe_env
command -v rocminfo >/dev/null 2>&1 || return 0
(unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES HSA_OVERRIDE_GFX_VERSION; rocminfo 2>/dev/null) \
| _rocminfo_gpu_records | sed 's/|.*$//' | awk 'NF'
}
-# Classify the physical NVIDIA inventory for a cu126 fallback: "cu126" when it covers every GPU, "uncovered" for an incompatible mix, empty when no fallback is needed or the inventory is unreadable. CUDA_VISIBLE_DEVICES is ignored because the wheel must support the host. Shared decision with install.ps1 / setup.ps1 / install_python_stack.py.
+# Physical inventory (ignores CUDA_VISIBLE_DEVICES): the wheel must support the host.
+# Shared decision with install.ps1 / setup.ps1 / install_python_stack.py.
_nvidia_cu126_verdict() {
- # $2: capabilities already read from the driver library, one per line, when nvidia-smi cannot.
if [ -n "${2:-}" ]; then
_ncv_caps=$2
else
@@ -5770,7 +5300,6 @@ _nvidia_cu126_verdict() {
'
}
-# Cap cu128/cu130 at cu126 when it covers every physical GPU: PyTorch 2.11's cu128/cu130 start at sm_75, cu126 spans sm_50-90. Non-x86_64 keeps driver-only selection.
_cap_cuda_family_for_pre_turing() {
case "$_ARCH" in
x86_64|amd64) ;;
@@ -5798,7 +5327,6 @@ _cap_cuda_family_for_pre_turing() {
# One helper per source, each returning 0 unconditionally: under set -e a failing source would kill the installer before the actionable warning at the end of the ROCm branch. Every source that execs runs through _run_bounded, since highest-wins consults all five and a single wedged probe would hang the installer; a timed-out probe just declined to answer.
_rocm_tag_from_amd_smi() {
command -v amd-smi >/dev/null 2>&1 || return 0
- # Cut at the field separator and require digits: the line is pipe-delimited ("... | ROCm version: N/A | amdgpu version: 6.10.10 | ..."), so stripping every non-digit fabricated rocm6.10 out of the amdgpu driver version. Position used to hide that; under highest-wins a fabricated reading outvotes a real 6.1.
_run_bounded amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
'NF>1{v=$2; sub(/[ \t|].*$/, "", v); if (v ~ /^[0-9]+\.[0-9]+/) {split(v,a,"."); print "rocm"a[1]"."a[2]} exit}' || return 0
}
@@ -5808,7 +5336,6 @@ _rocm_tag_from_version_file() {
awk -F. '{print "rocm"$1"."$2; exit}' /opt/rocm/.info/version || return 0
}
-# Naming pacman unconditionally told the unslothai#8731 reporter to run it on an immutable Fedora image, where it does not exist.
_rocm_sdk_install_hint() {
if command -v pacman >/dev/null 2>&1; then
echo "sudo pacman -S rocm-hip-sdk"
@@ -5824,7 +5351,6 @@ _rocm_sdk_install_hint() {
}
_rocm_tag_from_hipconfig() {
- # AMD's own installer puts hipconfig in ROCM_PATH/bin and leaves it off PATH unless its profile.d snippet ran, so a PATH-only lookup misses a tree that is right there. Not the Fedora shape: Fedora's hipconfig is /usr/bin/hipconfig, owned by hipcc.
_rt_hipconfig=""
if command -v hipconfig >/dev/null 2>&1; then
_rt_hipconfig=hipconfig
@@ -5839,7 +5365,8 @@ _rocm_tag_from_hipconfig() {
_rocm_tag_from_dpkg() {
command -v dpkg-query >/dev/null 2>&1 || return 0
- # Require the status word "installed" ($4 of the three-word ${Status}): dpkg-query -W lists every package except purged ones, so a removed-but-not-purged entry still reports its old version and could outrank the live runtime under highest-wins. ${Status} over ${db:Status-Status}: documented showformat field with no dpkg version floor, and an unrecognised field renders empty rather than failing, so a dpkg lacking it goes silent. `|| true` is load-bearing: dpkg-query exits nonzero when either package is absent while still printing the other's line. rocm-core wins outright; libhsa-runtime64-1 is read only in its absence (Debian ships no rocm-core), comes from the distro archive, and can be older.
+ # Require status "installed": removed-but-not-purged packages still report a version.
+ # `|| true`: dpkg-query exits nonzero when either package is absent.
{ _run_bounded dpkg-query -W -f='${Package} ${Status} ${Version}\n' rocm-core libhsa-runtime64-1 2>/dev/null || true; } \
| awk '
$4 == "installed" && $5 != "" {
@@ -5859,15 +5386,13 @@ _rocm_tag_from_dpkg() {
_rocm_tag_from_rpm() {
command -v rpm >/dev/null 2>&1 || return 0
- # Bounded, alone among the five, because this is the one source highest-wins newly made unconditional that can block forever: it used to be LAST in a first-answer-wins `||` chain, so /opt/rocm/.info/version answered at position two and rpm was never invoked on a normal RHEL/SLES install. `rpm -q` is not a lock-free read: a leftover /var/lib/rpm/__db.00* from a killed rpm/yum wedges plain queries in futex on the BerkeleyDB backend (rpm < 4.16, i.e. RHEL 8 / SLES 15; rhbz#485780, rhbz#73097), and rpm 6.0.x deadlocks `rpm --query` against a running dnf (rhbz#2463435). A version probe must not hang the installer, and a timed-out probe is just a source that declined to answer; _run_bounded no-ops where `timeout` is absent, so this adds no dependency.
- # Fedora ships rocm-core but nothing except the `rocm` metapackage requires it, so a host running rocm-hip/rocm-runtime answered nothing (unslothai#8731). All names in ONE query, since looping would pay the timeout above once per name; rpm reports misses on stdout, so keep only lines starting with a digit. Every installed component is emitted, not just the first: these are all AMD packages from the same repo, so a partial upgrade can leave rocm-core 5.7 beside rocm-runtime 6.4, and ranking by argument order would read that host as 5.7 and send a supported runtime to CPU wheels. _highest_rocm_tag ranks them, as it does across the other sources.
+ # Bounded: rpm -q can hang on stale db locks or dnf; query all names once, emit every version.
_rt_ver=$(_run_bounded rpm -q --qf '%{VERSION}\n' rocm-core rocm-runtime rocm-hip 2>/dev/null \
| awk '/^[0-9]/{print}') || return 0
[ -n "$_rt_ver" ] || return 0
printf '%s\n' "$_rt_ver" | awk -F'[.-]' 'NF{print "rocm"$1"."$2}' || return 0
}
-# Highest "rocmX.Y" line on stdin (major >= 1), or nothing when no line is usable.
_highest_rocm_tag() {
awk '
/^rocm[0-9]+\.[0-9]+$/ {
@@ -5882,9 +5407,8 @@ _highest_rocm_tag() {
'
}
-# Consult EVERY source and take the highest, not the first that answers. Distros with split ROCm packaging ship one component well behind the runtime the GPU actually uses: Debian 13 (and Linux Mint on top of it) packages hipconfig at 5.7.x next to a 6.1.x rocminfo/HSA, so first-answer resolution reported rocm5.7 on a working gfx1100 and the 6.0+ gate below sent it to CPU-only wheels (issue #8402). A source reading lower than another on the same host is stale packaging, not a downgrade. Overshoot is bounded: PyTorch's ROCm wheels vendor their own userspace and need only an amdgpu/KFD driver AMD documents as compatible +/- 2 releases, the normalisation below can only emit a leaf PyTorch publishes, package-manager sources that can report an uninstalled tree are filtered above, and any disagreement is named on stderr for the install log.
+# Take the highest source, not the first: split packaging ships stale components (#8402).
-# Path of the cross-subshell answer cache; set by the parent shell, empty when unused.
_ROCM_TAG_MEMO=""
_detect_rocm_version_tag() {
if [ -n "${_ROCM_TAG_MEMO:-}" ] && [ -f "$_ROCM_TAG_MEMO" ]; then
@@ -5900,11 +5424,10 @@ _detect_rocm_version_tag() {
} 2>/dev/null) || _rt_readings=""
_rt_best=$(printf '%s\n' "$_rt_readings" | _highest_rocm_tag) || _rt_best=""
if [ -n "$_rt_best" ]; then
- # Same shape gate as _highest_rocm_tag: a reading that was never a candidate must not be named as a dissenting opinion.
_rt_seen=$(printf '%s\n' "$_rt_readings" \
| grep '^rocm[1-9][0-9]*\.[0-9][0-9]*$' | sort -u | tr '\n' ' ') || _rt_seen=""
case "$_rt_seen" in
- ""|"$_rt_best ") : ;; # one reading, or every source agreeing
+ ""|"$_rt_best ") : ;;
*) echo "[WARN] ROCm version sources disagree (${_rt_seen% }) -- using the highest, $_rt_best." >&2 ;;
esac
fi
@@ -5930,13 +5453,8 @@ _rocm_bnb_compatible_generic_tag() {
}
# ── Detect GPU and choose PyTorch index URL ──
-# Mirrors Get-TorchIndexUrl in install.ps1.
-# On CPU-only machines this returns the cpu index, avoiding the solver
-# dead-end where --torch-backend=auto resolves to unsloth==2024.8.
+# Mirrors Get-TorchIndexUrl in install.ps1. CPU-only hosts get the cpu index (auto picks unsloth==2024.8).
get_torch_index_url() {
- # Cleared on ENTRY, not only in the helper that sets them: the helper runs only when NVIDIA is
- # detected AND the request is set, and the CUDA restore calls this a second time from a shell
- # the reroutes have populated. A stale gfx1100/probe pair clears the Van Gogh gate on gfx1033.
_AMD_REQUEST_TARGET_GFX=""
_AMD_REQUEST_TARGET_SOURCE=""
_base="${UNSLOTH_PYTORCH_MIRROR:-https://download.pytorch.org/whl}"
@@ -5945,7 +5463,6 @@ get_torch_index_url() {
_url="${UNSLOTH_TORCH_INDEX_URL:-}"
_url="${_url#"${_url%%[![:space:]]*}"}"; _url="${_url%"${_url##*[![:space:]]}"}"
if [ -n "$_url" ]; then
- # Trim trailing path slashes (they 404 on strict proxies), keeping ?query/#fragment.
_url=$(_trim_index_path_slashes "$_url")
echo "$_url"; return
fi
@@ -5956,9 +5473,7 @@ get_torch_index_url() {
while [ "${_family%/}" != "$_family" ]; do _family="${_family%/}"; done
echo "$_base/$_family"; return
fi
- # macOS: always CPU (no CUDA support)
case "$(uname -s)" in Darwin) echo "$_base/cpu"; return ;; esac
- # Require nvidia-smi to list a usable GPU; the binary alone installs CUDA wheels on AMD.
_smi=""
_nvidia_detected=0
if _has_usable_nvidia_gpu; then
@@ -5969,9 +5484,7 @@ get_torch_index_url() {
_smi="/usr/bin/nvidia-smi"
fi
fi
- # Here rather than only in _has_amd_rocm_gpu, because this index is exported as
- # UNSLOTH_TORCH_BACKEND, on which _ensure_rocm_torch returns immediately for "cuda":
- # relaxing the AMD probe alone swapped nothing (#10450).
+ # Here too: UNSLOTH_TORCH_BACKEND=cuda would make _ensure_rocm_torch return early (#10450).
if [ "$_nvidia_detected" -eq 1 ] && _rocm_torch_explicitly_requested && \
_amd_request_has_a_wheel_route; then
echo "[INFO] UNSLOTH_FORCE_ROCM_TORCH is set and an AMD GPU is present -- selecting ROCm PyTorch over CUDA." >&2
@@ -5990,7 +5503,6 @@ get_torch_index_url() {
fi
echo "$_base/cpu"; return
fi
- # A generic rocm index is only safe when the gfx arch is readable: the Strix reroute (gfx1150/1151 to the arch-specific index) learns gfx from rocminfo/amd-smi, so if those are missing OR do not enumerate the GPU, an unknown-arch box might be Strix and would get the broken _grouped_mm wheels. Probe via the shared helper (override first, then rocminfo/amd-smi with visibility masks cleared); if the arch is unreadable, never guess a rocm index. A KFD-only host whose arch is still inferable from hardware IDs (PCI/cpuinfo/lspci) returns the cpu index and lets the runtime-less reroute below upgrade it to AMD per-arch wheels, and the reroute gate uses this same probe so the handoff cannot misfire. Only when inference fails too is CPU final, with the actionable warning.
_amd_gfx_probe=$(_probe_amd_gfx_arch)
if [ -z "$_amd_gfx_probe" ]; then
if _amd_inferred_gfx=$(_infer_linux_amd_gfx_arch 2>/dev/null) && \
@@ -6029,7 +5541,7 @@ get_torch_index_url() {
_amd_gfx_gate_probe=$(_probe_amd_gfx_arch physical 2>/dev/null || true)
[ -n "$_amd_gfx_gate_probe" ] || _amd_gfx_gate_probe=$(_kfd_gfx_targets 2>/dev/null || true)
if [ -z "$_amd_gfx_gate_probe" ] && [ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ]; then
- # Under a spoof nothing override-independent named the silicon, so the only value left is the spoofed name: absence of evidence, not evidence of a healthy arch. HSA_OVERRIDE_GFX_VERSION only, NOT UNSLOTH_ROCM_GFX_ARCH, which is a DECLARED arch for the runtime-less #7301 hosts.
+ # HSA_OVERRIDE_GFX_VERSION only, not UNSLOTH_ROCM_GFX_ARCH (a declared arch for #7301 hosts).
echo "[WARN] HSA_OVERRIDE_GFX_VERSION is set and this host cannot confirm its real arch (no unspoofed rocminfo, amd-smi or KFD topology)." >&2
echo "[WARN] Installing CPU-only PyTorch rather than trusting the spoofed name: gfx1033 (Van Gogh) computes incorrect results under ROCm (studio/ROCM_RDNA2_APU.md)." >&2
echo "[WARN] Unset HSA_OVERRIDE_GFX_VERSION so the arch can be read, or pin UNSLOTH_TORCH_INDEX_URL to choose deliberately." >&2
@@ -6042,14 +5554,10 @@ get_torch_index_url() {
case "$_amd_gfx_tokens" in
*" gfx1033 "*) _amd_gfx_bad_arch=true ;;
esac
- # PRESENCE is the rule while the selected card is unknown. An honoured request has resolved
- # the one card this run hands torch, so answering on a sibling it hid took the cpu index for
- # a routable gfx1100. Probe-resolved only.
case "${_AMD_REQUEST_TARGET_GFX:-}" in
""|gfx1033) : ;;
*)
- # if/fi rather than `[ ... ] &&`: under set -e a failing test as the last
- # command of the arm would abort the installer.
+ # if/fi, not `[ ... ] &&`: a failing last test would abort under set -e.
if [ "${_AMD_REQUEST_TARGET_SOURCE:-}" = probe ]; then
_amd_gfx_bad_arch=false
fi
@@ -6103,10 +5611,9 @@ get_torch_index_url() {
fi
_rocm_tag=""
_rocm_tag=$(_detect_rocm_version_tag) || _rocm_tag=""
- # The `||` guard is belt and braces on the set -e contract the helpers hold, so a fresh AMD host with no version source at all still reaches the actionable no-version WARN below. stderr is deliberately not redirected: each source already silences its own noise, leaving only the sources-disagree breadcrumb, which belongs in the install log. The shape gate on "rocmX.Y" with major >= 1 is kept, though _highest_rocm_tag enforces it too, so a future source cannot leak garbage into the cases below.
case "$_rocm_tag" in
- rocm[1-9]*.[0-9]*) : ;; # valid (major >= 1)
- *) _rocm_tag="" ;; # reject malformed (empty, garbled, or major=0)
+ rocm[1-9]*.[0-9]*) : ;;
+ *) _rocm_tag="" ;;
esac
if [ -n "$_rocm_tag" ]; then
case "$_rocm_tag" in
@@ -6119,8 +5626,7 @@ get_torch_index_url() {
echo "[WARN] UNSLOTH_TORCH_INDEX_URL=<full index URL> (takes precedence, used verbatim)" >&2
echo "$_base/cpu"; return ;;
esac
- # Normalise to major.minor; 6.5+ clips to rocm6.4, 7.3+ caps to rocm7.2.
- # Leading ( on every arm: bash 3.2 (macOS /bin/sh) ends $(...) at a bare pattern) and aborts the script.
+ # 6.5+ clips to rocm6.4, 7.3+ caps to rocm7.2. Leading ( on every arm: bash 3.2 ends $(...) at a bare `)`.
_rocm_index=$(case "$_rocm_tag" in
(rocm6.0|rocm6.0.*) echo "$_base/rocm6.0" ;;
(rocm6.1|rocm6.1.*) echo "$_base/rocm6.1" ;;
@@ -6153,7 +5659,6 @@ get_torch_index_url() {
echo "$_rocm_index"
return
fi
- # AMD GPU confirmed (rocminfo/amd-smi or the KFD topology fallback) but no ROCm/HIP install was found to read the version from. This is the common fresh-install case: the GPU is real, but with no ROCm userspace the correct PyTorch build cannot be selected, so warn with an actionable fix rather than silently installing CPU PyTorch. The version only picks between the generic rocmX.Y leaves, so an arch with its own repo.amd.com/rocm/whl/gfx* index does not need one (#8731).
_amd_gfx_family=$(_amd_agreed_index_family "$_amd_gfx_probe") || _amd_gfx_family=""
if [ -n "$_amd_gfx_family" ]; then
_amd_gfx_first=$(_amd_sole_index_arch "$_amd_gfx_probe") || _amd_gfx_first=""
@@ -6166,7 +5671,6 @@ get_torch_index_url() {
fi
echo "[WARN] AMD GPU detected, but no ROCm version could be read to select the matching GPU PyTorch build -- falling back to CPU-only PyTorch." >&2
if [ -d "${ROCM_PATH:-/opt/rocm}" ]; then
- # Telling someone with a populated ROCm tree that "no ROCm install was found" sends them off to install a package they already have. Fedora is the OTHER branch: it owns no path under /opt/rocm, so it lands on the SDK hint.
echo "[WARN] ${ROCM_PATH:-/opt/rocm} exists, so ROCm is likely installed but not reporting a version this installer can read." >&2
echo "[WARN] Pin the wheels and re-run: UNSLOTH_TORCH_INDEX_FAMILY=rocm6.4 (a PyTorch wheel leaf: rocm6.0-6.4, rocm7.0-7.2)" >&2
else
@@ -6176,14 +5680,12 @@ get_torch_index_url() {
echo "[WARN] Version sources checked: amd-smi, /opt/rocm/.info/version, hipconfig, dpkg, rpm (Debian runtime package: libhsa-runtime64-1)." >&2
echo "$_base/cpu"; return
fi
- # CUDA version from nvidia-smi: accept "CUDA Version:" and the newer "CUDA UMD Version:".
_smi_rc=0
_smi_out=$(export LC_ALL=C; _run_bounded "$_smi" 2>/dev/null) || _smi_rc=$?
if [ "$_smi_rc" = "124" ]; then
echo "[INFO] nvidia-smi did not answer within 10s; retrying with a 45s limit..." >&2
_smi_rc=0
_smi_out=$(export LC_ALL=C; _run_bounded --secs 45 "$_smi" 2>/dev/null) || _smi_rc=$?
- # Still hung: do not spend another bound asking it for compute capabilities below.
[ "$_smi_rc" = "124" ] && _smi=""
fi
_cuda_ver=$(printf '%s\n' "$_smi_out" \
@@ -6193,12 +5695,10 @@ get_torch_index_url() {
| head -1)
_inventory_caps=""
_cuda_from_driver=""
- # A mirror base can carry credentials, so name only the leaf.
if [ -n "${UNSLOTH_PYTORCH_MIRROR:-}" ]; then _pin_hint="UNSLOTH_TORCH_INDEX_FAMILY="
else _pin_hint="UNSLOTH_TORCH_INDEX_URL=$_base/"
fi
if [ -z "$_cuda_ver" ]; then
- # nvidia-smi absent, stale or hung: the driver library knows both; cu126 is the last resort.
if _inventory=$(_nvidia_library_inventory) && [ -n "$_inventory" ]; then
_cuda_ver=${_inventory%% *}
_inventory_caps=$(printf '%s' "${_inventory#* }" | tr ',' '\n')
@@ -6239,7 +5739,7 @@ get_torch_index_url() {
}
# ── Torch flavor helpers (to repair a stale CPU / wrong-CUDA wheel) ──
-# torch.__version__ ($1) to flavor tag (cuXXX / rocm / xpu / cpu); untagged wheel is cpu. The xpu arm is load-bearing: without it a +xpu wheel reads as "cpu" and is force-reinstalled on every run.
+# The xpu arm is load-bearing: without it +xpu reads as cpu and reinstalls every run.
_torch_flavor_tag() {
case "$1" in
*+cu[0-9]*) printf '%s\n' "$1" | sed -n 's/.*+\(cu[0-9][0-9]*\).*/\1/p' ;;
@@ -6251,20 +5751,15 @@ _torch_flavor_tag() {
esac
}
-# Lowercased final path segment of an index URL, query/fragment stripped. Shared with py / ps1.
_torch_index_url_leaf() {
_tl_u="${1%%\?*}"
_tl_u="${_tl_u%%#*}"
- # Strip ALL trailing slashes: .../rocm7.2// must yield rocm7.2, not empty.
while [ -n "$_tl_u" ] && [ "${_tl_u%/}" != "$_tl_u" ]; do
_tl_u="${_tl_u%/}"
done
printf '%s' "${_tl_u##*/}" | tr '[:upper:]' '[:lower:]'
}
-# Did the resolution land on a ROCm index? The FINAL leaf only, so a mirror whose BASE path
-# contains rocm or gfx cannot read as one. Broader than _is_pip_rocm_family_leaf on purpose,
-# which declines the Radeon repo leaf rocm-rel-6.4.
_torch_index_url_is_rocm() {
case "$(_torch_index_url_leaf "${1:-}")" in
rocm*|gfx*) return 0 ;;
@@ -6272,7 +5767,7 @@ _torch_index_url_is_rocm() {
esac
}
-# HIP reads CUDA_VISIBLE_DEVICES when HIP_VISIBLE_DEVICES is unset, so the "" mask that steers a mixed NVIDIA + AMD host to ROCm torch also hides the AMD card at runtime.
+# HIP reads CUDA_VISIBLE_DEVICES when HIP_VISIBLE_DEVICES is unset, so "" hides the AMD card.
_warn_if_cuda_mask_hides_amd() {
_cvd_hides_nvidia || return 0
[ -z "${HIP_VISIBLE_DEVICES+x}" ] || return 0
@@ -6288,12 +5783,10 @@ _warn_if_cuda_mask_hides_amd() {
echo "" >&2
}
-# True for an EXACT ROCm family leaf; one that merely starts with rocm/gfx is a custom pin.
_is_pip_rocm_family_leaf() {
case "$1" in
gfx[0-9]*) return 0 ;;
rocm[0-9]*)
- # Major/minor both all-digits (rocm7., rocm7.2.1, rocm7.2-private are custom).
_rocm_rest="${1#rocm}"
case "$_rocm_rest" in
*.*.*) return 1 ;;
@@ -6358,9 +5851,8 @@ _cu130_torch213_platform() {
[ "$_ctr_py" = "3.13" ] && echo "yes" || echo "no"
}
-# "yes" only when the newest unsloth on PyPI admits torch $1: `studio update` runs the INSTALLED release's setup,
-# which re-resolves under its own cap and would downgrade a newer torch. Any failure answers "no", as does anything
-# making public PyPI's newest release not what uv will pick: an upload cutoff, offline mode, another package index.
+# `studio update` runs the installed release's setup, which would downgrade a newer torch;
+# any failure answers "no".
_pypi_unsloth_admits_torch() {
_pua_off=$(printf '%s' "${UV_OFFLINE:-}" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
case "$_pua_off" in 1|t|true|y|yes|on) echo "no"; return ;; esac
@@ -6406,15 +5898,12 @@ _torchaudio_for_torch_minor() {
fi
}
-# Keep the previous torch RELEASE when inside the window; UNSLOTH_TORCH_UPGRADE=1 opts out.
_previous_torch_pin() {
_ptp_ver="$1"
_ptp_con="$2"
[ -n "$_ptp_ver" ] || { echo ""; return; }
- # $3 = keep: an upgrade with no newer release to move to still keeps the resident one.
[ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] && [ "${3:-}" != "keep" ] && { echo ""; return; }
_ptp_base="${_ptp_ver%%+*}"
- # Base must be a plain numeric release; nightly/dev builds never become a pin.
case "$_ptp_base" in
*[!0-9.]* | *..* | .* | *.) echo ""; return ;;
[0-9]*.[0-9]*) ;;
@@ -6424,9 +5913,6 @@ _previous_torch_pin() {
echo "torch==$_ptp_base"
}
-# TheRock's multi-arch index: one URL for every target, selected by a package extra
-# (torch[device-gfx1010]), unlike repo.amd.com's per-family indexes. Nothing routes here
-# automatically; it exists so the message can name a real URL. Override for a mirror.
THEROCK_MIRROR="${UNSLOTH_THEROCK_MIRROR:-https://rocm.nightlies.amd.com/whl-multi-arch/}"
# The device extra TheRock publishes for a gfx, or non-zero when it builds none. Only arches
@@ -6439,17 +5925,12 @@ _therock_device_extra_for_gfx() {
esac
}
-# Insert a package extra: torch>=2.4,<2.11.0 -> torch[X]>=2.4,<2.11.0. Splits at the first
-# version-operator character, so ==, >=, ~= and bare names all work. An empty extra is a
-# no-op, which is every default path.
_torch_spec_with_extra() {
_tswe_spec="$1"
[ -n "${_TORCH_EXTRA:-}" ] || { printf '%s' "$_tswe_spec"; return; }
_tswe_name="${_tswe_spec%%[<>=~!]*}"
_tswe_rest="${_tswe_spec#"$_tswe_name"}"
case "$_tswe_name" in
- # torch[a][b] is not PEP 508, torch[a,b] is. No caller passes an extra
- # today; this only keeps the helper total for the next one.
*"]")
printf '%s,%s]%s' "${_tswe_name%?}" "$_TORCH_EXTRA" "$_tswe_rest"
;;
@@ -6459,14 +5940,8 @@ _torch_spec_with_extra() {
esac
}
-# Install torch from TORCH_INDEX_URL honoring a kept-release pin: with _PREV_TORCH_PIN set,
-# TORCH_CONSTRAINT is the exact previous release; fall back to the supported range if a
-# pruned mirror lacks it. Shared by every --default-index path so preservation is uniform;
-# extra args pass through to uv. torchaudio stays bare, as TheRock's documented invocation
-# leaves it, reaching the right build through torch's own rocm[libraries] dependency.
_install_torch_default_index() {
if [ -n "$_PREV_TORCH_PIN" ]; then
- # Pair companions with the kept torch minor (torchaudio no longer exact-pins torch).
_itdi_base="${_PREV_TORCH_PIN#torch==}"
_itdi_minor="${_itdi_base#*.}"
_itdi_minor="${_itdi_minor%%.*}"
@@ -6492,28 +5967,24 @@ _install_torch_default_index() {
fi
}
-# Expected tag from the index leaf ($1): cuXXX / cpu / xpu / rocm (rocmX.Y and gfx* both give rocm). Empty on an unknown leaf so the repair safely no-ops.
_expected_torch_flavor_tag() {
_leaf=$(_torch_index_url_leaf "$1")
case "$_leaf" in
cu[0-9]*)
- # Exact cu + digits only; a cu128-private leaf is custom.
case "${_leaf#cu}" in
*[!0-9]*) echo "" ;;
*) echo "$_leaf" ;;
esac
;;
cpu) echo "cpu" ;;
- # Intel XPU (SYCL) is a GPU flavor, so a pinned xpu index repairs a stale CPU wheel.
xpu) echo "xpu" ;;
- # Exact rocm/gfx families only; a custom rocm*-suffixed leaf -> "" (custom).
*)
if _is_pip_rocm_family_leaf "$_leaf"; then echo "rocm"; else echo ""; fi
;;
esac
}
-# Installed torch's version label, for expected-flavor tag $1. The xpu path reads it off disk, as setup.sh's fast-path escape does, since `import torch` can block forever on a wedged Intel driver. Other families keep the interpreter read.
+# xpu reads the version from disk: `import torch` can hang on a wedged Intel driver.
_installed_torch_version_for_tag() {
if [ "$1" = "xpu" ]; then
for _itv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
@@ -6526,21 +5997,17 @@ _installed_torch_version_for_tag() {
"$_VENV_PY" -I -c "import torch; print(torch.__version__)" 2>/dev/null || true
}
-# Whether index ($1) supports a plain --default-index reinstall. The pytorch.org cuXXX / xpu / rocmX.Y AND repo.amd.com gfx* indexes are all PEP 503 simple indexes uv resolves torch and every transitive dep from, the same URLs the fresh-install paths use, so a stale wheel is auto-repairable. Unknown or odd-mirror leaves are not, so we warn rather than risk a wrong reinstall.
_torch_index_repairable() {
_leaf=$(_torch_index_url_leaf "$1")
case "$_leaf" in
cu[0-9]*) echo "yes" ;;
- # /whl/xpu is a plain PEP 503 index (oneAPI runtime and triton-xpu are ordinary deps).
xpu) echo "yes" ;;
- # Only EXACT rocm/gfx families resolve via --default-index; a suffixed leaf is verbatim.
*)
if _is_pip_rocm_family_leaf "$_leaf"; then echo "yes"; else echo "no"; fi
;;
esac
}
-# Drops userinfo AND query/fragment. Shared with py / ps1.
_strip_index_url_credentials() {
_sic_url="$1"
case "$_sic_url" in
@@ -6549,11 +6016,9 @@ _strip_index_url_credentials() {
esac
_sic_scheme="${_sic_url%%://*}"
_sic_rest="${_sic_url#*://}"
- # Drop query / fragment (may hold auth tokens).
_sic_rest="${_sic_rest%%\?*}"
_sic_rest="${_sic_rest%%#*}"
_sic_auth="${_sic_rest%%/*}"
- # Drop user:pass@ userinfo if present.
case "$_sic_auth" in
*@*) _sic_host="${_sic_auth##*@}" ;;
*) _sic_host="$_sic_auth" ;;
@@ -6565,7 +6030,6 @@ _strip_index_url_credentials() {
fi
}
-# 0 when host version $1 (x.y or x.y.z) is no older than leaf version $2 (x.y), or $2 is empty
_radeon_host_ver_not_older() {
[ -n "$1" ] || return 1
[ -n "$2" ] || return 0
@@ -6578,7 +6042,6 @@ _radeon_host_ver_not_older() {
}
get_radeon_wheel_url() {
- # Only meaningful on Linux. AMD publishes both M.m and M.m.p rocm-rel directories, so both X.Y and X.Y.Z are valid leaf names here.
case "$(uname -s)" in Linux) ;; *) echo ""; return ;; esac
_full_ver=""
@@ -6603,10 +6066,9 @@ get_radeon_wheel_url() {
_full_ver="$_resolved_ver"
fi
- # Validate: must be X.Y or X.Y.Z with X >= 1
case "$_full_ver" in
- [1-9]*.[0-9]*.[0-9]*) : ;; # X.Y.Z
- [1-9]*.[0-9]*) : ;; # X.Y
+ [1-9]*.[0-9]*.[0-9]*) : ;;
+ [1-9]*.[0-9]*) : ;;
*) echo ""; return ;;
esac
echo "https://repo.radeon.com/rocm/manylinux/rocm-rel-${_full_ver}/"
@@ -6616,7 +6078,6 @@ get_radeon_wheel_url() {
_RADEON_LISTING=""
_RADEON_PYTAG=""
_RADEON_BASE_URL=""
-# true only while every attempt (X.Y.Z, then X.Y) returned 404/410; any transient failure pins "inconclusive".
_RADEON_HOST_ANSWERED=false
_radeon_fetch_listing() {
@@ -6633,14 +6094,12 @@ print('cp{}{}'.format(sys.version_info.major, sys.version_info.minor))
'
_radeon_http=${_RADEON_LISTING##*"$_radeon_nl"}
_RADEON_LISTING=${_RADEON_LISTING%"$_radeon_nl"*}
- # Re-strip trailing newlines as a plain $(curl) did, so a newline-only body still fails over to X.Y.
_RADEON_LISTING=$(printf '%s' "$_RADEON_LISTING")
elif command -v wget >/dev/null 2>&1; then
_RADEON_LISTING=$(wget -qO- --timeout=20 "$_RADEON_BASE_URL" 2>/dev/null) || _radeon_rc=$?
fi
- # A timeout or reset mid-body leaves a truncated listing that would pick an older wheel set.
[ "$_radeon_rc" -eq 0 ] || _RADEON_LISTING=""
- # Only 404/410 mean "no such release": curl -f exits 22 on 429/5xx too, and wget's 8 is any error.
+ # Only 404 and 410 mean no such release; curl -f exits 22 on 429/5xx too, wget 8 on any error.
case "$_radeon_http" in
404|410) [ "$_RADEON_HOST_ANSWERED" = inconclusive ] || _RADEON_HOST_ANSWERED=true ;;
*) [ -n "$_RADEON_LISTING" ] || _RADEON_HOST_ANSWERED=inconclusive ;;
@@ -6777,7 +6236,6 @@ _maybe_bootstrap_rocm_wsl() {
[ "${SKIP_TORCH:-false}" = "false" ] || return 0
[ "${UNSLOTH_SKIP_ROCM_WSL_SETUP:-0}" = "1" ] && return 0
if _has_usable_nvidia_gpu; then return 0; fi
- # Usable ROCm = a real gfx[1-9] agent, not gfx000; awk drains input so rocminfo survives.
_ensure_rocm_probe_env
if command -v rocminfo >/dev/null 2>&1 && \
rocminfo 2>/dev/null | awk '/Name:[[:space:]]*gfx[1-9]/ && !/generic/{found=1} END{exit !found}'; then
@@ -6785,9 +6243,7 @@ _maybe_bootstrap_rocm_wsl() {
_repair_rocm_wsl_bashrc
return 0
fi
- # WSL GPU passthrough device must exist (present on any WSL2 GPU host).
[ -e /dev/dxg ] || return 0
- # Strix APUs show in /proc/cpuinfo (the CPU model); discrete cards do not, so also ask the Windows host. Either signal suffices; the bootstrap detects arch from rocminfo.
if ! grep -qiE 'Ryzen AI Max|Radeon 80[0-9][05]S|Strix Halo' /proc/cpuinfo 2>/dev/null \
&& ! _wsl_amd_gpu_name >/dev/null 2>&1; then
return 0
@@ -6821,14 +6277,13 @@ _maybe_bootstrap_rocm_wsl() {
_rw_dxg_ref="4955d12888a3ec57057f1cf8660c2485e415e74c"
[ -n "$_rw_dxg_sha" ] || _rw_dxg_sha="$_rw_dxg_ref"
fi
- # A known SHA is authoritative, so forward it AS the ref: an operator pinning a branch plus its expected commit would otherwise have that symbolic ref cloned unverified by a helper old enough to ignore the SHA.
if [ -n "$_rw_dxg_sha" ]; then
_rw_dxg_ref="$_rw_dxg_sha"
fi
_rw_helper="${_REPO_ROOT:-.}/scripts/install_rocm_wsl_strixhalo.sh"
_rw_tmp=""
if [ "$_REPO_IS_CHECKOUT" != "1" ] || [ ! -r "$_rw_helper" ]; then
- # Never fall back to a fixed /tmp name: this file runs with sudo, and another user could own it.
+ # Never a fixed /tmp name: this runs elevated and another user could own it.
if ! _rw_tmp="$(mktemp 2>/dev/null)" || [ -z "$_rw_tmp" ]; then
substep "Could not create a private temp file for the ROCm-on-WSL helper; using CPU fallback." "$C_WARN"
return 0
@@ -6842,14 +6297,15 @@ _maybe_bootstrap_rocm_wsl() {
fi
fi
- # Run ONLY a helper declaring the contract (defined in its header): verifies the clone against the pinned SHA, and treats an unresolvable checkout as fatal. One without it swallows that failure and would build the repo's default HEAD as root once the pinned ref stopped existing. Gating on the declaration is what makes this fail closed whatever the pin supplies.
+ # Run only a helper declaring the contract, so a missing pinned ref fails closed.
if ! grep -q "^UNSLOTH_ROCM_WSL_HELPER_CONTRACT=2$" "$_rw_helper" 2>/dev/null; then
substep "ROCm-on-WSL helper predates the pinned-source check; using CPU fallback." "$C_WARN"
[ -n "$_rw_tmp" ] && rm -f "$_rw_tmp"
return 0
fi
- # Consent: the narrow guarded case is exactly the GPU setup the user ran the installer for, so it proceeds AUTOMATICALLY by default, with no TTY needed. Opt out via UNSLOTH_SKIP_ROCM_WSL_SETUP=1. The Tauri app drives its own consent UI, so under TAURI_MODE it only runs when the app passes UNSLOTH_ROCM_WSL_AUTO=1; else surface and wait.
+ # Runs automatically by default (opt out: UNSLOTH_SKIP_ROCM_WSL_SETUP=1). Under Tauri only with
+ # UNSLOTH_ROCM_WSL_AUTO=1.
_rw_go=1
if [ "${TAURI_MODE:-false}" = "true" ] && [ "${UNSLOTH_ROCM_WSL_AUTO:-0}" != "1" ]; then
tauri_log "ROCM_WSL_AVAILABLE" "strixhalo"
@@ -6858,7 +6314,6 @@ _maybe_bootstrap_rocm_wsl() {
fi
if [ "$_rw_go" = "1" ]; then
- # Helper does its own sudo and is idempotent. SMOKE_TEST=0: install.sh installs torch itself right after, into the real venv.
if UNSLOTH_WSL_SMOKE_TEST=0 \
UNSLOTH_LIBROCDXG_REF="$_rw_dxg_ref" UNSLOTH_LIBROCDXG_SHA="$_rw_dxg_sha" \
bash "$_rw_helper"; then
@@ -6879,7 +6334,6 @@ _maybe_bootstrap_rocm_wsl() {
[ -n "$_rw_tmp" ] && rm -f "$_rw_tmp"
return 0
}
-# A pinned wheel index skips the WSL ROCm bootstrap and the Radeon/Strix reroute below.
_torch_index_pinned=false
_ti_url_trim="${UNSLOTH_TORCH_INDEX_URL:-}"
_ti_url_trim="${_ti_url_trim#"${_ti_url_trim%%[![:space:]]*}"}"; _ti_url_trim="${_ti_url_trim%"${_ti_url_trim##*[![:space:]]}"}"
@@ -6890,7 +6344,8 @@ if [ -n "$_ti_url_trim" ] || [ -n "$_ti_family_trim" ]; then
fi
[ "$_torch_index_pinned" = true ] || _maybe_bootstrap_rocm_wsl || true
-# Created here, not inside get_torch_index_url: that runs in a command substitution, so only a file outlives it. mktemp -d, never a $$-derived name: a predictable path under a world-writable /tmp can be pre-created as a symlink, feeding the probe a chosen version.
+# A file outlives the command substitution. mktemp -d, never $$: a predictable /tmp path can be
+# pre-created as a symlink.
_ROCM_TAG_MEMO_DIR=$(mktemp -d "${TMPDIR:-/tmp}/unsloth-rocm.XXXXXX" 2>/dev/null) \
&& _ROCM_TAG_MEMO="$_ROCM_TAG_MEMO_DIR/tag" || _ROCM_TAG_MEMO=""
# The AMD display-class lspci lines, shared by _infer_linux_amd_gfx_arch and _infer_linux_unsupported_amd_gfx_arch.
@@ -6910,28 +6365,18 @@ if [ -n "$_te_trim" ]; then
fi
fi
-# The NVIDIA presence check runs here first: get_torch_index_url runs in a command substitution,
-# whose library inventory memo would not outlive it, and the later checks would probe again.
-# Not for a pinned index or no torch at all: the selection does not read the GPU then.
if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ]; then
_has_usable_nvidia_gpu >/dev/null 2>&1 || true
fi
TORCH_INDEX_URL=$(get_torch_index_url)
-# Linux: ROCm runtime missing but a supported AMD gfx arch is inferable (Strix Halo in /proc/cpuinfo, lspci marketing name, UNSLOTH_ROCM_GFX_ARCH). Route to AMD's per-arch wheels like install.ps1 does on Windows (unslothai#7301). Gated on the runtime probes NOT naming a gfx: either no AMD GPU is detected at all, or the GPU is visible only through the env-independent KFD topology while rocminfo/amd-smi cannot read its arch (#7314; before the KFD detection fix these hosts reached this reroute via the false branch, so the empty-probe condition preserves that routing). A */cpu index chosen WITH a readable gfx and a readable but UNSUPPORTED ROCm version is a deliberate fallback and stays excluded, since the shared probe returns its gfx; an UNREADABLE version is only a detection miss, so it gets its own way in below (#8731). UNSLOTH_ROCM_GFX_ARCH stays authoritative either way.
+# Runtime-less reroute to AMD per-arch wheels when the gfx is inferable (unslothai#7301, #7314).
+# A readable gfx with an unsupported ROCm version stays on cpu; an unreadable version is rerouted.
_amd_no_rocm_version_reroute=false
_amd_probed_gfx_first=""
-# Read before the branches below and reported after them: a closed node is invisible
-# to every probe this installer runs, so the index gets chosen as if the account could
-# use the card. On a runtime-less host the reroute above then rewrites a */cpu index to
-# a per-arch */gfx* one -- which is exactly the #10466 host -- so answering inside one
-# arm would miss the case this was written for.
-# `|| true` because this whole block is a DIAGNOSTIC and the script runs under `set -e`:
-# an unguarded assignment takes the installer down with it if the helper's last command
-# fails, and the helpers here shell out to stat, awk and tr. On a host missing one of
-# those the answer is "no advice", never "no install". Empty is what every consumer below
-# already treats as nothing to report.
+# Read before the branches: a closed node is invisible to every probe (#10466).
+# `|| true`: a diagnostic must never abort the install under set -e.
_closed_amd_nodes="$(_amd_nodes_closed_to_this_user || true)"
case "$TORCH_INDEX_URL" in
*/cpu)
@@ -6939,13 +6384,11 @@ case "$TORCH_INDEX_URL" in
[ -z "${UNSLOTH_ROCM_GFX_ARCH:-}" ] && \
! _nvidia_gpu_wins_over_amd && _has_amd_rocm_gpu; then
_amd_probe_out=$(_probe_amd_gfx_arch)
- # HSA_OVERRIDE_GFX_VERSION=11.0.0 is the standard Strix Halo workaround, and ROCr then reports the spoofed gfx1100. The llama.cpp path corrects that further down, which is too late for this branch: both the wheel family and the exported arch are derived from this probe, so an uncorrected gfx1151 would take gfx110X-all wheels and export gfx1100 to setup.sh.
_amd_spoof_inferred=$(_infer_linux_amd_gfx_arch 2>/dev/null || true)
_amd_spoof_physical=$(_hsa_spoofed_physical_gfx "$_amd_spoof_inferred" "$_amd_probe_out")
if [ -n "${_amd_spoof_physical:-}" ]; then
_amd_probe_out="$_amd_spoof_physical"
fi
- # An empty correction has two meanings and only one of them is "no spoof": the helper also declines whenever the KFD reports more than one GPU node, because the override can collapse several physical targets into one reported token. Counting NODES rather than distinct arches deliberately matches the helper's own rule, so a singleton probe it refused to vouch for never picks a family on its own.
if [ -z "${_amd_spoof_physical:-}" ] && [ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ] && \
[ "$(_kfd_gfx_targets | awk 'NF { n++ } END { print n + 0 }')" -gt 1 ]; then
_amd_probe_out=""
@@ -6954,19 +6397,16 @@ case "$TORCH_INDEX_URL" in
|| _amd_probed_family=""
_amd_probed_gfx_first=$(_amd_sole_index_arch "$_amd_probe_out") \
|| _amd_probed_gfx_first=""
- # Re-derived rather than read: _AMD_REQUEST_TARGET_GFX is assigned inside a command
- # substitution above, and the predicate is idempotent.
_amd_reroute_target=""
if _rocm_torch_explicitly_requested && _amd_request_has_a_wheel_route; then
_amd_reroute_target="${_AMD_REQUEST_TARGET_GFX:-}"
fi
_amd_reroute_bad_arch=false
- # A measured-bad arch anywhere in the inventory disqualifies the whole family, at the source not at each consumer: gfx1033 shares gfx103X-all with gfx1030-gfx1036, so the shared-family arm below would otherwise rewrite the cpu index the gate just chose back to ROCm wheels.
+ # A measured-bad arch anywhere disqualifies the whole family (gfx1033 shares gfx103X-all).
case " $(printf '%s\n' "$_amd_probe_out" | sed 's/:.*$//' \
| tr '[:upper:]' '[:lower:]' | tr '\n' ' ')" in
*" gfx1033 "*) _amd_reroute_bad_arch=true ;;
esac
- # Probe-resolved only, exactly as the gate inside get_torch_index_url.
case "$_amd_reroute_target" in
""|gfx1033) : ;;
*)
@@ -6980,9 +6420,6 @@ case "$TORCH_INDEX_URL" in
_amd_probed_family=""
_amd_probed_gfx_first=""
fi
- # Derived from the SELECTED card: _amd_agreed_index_family needs every physical GPU to
- # share a family and answers empty for a cross-family pair, which left the cpu index
- # unrewritten on exactly the host that resolved a routable target.
if [ "$_amd_reroute_bad_arch" = false ] && [ -n "$_amd_reroute_target" ] && \
[ "${_AMD_REQUEST_TARGET_SOURCE:-}" = probe ]; then
_amd_target_family=$(_amd_arch_index_family_for_gfx "$_amd_reroute_target") \
@@ -7006,18 +6443,16 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
[ "${_amd_no_rocm_version_reroute:-false}" = true ]; } && \
case "$(uname -s)" in Linux) true ;; *) false ;; esac && \
case "$_ARCH" in x86_64|amd64) true ;; *) false ;; esac; then
- # ROCm torch wheels are x86_64-only; get_torch_index_url returns CPU on other arches, so an inferred or overridden gfx must not reroute arm64 to AMD wheels.
case "$TORCH_INDEX_URL" in
*/cpu)
_linux_inferred_gfx=$(_infer_linux_amd_gfx_arch 2>/dev/null || true)
- # Inference hands an explicit override back verbatim, and HIP's gcnArchName carries feature flags (gfx1201:sramecc+:xnack-) the index table has no arm for, so the suffix silently cost the reroute. Normalise as the caller did.
_linux_inferred_gfx=$(_amd_sole_index_arch "$_linux_inferred_gfx") \
|| _linux_inferred_gfx=""
- # Route on the arch the probe read, not on lspci marketing-name inference: the two disagree on a mixed APU + discrete host, and inference's answer would install wheels for a GPU the reroute decision never looked at.
if [ "${_amd_no_rocm_version_reroute:-false}" = true ]; then
_linux_inferred_gfx="${_amd_probed_gfx_first:-}"
fi
- # The gfx1033 gate in get_torch_index_url is not enough alone: this reroute can take an explicit override or a no-version probe family straight back to gfx103X-all. UNSLOTH_ROCM_GFX_ARCH is unset too, not just the local: setup.sh forwards it as --rocm-gfx and _apply_host_overrides reads any forwarded gfx as proof of ROCm, skipping the Vulkan branch (112.8 vs 49.8 tok/s) and asking for a HIP build the host cannot run. Keyed on the PHYSICAL inventory, since a stale gfx1030 override makes the inferred value look healthy. The gate's own verdict ran in a command substitution and cannot be reused, hence the re-probe.
+ # Re-check the gfx1033 gate here: this reroute can bypass it. Also unset UNSLOTH_ROCM_GFX_ARCH
+ # so setup.sh does not request a HIP build. Keyed on the physical inventory.
_amd_reroute_physical=$(_probe_amd_gfx_arch physical 2>/dev/null || true)
[ -n "$_amd_reroute_physical" ] || _amd_reroute_physical=$(_kfd_gfx_targets 2>/dev/null || true)
case " $(printf '%s\n' "$_amd_reroute_physical" | sed 's/:.*$//' \
@@ -7038,7 +6473,6 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
_amd_family=$(_amd_arch_index_family_for_gfx "$_linux_inferred_gfx") || _amd_family=""
elif [ "${_amd_no_rocm_version_reroute:-false}" = true ] && \
[ -z "${_amd_probed_gfx_first:-}" ]; then
- # Multiple healthy arches may share one wheel family. No single arch is forwarded to llama.cpp, but torch can still use the agreed family.
_amd_family="${_amd_probed_family:-}"
fi
if [ -n "$_amd_family" ]; then
@@ -7047,11 +6481,9 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
_amd_mirror="${_amd_mirror%/}"
done
TORCH_INDEX_URL="${_amd_mirror}/${_amd_family}/"
- # Hand the arch to setup.sh (llama.cpp): it re-probes ROCm on its own, and on these runtime-less hosts its probes find nothing, so without this it classifies the box as non-ROCm and installs the CPU prebuilt while torch just got AMD per-arch wheels. setup.sh and install_llama_prebuilt.py both honor UNSLOTH_ROCM_GFX_ARCH, so exporting it is the whole handoff.
if [ -n "$_linux_inferred_gfx" ]; then
export UNSLOTH_ROCM_GFX_ARCH="$_linux_inferred_gfx"
fi
- # A corroborated spoof has to be cleared here as well. The rocm* leaf below does it, but this reroute produces a gfx* leaf, which that case never matches: the host would install native $_linux_inferred_gfx wheels while ROCr kept reporting the spoofed arch, leaving the kernels in those wheels unusable. SKIP_TORCH is false on this branch by its own guard, so the wheels really are going in.
if [ "${_amd_no_rocm_version_reroute:-false}" = true ] && \
[ -n "${_amd_spoof_physical:-}" ]; then
unset HSA_OVERRIDE_GFX_VERSION
@@ -7060,7 +6492,6 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
echo " [WARN] to report the real arch. Remove the export from your shell profile" >&2
echo " [WARN] (~/.bashrc, ~/.profile) as well, or the next terminal restores it." >&2
fi
- # Off the family, not the arch: no family straddles this boundary.
case "$_amd_family" in
gfx120X-all|gfx1151|gfx1150|gfx1152|gfx103X-all|gfx110X-all)
TORCH_CONSTRAINT="torch>=2.11.0,<2.12.0"
@@ -7069,7 +6500,6 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
;;
esac
echo "" >&2
- # KFD-only hosts reach this reroute with /dev/kfd present (that is what detected them), so do not claim it is missing.
if [ "${_amd_no_rocm_version_reroute:-false}" = true ]; then
echo " [WARN] AMD ${_linux_inferred_gfx:-$_amd_family} detected, but no ROCm version could be read (checked amd-smi, /opt/rocm/.info/version, hipconfig, dpkg, rpm)." >&2
echo " [WARN] The per-arch index is keyed on the arch alone, so the version is not needed." >&2
@@ -7092,9 +6522,6 @@ if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
esac
fi
-# The request buys a swap, never a downgrade. Asked of the RESOLVED index: the AMD branch
-# answers cpu for a ROCm too old, an arch no index covers, or a non-x86_64 host, and leaving
-# that would replace a working CUDA install with CPU torch.
if [ "$_torch_index_pinned" = false ] && [ "$SKIP_TORCH" = false ] && \
_rocm_torch_explicitly_requested && _has_usable_nvidia_gpu; then
if ! _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
@@ -7118,7 +6545,6 @@ while [ -n "$_torch_index_leaf" ] && [ "${_torch_index_leaf%/}" != "$_torch_inde
done
_torch_index_leaf="${_torch_index_leaf##*/}"
_torch_index_leaf=$(printf '%s' "$_torch_index_leaf" | tr '[:upper:]' '[:lower:]')
-# Whether the caller had already STATED a backend before the assignment below overwrites it. setup.sh documents UNSLOTH_TORCH_BACKEND=cpu as the way to keep a deliberate CPU install, and on a GPU-less host the resolved value is cpu too, so without this the manifest cannot tell a stated choice from the automatic answer.
if [ -n "${UNSLOTH_TORCH_BACKEND:-}" ]; then
_torch_backend_was_stated=true
_torch_backend_stated_value=$(printf '%s' "$UNSLOTH_TORCH_BACKEND" | tr '[:upper:]' '[:lower:]')
@@ -7150,14 +6576,12 @@ else
unset UNSLOTH_TORCH_BACKEND_SOURCE
fi
-# Whether TORCH_INDEX_URL names an actual pip ROCm family (rocm<digit>* / gfx*), gating the ROCm-only side effects below (AMD bitsandbytes, ROCm-torch repair). Digit-gated so a leaf merely STARTING with "rocm" is not force-repaired from the wrong path.
if _is_pip_rocm_family_leaf "$_torch_index_leaf"; then
_torch_index_is_rocm_family=true
else
_torch_index_is_rocm_family=false
fi
-# rocm7.2 and per-gfx indexes ship torch 2.11.0: raise the floor, matching the FINAL leaf only.
case "$_torch_index_leaf" in
rocm7.2|gfx120x-all|gfx1151|gfx1150|gfx1152|gfx103x-all|gfx110x-all)
TORCH_CONSTRAINT="torch>=2.11.0,<2.12.0"
@@ -7173,14 +6597,12 @@ case "$_torch_index_leaf" in
esac
_amd_gpu_radeon=false
-# Set when the runtime GPU has a generic-wheel floor, rerouted or not; the floor is per arch and the migrated-venv repair below must reuse the same number.
_gfx_rocm64_target=false
_gfx_rocm64_floor_maj=""
_gfx_rocm64_floor_min=""
_amd_arch_index_routed=false
_amd_arch_index_family=""
if [ "$_torch_index_pinned" = false ]; then
-# On the LEAF, like every other index classifier here: the AMD per-arch mirror is https://repo.amd.com/ROCM/whl/gfx120X-all/, so a whole-URL */rocm* glob brands every per-arch reroute as Radeon and the summary then reports repo.radeon.com wheels that were never fetched. The two older per-arch reroutes each clear the flag by hand afterwards; matching the leaf is what stops the next one from having to.
case "$_torch_index_leaf" in
rocm*)
if _has_amd_rocm_gpu && command -v rocminfo >/dev/null 2>&1 && \
@@ -7189,7 +6611,6 @@ case "$_torch_index_leaf" in
fi
;;
esac
-# 0 when a rocmX.Y index leaf ($1, the final path segment) is older than floor $2.$3 (int compare, so rocm7.2 < rocm7.13). Non-rocm leaves (gfx*, cu*, cpu) and non-numeric versions return 1. Leaf-based so a mirror base holding its own rocm token compares the family leaf, not the base path.
_rocm_leaf_below() {
case "$1" in rocm[0-9]*.[0-9]*) : ;; *) return 1 ;; esac
_rb=${1#rocm}; _maj=${_rb%%.*}; _min=${_rb#*.}; _min=${_min%%.*}
@@ -7198,8 +6619,7 @@ _rocm_leaf_below() {
if [ "$_maj" -eq "$2" ] && [ "$_min" -lt "$3" ]; then return 0; fi
return 1
}
-# 0 when the venv's torch has no identifiable rocm family at $2.$3 or newer, mirroring _installed_rocm_wheel_is_below in studio/install_python_stack.py
-# Venv torch's AMD per-arch family from the `rocm` meta-package (as install_python_stack.py); empty if unknown.
+# Mirrors _installed_rocm_wheel_is_below in studio/install_python_stack.py.
_venv_torch_amd_family() {
"$1" -I -c 'import re
from importlib import metadata
@@ -7221,37 +6641,29 @@ _venv_torch_rocm_below() {
}
# ── Strix Halo / Strix Point: route to the AMD arch-specific index ───────────
-# gfx1151/gfx1150 need torch 2.11+rocm7.13 from repo.amd.com/rocm/whl/gfx<arch>/, which carries AMD's real fixes (the rocm7.1 _grouped_mm segfault, moe_utils.py:167, and later Strix kernel bugs). Every generic pytorch.org index below rocm7.13 lacks them, and the Radeon repo can be offline (#7264), so reroute a detected Strix GPU whenever the picked index is older than the arch build; rocm7.13+ already has the fixes.
+# gfx1151/gfx1150 need torch 2.11+rocm7.13 from repo.amd.com; older generic indexes lack the fixes (#7264).
case "$_torch_index_leaf" in
rocm[0-9]*)
- # Re-declared because test_rocm_support.py lifts this arm out whole: under `set -u` an outside initialiser would abort it instead of routing.
+ # Re-declared because test_rocm_support.py lifts this arm out whole (set -u).
_gfx_rocm64_target=false
_gfx_rocm64_floor_maj=""
_gfx_rocm64_floor_min=""
_amd_arch_index_routed=false
_amd_arch_index_family=""
- # One record per adapter in probe enumeration order, indexed by HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES so the mask selects a CARD. A deduplicated arch list could not: gfx1100 + gfx1100 + gfx1200 ran off the end of a two-entry list, and a Strix iGPU + dGPU box rerouted the selected dGPU to the Strix per-gfx index. `|| true` on each probe so one that finds nothing does not abort the installer under set -euo pipefail before the next fallback. UNSLOTH_ROCM_GFX_ARCH overrides probing, mirroring setup.sh and the display block.
_gfx_all=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
- # strip a copied hip gcnArchName suffix, matching _gfx906_env below and the python helper
_gfx_all=${_gfx_all%%:*}
- # which probe answered: only rocminfo is filtered by an rocr mask, so only it can pre-apply one
_gfx_probe=""
- # Which index space _gfx_all is in: `hip` for rocminfo and for an explicit UNSLOTH_ROCM_GFX_ARCH, which names one arch outright, and for amd-smi only once _amd_smi_hip_order has translated its discovery order.
_gfx_space=hip
if [ -z "$_gfx_all" ] && command -v rocminfo >/dev/null 2>&1; then
_gfx_all=$(rocminfo 2>/dev/null | _rocminfo_gpu_records | _gfx_arch_slots || true)
- # rocminfo is an ROCr client, so it enumerates in the order HIP numbers from.
[ -n "$_gfx_all" ] && { _gfx_probe=rocminfo; _gfx_space=hip; }
fi
if [ -z "$_gfx_all" ] && command -v amd-smi >/dev/null 2>&1; then
_gfx_records=$(amd-smi list 2>/dev/null | _amd_smi_gpu_records || true)
- # PowerShell paths also probe `amd-smi static --asic`; mirror it so a host with hipinfo-less amd-smi reports the gfx target.
- # `amd-smi list` may answer ids with no arch (a record per device, arch column empty), so test for an arch, not for records.
case "$_gfx_records" in *gfx*) ;; *)
_gfx_records=$(amd-smi static --asic 2>/dev/null | _amd_smi_gpu_records || true) ;;
esac
if [ -n "$_gfx_records" ]; then
- # HIP_ID from `amd-smi list -e` maps discovery order onto the order HIP numbers, as the GPU summary below does. The first output line reports which space came back.
_gfx_smi_out=$(amd-smi list -e 2>/dev/null | _amd_smi_hip_order "$_gfx_records" || true)
_gfx_space=$(printf '%s\n' "$_gfx_smi_out" | sed -n 1p)
_gfx_records=$(printf '%s\n' "$_gfx_smi_out" | tail -n +2)
@@ -7259,7 +6671,7 @@ case "$_torch_index_leaf" in
[ -n "$_gfx_all" ] && _gfx_probe=amd-smi
fi
fi
- # get_torch_index_url reads the arch with ROCR/HIP masks cleared, so a mask hiding every agent (ROCR_VISIBLE_DEVICES=-1) still lands here on a generic rocm index; re-probe unmasked or a masked-out Strix box keeps the broken generic wheels. Partial masks never get here (they enumerate at least one agent above) and keep their selection. ${VAR+x}, not :-, because a SET-but-empty mask also hides every agent and must trigger the re-probe.
+ # A mask hiding every agent still lands here; re-probe unmasked. ${VAR+x}: set-but-empty hides all.
if [ -z "$_gfx_all" ] && [ -n "${ROCR_VISIBLE_DEVICES+x}${HIP_VISIBLE_DEVICES+x}" ]; then
if command -v rocminfo >/dev/null 2>&1; then
_gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; rocminfo 2>/dev/null) | _rocminfo_gpu_records | _gfx_arch_slots || true)
@@ -7269,11 +6681,10 @@ case "$_torch_index_leaf" in
_gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi list 2>/dev/null) | _amd_smi_gpu_records | _gfx_arch_slots || true)
[ -z "$_gfx_all" ] && \
_gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi static --asic 2>/dev/null) | _amd_smi_gpu_records | _gfx_arch_slots || true)
- # Left in discovery space: the single-GPU box this rescue is for routes normally, a mixed one declines below.
[ -n "$_gfx_all" ] && _gfx_space=discovery
fi
fi
- # HSA_OVERRIDE_GFX_VERSION=11.0.0 (the circulated Strix workaround) makes ROCr hand rocminfo the SPOOFED ISA, so a gfx1151 host reports gfx1100 and the Strix case below never matches (#7331). Correct the reading back to the physical arch first, only in the narrow shape that cannot be a real mixed host.
+ # Correct an HSA_OVERRIDE_GFX_VERSION spoof back to the physical arch first (#7331).
_spoof_physical=""
if [ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ] && [ -n "$_gfx_all" ]; then
_spoof_inferred=$(_infer_linux_amd_gfx_arch 2>/dev/null || true)
@@ -7288,12 +6699,10 @@ case "$_torch_index_leaf" in
# indexing by ROCR again shadows CUDA, its HIP alias: ROCR=2,1 + CUDA=1 is survivor 2.
_vis_masks="HIP_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES"
if [ "$_gfx_probe" != rocminfo ] && [ -n "${ROCR_VISIBLE_DEVICES:-}" ] && [ "$ROCR_VISIBLE_DEVICES" != "-1" ]; then
- # amd-smi is not ROCr-filtered: keep ROCr's survivors (prefix up to the first out-of-range or repeated ordinal, as _rocr_visible_subset; none keeps all), then HIP indexes them.
_rocr_kept=$(printf '%s\n' "$_gfx_all" | awk -v m="$ROCR_VISIBLE_DEVICES" '
NF { v[n++] = $0 }
END { k = split(m, t, ","); for (i = 1; i <= k; i++) { gsub(/[[:space:]]/, "", t[i]); if (t[i] !~ /^[0-9]+$/) continue; x = t[i] + 0; if (x >= n || (x in s)) break; s[x] = 1; print v[x] } }')
[ -n "$_rocr_kept" ] && _gfx_all="$_rocr_kept"
- # A UUID token names a device but no position here, so with unlike adapters no survivor is known to be the one selected: decline, as _rocr_visible_subset does.
_rocr_unresolved=$(printf '%s' "$ROCR_VISIBLE_DEVICES" | tr -d '0-9, \t')
fi
_vis_var=""
@@ -7320,8 +6729,6 @@ case "$_torch_index_leaf" in
if (idx < 0 || idx >= n) idx = 0
if (n > 0) print vals[idx]
}')
- # No HIP_ID map and unlike adapters: in amd-smi discovery order no ordinal names a
- # known device, so routing would install wheels for a card the runtime will not use.
if [ "$_gfx_space" != hip ] && \
[ "$(printf '%s\n' "$_gfx_all" | awk 'NF && !seen[$0]++ { n++ } END { print n + 0 }')" -gt 1 ]; then
echo "" >&2
@@ -7360,7 +6767,6 @@ case "$_torch_index_leaf" in
esac
fi
fi
- # An explicit UNSLOTH_ROCM_GFX_ARCH=gfx906 pins the runtime target to the MI50 / Radeon VII path and must win over Strix probe-order detection on a mixed Strix + MI50 host, so the Strix reroute is suppressed when it is set. Normalize a copied HIP gcnArchName (gfx906:sramecc-:xnack- to gfx906) and trim whitespace so the suffix or a stray newline does not defeat the exact gfx906 comparisons below.
_gfx906_env=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
_gfx906_env=${_gfx906_env%%:*}
_strix_gfx=""
@@ -7369,7 +6775,6 @@ case "$_torch_index_leaf" in
gfx1151|gfx1150|gfx1152) _strix_gfx="$_runtime_gfx" ;;
esac
fi
- # Skip rocm7.13+ generic indexes: they already ship the fixes, so the arch build (rocm7.13) would be a downgrade rather than a rescue.
if [ -n "$_strix_gfx" ] && _rocm_leaf_below "$_torch_index_leaf" 7 13; then
echo "" >&2
echo " [WARN] $_strix_gfx (Strix) detected -- routing to the AMD arch-specific index" >&2
@@ -7377,7 +6782,6 @@ case "$_torch_index_leaf" in
echo " [WARN] _grouped_mm segfault, moe_utils.py:167, and later Strix kernel bugs)," >&2
echo " [WARN] and is more reliable than the rocm7.2 index or an offline Radeon repo." >&2
echo "" >&2
- # AMD's arch index carries the real _grouped_mm fix (torch 2.11.0+rocm7.13.0).
_amd_strix_base="${UNSLOTH_AMD_ROCM_MIRROR:-https://repo.amd.com/rocm/whl}"
while [ "${_amd_strix_base%/}" != "$_amd_strix_base" ]; do
_amd_strix_base="${_amd_strix_base%/}"
@@ -7390,7 +6794,8 @@ case "$_torch_index_leaf" in
TORCHVISION_CONSTRAINT="torchvision>=0.26.0,<0.27.0"
TORCHAUDIO_CONSTRAINT="torchaudio>=2.11.0,<2.12.0"
_amd_gpu_radeon=false
- # Routing the wheels is only half of #7331: ROCr rebuilds the agent from HSA_OVERRIDE_GFX_VERSION in every LATER process (and this shell execs Unsloth further down), so leaving it set hands the freshly installed per-gfx wheels a device whose reported ISA matches none of their code. Only on this branch, where the spoof was corroborated and native $_strix_gfx wheels are going in; paths that keep generic wheels need the override as their only source of kernels. SKIP_TORCH is the other half of "the wheels are going in": --no-torch reaches this branch and installs nothing, so clearing the override there would strand the host with generic wheels AND no override. Mirrors _clear_confirmed_hsa_spoof in studio/install_python_stack.py.
+ # Clear the spoof only when native wheels are really going in.
+ # Mirrors _clear_confirmed_hsa_spoof in studio/install_python_stack.py.
if [ -n "$_spoof_physical" ] && [ "$SKIP_TORCH" = false ]; then
unset HSA_OVERRIDE_GFX_VERSION
echo " [WARN] Clearing HSA_OVERRIDE_GFX_VERSION for the rest of this install:" >&2
@@ -7399,14 +6804,14 @@ case "$_torch_index_leaf" in
echo " [WARN] (~/.bashrc, ~/.profile) as well, or the next terminal restores it." >&2
fi
fi
- # RDNA 4 generic wheels below 7.13 have a null HIP _grouped_mm (TheRock #5284); leaf rewritten so the rocm6.4 floor cannot undo it.
+ # RDNA 4 generic wheels below 7.13 have a null HIP _grouped_mm (TheRock #5284).
_rdna4_gfx=""
if [ "$_gfx906_env" != "gfx906" ]; then
case "$_runtime_gfx" in
gfx1200|gfx1201) _rdna4_gfx="$_runtime_gfx" ;;
esac
fi
- # gfx120X-all publishes cp310+ only, so a 3.9 venv keeps the generic wheels.
+ # gfx120X-all publishes cp310+ only.
if [ -n "$_rdna4_gfx" ] && [ "$("${VENV_DIR:-}/bin/python" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)" = "3.9" ]; then
_rdna4_gfx=""
fi
@@ -7430,36 +6835,14 @@ case "$_torch_index_leaf" in
_amd_gpu_radeon=false
_torch_index_leaf="gfx120x-all"
fi
- # Navi 33 (gfx1102) and RDNA 4 (gfx1200/gfx1201) have no kernels in the
- # older generic wheel families. The floor is per arch, read from the
- # rocBLAS and hipBLASLt Tensile library names in each leaf's cp312 wheels:
- #
- # rocm6.0 (2.3.1-2.4.1) gfx1030 gfx1100
- # rocm6.1 (2.5.0-2.6.0) gfx1030 gfx1100 gfx1101
- # rocm6.2 (2.5.0-2.5.1) gfx1030 gfx1100
- # rocm6.3 (2.7.0-2.9.1) gfx1030 gfx1100 gfx1101 gfx1102 gfx1200 gfx1201
- # rocm6.4 (2.8.0-2.9.1) same set
- #
- # gfx1102 floors at 6.3. gfx1200/gfx1201 keep 6.4, matching
- # _GENERIC_WHEEL_GFX_MIN_ROCM in studio/install_python_stack.py (keep the
- # two tables in step) and AMD's matrix, which puts production RDNA 4 at 6.4.
- #
- # Beside the gfx906 policy, not inside the runtime-less */cpu reroute,
- # because a valid host ROCm reading can otherwise select broken rocm6.1
- # wheels. Explicit torch-index pins skip this whole block.
+ # Navi 33 (gfx1102) floors at rocm6.3; gfx1200/gfx1201 at 6.4, matching
+ # _GENERIC_WHEEL_GFX_MIN_ROCM in studio/install_python_stack.py (keep the two tables in step).
case "$_runtime_gfx" in
gfx1102) _gfx_rocm64_floor_maj=6; _gfx_rocm64_floor_min=3 ;;
gfx1200|gfx1201) _gfx_rocm64_floor_maj=6; _gfx_rocm64_floor_min=4 ;;
esac
if [ -n "$_gfx_rocm64_floor_maj" ]; then
_gfx_rocm64_target=true
- # These arches train from the generic wheels, never repo.radeon.com, so
- # clear the marketing-name flag as the gfx906 branch below does: the
- # newest rocm-rel-6.4 trio (torch 2.6.0+rocm6.4.0) carries no gfx1102
- # Tensile library, and rocm-rel-7.2 is narrower still (gfx120X-all,
- # gfx90a, gfx942, gfx950). Cleared whenever the arch is the runtime
- # target, even when the leaf already satisfies the floor and the reroute
- # below is a no-op.
_amd_gpu_radeon=false
_gfx_rocm64_tag="rocm${_gfx_rocm64_floor_maj}.${_gfx_rocm64_floor_min}"
if _rocm_leaf_below "$_torch_index_leaf" "$_gfx_rocm64_floor_maj" "$_gfx_rocm64_floor_min"; then
@@ -7484,7 +6867,6 @@ case "$_torch_index_leaf" in
_gfx906_uniq=$(printf '%s\n' "$_gfx_all" | awk 'NF && !seen[$0]++')
[ "$_gfx906_uniq" = "gfx906" ] && _gfx906_target=true
fi
- # gfx906 always trains from the PyTorch rocm6.3 wheels, never the Radeon repo, whose wheels carry no gfx906 BLAS kernels. Clear the Radeon marketing-name flag as soon as gfx906 is the target, even when the host already picks rocm6.0-6.3 and the reroute below is a no-op, so a Radeon VII does not divert to the radeon branch on those versions.
if [ "$_gfx906_target" = true ]; then
_amd_gpu_radeon=false
fi
@@ -7502,17 +6884,14 @@ case "$_torch_index_leaf" in
_amd_gfx906_base="${_amd_gfx906_base%/}"
done
TORCH_INDEX_URL="${_amd_gfx906_base}/rocm6.3"
- # Cap below <2.12: a rocm7.2 pick floors at 2.11, which rocm6.3 (<= 2.9.x) cannot meet.
TORCH_CONSTRAINT="torch>=2.4,<2.11.0"
TORCHVISION_CONSTRAINT="torchvision>=0.19,<0.26.0"
TORCHAUDIO_CONSTRAINT="torchaudio>=2.4,<2.11.0"
- # (_amd_gpu_radeon already cleared above for every gfx906 target.)
fi
;;
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.
+# New installs on this route get 2.13; preservation keeps 2.4-2.14 installs on their release.
_PRESERVE_TORCH_CONSTRAINT="$TORCH_CONSTRAINT"
_CU130_NEW_INSTALL_ROUTE=false
if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL")" = "yes" ]; then
@@ -7527,12 +6906,9 @@ if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL"
fi
fi
_PREV_TORCH_PIN=""
-# The pre-route default: a kept release that fails to reinstall falls back here, never to 2.13.
_PREV_FALLBACK_CONSTRAINT="$TORCH_CONSTRAINT"
if [ "$SKIP_TORCH" = false ]; then
_prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT")
- # UNSLOTH_TORCH_UPGRADE=1 (Settings > Repair) with the 2.13 route closed (PyPI unreachable, a
- # mirror, an older release) must not move a resident release above the default range down.
if [ -z "$_prev_pin" ] && [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] \
&& [ "$_CU130_NEW_INSTALL_ROUTE" = false ] && [ -n "$_PREV_TORCH_VER" ] \
&& [ "$(_torch_release_in_window "${_PREV_TORCH_VER%%+*}" "$TORCH_CONSTRAINT")" != "yes" ]; then
@@ -7558,11 +6934,7 @@ tauri_diag_marker "$_TAURI_GPU_BRANCH" "$_TAURI_TORCH_INDEX_FAMILY"
# ── GPU detection summary (mirrors install.ps1 step "gpu" block) ──
-# Asked of the RESOLVED index, not the predicate that chose it: after the CUDA restore the
-# request is still set and an AMD card still present, so the predicate says "AMD wins" while
-# CUDA wheels are what gets installed. A PIN is exempt, because it names a wheel family rather
-# than a card: on an NVIDIA host pinned to a ROCm index there is no AMD card to describe, and
-# hiding the NVIDIA identity behind it reported hardware the machine does not have.
+# Asked of the resolved index; a pin names a wheel family, not a card.
if _has_usable_nvidia_gpu && \
{ [ "$_torch_index_pinned" = true ] || ! _torch_index_url_is_rocm "$TORCH_INDEX_URL"; }; then
_nv_banner_fields
@@ -7577,7 +6949,6 @@ if _has_usable_nvidia_gpu && \
# behind on the common path where there is no driver string to print.
if [ -n "$_nv_driver" ]; then substep "Driver: $_nv_driver"; fi
elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
- # Probe gfx arch for the display label, honouring HIP_VISIBLE_DEVICES
_ensure_rocm_probe_env
_gpu_disp_gfx_all=""
_gpu_disp_gfx=""
@@ -7595,7 +6966,6 @@ elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
| _amd_smi_hip_order "$_gpu_disp_smi_records" || true)
_gpu_disp_smi_space=$(printf '%s\n' "$_gpu_disp_smi_out" | sed -n 1p)
_gpu_disp_smi_records=$(printf '%s\n' "$_gpu_disp_smi_out" | tail -n +2)
- # No map, and the adapters are not interchangeable: the mask indexes HIP order while these records are in discovery order, so any ordinal is a guess. Report nothing rather than name one card while the mask selects another. amd-smi 6.1.1 reports no TARGET_GRAPHICS_VERSION at all and the arch is then inferred from the name, so an archless record is compared on its name instead. Interchangeable adapters are unaffected: every ordinal gives the same answer.
if [ "$_gpu_disp_smi_space" != hip ] && \
[ "$(printf '%s\n' "$_gpu_disp_smi_records" | awk -F'|' \
'NF { k = ($1 != "" ? $1 : "name:" $2); if (!(k in seen)) { seen[k]; n++ } }
@@ -7664,7 +7034,6 @@ elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
if [ -n "${UNSLOTH_ROCM_GFX_ARCH:-}" ]; then
_gpu_disp_gfx="${UNSLOTH_ROCM_GFX_ARCH}"
substep "gfx arch from UNSLOTH_ROCM_GFX_ARCH env override: $_gpu_disp_gfx"
- # Name-based arch inference when tools don't report gfx (mirrors install.ps1 nameArchTable)
elif [ -z "$_gpu_disp_gfx" ] && [ -n "$_gpu_disp_mkt" ]; then
# In sync with install.ps1 nameArchTable; gfx1102 before gfx1100 ("RX 7700S").
case "$_gpu_disp_mkt" in
@@ -7695,9 +7064,6 @@ elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
_gpu_rocm_ver=$(amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
'NF>1{gsub(/[[:space:]]/,"", $2); print $2; exit}' || true)
fi
- # $_gpu_disp_mkt is the marketing name of the SAME record the arch came from, so it
- # is safe to put on the step line: _rocminfo_gpu_records pairs it per GPU agent and
- # _amd_smi_hip_order puts the amd-smi records in the order the mask indexes.
if [ -n "$_gpu_disp_mkt" ] && [ -n "$_gpu_disp_gfx" ]; then
step "gpu" "$_gpu_disp_mkt ($_gpu_disp_gfx)"
elif [ -n "$_gpu_disp_mkt" ]; then
@@ -7708,7 +7074,6 @@ elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
step "gpu" "AMD ROCm"
fi
_rocm_root="${ROCM_PATH:-${HIP_PATH:-/opt/rocm}}"
- # Only claim a path that is really there: /opt/rocm is a FALLBACK, not a detection, and a runtime-only ROCm (no SDK tree) reaches here with nothing at that path.
if [ -d "$_rocm_root" ]; then
substep "ROCm: $_rocm_root"
else
@@ -7716,7 +7081,6 @@ elif _torch_index_url_is_rocm "$TORCH_INDEX_URL"; then
fi
[ -n "$_gpu_rocm_ver" ] && substep "hipconfig: $_gpu_rocm_ver"
elif [ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ]; then
- # Apple Silicon: PyTorch gets Metal (MPS) acceleration over unified memory, so not CPU-only.
step "gpu" "Apple Silicon (Metal, unified memory)"
elif _has_amd_rocm_gpu; then
# The arch read fine and get_torch_index_url sent it to CPU for having no wheels (#8529),
@@ -7736,12 +7100,10 @@ elif _has_amd_rocm_gpu; then
END { if (!bad && l != "") print l }') || _amd_unsup_read=""
fi
if [ "$_torch_index_pinned" = true ]; then
- # An explicit UNSLOTH_TORCH_INDEX_URL/_FAMILY pin skipped all probing; do not claim ROCm is unusable when a CPU or other index was requested.
step "gpu" "AMD GPU (torch index pinned: $_torch_index_leaf)" "$C_WARN"
elif [ -n "$_amd_unsup_read" ]; then
step "gpu" "AMD GPU ($_amd_unsup_read, no ROCm PyTorch wheels -- CPU fallback)" "$C_WARN"
else
- # AMD GPU visible to the kernel but the torch index stayed CPU: no usable ROCm userspace to pick a wheel. "none" would repeat the false diagnosis this installer used to give.
step "gpu" "AMD GPU (no usable ROCm -- CPU fallback)" "$C_WARN"
fi
elif [ "$_torch_index_leaf" = xpu ]; then
@@ -7759,7 +7121,6 @@ case "$TORCH_INDEX_URL" in
*/cpu)
if [ "$SKIP_TORCH" = false ] && [ "$OS" != "macos" ]; then
if [ "$_torch_index_pinned" = true ]; then
- # An explicit CPU pin is a request, not a detection failure: skip the SDK guidance, since ROCm may be perfectly healthy here.
substep "CPU-only PyTorch (index pinned via UNSLOTH_TORCH_INDEX_URL / _FAMILY)."
elif { [ -e /etc/nv_tegra_release ] || grep -qa 'nvidia,tegra' /proc/device-tree/compatible 2>/dev/null; } && \
_tegra_note_cuda=$(_nvidia_driver_cuda_version 2>/dev/null || true) && \
@@ -7778,7 +7139,6 @@ case "$TORCH_INDEX_URL" in
substep "Training runs on the CPU. A JetPack PyTorch build for this venv's Python, if you install one, is kept by updates;" "$C_WARN"
substep " NVIDIA's own wheels target JetPack's system Python: https://docs.nvidia.com/deeplearning/frameworks/install-pytorch-jetson-platform/" "$C_WARN"
elif _has_amd_rocm_gpu; then
- # A generation ROCm never covered is not a missing SDK (#8529). Unlike the arm in get_torch_index_url, this one runs even when the arch read fine, so it needs its own peer guard: an RX 5700 beside an RX 7900 lands here whenever the 7900's ROCm is too old, and blaming the 5700 would replace the upgrade advice with advice that is false for the card that caused the fallback. _infer_linux_amd_gfx_arch scans every display adapter, so a covered answer clears this one.
_covered_disp_gfx=$(_infer_linux_amd_gfx_arch 2>/dev/null) || _covered_disp_gfx=""
if [ -n "$_covered_disp_gfx" ] && _amd_arch_index_family_for_gfx "$_covered_disp_gfx" >/dev/null 2>&1; then
_unsup_disp_gfx=""
@@ -7787,7 +7147,6 @@ case "$TORCH_INDEX_URL" in
fi
[ -n "$_unsup_disp_gfx" ] || _unsup_disp_gfx="${_amd_unsup_read:-}"
if [ -n "$_unsup_disp_gfx" ]; then
- # Scoped to the card, as above: the SDK may still help another one.
substep "AMD GPU detected ($_unsup_disp_gfx) -- Unsloth has no ROCm PyTorch wheels for that arch, installing CPU PyTorch." "$C_WARN"
substep "Installing the ROCm/HIP SDK will not give this GPU ROCm PyTorch." "$C_WARN"
if [ "$_unsup_disp_gfx" = gfx1153 ]; then
@@ -7807,7 +7166,6 @@ case "$TORCH_INDEX_URL" in
substep "No GPU detected -- installing CPU-only PyTorch." "$C_WARN"
fi
if [ "$OS" = "wsl" ] && [ "$_torch_index_pinned" = false ]; then
- # WSL and no GPU detected. Common cause: an AMD GPU whose ROCm-on-WSL runtime is not exposed yet, with /dev/dxg present but no ROCm runtime.
_wsl_ubu_ver=""
[ -r /etc/os-release ] && _wsl_ubu_ver=$(. /etc/os-release 2>/dev/null; printf '%s' "${VERSION_ID:-}")
if [ -e /dev/dxg ]; then
@@ -7844,33 +7202,14 @@ case "$TORCH_INDEX_URL" in
fi
;;
esac
-# These sit after the whole case because they are properties of the HOST, not of the arm
-# the index landed in, and both are gated on the route: _has_amd_rocm_gpu returns false on
-# ANY host with a usable NVIDIA GPU, so without the gate every hybrid box with an AMD card
-# on the bus would be told to install a ROCm kernel stack its CUDA wheels never use.
-#
-# Two sibling arms rather than a nested `if`, since an ABSENT /dev/kfd is not a CLOSED one
-# and a host can need both repairs; the harnesses also lift this block by walking back to
-# the `if` above a sentence.
-#
-# The runtime half's needs_kfd: SKIP_TORCH does not settle it, because --no-torch still
-# installs a GGUF bundle and the ROCm one opens /dev/kfd exactly as torch would (the #10466
-# shape). The three named are the REQUESTABLE_BACKENDS that are not ROCm
-# (utils/prebuilt/llama_backend.py). Normalized as the bundle selector normalizes it
-# (studio/setup.sh, `awk '{$1=$1}'`): deleting internal whitespace let "vul kan" match here
-# and go quiet while setup.sh rejects it and may fall back to ROCm.
-
-# Whether the TORCH this run installs can open an AMD device node, which only a ROCm wheel
-# does. Asked positively, not as "anything that is not the cpu leaf": that read a CUDA
-# index as a KFD consumer, and told a healthy hybrid host to repair /dev/kfd permissions
-# for a node neither its CUDA wheel nor its Vulkan bundle opens. Classified exactly as the
-# route case classifies, so the two cannot disagree.
+# Host properties, gated on the route so hybrid NVIDIA hosts are not told to install ROCm.
+# Two sibling arms (absent vs closed /dev/kfd); harnesses lift this block by walking back to the `if`.
+
+# Whether the TORCH this run installs can open an AMD device node, which only a ROCm wheel does.
_torch_opens_amd_nodes() {
[ "$SKIP_TORCH" = true ] && return 1
_toan_leaf=$(_torch_index_url_leaf "${TORCH_INDEX_URL:-}")
case "$_toan_leaf" in
- # repo.radeon.com is rocm-rel-X.Y and nothing else; a pin that merely starts with
- # it is somebody's mirror, exactly as the route case anchors its own arm.
rocm-rel-*[!0-9.]*) return 1 ;;
rocm-rel-[0-9]*) return 0 ;;
esac
@@ -7878,20 +7217,10 @@ _torch_opens_amd_nodes() {
return 1
}
-# An unset or `auto` request is not a decision here, but it is not a coin toss either:
-# _linux_published_attempts takes the CUDA bundle under `if host.has_usable_nvidia:` and
-# only reaches ROCm in the `elif host.has_rocm` below it. So on a hybrid box the automatic
-# bundle opens no AMD node, and the AMD-evidence gates cannot tell: the card IS there and
-# its nodes ARE shut, they are simply nothing this install will use. Listed as the values
-# that ARE decisions rather than the two that are not, because setup.sh normalises anything
-# outside this set away (is_requestable_backend -> None -> auto).
_auto_bundle_opens_amd_nodes() {
case "$(_requested_llama_backend)" in
cpu|cuda|rocm|hip|vulkan) return 0 ;;
esac
- # Memoized: _has_usable_nvidia_gpu shells out to `nvidia-smi -L` and the two scope
- # predicates below ask repeatedly, so an NVIDIA-less host paid one probe per gate.
- # Nothing it reads changes within a run.
if [ -z "${_amd_auto_nvidia_cached:-}" ]; then
if _has_usable_nvidia_gpu; then
_amd_auto_nvidia_cached=yes
@@ -7903,13 +7232,8 @@ _auto_bundle_opens_amd_nodes() {
return 0
}
-# The effective llama.cpp backend request, resolved the way
-# utils/prebuilt/llama_backend.py::environment_backend_override resolves it: a RECOGNISED
-# UNSLOTH_LLAMA_CPP_BACKEND wins outright ("auto" included, being a request to detect), and
-# only an absent or unrecognised one leaves the legacy UNSLOTH_FORCE_VULKAN in effect.
-# Reading the new variable alone put UNSLOTH_FORCE_VULKAN=1 on the automatic route here while
-# effective_backend_request built a Vulkan bundle, so on a CUDA-indexed or hybrid host the
-# render-node diagnoses were suppressed for a run that opens exactly those nodes.
+# Resolved like llama_backend.py::environment_backend_override: a recognised
+# UNSLOTH_LLAMA_CPP_BACKEND wins, else legacy UNSLOTH_FORCE_VULKAN applies.
_requested_llama_backend() {
_rlb=$(printf '%s' "${UNSLOTH_LLAMA_CPP_BACKEND:-}" | awk '{$1=$1; print tolower($0)}')
case "$_rlb" in
@@ -7918,8 +7242,6 @@ _requested_llama_backend() {
case "$(printf '%s' "${UNSLOTH_FORCE_VULKAN:-}" | awk '{$1=$1; print tolower($0)}')" in
1|true|yes|on) printf '%s\n' vulkan; return 0 ;;
esac
- # An unrecognised value falls through unchanged, so the callers' cases miss it and the
- # automatic route decides, exactly as setup.sh normalises a typo away to auto.
printf '%s\n' "$_rlb"
}
@@ -7932,10 +7254,6 @@ _run_may_open_kfd() {
return 0
}
-# One layer wider, for the diagnoses that are not about /dev/kfd. A Vulkan bundle opens a
-# render node, so those still apply to it; a CPU or CUDA bundle beside --no-torch opens no
-# AMD node at all, and telling that install to join the render group describes a card
-# nothing in the run was going to touch.
_run_may_open_a_gpu_node() {
_torch_opens_amd_nodes && return 0
case "$(_requested_llama_backend)" in
@@ -7945,23 +7263,10 @@ _run_may_open_a_gpu_node() {
return 0
}
-# Read from the LEAF, and through the same _is_pip_rocm_family_leaf every other index
-# classifier here uses: a whole-URL */rocm*|*/gfx* glob also matches a custom pin whose
-# final segment merely STARTS with one ("gfx-mirror", "rocm7.2-private"), which that helper
-# exists to reject, and a hybrid host on such a pin then got repairs for a card its wheels
-# have nothing to do with. Recomputed from TORCH_INDEX_URL rather than reusing
-# $_torch_index_leaf, since the per-arch reroutes rewrite the URL after that is set.
-# repo.radeon.com is named separately: its leaf is rocm-rel-X.Y, a real ROCm route that is
-# not a pip family, so the family test alone would drop it.
-# Guarded for the same reason as the closed-node read above: a diagnostic may not
-# abort the install under `set -e`. An empty leaf falls to the pip-family arm below.
+# Leaf through _is_pip_rocm_family_leaf (rejects custom pins); repo.radeon.com handled apart.
+# Guarded: a diagnostic may not abort under set -e.
_amd_node_diag_leaf=$(_torch_index_url_leaf "$TORCH_INDEX_URL" || true)
case "$_amd_node_diag_leaf" in
- # A repo.radeon.com leaf is rocm-rel-X.Y[.Z] and nothing else, anchored the way
- # _is_pip_rocm_family_leaf anchors its own rocm[0-9]* arm: a pin that merely STARTS
- # with it (rocm-rel-7.0-private) is somebody's mirror. The gfx family is deliberately
- # NOT narrowed this way, since AMD's own indexes are gfx110X-all, gfx120X-all,
- # gfx103X-all, where a suffix is the convention rather than a custom pin.
rocm-rel-*[!0-9.]*) _amd_node_diag_route=false ;;
cpu|rocm-rel-[0-9]*) _amd_node_diag_route=true ;;
*)
@@ -7972,11 +7277,6 @@ case "$_amd_node_diag_leaf" in
fi
;;
esac
-# ... but only when a wheel is actually being installed. TORCH_INDEX_URL is resolved
-# unconditionally above, so --no-torch on a hybrid or CUDA-pinned host read as a CUDA route
-# and silenced all three diagnoses for a run whose bundle opens the very nodes they are
-# about. `auto` is deliberately included: the AMD-evidence gates below are what keep an
-# NVIDIA-only host silent, so routing here fails closed rather than guessing a backend.
if [ "$SKIP_TORCH" = true ]; then
if _run_may_open_a_gpu_node; then
_amd_node_diag_route=true
@@ -7984,21 +7284,10 @@ if [ "$SKIP_TORCH" = true ]; then
_amd_node_diag_route=false
fi
fi
-# ... and an EXPLICIT GPU bundle request opens AMD nodes whatever the wheels do. The route
-# above is derived from the torch index alone, so a CUDA or custom-pinned index asked for
-# the rocm or vulkan bundle read as false, and the SKIP_TORCH override could not catch it
-# because that only runs when no wheel is installed. This only ever turns the route ON: a
-# cpu or cuda request is still settled by the two scope predicates below.
case "$(_requested_llama_backend)" in
rocm|hip|vulkan) _amd_node_diag_route=true ;;
esac
-# Separate branches, not one branch with an inner test, because they need DIFFERENT
-# evidence. The mapping one is gated on the KFD topology, the amdkfd driver's own sysfs, so
-# it must not sit behind _has_amd_rocm_gpu: that probe answers from `amd-smi list`, which
-# reads the driver over sysfs and libdrm and so SUCCEEDS in a container given only
-# --device /dev/dri, where HIP has no /dev/kfd to open (llama_cpp.py's
-# _rocm_hip_is_reachable records the same disagreement). Behind that probe the warning was
-# suppressed on exactly the container shape it was written for.
+# Separate branches: amd-smi succeeds with only /dev/dri mapped, where HIP has no /dev/kfd.
if [ "$_amd_node_diag_route" = true ] && \
_run_may_open_kfd && [ "$OS" != "macos" ] && \
[ ! -e /dev/kfd ] && _amd_silicon_behind_a_missing_kfd; then
@@ -8028,26 +7317,15 @@ fi
if ! _run_may_open_kfd; then
_closed_amd_nodes=$(printf '%s\n' "$_closed_amd_nodes" | grep -vx /dev/kfd || true)
fi
-# The driver is loaded and the nodes exist, so neither a wheel nor a kernel stack
-# repairs this; only group membership does. Nothing else in this installer asks
-# whether the account can OPEN a node it just found (#10466). /dev/kfd alone stops
-# ROCm; a render node stops Vulkan as well, so the two are not claimed together.
+# Only group membership repairs this (#10466). /dev/kfd stops ROCm; a render node also stops Vulkan.
if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
[ -n "$_closed_amd_nodes" ]; then
substep "An AMD GPU is present but this account cannot open its device nodes:" "$C_WARN"
printf '%s\n' "$_closed_amd_nodes" | while IFS= read -r _n; do
substep " $_n"
done
- # Which backends the closed set blocks. The membership sentence is NOT here: when
- # every refused node has an unnamed GID, an ACL, or a mode no group can open,
- # _amd_node_repairs deliberately names no group, and this used to leave "Add yourself
- # to the" hanging above a branch explaining that no membership opens the node.
if printf '%s\n' "$_closed_amd_nodes" | grep -qv '^/dev/kfd$'; then
if _an_amd_render_node_is_open; then
- # The repair still stands -- these nodes are still shut -- but the claim does
- # not: some AMD render node here already opens, so a backend that enumerates
- # every device has a path and it is the card behind THESE nodes that is out of
- # reach. amd_node_permission_hint draws the same distinction on the Python side.
substep " Every backend needs them, ROCm and Vulkan alike, but another AMD"
substep " render node on this host is open, so what they block is the card"
substep " behind them rather than all GPU work."
@@ -8057,9 +7335,6 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
else
substep " ROCm needs it; Vulkan does not."
fi
- # Read from the nodes that were refused, so the advice matches those files.
- # Guarded: `set -e` plus an unguarded substitution would let a missing awk abort
- # the installer from inside the advice it was about to print.
_closed_amd_repairs=$(_amd_node_repairs "$_closed_amd_nodes" || true)
_closed_amd_groups=$(printf '%s\n' "$_closed_amd_repairs" | sed -n 's/^join://p' \
| tr '\n' ',' | sed 's/,*$//')
@@ -8077,22 +7352,9 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
| tr '\n' ',' | sed 's/,*$//')
_closed_amd_external=$(printf '%s\n' "$_closed_amd_repairs" | sed -n 's/^external://p' \
| tr '\n' ',' | sed 's/,*$//')
- # Who the mode tests above answered for. $USER is inherited, so a container that changes
- # its numeric user without resetting it names somebody else, and the usermod below would
- # then modify an account that is not the one holding the device shut.
- #
- # `id -un` FAILS for a uid with no passwd entry, which is the ordinary shape of
- # `docker run --user 1234`, and the inherited USER there commonly still says root. So
- # empty means "no account to name" and the branches below print the container repair
- # instead of a usermod that would succeed against an identity nothing is running as.
- # Status, not stdout: GNU id PRINTS the uid and then exits 1 for an unresolvable one
- # (coreutils id.c print_user falls back to uidtostr), so `|| printf ''` never runs and
- # the substitution captured "1234" -- the numeric form usermod rejects, prescribed on
- # exactly the container hosts the paragraph above is about.
+ # $USER may be stale in containers; `id -un` fails for a uid with no passwd entry, where GNU id
+ # still prints the uid, so use its status, not stdout.
_amd_repair_user=$(id -un 2>/dev/null) || _amd_repair_user=''
- # The documented pair is the fallback for nodes that could not be stat'd at all, where
- # some advice beats none. A node that WAS read and offers no joinable group gets the
- # sentences below instead of a command that would fail.
if [ -z "$_closed_amd_groups" ] && [ -z "$_closed_amd_gids" ] && \
[ -z "$_closed_amd_modes" ] && [ -z "$_closed_amd_acls" ] && \
[ -z "$_closed_amd_owned" ] && [ -z "$_closed_amd_priv" ] && \
@@ -8117,15 +7379,8 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
substep " sudo usermod -a -G $(_shell_quote "$_closed_amd_groups") $(_shell_quote "$_amd_repair_user")"
fi
if [ -n "$_closed_amd_gids" ]; then
- # One flag per GID, as docker/run.sh does and as the Python half already emits:
- # --group-add takes a SINGLE value, so a comma-joined pair is one group name that
- # does not exist, and naming only the first leaves the second node shut.
_closed_amd_gid_adds=$(printf '%s' "$_closed_amd_gids" | tr ',' '\n' \
| sed 's/^/--group-add /' | tr '\n' ' ' | sed 's/ *$//')
- # groupadd alone only gives the numeric owner a NAME: the account is still
- # outside the group and the node is still shut, so both halves are printed -- and
- # one pair PER GID, since one groupadd names one owner and the sentence above
- # already says "create a group for each".
case "$_closed_amd_gids" in
*,*) substep " Some of those nodes belong to GIDs $_closed_amd_gids, which have no" "$C_WARN"
substep " group entry here, so usermod cannot name them: create a group for each" ;;
@@ -8135,23 +7390,14 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
if [ -n "$_amd_repair_user" ]; then
substep " and add yourself to every one of them, then log out and back in:"
for _amd_gid in $(printf '%s' "$_closed_amd_gids" | tr ',' ' '); do
- # Generated, not a <name> placeholder: this is a command to paste, and angle
- # brackets are redirection operators, so `groupadd -g 993 <name>` is a syntax
- # error before groupadd runs. Keyed on the GID, which has no entry by
- # definition here -- which says nothing about the NAME, and some host may
- # already have taken it at a different GID.
+ # Generated name, not a <name> placeholder: angle brackets are redirections.
_amd_gid_name="amdgpu$_amd_gid"
- # Chained, so that collision cannot become a silent wrong repair: printed as
- # two separate lines, a failed groupadd is followed by a usermod that
- # SUCCEEDS against the wrong group and leaves the node exactly as shut,
- # having reported success. && stops there, and the error names the cause.
+ # Chained with && so a failed groupadd cannot be followed by a usermod on the wrong group.
substep " sudo groupadd -g $_amd_gid $_amd_gid_name && \\"
substep " sudo usermod -a -G $_amd_gid_name $(_shell_quote "$_amd_repair_user")"
done
substep " or recreate the container passing $_closed_amd_gid_adds."
else
- # The bare-host half needs an account to add and there is none, so the container
- # half is the whole repair for this shape.
substep " and this uid has no passwd entry either, so neither groupadd nor"
substep " usermod has anything to name: recreate the container passing"
substep " $_closed_amd_gid_adds."
@@ -8176,10 +7422,6 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
substep " however its group bits read: fix the mode, or the udev rule behind it."
fi
if [ -n "$_closed_amd_external" ]; then
- # Worded by the class that APPLIES, not by the owner one: this bucket holds a node
- # this account owns whose owner bits grant rw AND one it neither owns nor shares a
- # group with whose other bits do, and naming the owner for both told the second kind
- # it owns a node it does not. Mirrors the external sentence in amd.py.
substep " $_closed_amd_external is already granted read and write by the" "$C_WARN"
substep " permission bits that apply to this account, so the mode is not what"
substep " is shutting it:"
@@ -8196,12 +7438,7 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
substep " be read from its mode: check the real grant with getfacl before"
substep " changing group membership."
fi
- # The container shape of the missing-node problem: /dev/kfd mapped without
- # /dev/dri leaves the closed KFD node looking like the whole story while ROCr
- # has no render node to open, and no group creates one.
if ! _amd_render_node_present; then
- # The nodes THIS run opens: a Vulkan bundle beside --no-torch never opens /dev/kfd,
- # so naming it hands the container another host device for nothing.
if _run_may_open_kfd; then
_amd_map_devices="--device /dev/kfd --device /dev/dri"
else
@@ -8211,10 +7448,6 @@ if [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
substep " Vulkan both open one, so the device mapping needs fixing too; under"
substep " Docker that is $_amd_map_devices."
fi
-# The same missing render node with nothing closed, which is the ordinary container shape
-# of it: --device /dev/kfd and no --device /dev/dri leaves one openable node, so the list
-# above is empty and this went unsaid. Gated on the KFD topology naming AMD rather than on
-# the glob being empty, since every vendor's render nodes live under it.
elif [ "$_amd_node_diag_route" = true ] && _run_may_open_a_gpu_node && \
[ "$OS" != "macos" ] && \
! _amd_render_node_present && _kfd_topology_has_an_amd_gpu; then
@@ -8232,7 +7465,6 @@ fi
tauri_log "STEP" "Installing PyTorch"
_VENV_PY="$VENV_DIR/bin/python"
-# A piped or standalone install.sh has no sibling requirements tree. Bootstrap only the Unsloth wheel so its canonical Darwin override becomes available before the first with-dependencies resolution, avoiding backtracking mlx-vlm and then repairing it in a later phase. No-torch has no such resolve; repository, local and caller-configured installs already have an override and skip this.
_bootstrap_packaged_mlx_override() {
[ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ] || return 0
[ "$SKIP_TORCH" = false ] || return 0
@@ -8303,7 +7535,8 @@ for _p in ('torch', 'torchvision', 'torchaudio'):
_warn_torch_shadowed "$(printf '%s\n' "$_torch_trio_pins" | sed -n 's/^torch==//p' | head -n 1)"
case "$_torch_trio_pins" in
torch==*)
- # uv resolves an override's relative includes (-r nested.txt) against THAT file's dir, so merge beside the caller's override when they share one writable dir, else mktemp. Globbing is off for both walks below: uv reads the literal name, so an ov[1].txt would otherwise make them iterate a sibling ov1.txt.
+ # uv resolves an override's -r includes relative to that file, so merge beside it. Globbing off:
+ # uv reads literal names.
_ov_glob=on
case $- in *f*) _ov_glob=off ;; esac
set -f
@@ -8325,7 +7558,7 @@ for _p in ('torch', 'torchvision', 'torchaudio'):
_UNSLOTH_TORCH_OVERRIDES=""
if [ "$_ov_dir_ok" = 1 ] && [ -n "$_ov_dir" ] && [ -w "$_ov_dir" ]; then
_UNSLOTH_TORCH_OVERRIDES="$_ov_dir/.unsloth-torch-overrides.$$.txt"
- # 0600, as the mktemp fallback: the merge copies inherited requirements in, which can include an authenticated direct URL. The chmod is not redundant with the umask, as `: >` truncates a recycled-PID file without changing its mode.
+ # 0600: inherited requirements can hold authenticated URLs; `: >` keeps an old file's mode.
if (umask 077; : > "$_UNSLOTH_TORCH_OVERRIDES") 2>/dev/null; then
chmod 600 "$_UNSLOTH_TORCH_OVERRIDES" 2>/dev/null || true
else
@@ -8334,11 +7567,11 @@ for _p in ('torch', 'torchvision', 'torchaudio'):
fi
[ -n "$_UNSLOTH_TORCH_OVERRIDES" ] || _UNSLOTH_TORCH_OVERRIDES=$(mktemp)
printf '%s\n' "$_torch_trio_pins" > "$_UNSLOTH_TORCH_OVERRIDES"
- # --overrides replaces any UV_OVERRIDE env file, so fold its pins in; awk drops the inherited trio. tolower: a caller's "Torch<2.11" would be unsatisfiable to uv.
+ # --overrides replaces UV_OVERRIDE, so fold its pins in. tolower: uv would reject "Torch<2.11".
for _ov_file in ${UV_OVERRIDE:-}; do
[ -f "$_ov_file" ] && awk '!(tolower($0) ~ /^[[:space:]]*torch(vision|audio)?([[:space:]<>=!~;@[]|$)/)' "$_ov_file" >> "$_UNSLOTH_TORCH_OVERRIDES"
done
- # `if`, not `[ ... ] && set +f`: last command of the arm, so under `set -e` a false test would make the whole function exit non-zero.
+ # `if`, not `&&`: a false last test would make the function fail under set -e.
if [ "$_ov_glob" = on ]; then set +f; fi
;;
esac
@@ -8384,14 +7617,11 @@ _relax_unsloth_floors_to_index() {
_relax_unsloth_floors_to_index
if [ "$_MIGRATED" = true ]; then
- # Migrated env: force-reinstall unsloth+unsloth-zoo, keeping torch unless the ROCm repair fires.
_gfx906_bnb_snapshot
substep "upgrading unsloth in migrated environment..."
if [ "$SKIP_TORCH" = true ]; then
- # No-torch: --no-deps throughout (PyPI metadata still hard-deps torch).
- # --no-deps means unsloth's own metadata is never read, so this spec IS the zoo floor
- # for this path. Keep it equal to the unsloth_zoo floor in pyproject.toml
- # (tests/test_installer_zoo_floor_parity.py enforces that).
+ # --no-deps: this spec IS the zoo floor; keep it equal to pyproject.toml
+ # (tests/test_installer_zoo_floor_parity.py).
run_install_cmd_retry "install unsloth (migrated no-torch)" uv pip install --python "$_VENV_PY" --no-deps \
--reinstall-package unsloth --reinstall-package unsloth-zoo \
"$_unsloth_release_install_spec" "$_unsloth_zoo_install_spec"
@@ -8434,15 +7664,12 @@ if [ "$_MIGRATED" = true ]; then
_install_torch_default_index --force-reinstall
elif [ "$_gfx_rocm64_target" = true ] && \
_venv_torch_rocm_below "$_VENV_PY" "$_gfx_rocm64_floor_maj" "$_gfx_rocm64_floor_min"; then
- # A migrated venv keeps its hip torch, but a wheel below this arch's floor has no
- # kernels for it. The SAME floor the reroute used, so an adequate wheel is left alone.
substep "reinstalling torch from $_torch_index_leaf (the migrated wheels have no kernels for this GPU)..."
_install_torch_default_index --force-reinstall
elif [ "${_amd_arch_index_routed:-false}" = true ] && {
_venv_torch_rocm_below "$_VENV_PY" 7 13 ||
{ _vfam=$(_venv_torch_amd_family "$_VENV_PY")
[ -n "$_vfam" ] && [ "$_vfam" != "${_amd_arch_index_family:-}" ]; }; }; then
- # Below 7.13 or another family's wheel lacks kernels; an unreadable family is left alone.
substep "reinstalling torch from the AMD per-arch index (the migrated wheels do not match it)..."
_install_torch_default_index --force-reinstall
fi
@@ -8457,7 +7684,6 @@ if [ "$_MIGRATED" = true ]; then
_install_torch_default_index --force-reinstall
fi
elif [ -n "$TORCH_INDEX_URL" ]; then
- # Fresh: Step 1 - install torch from explicit index (skip when --no-torch or Intel Mac)
if [ "$SKIP_TORCH" = true ]; then
substep "skipping PyTorch (--no-torch or Intel Mac x86_64)." "$C_WARN"
elif [ "$_amd_gpu_radeon" = true ]; then
@@ -8467,7 +7693,6 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
if _radeon_fetch_listing "$_radeon_url" 2>/dev/null; then
_radeon_listing_ok=true
else
- # Try shorter X.Y path (AMD publishes both X.Y.Z and X.Y dirs)
_radeon_url_short=$(printf '%s\n' "$_radeon_url" \
| sed 's|rocm-rel-\([0-9]*\)\.\([0-9]*\)\.[0-9]*/|rocm-rel-\1.\2/|')
if [ "$_radeon_url_short" != "$_radeon_url" ] && \
@@ -8477,13 +7702,11 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
fi
if [ "$_radeon_listing_ok" = true ]; then
- # Independent highest picks can mismatch; downpair to the highest common minor.
_torch_whl=$(_pick_radeon_wheel "torch" 2>/dev/null) || _torch_whl=""
_tv_whl=$(_pick_radeon_wheel "torchvision" 2>/dev/null) || _tv_whl=""
_ta_whl=$(_pick_radeon_wheel "torchaudio" 2>/dev/null) || _ta_whl=""
_tri_whl=$(_pick_radeon_wheel "triton" 2>/dev/null) || _tri_whl=""
- # Verify the X.Y pairing (vision = torch.minor + 15); URL-decode %2B first.
_extract_version() {
_whl=$1
_pkg=$2
@@ -8498,7 +7721,6 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
_ta_ver=$(_extract_version "$_ta_whl" "torchaudio")
_radeon_versions_match=false
- # Kept release wins here too: exact patch, else newest of its minor, paired.
if [ -n "$_PREV_TORCH_PIN" ]; then
_prev_kept_base="${_PREV_TORCH_PIN#torch==}"
_prev_kept_minor="${_prev_kept_base#*.}"
@@ -8533,7 +7755,6 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
_tv_minor=${_tv_ver#*.}
_tv_equiv_minor=$((_tv_minor - 15))
- # Determine initial target minor (lowest common denominator)
_target_minor=$_torch_minor
[ "$_tv_equiv_minor" -lt "$_target_minor" ] && _target_minor=$_tv_equiv_minor
[ "$_ta_minor" -lt "$_target_minor" ] && _target_minor=$_ta_minor
@@ -8548,12 +7769,10 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
_curr_ta=$(_pick_radeon_wheel "torchaudio" "2.${_target_minor}." 2>/dev/null) || _curr_ta=""
if [ -n "$_curr_torch" ] && [ -n "$_curr_tv" ] && [ -n "$_curr_ta" ]; then
- # Extract versions from the wheels found in this iteration
_c_torch_ver=$(_extract_version "$_curr_torch" "torch")
_c_tv_ver=$(_extract_version "$_curr_tv" "torchvision")
_c_ta_ver=$(_extract_version "$_curr_ta" "torchaudio")
- # Parse Major.Minor for validation
_c_torch_major=${_c_torch_ver%%.*}
_c_torch_minor=${_c_torch_ver#*.}
_c_ta_major=${_c_ta_ver%%.*}
@@ -8594,7 +7813,6 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
_install_torch_default_index
else
substep "installing PyTorch from Radeon repo (${_RADEON_BASE_URL})..."
- # Explicit wheel URLs install the trio together; --find-links exposes the listing.
if [ -n "$_tri_whl" ]; then
run_install_cmd_retry "install triton + PyTorch" uv pip install --python "$_VENV_PY" \
--find-links "$_RADEON_BASE_URL" \
@@ -8630,7 +7848,6 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
fi
fi
_gfx906_bnb_snapshot
- # Fresh: Step 2 - install unsloth, preserving the torch Step 1 installed
tauri_log "STEP" "Installing Unsloth"
substep "installing unsloth (this may take a few minutes)..."
_build_unsloth_torch_overrides
@@ -8710,7 +7927,6 @@ else
fi
fi
-# Same probe as install.ps1: version() answers from whichever record the finder yields first, so a duplicate would be reported here as an ordinary version.
_installed_package_version_exit=0
if _installed_package_version=$("$_VENV_PY" -I -c '
import sys
@@ -8752,12 +7968,10 @@ fi
# PEP 440 ignores the +cpu/+cuXXX local label, so uv keeps a stale torch+cpu against a GPU index.
if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; then
_expected_torch_tag=$(_expected_torch_flavor_tag "$TORCH_INDEX_URL")
- # Only act when a GPU build is expected (cuXXX / rocm); cpu and unknown skip.
if [ -n "$_expected_torch_tag" ] && [ "$_expected_torch_tag" != "cpu" ]; then
_installed_torch_ver=$(_installed_torch_version_for_tag "$_expected_torch_tag")
_installed_torch_tag=""
[ -n "$_installed_torch_ver" ] && _installed_torch_tag=$(_torch_flavor_tag "$_installed_torch_ver")
- # Repair only when flavor is wrong AND the index is --default-index reinstallable.
if [ -n "$_installed_torch_tag" ] && [ "$_installed_torch_tag" != "$_expected_torch_tag" ] \
&& [ "$(_torch_index_repairable "$TORCH_INDEX_URL")" = "yes" ]; then
substep "PyTorch flavor mismatch (installed $_installed_torch_tag, need $_expected_torch_tag) -- reinstalling correct build..."
@@ -8767,7 +7981,6 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; then
_installed_torch_tag=""
[ -n "$_installed_torch_ver" ] && _installed_torch_tag=$(_torch_flavor_tag "$_installed_torch_ver")
fi
- # Safety net (incl. AMD/WSL): GPU build expected but still CPU -> warn loudly.
if [ "$_installed_torch_tag" = "cpu" ]; then
substep "[WARN] PyTorch is CPU-only but a $_expected_torch_tag GPU build was expected for this machine." "$C_WARN"
substep "[WARN] Training and GPU inference will run on CPU until this is fixed." "$C_WARN"
@@ -8777,7 +7990,6 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; then
fi
fi
-# A wrong CUDA family fails only at first kernel launch; never cuInit here (minutes on a congested driver).
if [ "$SKIP_TORCH" = false ] && ! _cvd_hides_nvidia; then
case "${_expected_torch_tag:-}" in
cu[0-9]*)
@@ -8903,7 +8115,7 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${_TORCH_EXTRA:-}" ]; then
fi
fi
-# manylinux 0.50.0 is the first with libbitsandbytes_xpu2025.so / _xpu2026.so, and nothing else here touches bitsandbytes on this index (both ROCm passes are gated on that family), so a migrated environment would keep a pre-XPU build and lose 4-bit QLoRA. Out here rather than in the install branches above: those are mutually exclusive, so a copy in the fresh arm never runs for a migrated env. --no-deps, since torch and numpy are already in. Best effort, like the Windows pass.
+# 0.50.0 is the first bnb with XPU libs; outside the install branches so migrated envs get it too.
# ── Intel XPU: bitsandbytes with XPU kernels ──
if [ "$SKIP_TORCH" = false ] && [ "$(_torch_index_url_leaf "${TORCH_INDEX_URL:-}")" = "xpu" ]; then
substep "installing bitsandbytes with Intel XPU kernels..."
@@ -8913,14 +8125,13 @@ if [ "$SKIP_TORCH" = false ] && [ "$(_torch_index_url_leaf "${TORCH_INDEX_URL:-}
fi
# ── CI only: overlay a source checkout over the package just installed ──
-# Not a consumer knob: no flag, absent from --help, ignored unless UNSLOTH_CI_SOURCE_OVERLAY names a directory holding a pyproject.toml. The clean-machine legs run THIS script from a branch but install unsloth from PyPI, so everything Python-side would be the released wheel's and a branch could not be validated. An editable overlay re-points `import studio` at the working tree, so the importlib.resources lookup below finds this ref's setup.sh. NOT --local: that also installs `unsloth-zoo @ git+https://...`, which needs the git these legs remove; editable + --no-deps resolves and clones nothing.
+# Not a consumer knob. Editable + --no-deps so CI legs validate this ref without git.
if [ -n "${UNSLOTH_CI_SOURCE_OVERLAY:-}" ]; then
if [ ! -f "$UNSLOTH_CI_SOURCE_OVERLAY/pyproject.toml" ]; then
echo "[ERROR] UNSLOTH_CI_SOURCE_OVERLAY is set to '$UNSLOTH_CI_SOURCE_OVERLAY' but there is no pyproject.toml there." >&2
exit 1
fi
substep "CI: overlaying source checkout (editable, no deps): $UNSLOTH_CI_SOURCE_OVERLAY"
- # Retry: the editable build fetches its backend from PyPI, same network risk.
run_install_cmd_retry "overlay CI source checkout" uv pip install --python "$_VENV_PY" \
--no-deps -e "$UNSLOTH_CI_SOURCE_OVERLAY"
fi
@@ -8933,16 +8144,13 @@ if [ "$STUDIO_LOCAL_INSTALL" = true ] && [ -f "$_REPO_ROOT/studio/setup.sh" ]; t
fi
if [ -z "$SETUP_SH" ] || [ ! -f "$SETUP_SH" ]; then
- # -I: a bare -c puts the caller's cwd first on sys.path, so launching from an unsloth
- # checkout resolved `studio` to the checkout and ran ITS setup.sh, which installed the
- # checkout's requirement pins while the wheel's verify_install read the wheel's.
+ # -I: otherwise the caller's cwd shadows `studio` with a checkout's setup.sh.
SETUP_SH=$("$VENV_DIR/bin/python" -I -c "
import importlib.resources
print(importlib.resources.files('studio') / 'setup.sh')
" 2>/dev/null || echo "")
fi
-# Fallback: search site-packages
if [ -z "$SETUP_SH" ] || [ ! -f "$SETUP_SH" ]; then
SETUP_SH=$(find "$VENV_DIR" -path "*/studio/setup.sh" -print -quit 2>/dev/null || echo "")
fi
@@ -8953,7 +8161,6 @@ if [ -z "$SETUP_SH" ] || [ ! -f "$SETUP_SH" ]; then
exit 1
fi
-# Ensure the venv's Python is on PATH so setup.sh can find it.
VENV_ABS_BIN="$(cd "$VENV_DIR/bin" && pwd)"
if [ -n "$VENV_ABS_BIN" ]; then
export PATH="$VENV_ABS_BIN:$PATH"
@@ -8969,7 +8176,6 @@ fi
step "setup" "running unsloth studio update..."
_SKIP_BASE=1
_SETUP_EXIT=0
-# Tauri desktop app bundles its own frontend — skip Node/npm/frontend build
_SKIP_FRONTEND=0
if [ "$TAURI_MODE" = true ]; then
_SKIP_FRONTEND=1
@@ -9014,23 +8220,20 @@ else
fi
if [ "$_SETUP_EXIT" -eq 0 ]; then
- # First: until this runs, anything that fails below reaches the exit trap, which would restore the previous environment over the one just installed.
+ # First: until this runs, a failure below would restore the old environment over the new one.
_commit_studio_venv_replacement
tauri_clear_install_error "studio setup completed"
fi
# ── Make 'unsloth' available via $_LOCAL_BIN (resolved earlier) ──
mkdir -p "$_LOCAL_BIN"
-# Refuse to delete a real directory at the shim path (could destroy user data).
_shim_path="$_LOCAL_BIN/unsloth"
if [ -d "$_shim_path" ] && [ ! -L "$_shim_path" ]; then
echo "ERROR: $_shim_path is a directory; refusing to delete it." >&2
echo " Move or remove it manually, then re-run the installer." >&2
exit 1
fi
-# -sfn is atomic and -n prevents descent into a symlink-to-directory at the shim path (the directory guard above already rejects a real directory).
if ! ln -sfn "$VENV_DIR/bin/unsloth" "$_shim_path" 2>/dev/null; then
- # A reinstall rebuilds the environment at the same path, so an entry already resolving to this executable is the shim we were about to write: not a failed install.
if [ "$_shim_path" -ef "$VENV_DIR/bin/unsloth" ] 2>/dev/null; then
substep "kept the existing shim at $_shim_path ($_LOCAL_BIN is not writable)"
else
@@ -9040,7 +8243,6 @@ if ! ln -sfn "$VENV_DIR/bin/unsloth" "$_shim_path" 2>/dev/null; then
fi
fi
-# Is $2 one of the colon-separated entries of $1? Field splitting also globs, so pathname expansion is off for the walk and restored afterwards: a directory holding *, ? or [ would otherwise match an unrelated entry and the persistence would be skipped.
_path_has_dir() {
_phd_glob=on
case $- in *f*) _phd_glob=off ;; esac
@@ -9056,15 +8258,8 @@ _path_has_dir() {
return "$_phd_found"
}
-# fish reads none of the POSIX rc files, so an `export` line is a no-op for a fish user: the next session resolves neither uv nor the shim. conf.d is fish's own drop-in directory and fish_add_path is idempotent by design. ~/.config, not XDG_CONFIG_HOME, because that is where astral's installer put its own fish file.
-# Is a conda environment ACTIVE in this shell? Both variables, matching install.ps1: a hook
-# exporting only CONDA_DEFAULT_ENV still leaves the caller inside conda's PATH ordering.
-# Replace a line THIS installer wrote with the form the current run needs, in place. A
-# previous run outside conda persisted the PREPEND spelling, and the presence checks below
-# accept any spelling, so without this the prepend would survive for ever (#5871). Only an
-# exact whole-line match on what we write is touched, and the content is copied back into the
-# ORIGINAL file so a symlinked rc keeps its link, mode and owner. A file that cannot be
-# rewritten is a warning, never a failure.
+# Rewrite in place only lines this installer wrote (prepend vs append under conda, #5871),
+# copying back into the original so a symlinked rc keeps link, mode and owner.
_unsloth_repoint_rc_line() {
[ -f "$1" ] || return 1
# OURS, not merely matching: a hand-written `export PATH="$HOME/.local/bin:$PATH"` is a
@@ -9119,25 +8314,12 @@ _persist_fish_path_dir() {
_pfp_dir_conf="$HOME/.config/fish/conf.d"
mkdir -p "$_pfp_dir_conf" 2>/dev/null || return 0
_pfp_file="$_pfp_dir_conf/unsloth.fish"
- # Single-quoted: an unquoted path with a space is two arguments to fish_add_path and neither exists. Inside fish single quotes only \\ and \' carry meaning.
_pfp_quoted=$(printf '%s' "$_pfp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")
- # fish_add_path PREPENDS, and that ordering outlives the conda activation (#5871), so
- # the conda arm appends. All three flags are load-bearing:
- # -a alone appends to $fish_user_paths, which fish prepends to PATH, so -P is what
- # makes it an append to PATH at all
- # -P edits $PATH for the session, which is right in conf.d: it is read alphabetically,
- # so conda.fish has already run
- # -m moves an entry already in PATH, which a bare `fish_add_path` from an older
- # install put there via the universal $fish_user_paths; without it the append is a
- # no-op and the stale prepend survives
- # https://fishshell.com/docs/current/cmds/fish_add_path.html
+ # Under conda append, since fish_add_path prepends (#5871). -a -P -m are all required:
+ # -P appends to PATH, -m moves an existing entry. See fishshell.com fish_add_path docs.
_pfp_line="fish_add_path '$_pfp_quoted'"
if _unsloth_conda_env_active; then
_pfp_line="fish_add_path -a -P -m '$_pfp_quoted'"
- # Every earlier spelling is a prepend as far as PATH is concerned -- the bare -a
- # appends to $fish_user_paths, which fish itself puts in front of PATH -- so a line
- # left by any previous run is repointed rather than accepted by the check below, and
- # that includes the -a -P line without -m, which cannot move an entry already in PATH.
for _pfp_stale in "fish_add_path '$_pfp_quoted'" "fish_add_path -a '$_pfp_quoted'" \
"fish_add_path -a -P '$_pfp_quoted'"; do
if _unsloth_repoint_rc_line "$_pfp_file" "$_pfp_stale" "$_pfp_line"; then
@@ -9146,12 +8328,9 @@ _persist_fish_path_dir() {
done
fi
[ "$_pfp_mode" = "repoint" ] && return 0
- # The exact line we would write, not any occurrence of the directory: /opt/uv-old must
- # not pass for /opt/uv. EVERY spelling counts as present, or a run outside conda adds a
- # second line for a directory a run inside it already registered.
if ! grep -v '^[[:space:]]*#' "$_pfp_file" 2>/dev/null \
| grep -qxF -e "fish_add_path '$_pfp_quoted'" -e "fish_add_path -a '$_pfp_quoted'" -e "fish_add_path -a -P '$_pfp_quoted'" -e "fish_add_path -a -P -m '$_pfp_quoted'"; then
- # Same single-redirect, warning-not-failure contract as the POSIX arm. 2>/dev/null comes FIRST: redirections apply left to right, so the other order prints the shell's own "Permission denied" before the redirect can silence it.
+ # Single redirect; failure only warns. 2>/dev/null first so the shell's own error is silenced.
if {
echo "# Added by Unsloth installer"
echo "$_pfp_line"
@@ -9166,19 +8345,13 @@ _persist_fish_path_dir() {
fi
}
-# A line that SETS PATH, as opposed to one that merely names the directory. The name boundary keeps PYTHONPATH and friends out; the three helpers are the common non-assignment spellings.
_PATH_LINE_RE='(^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper)'
-# Put a directory on the PATH of the NEXT shell, not just this process. $1 the directory, $2 the rc-file literal (~/.local/bin keeps $HOME unexpanded, as it always has), $3 how to name it in the line we print, $4 the grep that says it is already there, $5 an explicit profile file or empty to pick one the way this installer always has.
-# $6 "repoint" asks for the repositioning pass ALONE: fix a line a previous run wrote and add
-# nothing. The callers below are guarded on whether the directory is already on the login PATH,
-# and it IS on it precisely because the previous run wrote the line, so the ordinary call is
-# skipped in exactly the case the repointing exists for.
+# Persist $1 on the next shell's PATH. $6 "repoint" only fixes a line a previous run wrote.
_persist_login_path_dir() {
_plp_dir="$1"; _plp_literal="$2"; _plp_label="$3"; _plp_pattern="$4"; _plp_file="${5:-}"
_plp_mode="${6:-}"
[ -n "${HOME:-}" ] || return 0
- # fish reads none of the POSIX rc files, so an `export` line there is a no-op for a fish user. conf.d is fish's own drop-in directory and fish_add_path is idempotent by design.
if [ -z "$_plp_file" ] && [ "$(basename "${SHELL:-}")" = "fish" ]; then
_persist_fish_path_dir "$_plp_dir" "$_plp_label" "$_plp_mode"
return 0
@@ -9193,7 +8366,7 @@ _persist_login_path_dir() {
elif [ -f "$HOME/.profile" ]; then
_SHELL_PROFILE="$HOME/.profile"
elif [ -w "$HOME" ]; then
- # A fresh account can have no rc file at all: astral's installer used to create one, the pinned path does not. The append creates it, and every POSIX login shell reads ~/.profile.
+ # A fresh account can have no rc file at all; every POSIX login shell reads ~/.profile.
_SHELL_PROFILE="$HOME/.profile"
fi
[ -n "$_SHELL_PROFILE" ] || return 0
@@ -9205,9 +8378,6 @@ _persist_login_path_dir() {
if _unsloth_conda_env_active; then
_plp_prepend="$_plp_line"
_plp_line="export PATH=\"\$PATH:$_plp_literal\""
- # A prepend a previous run left behind is repositioned rather than accepted: the check
- # below treats it as present and would add nothing, leaving our directory ahead of the
- # active conda environment in every later shell.
if grep -qxF "$_plp_prepend" "$_SHELL_PROFILE" 2>/dev/null; then
if _unsloth_repoint_rc_line "$_SHELL_PROFILE" "$_plp_prepend" "$_plp_line"; then
step "path" "moved $_plp_label after the active conda environment in $_SHELL_PROFILE"
@@ -9219,13 +8389,11 @@ _persist_login_path_dir() {
fi
fi
fi
- # Repointing was the whole job for this call: adding a line the caller did not ask for
- # would put an entry in the rc file of someone whose PATH comes from somewhere else.
[ "$_plp_mode" = "repoint" ] && return 0
- # Comments stripped first, then only lines that actually set PATH: a commented-out old export is not an active entry, and neither is `UV_CACHE=/opt/uv` or `PYTHONPATH=/opt/uv`. The name boundary is what keeps PYTHONPATH out. Taking any of them for a PATH entry leaves the next shell with no uv at all.
if ! grep -v '^[[:space:]]*#' "$_SHELL_PROFILE" 2>/dev/null \
| grep -E "$_PATH_LINE_RE" | grep -qE "$_plp_pattern"; then
- # One redirect, not three: a write dying midway would leave a dangling "# Added by Unsloth installer" with no export under it. A failure is a WARNING carrying the manual line, never a failed install: set -e would abort after the venv, llama.cpp and the shim are in place, and a read-only rc (NixOS, home-manager, chezmoi) is a supported setup. 2>/dev/null first, as in the fish arm.
+ # One redirect so a dying write cannot leave a dangling marker. Failure only warns: read-only rc
+ # files (NixOS, home-manager) are supported.
if {
echo ''
echo '# Added by Unsloth installer'
@@ -9241,10 +8409,6 @@ _persist_login_path_dir() {
fi
}
-# Before the guard below, because that guard is satisfied by the very line that needs moving:
-# a previous run wrote the prepend, the shell that launched this installer evaluated it, and
-# the directory is therefore already on the login PATH. Repointing only, so a machine whose
-# PATH comes from somewhere else does not gain an rc line it never had.
if _unsloth_conda_env_active && [ "$_STUDIO_HOME_REDIRECT" != "env" ]; then
_persist_login_path_dir "$_LOCAL_BIN" '$HOME/.local/bin' "~/.local/bin" '\.local/bin' "" repoint
fi
@@ -9259,24 +8423,13 @@ if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_LOCAL_BIN"; then # not on a new sh
fi
fi
-# UV_INSTALL_DIR, UV_UNMANAGED_INSTALL, XDG_BIN_HOME and XDG_DATA_HOME all outrank ~/.local/bin, and astral's installer wrote a PATH line for whichever it picked, so replacing that installer means persisting its destination too. Both of astral's opt-outs are honoured. Not gated on the destination differing from ~/.local/bin: that IS the default, so gating there left every ordinary machine with the single-file write.
+# Persist uv's destination too, as astral's installer did; honour both of its opt-outs.
if [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] \
&& [ -z "${UV_NO_MODIFY_PATH:-}" ] && [ -z "${UV_UNMANAGED_INSTALL:-}" ] \
&& [ "$_STUDIO_HOME_REDIRECT" != "env" ]; then
- # Same repointing pass as the shim block, and ahead of the same guard for the same
- # reason: the directory is on the login PATH because the previous run's prepend put it
- # there. Computed here because the guard below owns the escaping.
if _unsloth_conda_env_active; then
_uv_repoint_literal=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[\\"$`]/\\&/g')
- # And the $HOME-relative spelling, because that is what the shim block above writes:
- # the default uv destination IS ~/.local/bin, so a repoint built only from the
- # expanded path could never match `export PATH="$HOME/.local/bin:$PATH"` and the
- # line it was meant to move stayed in front of conda. The shim's own repoint pass
- # reaches one profile, whichever is selected now, so a prepend a previous run left
- # in .profile outlives a user who since acquired a .bashrc or changed shells; this
- # loop already visits every startup file astral's installer wired, so it is where
- # both spellings belong. $HOME is left unexpanded on purpose and only the rest of
- # the path is escaped.
+ # Also match the $HOME-relative spelling the shim block writes, across every astral startup file.
_uv_repoint_home_literal=""
case "$_UNSLOTH_UV_BIN_DIR" in
"$HOME"/*)
@@ -9296,21 +8449,16 @@ if [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] \
_persist_fish_path_dir "$_UNSLOTH_UV_BIN_DIR" "" repoint
fi
if ! _path_has_dir "$_UNSLOTH_LOGIN_PATH" "$_UNSLOTH_UV_BIN_DIR"; then
- # The rc line is double-quoted, so a path holding $, ` or " would be expanded or terminated by the shell that reads it. The ~/.local/bin literal is exempt: its $HOME is meant to stay unexpanded.
_uv_rc_literal=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[\\"$`]/\\&/g')
- # Anchored on both sides, so /opt/uv is not satisfied by /opt/uv-old and the match has to be a whole PATH entry rather than any occurrence of the text.
_uv_grep_esc=$(printf '%s' "$_UNSLOTH_UV_BIN_DIR" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')
- # And the $HOME-relative spelling as well, because the shim block above writes `export PATH="$HOME/.local/bin:$PATH"` unexpanded. Without this the default install would add a second line for the same directory in the same file.
case "$_UNSLOTH_UV_BIN_DIR" in
"$HOME"/*)
_uv_grep_esc="$_uv_grep_esc|\\\$HOME$(printf '%s' "${_UNSLOTH_UV_BIN_DIR#$HOME}" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')"
;;
esac
_uv_pattern="(^|[^[:alnum:]_.~/-])($_uv_grep_esc)([^[:alnum:]_.~/-]|\$)"
- # Every startup file astral's installer wired, because it is the installer we replaced. Writing only the file for the shell that happens to be running leaves a bash user whose .bash_profile does not source .bashrc, or anyone who later switches shells, without uv.
for _uv_prof in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \
"$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do
- # ~/.profile is created when absent, as astral does; the rest are only touched when the user already has them.
if [ "$_uv_prof" = "$HOME/.profile" ] || [ -f "$_uv_prof" ]; then
_persist_login_path_dir "$_UNSLOTH_UV_BIN_DIR" "$_uv_rc_literal" \
"$_UNSLOTH_UV_BIN_DIR" "$_uv_pattern" "$_uv_prof"
@@ -9321,7 +8469,6 @@ if [ -n "${_UNSLOTH_UV_BIN_DIR:-}" ] \
fi
# end of the PATH persistence block
-# Non-Tauri installs keep shortcuts even if setup reports failure.
if [ "$TAURI_MODE" != true ]; then
create_studio_shortcuts "$VENV_ABS_BIN/unsloth" "$OS"
fi
@@ -9329,8 +8476,7 @@ fi
# If setup.sh failed, report and exit now.
if [ "$_SETUP_EXIT" -ne 0 ]; then
echo ""
- # A full disk surfaces here as nothing but an exit code, with the one "No space left on device" line buried in setup's output (#11313). Ask the filesystem directly and name it. Below 64 MiB nothing useful can be unpacked, so it is the cause rather than a coincidence.
- # Folded into the ERROR_DEFAULT message as well, not only stderr: under --tauri the desktop app reads that message, so a diagnosis printed beside it is one the UI never shows. One line, because a marker is one line.
+ # Below 64 MiB the full disk is the cause. Folded into ERROR_DEFAULT: --tauri shows only that.
_set_disk_full_suffix
if [ "$TAURI_MODE" = true ]; then
tauri_log "ERROR_DEFAULT" "studio setup failed (exit code $_SETUP_EXIT)$_DISK_FULL_SUFFIX"
@@ -9338,11 +8484,9 @@ if [ "$_SETUP_EXIT" -ne 0 ]; then
step "error" "studio setup failed (exit code $_SETUP_EXIT)" "$C_ERR"
fi
if [ -n "$_DISK_FULL_SUFFIX" ]; then
- # `|| true` for the same reason the exit trap guards its copy: a closed --tauri stdout or a redirected stderr must not turn a diagnostic into the thing that decides the exit status.
echo " $STUDIO_HOME has only $_DISK_FULL_MB MB free -- the disk is full, which is very likely the cause." >&2 || true
echo " $_DISK_FULL_REMEDY" >&2 || true
fi
- # Reported here, so the exit trap does not say it twice.
_DISK_FULL_REPORTED=true
echo ""
exit "$_SETUP_EXIT"
@@ -9354,11 +8498,9 @@ if [ "$TAURI_MODE" = true ]; then
exit 0
fi
-# Warn if another 'unsloth' wins on PATH; canonicalize via python (BSD readlink lacks -f).
_installed_bin="$VENV_DIR/bin/unsloth"
_path_unsloth=$(command -v unsloth 2>/dev/null || true)
if [ -n "$_path_unsloth" ] && [ -x "$VENV_DIR/bin/python" ]; then
- # If either side fails to resolve, skip the check rather than compare raw paths.
_canon() {
"$VENV_DIR/bin/python" -c \
'import os, sys; print(os.path.realpath(sys.argv[1]))' \
@@ -9392,7 +8534,6 @@ if [ "$_INSTALL_SYSTEMD" = true ]; then
fi
if [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ]; then
echo ""
- # No readable answer (closed/EOF tty) defaults to no; Enter is still yes. Prompt only when something can answer: `test -r` passes on the unopenable /dev/tty found in containers, leaving a dangling question in the log.
if _can_read_tty; then
printf " Start Unsloth Studio now? [Y/n] "
read -r _reply </dev/tty || _reply="n"
@@ -9404,9 +8545,9 @@ if [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ]; then
step "launch" "starting Unsloth Studio..."
_prepare_studio_uv_cache_for_launch
- # Detach stdin from the piped web install's pipe: as a foreground server the studio would otherwise drain the rest of this piped script, leaving the shell to die parsing the now-truncated tail (`unexpected fi`). trap '' INT waits for studio's shutdown instead of racing the prompt, and the subshell resets INT so the child still gets Ctrl+C.
+ # Detach stdin so the server cannot drain the rest of a piped script. trap '' INT waits for
+ # studio's shutdown; the subshell resets INT so the child still gets Ctrl+C.
trap '' INT
- # `|| ...`: capture the exit code without set -e aborting first.
_LAUNCH_EXIT=0
(trap - INT; exec "$VENV_DIR/bin/unsloth" studio -p 8888 </dev/null) || _LAUNCH_EXIT=$?
if [ "$_LAUNCH_EXIT" -ne 0 ] && [ "$_MIGRATED" = true ]; then
@@ -9431,11 +8572,9 @@ if [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ]; then
esac
else
step "launch" "manual commands:"
- # Single-quote-escape so paths with spaces / apostrophes copy-paste cleanly.
_li_shim_q="'$(printf '%s' "${_LOCAL_BIN}/unsloth" | sed "s/'/'\\\\''/g")'"
_li_act_q="'$(printf '%s' "${VENV_DIR}/bin/activate" | sed "s/'/'\\\\''/g")'"
if [ "$_STUDIO_HOME_REDIRECT" = "env" ]; then
- # Env-mode skips the rc PATH append, so print the absolute shim path.
substep "$_li_shim_q studio -p 8888"
substep "or activate env first:"
substep "source $_li_act_q"
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index bded1093b52..19371305588 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -11,17 +11,13 @@
function Uninstall-UnslothStudio {
$ErrorActionPreference = "Continue"
- # Reset at entry: a piped web run defines this function in the caller's session, so a
- # second run in the same window would otherwise inherit the first run's flags.
+ # Reset at entry: a piped run defines this function in the caller's session, so a rerun
+ # would otherwise inherit the previous run's flags.
$script:RemoveFailed = $false
$script:StudioDbRemoved = $false
- # The default root was REFUSED and still holds studio.db. Its own flag, not RemoveFailed:
- # nothing failed, so "remove those paths by hand" is the wrong thing to say about it.
+ # Separate from RemoveFailed: nothing failed, the default root was refused.
$script:StudioDbKept = $false
- # ONE budget for the run: what _RemovePath waits out is wall clock and shared, so whatever
- # the first blocked path waits, the next does not. Without it an undeletable root costs the
- # full escalation at each of the 18 call sites. Classifying the error instead does not work:
- # a delete-pending file and an antivirus hold both report access denied.
+ # One shared wall-clock wait budget for the whole run, not per call site.
$script:RemoveWaitBudgetMs = 20000
function _Usage {
@@ -58,8 +54,7 @@ Environment:
'@
}
- # Reject unknown arguments before destructive work. throw, not exit, so an embedded run reports
- # failure without killing the caller's PowerShell session.
+ # throw, not exit, so an embedded run does not kill the caller's session.
foreach ($arg in $args) {
if ($arg -in @('-h', '-help', '--help', '-?', '/?')) { _Usage; return }
Write-Host "uninstall.ps1: unrecognized argument: $arg" -ForegroundColor Red
@@ -70,18 +65,14 @@ Environment:
function _Step { param([string]$Msg) Write-Host $Msg }
function _Substep { param([string]$Msg, [string]$Color = "Gray") Write-Host " $Msg" -ForegroundColor $Color }
- # Remove a file/dir/symlink if present. Idempotent; retries since a just-killed
- # process can briefly hold a handle (Windows refuses the delete until released).
+ # Retries because a just-killed process can briefly hold a handle.
function _RemovePath {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
if (-not (Test-Path -LiteralPath $Path)) { return }
- # Escalating: torch inductor holds unattributable DATA handles under
- # TORCHINDUCTOR_CACHE_DIR for seconds after the server stops.
+ # torch inductor holds cache handles for seconds after the server stops.
$delays = @(250, 500, 1000, 2000, 4000, 4000, 4000, 4000)
- # 2100ms per path is free, exactly the flat 700ms x3 this replaced, so no path is retried
- # less than before: a lock only this path hits is not the shared wait. $false means both
- # are spent, so stop rather than retry with no pause in between.
+ # Each path gets 2100ms free before drawing on the shared budget.
$freeLeft = 2100
function _Wait {
param([int]$Ms, [ref]$FreeLeft)
@@ -105,16 +96,14 @@ Environment:
try {
Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop
} catch {
- # Read before $wait runs, so nothing can shadow the error record.
+ # Read before _Wait runs, so nothing can shadow the error record.
$failure = $_.Exception.Message
if (-not $lastTry -and (_Wait $delays[$attempt] ([ref]$freeLeft))) { continue }
_Substep "could not remove: $Path ($failure)" "Yellow"
- # The closing summary must not promise the data is gone.
$script:RemoveFailed = $true
return
}
- # Remove-Item -Recurse can report success yet leave a transiently-locked child (e.g.
- # unsloth.ico in Explorer's icon cache); verify + retry so "removed" is never a lie.
+ # Remove-Item -Recurse can report success yet leave a locked child, so verify.
if (-not (Test-Path -LiteralPath $Path)) {
_Substep "removed: $Path" "Green"
return
@@ -126,11 +115,7 @@ Environment:
}
}
- # rmdir, as uninstall.sh uses for the same two paths: empty or not at all, never recursed
- # into. Not "list it, then _RemovePath": -ErrorAction SilentlyContinue makes an enumeration
- # failure look like an empty directory, so a master root whose ACL denies listing was deleted
- # recursively with the user's files in it, and a separate check and delete let a file
- # arriving in between be taken by the -Recurse. Directory.Delete($path, $false) is one call.
+ # One Directory.Delete($path, $false) call: listing first can mistake an unreadable dir for empty.
function _RemoveDirIfEmpty {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
@@ -139,7 +124,6 @@ Environment:
[System.IO.Directory]::Delete($Path, $false)
_Substep "removed: $Path" "Green"
} catch {
- # Non-empty, unreadable or held open. All three mean "not ours to take".
_Substep "keeping non-empty directory: $Path" "Yellow"
}
}
@@ -149,16 +133,12 @@ Environment:
# a user-chosen master root is theirs. uninstall.sh applies the same shape.
$script:StaleLockPattern = '^\.(llama\.cpp|node|whisper\.cpp|audio\.cpp|sd\.cpp)\.install\.lock\.stale\.[0-9]+$'
- # An install lock, and only an install lock. prebuilt_core.install_lock creates these with
- # O_CREAT | O_EXCL, so a lock is always a regular file, while _RemovePath deletes recursively
- # and in a user-chosen master root would take a whole tree carrying one of these fixed names
- # with none of the owner-marker proof its neighbours require. Same rule as uninstall.sh.
+ # Install locks are always regular files (O_CREAT | O_EXCL); never delete a tree by that name.
function _RemoveLockFile {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
if (-not (Test-Path -LiteralPath $Path)) { return }
- # A reparse point at a lock name is not a lock either, and following one would delete
- # whatever it points at.
+ # A reparse point at a lock name is not a lock; following it would delete its target.
$item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
if ($null -ne $item -and -not $item.PSIsContainer -and
-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
@@ -168,8 +148,7 @@ Environment:
}
}
- # LOCALAPPDATA / APPDATA are dropped in service and CI contexts, so fall back to the known
- # folder; $null only if that fails too, which callers treat as incomplete cleanup.
+ # LOCALAPPDATA/APPDATA are unset in service and CI contexts; fall back to the known folder.
function _AppDataRoot {
param([string]$Var, [string]$Folder)
if (-not [string]::IsNullOrWhiteSpace($Var)) { return $Var }
@@ -178,32 +157,24 @@ Environment:
return $p
}
- # Remove an install root and record whether its studio.db really went with it. That file holds
- # the chat history (backend/storage/studio_db.py), not the provider API keys, which
- # providers_db.py keeps in the browser's localStorage only; an env-mode install keeps it in a
- # custom root a bare run cannot find. The check runs on the RESOLVED target: a relocated
- # install passes the before-check through the link, but the delete unlinks only the reparse
- # point. Verifying rather than chasing the link is deliberate: following a reparse point out of
- # the expected location to delete its target is what the deny list exists to stop.
- # A removal that got part way can take the sentinels and then fail on a locked child, leaving
- # a root the next run's gate would refuse. Put the marker back so a retry recognises it.
+ # A partial removal can take the sentinels and then fail; restore the marker so a retry
+ # recognises the root.
function _RestoreOwnerMarker {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return }
- # Get-Item -Force, not Test-Path: the latter follows a dangling link and answers false,
- # after which WriteAllText follows the link and writes outside the root.
+ # Get-Item -Force, not Test-Path: a dangling link reads as absent, then the write escapes the root.
$marker = Join-Path $Path ".unsloth-studio-owned"
if (Get-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue) { return }
try { [System.IO.File]::WriteAllText($marker, "") } catch { }
}
+ # Checks studio.db at the resolved target but deletes only the link: never chase a reparse
+ # point out of the tree to delete its target.
function _RemoveRootRecordingDb {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
- # Anchor a relative reparse-point target to the link's own parent, or Join-Path
- # resolves it from the uninstaller's working directory and the db test reads false.
- # -LiteralPath takes no -Parent (other parameter set; it throws) and already returns it.
+ # Anchor a relative reparse target to the link's parent, not the working directory.
$resolveTarget = {
param($Item, $Fallback)
if (-not $Item -or -not $Item.Target) { return $Fallback }
@@ -219,7 +190,7 @@ Environment:
$item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
$real = & $resolveTarget $item $Path
} catch { }
- # The db itself can be a reparse point out of the tree: the target survives the delete.
+ # studio.db can itself be a reparse point out of the tree.
$dbPath = Join-Path $real "studio.db"
$hadDb = Test-Path -LiteralPath $dbPath -PathType Leaf
if ($hadDb) {
@@ -239,45 +210,28 @@ Environment:
}
}
- # Reclaim ONLY what install.ps1 puts under "<LocalAppData>\Unsloth Studio\temp": directories
- # named ust-<pid>-<hex>, then the temp dir and its parent if left empty. Deliberately narrow:
- # this runs against every LocalAppData spelling, including one that can name a different user's
- # profile, so it must never recursively delete anything it did not create. Nothing here follows
- # a link (Directory.Delete with $false unlinks a reparse point without touching its target).
+ # Reclaim only install.ps1's ust-<pid>-<hex> dirs and the then-empty parents. Other spellings
+ # may be another user's profile, so never delete anything not created here or follow a link.
function _RemoveStudioPrivateTempTrees {
param(
[string[]]$Paths,
- # The spelling this uninstall is actually for. Any OTHER spelling can be
- # a different user's profile, so it gets the stricter rule below.
+ # Any other spelling may be a different user's profile.
[string]$PrimaryPath
)
- # Every directory this sweep kept, returned so the callers keep it too: the wholesale
- # data-directory removal runs over the same tree, and a live owner preserved here but
- # deleted there is not preserved at all.
+ # Returned so the data-directory removal keeps them too.
$preserved = @()
foreach ($temp in @($Paths)) {
if ([string]::IsNullOrWhiteSpace($temp)) { continue }
if (-not (Test-Path -LiteralPath $temp -PathType Container)) { continue }
$isPrimary = (-not [string]::IsNullOrWhiteSpace($PrimaryPath)) -and
[string]::Equals($temp.TrimEnd('\','/'), $PrimaryPath.TrimEnd('\','/'), [System.StringComparison]::OrdinalIgnoreCase)
- # Never descend through a link. Get-ChildItem on a reparse point enumerates the
- # TARGET, whose ordinary children carry no ReparsePoint attribute, so the recursive
- # delete below would take somebody else's tree by way of a redirected temp dir.
- #
- # How far up to look differs by spelling. For the profile this uninstall is FOR, the
- # temp directory and the "Unsloth Studio" directory above it are the two this script
- # created and the two that decide where the enumeration lands; a redirected
- # LocalAppData higher up is still that same user's own storage, and refusing there
- # would leave the installer's own temp tree behind on every host that uses folder
- # redirection. Any OTHER spelling may be another profile entirely, and a junction
- # anywhere along it -- LocalAppData, Users, the drive root -- is enough to redirect an
- # ordinary-looking "Unsloth Studio\temp", so there every ancestor has to be ordinary.
+ # Never descend through a link. For the primary profile only the two dirs we created must be
+ # ordinary; for other spellings every ancestor must be.
$ancestors = @()
if ($isPrimary) {
$ancestors = @($temp, [System.IO.Path]::GetDirectoryName($temp))
} else {
$walk = $temp
- # Bounded: GetDirectoryName returns $null at the root, and the cap stops a spin.
for ($depth = 0; $depth -lt 64; $depth++) {
if ([string]::IsNullOrWhiteSpace($walk)) { break }
$ancestors += $walk
@@ -296,19 +250,16 @@ Environment:
}
if ($linked) {
_Substep "skipped (reparse point): $temp" "Yellow"
- # Not ours to delete here, nor in the data-directory pass either.
$preserved += $temp
continue
}
$entries = @()
try { $entries = @(Get-ChildItem -LiteralPath $temp -Force -ErrorAction Stop) } catch { continue }
foreach ($entry in $entries) {
- # Shape, not prefix: "ust-legacy" and "ust-notapid-x" are not ours.
+ # Shape, not prefix.
if ($entry.Name -notmatch '^ust-[0-9]+-[0-9a-f]{8}$') { continue }
if (-not ($entry.PSIsContainer)) { continue }
- # A LIVE owner keeps its directory, exactly as install.ps1's own sweep does. An
- # uninstall stops the Unsloth instances under the roots it knows about; one from
- # another install root, or another user, is not among them and still needs %TEMP%.
+ # A live owner keeps its directory, as in install.ps1's own sweep.
$ownerPid = 0
try {
$ownerFile = Join-Path $entry.FullName "owner.pid"
@@ -327,11 +278,7 @@ Environment:
continue
}
} elseif (-not $isPrimary) {
- # No recorded owner, and not the profile being uninstalled. install.ps1 reads
- # that as UNKNOWN rather than abandoned, because an installer killed before
- # writing owner.pid leaves a live Unsloth holding the directory, and another
- # user's live %TEMP% is not this uninstall's business. Under our own profile
- # the shape is enough, since that is what is being removed.
+ # No recorded owner in another profile is unknown, not abandoned.
_Substep "no recorded owner in another profile, left alone: $($entry.FullName)" "Yellow"
$preserved += $entry.FullName
continue
@@ -348,8 +295,7 @@ Environment:
$script:RemoveFailed = $true
}
}
- # Only when empty, so a temp dir holding anything else is left alone, and likewise the
- # "Unsloth Studio" parent, which on the second spelling may not be ours to delete.
+ # Only when empty; the parent may not be ours on another spelling.
foreach ($dir in @($temp, [System.IO.Path]::GetDirectoryName($temp))) {
try {
if ((Test-Path -LiteralPath $dir -PathType Container) -and
@@ -362,8 +308,7 @@ Environment:
return $preserved
}
- # Delete a tree except for the paths in -Keep and the directories above them, which have to
- # survive to hold them. With an empty -Keep this is _RemovePath, which is the ordinary case.
+ # Delete a tree except -Keep paths and their ancestors; empty -Keep is _RemovePath.
function _RemoveTreeKeeping {
param(
[string]$Path,
@@ -376,7 +321,6 @@ Environment:
foreach ($k in @($Keep)) {
if ([string]::IsNullOrWhiteSpace($k)) { continue }
$kept = $k.TrimEnd('\','/')
- # The kept path itself: stop here, with everything inside it.
if ([string]::Equals($kept, $self, [System.StringComparison]::OrdinalIgnoreCase)) { return }
if ($kept.StartsWith(($self + '\'), [System.StringComparison]::OrdinalIgnoreCase) -or
$kept.StartsWith(($self + '/'), [System.StringComparison]::OrdinalIgnoreCase)) {
@@ -387,27 +331,23 @@ Environment:
_RemovePath $Path
return
}
- # Something below survives, so this directory does too; take the rest of its children.
Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue | ForEach-Object {
_RemoveTreeKeeping -Path $_.FullName -Keep $Keep
}
}
- # Remove the shared data dir, but keep unsloth.ico if a WSL shortcut still points
- # at it (else that shortcut blanks); uninstall.sh drops it when WSL is removed.
+ # Keep unsloth.ico while a WSL shortcut still points at it; uninstall.sh drops it with WSL.
function _RemoveDataDirKeepingWslIcon {
param(
[string]$DataDir,
- # WSL-shortcut search dirs; default Start Menu + Desktop, overridable for tests.
[string[]]$ShortcutDirs = $null,
- # Paths under the data dir a previous pass kept, typically a live Unsloth's %TEMP%.
+ # Paths a previous pass kept, typically a live Unsloth's %TEMP%.
[string[]]$Preserve = @()
)
if ([string]::IsNullOrWhiteSpace($DataDir)) { return }
if (-not (Test-Path -LiteralPath $DataDir)) { return }
- # $null = not passed (use defaults); test $null, not truthiness, so an explicit @() is honored.
+ # Test $null, not truthiness, so an explicit @() is honored.
if ($null -eq $ShortcutDirs) {
- # Guard $env:APPDATA: unset in service/CI contexts, where Join-Path errors noisily.
$ShortcutDirs = @()
if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {
$ShortcutDirs += Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs"
@@ -430,21 +370,14 @@ Environment:
return
}
if (@($wslShortcuts).Count -gt 0) {
- # A WSL shortcut survives: keep its shared icon.
_Substep "keeping $(Join-Path $DataDir 'unsloth.ico') for the WSL shortcut" "Gray"
$keep += (Join-Path $DataDir "unsloth.ico")
}
_RemoveTreeKeeping -Path $DataDir -Keep $keep
}
- # Is this bin\unsloth.cmd the launcher install.ps1 wrote, or just a file with that name? The
- # distinction decides whether a directory gets deleted recursively, and `unsloth.cmd` is a
- # plausible wrapper for anyone shipping an unsloth-based tool, so pointing UNSLOTH_STUDIO_HOME
- # at such a project must not hand its whole tree to _RemovePath.
- #
- # The trampoline is the marker: install.ps1 bakes that exact expression into the shim, no other
- # file has a reason to carry it, and it survives every layout the shim has. Bounded read: the
- # real shim is a few hundred bytes.
+ # Only the shim install.ps1 wrote counts: its trampoline expression is the marker, since
+ # unsloth.cmd is a plausible name for other tools. Bounded read: the real shim is tiny.
function _IsUnslothCmdShim {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }
@@ -453,52 +386,33 @@ Environment:
if ($item.Length -gt 8192) { return $false }
$text = [System.IO.File]::ReadAllText($Path)
} catch {
- # Unreadable proves nothing, and "proves nothing" must not mean "delete it".
+ # Unreadable proves nothing, and must not mean delete.
return $false
}
return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")
}
- # A path is an Unsloth-owned root iff one of install.ps1's sentinels exists:
- # <root>\share\studio.conf, <root>\unsloth_studio\.unsloth-studio-owned,
- # <root>\bin\unsloth.exe, or a <root>\bin\unsloth.cmd this installer wrote.
- # The .cmd is the launcher written where an Application Control policy denies the generated
- # console script, so an install whose .exe that policy quarantined still owns its root.
- # Plus the legacy venv shapes install.ps1 still migrates: share\studio.conf is never written
- # on Windows, so every sentinel above postdates the bin\ shim dir.
- # A sentinel this gate may trust. Deliberately a plain existence test, following links:
- # refusing a reparse point here, or a marker inside one, buys nothing and costs a supported
- # install. Nothing, because anyone who can plant a junction at that path can plant a plain
- # file there instead, which this has always accepted. A supported install, because relocating
- # a multi-gigabyte venv with a junction leaves a REAL marker behind one, and refusing it
- # strands the install, which is the failure this gate exists to prevent. The link test belongs
- # in install.ps1's claim, where following one would TRUNCATE the target rather than read it.
+ # Owned iff one of install.ps1's sentinels exists (studio.conf, owner marker, bin\unsloth.exe,
+ # our unsloth.cmd) or a legacy venv shape. Plain existence test that follows links on purpose.
function _IsOwnerMarker {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
return (Test-Path -LiteralPath $Path -PathType Leaf)
}
- # Is $Path a Python venv? What the gate reads out of one is evidence only if the directory
- # really is one; a bare name at that path is somebody else's.
function _IsVenvDir {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
- # No reparse check here either, and for the same reason: a relocated venv is still a
- # venv. The leftover scan below rejects links on its own, where the name came from a
- # wildcard rather than from us.
+ # No reparse check: a relocated venv is still a venv.
if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false }
if (Test-Path -LiteralPath (Join-Path $Path "pyvenv.cfg") -PathType Leaf) { return $true }
return (Test-Path -LiteralPath (Join-Path $Path "Scripts\python.exe") -PathType Leaf)
}
- # The exact shape an installer gives a moved-aside venv. install.ps1 keeps every other
- # spelling as the user's data (Test-StudioVenvRollbackMustBePreserved); do not be looser.
+ # Exactly the moved-aside venv shape; install.ps1 keeps every other spelling as user data.
function _IsInstallerLeftoverName {
param([string]$Name)
- # Two patterns: only the rollback name carries a collision counter (install.ps1:4171).
- # No "time" alternative; that is install.sh's date(1) fallback and has no Windows twin.
- # [0-9], not \d, which matches every Unicode decimal digit; install.ps1 writes ASCII.
+ # Only the rollback name has a collision counter. [0-9], not \d, which matches any Unicode digit.
if ($Name -match '^unsloth_studio\.rollback\.[0-9]{14}\.[0-9]+(\.[0-9]+)?$') { return $true }
return ($Name -match '^\.venv\.invalid\.[0-9]{14}\.[0-9]+$')
}
@@ -506,33 +420,26 @@ Environment:
function _IsStudioRoot {
param([string]$Path, [switch]$ManagedDefaultRoot)
if ([string]::IsNullOrWhiteSpace($Path)) { return $false }
- # install.ps1 writes the first when it creates the root, before the uv cache and long
- # before the venv, so a partial install identifies itself instead of being guessed at.
+ # install.ps1 writes the marker first, so a partial install identifies itself.
if (_IsOwnerMarker (Join-Path $Path ".unsloth-studio-owned")) { return $true }
if (_IsOwnerMarker (Join-Path $Path "share\studio.conf")) { return $true }
if (_IsOwnerMarker (Join-Path $Path "unsloth_studio\.unsloth-studio-owned")) { return $true }
if (_IsOwnerMarker (Join-Path $Path ".venv\.unsloth-studio-owned")) { return $true }
if (Test-Path -LiteralPath (Join-Path $Path "bin\unsloth.exe") -PathType Leaf) { return $true }
if (_IsUnslothCmdShim (Join-Path $Path "bin\unsloth.cmd")) { return $true }
- # Below here is INSIDE a venv, where pip puts it for any install of the wheel: it names
- # the wheel, not the owner. Proof only at the managed root, which install.ps1:4453 also
- # makes the only root that can hold the layout, or a stale UNSLOTH_STUDIO_HOME deletes it.
+ # Inside a venv a package names the wheel, not the owner; proof only at the managed root.
if (-not $ManagedDefaultRoot) { return $false }
foreach ($venv in @("unsloth_studio", ".venv")) {
if (-not (_IsVenvDir (Join-Path $Path $venv))) { continue }
if (Test-Path -LiteralPath (Join-Path $Path "$venv\Scripts\unsloth.exe") -PathType Leaf) { return $true }
- # Antivirus takes that .exe out of a venv that still runs; install.ps1:6412 repairs
- # through it, so a pre-marker root has nothing else left.
+ # The .exe can be removed from a working venv; a pre-marker root has nothing else left.
foreach ($pkg in @("unsloth_cli", "unsloth")) {
if (Test-Path -LiteralPath (Join-Path $Path "$venv\Lib\site-packages\$pkg") -PathType Container) { return $true }
}
}
- # An install that died between moving the old venv aside (install.ps1:4487, :4165) and
- # writing the marker (install.ps1:4524) leaves only these, and only install.ps1 makes
- # either name, always by renaming a venv.
+ # Only install.ps1 makes these names, by renaming a venv before writing the marker.
foreach ($leftover in @("unsloth_studio.rollback.*", ".venv.invalid.*")) {
foreach ($dir in @(Get-ChildItem -LiteralPath $Path -Filter $leftover -Directory -Force -ErrorAction SilentlyContinue)) {
- # Never a reparse point: install.ps1 refuses to prune a linked rollback either.
if (($dir.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }
if (-not (_IsInstallerLeftoverName $dir.Name)) { continue }
if (_IsVenvDir $dir.FullName) { return $true }
@@ -541,7 +448,6 @@ Environment:
return $false
}
- # install.ps1 records its uv cache in <root>\cache\uv-cache-dir.
function _RecordedUvCache {
param([string]$Root)
$marker = Join-Path $Root "cache\uv-cache-dir"
@@ -565,7 +471,6 @@ Environment:
return $normCache.StartsWith($normRoot + '\', [StringComparison]::OrdinalIgnoreCase)
}
- # Saw: any root recorded a cache. Leftovers: recorded caches outside every root this run deletes.
function _UvLeftoverCaches {
param([string[]]$Roots)
$saw = $false
@@ -576,7 +481,7 @@ Environment:
$saw = $true
$under = $false
foreach ($root in $Roots) {
- # A junctioned/symlinked root is only unlinked, so its target (and any cache in it) stays.
+ # A linked root is only unlinked, so its target cache stays.
$item = Get-Item -LiteralPath $root -Force -ErrorAction SilentlyContinue
if ($item -and $item.LinkType) { continue }
if (_UvCacheUnderRoot $rec $root) { $under = $true; break }
@@ -593,7 +498,6 @@ Environment:
$norm = $null
try { $norm = [System.IO.Path]::GetFullPath($Path).TrimEnd('\','/') } catch { return $true }
if ([string]::IsNullOrWhiteSpace($norm)) { return $true }
- # Drive root, e.g. C:\
if ($norm -match '^[A-Za-z]:[\\/]?$') { return $true }
$userProfile = $env:USERPROFILE
if ($userProfile) {
@@ -617,15 +521,13 @@ Environment:
return $false
}
- # Parse UNSLOTH_EXE='<path>' out of a share\studio.conf and return the
- # implied install root (three dirnames up from the venv exe).
+ # Install root is three dirnames up from UNSLOTH_EXE in share\studio.conf.
function _RootFromConf {
param([string]$ConfFile)
if (-not (Test-Path -LiteralPath $ConfFile -PathType Leaf)) { return $null }
$line = Get-Content -LiteralPath $ConfFile -ErrorAction SilentlyContinue |
Where-Object { $_ -match "^UNSLOTH_EXE\s*=" } | Select-Object -First 1
if (-not $line) { return $null }
- # Tolerate ' value ' single-quoted with '' -> ' apostrophe escape.
if ($line -match "^UNSLOTH_EXE\s*=\s*'(.*)'\s*$") {
$exe = $Matches[1] -replace "''", "'"
try {
@@ -638,8 +540,6 @@ Environment:
return $null
}
- # Expand a leading ~ or ~/ ~\ to $env:USERPROFILE, so env-mode roots written with the tilde
- # shape install.ps1 supports are found here too.
function _ExpandTilde {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) { return $Path }
@@ -653,25 +553,14 @@ Environment:
return $p
}
- # Discover non-default Unsloth roots from env vars + studio.conf files. Mirrors install.ps1's
- # precedence: UNSLOTH_STUDIO_HOME wins and STUDIO_HOME is ignored when both are set, or
- # uninstalling install A would also delete install B from a stale STUDIO_HOME.
- # The master root UNSLOTH_HOME names, or $null. studio\ is its child and llama.cpp, node and
- # whisper.cpp are its other children, so removing the Studio root alone strands them. Trimmed
- # and tilde-expanded like storage_roots.unsloth_home() and studio\setup.ps1.
+ # UNSLOTH_STUDIO_HOME wins and STUDIO_HOME is ignored when both are set, as in install.ps1.
+ # Master root from UNSLOTH_HOME, trimmed and tilde-expanded like storage_roots.unsloth_home().
function _MasterRoot {
$noteStudio = $null
$raw = $env:UNSLOTH_HOME
if ([string]::IsNullOrWhiteSpace($raw)) {
- # The note setup.ps1 leaves in the Studio tree, when this run has no UNSLOTH_HOME of
- # its own: a one-command `$env:UNSLOTH_HOME = 'D:\portable'` leaves nothing in a
- # later environment, so without it an uninstall stranded the runtimes. The deny list
- # and the marker gates still apply, so a stale note licenses nothing.
- #
- # Only the Studio root this run is about, in studio_root()'s precedence and with no
- # falling through: with two installs on one box, a legacy note otherwise won here
- # while the removal worked on the named tree, so the run deleted one Studio and the
- # OTHER install's runtime children. Mirrors _master_root in uninstall.sh.
+ # Fall back to the note setup.ps1 leaves in the Studio tree; only this run's Studio root, no
+ # falling through. Mirrors _master_root in uninstall.sh.
$noteRoots = @()
foreach ($override in @($env:UNSLOTH_STUDIO_HOME, $env:STUDIO_HOME)) {
if (-not [string]::IsNullOrWhiteSpace($override)) {
@@ -680,11 +569,7 @@ Environment:
}
}
if (-not $noteRoots) {
- # No override names one, so the root install.ps1 recorded in the default-mode
- # studio.conf, then the legacy tree. A master-root install puts Studio at
- # <master>\studio, and that conf is how this script finds it with a bare
- # environment. Read directly rather than through _CustomStudioRoots, which calls
- # back into this function.
+ # Read the default-mode conf directly; _CustomStudioRoots calls back into this function.
if ($env:LOCALAPPDATA) {
$confRoot = _RootFromConf (Join-Path $env:LOCALAPPDATA "Unsloth Studio\studio.conf")
if ($confRoot) { $noteRoots += $confRoot }
@@ -697,14 +582,8 @@ Environment:
$notePath = Join-Path $noteRoot "share\.unsloth-master-root"
if (-not (Test-Path -LiteralPath $notePath -PathType Leaf)) { continue }
try {
- # One line, and REFUSED when there is a second: storage_roots.py and the CLI
- # strip the WHOLE file, so a two-line note is not a directory to them and
- # they decline it, while accepting line 1 here let a note no runtime reader
- # honours authorise removing the master root's runtime children. Two lines
- # are read so the second can be seen; a trailing newline is not one.
- # -Encoding UTF8: 5.1 decodes BOM-less input with the ANSI code page, so a
- # master root holding non-ASCII came back mangled and its runtime siblings
- # were never found.
+ # Refuse a two-line note, as storage_roots and the CLI do.
+ # -Encoding UTF8: 5.1 reads BOM-less files as ANSI.
$noteLines = @(Get-Content -LiteralPath $notePath -TotalCount 2 -Encoding UTF8 -ErrorAction Stop)
} catch { continue }
if ($noteLines.Count -gt 1 -and -not [string]::IsNullOrWhiteSpace($noteLines[1])) { continue }
@@ -719,23 +598,15 @@ Environment:
if ([string]::IsNullOrWhiteSpace($raw)) { return $null }
$expanded = _ExpandTilde $raw.Trim()
$norm = $null
- # The provider path first, exactly as setup.ps1's Get-CanonicalDir resolves it.
- # [IO.Path]::GetFullPath anchors a RELATIVE root at [Environment]::CurrentDirectory,
- # which PowerShell does not keep in step with its own location, so after a Set-Location
- # a relative UNSLOTH_HOME named one install to setup and another here. Nothing downstream
- # notices: the marker spares trees that are not Unsloth's, not another Unsloth install.
+ # Resolve through the provider like setup.ps1's Get-CanonicalDir; GetFullPath uses a stale cwd.
try {
$norm = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($expanded)
} catch { $norm = $null }
try { $norm = [System.IO.Path]::GetFullPath($(if ($norm) { $norm } else { $expanded })).TrimEnd('\','/') }
catch { return $null }
if (-not $norm) { return $null }
- # A note must describe the tree it was found in: copy a Studio tree from master root A to
- # B and uninstall B, and the copied note still names A, whose runtimes carry the same
- # owner markers -- so the gates below would delete the ORIGINAL install's. Containment,
- # not an exact <root>\studio match, since the flat layout is supported. An explicit
- # UNSLOTH_HOME skips the check: that is the user speaking, not a file on disk. Mirrors
- # uninstall.sh and storage_roots._recorded_master_root().
+ # A note must describe the tree it was found in (containment); explicit UNSLOTH_HOME skips this.
+ # Mirrors uninstall.sh and storage_roots._recorded_master_root().
if ($noteStudio) {
$here = $null
try {
@@ -744,14 +615,8 @@ Environment:
try { $here = [System.IO.Path]::GetFullPath($(if ($here) { $here } else { $noteStudio })).TrimEnd('\','/') }
catch { $here = $null }
if (-not $here) { return $null }
- # A note found in the ordinary %USERPROFILE%\.unsloth\studio install is declined
- # outright, whatever it records, which is the rule storage_roots'
- # _is_legacy_studio_tree and the CLI already apply. Containment alone is not enough:
- # the profile directory CONTAINS the legacy tree, so a note naming it passed,
- # _CustomStudioRoots then derived "<profile>\studio", and uninstalling the legacy
- # install accepted a SECOND marked install there as a root to remove. The deny list
- # below refuses the profile as a MASTER root, not the Studio candidate derived from
- # it. Mirrors uninstall.sh.
+ # Decline any note in the legacy %USERPROFILE%\.unsloth\studio tree, as storage_roots does.
+ # Mirrors uninstall.sh.
if ($env:USERPROFILE) {
$legacyStudio = $null
try {
@@ -765,7 +630,6 @@ Environment:
return $null
}
}
- # The default root is left to the blocks that own it, which remove it unconditionally.
if ($env:USERPROFILE -and ($norm -ieq (Join-Path $env:USERPROFILE ".unsloth").TrimEnd('\','/'))) {
return $null
}
@@ -791,16 +655,13 @@ Environment:
}
$envRoot = $null
- # IsNullOrWhiteSpace, not truthiness: storage_roots.studio_root() trims these, so a
- # whitespace-only override is unset to every resolver, while a bare truthy test called it
- # present and suppressed the master-root branch below, leaving <UNSLOTH_HOME>\studio.
+ # IsNullOrWhiteSpace, not truthiness: the resolvers trim these.
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) {
$envRoot = $env:UNSLOTH_STUDIO_HOME.Trim()
} elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) {
$envRoot = $env:STUDIO_HOME.Trim()
} else {
- # Last, as in storage_roots.studio_root(): UNSLOTH_HOME names the tree, and the two
- # above name this exact directory, so either of them wins outright.
+ # Last, as in storage_roots.studio_root().
$master = _MasterRoot
if ($master) { $envRoot = (Join-Path $master "studio") }
}
@@ -810,7 +671,6 @@ Environment:
$confRoot = _RootFromConf (Join-Path $expandedEnv "share\studio.conf")
if ($confRoot) { & $emit $confRoot }
}
- # Default-mode conf at LOCALAPPDATA\Unsloth Studio.
if ($env:LOCALAPPDATA) {
$confRoot = _RootFromConf (Join-Path $env:LOCALAPPDATA "Unsloth Studio\studio.conf")
if ($confRoot) { & $emit $confRoot }
@@ -824,8 +684,8 @@ Environment:
}
}
- # Return $true iff the PID's image path lives under one of $KnownRoots, so an unrelated
- # process listening on a stale Unsloth port is never killed.
+ # True iff the PID's image is under $KnownRoots, so an unrelated process on a stale
+ # Unsloth port is never killed.
function _PidUnderKnownRoot {
param([int]$Pid_, [string[]]$KnownRoots)
if (-not $KnownRoots -or $KnownRoots.Count -eq 0) { return $false }
@@ -841,8 +701,6 @@ Environment:
return $false
}
- # Stop an Unsloth backend whose port is recorded in <DataDir>\studio.port.
- # Only kills if the listening PID's exe path is under a known Unsloth root.
function _StopByPortFile {
param([string]$PortFile, [string[]]$KnownRoots)
if (-not (Test-Path -LiteralPath $PortFile -PathType Leaf)) { return }
@@ -861,8 +719,7 @@ Environment:
} catch { }
}
} catch {
- # netstat fallback for older PowerShell. Require LISTENING so we never kill a process
- # whose remote endpoint just happens to be the cached port (browser -> :443 etc.).
+ # Require LISTENING so a process merely connected to that port is never killed.
try {
$lines = & netstat.exe -ano 2>$null |
Select-String -Pattern "LISTENING" |
@@ -880,12 +737,9 @@ Environment:
Remove-Item -LiteralPath $PortFile -Force -ErrorAction SilentlyContinue
}
- # Stop processes whose ExecutablePath lives under an unsloth_studio venv.
- # Anchoring on the venv path avoids matching unrelated python.exe / studio.exe.
function _StopStudioProcesses {
param([string[]]$KnownRoots)
- # An EXPLICIT empty list means "no root qualifies", not "do not scope". @() is false in
- # PowerShell, so `if ($KnownRoots)` swept the whole machine on a run with nothing to delete.
+ # An explicit empty list means no root qualifies; @() is falsy in PowerShell.
$scoped = $PSBoundParameters.ContainsKey('KnownRoots')
try {
$procs = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
@@ -894,7 +748,6 @@ Environment:
$_.CommandLine -and ($_.CommandLine -match 'studio')
}
foreach ($p in $procs) {
- # Optional scope: only kill if the exe is under a known root.
if ($scoped) {
$match = $false
foreach ($r in $KnownRoots) {
@@ -909,24 +762,10 @@ Environment:
} catch { }
}
- # The Unsloth-managed subtrees underneath the reparse-point TARGET of each Unsloth home, for
- # the stop scan only. A junction or symlinked home runs its native binaries out of the PHYSICAL
- # path (the backend resolves the home before deriving <home>\stable-diffusion.cpp and launching
- # sd-server there), while _CustomStudioRoots only normalizes the string: GetFullPath is lexical
- # and leaves a reparse point untouched. The prefix scan below reads Win32_Process.ExecutablePath,
- # the real image path, so without the target a running server never matches and survives an
- # uninstall that took its tree.
- #
- # The SUBTREES, never the bare target: the delete unlinks only the reparse point, so anything
- # under the target that is not ours is neither locking nor being removed and must not be
- # force-stopped. Homes only, for the same reason: a component dir ($defaultNode, ...) can
- # itself be a link onto a shared runtime, and resolving it would scope in every process there.
- #
- # Stop scan only, deliberately. The deletes still refuse to chase a link out of the expected
- # location, which is what the deny list exists to prevent; ending our own process is not.
+ # Managed subtrees under each home's reparse target, for the stop scan only: processes run from
+ # the physical path. Subtrees and homes only, never the bare target or component links.
function _ManagedPathsUnderReparseTargets {
param([string[]]$Roots)
- # Everything setup.ps1 / the prebuilt installers place inside an Unsloth home.
$managed = @(
"unsloth_studio", "share", "bin", "llama.cpp", "whisper.cpp", "audio.cpp", "node",
"stable-diffusion.cpp", ".cache", ".venv_t5_510", ".venv_t5_530", ".venv_t5_550"
@@ -938,8 +777,7 @@ Environment:
if (-not $item -or -not $item.Target) { continue }
$t = @($item.Target)[0]
if ([string]::IsNullOrWhiteSpace($t)) { continue }
- # A symlink target may be relative; a junction's never is. Anchor it on the link's
- # own parent, or GetFullPath would read it from the uninstaller's working directory.
+ # A relative symlink target is anchored on the link's parent, not the working directory.
if (-not [System.IO.Path]::IsPathRooted($t)) {
$t = Join-Path (Split-Path -LiteralPath $item.FullName) $t
}
@@ -954,10 +792,8 @@ Environment:
return $out
}
- # Stop processes that would block deleting the paths we remove. Unlike _StopStudioProcesses
- # (venv exe only), this also catches llama-server/llama-cli, the unsloth.exe shim and orphaned
- # mp workers holding a venv DLL (an open DLL handle blocks the dir delete), found by scanning
- # each candidate's loaded modules as well as its image path.
+ # Unlike _StopStudioProcesses, also catches llama-server, the shim and orphaned workers
+ # holding a venv DLL (via loaded modules).
function _StopProcessesLockingRoots {
param([string[]]$Roots)
$clean = @($Roots | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\','/') })
@@ -968,7 +804,6 @@ Environment:
foreach ($r in $clean) { if ($p -ieq $r -or $p -ilike "$r\*") { return $true } }
return $false
}
- # 1. Image path under a target root (venv python, shim, llama-server).
try {
foreach ($proc in (Get-CimInstance Win32_Process -ErrorAction SilentlyContinue)) {
if ((& $underRoot $proc.ExecutablePath)) {
@@ -976,21 +811,19 @@ Environment:
}
}
} catch { }
- # 2. A loaded module under a target root (orphaned mp-fork python holding a
- # venv DLL). Scoped to names that load our DLLs to keep the scan fast.
+ # Module scan is scoped to names that load our DLLs, to keep it fast.
try {
$cands = Get-Process -Name python, pythonw, unsloth, llama-server, llama-cli, sd-cli, sd-server -ErrorAction SilentlyContinue
foreach ($proc in $cands) {
$hit = $false
try {
foreach ($m in $proc.Modules) { if ((& $underRoot $m.FileName)) { $hit = $true; break } }
- } catch { } # access denied enumerating modules -> skip
+ } catch { }
if ($hit) { try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch { } }
}
} catch { }
}
- # Default install root + default data dir.
$defaultStudioHome = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".unsloth\studio" } else { $null }
$defaultDataRoot = _AppDataRoot $env:LOCALAPPDATA 'LocalApplicationData'
$defaultDataDir = if ($defaultDataRoot) { Join-Path $defaultDataRoot "Unsloth Studio" } else { $null }
@@ -1001,7 +834,6 @@ Environment:
# recursive, sentinel-free and deny-list-free.
$knownLocalAppData = $null
try { $knownLocalAppData = [Environment]::GetFolderPath('LocalApplicationData') } catch { $knownLocalAppData = $null }
- # The first non-blank spelling is the one _AppDataRoot resolved: the profile this run is for.
$primaryPrivateTemp = if ($defaultDataDir) { Join-Path $defaultDataDir "temp" } else { $null }
$privateTempDirs = @()
foreach ($root in @($env:LOCALAPPDATA, $knownLocalAppData)) {
@@ -1009,36 +841,25 @@ Environment:
$candidate = Join-Path $root "Unsloth Studio\temp"
if ($privateTempDirs -notcontains $candidate) { $privateTempDirs += $candidate }
}
- # Default-mode ~/.unsloth holds a SHARED llama.cpp build + .cache that are siblings of studio,
- # so deleting <studio> misses them. No-op in env/custom mode (nested under the custom root,
- # removed with it). A user-set UNSLOTH_LLAMA_CPP_PATH is left alone.
+ # Default-mode siblings of studio under ~/.unsloth. A user-set UNSLOTH_LLAMA_CPP_PATH is left alone.
$defaultUnslothHome = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".unsloth" } else { $null }
$defaultLlamaCpp = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome "llama.cpp" } else { $null }
- # Default-mode native diffusion build, a sibling of studio like llama.cpp. No-op in env/custom
- # mode and when absent. A user-set UNSLOTH_SD_CPP_PATH is left alone.
+ # A user-set UNSLOTH_SD_CPP_PATH is left alone.
$defaultSdCpp = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome "stable-diffusion.cpp" } else { $null }
$defaultCache = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome ".cache" } else { $null }
- # Isolated Node.js runtime (install_node_prebuilt.py), a default-mode sibling of studio.
$defaultNode = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome "node" } else { $null }
- # llama.cpp atomic-install staging root (install_llama_prebuilt.py), a sibling of the install
- # dir. Usually pruned after activate, but an interrupted build leaves a "<name>.staging-XXXX"
- # tree behind and that blocks the empty-dir cleanup of ~/.unsloth below.
+ # An interrupted build leaves .staging behind, which blocks pruning ~/.unsloth.
$defaultStaging = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome ".staging" } else { $null }
- # Managed whisper.cpp dictation engine (setup.ps1 installs it at $UnslothHome\whisper.cpp), a
- # default-mode sibling of studio. No-op in env/custom mode and when absent.
$defaultWhisperCpp = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome "whisper.cpp" } else { $null }
- # Managed audio.cpp engine (setup.ps1 installs it at $UnslothHome\audio.cpp), same rules.
$defaultAudioCpp = if ($defaultUnslothHome) { Join-Path $defaultUnslothHome "audio.cpp" } else { $null }
- # Build known-root list FIRST so the port-file kill can verify ownership.
+ # Build known roots first so the port-file kill can verify ownership.
$customRoots = @(_CustomStudioRoots)
$knownRoots = @()
if ($defaultStudioHome) { $knownRoots += $defaultStudioHome }
$knownRoots += $customRoots
- # The roots this run would actually delete. Everything that stops, deletes or edits on behalf
- # of a root takes THIS list, never $knownRoots: all of it runs before the gates below, and a
- # stale studio.conf can name a directory another application has taken over. _IsUnsafeRoot as
- # well as _IsStudioRoot, because the removal loop refuses on either.
+ # Everything that stops, deletes or edits for a root uses this list, never $knownRoots:
+ # a stale studio.conf can name a directory another application now owns.
$ownedRoots = @()
if ($defaultStudioHome -and (_IsStudioRoot $defaultStudioHome -ManagedDefaultRoot) -and
-not (_IsUnsafeRoot $defaultStudioHome)) {
@@ -1055,27 +876,20 @@ Environment:
if ($defaultDataDir) {
_StopByPortFile -PortFile (Join-Path $defaultDataDir "studio.port") -KnownRoots $ownedRoots
}
- # $ownedRoots, not $customRoots: _StopByPortFile deletes the port file on its way out.
+ # _StopByPortFile deletes the port file, so only owned roots.
foreach ($r in $ownedRoots) {
_StopByPortFile -PortFile (Join-Path $r "share\studio.port") -KnownRoots $ownedRoots
}
_StopStudioProcesses -KnownRoots $ownedRoots
- # The app and the WebView2 helpers holding its profile open must both exit before the
- # EBWebView delete below. Same resolver as that removal, or the sweep misses the profile
- # we then try to delete and the helpers keep holding locks.
+ # The app and WebView2 helpers must exit before the EBWebView delete; same resolver as that delete.
$localAppRoot = _AppDataRoot $env:LOCALAPPDATA 'LocalApplicationData'
$webviewProfile = if ($localAppRoot) { Join-Path $localAppRoot "ai.unsloth.studio" } else { $null }
- # Account-scoped, like every other kill here. installMode is currentUser, so the profile is
- # this account's and shared by all its sessions: a second console or RDS session must die
- # too or it re-creates the profile mid-delete, while another user's Unsloth must not be
- # touched. SIDs, so domain and locale do not matter; an unreadable owner is skipped.
+ # Account-scoped by SID: every session of this account must die, other users' must not.
$meSid = try { [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value } catch { $null }
$studioPids = @()
if ($meSid) {
try {
- # Unsloth.exe too: older releases used the product name as MAINBINARYNAME, and this
- # script is always fetched fresh from main, so it meets those installs. A missed
- # process re-creates the profile. The owner-SID filter keeps the broader name safe.
+ # Older releases used Unsloth.exe as the binary name; the SID filter keeps that safe.
$filter = "Name = 'unsloth-studio.exe' OR Name = 'Unsloth.exe'"
foreach ($sp in (Get-CimInstance Win32_Process -Filter $filter -ErrorAction SilentlyContinue)) {
$spSid = try { (Invoke-CimMethod -InputObject $sp -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid } catch { $null }
@@ -1084,18 +898,14 @@ Environment:
} catch { }
}
if ($webviewProfile) {
- # Escape "[", a wildcard class, or we miss our profile and match others. Trailing \
- # spares "<bid>2\EBWebView".
+ # Escape `[` (a wildcard class). Trailing \ spares "<bid>2\EBWebView".
$pattern = "*" + [System.Management.Automation.WildcardPattern]::Escape($webviewProfile) + "\*"
try {
$wvProcs = @(Get-CimInstance Win32_Process -Filter "Name = 'msedgewebview2.exe'" -ErrorAction SilentlyContinue)
- # Parent lookup for the ancestor walk; WebView2 procs are all the chain passes through.
$parentOf = @{}
foreach ($p in $wvProcs) { $parentOf[[int]$p.ProcessId] = [int]$p.ParentProcessId }
- # Chromium process model: the renderer, GPU and utility helpers are children of the
- # browser process, not of unsloth-studio.exe, so an immediate-parent check misses
- # them all and they keep EBWebView locked (Stop-Process is not recursive).
- # Depth-capped so a PID-reuse cycle cannot spin here.
+ # WebView2 helpers are children of the browser process, not the app.
+ # Depth-capped so a PID-reuse cycle cannot spin.
$isOurs = {
param($StartPid)
$cur = $StartPid
@@ -1109,7 +919,7 @@ Environment:
return $false
}
foreach ($proc in $wvProcs) {
- # CommandLine is null across an elevation boundary: fall back to the parent chain.
+ # CommandLine is null across an elevation boundary.
$mine = if ($proc.CommandLine) { $proc.CommandLine -ilike $pattern }
else { & $isOurs ([int]$proc.ProcessId) }
if ($mine) { try { Stop-Process -Id $proc.ProcessId -Force -ErrorAction SilentlyContinue } catch { } }
@@ -1118,19 +928,14 @@ Environment:
}
if ($studioPids) {
try { Stop-Process -Id $studioPids -Force -ErrorAction SilentlyContinue } catch { }
- # WebView2 releases the profile only once its browser processes have exited.
Wait-Process -Id $studioPids -Timeout 10 -ErrorAction SilentlyContinue
}
- # Only stop the default sd.cpp dir when it carries our owner marker, so stop matches the
- # marker-gated delete and a user's own sd-server at this default path is left running.
+ # Stop the default sd.cpp only when marked, matching the marker-gated delete.
$defaultSdCppToStop = $null
if ($defaultSdCpp -and (Test-Path -LiteralPath $defaultSdCpp) -and (Test-Path -LiteralPath (Join-Path $defaultSdCpp ".unsloth-studio-owned") -PathType Leaf)) {
$defaultSdCppToStop = $defaultSdCpp
}
- # A custom/env-mode sd.cpp build now sits UNDER its root, which the $knownRoots prefix match
- # below already covers. Older builds put it BESIDE the root at <parent>\stable-diffusion.cpp,
- # outside $knownRoots; we delete those marker-owned dirs below, so scan them too.
- # Gated too: a stale root's PARENT can hold another install's marked sd.cpp.
+ # Older builds put sd.cpp beside the root, outside $knownRoots; gated by marker too.
$customSdCppToStop = @()
foreach ($r in $customRoots) {
if (-not (_IsStudioRoot $r)) { continue }
@@ -1140,27 +945,19 @@ Environment:
$customSdCppToStop += $sdc
}
}
- # Also stop anything holding a handle on the exact paths we delete (llama-server,
- # the CLI shim, an mp-fork python with a venv DLL) so the dir delete isn't refused.
- # Resolved here, before the stop pass: a loaded llama-server.exe under the master root keeps
- # its own tree locked, and the removal below would exhaust its retries and leave it installed.
+ # Resolved before the stop pass: a loaded llama-server keeps its own tree locked.
$masterRootToStop = _MasterRoot
$masterChildrenToStop = @()
if ($masterRootToStop -and -not (_IsUnsafeRoot $masterRootToStop)) {
foreach ($childName in @("llama.cpp", "node", "whisper.cpp", "audio.cpp", "stable-diffusion.cpp")) {
$childPath = Join-Path $masterRootToStop $childName
- # Only the trees this uninstall is going to delete, so an unmarked neighbour's
- # process is never killed.
if (Test-Path -LiteralPath (Join-Path $childPath ".unsloth-studio-owned") -PathType Leaf) {
$masterChildrenToStop += $childPath
}
}
}
- # $ownedRoots, not $knownRoots: see the note where the two lists are built. The master
- # children are already marker-gated above, so they carry their own proof of ownership.
$stopRoots = @($ownedRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp, $defaultAudioCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop) + @($masterChildrenToStop)
- # The reparse expansion turns one path into generic subdirectories of wherever it points
- # (node, bin, unsloth_studio), so it is gated for the same reason.
+ # The reparse expansion yields generic subdirectories, so it is gated too.
_StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $ownedRoots))
# ── Remove custom-root install trees ──
@@ -1168,8 +965,7 @@ Environment:
foreach ($r in $customRoots) {
if (_IsUnsafeRoot $r) {
_Substep "refusing to remove unsafe path: $r" "Yellow"
- # install.ps1 accepts any writable root, so a real install can sit under a deny-listed
- # path. Nothing is deleted and it holds studio.db, so say so. Mirrors uninstall.sh.
+ # A refused root still holds studio.db, so report incomplete. Mirrors uninstall.sh.
if (Test-Path -LiteralPath $r) { $script:RemoveFailed = $true }
continue
}
@@ -1177,10 +973,8 @@ Environment:
_Substep "refusing to remove non-Unsloth path: $r" "Yellow"
continue
}
- # The flat layout, both variables naming one directory: _RemoveRootRecordingDb takes a
- # marked Studio root WHOLE, so without this the user-chosen master root went with the
- # install, which is the hole in the rule every other child below is marker-gated for.
- # Kept rather than pruned, since data left behind is recoverable. Mirrors uninstall.sh.
+ # Flat layout: keep the user-chosen master root rather than take it with the Studio root.
+ # Mirrors uninstall.sh.
$flatMaster = $masterRootToStop
if ($flatMaster -and ($r.TrimEnd('\', '/') -ieq $flatMaster.TrimEnd('\', '/'))) {
_Substep "keeping $r`: UNSLOTH_HOME and the Unsloth Studio root name the same directory," "Yellow"
@@ -1190,12 +984,8 @@ Environment:
continue
}
_RemoveRootRecordingDb $r
- # Native diffusion now installs UNDER the custom root, so the removal above already took
- # it. Older builds put it BESIDE the root at <parent>\stable-diffusion.cpp, which removing
- # the root alone would leave behind. <parent> is user-chosen and "stable-diffusion.cpp" is
- # exactly what a git clone of the upstream project produces, so require our owner marker
- # (install_sd_cpp_prebuilt) before rm and keep any unowned checkout. The derived parent
- # path gets the deny-list check too.
+ # Older builds put sd.cpp beside the root; require our marker, since an upstream clone has
+ # the same name.
$customSdCpp = Join-Path (Split-Path -LiteralPath $r) "stable-diffusion.cpp"
if (_IsUnsafeRoot $customSdCpp) {
_Substep "refusing to remove unsafe path: $customSdCpp" "Yellow"
@@ -1205,30 +995,22 @@ Environment:
_RemovePath $customSdCpp
}
}
- # Default install dir (always at %USERPROFILE%\.unsloth\studio when present). Same sentinels
- # as a custom root: an ungated run takes a hand-made one, then ~/.unsloth with the prune below.
+ # Gated like a custom root: an ungated run would delete a hand-made one, then ~/.unsloth if empty.
if ($defaultStudioHome -and (Test-Path -LiteralPath $defaultStudioHome) -and
-not (_IsStudioRoot $defaultStudioHome -ManagedDefaultRoot)) {
_Substep "refusing to remove non-Unsloth path: $defaultStudioHome" "Yellow"
- # A refused CUSTOM root is somebody else's by definition. This is our own default path,
- # where a damaged install can sit, so a studio.db here is chat history.
+ # Our own default path, so a studio.db here is chat history.
if (Test-Path -LiteralPath (Join-Path $defaultStudioHome "studio.db") -PathType Leaf) {
$script:StudioDbKept = $true
}
} elseif ($defaultStudioHome) {
_RemoveRootRecordingDb $defaultStudioHome
}
- # Default data dir. The private temp sweep goes FIRST and hands back what it kept: the primary
- # temp directory lives under this data dir, so a wholesale removal here would erase a live
- # Unsloth's %TEMP% before the sweep ever looked at its owner.pid.
+ # Temp sweep first: a wholesale data-dir removal would erase a live instance's %TEMP%.
$preservedTemp = @(_RemoveStudioPrivateTempTrees -Paths $privateTempDirs -PrimaryPath $primaryPrivateTemp)
if ($defaultDataDir) { _RemoveDataDirKeepingWslIcon $defaultDataDir -Preserve $preservedTemp }
- # The master root's own children, marker-gated rather than removed outright like the
- # ~/.unsloth ones below: <master> is a directory the user chose. The locks and .staging are
- # ours by name (prebuilt_core.py) and carry no marker. Mirrors scripts/uninstall.sh.
- # $masterRootToStop, not a fresh _MasterRoot: that resolver can read its answer from a note
- # inside a Studio tree the loop above has already removed, after which a second call returns
- # nothing and the runtime siblings are stranded.
+ # The master root's own children are marker-gated: the user chose that directory.
+ # Reuse $masterRootToStop, since its note may already be gone. Mirrors scripts/uninstall.sh.
$masterRoot = $masterRootToStop
if ($masterRoot -and (_IsUnsafeRoot $masterRoot)) {
_Substep "refusing to remove unsafe path: $masterRoot" "Yellow"
@@ -1248,45 +1030,36 @@ Environment:
".whisper.cpp.install.lock", ".audio.cpp.install.lock", ".sd.cpp.install.lock")) {
_RemoveLockFile (Join-Path $masterRoot $lockName)
}
- # The prebuilt installers SHARE <root>\.staging and prune it only when empty, so
- # anything left in it here is not ours: remove the directory only, never its contents.
+ # Shared .staging is pruned only when empty; never remove its contents.
_RemoveDirIfEmpty (Join-Path $masterRoot ".staging")
if (Test-Path -LiteralPath $masterRoot) {
- # $script:StaleLockPattern, not a glob: the shape has to be the installer's own,
- # name and numeric pid both, or a user's file in their own root is taken.
+ # The installer's exact shape only, or a user's file could be taken.
foreach ($stale in @(Get-ChildItem -LiteralPath $masterRoot -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match $script:StaleLockPattern })) {
_RemoveLockFile $stale.FullName
}
}
- # Only when nothing of the user's is left.
_RemoveDirIfEmpty $masterRoot
}
# Shared llama.cpp build + cache, siblings of studio under ~/.unsloth in default mode.
if ($defaultLlamaCpp) { _RemovePath $defaultLlamaCpp }
- # "stable-diffusion.cpp" is exactly what a git clone of leejet/stable-diffusion.cpp produces
- # and a user may keep their own checkout (or point UNSLOTH_SD_CPP_PATH) here, so require our
- # owner marker before rm: an unowned checkout or a pre-marker Unsloth build is kept.
+ # Require our marker: an upstream git clone produces the same directory name.
if ($defaultSdCpp -and (Test-Path -LiteralPath $defaultSdCpp) -and -not (Test-Path -LiteralPath (Join-Path $defaultSdCpp ".unsloth-studio-owned") -PathType Leaf)) {
_Substep "keeping sd.cpp without Unsloth owner marker: $defaultSdCpp" "Yellow"
} elseif ($defaultSdCpp) {
_RemovePath $defaultSdCpp
}
if ($defaultCache) { _RemovePath $defaultCache }
- # Isolated Node.js runtime, a sibling of studio under ~/.unsloth. Nested in env/custom mode.
if ($defaultNode) { _RemovePath $defaultNode }
if ($defaultStaging) { _RemovePath $defaultStaging }
- # Managed whisper.cpp prebuilt, a sibling of studio under ~/.unsloth. Only present when one
- # matching the pinned llama.cpp build existed at install time, so many installs lack it.
if ($defaultWhisperCpp) { _RemovePath $defaultWhisperCpp }
- # The installer always marks its tree and refuses an unmarked one, so an unmarked one is the user's.
+ # The installer always marks its tree, so an unmarked one is the user's.
if ($defaultAudioCpp -and (Test-Path -LiteralPath $defaultAudioCpp) -and -not (Test-Path -LiteralPath (Join-Path $defaultAudioCpp ".unsloth-studio-owned") -PathType Leaf)) {
_Substep "keeping audio.cpp without Unsloth owner marker: $defaultAudioCpp" "Yellow"
} elseif ($defaultAudioCpp) {
_RemovePath $defaultAudioCpp
}
- # audio.cpp lays its models out as links (copies across volumes) in unsloth-audiocpp-links beside
- # the Hugging Face hub cache (audio_cpp_files.py). The cache itself stays, as the note below says.
+ # audio.cpp model links live beside the HF hub cache; the cache itself stays.
$hfHub = if ($env:HF_HUB_CACHE) { $env:HF_HUB_CACHE }
elseif ($env:HUGGINGFACE_HUB_CACHE) { $env:HUGGINGFACE_HUB_CACHE }
elseif ($env:HF_HOME) { Join-Path $env:HF_HOME "hub" }
@@ -1295,23 +1068,19 @@ Environment:
else { $null }
$hfParent = if ($hfHub) { Split-Path -Parent $hfHub } else { $null }
if ($hfParent) { _RemovePath (Join-Path $hfParent "unsloth-audiocpp-links") }
- # The audio.cpp server's scratch home when the Studio root was unusable (audio_cpp_server.py).
- # %TEMP% is per user, and the name carries this user's, so no other account's is reached.
+ # %TEMP% is per user and the name carries this user's, so no other account is reached.
if ($env:USERNAME) {
$audioCppHome = Join-Path ([System.IO.Path]::GetTempPath()) "unsloth-audiocpp-home-$env:USERNAME"
if (Test-Path -LiteralPath $audioCppHome -PathType Container) { _RemovePath $audioCppHome }
}
- # Prebuilt install locks: every prebuilt serializes on <parent>\.<name>.install.lock
- # (prebuilt_core.py), and a stray lock keeps ~/.unsloth from being pruned below.
+ # A stray prebuilt install lock keeps ~/.unsloth from being pruned.
if ($defaultUnslothHome) {
foreach ($lockName in @(".llama.cpp.install.lock", ".node.install.lock", ".whisper.cpp.install.lock", ".audio.cpp.install.lock")) {
_RemoveLockFile (Join-Path $defaultUnslothHome $lockName)
}
- # Taking over an abandoned lock renames it to .stale.<pid> before unlinking; a crash
- # between the two strands the rename, so sweep any leftovers. -Force sees dotted names.
+ # A crash between rename and unlink strands .stale.<pid> locks.
if (Test-Path -LiteralPath $defaultUnslothHome) {
- # -match, not -Filter: the Win32 filter is unreliable for names with several dots,
- # and only the installer's exact shape is ours to remove.
+ # -match, not -Filter: the Win32 filter is unreliable with several dots.
foreach ($stale in @(Get-ChildItem -LiteralPath $defaultUnslothHome -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match $script:StaleLockPattern })) {
_RemoveLockFile $stale.FullName
@@ -1335,11 +1104,9 @@ Environment:
_RemovePath $defaultUnslothHome
}
- # Runtime data, created at first launch rather than by install.ps1: LOCALAPPDATA holds the
- # EBWebView profile (a leftover copy serves a stale frontend), APPDATA the app config dir.
+ # Created at first launch: a leftover EBWebView profile serves a stale frontend.
_Step "Removing WebView caches and app data (ai.unsloth.studio)..."
- # Count an unresolvable root as incomplete cleanup: skipping it silently would leave the
- # profile on disk while the summary reports the session as gone.
+ # An unresolvable root counts as incomplete cleanup.
foreach ($known in @(
@{ Var = $env:LOCALAPPDATA; Folder = 'LocalApplicationData' },
@{ Var = $env:APPDATA; Folder = 'ApplicationData' }
@@ -1362,8 +1129,7 @@ Environment:
if ($env:APPDATA) {
_RemovePath (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Unsloth Studio.lnk")
}
- # Invalidate the Win11 Start Menu tile cache so the removed shortcut's tile disappears instead
- # of lingering stale (mirrors install.ps1). Preserves start2.bin, the pin layout.
+ # Invalidate the Win11 Start tile cache (mirrors install.ps1); keep start2.bin, the pin layout.
try {
$smehTemp = Join-Path $env:LOCALAPPDATA "Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\TempState"
if (Test-Path -LiteralPath $smehTemp) {
@@ -1374,8 +1140,7 @@ Environment:
}
} catch { }
- # Re-sweep: the first pass may have left unsloth.ico locked by Explorer/SMEH for the native
- # shortcut; that handle is now freed. (A surviving WSL shortcut still keeps the icon.)
+ # Re-sweep: unsloth.ico may have been locked by Explorer on the first pass.
$preservedTemp = @(_RemoveStudioPrivateTempTrees -Paths $privateTempDirs -PrimaryPath $primaryPrivateTemp)
if ($defaultDataDir -and (Test-Path -LiteralPath $defaultDataDir)) {
_RemoveDataDirKeepingWslIcon $defaultDataDir -Preserve $preservedTemp
@@ -1392,9 +1157,7 @@ Environment:
$entries = $rawPath -split ';'
$kept = New-Object System.Collections.ArrayList
$removedAny = $false
- # Only remove PATH entries inside an Unsloth root we actually own. A literal
- # substring match on `unsloth_studio` would clobber unrelated user virtualenvs.
- # A root this run refused keeps its PATH entry, because it keeps its files.
+ # Only PATH entries inside a root we own; a substring match would hit user virtualenvs.
foreach ($e in $entries) {
if ([string]::IsNullOrWhiteSpace($e)) { continue }
$expanded = [Environment]::ExpandEnvironmentVariables($e).TrimEnd('\','/')
@@ -1463,19 +1226,14 @@ Environment:
Write-Host " signed-in session and local chat history may still be on disk. Remove"
Write-Host " those paths by hand to clear them."
} elseif ($script:StudioDbRemoved) {
- # Scoped to what was removed: a bare run never discovers a coexisting env-mode root.
Write-Host "Note: this also removed the app's WebView data and the studio.db it found, so"
Write-Host " the desktop app's session and the chat history in the install(s) removed"
Write-Host " above are gone."
} else {
- # No studio.db was deleted, so only the WebView-local data is accounted for: an env-mode
- # install this run never discovered still has its keys and history.
Write-Host "Note: this also removed the app's WebView data, so the desktop app's session"
Write-Host " is gone. A browser session is not affected: its tokens live in the same"
Write-Host " localStorage as the API keys below."
if ($script:StudioDbKept) {
- # Named, and with no advice to delete it: the gate kept it precisely because it
- # does not look like ours.
Write-Host " $defaultStudioHome carries no Unsloth install marker, so it was"
Write-Host " left alone. The studio.db inside it is still there; look at that"
Write-Host " directory yourself before deciding what to do with it."
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 996ca9b8406..e89db921357 100755
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -2,7 +2,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
# Unsloth Studio uninstaller (macOS / Linux / WSL). Run --help for details.
-# Custom roots (UNSLOTH_STUDIO_HOME / STUDIO_HOME) come from studio.conf.
# Usage: curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.sh | sh
set -e
@@ -52,14 +51,12 @@ Environment:
EOF
}
-# Stop an Unsloth server via its PID file (written by install.sh's _spawn_terminal).
_kill_pid_file() {
_pid_file="$1"
[ -f "$_pid_file" ] || return 0
_pid=$(sed -n '1s/[^0-9].*//p' "$_pid_file" 2>/dev/null || true)
if [ -n "$_pid" ] && kill -0 "$_pid" 2>/dev/null; then
kill -TERM "$_pid" 2>/dev/null || true
- # Wait up to 10s for graceful shutdown.
_i=0
while kill -0 "$_pid" 2>/dev/null && [ "$_i" -lt 20 ]; do
sleep 0.5
@@ -75,12 +72,8 @@ _pkill_escape() {
printf '%s' "$1" | sed -e 's:[][\\.^$*+?{|}()/]:\\&:g'
}
-# sd.cpp roots whose sd-server has to be stopped: the default $HOME/.unsloth/stable-diffusion.cpp,
-# plus per custom root the nested <root>/stable-diffusion.cpp and the legacy <parent> sibling.
-# A resident sd-server survives unlinking its binary, and the custom root is removed wholesale
-# below, so without the nested path the tree goes and the server keeps running.
-# The owner marker gates only the paths that SURVIVE when unowned (the default and the sibling), so
-# an unrelated checkout keeps its server; the nested path of a root this run deletes is not gated.
+# The nested <root>/stable-diffusion.cpp is not marker-gated since this run deletes that root;
+# the default and legacy sibling paths survive when unowned, so they are.
_owned_sd_cpp_roots() {
_default_sd="$HOME/.unsloth/stable-diffusion.cpp"
[ -f "$_default_sd/.unsloth-studio-owned" ] && printf '%s\n' "$_default_sd"
@@ -98,10 +91,8 @@ _owned_sd_cpp_roots() {
done
}
-# Every root an older build could have hung its sd.cpp sibling off: the canonicalized custom roots
-# and the lexical ones. They differ only when the Unsloth home is itself a symlink, and there only
-# the lexical form (what the old plain `dirname` produced) finds the tree. Every use is gated on
-# the owner marker, which is what keeps an unrelated checkout at either path safe.
+# Lexical roots differ from canonical ones only when the Unsloth home is a symlink;
+# old builds used plain dirname.
_sd_cpp_sibling_bases() {
{
_custom_studio_roots 2>/dev/null
@@ -109,8 +100,7 @@ _sd_cpp_sibling_bases() {
} | awk '!seen[$0]++'
}
-# pkill resident sd-server / sd-cli under an owned sd.cpp root before that tree is removed (a live
-# native server keeps running after its binary is unlinked). Anchored on the owned root.
+# A live sd-server keeps running after its binary is unlinked, so stop it first.
_stop_owned_sd_cpp_processes() {
_signal="$1"
command -v pkill >/dev/null 2>&1 || return 0
@@ -122,8 +112,7 @@ _stop_owned_sd_cpp_processes() {
done
}
-# Numeric owner of $HOME, empty if unresolvable. Not always the caller: macOS sudo keeps
-# HOME (env_keep), so the home stays the invoking user's while euid is 0.
+# Owner of $HOME, not the caller: macOS sudo keeps HOME, so euid can be 0 here.
_home_uid() {
# -L: stat lstats by default, so a root-owned link to a user home would read as uid 0.
_hu=$(stat -L -c %u "$HOME" 2>/dev/null || stat -L -f %u "$HOME" 2>/dev/null || true)
@@ -132,8 +121,7 @@ _home_uid() {
printf '%s\n' "$_hu"
}
-# Run "$@" as the $HOME owner when we are root and it is someone else, so per-user daemons
-# see the right domain. Plain "$@" otherwise, which is every non-elevated run.
+# Run as the $HOME owner when root, so per-user daemons see the right domain.
_run_as_home_owner() {
_ro=$(_home_uid)
if [ "$(id -u 2>/dev/null || echo 0)" = "0" ] && [ -n "$_ro" ] && [ "$_ro" != "0" ] &&
@@ -144,8 +132,7 @@ _run_as_home_owner() {
fi
}
-# Is the desktop app running? Only reached when there is no pkill to ask, so read /proc.
-# Scoped to the owner of the $HOME being cleared, matching the pkill -u call below.
+# Only reached without pkill. Scoped to the $HOME owner, matching pkill -u below.
_studio_app_running() {
[ -d /proc ] || return 1
_sar_uid=$(_home_uid)
@@ -163,7 +150,6 @@ _studio_app_running() {
}
_pkill_studio() {
- # Prefer PID files written by _spawn_terminal so we only touch our own installs.
for _data_dir in "$HOME/.local/share/unsloth" $(_custom_studio_data_dirs); do
[ -d "$_data_dir" ] || continue
for _pf in "$_data_dir"/studio-*.pid; do
@@ -172,8 +158,7 @@ _pkill_studio() {
done
if ! command -v pkill >/dev/null 2>&1; then
- # No procps (install.sh never requires it): the PID sweep above is all we have. A live
- # app re-creates the profile right after the delete, so do not claim a clean removal.
+ # No procps: a live app re-creates the profile after the delete, so do not claim a clean removal.
if _studio_app_running; then
echo " pkill not found and Unsloth Studio is running; close it and re-run" >&2
_set_marker "$_REMOVE_FAILED_FLAG"
@@ -181,8 +166,7 @@ _pkill_studio() {
return 0
fi
- # Scope fallback patterns to the install roots we are removing so a
- # different Unsloth install (different UNSLOTH_STUDIO_HOME) is not touched.
+ # Scope patterns to the roots being removed so a different install is not touched.
_kill_roots="$HOME/.unsloth/studio"
_roots_from_conf=$(_custom_studio_roots 2>/dev/null || true)
[ -n "$_roots_from_conf" ] && _kill_roots="$_kill_roots
@@ -192,7 +176,6 @@ $_roots_from_conf"
[ -n "$_root" ] || continue
[ -d "$_root" ] || continue
_re=$(_pkill_escape "$_root")
- # `unsloth studio` default-port, `-p N` and `--port N` forms, anchored on the venv path.
for _pat in \
"${_re}/unsloth_studio/bin/[^ ]* studio( |\$|.*-p[ =][0-9])" \
"${_re}/unsloth_studio/bin/[^ ]* studio.*--port[ =][0-9]" \
@@ -215,15 +198,12 @@ $_roots_from_conf"
done
done
- # sd-server / sd-cli survive unlinking their binary, so stop them before their trees go.
_stop_owned_sd_cpp_processes TERM
sleep 0.5
_stop_owned_sd_cpp_processes KILL
- # The app's WebView helpers re-create the caches removed below, so it has to die here. -x is
- # exact, so the "unsloth" CLI shim never matches. -u takes the owner of the $HOME being
- # cleared, not the caller (macOS sudo keeps HOME), so a root run spares other users and an
- # unknown owner skips entirely. Numeric uid and signal-first for BSD pkill (signal in argv[1]).
+ # WebView helpers re-create caches, so kill the app. -x spares the CLI shim; -u is the $HOME owner
+ # (macOS sudo keeps HOME). Numeric uid and signal first for BSD pkill.
_studio_uid=$(_home_uid)
if [ -n "$_studio_uid" ]; then
pkill -TERM -x -u "$_studio_uid" unsloth-studio 2>/dev/null || true
@@ -232,16 +212,9 @@ $_roots_from_conf"
fi
}
-# Summary state in files, not variables: custom roots are removed inside a pipeline subshell,
-# where an assignment would never reach the summary.
-# remove-failed an rm failed, or a root was skipped while still holding data
-# db-removed a removed install root actually held studio.db
-# db-kept the default root was REFUSED and still holds studio.db. Its own flag, not
-# remove-failed: nothing failed, so "remove those paths by hand" is wrong here.
-# studio.db holds the chat history (backend/storage/studio_db.py), not the provider API keys:
-# providers_db.py keeps those in the browser's localStorage only. An env-mode install keeps it in
-# a custom root a bare run cannot discover, so claim the history is gone only if one was deleted.
-# mktemp -d, not a $TMPDIR name: private (0700) and unpredictable, so nothing else can pre-create.
+# Markers in files, not variables: custom roots are removed in a pipeline subshell.
+# db-kept is separate from remove-failed: the refused default root failed nothing.
+# mktemp -d: private (0700) and unpredictable, so nothing else can pre-create the markers.
_MARKER_DIR=$(mktemp -d 2>/dev/null || true)
_REMOVE_FAILED_FLAG=""
_DB_REMOVED_FLAG=""
@@ -258,17 +231,14 @@ if [ -n "$_MARKER_DIR" ] && [ -d "$_MARKER_DIR" ]; then
_UV_SAW_MARKER_FLAG="$_MARKER_DIR/uv-saw-marker"
fi
-# `printf`, never `: > "$f"`: `:` is a POSIX special builtin, so a redirection error on it kills a
-# non-interactive shell outright (dash, busybox ash) and `|| true` does not stop it.
+# printf, not `: >`: a redirect error on a special builtin kills dash/ash despite || true.
_set_marker() {
[ -n "$1" ] || return 0
printf '' > "$1" 2>/dev/null || true
return 0
}
_marker_set() { [ -n "$1" ] && [ -f "$1" ]; }
-# No marker storage means no record of what failed, so the summary must not claim success.
-# Re-checked, not trusted from startup: the dir can vanish or lose write access mid-run, after
-# which _set_marker silently drops every failure.
+# Re-checked each time: the dir can vanish mid-run and _set_marker would silently drop failures.
_markers_unavailable() {
[ -n "$_MARKER_DIR" ] || return 0
[ -d "$_MARKER_DIR" ] || return 0
@@ -276,11 +246,9 @@ _markers_unavailable() {
return 1
}
-# install.sh records its uv cache in <root>/cache/uv-cache-dir. One under a removed root goes with
-# it; any other is shared and stays. Read before any root is deleted.
+# Read before any root is deleted; a uv cache outside removed roots is shared and stays.
_uv_cache_under_any_root() {
while IFS= read -r _uv_r; do
- # A symlinked root is only unlinked, so its target (and any cache in it) stays.
[ -L "$_uv_r" ] && continue
case "$1" in "$_uv_r"|"$_uv_r"/*) return 0 ;; esac
done < "$_UV_ROOTS_FILE"
@@ -311,7 +279,7 @@ _uv_print_leftover_notes() {
if [ -s "$_UV_LEFTOVER_FILE" ]; then
awk '!seen[$0]++' "$_UV_LEFTOVER_FILE" 2>/dev/null | while IFS= read -r _uv_path; do
[ -n "$_uv_path" ] || continue
- # --cache-dir: a bare `uv cache clean` cleans whichever cache uv resolves now.
+ # Explicit --cache-dir: bare `uv cache clean` cleans whatever cache uv resolves now.
_uv_q=$(printf '%s' "$_uv_path" | sed "s/'/'\\\\''/g")
echo "Note: the uv package cache at $_uv_path was left in place (it may be shared with other tools)."
echo " Free it with: uv cache clean --cache-dir '$_uv_q'"
@@ -322,7 +290,7 @@ _uv_print_leftover_notes() {
fi
}
-# EXIT, not a line at the end of main: --help, a bad argument and `set -e` all skip that.
+# EXIT trap: --help, a bad argument and set -e all skip an end-of-main cleanup.
_cleanup_markers() {
if [ -n "$_MARKER_DIR" ]; then
rm -rf "$_MARKER_DIR" 2>/dev/null || true
@@ -330,8 +298,7 @@ _cleanup_markers() {
}
trap _cleanup_markers EXIT
-# A removal that got part way can take the sentinels and then fail on a locked child, leaving a
-# root the next run's gate would refuse. Put the marker back so a retry recognises it.
+# A partial removal can drop the sentinels; restore the marker so a retry's gate accepts the root.
_restore_owner_marker() {
[ -d "$1" ] || return 0
if [ -e "$1/.unsloth-studio-owned" ] || [ -L "$1/.unsloth-studio-owned" ]; then return 0; fi
@@ -339,11 +306,8 @@ _restore_owner_marker() {
return 0
}
-# Remove an install root and record whether its studio.db really went with it. The check runs on
-# the RESOLVED path: a relocated install (~/.unsloth/studio a symlink to another disk) passes
-# `-f "$root/studio.db"` through the link, but `rm -rf` unlinks only the link, after which the
-# path reads as absent either way. Verifying rather than chasing the link is deliberate: following
-# a symlink out of the expected location to `rm -rf` its target is what the deny lists prevent.
+# The db check uses the resolved path: rm -rf only unlinks a symlinked root.
+# Never follow the link to delete its target; that is what the deny lists prevent.
_remove_root_recording_db() {
_rrd_root="$1"
# shellcheck disable=SC1007
@@ -353,8 +317,7 @@ _remove_root_recording_db() {
_rrd_db="$_rrd_real/studio.db"
if [ -f "$_rrd_db" ]; then
_rrd_had_db=1
- # The db itself can be a symlink out of the tree: -f follows it but the rm unlinks only
- # the link, so track where the bytes are. readlink without -f (BSD got it in macOS 12.3).
+ # A symlinked db survives rm of the link. No readlink -f (BSD lacks it before macOS 12.3).
if [ -L "$_rrd_db" ]; then
_rrd_link=$(readlink "$_rrd_db" 2>/dev/null || true)
if [ -n "$_rrd_link" ]; then
@@ -373,7 +336,6 @@ _remove_root_recording_db() {
_restore_owner_marker "$_rrd_root"
if [ "$_rrd_had_db" = 1 ]; then
if [ -f "$_rrd_db" ]; then
- # Only the link went, or the delete failed: the data is still on disk.
_set_marker "$_REMOVE_FAILED_FLAG"
else
_set_marker "$_DB_REMOVED_FLAG"
@@ -389,17 +351,13 @@ _remove_path() {
echo " removed: $_p"
else
echo " could not remove: $_p" >&2
- # A marker file, not a variable: custom roots are removed in a pipeline subshell.
_set_marker "$_REMOVE_FAILED_FLAG"
fi
fi
}
-# An install lock, and only an install lock. prebuilt_core.install_lock creates these with
-# O_CREAT | O_EXCL, so a lock is always a regular file: a directory or a link at that name is
-# the user's, and in a master root they chose _remove_path would rm -rf it. -L before -f, which
-# is true for a link to a file. uninstall.ps1's _RemoveLockFile excludes reparse points for the
-# same reason, and the two halves of one rule have to agree.
+# Locks are always regular files (O_CREAT|O_EXCL); a dir or link here is the user's.
+# Must agree with uninstall.ps1's _RemoveLockFile.
_remove_lock_file() {
_rlf="$1"
if [ -L "$_rlf" ]; then
@@ -411,28 +369,16 @@ _remove_lock_file() {
fi
}
-# $1 override, $2 default. A relative override is invalid per XDG and dropped by dirs (which
-# Tauri resolves through), so honouring one would spare the real data and rm -rf under our cwd.
+# A relative XDG override is invalid and ignored by Tauri, so honouring it would rm under cwd.
_xdg_dir() {
case "$1" in /*) printf '%s\n' "$1" ;; *) printf '%s\n' "$2" ;; esac
}
-# Accept as Unsloth root only if an Unsloth sentinel exists (matching install.sh's env-mode
-# ownership guard). A bare unsloth_studio/ directory is NOT enough: require the install-time owner
-# marker so a user directory that happens to contain such a folder is safe.
-# Is $1 a Python venv? What the gate reads out of one is evidence only if the directory really
-# is one; a bare file at that path is somebody else's.
-# A sentinel this gate may trust. Deliberately just -f, following links: refusing one that is a
-# link, or that sits inside a linked directory, buys nothing here and costs a supported install.
-# It buys nothing because anyone who can plant a link at that path can plant a plain file there
-# instead, which this has always accepted. It costs a supported install because relocating a
-# multi-gigabyte venv with a symlink leaves a REAL marker behind a link, and refusing it strands
-# the install, which is the failure this whole gate exists to prevent. The link test belongs in
-# install.sh's _claim_sentinel, where following one would TRUNCATE the target rather than read it.
+# Root accepted only with an install-time owner marker (matches install.sh's env-mode guard).
+# Plain -f, following links: a relocated venv keeps a real marker behind a link.
_is_owner_marker() { [ -f "$1" ]; }
-# No -L here either, and for the same reason: a relocated venv is still a venv. The leftover scan
-# below rejects links on its own, where the name came from a glob rather than from us.
+# No -L: a relocated venv is still a venv.
_is_venv_dir() {
[ -d "$1" ] || return 1
[ -f "$1/pyvenv.cfg" ] && return 0
@@ -440,13 +386,10 @@ _is_venv_dir() {
return 1
}
-# The exact name an installer gives a moved-aside venv: <prefix>.<stamp>.<pid>[.<n>], with a
-# 14-digit stamp or install.sh's "time" date(1) fallback. install.sh keeps every other spelling
-# as the user's data (_studio_venv_rollback_must_be_preserved); do not be looser.
+# Exact installer name <prefix>.<stamp>.<pid>[.<n>]; must not be looser than install.sh.
_is_installer_leftover_name() {
_l=${1##*/}
- # Only the rollback name carries a collision counter (install.sh:823); .venv.invalid is
- # written once per run, so it takes no suffix.
+ # Only the rollback name carries a collision counter; .venv.invalid takes no suffix.
_l_suffix_ok=false
case "$_l" in
unsloth_studio.rollback.*) _l=${_l#unsloth_studio.rollback.}; _l_suffix_ok=true ;;
@@ -473,12 +416,9 @@ _is_installer_leftover_name() {
_is_studio_root() {
_r="$1"
- # $2 = "managed": $_r is the default root install.sh manages, $HOME/.unsloth/studio.
_managed="${2:-}"
[ -n "$_r" ] || return 1
- # install.sh writes the first when it creates the root, before the uv cache and long before
- # the venv, so a partial install identifies itself instead of being guessed at. The last is
- # the legacy venv name, which only install.sh writes.
+ # install.sh writes the marker before the venv, so partial installs identify themselves.
_is_owner_marker "$_r/.unsloth-studio-owned" && return 0
_is_owner_marker "$_r/share/studio.conf" && return 0
_is_owner_marker "$_r/unsloth_studio/.unsloth-studio-owned" && return 0
@@ -487,20 +427,14 @@ _is_studio_root() {
_t=$(readlink "$_r/bin/unsloth" 2>/dev/null || true)
case "$_t" in *unsloth_studio/bin/unsloth) return 0 ;; esac
fi
- # All a pre-marker install has left is bin/unsloth inside the venv, pip's console script,
- # which ANY venv with the wheel has: proof only at the managed root, which install.sh:2987
- # also makes the only root that can hold the layout, or a stale UNSLOTH_STUDIO_HOME deletes
- # the project it points at.
+ # bin/unsloth alone is weak proof (any venv with the wheel has it), so only trust it at the managed root.
[ "$_managed" = managed ] || return 1
for _v in unsloth_studio .venv; do
_is_venv_dir "$_r/$_v" || continue
[ -f "$_r/$_v/bin/unsloth" ] && return 0
done
- # An install that died between moving the old venv aside (install.sh:3027, :819) and writing
- # the marker (install.sh:3190) leaves only these, and only install.sh makes either name,
- # always by renaming a venv.
+ # An install that died between moving the venv aside and writing the marker leaves only these.
for _p in "$_r"/unsloth_studio.rollback.* "$_r"/.venv.invalid.*; do
- # Never a link: install.sh refuses to prune a rollback symlink either.
[ -L "$_p" ] && continue
_is_installer_leftover_name "$_p" || continue
_is_venv_dir "$_p" && return 0
@@ -519,38 +453,21 @@ _is_unsafe_root() {
return 1
}
-# Print share/ dirs of known custom roots (where PID files live).
_custom_studio_data_dirs() {
_custom_studio_roots 2>/dev/null | while IFS= read -r _r; do
[ -d "$_r/share" ] && printf '%s\n' "$_r/share"
done
}
-# Resolve a custom install root from any of:
-# 1. UNSLOTH_STUDIO_HOME / STUDIO_HOME env vars at uninstall time
-# 2. Default-mode studio.conf at $HOME/.local/share/unsloth/studio.conf
-# 3. Env-mode studio.conf at $<root>/share/studio.conf (discovered via 1)
-# install.sh writes UNSLOTH_EXE='<root>/unsloth_studio/bin/unsloth', so the install root is three
-# dirnames up. Each discovered non-default root is printed on its own line, de-duplicated.
-# The master root UNSLOTH_HOME names, or empty. studio/ is its child and llama.cpp, node and
-# whisper.cpp are its other children, so removing the Studio root alone strands them. Stripped
-# and tilde-expanded like storage_roots.unsloth_home() and studio/setup.sh, or a padded value
-# would name a directory neither install nor uninstall agrees on.
+# The master root UNSLOTH_HOME names, or empty. Trimmed and tilde-expanded like
+# storage_roots.unsloth_home().
_master_root() {
_mr_from_note=
_mr=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
- # The note setup.sh leaves in the Studio tree, when this run has no UNSLOTH_HOME of its own:
- # `UNSLOTH_HOME=/mnt/portable unsloth studio update` leaves nothing in the environment, so
- # without it an uninstall stranded the runtimes. The deny list and the marker gate still
- # apply, so a stale note licenses nothing the environment could not.
- #
- # Only the Studio root this run is about, in studio_root()'s precedence and with no falling
- # through: with two installs on one box, a legacy note otherwise won here while the removal
- # worked on the named tree, so the run deleted one Studio and the OTHER install's runtimes.
+ # Fall back to the note setup.sh leaves in the Studio tree, only for the root this run targets,
+ # in studio_root() precedence, or two installs could cross-delete runtimes.
if [ -z "$_mr" ]; then
- # Trimmed as setup.sh trimmed them when it chose where to write the note: appending to
- # a padded UNSLOTH_STUDIO_HOME looked somewhere that does not exist, so the note was
- # never found while the loop below still removed the tree.
+ # Trimmed as setup.sh trims it, or a padded value never finds the note.
_mr_ush=$(printf '%s' "${UNSLOTH_STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
_mr_sh=$(printf '%s' "${STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_mr_ush" ]; then
@@ -558,11 +475,8 @@ _master_root() {
elif [ -n "$_mr_sh" ]; then
_mr_roots="$_mr_sh"
else
- # No override, so the root install.sh recorded in the default-mode studio.conf, then
- # the legacy tree: with a bare environment that conf is the only way to find a
- # <master>/studio at all. Read here, not through _custom_studio_roots, which calls
- # back into this function. UNSLOTH_EXE='<root>/unsloth_studio/bin/unsloth', so the
- # root is three dirnames up; apostrophes arrive escaped as '\''.
+ # Not via _custom_studio_roots, which calls back into this function. Root is three dirnames
+ # up from UNSLOTH_EXE; apostrophes arrive escaped as '\''.
_mr_roots=""
_mr_dconf="$HOME/.local/share/unsloth/studio.conf"
if [ -f "$_mr_dconf" ]; then
@@ -581,11 +495,8 @@ $HOME/.unsloth/studio"
[ -n "$_mr_studio" ] || continue
_mr_conf="${_mr_studio}/share/.unsloth-master-root"
[ -f "$_mr_conf" ] || continue
- # One line, and REFUSED when there is a second. storage_roots.py and the CLI both
- # strip the WHOLE file, so a two-line note is not a directory to them and they
- # decline it, while taking line 1 here authorised removing <master>/llama.cpp, node,
- # whisper.cpp and stable-diffusion.cpp: a note no runtime reader honours must not
- # license a delete. A trailing newline is not a second line.
+ # A multi-line note is refused: storage_roots.py and the CLI reject it too, so it
+ # must not license a delete.
if [ -n "$(sed -n '2,$p' "$_mr_conf" 2>/dev/null | tr -d '[:space:]')" ]; then
continue
fi
@@ -605,26 +516,15 @@ $HOME/.unsloth/studio"
"~/"*) _mr="$HOME/${_mr#'~/'}" ;;
esac
# shellcheck disable=SC1007
- # || _mr_canon="": a bare assignment takes the substitution's exit status under set -e, and
- # a root already gone or on a disconnected drive is the ordinary case here, which killed the
- # whole run. bash hides this by clearing errexit inside command substitution; dash and POSIX
- # `sh`, which the advertised `| sh` one-liner uses, do not.
+ # || fallback: dash/POSIX sh apply set -e to a failed substitution in an assignment.
_mr_canon=$(CDPATH= cd -P -- "$_mr" 2>/dev/null && pwd -P) || _mr_canon=""
[ -n "$_mr_canon" ] && _mr="$_mr_canon"
- # A note must describe the tree it was found in: copy a Studio tree from master root A to B
- # and uninstall B, and the copied note still names A, whose runtimes carry the same owner
- # markers -- so the gates below would delete the ORIGINAL install's. Containment, not an
- # exact <root>/studio match, since the flat layout is supported. An explicit UNSLOTH_HOME
- # skips all of this: that is the user speaking, not a file on disk.
+ # A note must describe the tree it was found in, or a copied tree would delete the original's runtimes.
+ # An explicit UNSLOTH_HOME skips this check.
if [ "${_mr_from_note:-}" = 1 ]; then
_mr_here=$(CDPATH= cd -P -- "$_mr_studio" 2>/dev/null && pwd -P) || _mr_here=""
- # A note found in the ordinary ~/.unsloth/studio install is declined outright, whatever
- # it records, which is the rule storage_roots._is_legacy_studio_tree and the CLI already
- # apply. Containment alone is not enough here: $HOME contains the legacy tree, so a note
- # naming it passed, _custom_studio_roots then emitted "$HOME/studio", and uninstalling
- # the legacy install accepted a SECOND marked install there as a root to remove, taking
- # its database and outputs with it. The deny list does not catch that -- it refuses
- # $HOME as a master root, not the separate Studio candidate derived from it.
+ # A note inside ~/.unsloth/studio is declined outright, matching
+ # storage_roots._is_legacy_studio_tree.
_mr_legacy_studio=$(CDPATH= cd -P -- "$HOME/.unsloth/studio" 2>/dev/null && pwd -P) \
|| _mr_legacy_studio="$HOME/.unsloth/studio"
[ "$_mr_here" != "$_mr_legacy_studio" ] || return 0
@@ -639,23 +539,20 @@ $HOME/.unsloth/studio"
}
_custom_studio_roots() {
- # $1 = "lexical": skip the canonicalization (see the legacy sd.cpp sibling below). Reset on
- # every call, so a plain call is never affected by a preceding lexical one.
+ # $1 = "lexical" skips canonicalization; reset on every call.
_studio_roots_lexical="${1:-}"
_seen=""
_emit() {
_r="$1"
[ -z "$_r" ] && return 0
- # Tilde expansion (env vars are not subject to it on quoted assignment), matching
- # install.sh's _resolve_studio_destinations. The literal "~/" pattern is intentional.
+ # Tilde expansion, matching install.sh's _resolve_studio_destinations.
# shellcheck disable=SC2088
case "$_r" in
"~") _r="$HOME" ;;
"~/"*) _r="$HOME/${_r#'~/'}" ;;
esac
- # Canonicalize so syntactic variants ($HOME/../$USER, trailing slash) resolve to the same
- # path and hit the _is_unsafe_root deny list. Skipped for the lexical pass, which rebuilds
- # the path an older build derived with a plain dirname (see _sd_cpp_sibling_bases).
+ # Canonicalize so variants hit the _is_unsafe_root deny list; the lexical pass
+ # rebuilds old dirname paths.
if [ "${_studio_roots_lexical:-}" != "lexical" ]; then
# shellcheck disable=SC1007
_canon=$(CDPATH= cd -P -- "$_r" 2>/dev/null && pwd -P)
@@ -668,17 +565,12 @@ _custom_studio_roots() {
}
_from_conf() {
[ -f "$1" ] || return 0
- # Tolerate paths containing apostrophes (install.sh emits '\'' for them).
_exe=$(sed -n "s/^UNSLOTH_EXE='\(.*\)'\$/\1/p" "$1" | head -n1)
_exe=$(printf '%s' "$_exe" | sed "s/'\\\\''/'/g")
[ -n "$_exe" ] || return 0
_emit "$(dirname "$(dirname "$(dirname "$_exe")")")"
}
- # Mirror install.sh's precedence: UNSLOTH_STUDIO_HOME wins, STUDIO_HOME is ignored when both
- # are set, or uninstalling install A could also delete install B from a leftover STUDIO_HOME.
- # Trimmed, as storage_roots.studio_root() trims them: a whitespace-only override is unset to
- # every resolver, but a bare -n test called it present and suppressed the master-root branch
- # below, leaving <UNSLOTH_HOME>/studio installed.
+ # Mirror install.sh: UNSLOTH_STUDIO_HOME wins over STUDIO_HOME. Trimmed like storage_roots.studio_root().
_ush=$(printf '%s' "${UNSLOTH_STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
_sh=$(printf '%s' "${STUDIO_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_ush" ]; then
@@ -688,8 +580,7 @@ _custom_studio_roots() {
_emit "$_sh"
_from_conf "$_sh/share/studio.conf"
elif [ -n "$(_master_root)" ]; then
- # Last, as in storage_roots.studio_root(): UNSLOTH_HOME names the tree, and the two
- # above name this exact directory, so either of them wins outright.
+ # Last, as in storage_roots.studio_root().
_emit "$(_master_root)/studio"
_from_conf "$(_master_root)/studio/share/studio.conf"
fi
@@ -697,9 +588,7 @@ _custom_studio_roots() {
_from_conf "$HOME/.local/share/unsloth/studio.conf"
}
-# Remove $HOME/.local/bin/unsloth only if it is the symlink install.sh created into the studio
-# venv. A pip-installed `unsloth` CLI is a regular file: leave it alone rather than wiping an
-# unrelated install.
+# Remove the CLI shim only if it is install.sh's symlink; a pip-installed unsloth is a regular file.
_remove_cli_shim() {
_shim="$HOME/.local/bin/unsloth"
[ -L "$_shim" ] || return 0
@@ -710,8 +599,7 @@ _remove_cli_shim() {
esac
}
-# Print key $2 from the Info.plist $1. PlistBuddy also reads binary plists;
-# the awk fallback covers XML on hosts without it.
+# PlistBuddy reads binary plists; awk fallback handles XML only.
_plist_string() {
[ -f "$1" ] || return 1
if [ -x /usr/libexec/PlistBuddy ]; then
@@ -721,21 +609,18 @@ _plist_string() {
f && /<string>/ { sub(/.*<string>/, ""); sub(/<\/string>.*/, ""); print; exit }' "$1"
}
-# True when the bundle $1 is the packaged desktop app carrying bundle id $2.
-# install.sh's shell launcher shares that id, so exclude it by its executable.
+# install.sh's shell launcher shares the bundle id, so exclude it by executable.
_owns_bundle_id() {
[ -d "$1" ] || return 1
[ "$(_plist_string "$1/Contents/Info.plist" CFBundleIdentifier)" = "$2" ] || return 1
[ "$(_plist_string "$1/Contents/Info.plist" CFBundleExecutable)" != "launch-studio" ]
}
-# Path of the installed app owning bundle id $1, empty if there is none. A renamed bundle or a
-# nested one ("/Applications/AI & ML/Unsloth.app") is supported, so match on the identifier.
+# Match on bundle id: renamed and nested bundles are supported.
_bundle_id_owner() {
# Overridable so tests can point the scan at a fixture dir.
_bio_apps="${UNSLOTH_APPLICATIONS_DIR:-/Applications}"
- # Spotlight finds it anywhere on disk. Skipped for a fixture scan: a real
- # install on the machine running the tests must not change the result.
+ # Skipped for fixture scans so a real install does not change test results.
if [ -z "${UNSLOTH_APPLICATIONS_DIR:-}" ] && command -v mdfind >/dev/null 2>&1; then
_bio_hit=$(mdfind "kMDItemCFBundleIdentifier == '$1'" 2>/dev/null |
while IFS= read -r _bio_app; do
@@ -746,8 +631,7 @@ _bundle_id_owner() {
return 0
fi
fi
- # Spotlight can be off or still indexing, so walk the usual roots too. No depth cap:
- # -prune stops the walk at each bundle, so nesting is free and bundles are never entered.
+ # Spotlight can be off or indexing. -prune stops at each bundle, so no depth cap is needed.
find "$_bio_apps" "$HOME/Applications" -name '*.app' -type d -prune -print 2>/dev/null |
while IFS= read -r _bio_app; do
if _owns_bundle_id "$_bio_app" "$1"; then
@@ -758,7 +642,6 @@ _bundle_id_owner() {
}
_unsloth_uninstall_main() {
- # Reject unknown arguments before destructive work.
for _arg in "$@"; do
case "$_arg" in
-h|--help) _usage; return 0 ;;
@@ -780,12 +663,10 @@ _unsloth_uninstall_main() {
_sd_dir="$(_xdg_dir "${XDG_CONFIG_HOME:-}" "$HOME/.config")/systemd/user"
_sd_unit="$_sd_dir/unsloth-studio.service"
if [ ! -f "$_sd_unit" ] && command -v systemctl >/dev/null 2>&1; then
- # HOME redirected: ask the manager where the unit it loaded lives.
_sd_frag=$(systemctl --user show -p FragmentPath --value unsloth-studio.service 2>/dev/null || true)
case "$_sd_frag" in */unsloth-studio.service) _sd_unit="$_sd_frag"; _sd_dir="${_sd_frag%/*}" ;; esac
fi
if [ ! -f "$_sd_unit" ] && command -v getent >/dev/null 2>&1; then
- # No manager to ask: its HOME is the passwd one.
_sd_pw=$(getent passwd "$(id -un 2>/dev/null)" 2>/dev/null | cut -d: -f6)
case "$_sd_pw" in /*) _sd_dir="$_sd_pw/.config/systemd/user"; _sd_unit="$_sd_dir/unsloth-studio.service" ;; esac
fi
@@ -808,28 +689,21 @@ _unsloth_uninstall_main() {
echo "Removing data and install directories..."
_uv_collect_from_install_roots
- # Resolved ONCE, before anything is deleted: _master_root can read its answer from a note
- # inside a Studio tree the loop below removes, after which the runtime siblings are stranded.
+ # Resolved once before deletion: the note it may read lives in a tree the loop removes.
_MASTER_ROOT_SAVED="$(_master_root)"
_custom_studio_roots | while IFS= read -r _custom_root; do
[ -n "$_custom_root" ] || continue
if _is_unsafe_root "$_custom_root"; then
echo " refusing to remove unsafe path: $_custom_root" >&2
- # install.sh accepts any writable root, so a real install can sit under a deny-listed
- # path (/var/tmp/studio). Nothing is deleted and it holds studio.db, so say so.
+ # A real install can sit under a deny-listed path; it still holds studio.db, so flag it.
[ -d "$_custom_root" ] && _set_marker "$_REMOVE_FAILED_FLAG"
continue
fi
if ! _is_studio_root "$_custom_root"; then
- # Not ours, so skipping leaves none of the user's data behind.
echo " refusing to remove non-Unsloth path: $_custom_root" >&2
continue
fi
- # The flat layout, both variables naming one directory: _remove_root_recording_db takes
- # a marked Studio root WHOLE, so without this the user-chosen master root went with the
- # install, which is the hole in the rule that every other child below is marker-gated
- # for. Kept rather than pruned, since data left behind is recoverable and printed.
- # Canonicalised on both sides, or a symlinked path compares unequal to itself.
+ # Flat layout (both variables name one dir): do not take the user-chosen master root with it.
_crf_canon=$(CDPATH= cd -P -- "$_custom_root" 2>/dev/null && pwd -P) || _crf_canon=""
[ -n "$_crf_canon" ] || _crf_canon="$_custom_root"
_crf_master="$_MASTER_ROOT_SAVED"
@@ -843,12 +717,8 @@ _unsloth_uninstall_main() {
fi
unset _crf_canon _crf_master
_remove_root_recording_db "$_custom_root"
- # Native diffusion now installs UNDER the custom root, so the removal above already took
- # it. Older builds put it BESIDE the root at <parent>/stable-diffusion.cpp, which removing
- # the root alone would leave behind. <parent> is user-chosen and "stable-diffusion.cpp" is
- # exactly what `git clone` of the upstream project produces, so require our owner marker
- # (install_sd_cpp_prebuilt) before rm: an unowned checkout or a pre-marker build is kept,
- # never a user file deleted. The derived parent path gets the deny-list check too.
+ # Older builds put sd.cpp beside the root; require our owner marker, since a git
+ # clone has the same name.
_custom_sd_cpp="$(dirname "$_custom_root")/stable-diffusion.cpp"
if _is_unsafe_root "$_custom_sd_cpp"; then
echo " refusing to remove unsafe path: $_custom_sd_cpp" >&2
@@ -858,19 +728,14 @@ _unsloth_uninstall_main() {
_remove_path "$_custom_sd_cpp"
fi
done
- # The lexical parent as well. A home that is itself a symlink has its old sd.cpp tree beside
- # the LINK, which the canonicalized loop above never saw. Marker only, no "keeping" notice: an
- # unmarked directory here is somebody's checkout, and the canonical pass already reported.
+ # The lexical parent too: a symlinked home has its old sd.cpp tree beside the link.
_custom_studio_roots lexical 2>/dev/null | while IFS= read -r _lex_root; do
[ -n "$_lex_root" ] || continue
- # The same ownership check the canonical loop makes. A stale or mistyped
- # UNSLOTH_STUDIO_HOME still reaches here (the lexical pass has no cd -P to filter it), and
- # without this "/parent/typo" would take somebody else's marked sd.cpp with it.
+ # Same ownership check, or a mistyped UNSLOTH_STUDIO_HOME could take someone's marked sd.cpp.
_is_studio_root "$_lex_root" || continue
_lex_sd_cpp="$(dirname "$_lex_root")/stable-diffusion.cpp"
[ -f "$_lex_sd_cpp/.unsloth-studio-owned" ] || continue
- # The deny list is string-based, so it has to see the RESOLVED path: the lexical form can
- # carry ".." or a symlinked ancestor and slip a protected tree past it. The rm stays lexical.
+ # The deny list is string-based, so check the resolved path; the rm stays lexical.
# shellcheck disable=SC1007
_lex_sd_canon=$(CDPATH= cd -P -- "$_lex_sd_cpp" 2>/dev/null && pwd -P)
[ -n "$_lex_sd_canon" ] || _lex_sd_canon="$_lex_sd_cpp"
@@ -880,9 +745,7 @@ _unsloth_uninstall_main() {
_remove_path "$_lex_sd_cpp"
fi
done
- # The master root's own children, marker-gated and deny-listed rather than removed outright
- # like the ~/.unsloth ones below: <master> is a directory the user chose. The locks and
- # .staging are ours by name (prebuilt_core.py) and carry no marker.
+ # The master root's own children are marker-gated and deny-listed: <master> is user-chosen.
_mr_root="$_MASTER_ROOT_SAVED"
if [ -n "$_mr_root" ]; then
if _is_unsafe_root "$_mr_root"; then
@@ -892,9 +755,7 @@ _unsloth_uninstall_main() {
_mr_path="$_mr_root/$_mr_child"
if _is_unsafe_root "$_mr_path"; then
echo " refusing to remove unsafe path: $_mr_path" >&2
- # -L as well as -e: -e is false for a dangling symlink, so one named llama.cpp
- # with its target volume unmounted fell through to _remove_path, which treats
- # -L as present and unlinks it. In a root the user chose, that link is theirs.
+ # -L too: -e is false for a dangling link, which in a user-chosen root is theirs.
elif { [ -e "$_mr_path" ] || [ -L "$_mr_path" ]; } \
&& [ ! -f "$_mr_path/.unsloth-studio-owned" ]; then
echo " keeping $_mr_child without Unsloth owner marker: $_mr_path" >&2
@@ -906,9 +767,7 @@ _unsloth_uninstall_main() {
.whisper.cpp.install.lock .audio.cpp.install.lock .sd.cpp.install.lock; do
_remove_lock_file "$_mr_root/$_mr_lock"
done
- # The prebuilt installers SHARE <root>/.staging and prune it only when empty, so
- # anything left in it here is not ours. rmdir, not _remove_path: in a user-chosen
- # root a recursive delete would take files an install was content to leave.
+ # Shared .staging is pruned only when empty; rmdir, not a recursive delete.
rmdir "$_mr_root/.staging" 2>/dev/null || true
# The exact shape prebuilt_core.py leaves: a component lock name, ".stale.", and the
# pid. A bare .*.install.lock.stale.* also matched .backup.install.lock.stale.copy.
@@ -921,20 +780,15 @@ _unsloth_uninstall_main() {
{ [ -e "$_mr_stale" ] || [ -L "$_mr_stale" ]; } && _remove_lock_file "$_mr_stale"
done
done
- # Only when nothing of the user's is left; rmdir refuses a non-empty directory.
rmdir "$_mr_root" 2>/dev/null || true
fi
fi
# end master-root children
- # Same gate as a custom root: an ungated run takes a hand-made ~/.unsloth/studio, and then
- # ~/.unsloth via the empty-dir prune below.
- # -e OR -L: -e follows a link and misses a dangling one, which _remove_path would still
- # unlink, so the gate has to see every entry that exists at that path.
+ # -e OR -L: _remove_path also unlinks dangling links, so the gate must see them.
if { [ -e "$HOME/.unsloth/studio" ] || [ -L "$HOME/.unsloth/studio" ]; } \
&& ! _is_studio_root "$HOME/.unsloth/studio" managed; then
echo " refusing to remove non-Unsloth path: $HOME/.unsloth/studio" >&2
- # A refused CUSTOM root is somebody else's by definition. This is our own default path,
- # where a damaged install can sit, so a studio.db here is chat history.
+ # Unlike a refused custom root, a studio.db in our default path is chat history.
if [ -f "$HOME/.unsloth/studio/studio.db" ]; then
_set_marker "$_DB_KEPT_FLAG"
fi
@@ -944,11 +798,7 @@ _unsloth_uninstall_main() {
# Shared llama.cpp build + cache, siblings of studio in default mode (deleting studio misses
# them). No-op in env/custom mode and when absent. A user-set UNSLOTH_LLAMA_CPP_PATH is kept.
_remove_path "$HOME/.unsloth/llama.cpp"
- # Default-mode native diffusion build, a sibling of studio like llama.cpp. No-op in env/custom
- # mode and when absent. "stable-diffusion.cpp" is exactly what a `git clone` of
- # leejet/stable-diffusion.cpp produces and a user may keep their own checkout (or point
- # UNSLOTH_SD_CPP_PATH) here, so require our owner marker (install_sd_cpp_prebuilt) before rm,
- # mirroring the custom-root guard above.
+ # A user's own stable-diffusion.cpp checkout may sit here, so require our owner marker.
_default_sd_cpp="$HOME/.unsloth/stable-diffusion.cpp"
if [ -e "$_default_sd_cpp" ] && [ ! -f "$_default_sd_cpp/.unsloth-studio-owned" ]; then
echo " keeping sd.cpp without Unsloth owner marker: $_default_sd_cpp" >&2
@@ -956,16 +806,11 @@ _unsloth_uninstall_main() {
_remove_path "$_default_sd_cpp"
fi
_remove_path "$HOME/.unsloth/.cache"
- # Isolated Node.js runtime (install_node_prebuilt.py), a default-mode sibling of studio.
_remove_path "$HOME/.unsloth/node"
- # llama.cpp atomic-install staging root (install_llama_prebuilt.py). Normally pruned after
- # activate, but an interrupted build leaves it behind and it blocks the rmdir below.
+ # An interrupted llama.cpp install leaves .staging, which blocks the rmdir below.
_remove_path "$HOME/.unsloth/.staging"
- # Managed whisper.cpp dictation engine (install_whisper_prebuilt.py), a default-mode sibling.
- # Only present when a prebuilt matching the pinned llama.cpp build existed at install time.
_remove_path "$HOME/.unsloth/whisper.cpp"
- # Managed audio.cpp engine (install_audio_cpp_prebuilt.py), a default-mode sibling. The installer
- # always marks its tree and refuses an unmarked one, so an unmarked one is the user's own build.
+ # The audio.cpp installer always marks its tree, so an unmarked one is the user's build.
_default_audio_cpp="$HOME/.unsloth/audio.cpp"
if { [ -e "$_default_audio_cpp" ] || [ -L "$_default_audio_cpp" ]; } \
&& [ ! -f "$_default_audio_cpp/.unsloth-studio-owned" ]; then
@@ -973,18 +818,15 @@ _unsloth_uninstall_main() {
else
_remove_path "$_default_audio_cpp"
fi
- # Prebuilt install locks: every prebuilt serializes on <parent>/.<name>.install.lock
- # (prebuilt_core.py), and a stray lock keeps ~/.unsloth from being pruned below.
+ # A stray install lock keeps ~/.unsloth from being pruned below.
_remove_lock_file "$HOME/.unsloth/.llama.cpp.install.lock"
_remove_lock_file "$HOME/.unsloth/.node.install.lock"
_remove_lock_file "$HOME/.unsloth/.whisper.cpp.install.lock"
_remove_lock_file "$HOME/.unsloth/.audio.cpp.install.lock"
- # audio.cpp lays its models out as links (copies across volumes) in unsloth-audiocpp-links beside
- # the Hugging Face hub cache (audio_cpp_files.py). The cache itself stays, as the note below says.
+ # audio.cpp model links live beside the HF hub cache; the cache itself stays.
_hf_hub="${HF_HUB_CACHE:-${HUGGINGFACE_HUB_CACHE:-${HF_HOME:-${XDG_CACHE_HOME:-$HOME/.cache}/huggingface}/hub}}"
_remove_path "$(dirname "$_hf_hub")/unsloth-audiocpp-links"
- # The audio.cpp server's scratch home when the Studio root was unusable (audio_cpp_server.py);
- # per uid, so another user's is never touched, and only a real directory this user owns.
+ # Per-uid audio.cpp scratch home; only a real directory this user owns.
_audiocpp_home="${TMPDIR:-/tmp}"
_audiocpp_home="${_audiocpp_home%/}/unsloth-audiocpp-home-$(id -u 2>/dev/null)"
if [ -d "$_audiocpp_home" ] && [ ! -L "$_audiocpp_home" ] && [ -O "$_audiocpp_home" ]; then
@@ -1005,17 +847,13 @@ _unsloth_uninstall_main() {
{ [ -e "$_stale" ] || [ -L "$_stale" ]; } && _remove_lock_file "$_stale"
done
done
- # ROCm-on-WSL helper artifacts (librocdxg clone, smoke-test venv); removing them frees the rmdir.
_remove_path "$HOME/.unsloth/librocdxg"
_remove_path "$HOME/.unsloth/rocm-smoketest"
- # Drop ~/.unsloth only if now empty (rmdir refuses non-empty, so user content is kept).
rmdir "$HOME/.unsloth" 2>/dev/null || true
_remove_path "$HOME/.local/share/unsloth"
- # CLI shim: only the symlink Unsloth created, never a pip-installed file.
_remove_cli_shim
echo "Removing desktop shortcut and launcher lock..."
- # install.sh creates Desktop/Unsloth Studio as a symlink; an unrelated regular dir is kept.
_desktop_link="$HOME/Desktop/Unsloth Studio"
if [ -L "$_desktop_link" ] || [ ! -e "$_desktop_link" ]; then
_remove_path "$_desktop_link"
@@ -1023,7 +861,6 @@ _unsloth_uninstall_main() {
echo " refusing to remove non-symlink Desktop path: $_desktop_link" >&2
fi
_remove_path "$HOME/Desktop/unsloth-studio.desktop"
- # Locks are namespaced per-uid; env-mode adds an extra suffix.
_lock_glob="${XDG_RUNTIME_DIR:-/tmp}/unsloth-studio-launcher-${_uid}"
for _lock in "$_lock_glob".lock "$_lock_glob"-*.lock; do
[ -e "$_lock" ] && _remove_path "$_lock"
@@ -1037,9 +874,7 @@ _unsloth_uninstall_main() {
if [ -x "$_lsr" ]; then
"$_lsr" -u "$HOME/Applications/Unsloth Studio.app" 2>/dev/null || true
fi
- # WKWebView data, keyed by bundle id; created at first launch, not by install.sh. The
- # packaged desktop app shares this id and is the only thing that writes the data, so
- # while that app is still installed this script must not reset it either.
+ # While the packaged app is installed, do not reset its WebView data.
_bid="ai.unsloth.studio"
_bid_owner=$(_bundle_id_owner "$_bid")
if [ -n "$_bid_owner" ]; then
@@ -1053,8 +888,7 @@ _unsloth_uninstall_main() {
_remove_path "$HOME/Library/HTTPStorages/$_bid.binarycookies"
_remove_path "$HOME/Library/Cookies/$_bid.binarycookies"
_remove_path "$HOME/Library/Saved Application State/$_bid.savedState"
- # defaults, not rm: cfprefsd rewrites the plist from memory. ByHost is a separate
- # domain. As the home's owner, or under sudo root just edits root's own domain.
+ # defaults, not rm: cfprefsd rewrites the plist from memory.
if command -v defaults >/dev/null 2>&1; then
_run_as_home_owner defaults delete "$_bid" >/dev/null 2>&1 || true
_run_as_home_owner defaults -currentHost delete "$_bid" >/dev/null 2>&1 || true
@@ -1065,18 +899,14 @@ _unsloth_uninstall_main() {
Linux)
if [ "$_is_wsl" = "1" ]; then
echo "Removing WSL Windows-side shortcuts..."
- # install.sh creates per-distro 'Unsloth Studio (WSL - <distro>).lnk' on the
- # Windows Desktop + Start Menu. Scope removal to THIS distro so a multi-distro
- # install keeps the other distros' launchers; the TARGET=wsl.exe check spares a
- # native install's "Unsloth Studio.lnk". Test powershell.exe can EXECUTE:
- # `command -v` succeeds even with interop OFF and the .exe then fails to run.
+ # Remove only THIS distro's WSL shortcuts. Test powershell.exe can execute:
+ # `command -v` succeeds even with interop off.
_wsl_distro="${WSL_DISTRO_NAME:-}"
_ps_ran=0
if command -v powershell.exe >/dev/null 2>&1 && \
powershell.exe -NoProfile -Command "exit 0" >/dev/null 2>&1; then
_ps_ran=1
- # Inject the distro into the command: a -Command string does not receive
- # trailing tokens as $args. WSL distro names are safe to embed.
+ # A -Command string does not receive trailing tokens as $args, so inject the distro.
# shellcheck disable=SC2016
powershell.exe -NoProfile -Command '$distro = "'"$_wsl_distro"'";
$dirs = @(
@@ -1118,9 +948,8 @@ _unsloth_uninstall_main() {
if ((Test-Path -LiteralPath $iconDir) -and -not (Get-ChildItem -LiteralPath $iconDir -Force -ErrorAction SilentlyContinue)) { Remove-Item -LiteralPath $iconDir -Recurse -Force -ErrorAction SilentlyContinue }
}' >/dev/null 2>&1 || true
fi
- # Remove $1's shared unsloth.ico only if no Unsloth shortcut (native install or
- # another WSL distro) still uses it, then drop the dir if empty. Reciprocal of
- # uninstall.ps1's _RemoveDataDirKeepingWslIcon.
+ # Keep the shared icon while any shortcut uses it.
+ # Reciprocal of uninstall.ps1's _RemoveDataDirKeepingWslIcon.
_drop_shared_icon_if_unused() {
_du="$1"
_icodir="$_du/AppData/Local/Unsloth Studio"
@@ -1141,8 +970,6 @@ _unsloth_uninstall_main() {
fi
[ -d "$_icodir" ] && rmdir "$_icodir" 2>/dev/null || true
}
- # Fallback when interop is off: remove WSL .lnk files via drvfs. The
- # "Unsloth Studio (WSL..." name never matches a native "Unsloth Studio.lnk".
if [ "$_ps_ran" = "0" ]; then
for _drive in /mnt/c /mnt/d /mnt/e; do
[ -d "$_drive/Users" ] || continue
@@ -1155,25 +982,20 @@ _unsloth_uninstall_main() {
"$_udir/AppData/Roaming/Microsoft/Windows/Start Menu/Programs"; do
[ -d "$_scdir" ] || continue
if [ -n "$_wsl_distro" ]; then
- # Exact per-distro name (no glob) so other distros survive.
_lnk="$_scdir/Unsloth Studio (WSL - ${_wsl_distro}).lnk"
[ -e "$_lnk" ] && rm -f "$_lnk" 2>/dev/null && echo " removed: $_lnk" || true
else
- # Distro unknown: fall back to the broad WSL prefix.
for _lnk in "$_scdir"/"Unsloth Studio (WSL"*.lnk; do
[ -e "$_lnk" ] && rm -f "$_lnk" 2>/dev/null && echo " removed: $_lnk" || true
done
fi
done
- # Drop the shared icon only when no shortcut still needs it.
_drop_shared_icon_if_unused "$_udir"
done
done
fi
# ── ROCm-on-WSL config (install_rocm_wsl_strixhalo.sh) ──
- # Remove Unsloth's own ROCDXG config (the env it persisted). The system
- # ROCm userspace is a shared prereq (like CUDA) and is LEFT IN PLACE by
- # default; set UNSLOTH_UNINSTALL_ROCM=1 to remove it too.
+ # System ROCm is kept unless UNSLOTH_UNINSTALL_ROCM=1.
echo "Removing ROCm-on-WSL config..."
_sudo=""
if [ "$_uid" != "0" ] && command -v sudo >/dev/null 2>&1; then _sudo="sudo"; fi
@@ -1198,8 +1020,6 @@ _unsloth_uninstall_main() {
echo " sudo rm -rf /opt/rocm /opt/rocm-* && sudo ldconfig"
fi
fi
- # webkit2gtk data by bundle id: Tauri points the WebView at LocalData/<bid>, so the
- # caches sit under XDG_DATA_HOME; the rest is app data.
_bid="ai.unsloth.studio"
echo "Removing WebView caches and app data ($_bid)..."
_remove_path "$(_xdg_dir "${XDG_DATA_HOME:-}" "$HOME/.local/share")/$_bid"
@@ -1208,15 +1028,12 @@ _unsloth_uninstall_main() {
_remove_path "$(_xdg_dir "${XDG_STATE_HOME:-}" "$HOME/.local/state")/$_bid"
echo "Removing Linux .desktop entry..."
_remove_path "$HOME/.local/share/applications/unsloth-studio.desktop"
- # tauri-plugin-deep-link rewrites "<exe>-handler.desktop" on every launch for the
- # unsloth:// scheme, so it exists on any machine the app has started on. Unlike
- # install.sh's own shortcut it uses Tauri's data_dir(), which honours XDG_DATA_HOME.
+ # tauri-plugin-deep-link rewrites this on every launch and honours XDG_DATA_HOME.
_un_appdir="$(_xdg_dir "${XDG_DATA_HOME:-}" "$HOME/.local/share")/applications"
_remove_path "$_un_appdir/unsloth-studio-handler.desktop"
if [ "$_un_appdir" != "$HOME/.local/share/applications" ]; then
_remove_path "$HOME/.local/share/applications/unsloth-studio-handler.desktop"
fi
- # Rebuild mimeinfo.cache wherever an entry was removed, or it keeps advertising it.
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
if [ "$_un_appdir" != "$HOME/.local/share/applications" ]; then
@@ -1229,25 +1046,19 @@ _unsloth_uninstall_main() {
echo ""
echo "Unsloth Studio uninstalled."
if _markers_unavailable || _marker_set "$_REMOVE_FAILED_FLAG"; then
- # Also the no-marker-storage case: no record of a failed rm, so do not claim success.
echo "Note: some paths could not be removed (see 'could not remove:' above), so the"
echo " signed-in session and local chat history may still be on disk. Remove"
echo " those paths by hand to clear them."
elif _marker_set "$_DB_REMOVED_FLAG"; then
- # Scoped to what was removed: a default and an env-mode install can coexist, and a bare
- # run never discovers the custom root, so "are gone" would be false for its database.
+ # A bare run never discovers an env-mode root, so do not claim its database is gone.
echo "Note: this also removed the app's WebView data and the studio.db it found, so"
echo " the desktop app's session and the chat history in the install(s) removed"
echo " above are gone."
else
- # No studio.db was deleted, so only the WebView-local data is accounted for: an env-mode
- # install this run never discovered still has its keys and history.
echo "Note: this also removed the app's WebView data, so the desktop app's session is"
echo " gone. A browser session is not affected: its tokens live in the same"
echo " localStorage as the API keys below."
if _marker_set "$_DB_KEPT_FLAG"; then
- # Named, and with no advice to delete it: the gate kept it precisely because it
- # does not look like ours.
echo " $HOME/.unsloth/studio carries no Unsloth install marker, so it was left"
echo " alone. The studio.db inside it is still there; look at that directory"
echo " yourself before deciding what to do with it."
@@ -1262,8 +1073,6 @@ _unsloth_uninstall_main() {
echo "Note: Hugging Face model cache at ~/.cache/huggingface was left in place."
echo "Remove it manually with 'rm -rf ~/.cache/huggingface/hub' if desired."
_uv_print_leftover_notes
- # Env-mode installs leave no breadcrumb in $HOME, so a custom root is only found when the
- # user re-exports the variable. Hint when neither is set, so `curl | sh` does not silently miss.
if [ -z "${UNSLOTH_STUDIO_HOME:-}" ] && [ -z "${STUDIO_HOME:-}" ]; then
echo ""
echo "If you installed Unsloth Studio with UNSLOTH_STUDIO_HOME or STUDIO_HOME"
@@ -1273,8 +1082,7 @@ _unsloth_uninstall_main() {
fi
}
-# Parse the entire script before running destructive work. This keeps piped help
-# from closing the writer early and makes a truncated download inert.
+# Parse the whole script first so a truncated download is inert.
{
_unsloth_uninstall_main "$@"
}
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 39aba4b0151..469d5879d95 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -21,11 +21,7 @@
$ErrorActionPreference = "Stop"
-# This script is spawned as powershell.exe -- Windows PowerShell 5.1 (see the PSModulePath note
-# below) -- where the Invoke-WebRequest progress bar is redrawn on every read and sets the rate
-# instead of the link: the VC++ runtime (24.4 MB, Ensure-VCRedist) took 38.18s with the bar on
-# against 0.29s with it off on a windows-latest runner. -UseBasicParsing does not help; only this
-# preference does. Script scope, in a separate short-lived process, so nothing outlives it.
+# Windows PowerShell 5.1 progress bar redraws make downloads ~130x slower (38.18s vs 0.29s).
$ProgressPreference = 'SilentlyContinue'
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
@@ -78,20 +74,13 @@ if ($PSVersionTable.PSEdition -ne 'Core' -and $env:SystemRoot) {
}
}
-# UTF-8 output invariant. 5.1 encodes redirected output with the OEM code page,
-# but the desktop app decodes the pipe as UTF-8 (from_utf8_lossy, install.rs):
-# U+1F9A5 prints as '??', U+2500 becomes a bare 0xC4 and arrives as U+FFFD.
-# Must precede the first write, since this rebuilds [Console]::Out. ASCII-only,
-# because 5.1 parses these BOM-less files as ANSI.
+# 5.1 writes redirected output in the OEM code page but the desktop app decodes UTF-8.
+# Must precede the first write. Keep this file ASCII-only: 5.1 parses BOM-less files as ANSI.
$_UnslothUtf8NoBom = New-Object System.Text.UTF8Encoding $false
try {
[Console]::OutputEncoding = $_UnslothUtf8NoBom
} catch {
- # No console (CREATE_NO_WINDOW). The setter P/Invokes SetConsoleOutputCP and
- # drops the cached writer BEFORE throwing, assigning OutputEncoding only
- # after, so [Console]::Out would rebuild on the OLD code page. Bind UTF-8
- # writers instead: redirected step/substep use Out as their only sink, and
- # Tauri decodes stderr the same way to build its failure text.
+ # Without a console the setter drops the cached writer before throwing, so bind UTF-8 writers directly.
try {
$_UnslothStdout = New-Object System.IO.StreamWriter -ArgumentList ([Console]::OpenStandardOutput()), $_UnslothUtf8NoBom
$_UnslothStdout.AutoFlush = $true
@@ -105,19 +94,12 @@ $OutputEncoding = $_UnslothUtf8NoBom
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
-# Resolved once: it picks the output sink in step/substep and must not change
-# mid-run. See Write-StudioStdoutMirror.
+# Resolved once: it picks the output sink in step/substep and must not change mid-run.
$script:StudioStdoutRedirected = $false
try { $script:StudioStdoutRedirected = [Console]::IsOutputRedirected } catch { }
-# Every other line in this script reached the pipe through Write-Host, which
-# 5.1's console host writes with its own writer on the OEM code page, not the
-# UTF-8 [Console]::Out rebound above. Under CREATE_NO_WINDOW that writer is
-# still what the desktop app reads, so the banner emoji, the U+2500 rule and
-# every warning arrived as U+FFFD out of from_utf8_lossy. One sink instead: the
-# console handle when redirected, Write-Host when interactive, since it is the
-# only one that colorizes. Defined above the first write, for the same ordering
-# reason as the encoding block.
+# 5.1's Write-Host uses the OEM code page even when redirected, so use one sink:
+# the console handle when redirected, Write-Host (colorized) when interactive.
function Write-StudioLine {
param([string]$Message = "", [string]$ForegroundColor)
if ($script:StudioStdoutRedirected) {
@@ -145,24 +127,15 @@ function Show-DownloadProgress {
}
# --------------------------------------------------------------------------
-# Maintainer-editable defaults
-# Change these in the GitHub-hosted script so users get updated defaults.
-# User env vars always override these baked-in values.
# --------------------------------------------------------------------------
-# Prefer "latest" over "master" -- "master" bypasses the prebuilt resolver
-# (no matching GitHub release), forces a source build, and causes HTTP 422
-# errors. Only use "master" temporarily when the latest release is missing
-# support for a new model architecture.
-#
-# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "cuda", "vulkan",
-# "hip", or "rocm". Concrete values select and persist a backend across updates;
-# "auto" restores detection. Overrides Unsloth's Settings > System selection.
+# Maintainer-editable defaults; user env vars always override them.
+# Prefer "latest" over "master": master bypasses the prebuilt resolver and forces a source build.
+# UNSLOTH_LLAMA_CPP_BACKEND: auto|cpu|cuda|vulkan|hip|rocm; concrete values persist across updates.
$DefaultLlamaPrForce = ""
$DefaultLlamaSource = "https://github.com/ggml-org/llama.cpp"
$DefaultLlamaTag = "latest"
$DefaultLlamaForceCompileRef = "master"
-# Verbose can be enabled either by CLI flag or by UNSLOTH_VERBOSE=1.
$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq '1')
foreach ($a in $args) {
if ($a -eq '--verbose' -or $a -eq '-v') {
@@ -179,8 +152,7 @@ $script:NvidiaSmiRejected = $false
$script:NvidiaDriverLibraryOnly = $false
$script:NvidiaLibraryInventoryProbed = $false
$script:NvidiaLibraryInventory = $null
-# Set by the offline keep, read unconditionally by the sidecar and legacy-migration blocks:
-# initialised for Set-StrictMode and for a dot-sourced rerun in the same session.
+# Initialised for Set-StrictMode and for a dot-sourced rerun in the same session.
$script:OfflineFastPath = $false
$script:CudaToolkitReady = $false
$script:NvccPath = $null
@@ -380,8 +352,7 @@ function Restore-SetupStartEnvironment {
function Get-SetupHostInterpreterInVenv {
param([Parameter(Mandatory = $true)][string]$VenvDir)
$root = $null
- # Not a literal '\': off Windows GetFullPath returns '/' and '\' is an ordinary filename
- # character, so a hardcoded one builds a prefix nothing matches. The pwsh tests run there.
+ # Not a literal '\': off Windows GetFullPath returns '/', and the pwsh tests run there.
$sep = [System.IO.Path]::DirectorySeparatorChar
try { $root = [System.IO.Path]::GetFullPath($VenvDir).TrimEnd('\', '/') + $sep } catch { return $null }
$inside = {
@@ -389,12 +360,7 @@ function Get-SetupHostInterpreterInVenv {
if ([string]::IsNullOrWhiteSpace($Candidate)) { return $false }
try { $full = [System.IO.Path]::GetFullPath($Candidate) } catch { return $false }
if (-not $full.StartsWith($root, [System.StringComparison]::OrdinalIgnoreCase)) { return $false }
- # A path, not a file, is not an interpreter that can be holding anything open. The hint
- # below is an inherited environment variable and can outlive what it names -- a stale one
- # pointing inside the venv would otherwise route a venv that genuinely needs rebuilding
- # into an in-place repair it has no interpreter to perform. A live process's own
- # ExecutablePath passes this trivially; an unreadable one reads as "not inside", which is
- # the pre-existing rebuild.
+ # An inherited hint can outlive what it names; a stale one must not force an in-place repair.
return (Test-Path -LiteralPath $full -PathType Leaf)
}
if (& $inside $env:UNSLOTH_SETUP_HOST_PYTHON) { return $env:UNSLOTH_SETUP_HOST_PYTHON }
@@ -410,10 +376,7 @@ function Get-SetupHostInterpreterInVenv {
if (& $inside $row.ExecutablePath) { return $row.ExecutablePath }
$parent = [int]$row.ParentProcessId
if ($parent -le 0 -or $parent -eq $cur) { break }
- # A parent that started AFTER its child is not the parent: Windows reuses process ids
- # once the real one has exited, and Microsoft's own Win32_Process guidance is to
- # compare creation dates before trusting ParentProcessId. Unreadable dates on either
- # side leave the hop alone rather than ending the walk, since the bound already caps it.
+ # Windows reuses process ids, so a parent created after its child is not the parent.
$parentRow = $byPid[$parent]
if ($parentRow -and $row.CreationDate -and $parentRow.CreationDate -and
$parentRow.CreationDate -gt $row.CreationDate) { break }
@@ -423,7 +386,6 @@ function Get-SetupHostInterpreterInVenv {
return $null
}
-# Detect if running from pip install (no frontend/ dir in studio)
$FrontendDir = Join-Path $ScriptDir "frontend"
# Build state, not a source input, so the CI dist cache key rightly leaves it out.
$FrontendBuildMark = Join-Path $FrontendDir ".unsloth-build.local"
@@ -431,36 +393,24 @@ $OxcValidatorDir = Join-Path $ScriptDir "backend\core\data_recipe\oxc-validator"
$IsPipInstall = -not (Test-Path $FrontendDir)
# ─────────────────────────────────────────────
-# Helper functions
# ─────────────────────────────────────────────
-
function Refresh-Environment {
foreach ($level in @('Machine', 'User')) {
$vars = [System.Environment]::GetEnvironmentVariables($level)
foreach ($key in $vars.Keys) {
- # PSModulePath joins Path as an exception. Reloading it from the
- # registry would undo the normalization at the top of this file,
- # and several callers of this function run before the uv installer
- # (which loads Microsoft.PowerShell.Security), so the module path
- # would be broken again exactly where it has to be right.
+ # Reloading PSModulePath would undo the normalization at the top of this file.
if ($key -eq 'Path' -or $key -eq 'PSModulePath') { continue }
- # Same exception, for the UTF-8 invariant at the top. This runs
- # repeatedly, so a registry PYTHONUTF8=0 would otherwise reload over
- # ours and every later Python child would go back to mojibake.
+ # Same for the UTF-8 invariant: a registry PYTHONUTF8=0 must not reload over ours.
if ($key -eq 'PYTHONUTF8' -or $key -eq 'PYTHONIOENCODING') { continue }
Set-Item -Path "Env:$key" -Value $vars[$key] -ErrorAction SilentlyContinue
}
}
$machinePath = [System.Environment]::GetEnvironmentVariable('Path', 'Machine')
$userPath = [System.Environment]::GetEnvironmentVariable('Path', 'User')
- # Merge: venv Scripts (if active) > active conda > Machine > User > current $env:Path.
- # Dedup raw+expanded.
+ # Order: venv Scripts > active conda > Machine > User > current PATH; deduped raw+expanded.
$venvScripts = if ($env:VIRTUAL_ENV) { Join-Path $env:VIRTUAL_ENV 'Scripts' } else { $null }
- # An activated conda environment lives ONLY in the process PATH, so rebuilding as
- # machine + user + previous puts every conda entry behind the User PATH. Running this
- # script directly shares the caller's process, so the demotion would outlive the setup.
- # Mirrors install.ps1's Refresh-SessionPath; parity is asserted in
- # tests/python/test_installer_conda_path_guard.py.
+ # An active conda env lives only in the process PATH; keep it in front. Mirrors install.ps1
+ # Refresh-SessionPath (parity in tests/python/test_installer_conda_path_guard.py).
$condaFront = @()
if (Test-ActiveCondaEnvironment) {
$prefixes = Get-ActiveCondaPrefixes
@@ -471,9 +421,7 @@ function Refresh-Environment {
}
}
} else {
- # A hook that exports CONDA_DEFAULT_ENV and nothing that names a directory: which
- # entries are conda's cannot be established, so the caller's PATH is kept whole
- # and in front rather than reconstructed. Same reasoning as install.ps1.
+ # Conda entries cannot be identified, so keep the caller's PATH whole and in front.
$condaFront = @($env:Path)
}
}
@@ -497,8 +445,6 @@ function Refresh-Environment {
}
# ── Helper: is a conda environment ACTIVE in this session? ──
-# Mirrors install.ps1. CONDA_PREFIX separates "conda is installed" from "we are inside one
-# of its environments".
function Test-ActiveCondaEnvironment {
foreach ($condaVar in @($env:CONDA_PREFIX, $env:CONDA_DEFAULT_ENV)) {
if (-not [string]::IsNullOrWhiteSpace($condaVar)) { return $true }
@@ -506,14 +452,11 @@ function Test-ActiveCondaEnvironment {
return $false
}
-# Every directory the active conda installation owns: the environment itself, the stack of
-# environments it was activated on top of, and the base installation. Mirrors install.ps1.
+# Every prefix the active conda owns (env, stacked envs, base). Mirrors install.ps1.
function Get-ActiveCondaPrefixes {
$prefixes = New-Object System.Collections.Generic.List[string]
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_PREFIX)) { $prefixes.Add($env:CONDA_PREFIX) }
- # Enumerated from CONDA_SHLVL, not a fixed list: a hard-coded tail of three dropped
- # everything past the fourth stacked environment and inverted its ordering. The ceiling
- # stops a bad value spinning.
+ # Enumerated from CONDA_SHLVL, not a fixed list; the ceiling stops a bad value spinning.
$levels = 0
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_SHLVL)) {
[void][int]::TryParse($env:CONDA_SHLVL, [ref]$levels)
@@ -526,8 +469,7 @@ function Get-ActiveCondaPrefixes {
}
if (-not [string]::IsNullOrWhiteSpace($env:_CONDA_ROOT)) { $prefixes.Add($env:_CONDA_ROOT) }
if (-not [string]::IsNullOrWhiteSpace($env:CONDA_EXE)) {
- # ...\<root>\Scripts\conda.exe -> ...\<root>. Regex rather than Split-Path, which is
- # provider-aware and keeps backslashes on the non-Windows PowerShell the tests use.
+ # Regex, not Split-Path, which keeps backslashes on the non-Windows pwsh the tests use.
$scripts = $env:CONDA_EXE -replace '[\\/][^\\/]*$', ''
$root = $scripts -replace '[\\/][^\\/]*$', ''
if ($root -and $root -ne $env:CONDA_EXE) { $prefixes.Add($root) }
@@ -535,8 +477,7 @@ function Get-ActiveCondaPrefixes {
return $prefixes
}
-# Is $Path inside one of $Prefixes? On a directory boundary, so "C:\conda-backup" is not
-# dragged to the front along with "C:\conda".
+# Directory-boundary match, so C:\conda-backup does not match C:\conda.
function Test-PathUnderCondaPrefix {
param([string]$Path, $Prefixes)
if ([string]::IsNullOrWhiteSpace($Path) -or -not $Prefixes) { return $false }
@@ -553,9 +494,8 @@ function Test-PathUnderCondaPrefix {
return $false
}
-# The position a PERSISTENT PATH write may actually use: a prepend outlives the activation
-# it was made under and leaves our directory ahead of conda's own entries (#5871). Mirrors
-# install.ps1; parity is asserted in tests/python/test_installer_conda_path_guard.py.
+# A persistent prepend outlives the conda activation and would shadow conda's entries.
+# Mirrors install.ps1; parity in tests/python/test_installer_conda_path_guard.py.
function Resolve-UserPathPosition {
param(
[ValidateSet('Append','Prepend')]
@@ -573,10 +513,7 @@ function Add-ToUserPath {
[string]$Position = 'Append'
)
if (Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue) { return $false }
- # Every persistent PATH write goes through Resolve-UserPathPosition, so an active conda
- # environment cannot be demoted by any call site.
- # A downgraded request has to be able to MOVE an entry that a previous non-conda run left at the
- # FRONT, not just decline to add one; see the same guard in install.ps1.
+ # A downgraded request must also MOVE an entry a previous run left at the front.
$requestedPosition = $Position
$Position = Resolve-UserPathPosition -Position $Position
$positionDowngraded = ($Position -ne $requestedPosition)
@@ -602,7 +539,6 @@ function Add-ToUserPath {
$kept.Add($entries[$i])
}
$alreadyPresent = $matchIndices.Count -gt 0
- # Already at the back is still a no-op, caught by the $newPath -ceq $rawPath check below.
if ($alreadyPresent -and $Position -eq 'Append' -and -not $positionDowngraded) {
return $false
}
@@ -610,7 +546,6 @@ function Add-ToUserPath {
$matchIndices.Count -eq 1 -and $matchIndices[0] -eq 0) {
return $false
}
- # One-time backup under HKCU\Software\Unsloth\PathBackup
if ($rawPath) {
try {
$backupKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Unsloth')
@@ -656,7 +591,7 @@ function Add-ToUserPath {
}
}
-# PowerShell 5.1 compatibility helper: avoid relying on New-TemporaryFile.
+# PowerShell 5.1 lacks New-TemporaryFile.
function New-UnslothTemporaryFile {
$tempPath = [System.IO.Path]::GetTempFileName()
return Get-Item -LiteralPath $tempPath
@@ -687,7 +622,6 @@ function Remove-AgentInstructionFiles {
}
}
-# Recognize ERROR_ACCESS_DENIED through PowerShell's wrapper exceptions.
function Test-AccessDeniedError {
param($ErrorRecord)
@@ -723,8 +657,6 @@ function Get-PathState {
}
}
-# Non-throwing Test-Path for paths inside install trees we do not control.
-# Callers that must react to a denial use Get-PathState instead.
function Test-PathQuiet {
param(
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path,
@@ -754,7 +686,6 @@ function Get-LlamaCppInstallReadState {
return "Readable"
}
-# Describe a denied link target without risking another reporting failure.
function Get-PathDenialDetail {
param([Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path)
@@ -800,31 +731,8 @@ function Get-PathDenialDetail {
return ""
}
-# Which security software could be denying this path, as a possibility.
-#
-# Worth naming because takeown and icacls cannot clear a filter-driver block
-# and elevation does not either, so a user whose antivirus is holding the
-# folder is otherwise sent round the takeown loop for as long as they are
-# willing. Nothing readable from here attributes the specific denial though,
-# so this names the candidate and the log that settles it and never
-# contradicts the ACL advice it follows.
-#
-# Defender's Controlled folder access modes are 0 Disabled, 1 Enabled,
-# 2 AuditMode, 3 BlockDiskModificationOnly, 4 AuditDiskModificationOnly. Only
-# 1 gates file access; 3 and 4 are direct disk-sector writes rather than
-# files, so neither explains a denied folder.
-#
-# When Defender is not it, name whichever antivirus is registered and running
-# instead: third-party suites ship the same protected-folders feature under
-# their own product names, and the user cannot act on advice that does not say
-# which product to open. Which suite ships what is recorded in
-# tests/studio/test_installer_av_shapes.py and deliberately not repeated here,
-# because this file is scanned in full before a line of it runs and a comment
-# listing security products raises the score of the very file explaining it.
-# Nothing below hard-codes a product: it reads what SecurityCenter2 registered.
-#
-# Answers "" whenever it cannot tell, so a machine with no Defender module
-# and no SecurityCenter registration reads the same as one that says no.
+# Names security software that might be denying the path; takeown/icacls cannot clear a filter driver.
+# No product names here: see tests/studio/test_installer_av_shapes.py. Returns "" when unsure.
function Get-SecuritySoftwareNote {
$mode = $null
try {
@@ -858,7 +766,7 @@ function Get-SecuritySoftwareNote {
return ""
}
-# Print guidance; returns the failure reason as its only pipeline output.
+# Prints guidance; returns the failure reason as its only pipeline output.
function Write-PathAccessDenied {
param(
[Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path,
@@ -897,7 +805,6 @@ function Write-PathAccessDenied {
return "Access denied reading the existing $Label at $Path. Delete or rename that folder (Unsloth reinstalls it) or restore access with takeown/icacls, then re-run setup. Reinstalling the app does not reset it."
}
-# Canonicalize a directory for comparison; unresolvable ones are only normalized.
function Get-CanonicalDir {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
@@ -924,17 +831,13 @@ function Get-CanonicalDir {
return $resolvedPath
}
-# Compare canonical homes so path spelling does not change ownership policy.
function Test-StudioHomeIsCustom {
return ((Get-CanonicalDir -Path $StudioHome) -ne
(Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")))
}
-# Is this bin\unsloth.cmd one install.ps1 wrote? Only then does it prove the root is
-# ours. The name alone is a plausible wrapper for anything built on unsloth, and the
-# caller uses the answer to decide whether a user-chosen venv may be deleted. The
-# trampoline is the marker; no other file carries it. Mirrored in install.ps1
-# (Test-UnslothCmdShimFile) and scripts/uninstall.ps1 (_IsUnslothCmdShim).
+# Only an install.ps1-written shim (trampoline marker) proves the root is ours; the caller may
+# delete a venv on that answer. Mirrored in install.ps1 and scripts/uninstall.ps1.
function Test-UnslothCmdShimFile {
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$Path)
@@ -950,9 +853,7 @@ function Test-UnslothCmdShimFile {
return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")
}
-# The master root storage_roots.unsloth_home() reads. llama.cpp, node and whisper.cpp sit
-# BESIDE studio\ under it, so deriving them from $StudioHome would put them one level below
-# where every runtime resolver looks.
+# llama.cpp, node and whisper.cpp sit BESIDE studio\ under the master root, not inside it.
function Get-MasterRootOverride {
if ([string]::IsNullOrWhiteSpace($env:UNSLOTH_HOME)) { return $null }
$value = $env:UNSLOTH_HOME.Trim()
@@ -964,8 +865,6 @@ function Get-MasterRootOverride {
return (Get-CanonicalDir -Path $value)
}
-# Explicit staging root, the master root, the shared default cache, or the custom Unsloth
-# home's tree.
function Get-ManagedLlamaCppDir {
param([AllowNull()][string]$StagingRoot = $null)
@@ -1228,7 +1127,7 @@ function Get-MirrorDnsServers {
} catch {}
}
-# No network call: a mainland China time zone, or a resolver from a mainland public DNS or cloud, as _mirror_in_china in install.sh.
+# No network call: mirrors _mirror_in_china in install.sh.
function Test-MirrorInChina {
try { if ((Get-TimeZone).Id -in 'China Standard Time', 'Asia/Shanghai', 'Asia/Chongqing', 'Asia/Chungking', 'Asia/Harbin', 'Asia/Urumqi', 'Asia/Kashgar', 'PRC') { return $true } } catch {}
return [bool](@(Get-MirrorDnsServers) -match '^(223\.5\.5\.5|223\.6\.6\.6|119\.29\.29\.29|114\.114\.11[45]\.11[0459]|182\.254\.116\.116|119\.28\.28\.28|180\.76\.76\.76|1\.2\.4\.8|210\.2\.4\.8|100\.100\.2\.13[68]|183\.60\.8[23]\.(19|98))$')
@@ -1382,7 +1281,6 @@ function Get-MirrorFailedHost {
elseif ($Ran -and $Output -notmatch 'https?://') { $Ran }
}
-# Stop every install path consistently when its destination is unreadable.
function Exit-PathAccessDenied {
param(
[Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path,
@@ -1395,7 +1293,7 @@ function Exit-PathAccessDenied {
-UserSupplied:$UserSupplied -OwnershipUnverified:$OwnershipUnverified)
}
-# Why the prebuilt update failed, for the keep message. Twin of setup.sh _llama_update_fail_reason.
+# Why the prebuilt update failed, for the keep message; twin of the setup.sh fail reason.
function Get-LlamaUpdateFailReason {
param([string]$Output)
if ($Output -match '(?i)429|rate limit') { return "GitHub rate limit" }
@@ -1403,8 +1301,7 @@ function Get-LlamaUpdateFailReason {
return "download failed"
}
-# The marker's backend as setup.sh _installed_prebuilt_backend reads it: backend, then the
-# llama_backend request, then the asset name of a marker from before the field existed.
+# Mirrors setup.sh _installed_prebuilt_backend: backend, then llama_backend, then asset name.
function Get-PrebuiltMarkerBackend {
param([string]$Marker)
if (-not (Test-PathQuiet $Marker "Leaf")) { return "" }
@@ -1428,13 +1325,12 @@ function Get-PrebuiltMarkerBackend {
return $answer
}
-# The backend of an installed GPU prebuilt that still runs on a host that still has that GPU,
-# else "" (nothing to keep, GPU gone, or this run asked for something else). Twin of setup.sh.
+# Backend of an installed GPU prebuilt still usable on this host, else "". Twin of setup.sh.
function Get-GpuPrebuiltToKeepOverSourceBuild {
param([string]$InstallDir)
if ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1" -or $LlamaPr -or $explicitLlamaSourceBackend) { return "" }
if ($env:UNSLOTH_LLAMA_RELEASE_TAG) { return "" }
- # "master" is a branch, never a release: it asks for a source build, so nothing is kept.
+ # "master" is a branch, never a release: it asks for a source build.
if ("$($env:UNSLOTH_LLAMA_TAG)".Trim() -notin @("", "latest")) { return "" }
$backend = Get-PrebuiltMarkerBackend -Marker (Join-Path $InstallDir "UNSLOTH_PREBUILT_INFO.json")
if (-not $backend) { return "" }
@@ -1443,7 +1339,7 @@ function Get-GpuPrebuiltToKeepOverSourceBuild {
$present = switch ($backend) {
"cuda" { $nvidia }
"rocm" { $amd }
- # Any Intel adapter runs the Vulkan bundle (windows_intel_gpu_in_registry), not only an XPU part.
+ # Any Intel adapter runs the Vulkan bundle, not only an XPU part.
"vulkan" { $nvidia -or $amd -or [bool]$script:IsIntelXpu -or (@(Get-IntelRegistryAdapterNames).Count -gt 0) }
default { $false }
}
@@ -1470,8 +1366,7 @@ function Get-InstalledLlamaPrebuiltRelease {
return $null
}
- # An interrupted write leaves an empty marker, which deserializes to $null: reading a
- # property off that is fatal under a caller's Set-StrictMode, and printed "@" without one.
+ # An interrupted write leaves an empty marker; reading a property off $null is fatal under StrictMode.
if ($null -eq $payload -or $payload -isnot [System.Management.Automation.PSCustomObject]) {
return $null
}
@@ -1484,7 +1379,6 @@ function Get-InstalledLlamaPrebuiltRelease {
}
$message = "installed release: $($payload.published_repo)@$($payload.release_tag)"
- # tag is optional too, so it carries the same strict-mode hazard as backend.
$llamaTag = ""
if ($payload.PSObject.Properties.Name -ccontains 'tag') {
$llamaTag = [string]$payload.tag
@@ -1492,10 +1386,7 @@ function Get-InstalledLlamaPrebuiltRelease {
if ($llamaTag -and $llamaTag -ne $payload.release_tag) {
$message += " (tag $llamaTag)"
}
- # Name the backend: a Vulkan and a ROCm bundle print an identical line without it.
- # Absent in every marker written before #8520, and a missing property is fatal under a
- # caller's Set-StrictMode. -ccontains and the type/shape checks keep this byte-identical
- # to the setup.sh twin, which is case-sensitive and renders non-strings differently.
+ # Older markers lack the field (fatal under StrictMode). Keep byte-identical to the setup.sh twin.
$backendName = ""
if (($payload.PSObject.Properties.Name -ccontains 'backend') -and ($payload.backend -is [string])) {
$backendName = $payload.backend.Trim()
@@ -1514,7 +1405,6 @@ function Find-Nvcc {
if ($MaxVersion -and (Test-Path $toolkitBase)) {
$drMajor = [int]$MaxVersion.Split('.')[0]
- # Get all installed CUDA dirs, sorted descending (highest first)
$cudaDirs = Get-ChildItem -Directory $toolkitBase | Where-Object {
$_.Name -match '^v(\d+)\.(\d+)'
} | Sort-Object { [version]($_.Name -replace '^v','') } -Descending
@@ -1532,17 +1422,12 @@ function Find-Nvcc {
}
}
- # No compatible side-by-side version found
return $null
}
- # Fallback: no version constraint — pick latest or whatever is available
-
- # 1. Check nvcc on PATH
$cmd = Get-Command nvcc -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
- # 2. Check CUDA_PATH env var
$cudaRoot = [Environment]::GetEnvironmentVariable('CUDA_PATH', 'Process')
if (-not $cudaRoot) { $cudaRoot = [Environment]::GetEnvironmentVariable('CUDA_PATH', 'Machine') }
if (-not $cudaRoot) { $cudaRoot = [Environment]::GetEnvironmentVariable('CUDA_PATH', 'User') }
@@ -1550,7 +1435,6 @@ function Find-Nvcc {
return (Join-Path $cudaRoot 'bin\nvcc.exe')
}
- # 3. Scan standard toolkit directory
if (Test-Path $toolkitBase) {
$latest = Get-ChildItem -Directory $toolkitBase | Where-Object {
$_.Name -match '^v(\d+)\.(\d+)'
@@ -1586,9 +1470,7 @@ function Test-CudaDriverNeedsUncompressedFatbin {
}
function Get-CudaComputeCapability {
- # $NvidiaSmiExe is an absolute path that survives Refresh-Environment. Not rediscovered
- # once detection rejected nvidia-smi: the driver library answered, and asking a wedged
- # binary again costs a deadline per call.
+ # Not rediscovered once detection rejected nvidia-smi: a wedged binary costs a deadline per call.
$smiExe = if ($script:NvidiaSmiExe) { $script:NvidiaSmiExe } elseif ($script:NvidiaSmiRejected) { $null } else {
$cmd = Get-Command nvidia-smi -ErrorAction SilentlyContinue
if ($cmd) { $cmd.Source } else { $null }
@@ -1601,7 +1483,7 @@ function Get-CudaComputeCapability {
} catch { }
}
if (-not $cap) {
- # Without it the source build turns CUDA off (#5854); the driver library has it.
+ # Without it the source build turns CUDA off; the driver library has it.
$inventory = Get-NvidiaLibraryInventory
if ($inventory) { $cap = $inventory.ComputeCaps[0] }
}
@@ -1639,18 +1521,12 @@ function Get-NvccMaxArch {
return $null
}
-# Reserved for the OS, and budgeted per compile job, both in MB. The budget sits
-# above the measured per-translation-unit peak on purpose; see the derivation on
-# _LLAMA_BUILD_* in setup.sh, which these must match and which the shell test
-# pins. MSVC and Windows, where the freeze was reported, need that headroom more.
+# MB reserved for the OS and budgeted per compile job. Must match _LLAMA_BUILD_* in setup.sh.
$LlamaBuildReserveMb = 2048
$LlamaBuildMbPerJob = 2048
-# The cmake -j count. A negative $TotalMb means RAM was unreadable and keeps the
-# old core-count behaviour. Zero is a reading, not a failure: a box with no
-# memory left is the last one that should get its full core count, so it falls
-# through and floors at 1, as _llama_jobs_for does for a numeric 0.
-# UNSLOTH_LLAMA_BUILD_JOBS wins. Pure, so the tests can drive it.
+# cmake -j count. Negative $TotalMb (unreadable) keeps core count; 0 floors at 1.
+# UNSLOTH_LLAMA_BUILD_JOBS wins. Pure, so tests can drive it.
function Get-LlamaJobsFor {
param([int]$Cores, [long]$TotalMb)
@@ -1667,13 +1543,7 @@ function Get-LlamaJobsFor {
return $jobs
}
-# Usable RAM in MB; -1 when it cannot be read at all. Available, not installed:
-# a box with 8 GB already resident cannot host a 14 GB compile just because
-# 16 GB is fitted. AvailableMBytes counts the standby list, which the Free
-# counters do not, and the raw perf class is not localized the way Get-Counter
-# paths are; installed RAM stays the fallback. A reading of 0 is returned as 0
-# rather than treated as unreadable, since falling back to installed RAM under
-# real pressure would hand the machine its full core count at the worst moment.
+# Available (not installed) RAM in MB, -1 if unreadable. 0 is a real reading, not a failure.
function Get-UsableMemoryMb {
# -AvailableOnly: -1 rather than installed RAM when free memory cannot be read.
param([switch]$AvailableOnly)
@@ -1687,7 +1557,7 @@ function Get-UsableMemoryMb {
if ($bytes -gt 0) { return [long]($bytes / 1MB) }
} catch { }
try {
- # TotalVisibleMemorySize is in KB and excludes hardware-reserved RAM.
+ # TotalVisibleMemorySize is in KB.
$kb = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).TotalVisibleMemorySize
if ($kb -gt 0) { return [long]($kb / 1KB) }
} catch { }
@@ -1698,10 +1568,8 @@ function Get-LlamaBuildJobs {
return (Get-LlamaJobsFor -Cores ([Environment]::ProcessorCount) -TotalMb (Get-UsableMemoryMb))
}
-# Classify the physical NVIDIA inventory for a cu126 fallback: "cu126" when it covers
-# every GPU, "uncovered" for an incompatible mix, empty when no fallback is needed or the
-# inventory is unreadable. CUDA_VISIBLE_DEVICES is ignored because the wheel must support
-# the host. Mirrors _nvidia_cu126_verdict in install.sh.
+# "cu126" when it covers every GPU, "uncovered" for an incompatible mix, else empty.
+# Ignores CUDA_VISIBLE_DEVICES: the wheel must support the host. Mirrors install.sh.
function Get-NvidiaCu126Verdict {
# Floor is per-release, not fixed: only 2.11 dropped sm_70 from cu128.
param([string]$SmiExe, [int]$LegacyFloorSm = 75, [string[]]$ComputeCaps = @())
@@ -1735,7 +1603,7 @@ function Get-CudaFamilyCappedForPreTuring {
$legacyFloorSm = 75
$verdict = Get-NvidiaCu126Verdict $SmiExe $legacyFloorSm $ComputeCaps
if (-not $verdict) { return $Family }
- # This runs twice per setup; announce once without polluting pipeline output.
+ # Runs twice per setup; announce once without polluting pipeline output.
$announce = -not $script:PreTuringCapAnnounced
$script:PreTuringCapAnnounced = $true
if ($verdict -eq 'cu126') {
@@ -1751,10 +1619,7 @@ function Get-CudaFamilyCappedForPreTuring {
return $Family
}
-# Interpreter for the shared inventory's Python rung, deliberately NOT part of the shared
-# region: the two files find Python in different places. setup.ps1 runs after the installer,
-# so the venv a previous run built is the interpreter, and $VenvDir is set well before the
-# first Get-NvidiaLibraryInventory call. No interpreter simply means the rung declines.
+# Deliberately NOT in the shared region: setup.ps1 uses the venv a previous run built.
function Get-NvidiaProbePythonExe {
if ("$($env:UNSLOTH_EARLY_PYTHON_PROBE)".Trim() -eq "0") { return "" }
if (-not $VenvDir) { return "" }
@@ -2340,9 +2205,8 @@ function Get-NvidiaLibraryInventory {
}
# ── END SHARED WITH install.ps1 (Get-NvidiaLibraryInventory) ──
-# Detect driver's max CUDA version from nvidia-smi and return the highest
-# Must match install.ps1's Get-TorchIndexUrl ladder character for character (asserted by a test).
-# PyTorch 2.10 offers: cu124, cu126, cu128, cu130. Anything below CUDA 11 gets "cpu".
+# Must match install.ps1's Get-TorchIndexUrl ladder exactly (asserted by a test).
+# Below CUDA 11 gets "cpu".
function Get-CudaFamilyForVersion {
param([int]$Major, [int]$Minor)
if ($Major -ge 13) { return "cu130" }
@@ -2353,10 +2217,7 @@ function Get-CudaFamilyForVersion {
return "cpu"
}
-# compatible PyTorch CUDA index tag (e.g. "cu128").
-# PyTorch on Windows ships CPU-only by default from PyPI; CUDA wheels live at
-# https://download.pytorch.org/whl/<tag>. The tag must not exceed the driver's
-# capability: e.g. driver "CUDA Version: 12.9" → cu128 (not cu130).
+# The tag must not exceed the driver's capability: driver CUDA 12.9 -> cu128, not cu130.
function Get-PytorchCudaTag {
# Not rediscovered once detection rejected nvidia-smi (see Get-CudaComputeCapability).
$smiExe = if ($script:NvidiaSmiExe) { $script:NvidiaSmiExe } elseif ($script:NvidiaSmiRejected) { $null } else {
@@ -2376,8 +2237,7 @@ function Get-PytorchCudaTag {
} catch { }
}
if ($null -eq $major) {
- # nvidia-smi absent, stale or hung: the driver library knows the version. With neither,
- # "" means unknown; guessing cu126 replaced a working cu130 venv every update (#9255).
+ # nvidia-smi absent or hung: ask the driver library. "" means unknown; never guess cu126.
$inventory = Get-NvidiaLibraryInventory
if (-not $inventory) { return "" }
$major = $inventory.CudaMajor
@@ -2410,7 +2270,7 @@ function Get-PinnedTorchIndexUrl {
return $null
}
-# Query/fragment dropped first, so .../cu128?token=x classifies as cu128 and does not reinstall.
+# Query/fragment dropped first, so .../cu128?token=x classifies as cu128.
function Get-TorchIndexLeaf {
param([string]$Url)
if ([string]::IsNullOrWhiteSpace($Url)) { return $null }
@@ -2428,8 +2288,7 @@ function Redact-InstallOutput {
return $Text -replace '(https?://[^\s`#]+)#[^\s`]+', '$1#<redacted>'
}
-# A credential-free identity for an index URL (no userinfo, query, fragment or trailing slash),
-# recorded beside the venv and compared across runs.
+# Credential-free identity for an index URL, recorded beside the venv and compared across runs.
function Get-IndexIdentity {
param([string]$Url)
if (-not $Url) { return "" }
@@ -2505,7 +2364,6 @@ function Get-RocmPinStaleTags {
return @{ Expected = "rocm"; Installed = $installed }
}
- # rocmX.Y pin.
if ($_pinVer -and $_instVer) {
# A +rocm7.2 wheel drifted to 2.12 shares the tag but violates the spec, so fold both.
$_pinKnown211 = Test-RocmKnown211Version -Major ([int]$_pinRocm.Groups[1].Value) -Minor ([int]$_pinRocm.Groups[2].Value)
@@ -2526,18 +2384,11 @@ function Get-RocmPinStaleTags {
}
}
-# Bounded "ask python a question" probe, shared by every torch probe below: a wedged torch import
-# or a hanging Intel driver init would block a bare `& python -c ...` forever. ProcessStartInfo,
-# not &, so stderr cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import
-# cannot deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure
-# reads as .Ok = $false, and .Error carries WHICH failure: stderr used to be drained and thrown
-# away, so "the HIP DLLs will not load", "torch is not installed" and "the import never came back"
-# all reached the caller as one silent False -- and one such caller deletes the environment over
-# that answer. Mirrors install.ps1's copy.
+# Bounded python -c probe: a wedged torch import or Intel driver init would hang forever.
+# Both streams drain async; .Error keeps stderr since callers decide venv fate on it. Mirrors install.ps1.
function Invoke-BoundedPythonProbe {
param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)
- # TimedOut separates "never answered" from "answered with a failure": both leave Ok
- # false, only the second says anything about the installation.
+ # TimedOut separates "never answered" from "answered with a failure".
$result = [pscustomobject]@{ Ok = $false; Output = ""; Error = ""; TimedOut = $false }
if (-not $PythonExe -or -not $Code) { return $result }
try {
@@ -2554,15 +2405,12 @@ function Invoke-BoundedPythonProbe {
$errTask = $proc.StandardError.ReadToEndAsync()
if (-not $proc.WaitForExit($TimeoutSec * 1000)) {
try { $proc.Kill() } catch {}
- # Synthesised, not read back: waiting on the reader tasks of a wedged child would
- # reintroduce the hang this helper exists to bound.
+ # Synthesised: waiting on a wedged child's reader tasks would reintroduce the hang.
$result.Error = "python did not answer within $TimeoutSec seconds"
$result.TimedOut = $true
return $result
}
$result.Output = $outTask.GetAwaiter().GetResult()
- # Kept, not discarded: the only place a failed probe's OSError / WinError text exists, and
- # the caller decides what to do with the venv based on it.
$result.Error = $errTask.GetAwaiter().GetResult()
$result.Ok = ($proc.ExitCode -eq 0)
return $result
@@ -2572,13 +2420,11 @@ function Invoke-BoundedPythonProbe {
}
}
-# True when $PythonExe's torch can actually drive an Intel GPU. Quiet on purpose: the three
-# callers read a False differently. Only an XPU build can answer True, so a CPU build never
-# vetoes a migration.
+# True only when an XPU torch build can drive an Intel GPU.
function Test-TorchXpuAvailable {
param([string]$PythonExe)
if (-not $PythonExe) { return $false }
- # Line-anchored so a stdout banner cannot hide the answer; a timeout reads as "no XPU".
+ # Line-anchored so a stdout banner cannot hide the answer; a timeout reads as no XPU.
$probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'
return ($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$')
}
@@ -2596,10 +2442,7 @@ function Test-NvidiaPresenceStaleGpuWheel {
return $script:NvidiaPresenceStaleGpuWheel
}
-# Post-install XPU runtime check. A WMI name match says the part is XPU-capable, not that the
-# compute runtime works: on an old Intel driver the wheel installs fine, never initializes, and
-# unsloth/device_type.py raises NotImplementedError at import -- a hard crash, not a chat-only
-# downgrade. Warn only: the wheel is correct and a driver update fixes it.
+# On an old Intel driver the XPU wheel installs but unsloth raises at import. Warn only.
function Assert-XpuRuntimeReady {
param([string]$PythonExe)
if (Test-TorchXpuAvailable -PythonExe $PythonExe) { return $true }
@@ -2611,11 +2454,8 @@ function Assert-XpuRuntimeReady {
return $false
}
-# Bounded Win32_VideoController scan: the query can block forever on a degraded WMI repository,
-# -ErrorAction only suppresses reported errors, and -OperationTimeoutSec is not enforced for the
-# local COM session this uses, so out of process with a wall-clock kill is the only bound that
-# holds. Ok = $false on an empty answer too, since a Windows host always has an adapter.
-# Mirrors install.ps1's copy.
+# Win32_VideoController can hang on a broken WMI repository and -OperationTimeoutSec is not
+# enforced locally, so run out of process with a wall-clock kill. Mirrors install.ps1.
function Invoke-BoundedVideoControllerScan {
param([int]$TimeoutSec = 15)
# Cached even when Ok = $false: that is the hang case, and a retry would hang again.
@@ -2645,11 +2485,8 @@ function Invoke-BoundedVideoControllerScan {
return $result
}
-# Registry fallback for the scan above, mirroring install_llama_prebuilt.py's
-# windows_intel_gpu_in_registry(): the display-adapter class key, one NNNN subkey per driver
-# config. Weaker than WMI (a config can outlive removed hardware), so it is the fallback here
-# while that function is registry-first -- there a false positive only picks a different
-# llama.cpp bundle, here it would install XPU torch on a host with no Arc. Mirrors install.ps1.
+# Registry fallback, weaker than WMI (configs outlive hardware), so only a fallback here
+# where a false positive installs XPU torch. Mirrors install.ps1.
function Get-IntelRegistryAdapterNames {
$names = @()
$classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
@@ -2682,9 +2519,7 @@ function Get-IntelRegistryAdapterNames {
return $names
}
-# The studio venv directory, guessed from the environment alone. The canonical $VenvDir is
-# resolved ~1100 lines below, far past the hardware report, so the Intel scan needs its own
-# read-only guess. Returns $null when there is nothing to look at; never creates or validates.
+# Read-only guess at the studio venv dir for the early Intel scan; never creates or validates.
function Get-ProbableStudioVenvDir {
$root = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $env:UNSLOTH_STUDIO_HOME.Trim() }
elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $env:STUDIO_HOME.Trim() }
@@ -2705,9 +2540,7 @@ function Get-ProbableStudioVenvDir {
return $null
}
-# Is this venv's torch an XPU wheel? Read off disk, not through the interpreter: version.py
-# carries the full local label ("2.9.1+xpu") and costs nothing, so a CPU-only host never pays for
-# an `import torch`. The dist-info name is NOT usable -- pip normalises the local label out of it.
+# Read version.py off disk (no import). The dist-info name drops the local label.
function Test-VenvTorchIsXpu {
param([string]$VenvPath)
if (-not $VenvPath) { return $false }
@@ -2718,17 +2551,8 @@ function Test-VenvTorchIsXpu {
} catch { return $false }
}
-# Is this venv's torch a ROCm wheel? The AMD counterpart of the check above, for the same reason:
-# on an AMD box whose HIP runtime faulted the DLL load raises OSError (or hangs) while version.py
-# on disk still names a perfectly good wheel, so answering by launching the interpreter that just
-# died is how a working environment got deleted. Read off disk, never imported.
-#
-# The label is always "+rocm", never "+gfx", on every index that publishes wheels:
-# repo.amd.com/rocm/whl/<arch>/torch/ (the Windows wheels, arch in the URL only) ships
-# torch-2.11.0+rocm7.13.0-cp312-cp312-win_amd64.whl, and download.pytorch.org/whl/rocm6.4 ships
-# the two-component 2.8.0+rocm6.4 (Linux only). "gfx" is accepted anyway, cheaply, so a future
-# per-arch local label cannot make this read a ROCm venv as unknown and delete it. The dist-info
-# name is NOT usable either -- pip normalises the local label out of it.
+# Read off disk, never imported: a faulted HIP runtime makes import fail, which wiped good venvs.
+# Labels are "+rocm"; "gfx" is accepted too in case a per-arch label appears.
function Test-VenvTorchIsRocm {
param([string]$VenvPath)
if (-not $VenvPath) { return $false }
@@ -2739,9 +2563,7 @@ function Test-VenvTorchIsRocm {
} catch { return $false }
}
-# The NVIDIA counterpart of the XPU and ROCm on-disk rescues: a wedged display driver hangs or
-# faults `import torch`, and the chain then fell through to a rebuild with a null tag, deleting a
-# healthy CUDA venv with no rollback copy. Returns the FAMILY, since the stale check needs it.
+# A wedged display driver can hang import torch; read the CUDA family off disk instead.
function Get-VenvTorchCudaTag {
param([string]$VenvPath)
if (-not $VenvPath) { return $null }
@@ -2763,9 +2585,7 @@ function Test-VenvTorchIsCuda {
return [bool](Get-VenvTorchCudaTag -VenvPath $VenvPath)
}
-# Same free disk read, plus the supported range: unsloth/models/_utils.py raises at import for an
-# XPU device on torch < 2.6, so flavour alone would call a 2.5+xpu venv fine; 2.11 is the trio's
-# ceiling. Flavour and range ONLY -- whether the runtime reaches the GPU is a driver question.
+# unsloth raises for XPU on torch < 2.6; 2.11 is the ceiling. Flavour and range only.
function Test-VenvTorchIsXpuSupported {
param([string]$VenvPath)
if (-not $VenvPath) { return $false }
@@ -2782,8 +2602,7 @@ function Test-VenvTorchIsXpuSupported {
} catch { return $false }
}
-# VS generator -> MSBuild BuildCustomizations dir; toolset tracks the VS major
-# (18->v180, 17->v170), defaulting to v170 when unparseable.
+# Toolset tracks the VS major (18->v180, 17->v170), defaulting to v170.
function Get-VcBuildCustomizationsDir {
param(
[Parameter(Mandatory)][string]$VsInstallPath,
@@ -2796,7 +2615,6 @@ function Get-VcBuildCustomizationsDir {
return (Join-Path $VsInstallPath "MSBuild\Microsoft\VC\$toolset\BuildCustomizations")
}
-# Installed cmake version, or $null if absent/unparseable.
function Get-CmakeVersion {
$raw = & cmake --version 2>$null | Select-Object -First 1
if ($raw -and ($raw -match '(\d+)\.(\d+)(?:\.(\d+))?')) {
@@ -2806,7 +2624,7 @@ function Get-CmakeVersion {
return $null
}
-# VS 18 2026 generator needs cmake >= 4.2 (added there); true for older VS generators.
+# VS 18 2026 generator needs cmake >= 4.2.
function Test-CmakeSupportsGenerator {
param(
[Parameter(Mandatory)][string]$CmakeVersion,
@@ -2821,7 +2639,7 @@ function Test-CmakeSupportsGenerator {
}
function Test-CmakeListsGenerator {
- # Probe rather than trust the version: a VS-bundled cmake can drive VS 2026 below 4.2. (#6473)
+ # Probe rather than trust the version: a VS-bundled cmake can drive VS 2026 below 4.2.
param([Parameter(Mandatory)][string]$Generator)
$help = & cmake --help 2>$null | Out-String
if (-not $help) { return $false }
@@ -2831,7 +2649,6 @@ function Test-CmakeListsGenerator {
}
function Test-CmakeCanDriveGenerator {
- # cmake can drive $Generator if it lists it (VS-bundled below 4.2) or meets the floor.
param([Parameter(Mandatory)][string]$Generator)
if (Test-CmakeListsGenerator -Generator $Generator) { return $true }
$verObj = Get-CmakeVersion
@@ -2859,7 +2676,6 @@ function Get-FallbackVsGenerator {
# Newest pre-2026 VS whose generator this cmake can drive. vswhere first, for roots like D:\.
$knownEditions = @('BuildTools', 'Community', 'Professional', 'Enterprise', 'Preview')
- # install path if it holds a usable cl.exe, else $null
$tryCandidate = {
param($gen, $installPath)
if (-not $installPath) { return $null }
@@ -2870,7 +2686,6 @@ function Get-FallbackVsGenerator {
return $null
}
- # vswhere (non-default roots)
$vsw = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vsw) {
$json = & $vsw -all -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -format json 2>$null | Out-String
@@ -2880,7 +2695,6 @@ function Get-FallbackVsGenerator {
$label = if ($_.catalog -and $_.catalog.productLineVersion) { [string]$_.catalog.productLineVersion } else { '' }
[pscustomobject]@{ Gen = (Resolve-VsGeneratorFromLabel $label); Path = [string]$_.installationPath }
} | Where-Object { $_.Gen -and ($_.Gen -notmatch 'Visual Studio 18\b') }
- # newest first: 2022 > 2019 > 2017
$ranked = $ranked | Sort-Object { switch -regex ($_.Gen) { '17 2022' {0} '16 2019' {1} '15 2017' {2} default {9} } }
foreach ($cand in $ranked) {
if (-not (Test-CmakeListsGenerator -Generator $cand.Gen)) { continue }
@@ -2890,7 +2704,6 @@ function Get-FallbackVsGenerator {
}
}
- # Program Files scan
$roots = @($env:ProgramFiles, ${env:ProgramFiles(x86)}) | Where-Object { $_ }
$older = @(
@{ Dir = '2022'; Generator = 'Visual Studio 17 2022' },
@@ -2913,7 +2726,7 @@ function Get-FallbackVsGenerator {
return $null
}
-# productLineVersion is the year for VS <= 2022 but "18" for VS 2026; dir names use either form.
+# productLineVersion is the year for VS <= 2022 but "18" for VS 2026.
function Resolve-VsGeneratorFromLabel {
param([string]$Label)
if (-not $Label) { return $null }
@@ -2926,10 +2739,8 @@ function Resolve-VsGeneratorFromLabel {
return $map[$Label.Trim()]
}
-# Find VS Build Tools for cmake -G: vswhere, then a filesystem scan (handles broken
-# vswhere registration). Returns @{ Generator; InstallPath; Source } or $null.
+# Returns @{ Generator; InstallPath; Source } or $null.
function Find-VsBuildTools {
- # vswhere first (works when VS is properly registered)
$vsw = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vsw) {
$info = & $vsw -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property catalog_productLineVersion 2>$null
@@ -2942,7 +2753,7 @@ function Find-VsBuildTools {
}
}
- # filesystem scan (handles broken vswhere registration); VS 2026+ dir is "18"
+ # Filesystem scan handles broken vswhere registration; VS 2026+ dir is "18".
$roots = @($env:ProgramFiles, ${env:ProgramFiles(x86)}) | Where-Object { $_ }
$knownEditions = @('BuildTools', 'Community', 'Professional', 'Enterprise', 'Preview')
$dirs = @('18', '2026', '2022', '2019', '2017')
@@ -2953,7 +2764,7 @@ function Find-VsBuildTools {
foreach ($r in $roots) {
$vsBase = Join-Path $r "Microsoft Visual Studio\$d"
if (-not (Test-Path $vsBase)) { continue }
- # VS 2026 (dir "18") may use non-standard edition names, so scan every subdir
+ # VS 2026 may use non-standard edition names, so scan every subdir.
if ($d -eq '18' -or $d -eq '2026') {
$editionCandidates = Get-ChildItem -Path $vsBase -Directory -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName }
} else {
@@ -3041,7 +2852,6 @@ function Test-LlamaBuildToolsInstallAllowed {
# Deferred from Phase 1 so the prebuilt path never pays for the multi-GB install.
function Ensure-BuildToolsForLlamaSourceBuild {
- # CMake
if ($null -eq (Get-Command cmake -ErrorAction SilentlyContinue)) {
Write-StudioLine "CMake not found -- installing via winget (needed for the llama.cpp source build)..." -ForegroundColor Yellow
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
@@ -3050,7 +2860,7 @@ function Ensure-BuildToolsForLlamaSourceBuild {
Refresh-Environment
} catch { }
}
- # winget may install cmake but not put it on PATH yet; try the default dir
+ # winget may install cmake without putting it on PATH yet.
if ($null -eq (Get-Command cmake -ErrorAction SilentlyContinue)) {
$cmakeDefaults = @(
"$env:ProgramFiles\CMake\bin",
@@ -3068,7 +2878,6 @@ function Ensure-BuildToolsForLlamaSourceBuild {
if ($null -ne (Get-Command cmake -ErrorAction SilentlyContinue)) { step "cmake" "installed" }
}
- # VS Build Tools
if ($script:VsInstallPath) { return } # already detected by the early probe
$vsResult = Find-VsBuildTools
if (-not $vsResult) {
@@ -3079,7 +2888,7 @@ function Ensure-BuildToolsForLlamaSourceBuild {
$ErrorActionPreference = "Continue"
winget install Microsoft.VisualStudio.2022.BuildTools --source winget --accept-package-agreements --accept-source-agreements --override "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --passive --wait"
$ErrorActionPreference = $prevEAPTemp
- # Re-scan after install (don't trust vswhere catalog)
+ # Re-scan after install; do not trust the vswhere catalog.
$vsResult = Find-VsBuildTools
}
}
@@ -3097,8 +2906,7 @@ function Ensure-BuildToolsForLlamaSourceBuild {
}
}
-# Machine arch: PROCESSOR_ARCHITECTURE describes this PROCESS, so an emulated x64 shell on
-# ARM64 reports AMD64; PROCESSOR_ARCHITEW6432 is ARM64 in exactly that case.
+# PROCESSOR_ARCHITECTURE describes the process; PROCESSOR_ARCHITEW6432 is ARM64 under x64 emulation.
function Get-HostMachineArch {
$osArch = ""
try { $osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { }
@@ -3111,10 +2919,7 @@ function Get-HostMachineArch {
return "other"
}
-# Detect the VC++ 2015-2022 Redistributable prebuilt llama-server and PyTorch need (they
-# link VCRUNTIME140_1.dll, absent from the Universal CRT). Registry first: Runtimes\x64 is
-# the only x64-specific proof; System32\vcruntime140_1.dll is arch-blind and on ARM64 may
-# be the ARM64-only package, unloadable under x64 emulation.
+# Registry first: System32\vcruntime140_1.dll is arch-blind and may be ARM64-only.
function Test-VCRedistInstalled {
foreach ($k in @(
'HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
@@ -3131,8 +2936,7 @@ function Test-VCRedistInstalled {
return $false
}
-# Install the VC++ 2015-2022 runtime if missing (non-fatal; usually a no-op). Unlike CMake
-# and Build Tools torch cannot import without it, and winget is absent on LTSC/Server images.
+# Installs the VC++ runtime if missing (non-fatal): torch cannot import without it.
function Ensure-VCRedist {
if (Test-VCRedistInstalled) { step "vcredist" "present"; return }
if ($StageRoot) { step "vcredist" "missing; unchanged during staging" "Yellow"; return }
@@ -3150,19 +2954,11 @@ function Ensure-VCRedist {
} catch { substep "VCRedist install failed: $($_.Exception.Message)" "Yellow" }
}
if (-not (Test-VCRedistInstalled)) {
- # Evergreen link; /quiet /norestart so it never blocks or reboots an unattended run.
- # Always the x64 package, deliberately: Microsoft ships it as the Arm64X superset of
- # both ARM64 and X64 binaries and documents it as the one for ARM64 devices, while
- # the arm64 package is ARM64-only (learn.microsoft.com/cpp/windows/latest-supported-vc-redist).
- # PROCESSOR_ARCHITECTURE is wrong twice here: it reports the process, and the runtime
- # must match the interpreter loading the DLLs, an emulated x64 Python not yet created.
+ # Always the x64 package: it is the Arm64X superset Microsoft recommends for ARM64 too.
$url = "https://aka.ms/vs/17/release/vc_redist.x64.exe"
$dst = Join-Path ([System.IO.Path]::GetTempPath()) "vc_redist.x64.exe"
substep "winget unavailable or failed; downloading the runtime directly..."
- # Windows PowerShell 5.1 on an old image can carry a .NET default protocol set that
- # predates TLS 1.2, which aka.ms refuses -- exactly the no-winget host this fallback
- # exists for. SystemDefault (0) means "let the OS choose" and already covers TLS 1.2+,
- # so only an explicit legacy set is upgraded, and it is restored afterwards.
+ # Old 5.1 images may default to pre-TLS 1.2 protocols, which aka.ms refuses.
$_prevProtocol = $null
try {
$_cur = [System.Net.ServicePointManager]::SecurityProtocol
@@ -3173,10 +2969,7 @@ function Ensure-VCRedist {
} catch { $_prevProtocol = $null }
try {
Invoke-WebRequest -Uri $url -OutFile $dst -UseBasicParsing -TimeoutSec 300
- # HTTPS secures the transfer, not the payload, and this runs with the setup
- # process's privileges. The evergreen URL rules out a SHA-256 pin (the bytes
- # change with every VS servicing update), so check the publisher. Status alone
- # is not enough: any trusted CA's code-signing cert passes it.
+ # Evergreen URL rules out a SHA-256 pin, so verify the publisher, not just Status.
$sig = Get-AuthenticodeSignature -LiteralPath $dst
if ($sig.Status -ne [System.Management.Automation.SignatureStatus]::Valid -or
$null -eq $sig.SignerCertificate -or
@@ -3184,7 +2977,7 @@ function Ensure-VCRedist {
throw "the downloaded VC++ runtime is not validly signed by Microsoft (signature status: $($sig.Status))"
}
$p = Start-Process -FilePath $dst -ArgumentList '/quiet', '/norestart' -Wait -PassThru
- # 3010 = success, reboot required; usable either way.
+ # 3010 = success, reboot required.
if ($p.ExitCode -notin @(0, 3010)) {
substep "VC++ runtime installer exited $($p.ExitCode)" "Yellow"
}
@@ -3207,36 +3000,17 @@ function Ensure-VCRedist {
}
# ─────────────────────────────────────────────
-# Output style (aligned with studio/setup.sh: step / substep)
# ─────────────────────────────────────────────
$Rule = [string]::new([char]0x2500, 52)
function Enable-StudioVirtualTerminal {
if ($env:NO_COLOR) { return $false }
- # A redirected stdout is not a console, so there is no virtual terminal to speak of. The CLI and
- # the desktop app both pipe us, so that is the path they are on, and it is decided here before
- # anything else is consulted.
+ # A redirected stdout is not a console.
if ($script:StudioStdoutRedirected) { return $false }
- # Windows PowerShell's console host already does the GetStdHandle / GetConsoleMode /
- # SetConsoleMode sequence this function used to do by hand, at startup, and reports
- # the outcome through this property, and it is STRICTER than what this replaced:
- # ConsoleHostUserInterface.TryTurnOnVirtualTerminal re-reads the mode after setting it, because
- # older systems accept the call and ignore the flag. The deleted code trusted SetConsoleMode's
- # return value. So the property cannot read True while VT is actually off.
- #
- # Measured on Windows PowerShell 5.1.26100 attached to a real console: the property answers True,
- # the native call answers True, and the console mode read BEFORE touching it is already 0x7 --
- # which contains 0x4, ENABLE_VIRTUAL_TERMINAL_PROCESSING. The SetConsoleMode this replaced was
- # re-setting a bit the host had already set. It was a no-op. The measurement and the lane that
- # produced it are in PR #10984; the record that travels with this repo is in
- # tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD).
- #
- # [bool] rather than a bare return: the property is virtual with a base of $false, so a host
- # that does not override it answers $false already -- but a host with no UI at all yields $null,
- # and the cast makes that $false too. The try/catch is for Set-StrictMode in a caller's profile,
- # where reading an absent property raises PropertyNotFoundException rather than returning $null.
+ # The host already enables VT at startup and verifies it; see PR #10984 and
+ # tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD). try/catch for caller StrictMode.
try { return [bool]$Host.UI.SupportsVirtualTerminal } catch { return $false }
}
$script:StudioVtOk = Enable-StudioVirtualTerminal
@@ -3294,7 +3068,6 @@ function Invoke-SetupCommand {
$prevEap = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try {
- # Reset to avoid stale values from prior native commands.
$global:LASTEXITCODE = 0
if ($script:UnslothVerbose -and -not $AlwaysQuiet) {
# PS 5.1 turns stderr records into $? = $false even on exit 0; redact per record.
@@ -3337,14 +3110,8 @@ function Write-LlamaFailureLog {
Write-StudioLine " | $line" -ForegroundColor DarkGray
}
}
-# Plain (no ANSI) form of a step/substep message on the OS stdout handle.
-# Write-Host on 5.1 goes through the Information stream, which does not survive
-# every install.ps1 -> python -> powershell.exe chain.
-#
-# One half of an either/or: when redirected this is the ONLY sink. It used to
-# run in ADDITION to Write-Host, assuming that never reached the pipe. It does,
-# because the CLI spawns us as `-Command "& 'setup.ps1' *>&1"`, so every step
-# printed twice.
+# Plain step/substep text on the OS stdout handle. When redirected this is the ONLY sink:
+# the CLI runs us with *>&1, so also calling Write-Host printed every step twice.
function Write-StudioStdoutMirror {
param([Parameter(Mandatory = $true)][string]$Line)
try {
@@ -3362,8 +3129,6 @@ function step {
[string]$Color = "Green"
)
$padded = if ($Label.Length -ge 15) { $Label.Substring(0, 15) } else { $Label.PadRight(15) }
- # Exactly one sink: the console handle when redirected, Write-Host (the only
- # one that colorizes) when interactive.
if ($script:StudioStdoutRedirected) {
Write-StudioStdoutMirror (" {0}{1}" -f $padded, $Value)
return
@@ -3387,9 +3152,7 @@ function step {
'DarkGray' { 'DarkGray' }
default { 'DarkGreen' }
}
- # One composed record, not `-NoNewline` label + value: two Write-Host
- # calls are two Information records, and a redirected consumer turns each
- # boundary into a line break. Costs the dimmed label on no-VT consoles.
+ # One record: two Write-Host calls become two lines for a redirected consumer.
Write-Host (" {0}{1}" -f $padded, $Value) -ForegroundColor $fc
}
}
@@ -3399,7 +3162,6 @@ function substep {
[Parameter(Mandatory = $true)][string]$Message,
[string]$Color = "DarkGray"
)
- # Exactly one sink, as in `step` above.
if ($script:StudioStdoutRedirected) {
Write-StudioStdoutMirror (" {0,-15}{1}" -f "", $Message)
return
@@ -3420,16 +3182,13 @@ function substep {
}
}
-# Matched on npm's error code line, not anywhere in the log: Windows cleanup warnings
-# carry EPERM after a network failure too. FetchError names registry.npmjs.org even
-# on a local errno, so this runs before the network check (#8725).
+# Match npm's error code line only (cleanup warnings carry EPERM too); runs before the network check.
$script:NpmLocalFailureRe = 'npm (error|ERR!) code (EACCES|EPERM|EBUSY|ENOSPC|ENFILE|EMFILE)|operation was rejected by your operating system'
# Keep in sync with _suggest_npm_registry in studio/setup.sh.
$script:NpmNetworkFailureRe = '40[13]|ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ConnectionRefused|failed to resolve|registry\.npmjs\.org|getaddrinfo|tunneling socket|network|proxy|self.?signed|unable to (get|verify)'
function Show-NpmLocalFailureHint {
- # -Socket: FetchError with no "npm error path" line, i.e. the OS refused node.exe's
- # socket (per-program firewall / antivirus rule). A cache write failure has a path.
+ # -Socket: FetchError with no path line means the OS refused node.exe's socket.
param([switch]$Socket)
Write-StudioLine ""
if ($Socket) {
@@ -3456,7 +3215,6 @@ function Invoke-NpmMirrorRetry {
}
function Show-NpmRegistryHint {
- # Empty output (verbose runs stream npm) keeps the unconditional registry hint.
param([string]$FailureOutput = "")
if ($FailureOutput) {
$FailureOutput = $FailureOutput -replace "$([char]27)\[[0-9;]*m", ''
@@ -3466,8 +3224,7 @@ function Show-NpmRegistryHint {
if ($env:UNSLOTH_NPM_REGISTRY) { return }
$mirror = $env:NPM_CONFIG_REGISTRY
if (-not $mirror) {
- # Read npm config from a dir with no project .npmrc so the frontend's pinned
- # registry= does not mask the user's ~/.npmrc / global mirror.
+ # Read npm config outside the project so the frontend's pinned registry= does not mask the user's.
$pushed = $false
try {
Push-Location ([System.IO.Path]::GetTempPath()) -ErrorAction Stop
@@ -3505,25 +3262,18 @@ if ($script:StudioVtOk -and -not $env:NO_COLOR) {
Write-StudioLine " $Rule" -ForegroundColor DarkGray
}
-# WebView2 caches keyed by the bundle id can keep serving the previous frontend
-# after an update. Cache-only: storage, cookies, settings, models and the studio
-# database are untouched. Called only once the UNSLOTH_STUDIO_HOME / STUDIO_HOME
-# override is validated, so a mistyped override cannot wipe the cache and then abort.
+# Clear WebView2 caches (cache only) so the old frontend is not served after an update.
+# Called only after the home override is validated.
function Clear-WebViewCaches {
if (-not $env:LOCALAPPDATA) { return }
$wvDefault = Join-Path $env:LOCALAPPDATA "ai.unsloth.studio\EBWebView\Default"
- # Drop the version stamp first. The old WebView still holds these files, which is
- # why the removals below can fail; the app's own clear is the retry, and it is
- # skipped while the stamp matches the running version. Unconditional, since a
- # repair or a local rebuild leaves the version unchanged and a redundant clear on
- # the next launch is the cheap side of the trade.
+ # Drop the version stamp first so the app retries the clear on next launch if removals fail.
Remove-Item -LiteralPath (Join-Path $env:LOCALAPPDATA "ai.unsloth.studio\.webview-cache-cleared") `
-Force -ErrorAction SilentlyContinue
$wvCleared = $false
foreach ($wvSub in @("Cache", "Code Cache", "GPUCache", "Service Worker")) {
$wvPath = Join-Path $wvDefault $wvSub
- # Get-Item -Force, not Test-Path: the probe throws on an ACL denial under
- # "Stop", and a reparse point must be unlinked, not recursed into.
+ # Get-Item -Force, not Test-Path: Test-Path throws on ACL denial and reparse points must be unlinked.
$wvItem = Get-Item -LiteralPath $wvPath -Force -ErrorAction SilentlyContinue
if (-not $wvItem) { continue }
try {
@@ -3535,8 +3285,7 @@ function Clear-WebViewCaches {
if ($wvCleared) { substep "cleared stale WebView caches (ai.unsloth.studio); settings and data kept" }
}
-# install.ps1 (SKIP_STUDIO_BASE=1) already reported this for the install it drives, so this
-# covers direct setup, update and desktop repair. Keep in step with the copies in install.ps1.
+# Elevation report; install.ps1 (SKIP_STUDIO_BASE=1) already printed it. Keep in step with its copies.
if ($env:SKIP_STUDIO_BASE -ne "1") {
$ElevationState = "unknown"
try {
@@ -3572,7 +3321,6 @@ if ($env:SKIP_STUDIO_BASE -ne "1") {
}
if ($ElevationState -eq "true") {
- # $StudioHome is resolved much later, so mirror its precedence for the message only.
# USERPROFILE can be unset (service, CI), where a bare Join-Path throws under Stop.
$_unslothRoot = if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
'%USERPROFILE%\.unsloth'
@@ -3588,7 +3336,6 @@ if ($env:SKIP_STUDIO_BASE -ne "1") {
} else {
$_unslothRoot
}
- # A legacy-equal override is not a custom root: name the parent that holds llama.cpp.
if ((Get-CanonicalRootPath $_elevRoot) -ieq
(Get-CanonicalRootPath (Join-Path $_unslothRoot "studio"))) {
$_elevRoot = $_unslothRoot
@@ -3603,10 +3350,7 @@ if ($env:SKIP_STUDIO_BASE -ne "1") {
}
}
-# Resolve and preflight the install root before phase 1, with the same override
-# precedence as the other resolvers. Everything below joins onto USERPROFILE, so a
-# blank one must fail here instead of throwing a raw binding error under "Stop".
-# Null or empty only: Join-Path accepts whitespace, and those runs used to complete.
+# Everything joins onto USERPROFILE; null/empty must fail here (whitespace is accepted).
if ([string]::IsNullOrEmpty($env:USERPROFILE)) {
Write-StudioLine "ERROR: USERPROFILE is not set." -ForegroundColor Red
Exit-SetupFailure "USERPROFILE is not set"
@@ -3650,35 +3394,18 @@ $StageRoot = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_STAGE_ROO
$RuntimeRoot = if ($StageRoot) { $StageRoot } else { $StudioHome }
$VenvDir = Join-Path $RuntimeRoot "unsloth_studio"
$StudioOwnedMarker = ".unsloth-studio-owned"
-# Dropped into an environment this script has moved aside, so the sweep that removes such copies
-# can tell one it made from a directory that merely wears the same name. Written after the rename
-# and rewritten if the delete that follows fails, because a half-deleted copy can lose everything
-# else that identified it.
+# Marks venvs this script moved aside, so the sweep never deletes a lookalike.
$StudioStaleMarker = ".unsloth-studio-stale"
# Mirrors install_manifest.NO_TORCH_MARKER; keep the two in step.
$NoTorchMarker = ".unsloth-no-torch"
$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
$StudioHomeIsCustom = Test-StudioHomeIsCustom
-# Ownership applies to node\, llama.cpp\ and whisper.cpp\ whenever a master root moves them,
-# even with $StudioHome left at the legacy path: $StudioHomeIsCustom is false there, and false
-# is what licenses the installers to replace and delete without the Unsloth-owned marker. The
-# Studio home itself, and the venvs under it, keep the other flag. Mirrors setup.sh.
+# Mirrors setup.sh: runtime-root ownership is separate from the Studio home flag.
$RuntimeRootIsCustom = $StudioHomeIsCustom
-# Keyed on where the runtimes LAND, not on whether a master root was named: UNSLOTH_HOME set to
-# the root an install already uses moves nothing, and calling that custom would demand an owner
-# marker from a legacy source-built .unsloth\llama.cpp that predates markers. The comparison
-# setup.sh makes; taking any non-empty master root instead was a real divergence.
-#
-# Staging is excluded for the same reason, not as an exception to it: Get-ManagedLlamaCppDir
-# gives $StageRoot precedence over the master root, so during a staged update the master root is
-# not where anything lands. ASSIGNED, not merely raised, or a custom Studio home whose runtimes
-# land in the legacy root keeps the flag true and demands markers from exactly the pre-marker
-# tree this comparison exists to spare.
+# Keyed on where runtimes LAND, as setup.sh does. A staged update lands in $StageRoot, so it is excluded.
$_masterRootForOwnership = Get-MasterRootOverride
if ($_masterRootForOwnership -and -not $StageRoot) {
- # Canonicalised the same way Get-MasterRootOverride canonicalises its answer, or a
- # junctioned profile compares unequal to itself. Case-insensitively, since two Windows
- # paths differing only in case are one directory.
+ # Canonicalised like Get-MasterRootOverride, compared case-insensitively.
$_legacyRuntimeRoot = Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth")
$RuntimeRootIsCustom = ($_masterRootForOwnership -ine $_legacyRuntimeRoot)
}
@@ -3698,17 +3425,10 @@ function Test-MasterRootNoteIsHonoured {
if (-not $norm) { return $false }
$here = Get-CanonicalDir -Path $StudioRoot
if (-not $here) { return $false }
- # The legacy default is the one root every reader finds without help, and both uninstallers
- # refuse it outright. Recording it turned a one-command UNSLOTH_HOME=%USERPROFILE%\.unsloth
- # into a permanent portable install: every later bare launch read it back and HF_HUB_CACHE
- # moved off the shared Hugging Face cache this change promises not to move.
+ # Never record the legacy default root: readers would then treat every launch as portable.
$legacy = Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth")
if ($legacy -and ($norm -ieq $legacy)) { return $false }
- # Keyed on the TREE as well, because that is what the readers key on: storage_roots'
- # _is_legacy_studio_tree and the CLI both decline ANY note found in the legacy Studio tree,
- # whatever it records. Without this, UNSLOTH_HOME=%USERPROFILE% passed containment (the
- # legacy tree is inside the profile) and is not the legacy root, so the note was written,
- # warned about nothing, and was then honoured by nobody.
+ # Readers ignore any note inside the legacy Studio tree, so do not write one there.
$legacyStudio = Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")
if ($legacyStudio -and ($here -ieq $legacyStudio)) {
Write-StudioLine " note: the managed runtimes were installed under $norm, but Unsloth Studio is the" -ForegroundColor Yellow
@@ -3739,15 +3459,10 @@ if ((Get-MasterRootOverride) -and -not $StageRoot -and
if (-not (Test-Path -LiteralPath $noteDir -PathType Container)) {
[void][System.IO.Directory]::CreateDirectory($noteDir)
}
- # Staged then renamed: a reader that caught a half-written note would name a truncated
- # path, and this note licenses deletions.
+ # Staged then renamed: this note licenses deletions, so it must never be half-written.
$notePath = Join-Path $noteDir ".unsloth-master-root"
$noteBytes = [System.Text.Encoding]::UTF8.GetBytes($UnslothHome + [Environment]::NewLine)
- # Nothing to do when the note already says this, which is every run after the first.
- # Move-Item -Force is NOT an atomic replace: the provider deletes the destination then
- # moves the source, so an interruption leaves NO note and a backend that looks next
- # caches "no master root". Re-entering that window to rewrite identical bytes is the
- # avoidable half.
+ # Move-Item -Force is not atomic, so skip rewriting identical bytes.
$noteCurrent = $null
try {
if (Test-Path -LiteralPath $notePath -PathType Leaf) {
@@ -3762,10 +3477,7 @@ if ((Get-MasterRootOverride) -and -not $StageRoot -and
}
}
if (-not $noteSame) {
- # An unpredictable name opened CreateNew, not "$notePath.$PID" through WriteAllText:
- # the predictable pair lets anyone who can write share/ precreate that name as a link
- # and have this write land on its target. Move-Item -Force replaces a link at the
- # final path rather than following it.
+ # Random name opened CreateNew: a predictable temp name could be precreated as a link.
$noteTmp = Join-Path $noteDir (".unsloth-master-root." + [System.IO.Path]::GetRandomFileName())
try {
$noteStream = [System.IO.File]::Open(
@@ -3779,13 +3491,10 @@ if ((Get-MasterRootOverride) -and -not $StageRoot -and
} finally {
$noteStream.Dispose()
}
- # Move-Item -Force, not [IO.File]::Move with an overwrite flag: that overload is
- # .NET Core only and setup.ps1 still runs under Windows PowerShell 5.1.
+ # [IO.File]::Move with overwrite is .NET Core only; 5.1 lacks it.
Move-Item -LiteralPath $noteTmp -Destination $notePath -Force
$noteTmp = $null
} finally {
- # The staging file is unreadable to every reader but still occupies share/, and
- # nothing else ever removes it. Cleared whether the move threw or not.
if ($noteTmp) { Remove-Item -LiteralPath $noteTmp -Force -ErrorAction SilentlyContinue }
}
}
@@ -3794,16 +3503,11 @@ if ((Get-MasterRootOverride) -and -not $StageRoot -and
}
}
-# Clear a note an earlier run left naming the legacy default root, whatever this run was asked
-# to do: the gate above stops new ones, but an install that already has one keeps reading it
-# back and no later update would reach the write block to correct it. Narrow on purpose -- both
-# uninstallers already refuse this value, so removing it takes nothing a reader could act on.
+# Clear a stale note naming the legacy root; both uninstallers already refuse that value.
try {
$staleNote = Join-Path (Join-Path $StudioHome "share") ".unsloth-master-root"
if (Test-Path -LiteralPath $staleNote -PathType Leaf) {
- # -Encoding UTF8: the writer emits BOM-less UTF-8 and Windows PowerShell 5.1 decodes
- # BOM-less input with the ANSI code page, so a root holding non-ASCII read back
- # mangled and never matched the value this sweep exists to clear.
+ # -Encoding UTF8: 5.1 decodes BOM-less input as ANSI.
$staleValue = (Get-Content -LiteralPath $staleNote -TotalCount 1 -Encoding UTF8 -ErrorAction Stop)
if ($staleValue) { $staleValue = $staleValue.Trim() }
if ($staleValue) {
@@ -3819,7 +3523,7 @@ try {
}
}
} catch {
- # A note this run cannot read is one it has no business deleting.
+ # A note this run cannot read is not ours to delete.
}
$WithLlamaCppDir = $null
@@ -3856,21 +3560,18 @@ if (-not $StageRoot) {
}
# ==========================================================================
-# PHASE 1: System-level prerequisites (winget installs, env vars)
-# All heavy system tool installs happen here BEFORE touching Python.
+# PHASE 1: System-level prerequisites (winget installs, env vars)
# ==========================================================================
# ============================================
-# 1a. GPU detection
+# A wedged driver can block nvidia-smi; WaitForExit bounds it.
# ============================================
-# A wedged driver can block nvidia-smi during init or after a reset; WaitForExit bounds it.
function Invoke-NvidiaSmiBounded {
param(
[Parameter(Mandatory = $true, Position = 0)][string]$Exe,
[Parameter(Position = 1)][string[]]$SmiArgs = @(),
[int]$TimeoutSec = 10,
- # Driver warnings on stderr would corrupt machine-readable --query-gpu
- # output; the human-readable probes keep the default merge.
+ # Driver warnings on stderr would corrupt machine-readable --query-gpu output.
[switch]$StdoutOnly
)
try {
@@ -3899,28 +3600,8 @@ function Invoke-NvidiaSmiBounded {
}
# ── BEGIN SHARED WITH install.ps1 (Get-NvidiaSmiCandidatePaths) ──
-# Every directory nvidia-smi might be in, in the order worth trying, filtered to the ones that
-# actually hold the binary. Callers still run their own Test-NvidiaSmiHasGpu over the result:
-# existing is not the same as answering.
-#
-# Only two locations were searched before, and each addition below is a host where a real NVIDIA
-# GPU was reported absent, which sends the installer to CPU-only PyTorch:
-#
-# SysNative From a 32-bit process "System32" is redirected to SysWOW64, which has no
-# nvidia-smi. SysNative is the alias that reaches the real System32.
-# ProgramW64 In that same process $env:ProgramFiles is "Program Files (x86)".
-# ProgramW6432 is the 64-bit Program Files whatever the process bitness.
-# x86 Not the driver's own location, but a machine that once had a 32-bit
-# toolkit can carry a working copy there.
-# DriverStore Where the driver package itself lives. Present on hosts where the copy
-# into System32 did not happen, which is the #9255 population.
-#
-# Nothing is removed. One ordering does change, and deliberately: the two call sites disagreed
-# with each other before, one trying System32 first and the other the NVSMI directory first, and
-# a single list cannot keep both. System32 wins, because that is where the current driver puts
-# its copy; NVSMI is the legacy location and a machine carrying both can have an older binary
-# there reporting an older CUDA version. This only affects a host that has both, and only in
-# which of two working binaries answers.
+# nvidia-smi dirs in preference order, filtered to ones holding the binary (SysNative/ProgramW6432 for
+# 32-bit processes, DriverStore). System32 before legacy NVSMI, which may hold an older binary.
function Get-NvidiaSmiCandidatePaths {
$dirs = @()
# Current driver locations first, in BOTH process bitnesses, before any legacy one.
@@ -3977,9 +3658,7 @@ function Get-NvidiaSmiCandidatePaths {
# ── END SHARED WITH install.ps1 (Get-NvidiaSmiCandidatePaths) ──
# A driverless nvidia-smi exits 0 listing no GPU, so require a "GPU <n>:" row.
-# 124 is what Invoke-NvidiaSmiBounded reports when it had to kill the probe. Recorded so
-# the banner below can skip a second query: detection already waited out the full bound on
-# this binary, and asking a hung nvidia-smi again only doubles the stall.
+# 124 means the bounded runner killed the probe; recorded so the banner skips a second query.
$script:NvidiaSmiWedged = $false
# Reset per run: streamed execution shares the caller's script scope.
$script:NvidiaPresenceOnly = $false
@@ -4008,51 +3687,18 @@ try {
}
} catch {}
if (-not $HasNvidiaSmi) {
- # Two passes, not one, and the reason is the ordering this change introduces. Listing a GPU is
- # not the same as being able to report a CUDA version: a partially installed or stale utility
- # can answer -L and still print a banner the version ladder cannot parse. Taking the first
- # binary that merely lists a GPU could hand a newer-capable host an older CUDA family purely
- # because of which directory is searched first. Prefer a candidate that answers BOTH, and
- # settle for one that just lists a GPU only if none does.
- #
- # One deadline across the whole loop, not just the per-call one. Each candidate gets its own
- # bounded runner, and on a host with a wedged driver every one of them waits out that bound
- # before failing. The list is longer than it was, so what used to be two stalls could now be
- # ten, and all of it is spent in front of the driver-library fallback that would have answered
- # in milliseconds. The bound is on TIME rather than on the number of candidates because the
- # cost being controlled is time: a machine where every probe answers at once still gets to
- # try them all, and one where they hang stops early.
- #
- # Get-Date rather than a Stopwatch: Constrained Language Mode refuses the method calls, and
- # this runs on hosts that enforce it.
- # Enumerated BEFORE the clock starts. Discovery is Test-Path calls, but on a machine with a
- # filesystem filter driver or slow storage it is not free, and charging it to the probe
- # budget is how a slow disk turns into no GPU.
+ # Prefer a candidate that lists a GPU AND prints a parseable CUDA banner; else the first that lists.
+ # Get-Date, not Stopwatch (CLM). Candidates are enumerated before the clock starts.
$smiCandidates = @(Get-NvidiaSmiCandidatePaths)
- # Two budgets, because "stop early" means two different things here.
- #
- # The soft one applies ONLY once a usable answer is already in hand: there is a working
- # nvidia-smi, and continuing just looks for a better CUDA banner. Giving that up costs at
- # most a wheel family.
- #
- # The hard one is the only thing allowed to end the search with NOTHING found, because that
- # outcome is CPU-only PyTorch on a machine with a GPU. The first version of this had a single
- # budget and broke out of the loop after one slow failure, so a host whose System32 copy is
- # broken and whose legacy NVSMI copy works lost its GPU entirely. That is strictly worse than
- # the stall it was added to prevent.
+ # Soft deadline applies only once a usable answer exists; only the hard one may end with nothing,
+ # since finding nothing means CPU-only PyTorch.
$probeDeadline = (Get-Date).AddSeconds(30)
$probeHardDeadline = (Get-Date).AddSeconds(60)
$firstListing = $null
- # Captured beside the path, because $script:NvidiaSmiWedged describes the LAST binary probed
- # and the one this loop settles on can be an earlier one. Captured rather than assumed to be
- # false: it is false today because a candidate only becomes $firstListing when its -L probe
- # succeeded, and that is a property of Test-NvidiaSmiHasGpu rather than of this loop.
+ # $script:NvidiaSmiWedged describes the LAST binary probed, not necessarily the one selected.
$firstListingWedged = $false
foreach ($p in $smiCandidates) {
- # Only give up early when there is already something to fall back on.
if ($null -ne $firstListing -and (Get-Date) -gt $probeDeadline) { break }
- # With nothing found, keep going to the hard bound. Reporting no GPU is the expensive
- # answer, so it has to be the one that costs the most before it is reached.
if ((Get-Date) -gt $probeHardDeadline) { break }
try {
if (-not (Test-NvidiaSmiHasGpu $p)) { continue }
@@ -4060,11 +3706,7 @@ if (-not $HasNvidiaSmi) {
$firstListing = $p
$firstListingWedged = $script:NvidiaSmiWedged
}
- # Rechecked here, not only at the top. The listing probe that just returned can have
- # spent most of its own bound, and the banner probe below has a full bound of its
- # own, so a candidate starting just inside the deadline could add nearly twice the
- # per-probe timeout after it. There is already a usable answer in $firstListing at
- # this point, so stopping costs at most a wheel family.
+ # Rechecked: the listing probe may have used most of its bound.
if ((Get-Date) -gt $probeDeadline) { break }
$banner = Invoke-NvidiaSmiBounded $p
if ($banner -match 'CUDA(?: UMD)? Version:\s+\d+\.\d+') {
@@ -4078,11 +3720,7 @@ if (-not $HasNvidiaSmi) {
if (-not $HasNvidiaSmi -and $firstListing) {
$HasNvidiaSmi = $true
$NvidiaSmiExe = $firstListing
- # Restored for the binary actually selected. A later candidate that timed out leaves the
- # flag set for ITS path, and the guard downstream reads the flag to decide whether to ask
- # the selected binary for the name, the compute capability and the driver version. Left
- # alone, a working nvidia-smi would be treated as wedged and all three queries skipped
- # because a different binary elsewhere on the machine hung.
+ # Restore the wedged flag for the selected binary, not a later one that timed out.
$script:NvidiaSmiWedged = $firstListingWedged
Write-StudioLine " Found nvidia-smi at $(Split-Path $firstListing -Parent)" -ForegroundColor Gray
}
@@ -4115,8 +3753,6 @@ function Get-NvidiaRegistryAdapter {
return [pscustomobject]@{ Release = $versions[0] }
}
-# True when no healthy NVIDIA adapter reports an NVIDIA-shaped driver version (e.g. Microsoft Basic
-# Display): no CUDA driver, so the host must keep CPU wheels and AMD / Intel detection.
function Test-NvidiaAdapterWithoutNvidiaDriver {
param($Scan = $null)
if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
@@ -4133,8 +3769,7 @@ function Test-NvidiaAdapterWithoutNvidiaDriver {
return $foreign
}
-# VEN_10DE and ConfigManagerErrorCode 0 only, never names: a false yes sets $HasNvidiaSmi and
-# switches off AMD and Intel detection.
+# VEN_10DE and ConfigManagerErrorCode 0 only: a false yes switches off AMD and Intel detection.
function Test-NvidiaAdapterPresent {
param($Scan = $null)
@@ -4150,9 +3785,8 @@ function Test-NvidiaAdapterPresent {
return $false
}
-# Keeps the promotion additive: a hybrid host already gets AMD or Intel wheels.
-# Must match the Intel route's pattern exactly (asserted by test_nvidia_adapter_presence.ps1); a
-# function, not a $script: variable, since an unset $null pattern matches every string.
+# Must match the Intel route's pattern exactly (asserted by test_nvidia_adapter_presence.ps1).
+# A function, since an unset $script: pattern would match every string.
function Get-XpuCapableNameRegex { return "(?i)Intel.*(Arc|Data Center GPU)" }
function Test-IntelXpuRuntimeProven {
@@ -4224,7 +3858,6 @@ function Test-OtherVendorAdapterPresent {
}
# Ported from studio/nvidia_probe.py's cuda_version_for_driver; the parity test generates the table.
-# Kept apart from the floor so "no version" differs from "too old for every row".
function Get-NvidiaDriverRelease {
param([string]$DriverVersion)
if ([string]::IsNullOrWhiteSpace($DriverVersion)) { return $null }
@@ -4301,21 +3934,16 @@ function Get-NvidiaAdapterCudaFloor {
}
if (-not $HasNvidiaSmi -and (Get-NvidiaLibraryInventory)) {
- # A driver too old for any CUDA wheel (below 11) is no GPU this route can serve: the Intel and
- # AMD routes still get their turn instead of the install falling to CPU.
+ # A driver below CUDA 11 cannot serve any wheel; let the Intel and AMD routes try.
if ((Get-NvidiaLibraryInventory).CudaMajor -ge 11) {
- # The driver lists a GPU nvidia-smi cannot: the gates below read this as "GPU present",
- # and the consumers stop asking nvidia-smi, absent or rejected, for the rest of the run.
$HasNvidiaSmi = $true
$script:NvidiaSmiRejected = $true
Write-StudioLine " NVIDIA GPU found through the driver library; nvidia-smi is unavailable" -ForegroundColor Gray
} else {
- # Still a physical NVIDIA GPU: an installed llama.cpp prebuilt it runs is kept, as before.
$script:NvidiaDriverLibraryOnly = $true
}
}
-# Last resort for #9255: presence only, gated on no healthy AMD or Intel adapter. The CUDA
-# version is decided separately by the version ladder.
+# Last resort: presence only, gated on no healthy AMD or Intel adapter.
if (-not $HasNvidiaSmi) {
$presenceScan = Invoke-BoundedVideoControllerScan
# Any throw declines the promotion; flags are set only once every answer is in hand.
@@ -4334,7 +3962,6 @@ if (-not $HasNvidiaSmi) {
$_presenceRelease = Get-NvidiaAdapterDriverRelease -Scan $presenceScan
$HasNvidiaSmi = $true
$script:NvidiaPresenceOnly = $true
- # Stops Get-CudaComputeCapability / Get-PytorchCudaTag rediscovering an already rejected nvidia-smi.
$script:NvidiaSmiRejected = $true
$script:NvidiaPresenceCudaFloor = $_presenceFloor
$script:NvidiaPresenceDriverRelease = $_presenceRelease
@@ -4342,19 +3969,10 @@ if (-not $HasNvidiaSmi) {
}
} catch {}
}
-# The promotion widens TORCH selection only; llama.cpp prebuilts and source builds need a real
-# driver stack, and install_llama_prebuilt.py never sees the PCI bus.
+# Widens TORCH selection only; llama.cpp needs a real driver stack.
$HasNvidiaDriverEvidence = $HasNvidiaSmi -and -not $script:NvidiaPresenceOnly
-# nvidia-smi was already resolved above and never asked which card it found, so the banner
-# said "NVIDIA GPU detected" on every NVIDIA host alike. compute_cap is the counterpart of the
-# gfx arch shown for AMD, the driver version the counterpart of the HIP SDK line, and one
-# query returns all three. Honour the same visible-device index the AMD probes do.
-#
-# A mask of "" or -1 hides every device, so it selects nothing to name. It is also not a
-# UUID, and letting it reach the prefix match below would spend a second probe that can
-# never match and then name row 0 anyway. $HasNvidiaSmi still drives wheel selection here,
-# as it does on main, so only the naming is skipped: the banner keeps the vendor-only
-# wording rather than claiming a card CUDA does not expose.
+# Name the GPU for the banner, honouring the visible-device mask. A mask of "" or -1 hides
+# every device, so naming is skipped.
$NvidiaGpuName = $null
$NvidiaSmArch = $null
$NvidiaDriverVersion = $null
@@ -4365,30 +3983,20 @@ if ($null -ne $env:CUDA_VISIBLE_DEVICES) {
}
if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not $nvMaskHidesAll) {
try {
- # Through the bounded runner, like every other nvidia-smi call here: a wedged
- # driver blocks nvidia-smi indefinitely, and a bare `&` call has nothing to
- # time it out. -StdoutOnly because driver warnings on stderr would corrupt
- # this machine-readable CSV.
+ # -StdoutOnly: driver warnings on stderr would corrupt the CSV.
$nvOut = Invoke-NvidiaSmiBounded $NvidiaSmiExe @('--query-gpu=name,compute_cap,driver_version', '--format=csv,noheader') -StdoutOnly
$nvRows = @($nvOut -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if ($nvRows.Count -gt 0) {
- # nvidia-smi ignores CUDA_VISIBLE_DEVICES, so the mask is resolved against its
- # physical rows here. A non-numeric token is a GPU UUID, or a MIG id
- # (MIG-<GPU-UUID>/<gi>/<ci>) embedding one; NVIDIA allows the UUID to be
- # abbreviated to any unique leading portion, so it is matched on prefix.
+ # nvidia-smi ignores CUDA_VISIBLE_DEVICES; UUID/MIG tokens match on unique prefix.
$nvIdx = 0
$nvTok = if ($env:CUDA_VISIBLE_DEVICES) { ($env:CUDA_VISIBLE_DEVICES -split ',')[0].Trim() } else { '' }
- # True while nothing has IDENTIFIED a device: a plain ordinal.
$nvByOrdinal = $true
- # Set when an identity mask was given but did not resolve, which means CUDA
- # selected NO device. Row 0 is not a fallback for that.
+ # Set when an identity mask did not resolve: CUDA selected NO device, so row 0 is no fallback.
$nvUnresolved = $false
if ($nvTok -match '^\d+$') {
$nvIdx = [int]$nvTok
} elseif ($nvTok -like 'MIG-*' -and $nvTok -notlike 'MIG-GPU-*') {
- # R470 and later give each MIG instance its OWN opaque UUID, which
- # carries nothing of the parent, so --query-gpu=uuid can never match it.
- # `nvidia-smi -L` nests the instances under their GPU.
+ # R470+ MIG UUIDs carry nothing of the parent; nvidia-smi -L nests them under their GPU.
$nvListOut = Invoke-NvidiaSmiBounded $NvidiaSmiExe @('-L') -StdoutOnly
$cur = 0
$nvByOrdinal = $false
@@ -4405,9 +4013,7 @@ if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not
$nvUuids = @($nvUuidOut -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$nvByOrdinal = $false
$nvFound = $false
- # NVIDIA accepts an abbreviation only when it is a UNIQUE leading portion, so
- # a prefix matching two cards selects NO device. Collect, do not stop at the
- # first hit, or the banner names one of them.
+ # A prefix matching two cards selects NO device, so collect all hits.
$nvMatches = @()
for ($i = 0; $i -lt $nvUuids.Count; $i++) {
if ($nvUuids[$i].StartsWith($nvTok, [System.StringComparison]::OrdinalIgnoreCase)) { $nvMatches += $i }
@@ -4416,15 +4022,8 @@ if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not
if (-not $nvFound) { $nvUnresolved = $true }
}
$nvRow = if ($nvIdx -lt $nvRows.Count) { $nvRows[$nvIdx] } else { $nvRows[0] }
- # A numeric entry is a CUDA ordinal, and CUDA's default
- # CUDA_DEVICE_ORDER=FASTEST_FIRST puts the fastest card at 0 and leaves the
- # rest unspecified, while nvidia-smi always lists in PCI order. So an ordinal
- # identifies an nvidia-smi row only when the order is pinned to PCI_BUS_ID, or
- # when the cards are interchangeable and every row gives the same answer
- # anyway. Compared on name and compute_cap, not the driver, which is host-wide.
- # CUDA stops enumerating at the first invalid index, so an ordinal past the last
- # row exposes NO device. The row pick below clamps to 0 so the driver still
- # reads, but row 0 is not the selected card -- nothing is.
+ # CUDA's default FASTEST_FIRST order differs from nvidia-smi's PCI order, so an ordinal identifies a
+ # row only if PCI_BUS_ID is pinned or all rows agree. An ordinal past the last row exposes nothing.
if ($nvByOrdinal -and $nvIdx -ge $nvRows.Count) { $nvUnresolved = $true }
$nvAmbiguous = $nvUnresolved
if ($nvByOrdinal -and -not $nvAmbiguous) {
@@ -4433,8 +4032,7 @@ if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not
Sort-Object -Unique).Count
$nvAmbiguous = ($nvOrder -ne 'PCI_BUS_ID' -and $nvModels -gt 1)
}
- # Split from the right: nvidia-smi does not quote, so a comma in a device name
- # would otherwise shift every field.
+ # Split from the right: nvidia-smi does not quote commas in device names.
$nvParts = $nvRow -split ','
if ($nvParts.Count -ge 3) {
$NvidiaDriverVersion = $nvParts[-1].Trim()
@@ -4444,22 +4042,17 @@ if ($HasNvidiaSmi -and $NvidiaSmiExe -and -not $script:NvidiaSmiWedged -and -not
$NvidiaSmArch = "sm_" + (([int]$Matches[1] * 10) + [int]$Matches[2])
}
} else {
- # Short row: field 1 only. Taking the whole row would print the
- # compute capability as part of the name ("RTX 4090, 8.9").
$NvidiaGpuName = $nvParts[0].Trim()
}
- # An nvidia-smi too old for a field answers with a placeholder rather
- # than failing (the 470 branch has no compute_cap at all).
+ # Old nvidia-smi answers with a placeholder for unknown fields (470 has no compute_cap).
$nvPlaceholders = @('[N/A]', '[Not Supported]', '[Unknown Error]')
if ($nvPlaceholders -contains $NvidiaGpuName) { $NvidiaGpuName = $null }
if ($nvPlaceholders -contains $NvidiaDriverVersion) { $NvidiaDriverVersion = $null }
- # Keep the driver, drop the identity: the banner falls back to the vendor-only
- # wording rather than claiming a card that may not be the one CUDA will use.
if ($nvAmbiguous) { $NvidiaGpuName = $null; $NvidiaSmArch = $null }
}
} catch {}
}
-# amd-smi auto-elevates to read GPU memory, popping a DiskPart UAC prompt; RunAsInvoker stops it.
+# amd-smi auto-elevates and pops a UAC prompt; RunAsInvoker stops it.
function Invoke-AmdSmiNoElevate {
param(
[Parameter(Mandatory = $true, Position = 0)][string]$Exe,
@@ -4469,7 +4062,7 @@ function Invoke-AmdSmiNoElevate {
$prevCompat = [Environment]::GetEnvironmentVariable('__COMPAT_LAYER', 'Process')
$env:__COMPAT_LAYER = 'RunAsInvoker'
try {
- # [Process]::Start, NOT Start-Process -PassThru, which leaves .ExitCode $null on PS 5.1.
+ # [Process]::Start: Start-Process -PassThru leaves .ExitCode $null on PS 5.1.
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($SmiArgs -join ' ')
@@ -4503,21 +4096,14 @@ function Invoke-AmdSmiNoElevate {
$HasROCm = $false
$HipSdkInstalled = $false # HIP SDK binary found (independent of device accessibility)
$ROCmGpuLabel = $null
-# Marketing name on its own ("AMD Radeon RX 9060 XT"), never decorated. Kept apart from
-# $ROCmGpuLabel because that one doubles as the input to the name -> arch tables below;
-# this one only ever reaches the banner.
+# Banner-only name; $ROCmGpuLabel doubles as input to the name->arch tables.
$ROCmGpuName = $null
$script:ROCmGpuLabels = @() # every AMD adapter name WMI reported (shadowing-aware inference)
$script:ROCmGfxArch = $null
-# Beside ROCmGfxArch, NOT inside the `-not $HasNvidiaSmi` block below: the ROCm summary
-# reads this unconditionally, so an NVIDIA host would hit an undefined variable under a
-# caller's Set-StrictMode. Assigning here also clears a stale value on a re-invocation.
+# Declared here: the ROCm summary reads it unconditionally (StrictMode).
$script:ROCmUnsupportedGfxArch = $null
-# APU gfx arches whose board commonly also carries a discrete Radeon. HIP often
-# enumerates the APU first, so an index-0 pick reads the iGPU's arch and the dGPU never
-# gets its wheels (#7776: gfx1036 Raphael shadowing a gfx1200 RX 9060 XT). In sync with
-# _SHADOWING_INTEGRATED_GFX in studio/install_python_stack.py. The Strix arches
-# (gfx1150/1151/1152) are deliberately absent: first-class training targets, untouched.
+# APU arches that often shadow a discrete Radeon at HIP index 0. In sync with
+# _SHADOWING_INTEGRATED_GFX in studio/install_python_stack.py; Strix arches deliberately absent.
$script:ShadowingIntegratedGfx = @(
"gfx90c", # Renoir / Cezanne
"gfx1013", # Cyan Skillfish
@@ -4528,10 +4114,7 @@ $script:ShadowingIntegratedGfx = @(
"gfx1153" # Krackan Point 2
)
-# gfx arch -> AMD per-arch wheel index family. Defined here, not beside $ROCmIndexUrl,
-# because Resolve-ShadowingGfxPick runs during detection, long before the install block,
-# and must know which arches AMD ships Windows wheels for. In sync with
-# _GFX_TO_AMD_INDEX_ARCH (test_rocm_arch_table_parity.py).
+# Defined early: Resolve-ShadowingGfxPick runs during detection. In sync with _GFX_TO_AMD_INDEX_ARCH.
$archFamilyMap = @{
"gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4
"gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)
@@ -4544,8 +4127,8 @@ $archFamilyMap = @{
"gfx1030" = "gfx103X-all"
"gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100
}
-# RDNA arches route to AMD's multi-arch index, one pinned tag (unslothai#11815, #11614, #11814).
-# gfx1033 (miscomputes) and CDNA stay on the family map. In sync with _WINDOWS_MULTIARCH_GFX in studio/install_python_stack.py.
+# RDNA arches route to AMD's multi-arch index; gfx1033 (miscomputes) and CDNA stay on the family map.
+# In sync with _WINDOWS_MULTIARCH_GFX in studio/install_python_stack.py.
$multiArchGfx = @(
"gfx1010", "gfx1011", "gfx1012", # RDNA 1
"gfx1030", "gfx1031", "gfx1032", "gfx1034", "gfx1035", "gfx1036", # RDNA 2, gfx1033 stays per-family
@@ -4554,16 +4137,14 @@ $multiArchGfx = @(
"gfx1200", "gfx1201" # RDNA 4
)
$MultiArchIndexBase = if ($env:UNSLOTH_ROCM_WINDOWS_MULTIARCH_MIRROR) { $env:UNSLOTH_ROCM_WINDOWS_MULTIARCH_MIRROR.TrimEnd('/') } else { "https://repo.amd.com/rocm/whl-multi-arch" }
-# Not rocm7.14.1: its Windows wheels ship a mismatched AOTriton runtime, so fused SDPA fails (ROCm/TheRock#7992).
+# Not rocm7.14.1: its Windows wheels ship a mismatched AOTriton runtime, so fused SDPA fails.
$MultiArchTag = "rocm7.14.0"
$MultiArchTorchVersion = "2.11.0"
$MultiArchTorchvisionVersion = "0.26.0"
$MultiArchTorchaudioVersion = "2.11.0"
-# True when any of the three masks is set. Mirrors _visible_devices_pinned(): ANY value
-# is a deliberate selection, "" and "-1" included -- those select NO GPU rather than
-# meaning "unset".
+# Mirrors _visible_devices_pinned(): ANY value, "" and "-1" included, is a deliberate selection.
function Test-VisibleDevicesPinned {
foreach ($visEnv in @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES, $env:CUDA_VISIBLE_DEVICES)) {
if ($null -ne $visEnv) { return $true }
@@ -4571,12 +4152,8 @@ function Test-VisibleDevicesPinned {
return $false
}
-# The one mask -> index resolver for every pick site below; the sites used to inline
-# their own expressions and disagreed (hipinfo rejected " 1 ", amd-smi rejected "1,0"),
-# and a mask Resolve-ShadowingGfxPick honours but the index ignores lands on GPU 0, the
-# very iGPU this preference exists to skip. Mirrors _pick_visible_index(): first-set-wins
-# (the runtime lets an empty HIP mask shadow CUDA_VISIBLE_DEVICES rather than defer to
-# it), and an unparseable or out-of-range value falls back to GPU 0.
+# The single mask -> index resolver; mirrors _pick_visible_index(). First set mask wins;
+# unparseable or out-of-range falls back to GPU 0.
function Resolve-VisibleGpuIndex {
param([int]$Count)
foreach ($visEnv in @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES, $env:CUDA_VISIBLE_DEVICES)) {
@@ -4584,9 +4161,7 @@ function Resolve-VisibleGpuIndex {
$val = $visEnv.Trim()
if ($val -eq "" -or $val -eq "-1") { return 0 }
$first = ($val -split ',')[0].Trim()
- # TryParse, not [int]: '2147483648' overflows and .NET's \d also matches full-width
- # digits, and either cast throws a TERMINATING error under this script's
- # $ErrorActionPreference = "Stop", aborting the install where nothing catches it.
+ # TryParse, not [int]: overflow or full-width digits would throw a terminating error under Stop.
[int]$parsed = 0
if ([int]::TryParse($first, [ref]$parsed)) {
if ($parsed -ge 0 -and $parsed -lt $Count) { return $parsed }
@@ -4597,26 +4172,18 @@ function Resolve-VisibleGpuIndex {
return 0
}
-# Mirrors _dedup_pick(). setup.ps1 resolves the arch and builds $ROCmIndexUrl from it
-# before ever invoking the Python stack installer, so the shadowing-iGPU skip has to
-# happen here too or a fresh install still pulls the iGPU's wheel family. Returns $Picked
-# unchanged when pinned, when only one distinct arch exists, or when no discrete arch is.
+# Mirrors _dedup_pick(): skip a shadowing iGPU here too, since the index URL is built before the
+# Python installer runs. Unchanged when pinned or only one distinct arch exists.
function Resolve-ShadowingGfxPick {
param([AllowNull()][string]$Picked, [AllowNull()][string[]]$AllArches)
if (-not $Picked) { return $Picked }
- # Only arches in $archFamilyMap have an AMD Windows wheel index.
function Test-GfxHasWheels { param([AllowNull()][string]$Arch) return [bool]($Arch -and ($archFamilyMap.ContainsKey($Arch) -or $multiArchGfx -contains $Arch)) }
- # A selected device is honoured verbatim; never repick over the user.
+ # A selected device is honoured verbatim.
if (Test-VisibleDevicesPinned) { return $Picked }
if ($script:ShadowingIntegratedGfx -notcontains $Picked) { return $Picked }
$distinctArches = @($AllArches | Select-Object -Unique)
if ($distinctArches.Count -lt 2) { return $Picked }
- # Deposing a supported APU for a discrete card with no Windows wheels (gfx1036 + a
- # gfx803) resolves to no index and drops the host to CPU, worse than the
- # shadowing itself. So prefer a wheel-backed discrete card, and fall back to an
- # unsupported one only when the pick has no wheels either: taking the first
- # non-integrated arch instead sent gfx90c,gfx803,gfx1200 to CPU torch despite the
- # supported gfx1200. Mirrors _dedup_pick()'s `_withWheels or (...)`.
+ # Prefer a wheel-backed discrete card; an unsupported one only when the pick has no wheels either.
$pickedHasWheels = Test-GfxHasWheels $Picked
$others = @($AllArches | Where-Object { $script:ShadowingIntegratedGfx -notcontains $_ })
$withWheels = @($others | Where-Object { Test-GfxHasWheels $_ })
@@ -4625,22 +4192,20 @@ function Resolve-ShadowingGfxPick {
else { @() }
$discreteArch = $candidates | Select-Object -First 1
if (-not $discreteArch) { return $Picked }
- # Not always device 1: on gfx1036,gfx803,gfx1200 the pick is device 2, and
- # naming 1 would expose the gfx803 the wheels do not target.
+ # Not always device 1; the pick can be a later index, e.g. device 2 for gfx1036,gfx803,gfx1200.
$discreteIdx = [array]::IndexOf(@($AllArches), $discreteArch)
if ($discreteIdx -lt 0) { $discreteIdx = 1 }
substep "multiple AMD GPUs detected ($($distinctArches -join ', ')); installing for the discrete $discreteArch instead of the integrated $Picked" "Cyan"
- # HIP still enumerates the iGPU as device 0 at runtime, so the wheels alone do not
- # steer training to the dGPU; setx makes the mask persist across sessions.
+ # HIP still enumerates the iGPU as device 0 at runtime, so the mask must persist.
substep "Run 'setx HIP_VISIBLE_DEVICES $discreteIdx' and reopen your terminal so Unsloth uses $discreteArch at runtime too, not just at install time" "Cyan"
return $discreteArch
}
if (-not $HasNvidiaSmi) {
- # Ignore the venv hipInfo.exe: an AMD wheel, not a HIP SDK, so amd-smi still auto-elevates.
+ # The venv hipInfo.exe comes from an AMD wheel, not a HIP SDK.
function Test-HipinfoIsVenvInternal {
param([AllowNull()][string]$HipinfoPath)
if ([string]::IsNullOrWhiteSpace($HipinfoPath)) { return $false }
- # VenvDir/VIRTUAL_ENV can be unset this early, so also derive it from the setup python.
+ # VenvDir/VIRTUAL_ENV can be unset this early.
$venvRoots = @()
if ($env:VIRTUAL_ENV) { $venvRoots += $env:VIRTUAL_ENV }
$vd = Get-Variable -Name VenvDir -ValueOnly -ErrorAction SilentlyContinue
@@ -4663,7 +4228,7 @@ if (-not $HasNvidiaSmi) {
foreach ($root in $venvRoots) {
if ([string]::IsNullOrWhiteSpace($root)) { continue }
try { $r = [System.IO.Path]::GetFullPath($root).TrimEnd('\', '/') } catch { continue }
- # Skip a bare drive root; it would match every path on that drive.
+ # A bare drive root would match every path on that drive.
if ($r -match '^[a-zA-Z]:$') { continue }
if ($hip.Equals($r, [System.StringComparison]::OrdinalIgnoreCase) -or
$hip.StartsWith($r + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
@@ -4704,19 +4269,13 @@ if (-not $HasNvidiaSmi) {
try {
$hipOut = & $hipinfoExe.Source 2>&1 | Out-String
if ($hipOut -match "(?i)gcnArchName") {
- # hipinfo can crash after printing gcnArchName (#6043); keep the ROCm path.
+ # hipinfo can crash after printing gcnArchName; keep the ROCm path.
$HasROCm = $true
$_hipAllArches = @([regex]::Matches($hipOut, "(?im)^\s*gcnArchName\s*:\s*(\S+)") | ForEach-Object { ($_.Groups[1].Value -split ':')[0].Trim().ToLower() })
- # hipinfo prints "Name:" per device alongside gcnArchName. Anchored so
- # gcnArchName cannot match. Only trusted when the two lists line up, and read
- # at the index the arch pick landed on, so the banner names the card the
- # wheels were chosen for.
+ # Names trusted only when they line up with the arches, read at the picked index.
$_hipAllNames = @([regex]::Matches($hipOut, "(?im)^\s*Name\s*:\s*(.+?)\s*$") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_hipAllArches.Count -gt 0) {
- # hipinfo is itself a HIP application, so under a mask it already
- # enumerated only the visible devices, renumbered from 0; indexing it
- # again applies the mask twice and lands on the wrong card. amd-smi and
- # the WMI path below list every GPU, so they still index.
+ # hipinfo already honours the mask and renumbers from 0, so do not index it again.
$script:ROCmGfxArch = $_hipAllArches[0]
$script:ROCmGfxArch = Resolve-ShadowingGfxPick $script:ROCmGfxArch $_hipAllArches
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
@@ -4748,13 +4307,11 @@ if (-not $HasNvidiaSmi) {
$smiOut = Invoke-AmdSmiNoElevate $amdSmiExe.Source @('list')
if ($LASTEXITCODE -eq 0 -and $smiOut -match "(?im)^GPU\s*[:\[]\s*\d") {
$HasROCm = $true
- # ALL gfx tokens in output order, no dedup, so HIP_VISIBLE_DEVICES indexes in.
+ # All gfx tokens in output order, no dedup, so the mask index lines up.
$allGfxArches = @([regex]::Matches($smiOut, '(?i)\b(gfx\d+[a-z]?)\b') |
ForEach-Object { $_.Groups[1].Value.ToLower() })
if ($allGfxArches.Count -gt 0) {
- # amd-smi lists every GPU regardless of the masks, so resolve the
- # index here, via the shared helper so a comma list or a padded
- # value cannot select a different GPU than elsewhere.
+ # amd-smi lists every GPU regardless of masks, so resolve the index here.
$_smiPickIdx = Resolve-VisibleGpuIndex $allGfxArches.Count
$script:ROCmGfxArch = $allGfxArches[$_smiPickIdx]
$_smiShadowPick = Resolve-ShadowingGfxPick $script:ROCmGfxArch $allGfxArches
@@ -4763,22 +4320,16 @@ if (-not $HasNvidiaSmi) {
$_smiPickIdx = [array]::IndexOf($allGfxArches, $_smiShadowPick)
}
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
- # Banner only, read at the index the arch pick landed on. The index
- # is carried forward rather than recovered from the arch VALUE:
- # the list is deliberately not deduplicated, so IndexOf on two
- # same-arch cards always returns 0 and names the first one even
- # when the mask selected the second (RX 7900 XTX vs PRO W7900).
+ # Carry the index forward: IndexOf on duplicate arches always returns 0.
$_smiNames = @([regex]::Matches($smiOut, "(?im)Market.?Name\s*[:\|]\s*([^\r\n]+)") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_smiNames.Count -eq $allGfxArches.Count -and $_smiPickIdx -ge 0) {
$ROCmGpuName = $_smiNames[$_smiPickIdx]
}
} else {
- # Attempt 2: 'static --asic' exposes the GFX target on ROCm 6+.
+ # 'static --asic' exposes the GFX target on ROCm 6+.
$smiAsicOut = ""
try { $smiAsicOut = Invoke-AmdSmiNoElevate $amdSmiExe.Source @('static','--asic') } catch {}
- # Every token, not just the first: this branch is reached precisely
- # when 'list' saw multiple GPUs but printed no arches, so a leading
- # iGPU here reintroduces #7776.
+ # Every token, not just the first, or a leading iGPU is picked.
$asicGfxArches = @([regex]::Matches($smiAsicOut, '(?i)\b(gfx\d+[a-z]?)\b') |
ForEach-Object { $_.Groups[1].Value.ToLower() })
if ($asicGfxArches.Count -gt 0) {
@@ -4790,8 +4341,6 @@ if (-not $HasNvidiaSmi) {
$_asicPickIdx = [array]::IndexOf($asicGfxArches, $_asicShadowPick)
}
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
- # Index carried forward, not recovered from the arch value --
- # see the sibling branch above.
$_asicNames = @([regex]::Matches($smiAsicOut, "(?im)Market.?Name\s*[:\|]\s*([^\r\n]+)") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_asicNames.Count -eq $asicGfxArches.Count -and $_asicPickIdx -ge 0) {
$ROCmGpuName = $_asicNames[$_asicPickIdx]
@@ -4810,25 +4359,13 @@ if (-not $HasNvidiaSmi) {
# WMI gives a marketing name, never a gfx arch, so $HasROCm stays false.
if (-not $HasROCm) {
try {
- # Keep every AMD adapter, not just the first: WMI orders controllers as the
- # driver stack enumerated them, so a shadowing iGPU can lead here exactly as
- # under HIP (#7776), and the inference below runs the same preference over the
- # whole list. ConfigManagerErrorCode 0 is "working properly": a disabled or
- # driver-errored Radeon must not depose a working iGPU.
+ # Keep every AMD adapter (a shadowing iGPU can lead). Error code 0 only, so a broken dGPU cannot win.
$amdGpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match "AMD|Radeon" })
$healthyGpus = @($amdGpus | Where-Object {
($null -eq $_.ConfigManagerErrorCode) -or ($_.ConfigManagerErrorCode -eq 0) })
- # If that leaves none, the filter alone made the host look GPU-less and the
- # inference forwards nothing: code 45 ("not connected") is routine on a muxless
- # laptop with a parked dGPU, and with no healthy peer there is nothing to
- # depose. Mirrors the same fallback in install_python_stack.py's WMI path.
- # @() wraps the WHOLE if, not each branch: a one-element array unrolls on its way
- # out of an if-expression, and a scalar's .Count is $null under Windows PowerShell
- # 5.1, so the single Radeon in the machine read as no AMD GPU at all -- no
- # $script:ROCmGpuLabels, no inferred gfx arch, "gpu none" in the report, and an
- # installed +rocm venv judged stale against a required "cpu" (#8335). Same idiom as
- # the Intel scan below and in install.ps1.
+ # Fall back to all adapters if none is healthy (code 45 is routine for a parked dGPU).
+ # @() wraps the WHOLE if: a one-element array unrolls and .Count is $null on 5.1.
$wmiGpus = @(if ($healthyGpus.Count -gt 0) { $healthyGpus } else { $amdGpus })
if ($wmiGpus.Count -gt 0) {
$script:ROCmGpuLabels = @($wmiGpus | ForEach-Object { $_.Name })
@@ -4837,10 +4374,7 @@ if (-not $HasNvidiaSmi) {
}
} catch {}
}
- # Peer names for the REPORT ONLY. amd-smi can confirm a runtime with no gfx token and
- # only the first card's name, and the scan above is skipped there, so the verdict below
- # would speak for a host it has seen one adapter of. Kept out of $script:ROCmGpuLabels
- # deliberately: that feeds the inference, and widening it turned a CPU install into ROCm.
+ # Peer names for the REPORT ONLY; feeding them to inference changed CPU installs to ROCm.
$script:ROCmPeerLabels = @()
if ($HasROCm -and -not $script:ROCmGfxArch) {
try {
@@ -4853,29 +4387,21 @@ if (-not $HasNvidiaSmi) {
} catch {}
}
- # GPU name -> gfx arch for AMD generations no ROCm wheel covers: Polaris 10/20/30
- # (unslothai#8529). Kept apart from $nameArchTable on purpose: it only WORDS a message,
- # never selects a wheel index or a prebuilt. The (?!0) guards stop "RX 570" swallowing
- # an "RX 5700"; Polaris 11/12 (RX 460/550/560, a different die) is left out.
+ # Name -> arch for generations no ROCm wheel covers; only words a message, never selects an index.
$unsupportedNameArchTable = @(
@{ P = "RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100"; A = "gfx803" } # Polaris 10/20/30
)
$script:ROCmUnsupportedGfxArch = $null
# ── Arch resolution: env-var override → name inference ──────────────────
- # Runs after all probes, even when none confirmed a ROCm runtime ($HasROCm false):
- # the Adrenalin driver alone runs the per-gfx ROCm llama.cpp prebuilt (bundles its
- # own runtime), and all it needs is the gfx arch, inferable from the WMI GPU name.
- # Resolving it here lets setup.ps1 forward --rocm-gfx so a GPU llama.cpp is pulled
- # instead of CPU. (PyTorch ROCm wheels still require a HIP SDK -- gated on $HasROCm
- # below -- so this only affects llama.cpp / inference.)
+ # Runs even without a confirmed runtime: the Adrenalin driver alone runs the per-gfx llama.cpp
+ # prebuilt, which only needs the arch. PyTorch ROCm wheels stay gated on $HasROCm.
if (-not $script:ROCmGfxArch) {
- # 1. Manual override: set UNSLOTH_ROCM_GFX_ARCH=gfx1151 before running.
if ($env:UNSLOTH_ROCM_GFX_ARCH) {
$script:ROCmGfxArch = ($env:UNSLOTH_ROCM_GFX_ARCH.Trim().ToLower() -split ':')[0] # drop HIP feature suffixes (gfx1010:xnack-)
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
substep "gfx arch from UNSLOTH_ROCM_GFX_ARCH env override: $script:ROCmGfxArch" "Cyan"
}
- # 2. Name -> arch, most-specific first; unknown names fall back to CPU.
+ # Name -> arch, most-specific first; unknown names fall back to CPU.
elseif ($ROCmGpuLabel) {
$nameArchTable = @(
@{ P = "9070|9080|R9700"; A = "gfx1201" } # RDNA 4 (Navi 48: Radeon RX 9070 XT / 9070 GRE / 9070 / 9080, Radeon AI PRO R9700)
@@ -4900,64 +4426,34 @@ if (-not $HasNvidiaSmi) {
foreach ($row in $Table) { if ($Name -match $row.P) { return $row.A } }
return $null
}
- # Only the WMI path carries more than one name; other callers left a single
- # synthesized label, so default to it.
- # @() wraps the WHOLE if, not each branch: a one-element branch unrolls on its way
- # out, leaving a bare String on a single-adapter host, and $gpuNames[$nameIdx] then
- # indexes the NAME and yields "A". Nothing maps, and the $nameArches[0] rescue below
- # is skipped under a visible-device mask, so a pinned single-GPU host inferred no
- # arch at all -- the same "gpu none" the WMI scan above used to report.
+ # @() wraps the WHOLE if: a one-element branch unrolls to a String and indexing yields a character.
$gpuNames = @(if ($script:ROCmGpuLabels) { @($script:ROCmGpuLabels) } else { @($ROCmGpuLabel) })
- # Index over the ADAPTER list, not the inferred arches: an unrecognised name
- # drops out below, and indexing the shortened list would name the wrong card.
+ # Index over the ADAPTER list, not the shorter inferred-arch list.
$nameIdx = Resolve-VisibleGpuIndex $gpuNames.Count
$nameArches = @()
- # Which ADAPTER each inferred arch came from. Unmappable names drop out, so
- # $nameArches is shorter than $gpuNames and its positions stop lining up; the
- # borrow below has to be able to say which card it borrowed from.
$nameArchSrc = @()
for ($_gi = 0; $_gi -lt $gpuNames.Count; $_gi++) {
$inferred = Get-GfxArchFromGpuName -Name $gpuNames[$_gi] -Table $nameArchTable
if ($inferred) { $nameArches += $inferred; $nameArchSrc += $_gi }
}
$pickedName = Get-GfxArchFromGpuName -Name $gpuNames[$nameIdx] -Table $nameArchTable
- # Borrow another adapter's arch only when unpinned: an unmappable leading
- # adapter is exactly the #7776 iGPU and the named discrete card should decide,
- # but under a mask substituting installs wheels for a GPU they masked away.
- # Which adapter actually supplied the arch: the borrowed one, or the selected
- # one when its own name mapped. -1 only when nothing mapped. Both cases need
- # it, because either can leave $nameArches shorter than $gpuNames and so skip
- # the repick block below.
+ # Borrow another adapter's arch only when unpinned; under a mask that would target a hidden GPU.
$_archSrcIdx = -1
if (-not $pickedName -and -not (Test-VisibleDevicesPinned) -and $nameArches.Count -gt 0) {
$pickedName = $nameArches[0]
$_archSrcIdx = $nameArchSrc[0]
}
- # Guarded on $_archSrcIdx so a borrow above is not overwritten. Spelled with
- # -and rather than a bare truthiness test on $pickedName alone, because that
- # exact spelling is the end anchor TestSetupPs1ShadowingParity slices this
- # block on; a second copy closes its window early and hides the pinned-mask
- # guard from it.
+ # Spelled with -and: a bare `if ($pickedName) {` is TestSetupPs1ShadowingParity's end anchor.
if ($pickedName -and $_archSrcIdx -lt 0) { $_archSrcIdx = $nameIdx }
if ($pickedName) {
- # Repick only when every adapter mapped: an unknown name may BE the
- # discrete card, so skipping the iGPU could pick the wrong one.
+ # Repick only when every adapter mapped: an unknown name may BE the discrete card.
$script:ROCmGfxArch = if ($nameArches.Count -eq $gpuNames.Count) {
Resolve-ShadowingGfxPick -Picked $pickedName -AllArches $nameArches
} else { $pickedName }
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
- # Move the banner name onto the adapter this arch actually came from.
- # $ROCmGpuName was set to adapter 0 by the WMI scan above, but all three
- # mechanisms here -- the visible-device mask, the $nameArches[0] borrow
- # and the shadowing repick -- can land the arch on a different adapter.
- # Left alone, an iGPU+dGPU host reads "AMD Radeon 890M (gfx1201)":
- # the integrated name against the discrete arch.
+ # Move the banner name onto the adapter the arch actually came from.
if ($nameArches.Count -eq $gpuNames.Count) {
- # Keep $nameIdx when the arch at that index is the one that was
- # picked: two adapters can map to the same arch (RX 7900 XTX and
- # PRO W7900 are both gfx1100), and IndexOf on a non-unique value
- # returns 0, naming the first card even under a mask selecting the
- # second. IndexOf is only the fallback for a shadowing repick.
+ # Keep $nameIdx when its arch is the pick: IndexOf returns the first of duplicate arches.
$_nameArchIdx = if ($nameIdx -lt $nameArches.Count -and $nameArches[$nameIdx] -eq $script:ROCmGfxArch) {
$nameIdx
} else {
@@ -4965,34 +4461,18 @@ if (-not $HasNvidiaSmi) {
}
if ($_nameArchIdx -ge 0) { $ROCmGpuName = $gpuNames[$_nameArchIdx] }
} elseif ($_archSrcIdx -ge 0) {
- # Not every adapter mapped, so the block above cannot run, but the arch
- # came from a KNOWN adapter and $ROCmGpuName is still adapter 0. Covers
- # both shapes: an unmappable iGPU ahead of an RX 9070 with no mask, and
- # the same pair with HIP_VISIBLE_DEVICES=1 selecting the RX 9070
- # directly. Either otherwise reads "AMD Radeon Graphics (gfx1201)":
- # the integrated name against the discrete arch.
$ROCmGpuName = $gpuNames[$_archSrcIdx]
}
substep "gfx arch inferred from GPU name: $script:ROCmGfxArch" "Cyan"
substep "Tip: set UNSLOTH_ROCM_GFX_ARCH=$script:ROCmGfxArch to skip inference next time" "Cyan"
} else {
- # Nothing mapped: the card may be a generation ROCm never covered rather
- # than one we failed to recognise (unslothai#8529). $script:ROCmGfxArch
- # stays null either way, so only the wording of the report below moves.
- # Stay quiet when a PEER is covered: "no override can help" is false beside a
- # card that has wheels. Read-only; never reaches $gpuNames or the inference.
- # HIP/ROCR only, unlike Test-VisibleDevicesPinned: CUDA_VISIBLE_DEVICES says
- # nothing about which Radeon was chosen, and counting it would fire the verdict
- # beside a covered card.
+ # Nothing mapped: maybe a generation ROCm never covered. Wording only, and quiet when a peer is
+ # covered. HIP/ROCR masks only: CUDA_VISIBLE_DEVICES says nothing about Radeons.
$unsupMasked = @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES) |
Where-Object { $null -ne $_ }
$unsupPeerCovered = $false
if ($unsupMasked) {
- # Under a mask a peer cannot answer for the named card, as the
- # arch-borrowing rule above. But $gpuNames is one synthesized label on the
- # amd-smi path, and $nameIdx cannot index a card it never saw, so a mask
- # onto a supported peer would be blamed on adapter 0. Unseen peer, no
- # verdict: Win32_VideoController does not promise HIP's order to guess with.
+ # Under a mask a peer cannot answer for the named card; an unseen peer gives no verdict.
$unsupPeerCovered = ($script:ROCmPeerLabels.Count -gt $gpuNames.Count)
} else {
foreach ($peerName in $script:ROCmPeerLabels) {
@@ -5008,26 +4488,15 @@ if (-not $HasNvidiaSmi) {
}
}
}
- # 3. Last resort: the arch install.ps1 resolved a second ago. Last because everything above
- # is mask- and shadowing-aware and the installer's scan is not, so this fills a gap rather
- # than deposing a better answer. Without it, a scan that answers there but not here expects
- # cpu torch against the ROCm wheels just placed, calls the venv stale, and loops forever.
- # Private, never UNSLOTH_ROCM_GFX_ARCH: nested installers read that as an operator
- # override, and this value is inferred, not chosen by anyone.
- # Skipped under a visible-device mask, matching the inference above, which leaves
- # $pickedName unset rather than borrowing a peer's arch when pinned. The installer's scan
- # ignores the masks, so its answer is the FIRST adapter, not the selected one, and taking
- # it would install for a GPU the mask hides from the runtime entirely. A host that wants
- # an arch named under a mask sets UNSLOTH_ROCM_GFX_ARCH, which still wins above.
+ # Last resort: the arch install.ps1 just resolved (private handoff, never UNSLOTH_ROCM_GFX_ARCH).
+ # Skipped under a mask: the installer's scan ignores masks and would name the first adapter.
if (-not $script:ROCmGfxArch -and $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF -and
-not (Test-VisibleDevicesPinned)) {
$script:ROCmGfxArch = $env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF.Trim().ToLower()
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
substep "gfx arch forwarded by the installer: $script:ROCmGfxArch" "Cyan"
}
- # Capture ROCm version early for display and wheel selection.
- # Run whenever the HIP SDK binary is present, not just when the device is accessible --
- # hipconfig --version works even when hipinfo reports no ROCm device (driver issue).
+ # hipconfig --version works even when hipinfo sees no device.
if ($HasROCm -or $HipSdkInstalled) {
$script:ROCmVersion = $null
$hipConfigExe = Get-Command hipconfig -ErrorAction SilentlyContinue
@@ -5063,10 +4532,7 @@ if (-not $HasNvidiaSmi) {
} catch {}
}
}
- # Last resort: the SDK root itself is versioned (...\AMD\ROCm\7.1). Reporting
- # "ROCm (version unknown)" while the very next line prints that path made the summary
- # look broken on a perfectly good install; both probes above can miss when hipconfig
- # is absent from a runtime-only layout and amd-smi is not on PATH.
+ # Last resort: the SDK root itself is versioned (...\AMD\ROCm\7.1).
if (-not $script:ROCmVersion) {
$hipVersionedRoot = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { $null }
if ($hipVersionedRoot -match '[\\/](\d+\.\d+(?:\.\d+)?)[\\/]?$') { $script:ROCmVersion = $Matches[1] }
@@ -5074,9 +4540,8 @@ if (-not $HasNvidiaSmi) {
}
}
-# gfx arches AMD publishes Windows ROCm wheels for (repo.amd.com/rocm/whl/<family>). Hoisted
-# above the Intel scan, which needs it: an unlisted arch gets CPU torch, so it must not outrank a
-# usable Arc card. test_rocm_arch_table_parity.py keeps it in sync with $archFamilyMap below.
+# Arches with AMD Windows ROCm wheels. Hoisted above the Intel scan, which needs it.
+# test_rocm_arch_table_parity.py keeps it in sync with $archFamilyMap.
$_rocmWheelArches = @(
"gfx1201", "gfx1200", # RDNA 4
"gfx1151", "gfx1150", "gfx1152", "gfx1153", # RDNA 3.5 (Strix Halo/Point, Krackan Point)
@@ -5085,40 +4550,24 @@ $_rocmWheelArches = @(
"gfx1012", "gfx1011", "gfx1010", # RDNA 1 (RX 5000): AMD's multi-arch index (unslothai#11755)
"gfx90a", "gfx908" # MI200 / MI100
)
-# "AMD gets GPU wheels here", NOT "an AMD GPU is present": $HasROCm / $ROCmGfxArch are true on
-# unmapped arches (Vega, Polaris) too, and those install CPU torch. Must include $multiArchGfx.
+# "AMD gets GPU wheels", not "AMD GPU present": unmapped arches install CPU torch.
$AmdHasGpuWheels = [bool]($script:ROCmGfxArch -and ($_rocmWheelArches -contains $script:ROCmGfxArch))
-# Mirrors the Intel scan in install.ps1 so setup does not report "none (chat-only)" right after
-# install.ps1 reported a usable Arc GPU. Self-contained, because `studio update` runs setup.ps1
-# standalone. Same $AmdHasGpuWheels gate (an Arc card wins over an AMD host heading for CPU torch
-# anyway) and the same Arc / Data Center match.
+# Mirrors install.ps1's Intel scan; self-contained since `studio update` runs setup.ps1 standalone.
$script:IsIntelXpu = $false
-# Set when the stale check below keeps an installed +xpu venv instead of wiping it. Separate from
-# $script:IsIntelXpu on purpose: it steers the INSTALL, not the hardware report, which must stay
-# honest about the NVIDIA GPU that is also in the machine.
+# Steers the INSTALL, not the hardware report.
$script:PreservedXpuVenv = $false
-# Flavour tag ("rocm" / "cu128" / "xpu") of a GPU wheel the stale check below kept. Declared here,
-# like the flag above it, because the index selection reads it on every run while a fresh install
-# never reaches the assignment -- so under a caller's Set-StrictMode the read would be fatal.
+# Declared here: read on every run, assigned only on some (StrictMode).
$script:PreservedInstallerTorchTag = $null
$IntelGpuLabel = $null
if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {
try {
- # Bounded, registry as the fallback when WMI does not answer: an unbounded query hangs
- # `studio update`, a swallowed one silently reports no GPU.
+ # Bounded; registry fallback when WMI does not answer.
$_gpuScan = Invoke-BoundedVideoControllerScan
- # @() wraps the WHOLE if, not each branch: a one-element array unrolls on its way out,
- # making $_gpuNames a String on a single-adapter host and turning the += below into
- # string concatenation.
+ # @() wraps the WHOLE if: a one-element array unrolls to a String.
$_gpuNames = @(if ($_gpuScan.Ok) { $_gpuScan.Names } else { Get-IntelRegistryAdapterNames })
- # One definition for both the reconciliation gate and the classification below.
$_xpuNameRe = "(?i)Intel.*(Arc|Data Center GPU)"
- # On non-English Windows the WMI name carries no ASCII "Intel" for the classification
- # below. The registry helper resolves the PCI vendor id, so use it to RE-LABEL an adapter
- # WMI already reported, never to add one (an unmatched entry is a driver record outliving
- # its card). Gated on the absence of an XPU match, not of any Intel name: a hybrid laptop
- # reports "Intel UHD" next to a localized Arc.
+ # Non-English WMI names lack "Intel": re-label (never add) adapters via the registry vendor id.
if ($_gpuScan.Ok -and -not ($_gpuNames | Where-Object { $_ -match $_xpuNameRe })) {
foreach ($_reg in @(Get-IntelRegistryAdapterNames)) {
foreach ($_wmiName in $_gpuNames) {
@@ -5129,11 +4578,7 @@ if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {
$xpuGpu = $_gpuNames | Where-Object { $_ -match $_xpuNameRe } | Select-Object -First 1
if ($xpuGpu) { $script:IsIntelXpu = $true; $IntelGpuLabel = $xpuGpu }
} catch {}
- # Neither WMI nor the registry recognised an adapter, so ask the environment: an installed
- # +xpu wheel whose runtime initialises proves the host better than a marketing name. The same
- # check runs ~1300 lines below, but AFTER the report just below, so without this an Arc user
- # on a wedged WMI is told no training GPU exists and then watches setup keep the XPU
- # environment. Own try, so a throwing scan or a junk UNSLOTH_STUDIO_HOME cannot abort setup.
+ # No adapter recognised: an installed +xpu wheel whose runtime works proves the host.
if (-not $script:IsIntelXpu) {
try {
$_probeVenv = Get-ProbableStudioVenvDir
@@ -5148,18 +4593,12 @@ if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {
}
}
-# One banner string for the AMD arms below. The arch alone ("AMD ROCm (gfx1200)") named a
-# target nobody shopping for a GPU recognises, while every probe above already had the
-# marketing name in hand and threw it away.
$ROCmGpuDisplay =
if ($ROCmGpuName -and $script:ROCmGfxArch) { "$ROCmGpuName ($script:ROCmGfxArch)" }
elseif ($ROCmGpuName) { $ROCmGpuName }
elseif ($script:ROCmGfxArch) { "AMD ROCm ($script:ROCmGfxArch)" }
else { $ROCmGpuLabel }
-# Same shape for every vendor: the device on the step line, its compute target in
-# parentheses, the runtime below. Intel has no counterpart to gfx1200 / sm_89 that any probe
-# here already resolves, so it gets the name alone rather than an invented one.
$NvidiaGpuDisplay =
if ($NvidiaGpuName -and $NvidiaSmArch) { "$NvidiaGpuName ($NvidiaSmArch)" }
elseif ($NvidiaGpuName) { $NvidiaGpuName }
@@ -5170,23 +4609,19 @@ if ($HasNvidiaSmi) {
step "gpu" $NvidiaGpuDisplay
if ($NvidiaDriverVersion) { substep "Driver: $NvidiaDriverVersion" }
} elseif ($script:IsIntelXpu) {
- # Ranks above every AMD branch: only true when AMD gets no GPU wheel ($AmdHasGpuWheels gates
- # the scan above), so those branches would all end on CPU torch.
+ # Only true when AMD gets no GPU wheel, so AMD branches would end on CPU torch.
Write-StudioLine ""
step "gpu" $IntelGpuDisplay "Green"
substep "PyTorch XPU (SYCL) wheels provide training and GPU inference on this GPU." "Cyan"
Write-StudioLine ""
} elseif ($HasROCm -and -not $script:ROCmUnsupportedGfxArch) {
- # Guarded like the HIP SDK arm below: amd-smi can report a GPU with no gfx token
- # and only a market name, which sets $HasROCm without an arch.
+ # amd-smi can set $HasROCm without an arch.
step "gpu" $ROCmGpuDisplay
$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }
substep "HIP SDK: $hipSdkPath"
if ($script:ROCmVersionFull) { substep "hipconfig: $script:ROCmVersionFull" }
} elseif ($HipSdkInstalled -and $ROCmGpuLabel -and -not $script:ROCmUnsupportedGfxArch) {
- # HIP SDK installed but ROCm can't see the device (driver issue, not SDK issue).
- # Excludes cards already known to be out of scope: the #8529 reporters installed the
- # HIP SDK BECAUSE this arm said to, so unguarded it hides the arm below from them.
+ # HIP SDK installed but ROCm cannot see the device. Excludes known out-of-scope cards.
$sdkVer = if ($script:ROCmVersionFull) { " (HIP $script:ROCmVersionFull)" } else { "" }
Write-StudioLine ""
step "gpu" "AMD GPU detected -- not ROCm-accessible$sdkVer" "Yellow"
@@ -5196,8 +4631,7 @@ if ($HasNvidiaSmi) {
substep " Ensure the ROCm compute driver is installed alongside the display driver:" "Yellow"
substep " https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" "Yellow"
} elseif ($script:ROCmGfxArch) {
- # Known arch: PyTorch comes from AMD's bundled-runtime ROCm wheels (repo.amd.com),
- # which ship their own runtime -- HIP SDK optional (only adds the system toolchain).
+ # Known arch: AMD's ROCm wheels bundle their own runtime, so the HIP SDK is optional.
Write-StudioLine ""
step "gpu" $ROCmGpuDisplay "Cyan"
substep "Detected: $ROCmGpuLabel" "Cyan"
@@ -5246,7 +4680,6 @@ if ($HasNvidiaSmi) {
}
# ============================================
-# 1a.5. Windows Long Paths (required for deep node_modules / Python paths)
# ============================================
$LongPathsEnabled = $false
try {
@@ -5291,26 +4724,18 @@ if ($LongPathsEnabled) {
}
# ============================================
-# 1b. Git (only required for --local / source installs)
# ============================================
-# Was fatal as "required by pip and npm", but the consumer path uses neither: the
-# unsloth-zoo git+https URL is STUDIO_LOCAL_INSTALL only, node is a pinned prebuilt, and the
-# frontend lockfile has no VCS deps. Being fatal blocked clean no-winget Windows boxes.
+# Git is required only for --local / source installs; the consumer path uses neither pip VCS nor npm git.
$HasGit = $null -ne (Get-Command git -ErrorAction SilentlyContinue)
if (-not $HasGit) {
- # Fatal only where git is used: --local and the opt-in llama.cpp source build. A local
- # llama.cpp dir overrides those opt-ins, but only once it holds a reusable binary:
- # pointing at the canonical install location with nothing built there falls through to
- # the normal install, so an explicit source build still needs git. The automatic
- # fallback after a failed prebuilt download is not knowable here; Phase 4 handles it.
+ # Fatal only for --local and the opt-in llama.cpp source build, unless a local dir has a binary.
$gitNeeded = ($env:STUDIO_LOCAL_INSTALL -eq '1')
$_localLlamaDir = if ($env:UNSLOTH_LOCAL_LLAMA_CPP_DIR) { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR.Trim() } else { "" }
$_localLlamaBuilt = $false
if ($_localLlamaDir) {
# Same layout candidates as the reuse check in Phase 4.
foreach ($_c in @("llama-server.exe", "build\bin\llama-server.exe", "build\bin\Release\llama-server.exe")) {
- # Denied here terminated the run under "Stop" long before Phase 4's
- # guarded probes, so this scan needs the same three-state handling.
+ # A denial here must not terminate under Stop.
$_cState = Get-PathState -Path (Join-Path $_localLlamaDir $_c)
if ($_cState -eq "Denied") {
Exit-PathAccessDenied -Path $_localLlamaDir -Label "the UNSLOTH_LOCAL_LLAMA_CPP_DIR build" -UserSupplied
@@ -5321,14 +4746,12 @@ if (-not $HasGit) {
if (-not $_localLlamaBuilt) {
$_prForce = if ($env:UNSLOTH_LLAMA_PR_FORCE) { $env:UNSLOTH_LLAMA_PR_FORCE.Trim() } else { $DefaultLlamaPrForce }
$_llamaSrc = $DefaultLlamaSource -replace '\.git$', ''
- # Same tag resolution as Phase 4. "master" is a branch, never a release, so the
- # prebuilt lookup always misses and Phase 4 rebuilds it from source.
+ # Same tag resolution as Phase 4; "master" always builds from source.
$_llamaTag = if ($env:UNSLOTH_LLAMA_TAG) { $env:UNSLOTH_LLAMA_TAG } else { $DefaultLlamaTag }
if ($_llamaTag -eq "master") { $gitNeeded = $true }
if ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq '1') { $gitNeeded = $true }
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_LLAMA_PR)) { $gitNeeded = $true }
- # Same positive-integer predicate as the PR_FORCE promotion below: 0 or non-numeric
- # never forces a source build, so it must not demand git.
+ # Same positive-integer predicate as the PR_FORCE promotion below.
if ($_prForce -match '^\d+$' -and [int]$_prForce -gt 0) { $gitNeeded = $true }
if ($_llamaSrc -ne "https://github.com/ggml-org/llama.cpp") { $gitNeeded = $true }
}
@@ -5365,15 +4788,13 @@ if (-not $HasGit) {
}
# ============================================
-# 1b.5. Visual C++ Redistributable (runtime for the prebuilt llama.cpp + PyTorch)
+# Visual C++ Redistributable: runtime for the prebuilt llama.cpp + PyTorch.
# ============================================
-# Runtime dep, not a build tool: the prebuilt llama-server and PyTorch load it.
Ensure-VCRedist
# ============================================
-# 1c. CMake (only needed for a llama.cpp SOURCE build -- detection only)
+# CMake detection only; a source build gets it from Ensure-BuildToolsForLlamaSourceBuild.
# ============================================
-# Detection only; a source build gets CMake from Ensure-BuildToolsForLlamaSourceBuild.
$HasCmake = $null -ne (Get-Command cmake -ErrorAction SilentlyContinue)
if ($HasCmake) {
step "cmake" "$(cmake --version | Select-Object -First 1)"
@@ -5382,7 +4803,6 @@ if ($HasCmake) {
}
# ============================================
-# 1d. Visual Studio Build Tools (only needed for a llama.cpp SOURCE build -- detection only)
# ============================================
$CmakeGenerator = $null
$VsInstallPath = $null
@@ -5398,12 +4818,11 @@ if ($vsResult) {
}
# ============================================
-# 1e. CUDA Toolkit (nvcc for llama.cpp build + env vars)
# ============================================
# Lazy: the prebuilt path needs no local toolkit. -RequireOrExit hard-fails when none is found.
function Resolve-CudaToolkit {
param([switch]$RequireOrExit)
-# Toolkit major must be <= the driver's max CUDA major; a newer-major toolkit fails at runtime.
+# Toolkit major must be <= the driver's max CUDA major.
$DriverMaxCuda = $null
try {
@@ -5421,7 +4840,6 @@ try {
}
} catch {}
if (-not $DriverMaxCuda -and (Get-Command Get-NvidiaLibraryInventory -ErrorAction SilentlyContinue)) {
- # No nvidia-smi answer: the driver library names the same ceiling, so the toolkit filter holds.
$inventory = Get-NvidiaLibraryInventory
if ($inventory) {
$DriverMaxCuda = "$($inventory.CudaMajor).$($inventory.CudaMinor)"
@@ -5429,20 +4847,17 @@ if (-not $DriverMaxCuda -and (Get-Command Get-NvidiaLibraryInventory -ErrorActio
}
}
-# Detect compute capability early so we can validate toolkit support
$CudaArch = Get-CudaComputeCapability
if ($CudaArch) {
substep "GPU Compute Capability = $($CudaArch.Insert($CudaArch.Length-1, '.')) (sm_$CudaArch)"
}
-# Prefer CUDA_PATH when driver-compatible; scanning side-by-side installs avoids mismatches.
$IncompatibleToolkit = $null
$NvccPath = $null
if ($DriverMaxCuda) {
$drMajorCuda = [int]$DriverMaxCuda.Split('.')[0]
- # --- Step 1: Check existing CUDA_PATH first ---
$existingCudaPath = [Environment]::GetEnvironmentVariable('CUDA_PATH', 'Machine')
if (-not $existingCudaPath) {
$existingCudaPath = [Environment]::GetEnvironmentVariable('CUDA_PATH', 'User')
@@ -5454,7 +4869,6 @@ if ($DriverMaxCuda) {
$tkMaj = [int]$Matches[1]; $tkMin = [int]$Matches[2]
$isCompat = ($tkMaj -le $drMajorCuda)
if ($isCompat) {
- # Also verify the toolkit supports our GPU architecture
$archOk = $true
if ($CudaArch) {
$archOk = Test-NvccArchSupport -NvccExe $candidateNvcc -Arch $CudaArch
@@ -5473,7 +4887,6 @@ if ($DriverMaxCuda) {
}
}
- # --- Step 2: Fall back to scanning side-by-side installs ---
if (-not $NvccPath) {
$NvccPath = Find-Nvcc -MaxVersion $DriverMaxCuda
if ($NvccPath) {
@@ -5504,15 +4917,13 @@ if ($DriverMaxCuda) {
$NvccPath = Find-Nvcc
}
-# A newer-major toolkit blocked by the driver: explain the mismatch.
if (-not $NvccPath -and $IncompatibleToolkit) {
Write-CudaDriverToolkitMismatch -ToolkitVersion $IncompatibleToolkit -DriverMaxCuda $DriverMaxCuda
if (-not $RequireOrExit) {
$script:CudaToolkitReady = $false
return
}
- # Reached only by a source build (forced, or after a prebuilt-install failure);
- # with no compatible toolkit it must fail (setup.sh degrades to CPU instead).
+ # Only a source build reaches here, so fail (setup.sh degrades to CPU instead).
Write-StudioLine "" -ForegroundColor Red
Write-StudioLine "========================================================================" -ForegroundColor Red
Write-StudioLine "[ERROR] CUDA source build cannot use the installed toolkit with this driver." -ForegroundColor Red
@@ -5526,12 +4937,10 @@ if (-not $NvccPath -and $RequireOrExit) {
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
if ($DriverMaxCuda) {
- # Query winget for available CUDA Toolkit versions
$drMajor = [int]$DriverMaxCuda.Split('.')[0]
$AvailableVersions = @()
try {
$rawOutput = winget show Nvidia.CUDA --versions --source winget --accept-source-agreements 2>&1 | Out-String
- # Parse version lines (e.g. "12.6", "12.5", "11.8")
foreach ($line in $rawOutput -split "`n") {
$line = $line.Trim()
if ($line -match '^\d+\.\d+') {
@@ -5540,7 +4949,6 @@ if (-not $NvccPath -and $RequireOrExit) {
}
} catch {}
- # Filter to compatible major versions and pick the highest
$BestVersion = $null
foreach ($ver in $AvailableVersions) {
$parts = $ver.Split('.')
@@ -5594,30 +5002,27 @@ if (-not $NvccPath) {
# -- Set CUDA env vars so cmake AND MSBuild can find the toolkit --
$CudaToolkitRoot = Split-Path (Split-Path $NvccPath -Parent) -Parent
-# CUDA_PATH: used by cmake's find_package(CUDAToolkit)
[Environment]::SetEnvironmentVariable('CUDA_PATH', $CudaToolkitRoot, 'Process')
-# CudaToolkitDir: MSBuild property the CUDA .targets checks; trailing backslash required.
+# MSBuild's CUDA .targets need the trailing backslash.
[Environment]::SetEnvironmentVariable('CudaToolkitDir', "$CudaToolkitRoot\", 'Process')
[Environment]::SetEnvironmentVariable('CUDA_PATH', $CudaToolkitRoot, 'User')
substep "Persisted CUDA_PATH=$CudaToolkitRoot to user environment"
-# Clear versioned CUDA_PATH_V* vars so cmake/MSBuild cannot find a conflicting install.
+# Clear CUDA_PATH_V* so cmake/MSBuild cannot find a conflicting install.
$cudaPathVars = @([Environment]::GetEnvironmentVariables('Process').Keys | Where-Object { $_ -match '^CUDA_PATH_V' })
foreach ($v in $cudaPathVars) {
[Environment]::SetEnvironmentVariable($v, $null, 'Process')
}
-# Set only the versioned var matching the selected toolkit (e.g. CUDA_PATH_V13_0)
$tkDirName = Split-Path $CudaToolkitRoot -Leaf
if ($tkDirName -match '^v(\d+)\.(\d+)') {
$cudaPathVerVar = "CUDA_PATH_V$($Matches[1])_$($Matches[2])"
[Environment]::SetEnvironmentVariable($cudaPathVerVar, $CudaToolkitRoot, 'Process')
substep "Set $cudaPathVerVar (cleared other CUDA_PATH_V* vars)"
}
-# Ensure nvcc's bin dir is on PATH for this process
$nvccBinDir = Split-Path $NvccPath -Parent
if ($env:PATH -notlike "*$nvccBinDir*") {
[Environment]::SetEnvironmentVariable('PATH', "$nvccBinDir;$env:PATH", 'Process')
}
-# Persist nvcc bin dir (Prepend so the driver-compatible toolkit wins).
+# Prepend so the driver-compatible toolkit wins.
if (Add-ToUserPath -Directory $nvccBinDir -Position 'Prepend') {
substep "Persisted CUDA bin dir to user PATH"
}
@@ -5663,7 +5068,6 @@ substep "CudaToolkitDir = $CudaToolkitRoot\"
if (-not $CudaArch) {
substep "could not detect compute capability -- cmake will use defaults" "Yellow"
}
-# Publish the resolved toolkit to script scope for the Phase 4 build.
$script:NvccPath = $NvccPath
$script:CudaToolkitRoot = $CudaToolkitRoot
$script:CudaArch = $CudaArch
@@ -5677,15 +5081,13 @@ if ($HasROCm -and -not $script:ROCmUnsupportedGfxArch) {
} elseif ($script:ROCmGfxArch) {
step "rocm" "GPU via bundled ROCm wheels ($script:ROCmGfxArch) -- HIP SDK optional" "Cyan"
} elseif ($script:ROCmUnsupportedGfxArch) {
- # Naming the HIP SDK here would read as "install it and this resolves"; on a
- # generation with no ROCm PyTorch wheels it never does (unslothai#8529).
+ # Do not suggest the HIP SDK: these generations have no ROCm PyTorch wheels.
step "rocm" "AMD GPU detected ($script:ROCmUnsupportedGfxArch) -- no ROCm PyTorch wheels Unsloth installs" "Yellow"
} elseif ($ROCmGpuLabel) {
step "rocm" "AMD GPU detected -- arch unknown; HIP SDK not found" "Yellow"
}
# ============================================
-# 1f. Node.js / npm (skip if pip-installed or Tauri -- only needed for frontend build)
# ============================================
function Get-NodeDecision {
param(
@@ -5711,16 +5113,8 @@ function Get-NodeDecision {
function Test-PackagedFrontend {
param([string]$LocalInstall, [string]$IndexPath, [string]$ProjectFilePath)
- # install.ps1 and `unsloth studio update` explicitly pass 0 for PyPI
- # installs. Wheel extraction mtimes do not preserve build ordering, so use
- # the release-built dist whenever its entry point is present.
- #
- # $ProjectFilePath is the pyproject.toml beside studio/. The mode records
- # where the Python package came from, not which tree this script runs out
- # of, and an editable overlay separates the two: it leaves the mode at 0
- # while $ScriptDir is a checkout, whose dist is a stale build artifact
- # rather than a release one. A wheel ships no top-level files, so that file
- # existing means source tree -- keep the mtime rebuild there.
+ # PyPI installs (mode 0) use the release-built dist: wheel mtimes are not build order.
+ # A pyproject.toml beside studio/ means a source checkout (editable overlay): keep mtime rebuilds.
if ($LocalInstall -ne "0") { return $false }
if ($ProjectFilePath -and (Test-Path -LiteralPath $ProjectFilePath -PathType Leaf)) { return $false }
return (Test-Path -LiteralPath $IndexPath -PathType Leaf)
@@ -5735,13 +5129,11 @@ $SysNpmVersion = ""
$NodeSource = $null
if (-not $IsPipInstall) {
- # Put Node beside the Unsloth root. OXC can still need npm when the
- # frontend build is skipped.
$_masterRoot = Get-MasterRootOverride
if ($StageRoot) {
$NodeParent = $StageRoot
} elseif ($_masterRoot) {
- # Same derivation as Get-ManagedLlamaCppDir: beside studio\, not inside it.
+ # Beside studio\, not inside it, as in Get-ManagedLlamaCppDir.
$NodeParent = $_masterRoot
} else {
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $NodeOverride = $env:UNSLOTH_STUDIO_HOME.Trim() }
@@ -5758,7 +5150,6 @@ if (-not $IsPipInstall) {
Exit-SetupFailure "UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist"
}
$NodeParent = (Resolve-Path -LiteralPath $NodeOverride).Path
- # legacy default overrides map to ~/.unsloth/node, matching runtime resolution.
$_legacyStudio = Join-Path $env:USERPROFILE ".unsloth\studio"
if (Test-Path -LiteralPath $_legacyStudio -PathType Container) {
$_legacyStudio = (Resolve-Path -LiteralPath $_legacyStudio).Path
@@ -5773,7 +5164,7 @@ if (-not $IsPipInstall) {
}
$NodeDir = Join-Path $NodeParent "node"
- # Under -ErrorAction Stop a bare `node -v` throws past 2>$null; empty means "bundled".
+ # Under Stop a bare `node -v` throws past 2>$null.
$SysNodeVersion = try { if (Get-Command node -ErrorAction SilentlyContinue) { (node -v 2>$null) } else { "" } } catch { "" }
$SysNpmVersion = try { if (Get-Command npm -ErrorAction SilentlyContinue) { (npm -v 2>$null) } else { "" } } catch { "" }
$NodeSource = Get-NodeDecision -NodeVersion "$SysNodeVersion" -NpmVersion "$SysNpmVersion" -SkipInstall "$($env:UNSLOTH_SKIP_NODE_INSTALL)"
@@ -5793,7 +5184,7 @@ if ($IsPipInstall) {
}
}
-# Conda CPython breaks torch's c10.dll, and a venv from it inherits base_prefix, so check both.
+# Conda CPython breaks torch's c10.dll; a venv from it inherits base_prefix, so check both.
$CondaSkipPattern = '(?i)(conda|miniconda|anaconda|miniforge|mambaforge)'
function Test-IsConda {
param([string]$Exe)
@@ -5805,7 +5196,7 @@ function Test-IsConda {
return $false
}
-# 1g. Python (>= 3.11, < 3.14). Prefer the validated venv python over a stub-led PATH probe.
+# Python >= 3.11, < 3.14. Prefer the validated venv python over a stub-led PATH probe.
function Resolve-ReusedSetupPython {
if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_SETUP_PYTHON) -and
(Test-Path -LiteralPath $env:UNSLOTH_SETUP_PYTHON)) {
@@ -5847,7 +5238,6 @@ function Add-PythonDirToProcessPath {
} catch { }
}
-# Reuse the install.ps1 / venv interpreter before any system probe.
$ValidatedSetupPython = $null
if ($ReusedSetupPython) {
$_reusedVer = Get-CompatiblePythonVersion $ReusedSetupPython
@@ -5859,7 +5249,7 @@ if ($ReusedSetupPython) {
}
}
-# -All is required: PS 5.1 returns only the first py launcher without it.
+# -All: PS 5.1 returns only the first py launcher without it.
$PyLaunchers = if ($PythonOk) { @() } else { @(Get-Command py -All -CommandType Application -ErrorAction SilentlyContinue) }
foreach ($PyLauncher in $PyLaunchers) {
@@ -5869,7 +5259,7 @@ foreach ($PyLauncher in $PyLaunchers) {
$out = & $PyLauncher.Source "-$minor" --version 2>&1 | Out-String
if ($out -match 'Python (3\.\d+\.\d+)') {
$DetectedPyVer = $Matches[1]
- # Make `python` resolvable: a py-launcher-only install would crash on bare `python`.
+ # A py-launcher-only install would crash on bare `python`.
try {
$resolvedExe = (& $PyLauncher.Source "-$minor" -c "import sys; print(sys.executable)" 2>$null | Select-Object -First 1)
if ($resolvedExe -and (Test-Path $resolvedExe)) {
@@ -5898,10 +5288,6 @@ if (-not $PythonOk -and $HasPython) {
if ($PythonOk) {
substep "Python $DetectedPyVer"
} elseif (-not $HasPython) {
- # No `python` on PATH (and py.exe either absent or only had unsupported
- # minors). Try winget as before -- gating on $HasPython alone, not also
- # on $PyLauncher, so a launcher-only install with just 3.14 still gets
- # an automatic 3.12 install instead of a hard error.
Write-StudioLine "Python 3.11-3.13 not found -- installing Python 3.12 via winget..." -ForegroundColor Yellow
$HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
if ($HasWinget) {
@@ -5917,8 +5303,6 @@ if ($PythonOk) {
step "python" "$(python --version 2>&1)"
$PythonOk = $true
} else {
- # python.exe is on PATH but its version is unsupported, and py.exe (if
- # present) had no supported minor either.
Write-StudioLine "[ERROR] No supported Python (3.11-3.13) found on this system." -ForegroundColor Red
Write-StudioLine " py.exe could not locate -3.11/-3.12/-3.13 and `python` on PATH is unsupported." -ForegroundColor Yellow
Write-StudioLine " Install Python 3.12 from https://python.org/downloads/" -ForegroundColor Yellow
@@ -5928,7 +5312,7 @@ if ($PythonOk) {
# Add user-scheme Python Scripts dir to PATH (nt_user only, no venv fallback).
$ScriptsDir = python -c "import os, sysconfig; p = sysconfig.get_path('scripts', 'nt_user'); print(p if os.path.exists(p) else '')"
if ($LASTEXITCODE -eq 0 -and $ScriptsDir -and (Test-Path $ScriptsDir)) {
- # Append (not Prepend) -- this dir has other pip scripts; shim handles unsloth.
+ # Append: this dir has other pip scripts; the shim handles unsloth.
if (Add-ToUserPath -Directory $ScriptsDir) {
$ProcessPathEntries = $env:PATH.Split(';')
if (-not ($ProcessPathEntries | Where-Object { $_.TrimEnd('\') -eq $ScriptsDir })) {
@@ -5944,24 +5328,20 @@ Write-StudioLine ""
Invoke-MirrorFallback -SpareOnly
-# UNSLOTH_NPM_REGISTRY: opt-in --registry splat past the frontend .npmrc lock (corporate proxies).
$NpmRegistryArgs = @()
if ($env:UNSLOTH_NPM_REGISTRY) {
$NpmRegistryArgs = @('--registry', $env:UNSLOTH_NPM_REGISTRY)
}
# ==========================================================================
-# PHASE 2: Frontend build (skip if pip-installed -- already bundled)
+# PHASE 2: Frontend build (skip if pip-installed -- already bundled)
# ==========================================================================
$DistDir = Join-Path $FrontendDir "dist"
$PackagedFrontend = Test-PackagedFrontend `
-LocalInstall "$($env:STUDIO_LOCAL_INSTALL)" `
-IndexPath (Join-Path $DistDir "index.html") `
-ProjectFilePath (Join-Path $PackageDir "pyproject.toml")
-# Wheel extraction mtimes are not a source-freshness signal. Standard PyPI
-# installs use the release-built dist; local/source installs retain mtime checks.
-# Tauri is checked first so the reported reason matches setup.sh on a desktop
-# update, where both this and the packaged branch would otherwise apply.
+# Wheel mtimes are not a freshness signal. Tauri is checked first to match setup.sh's reason.
$NeedFrontendBuild = $true
if ($SkipFrontend) {
$NeedFrontendBuild = $false
@@ -5972,7 +5352,6 @@ if ($SkipFrontend) {
} elseif (Test-Path $DistDir) {
$DistTime = (Get-Item $DistDir).LastWriteTime
$NewerFile = $null
- # Check src/ and public/ recursively (probe paths directly, not via -Include)
foreach ($subDir in @("src", "public")) {
$subPath = Join-Path $FrontendDir $subDir
if (Test-Path $subPath) {
@@ -5981,7 +5360,6 @@ if ($SkipFrontend) {
if ($NewerFile) { break }
}
}
- # Also check all top-level files (package.json, vite.config.ts, index.html, etc.)
if (-not $NewerFile) {
$NewerFile = Get-ChildItem -Path $FrontendDir -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -ne "bun.lock" -and $_.LastWriteTime -gt $DistTime } |
@@ -6010,28 +5388,14 @@ if ($NeedNodeForSetup) {
substep "install a suitable Node + npm, or unset UNSLOTH_SKIP_NODE_INSTALL to let Unsloth manage an isolated Node" "Yellow"
} elseif ($NodeSource -eq "bundled") {
New-Item -ItemType Directory -Force -Path $NodeParent -ErrorAction SilentlyContinue | Out-Null
- # Minimal ownership guard; never os.replace over a user-owned dir.
- # $RuntimeRootIsCustom as well as $NodeOverride: the master-root branch above leaves
- # $NodeOverride null, so <master>\node reached install_node_prebuilt.py's whole-directory
- # replacement with none of the ownership evidence a custom UNSLOTH_STUDIO_HOME requires,
- # and the master root is the user's directory too. Or, not replacing: a custom Studio
- # home keeps the guard it had.
- #
- # Anything at the path counts as occupied, not just a directory: _swap_into_place renames
- # whatever it finds out of the way, so a file or symlink named `node` was displaced by a
- # guard that only asked about containers. Ownership evidence lives inside a directory, so
- # a non-directory can never carry it and is refused outright.
- # Get-Item -Force, not Test-Path: under Windows PowerShell 5.1 Test-Path reports whether
- # the TARGET resolves, so a dangling link named `node` reads as absent and
- # install_node_prebuilt.py installs through it.
+ # Never let install_node_prebuilt.py replace a user-owned path. Anything at the path counts, and
+ # Get-Item -Force sees dangling links that 5.1's Test-Path reports as absent.
$nodeEntry = if ($NodeOverride -or $RuntimeRootIsCustom) {
Get-Item -LiteralPath $NodeDir -Force -ErrorAction SilentlyContinue
} else { $null }
if ($nodeEntry) {
$nodeOwnedMarker = Join-Path $NodeDir ".unsloth-studio-owned"
$nodeMeta = Join-Path $NodeDir "UNSLOTH_NODE_PREBUILT_INFO.json"
- # From the entry, not a second probe: a dangling link is a container to neither, and
- # a reparse point carrying no ownership evidence is not an install of ours.
$nodeIsDir = $nodeEntry.PSIsContainer -and
-not ($nodeEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)
if (-not $nodeIsDir -or (
@@ -6044,7 +5408,7 @@ if ($NeedNodeForSetup) {
}
}
substep "installing isolated Node (system Node/npm left untouched)..."
- # Prefer the validated handed-off/venv Python: bare `python` may be a Store stub here.
+ # Bare `python` may be a Store stub here.
$NodeInstallPython = if ($ValidatedSetupPython) { $ValidatedSetupPython } else { "python" }
# PS 5.1 turns redirected native stderr (even Python warnings) into errors; the exit code decides.
$prevEAPNode = $ErrorActionPreference
@@ -6070,16 +5434,9 @@ if ($NeedNodeForSetup) {
step "node" "install blocked by another active Unsloth install" "Red"
Exit-SetupFailure "Node install is blocked by another active Unsloth install" 3
} elseif ($nodeExit -eq 4) {
- # The Node cache could not be written. The generic advice below sends
- # people to nodejs.org and their router; neither is the fix, and the
- # same guidance the llama.cpp cache gets is the right one.
Write-StudioLine $nodeOut -ForegroundColor DarkGray
Write-StudioLine ""
- # The install lock and the .staging root live in $NodeParent, so the
- # refused object is not always $NodeDir, which in that case may not
- # even exist. Deleting it cannot make a parent writable, and the
- # parent holds more than Node, so it is never ours to offer up for
- # deletion either. install_node_prebuilt.py classifies which it was.
+ # The refused object may be $NodeParent, which holds more than Node: never offer it for deletion.
if ($nodeOut -match "denied-scope: parent") {
Exit-PathAccessDenied -Path $NodeParent -Label "Node install parent directory" `
-OwnershipUnverified
@@ -6092,25 +5449,21 @@ if ($NeedNodeForSetup) {
Write-StudioLine " Install Node >= 20.19 (with npm >= 11) from https://nodejs.org/ and re-run, or check your network." -ForegroundColor Yellow
Exit-SetupFailure "Could not install an isolated Node runtime"
} elseif ($nodeOut -match "keeping existing isolated Node") {
- # Exit 0 also covers a failed update that kept a working Node; relay any repair lines.
if ($nodeOut -match 'takeown /F') {
Write-StudioLine $nodeOut -ForegroundColor DarkGray
}
step "node" "update not applied, existing isolated Node kept" "Yellow"
}
- # Same condition as the guard above, or the tree this run just created under a master
- # root stays unmarked and the uninstaller declines to remove it as somebody else's.
+ # Same condition as the guard above, or the uninstaller treats the new tree as foreign.
if (($NodeOverride -or $RuntimeRootIsCustom) -and (Test-Path -LiteralPath $NodeDir -PathType Container)) {
New-Item -ItemType File -Force -Path (Join-Path $NodeDir ".unsloth-studio-owned") -ErrorAction SilentlyContinue | Out-Null
}
$env:PATH = "$NodeDir;" + $env:PATH
- # Keep npm and module resolution inside the isolated Node.
$env:NPM_CONFIG_PREFIX = $NodeDir
$env:npm_config_prefix = $NodeDir
Remove-Item Env:NODE_PATH -ErrorAction SilentlyContinue
step "node" "$(node -v) | npm $(npm -v) (isolated)"
- # bun (optional, unused when package-lock.json means `npm ci`); npm -g stays in the isolated prefix.
if (-not (Test-Path (Join-Path $FrontendDir "package-lock.json")) -and -not (Get-Command bun -ErrorAction SilentlyContinue)) {
substep "installing bun (faster frontend package installs)..."
$prevEAP_bun = $ErrorActionPreference
@@ -6140,7 +5493,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
# Cleared only once the build succeeds, so one that dies at any point is redone next run.
try { [System.IO.File]::WriteAllText($FrontendBuildMark, "$PID") } catch { }
- # Tailwind v4's oxide scanner respects parent .gitignore, and a venv's "*" hides the .tsx files.
+ # Tailwind v4's oxide scanner honours parent .gitignore, and a venv's "*" hides the .tsx files.
$HiddenGitignores = @()
$WalkDir = (Get-Item $FrontendDir).Parent.FullName
while ($WalkDir -and $WalkDir -ne [System.IO.Path]::GetPathRoot($WalkDir)) {
@@ -6169,7 +5522,7 @@ if ($NeedFrontendBuild -and -not $IsPipInstall) {
$UseBun = -not (Test-Path "package-lock.json") -and (Test-Path "bun.lock") -and ($null -ne (Get-Command bun -ErrorAction SilentlyContinue))
$NpmInstallVerb = if (Test-Path "package-lock.json") { "ci" } else { "install" }
- # A corrupt bun cache still exits 0, so validate, clear it, retry once, then fall back to npm.
+ # A corrupt bun cache still exits 0, so validate, clear, retry once, then fall back to npm.
if ($UseBun) {
Write-StudioLine " Using bun for package install (faster)" -ForegroundColor DarkGray
$bunExit = Invoke-SetupCommand { bun install --frozen-lockfile @NpmRegistryArgs }
@@ -6268,7 +5621,7 @@ Remove-AgentInstructionFiles -Roots @(
)
# ==========================================================================
-# PHASE 3: Python environment + dependencies
+# PHASE 3: Python environment + dependencies
# ==========================================================================
Write-StudioLine ""
substep "setting up Python environment..."
@@ -6296,7 +5649,7 @@ foreach ($pyLauncher in $PyLaunchersResolve) {
if ($out -match 'Python 3\.(\d+)') {
$pyMinor = [int]$Matches[1]
if ($pyMinor -ge 11 -and $pyMinor -le 13) {
- # Resolve the actual executable so venv creation does not re-resolve to conda.
+ # Resolve the real executable so venv creation does not re-resolve to conda.
$resolvedExe = (& $pyLauncher.Source "-$minor" -c "import sys; print(sys.executable)" 2>$null | Out-String).Trim()
if ($resolvedExe -and (Test-Path $resolvedExe) -and -not (Test-IsConda $resolvedExe)) {
$PythonCmd = $resolvedExe
@@ -6371,17 +5724,13 @@ function Get-StudioAdoptableState {
}
}
if ($denied) { return "Denied" }
- # Windows reports a MISSING child of an unreadable directory as absent, so the
- # probes above cannot tell "no markers here" from "cannot look"; listing the
- # directory itself can. Without this a denied tree reads as unowned.
+ # Windows reports a missing child of an unreadable dir as absent; listing the dir itself can tell.
try { $null = @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop | Select-Object -First 1) }
catch {
if (Test-AccessDeniedError $_) { return "Denied" }
- # Anything else was not adoptable before either; this must not throw.
}
return "No"
}
-# Boolean view for callers that only gate a cosmetic cleanup on adoption.
function Test-StudioOwnedAdoptable {
param([Parameter(Mandatory = $true)][string]$Path)
return ((Get-StudioAdoptableState -Path $Path) -eq "Yes")
@@ -6390,33 +5739,23 @@ function Assert-StudioOwnedOrAbsent {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Label,
- # whisper.cpp is non-fatal by contract, so it needs the denial handed back
- # rather than exited on. Only this mode returns a value.
+ # whisper.cpp is non-fatal by contract, so the denial is returned, not exited on.
[switch]$NonFatal,
- # The runtime children pass $RuntimeRootIsCustom; everything under the
- # Studio home keeps $StudioHomeIsCustom.
[AllowNull()][object]$IsCustom = $null
)
$isCustomRoot = $StudioHomeIsCustom
if ($null -ne $IsCustom) { $isCustomRoot = [bool]$IsCustom }
- # Denied is not Absent: a root we cannot read cannot be proven ours, and
- # returning here would let the caller replace it; a default-home denial is
- # reported by the phase that owns the path.
+ # Denied is not Absent: an unreadable root cannot be proven ours.
$pathState = Get-PathState -Path $Path -PathType Container
if ($pathState -ne "Present") {
if ($isCustomRoot -and $pathState -eq "Denied") {
if ($NonFatal) { return "Denied" }
Exit-PathAccessDenied -Path $Path -Label $Label -OwnershipUnverified
}
- # A Container probe answers false for a regular file and for a link whose target is gone,
- # and the caller then deleted the path or let install_*_prebuilt.py replace it; both
- # shapes are things the user put in a directory they chose. Get-Item -Force still sees
- # the directory entry where Test-Path does not, which is the dangling link under 5.1.
+ # Get-Item -Force sees files and dangling links that a Container probe misses.
if (-not $isCustomRoot) { return }
if (-not (Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue)) { return }
- # Ownership evidence lives inside a directory, so a non-directory can never carry it
- # and is refused outright rather than asked for markers. Fatal even under -NonFatal:
- # that mode rescues a denial, not somebody else's file.
+ # Fatal even under -NonFatal: that mode rescues a denial, not somebody else's file.
Write-StudioLine "[ERROR] $Path already exists and is not a directory." -ForegroundColor Red
Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
Exit-SetupFailure "$Label path is not an Unsloth-owned install: $Path"
@@ -6449,12 +5788,7 @@ function Mark-StudioOwned {
} catch {}
}
-# The mode this venv was installed with. install.ps1 exports UNSLOTH_NO_TORCH for
-# its own run only, so a later `unsloth studio update` (which exports nothing) has
-# no other way to know. Two sources, because the completion manifest is dropped
-# before every dependency pass and so cannot answer for a run killed mid-pass:
-# the manifest key first, then .unsloth-no-torch, which outlives the pass. Neither
-# present reads as "install torch" -- the pre-existing behavior.
+# Persisted no-torch mode: manifest key first, then .unsloth-no-torch, which survives an interrupted pass.
function Get-PersistedNoTorch {
param([Parameter(Mandatory = $true)][string]$VenvPath)
$manifestPath = Join-Path $VenvPath "unsloth_install_manifest.json"
@@ -6472,7 +5806,6 @@ function Get-PersistedNoTorch {
return (Test-Path -LiteralPath (Join-Path $VenvPath $NoTorchMarker) -PathType Leaf)
}
-# The CUDA index install.ps1 chose. Only NVIDIA's channels are written, so never credentialed.
function Get-PersistedWoaTorchIndex {
param([Parameter(Mandatory = $true)][string]$VenvPath)
$manifestPath = Join-Path $VenvPath "unsloth_install_manifest.json"
@@ -6484,13 +5817,12 @@ function Get-PersistedWoaTorchIndex {
}
if ($null -eq $payload -or -not $payload.woa_torch_index) { return "" }
$value = "$($payload.woa_torch_index)".Trim().TrimEnd('/')
- # Re-checked on read, anchored, no `?` or `#`: a hand-edited manifest must not redirect torch.
+ # Re-checked on read: a hand-edited manifest must not redirect torch.
if ($value -notmatch '^https://pypi\.nvidia\.com(/[A-Za-z0-9._~/-]*)?$') { return "" }
return $value
}
-# The dependency pass drops the manifest before rebuilding it, so this marker lives outside it.
-# Parity copies of install.ps1's index probe, kept identical by a parity test: the forced repair below carries the same unsafe-best-match, so an open-ended spec lets a PyPI CPU release win.
+# Parity copies of install.ps1's index probe, kept identical by a parity test.
function Test-WoaWheelTagsParity {
param([string]$Name, [string]$PyTag, [string]$AbiTag)
if (-not $Name) { return $false }
@@ -6518,7 +5850,7 @@ function Test-WoaPairsWithTorchParity {
if ((& $stamp $TorchVersion) -ne (& $stamp $OtherVersion)) { return $false }
if ((& $local $TorchVersion) -ne (& $local $OtherVersion)) { return $false }
if (& $stamp $TorchVersion) { return $true }
- # Stable releases share an empty stamp, so they pair by offset: torchvision 0.(M+15) to torch 2.M.
+ # Stable releases pair by offset: torchvision 0.(M+15) with torch 2.M.
$rel = {
param($v)
$m = [regex]::Match($v, '^(\d+)\.(\d+)')
@@ -6562,7 +5894,7 @@ function New-WoaTorchStepOverrideValueParity {
return $result
}
-# Parity copies of install.ps1's uv index policy readers: the index that serves torch's shared dependencies beside the CUDA one has to be the same answer from a fresh shell.
+# Parity copies of install.ps1's uv index policy readers.
function Remove-WoaTomlComment {
param([string]$Line)
$inD = $false; $inS = $false
@@ -6592,7 +5924,6 @@ function Split-WoaTomlKey {
if ($c -eq '"' -or $c -eq "'") {
$q = $c; $i++; $sb = ""
while ($i -lt $Text.Length -and $Text[$i] -ne $q) {
- # Basic strings escape; literal (single-quoted) ones do not.
if ($q -eq '"' -and $Text[$i] -eq '\' -and ($i + 1) -lt $Text.Length) { $i++ }
$sb += $Text[$i]; $i++
}
@@ -6615,7 +5946,8 @@ function Split-WoaTomlKey {
return ,$parts
}
-# uv's inline spelling of [[index]], returning @{ DefaultUrl; Extras } or $null on ANY doubt, and only for a single-line array of FLAT inline tables. The brace characters below are built from code points: the parity tests extract a function by counting braces.
+# uv inline [[index]] reader; $null on ANY doubt. Braces are built from code points because
+# the parity tests extract functions by counting braces.
function Read-WoaUvInlineIndexArray {
param([string]$Value)
$lb = [char]0x7B; $rb = [char]0x7D
@@ -6623,7 +5955,6 @@ function Read-WoaUvInlineIndexArray {
if ($v -notmatch '^\[(.*)\]$') { return $null }
$inner = $Matches[1].Trim()
$result = @{ DefaultUrl = $null; Extras = @() }
- # `index = []` is a definite answer -- no indexes -- not a failure to read one.
if (-not $inner) { return $result }
$groups = @()
$depth = 0; $start = -1; $inD = $false; $inS = $false
@@ -6631,7 +5962,7 @@ function Read-WoaUvInlineIndexArray {
$c = $inner[$i]
if ($inD) { if ($c -eq '\') { $i++ } elseif ($c -eq '"') { $inD = $false }; continue }
if ($inS) { if ($c -eq "'") { $inS = $false }; continue }
- # A quote at depth 0 opens a BARE entry, not an inline table. Tested before string mode starts, or the literal is consumed whole.
+ # A quote at depth 0 opens a bare entry; tested before string mode starts.
if (($c -eq '"' -or $c -eq "'") -and $depth -eq 0) { return $null }
if ($c -eq '"') { $inD = $true; continue }
if ($c -eq "'") { $inS = $true; continue }
@@ -6659,11 +5990,11 @@ function Read-WoaUvInlineIndexArray {
$bool = if ($raw -match '^(true|false)$') { $raw -eq 'true' } else { $null }
if ($k -eq 'url') { if (-not $str) { return $null }; $url = $str }
elseif ($k -eq 'default') { if ($null -eq $bool) { return $null }; $isDefault = $bool }
- # uv: an explicit index serves only packages pinned to it via [tool.uv.sources], so it is neither the default nor an extra.
+ # An explicit index serves only pinned packages, so it is neither default nor extra.
elseif ($k -eq 'explicit') { if ($null -eq $bool) { return $null }; $isExplicit = $bool }
}
if (-not $url) { return $null }
- # explicit AND default also removes PyPI as the default (uv docs): not modelled, so doubt.
+ # explicit AND default also removes PyPI as default: not modelled, so doubt.
if ($isExplicit) { if ($isDefault) { return $null }; continue }
if ($isDefault) { if (-not $result.DefaultUrl) { $result.DefaultUrl = $url } }
else { $result.Extras += $url }
@@ -6812,7 +6143,7 @@ function Get-WoaUvConfigIndexPolicy {
return $result
}
-# True when uv's own config decides the indexes and we could not read it: fatal where the caller scrubs UV_* and sets UV_NO_CONFIG, because the trio index would be the only source left.
+# Fatal where the caller scrubs UV_* and sets UV_NO_CONFIG: the trio index would be the only source.
function Test-WoaUvIndexPolicyUnreadable {
foreach ($name in @("UV_NO_INDEX", "UV_DEFAULT_INDEX", "UV_INDEX_URL")) {
$v = [string][Environment]::GetEnvironmentVariable($name)
@@ -6857,7 +6188,7 @@ function Get-WoaDependencyIndexArgs {
return $indexArgs
}
-# Parity copy of install.ps1's Test-WoaAudioMatchesTorch: torchaudio tracks torch's major.minor.
+# Parity copy of install.ps1's Test-WoaAudioMatchesTorch.
function Test-WoaAudioMatchesTorchParity {
param([string]$TorchVersion, [string]$AudioVersion)
if (-not $TorchVersion -or -not $AudioVersion) { return $false }
@@ -6883,7 +6214,7 @@ function Get-WoaCudaWheelVersionParity {
if ([string]::IsNullOrWhiteSpace($body)) { return $null }
$best = $null
$bestKey = $null
- # PEP 440 order within one numeric release: dev < a < b < rc < final, then by number.
+ # PEP 440 order within one release: dev < a < b < rc < final.
$prerelease = {
param([string]$v)
$r = ($v -split '\+', 2)[0]
@@ -6891,7 +6222,6 @@ function Get-WoaCudaWheelVersionParity {
if ($r -match '(?i)(a|b|rc)(\d+)') { return @(@{ a = 1; b = 2; rc = 3 }[$Matches[1].ToLowerInvariant()], [long]$Matches[2]) }
return @(4, [long]0)
}
- # -Below: only versions ranked strictly under it, so a caller can walk back from an unpaired newest.
$belowKey = $null; $belowRank = $null
if ($Below) {
$belowNumeric = [regex]::Match((($Below -split '\+', 2)[0]), '^\d+(\.\d+){0,2}').Value
@@ -6939,7 +6269,7 @@ function Save-WoaTorchIndexMarker {
param([string]$IndexUrl)
$value = "$IndexUrl".Trim().TrimEnd('/')
if (-not (Test-WoaPersistableIndex $value)) {
- # CLEARED, not just skipped: a stale marker sent a corporate-mirror host back to NVIDIA's.
+ # Cleared, not just skipped: a stale marker sent a mirror host back to NVIDIA's index.
Remove-Item -LiteralPath (Get-WoaTorchIndexMarkerPath) -Force -ErrorAction SilentlyContinue
return
}
@@ -6983,7 +6313,7 @@ function Get-UvSafePath {
function Resolve-WoaOverrideLine {
param([string]$Line, [string]$BaseDir)
if (-not $BaseDir -or $Line -match '^\s*(#|$)') { return $Line }
- # pip's inline comment is whitespace then "#": split off, or the rebase reads it as part of the path.
+ # pip's inline comment is whitespace then "#"; split it off before rebasing the path.
$comment = ""
if ($Line -match '^(.*?)(\s+#.*)$') { $Line = $Matches[1]; $comment = $Matches[2] }
$abs = {
@@ -6992,14 +6322,14 @@ function Resolve-WoaOverrideLine {
try { return [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($BaseDir, $p)) } catch { return $p }
}
if ($Line -match '^(\s*)(-r|--requirement|-c|--constraint|-f|--find-links)([=\s]+)(.+?)(\s*)$') {
- # Copied out FIRST: the -match below replaces $Matches, dropping the option token.
+ # Copied out FIRST: the -match below replaces $Matches.
$lead = $Matches[1]; $opt = $Matches[2]; $sep = $Matches[3]
$bare = $Matches[4].Trim('"').Trim("'"); $tail = $Matches[5]
$rebased = & $abs $bare
if ($rebased -match '\s') { $rebased = '"' + $rebased + '"' }
return "$lead$opt$sep$rebased$tail$comment"
}
- # -e / --editable names a path too. Extras split off first, or GetFullPath folds ".[dev]" into the parent.
+ # Extras split off first, or GetFullPath folds ".[dev]" into the parent.
if ($Line -match '^(\s*)(-e|--editable)([=\s]+)(.+?)(\s*)$') {
$lead = $Matches[1]; $opt = $Matches[2]; $sep = $Matches[3]
$bare = $Matches[4].Trim('"').Trim("'"); $tail = $Matches[5]
@@ -7011,7 +6341,7 @@ function Resolve-WoaOverrideLine {
}
if ($Line -match '^(\s*[^\s@]+\s*@\s*)(.+?)(\s*)$') {
$head = $Matches[1]; $target = $Matches[2]; $tail = $Matches[3]
- # PEP 508 separates a marker from a URL with whitespace before the ";": kept aside, or it would be rebased as part of the path.
+ # A PEP 508 marker must be kept aside or it is rebased as part of the path.
$marker = ""
if ($target -match '^(.*?)(\s+;.*)$') { $target = $Matches[1]; $marker = $Matches[2] }
if ($target -match '^file:(?!//)(.*)$') {
@@ -7025,7 +6355,6 @@ function Resolve-WoaOverrideLine {
$lead = $Matches[1]; $path = $Matches[2]; $rest = $Matches[3]
if ($path -match '[\\/]') { return "$lead" + (& $abs $path) + "$rest$comment" }
}
- # A bare local directory is a requirement to pip and uv both; the leading dot segment is what tells it from a package name.
if ($Line -match '^(\s*)(\.{1,2}[^\s#;]*)(\s*(?:[;#].*)?)$') {
$lead = $Matches[1]; $path = $Matches[2]; $rest = $Matches[3]
$extras = ""
@@ -7044,7 +6373,7 @@ function Get-RequirementName {
return ($name -replace '[-_.]+', '-').ToLowerInvariant()
}
-# Includes followed: a conflict can sit a level down, and two files naming one package is an error.
+# Includes followed: uv errors when two files name one package.
function Get-RequirementEntries {
param([string]$Path, $Seen = $null, [int]$Depth = 0)
if ($Depth -gt 8) { return @() }
@@ -7078,7 +6407,7 @@ function Get-RequirementNames {
return @($names | Sort-Object -Unique)
}
-# Put back what install.ps1 exported: process-scoped, so a direct update starts without them. The merged override file copies caller lines, which can carry credentials, so it lives for one run only.
+# The merged override file can carry caller credentials, so it lives for one run only.
function Remove-WoaMergedOverrides {
if ($script:WoaMergedOverrides) {
Remove-Item -LiteralPath $script:WoaMergedOverrides -Force -ErrorAction SilentlyContinue
@@ -7092,7 +6421,6 @@ function Restore-WoaResolverEnvironment {
$overrides = Join-Path $woaDir "overrides.txt"
$wheels = Join-Path $woaDir "wheels"
Remove-Item -LiteralPath (Join-Path $woaDir "overrides.merged.txt") -Force -ErrorAction SilentlyContinue
- # install.ps1's per-run copy of folded caller lines; an interrupted run must not leave it behind.
Remove-Item -LiteralPath (Join-Path $woaDir "overrides.session.txt") -Force -ErrorAction SilentlyContinue
if (-not (Test-Path -LiteralPath $overrides -PathType Leaf)) {
if (-not $env:UV_OVERRIDE) {
@@ -7127,7 +6455,7 @@ function Restore-WoaResolverEnvironment {
foreach ($_woaFile in $_woaCallerFiles) {
foreach ($_woaEntry in (Get-RequirementEntries -Path $_woaFile)) {
if ((Get-RequirementName -Line $_woaEntry.Line) -in $_woaOursNames) { continue }
- # Rebased: uv resolves these against the file CONTAINING the line.
+ # Rebased: uv resolves these against the file containing the line.
$_woaLines += (Resolve-WoaOverrideLine -Line $_woaEntry.Line -BaseDir $_woaEntry.BaseDir)
}
}
@@ -7147,7 +6475,7 @@ function Restore-WoaResolverEnvironment {
}
}
if (Test-Path -LiteralPath $wheels -PathType Container) {
- # PREPENDED, never skipped: standing down left the staged win_arm64 wheels out entirely.
+ # Prepended, never skipped, or the staged win_arm64 wheels are left out.
$_woaSafeWheels = Get-UvSafePath $wheels
if (-not $env:UV_FIND_LINKS) { $env:UV_FIND_LINKS = $wheels }
elseif (($env:UV_FIND_LINKS -split '[,\s]+') -notcontains $wheels) {
@@ -7160,8 +6488,7 @@ function Restore-WoaResolverEnvironment {
}
}
-# Written before anything that could be interrupted, and cleared when torch is
-# wanted so migrating out of no-torch leaves nothing stale behind.
+# Written before anything interruptible; cleared when torch is wanted.
function Set-PersistedNoTorch {
param(
[Parameter(Mandatory = $true)][string]$VenvPath,
@@ -7178,50 +6505,31 @@ function Set-PersistedNoTorch {
} catch {}
}
-# Stale-venv detection: if the venv exists but its torch flavor no longer
-# matches the current machine, repair according to invocation context.
-# - install.ps1 sets UNSLOTH_INSTALL_ROLLBACK_MANAGED=1 so setup can delegate
-# to the installer-level rollback that restores the previous environment.
-# - direct `unsloth studio update` keeps the pre-existing self-repair behavior.
-# In no-torch mode, a missing torch package is expected.
$NoTorchMode = $env:UNSLOTH_NO_TORCH -match '^\s*(?i:true|1|yes|on)\s*$'
-# No env var at all means `unsloth studio update` / `studio setup` / setup.bat,
-# none of which export one. Without the manifest fallback the check below reads a
-# GGUF-only venv's missing torch as a stale venv and tries to delete the venv this
-# script is itself running out of, which fails on a locked python.exe.
+# No env var means a direct update; without the manifest fallback a GGUF-only venv reads as stale.
if (-not $NoTorchMode -and [string]::IsNullOrWhiteSpace($env:UNSLOTH_NO_TORCH)) {
$NoTorchMode = Get-PersistedNoTorch -VenvPath $VenvDir
if ($NoTorchMode) {
substep "no-torch install detected -- keeping this environment GGUF-only." "Yellow"
}
}
-# Persist before the torch install and the dependency pass below, either of which
-# can be interrupted; install_python_stack.py refreshes the same marker.
Set-PersistedNoTorch -VenvPath $VenvDir -NoTorch $NoTorchMode
-# install_python_stack.py drops the manifest before its dependency pass, so it
-# cannot repeat the lookup above; hand it the resolved answer. This also collapses
-# every accepted spelling to one value both sides parse identically.
+# Hand install_python_stack.py the resolved answer: it drops the manifest before reading it.
$env:UNSLOTH_NO_TORCH = if ($NoTorchMode) { "true" } else { "false" }
$InstallerManagedSetup = $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -match '^(?i:true|1|yes)$'
-# The torch family install.ps1 settled on, in the vocabulary the probe below produces (cu<digits>
-# / rocm / xpu / cpu). $null means it did not say: an installer predating the variable (setup.ps1
-# ships in the pip package, install.ps1 is fetched from unsloth.ai, so the two can be different
-# ages), --no-torch, or a custom index whose leaf names no flavor. Absent is unknown rather than a
-# mismatch, which keeps an older cached installer on its pre-variable behaviour. IsNullOrWhiteSpace
-# rather than a presence test: 7.5+ keeps an empty assignment as a present blank value, 5.1 and
-# 7.0-7.4 remove the variable.
+# $null means unknown (older installer, --no-torch, custom index), not a mismatch.
+# IsNullOrWhiteSpace: 7.5+ keeps an empty assignment as a present blank value.
$InstallerTorchTag = if ([string]::IsNullOrWhiteSpace($env:UNSLOTH_INSTALLER_TORCH_TAG)) { $null }
else { $env:UNSLOTH_INSTALLER_TORCH_TAG.Trim().ToLowerInvariant() }
-# Asked of the INTERPRETER, not the machine: an emulated x64 python is win-amd64. Memoized.
+# Asked of the INTERPRETER, not the machine: an emulated x64 python is win-amd64.
$script:_winArm64Venv = $null
function Test-WinArm64Venv {
if ($null -ne $script:_winArm64Venv) { return $script:_winArm64Venv }
- # Answered before any interpreter is launched: a corrupt python could hang the install.
+ # Before any interpreter launch: a corrupt python could hang.
if ((Get-HostMachineArch) -ne "arm64") {
$script:_winArm64Venv = $false
return $false
}
- # By path first: `python` may not be the venv's own, and a wrong answer "repairs" a good torch.
$candidates = @()
$managed = Join-Path $VenvDir "Scripts\python.exe"
if (Test-Path -LiteralPath $managed) { $candidates += $managed }
@@ -7232,7 +6540,7 @@ function Test-WinArm64Venv {
$platform = (& $exe -c "import sysconfig; print(sysconfig.get_platform())" 2>$null | Out-String).Trim().ToLowerInvariant()
} catch { $platform = "" }
if ($platform) {
- # Caching a failure would pin the wrong answer for the rest of the run.
+ # Do not cache a failure.
$script:_winArm64Venv = ($platform -eq "win-arm64")
return $script:_winArm64Venv
}
@@ -7240,73 +6548,51 @@ function Test-WinArm64Venv {
return $false
}
-# Only the stale-venv block below assigns this, but the XPU install reads it to decide whether to
-# force-reinstall and a fresh install never enters that block. Declaring it keeps a caller's
-# Set-StrictMode from making the read fatal.
+# Declared for StrictMode: a fresh install never assigns it but the XPU install reads it.
$installedTorchTag = $null
-# Hoisted for the same reason: four install arms read it to decide --force-reinstall and the
-# installer-managed repair below raises it, yet only the block a fresh install never enters
-# assigns it.
+# Hoisted for StrictMode, like the variable above.
$script:PinChangedForceReinstall = $false
$script:TorchImportDefinitivelyFailed = $false
if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode) {
$VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"
$installedTorchTag = $null
- # Declared before the branch that assigns it: the failure message below reads its .Error, and
- # a venv with no python.exe never runs the probe at all.
$_verProbe = $null
$shouldRebuild = $false
- # Set when a stale venv under a pin is repaired in place (force-reinstall) not wiped.
$script:PinChangedForceReinstall = $false
if (Test-Path -LiteralPath $VenvPyExe) {
- # Bounded like every other torch probe: reading stdout to EOF before waiting would hang
- # setup forever on a wedged `import torch`, and an undrained stderr deadlocks on a noisy
- # import. An unreadable flavor -> rebuild.
+ # Bounded: a wedged `import torch` would hang setup. An unreadable flavor rebuilds.
$_verProbe = Invoke-BoundedPythonProbe -PythonExe $VenvPyExe -Code 'import torch; print(torch.__version__)'
$torchVer = $_verProbe.Output.Trim()
if ($_verProbe.Ok -and $torchVer) {
if ($torchVer -match '\+(cu\d+)') {
$installedTorchTag = $Matches[1]
} elseif ($torchVer -match '\+rocm') {
- # Any +rocm / gfx wheel -> generic "rocm" flavor (the exact version is
- # repaired later by install_python_stack.py; here we only need the flavor).
$installedTorchTag = "rocm"
} elseif ($torchVer -match '\+xpu') {
- # Without this arm a +xpu wheel reads as "cpu" and an Arc venv looks correct
- # while being CPU-only. Matches ConvertTo-TorchFlavorTag.
+ # Without this a +xpu wheel reads as cpu. Matches ConvertTo-TorchFlavorTag.
$installedTorchTag = "xpu"
} elseif ($torchVer -match '\+cpu') {
$installedTorchTag = "cpu"
} else {
- # Untagged wheel (plain "2.x.y" from PyPI) -> cpu.
$installedTorchTag = "cpu"
}
} elseif (Test-VenvTorchIsXpu -VenvPath $VenvDir) {
- # Bounding this probe made a timeout mean "rebuild", and the host most likely to
- # time out inside `import torch` is an Arc box with a stalled driver -- where
- # version.py still names a good +xpu wheel, and the stale path would DELETE $VenvDir.
- # Trust the disk and warn about the driver; other families keep rebuilding.
+ # A stalled Arc driver times out the import; trust version.py rather than delete the venv.
$installedTorchTag = "xpu"
substep "PyTorch did not respond in time but this venv holds an XPU build -- keeping it." "Yellow"
substep "If training fails, update the Intel GPU compute driver." "Yellow"
} elseif (Test-VenvTorchIsRocm -VenvPath $VenvDir) {
- # Same rescue on the AMD side, and the one that has cost users whole installs: a
- # faulted Adrenalin or HIP runtime makes `import torch` raise at the DLL load or never
- # return, so a fine ROCm environment read as "torch could not be imported" and was
- # thrown away, which does not fix a driver. version.py on disk still names the wheel,
- # so trust it and point at the driver instead (#8335, #7275).
+ # Same on AMD: a faulted HIP runtime breaks the import while the wheel is fine; trust version.py.
$installedTorchTag = "rocm"
substep "PyTorch did not respond but this venv holds a ROCm build -- keeping it." "Yellow"
substep "If training fails, reboot and update the AMD Adrenalin / HIP SDK driver." "Yellow"
} elseif (Test-VenvTorchIsCuda -VenvPath $VenvDir) {
- # Without this the chain fell through with a NULL tag, so the no-wipe escape
- # below saw no cu* wheel to preserve. Keep the FAMILY, not a generic "cuda".
+ # Keep the CUDA FAMILY, or the no-wipe escape below sees nothing to preserve.
$installedTorchTag = Get-VenvTorchCudaTag -VenvPath $VenvDir
substep "PyTorch did not respond but this venv holds a $installedTorchTag build -- keeping it." "Yellow"
substep "If training fails, reboot and update the NVIDIA driver." "Yellow"
- # A half-written torch also leaves a +cu* version.py behind, and the matched
- # install below would write a completion manifest over it. Force the reinstall.
+ # A half-written torch leaves a +cu* version.py too; force the reinstall.
if ($_verProbe -and -not $_verProbe.TimedOut) {
$script:TorchImportDefinitivelyFailed = $true
substep "PyTorch failed to import rather than timing out -- reinstalling the same family in place." "Yellow"
@@ -7320,11 +6606,7 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
}
if (-not $shouldRebuild) {
- # The scan above only matches a WMI marketing name, so a throwing Get-CimInstance -- or
- # an Intel part outside the Arc|Data Center regex -- leaves $script:IsIntelXpu false, and
- # the chain below would expect "cpu", see "xpu" and WIPE a working XPU venv.
- # torch.xpu.is_available() on a +xpu wheel proves the host, so re-evaluate before the
- # stale decision. This repeats the scan's own gate, so NVIDIA / AMD keep winning.
+ # The WMI scan can miss an XPU host; torch.xpu.is_available() proves it before the stale decision.
if ($installedTorchTag -eq "xpu" -and -not $script:IsIntelXpu -and
-not $HasNvidiaSmi -and -not $AmdHasGpuWheels -and
(Test-TorchXpuAvailable -PythonExe $VenvPyExe)) {
@@ -7335,45 +6617,31 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$_expectedKnown = $true
if ($_pinnedIdx) {
$_pinLeaf = Get-TorchIndexLeaf $_pinnedIdx
- # Digit-gated like the install selection: a custom rocm-* leaf (rocm-current /
- # rocm-rel-7.2.1) is NOT a ROCm family and must not be stale-compared.
+ # Digit-gated: custom rocm-* leaves are not a ROCm family.
if (Test-PipRocmFamilyLeaf $_pinLeaf) {
# Keep the pinned leaf specific: a generic "rocm" masks a rocm6.4 -> gfx1151 change.
$_rocmTags = Get-RocmPinStaleTags -PinLeaf $_pinLeaf -TorchVersion $torchVer
$expectedTorchTag = $_rocmTags.Expected
$installedTorchTag = $_rocmTags.Installed
} elseif ((Test-CudaFamilyLeaf $_pinLeaf) -or $_pinLeaf -eq 'cpu' -or $_pinLeaf -eq 'xpu') {
- # cu*/cpu/xpu leaves stay specific so a cu126-vs-cu128 (or cpu-vs-xpu) mismatch
- # is caught; /custom and /current fall through to the unknown-index branch below.
$expectedTorchTag = $_pinLeaf
} else {
- # Custom index whose leaf is not a torch flavor (/simple mirror): never stale.
$_expectedKnown = $false
$expectedTorchTag = $installedTorchTag
}
} elseif ($HasNvidiaSmi) {
$expectedTorchTag = Get-PytorchCudaTag
if (-not $expectedTorchTag) {
- # No driver version from anywhere: not evidence the venv is stale.
$_expectedKnown = $false
$expectedTorchTag = $installedTorchTag
}
} elseif ($script:IsIntelXpu) {
- # Arc / Data Center host: the install below selects the xpu index. BEFORE the AMD
- # arm -- both can be true on an unmapped-arch AMD box, where xpu is what gets
- # installed. A CPU wheel is not wiped (the xpu install force-reinstalls over it in
- # place), so expect "cpu" there; a cu*/rocm wheel still rebuilds.
+ # Before the AMD arm: both can be true, and xpu is what gets installed. A CPU wheel is upgraded in place.
$expectedTorchTag = if ($installedTorchTag -eq "cpu") { "cpu" } else { "xpu" }
} elseif ($HasROCm -or $script:ROCmGfxArch) {
- # AMD/ROCm host with no explicit pin: an existing +rocm wheel is correct (gfx arch
- # counts even when $HasROCm is false). But only the arches the install path maps to a
- # repo.amd.com index get ROCm torch; an unmapped arch installs CPU, so expect "cpu"
- # for those or a correct CPU venv rebuilds every update.
- # $_rocmWheelArches is defined above the Intel scan (that gate needs it too).
+ # Only arches mapped to a repo.amd.com index get ROCm torch; others expect cpu.
if ($AmdHasGpuWheels) {
- # A correct +rocm wheel is not stale. A CPU wheel on a supported AMD arch is
- # NOT wiped either (the AMD Windows ROCm override below upgrades it in place);
- # expect "cpu" for that case. A wrong CUDA wheel still rebuilds.
+ # A CPU wheel on a supported AMD arch is upgraded in place, not wiped.
if ($installedTorchTag -eq "cpu") {
$expectedTorchTag = "cpu"
} else {
@@ -7390,7 +6658,7 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
}
}
- # Keep a CUDA torch already here: its family tag is not one download.pytorch.org publishes, so the comparison can only disagree. ANY explicit pin is exempt; this distrusts the INFERRED one.
+ # download.pytorch.org does not publish this family tag, so only explicit pins are compared.
if ((Test-WinArm64Venv) -and $installedTorchTag -and (Test-CudaFamilyLeaf $installedTorchTag) -and
-not $_pinnedIdx) {
if ($shouldRebuild) {
@@ -7400,110 +6668,55 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$script:PinChangedForceReinstall = $false
}
- # A stale venv whose torch still imports is repaired in place; only a broken venv wipes.
if ($shouldRebuild -and $_pinnedIdx -and $installedTorchTag) {
substep "Torch-index pin changed ($installedTorchTag) -- reinstalling torch from the pin in place." "Cyan"
$script:PinChangedForceReinstall = $true
$shouldRebuild = $false
}
- # Same for an unpinned cu* -> cu* move: the cap can change the expected family on a
- # healthy venv, and only install.ps1 creates venvs, so wiping here strands a direct
- # `studio update`. CPU/ROCm/XPU drift still rebuilds.
+ # Only install.ps1 creates venvs, so a direct update must not wipe on a cu* -> cu* move.
if ($shouldRebuild -and -not $_pinnedIdx -and $installedTorchTag -and
(Test-CudaFamilyLeaf $installedTorchTag) -and (Test-CudaFamilyLeaf $expectedTorchTag)) {
substep "CUDA family $installedTorchTag does not cover this host -- reinstalling $expectedTorchTag in place." "Cyan"
$script:PinChangedForceReinstall = $true
$shouldRebuild = $false
}
- # A +xpu venv is never wiped by a DIRECT update: on a hybrid NVIDIA+Arc box the promotion
- # above is gated on -not $HasNvidiaSmi, so a later pinless update expects a cu* tag, calls the
- # working Arc venv stale and deletes it -- then exits, because only install.ps1 creates venvs.
- # Under install.ps1 the in-place repair below covers every flavour, so this escape stays out.
+ # A direct update never wipes a +xpu venv: on hybrid NVIDIA+Arc the expected tag is cu*.
if ($shouldRebuild -and -not $InstallerManagedSetup -and $installedTorchTag -eq "xpu") {
substep "Keeping the installed Intel XPU environment (this host expects $expectedTorchTag)." "Yellow"
substep "Re-run install.ps1 to replace it -- that path rebuilds with a rollback copy." "Yellow"
$shouldRebuild = $false
- # Keeping the venv is only half the job: the index selection below prefers NVIDIA, and
- # the CUDA arm does NOT --reinstall-package torch, so uv would keep the +xpu wheel as
- # satisfied while installing triton-windows over torch's XPU triton, with $XpuIndexUrl
- # null and nothing to swap it back. So the whole pass stays on the xpu index.
+ # Stay on the xpu index, or triton-windows lands over torch's XPU triton.
$script:PreservedXpuVenv = $true
}
- # A GPU wheel install.ps1 SELECTED is never force-reinstalled onto a different family on the
- # strength of a rescan. Only a wheel matching the family install.ps1 reported in
- # $env:UNSLOTH_INSTALLER_TORCH_TAG counts as its answer, because "there is a GPU wheel in the
- # venv" does not by itself mean this run put it there: the migrated-venv arm (install.ps1's
- # `if ($_Migrated)`) installs unsloth alone and never touches torch, and install.ps1's flavor
- # repair no-ops whenever its expected tag is 'cpu' or unrecognised. So an ordinary upgrade off
- # the legacy ~/.unsloth/studio/.venv layout can hand setup a +cu118 wheel from a previous
- # install on different hardware; preserving THAT would leave the environment permanently wrong
- # and, on a mapped AMD host, the kept cu* tag also blocks the ROCm reroute below (it needs
- # $CuTag -eq "cpu"). Those repair in place, as they did before this guard existed.
- #
- # $InstallerTorchTag $null means the installer did not say (an older cached install.ps1, or
- # --no-torch), and unknown falls back to preserving, the behaviour that shipped before the
- # variable existed. Otherwise the disagreement is between setup's second probe and the first,
- # not with the hardware -- a Get-CimInstance that threw, an nvidia-smi that did not answer, the
- # single-Radeon unroll of #8335 -- and setup has no better claim than the installer that just
- # ran: the in-place repair below would --force-reinstall the other family over a working GPU
- # environment and exit 0, at which point install.ps1 discards the rollback copy and the damage
- # is permanent. A loud failure traded for a silently wrong install is worse than the loop this
- # block exists to end.
- #
- # Covers cpu rescans (+rocm -> cpu) and family-to-family ones (+rocm -> cu128, +cu128 -> rocm,
- # +xpu -> cu128) alike. Nothing legitimate is suppressed: a venv whose torch does not import at
- # all leaves $installedTorchTag $null and still repairs, a CPU wheel that has to become a GPU
- # one still repairs, cu* -> cu* already repaired in place above, and an explicit index pin
- # escaped before that. A genuine GPU swap is install.ps1's job, done before calling here.
- #
- # $expectedTorchTag is read in the MESSAGE, never in the condition: it is assigned only inside
- # the `if (-not $shouldRebuild)` block above, so on a venv whose torch would not import it was
- # never created and reading it under a caller's Set-StrictMode is fatal. The body is reached
- # only once $installedTorchTag has answered, which is only true on the path that assigned it.
+ # Never force-reinstall a different family over a GPU wheel install.ps1 just selected
+ # ($env:UNSLOTH_INSTALLER_TORCH_TAG); a rescan disagreeing is setup's probe failing, not new hardware.
+ # $expectedTorchTag is read only in the message: it is unset when torch did not import (StrictMode).
if ($shouldRebuild -and $InstallerManagedSetup -and
$installedTorchTag -and $installedTorchTag -ne "cpu" -and
((-not $InstallerTorchTag) -or $installedTorchTag -eq $InstallerTorchTag)) {
substep "This host rescanned as $expectedTorchTag but the installer just placed a $installedTorchTag build here -- keeping it." "Yellow"
substep "Set UNSLOTH_TORCH_INDEX_URL to move this environment onto another PyTorch build on purpose." "DarkGray"
$shouldRebuild = $false
- # Keeping the wheel is only half the job: the index selection below re-runs the same
- # rescan, and two of its arms force-reinstall torch regardless of
- # $script:PinChangedForceReinstall (the AMD arm always, the XPU arm whenever the installed
- # tag is not xpu), undoing this guard from a thousand lines further down.
+ # The index selection rescans and its AMD/XPU arms force-reinstall regardless, so record the keep.
$script:PreservedInstallerTorchTag = $installedTorchTag
- # Same reason as the direct-update escape above, and it needs its own flag: stay on the
- # xpu index, or triton-windows lands over torch's XPU triton with nothing to swap it back.
if ($installedTorchTag -eq "xpu") { $script:PreservedXpuVenv = $true }
}
$reason = $null
if ($shouldRebuild) {
$reason = if ($installedTorchTag) { "torch $installedTorchTag != required $expectedTorchTag" } else { "torch could not be imported" }
- # "torch could not be imported" covers a dead GPU driver, a half-written wheel and no torch
- # at all. Print what python actually said (the last stderr line is the exception), so a
- # WinError 126 reads as a driver problem instead of a broken install.
+ # Print python's last stderr line so a WinError 126 reads as a driver problem.
if ($_verProbe -and -not $_verProbe.Ok -and $_verProbe.Error) {
- # No @(...)[0] around this: the guard above passes on a whitespace-only stderr,
- # Where-Object then drops every line, and [0] into the empty array that leaves is fatal
- # under a caller's Set-StrictMode. -Last 1 already yields one string or nothing.
+ # No @(...)[0]: indexing an empty array is fatal under StrictMode.
$_probeErrLine = $_verProbe.Error -split "`r?`n" |
Where-Object { $_.Trim() } | Select-Object -Last 1
if ($_probeErrLine) { substep "PyTorch reported: $($_probeErrLine.Trim())" "DarkGray" }
}
}
- # The abort that used to live here was an unrecoverable fixed point, reported from four
- # separate triggers (#5942, #7275, #8335, plus a driver crash). It told the user to re-run
- # install.ps1 for a safe rollback replace -- but install.ps1 IS the caller under
- # $InstallerManagedSetup, it had already done exactly that earlier in the same run, and its
- # failure path moves the previous environment straight back, so every attempt ended on the
- # byte-identical state it started from and the install could never converge.
- #
- # Repair in place instead of wiping: the dependency pass force-reinstalls the torch trio from
- # the resolved index over this venv, the route an index-pin change and a cu* family change
- # already take above. Deleting is not an option here anyway -- install.ps1 invokes setup
- # through the venv's own python.exe, which is therefore locked by the process running this.
+ # Repair in place: install.ps1 is the caller and already did its rollback, and the venv's
+ # python.exe running this script is locked, so aborting or deleting could never converge.
if ($shouldRebuild -and $InstallerManagedSetup) {
substep "Environment does not match this host ($reason) -- reinstalling PyTorch in place." "Yellow"
substep "install.ps1 keeps a rollback copy of the previous environment until this run succeeds." "DarkGray"
@@ -7511,31 +6724,20 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$shouldRebuild = $false
}
- # A cu* venv is never wiped by a DIRECT update just because nvidia-smi did not answer:
- # every way that bounded probe comes back empty on a working NVIDIA host collapses
- # $expectedTorchTag to "cpu", no escape above catches it, and the wipe has no rollback
- # copy. Narrow on purpose: unpinned only, cu* installed only, and only when the collapse
- # was for want of an NVIDIA answer. The -and order also keeps the reads legal under
- # Set-StrictMode, since both are assigned inside `if (-not $shouldRebuild)`.
+ # A direct update never wipes a cu* venv just because nvidia-smi did not answer. The -and order
+ # keeps reads legal under StrictMode.
if ($shouldRebuild -and -not $InstallerManagedSetup -and
$installedTorchTag -and (Test-CudaFamilyLeaf $installedTorchTag) -and
-not $_pinnedIdx -and -not $HasNvidiaSmi -and $expectedTorchTag -eq "cpu") {
substep "nvidia-smi did not answer, but this venv holds a $installedTorchTag build -- keeping it." "Yellow"
substep "If training runs on CPU, re-run install.ps1: irm https://unsloth.ai/install.ps1 | iex" "Yellow"
$shouldRebuild = $false
- # Keeping the wheel is half the job: the index selection below rescans, sees no
- # NVIDIA either, and would route the install to the /cpu arm.
+ # Otherwise the index selection rescans and routes to /cpu.
$script:PreservedInstallerTorchTag = $installedTorchTag
}
- # A direct `unsloth studio update` has the installer-managed shape: the CLI is this script's
- # parent and runs from the venv's own python.exe, so the wipe below left a venv with no
- # unsloth_cli and a desktop whose update AND repair both start from it (#11247). Detected, not
- # assumed: run by hand from a checkout there is no interpreter inside, and the rebuild stands.
- # LAST of the direct-update escapes: this condition holds for EVERY stale direct update, so
- # ahead of the narrower ones it consumes $shouldRebuild and they never fire. Ahead of the
- # nvidia-smi guard specifically, $script:PreservedInstallerTorchTag goes unset and pairs with
- # the $PinChangedForceReinstall below to force a CPU wheel over a working cu* venv (#9857).
+ # A direct `studio update` runs from the venv's python.exe, so wiping breaks the CLI.
+ # Must stay LAST of the direct-update escapes: it matches every stale direct update.
if ($shouldRebuild -and -not $InstallerManagedSetup) {
$_hostPy = Get-SetupHostInterpreterInVenv -VenvDir $VenvDir
if ($_hostPy) {
@@ -7546,20 +6748,12 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
}
}
- # Outside the rebuild branch: an install that moved a venv aside, failed to delete the copy and
- # thereafter only repairs in place would never reach a sweep that lived inside it.
- # Validated like install.ps1's rollback sweep (Test-StudioVenvRollbackMustBePreserved), and then
- # some, because this one deletes on runs that rebuild nothing and runs ahead of the custom-root
- # guard: a NAME cannot be its whole authority, or the cost of a false positive is paid by a user
- # who never had a stale venv. Five refusals: a root that does not show it is ours, anything
- # outside the generated shape, a reparse point, a live owner (a concurrent setup's rescue copy,
- # not litter), and a directory carrying no sign of an environment we moved aside.
+ # Outside the rebuild branch: sweep moved-aside venvs. Strictly validated: ours root, generated
+ # name shape, no reparse point, no live owner, and a sign of a moved environment.
$_venvParent = Split-Path -Parent $VenvDir
$_venvLeaf = Split-Path -Leaf $VenvDir
- # Trailing -<n>: the rename below adds one when the destination is taken, as install.sh's
- # _start_studio_venv_replacement does, so the sweep must recognise it or that copy is permanent.
+ # Trailing -<n> matches the rename suffix, as in install.sh's _start_studio_venv_replacement.
$_staleShape = '^' + [regex]::Escape($_venvLeaf) + '\.stale-[0-9]{14}-([0-9]+)(?:-[0-9]+)?$'
- # Hoisted out of the rebuild branch below, which asks the same question before its own delete.
$_studioRootIsOurs = (
-not $StudioHomeIsCustom -or
(Test-Path -LiteralPath (Join-Path $VenvDir $StudioOwnedMarker) -PathType Leaf) -or
@@ -7567,8 +6761,7 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
(Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf) -or
(Test-UnslothCmdShimFile (Join-Path $StudioHome "bin\unsloth.cmd"))
)
- # [regex]::Match, not $Matches: which operator fills it, and on which result, moves between
- # Windows PowerShell 5.1 and 7.x, and a capture group decides what gets deleted here.
+ # [regex]::Match, not $Matches: its filling differs between 5.1 and 7.x, and it decides deletes.
foreach ($_old in @(
if ($_studioRootIsOurs) { Get-ChildItem -LiteralPath $_venvParent -Directory -Force -ErrorAction SilentlyContinue }
)) {
@@ -7578,9 +6771,6 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
$_ownerPid = 0
if (-not [int]::TryParse($_staleMatch.Groups[1].Value, [ref]$_ownerPid)) { continue }
if ($_ownerPid -ne $PID -and $null -ne (Get-Process -Id $_ownerPid -ErrorAction SilentlyContinue)) { continue }
- # pyvenv.cfg is in every environment `python -m venv` and `uv venv` create, the owned
- # marker is what install.ps1 and this script write into a root they adopt, and the stale
- # marker is dropped by the rename below and rewritten whenever the delete after it fails.
$_looksMoved = $false
foreach ($_sign in @("pyvenv.cfg", $StudioOwnedMarker, $StudioStaleMarker)) {
if (Test-Path -LiteralPath (Join-Path $_old.FullName $_sign) -PathType Leaf) { $_looksMoved = $true; break }
@@ -7594,24 +6784,14 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
if ($shouldRebuild) {
substep "Stale venv detected ($reason) -- rebuilding..." "Yellow"
- # why: mirror install.ps1 env-mode guard so an update against a custom
- # UNSLOTH_STUDIO_HOME never wipes an unrelated unsloth_studio venv;
- # -PathType Leaf rejects a directory masquerading as the sentinel.
- # The .cmd counts too, and for the same reason the uninstaller accepts it: a
- # policy's quarantine can take the unsigned .exe and leave a root that is still
- # ours. Content-checked, never by name -- this guard gates a recursive delete.
+ # Custom UNSLOTH_STUDIO_HOME: require the ownership marker (content-checked) before a recursive delete.
if (-not $_studioRootIsOurs) {
Write-StudioLine "[ERROR] $VenvDir already exists but does not look like an Unsloth Studio install." -ForegroundColor Red
Write-StudioLine " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." -ForegroundColor Yellow
Exit-SetupFailure "$VenvDir is not an Unsloth Studio environment"
}
- # Moved aside, then deleted: a rename takes the whole tree or fails and leaves it intact,
- # where Remove-Item -Recurse stops at the first locked file and leaves an environment that
- # can neither start nor update itself. Deleting the copy is best-effort, swept next run.
- # The pid joins the timestamp so two rebuilds in one second cannot collide on a name, and a
- # taken name still takes a numeric suffix: one process can reach this twice inside a second,
- # and a copy it left earlier may be on disk because its delete failed. Same shape, and the
- # same reason, as install.sh's _start_studio_venv_replacement.
+ # Rename, then delete: a rename is all-or-nothing, Remove-Item can stop half-way.
+ # pid plus timestamp plus suffix avoids name collisions.
$_staleStamp = Get-Date -Format 'yyyyMMddHHmmss'
$_staleLeaf = "$_venvLeaf.stale-$_staleStamp-$PID"
$_staleTry = 0
@@ -7627,10 +6807,7 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode
Exit-SetupFailure "Could not remove the stale environment at $VenvDir"
}
$_staleDir = Join-Path $_venvParent $_staleLeaf
- # Stamped before the delete and again after one fails: the sweep above refuses a copy that
- # carries no sign of being an environment we moved, and a half-deleted one can have lost
- # its pyvenv.cfg. Without the rewrite the litter this branch announces would be exactly the
- # litter the next run declines to touch.
+ # Stamped before and after a failed delete, or the sweep refuses the half-deleted copy.
try { [System.IO.File]::WriteAllText((Join-Path $_staleDir $StudioStaleMarker), "") } catch {}
try {
Remove-Item -LiteralPath $_staleDir -Recurse -Force -ErrorAction Stop
@@ -7651,13 +6828,7 @@ if (-not (Test-Path -LiteralPath $VenvDir)) {
$_venvPyExe = Join-Path $VenvDir "Scripts\python.exe"
$_venvActivate = Join-Path $VenvDir "Scripts\Activate.ps1"
if (Test-Path -LiteralPath $_venvPyExe) {
- # The interpreter is not the only file the rest of this script needs. Everything below
- # reaches the venv through the dot-sourced Activate.ps1 and a bare `python` (Fast-Install
- # resolves its target with (Get-Command python).Source), and install.ps1 deliberately
- # leaves the venv's Scripts directory off PATH. So a venv that kept python.exe but lost
- # Activate.ps1 fails the dot-source non-terminatingly at the "Continue" the pip section
- # runs at, installs the whole stack into whatever interpreter is on PATH, and exits 0.
- # Newly reachable now that an installer-managed stale verdict repairs instead of aborting.
+ # Activate.ps1 missing would silently install into PATH's python and exit 0.
if (-not (Test-Path -LiteralPath $_venvActivate)) {
Write-StudioLine "[ERROR] $VenvDir has no activation script at Scripts\Activate.ps1." -ForegroundColor Red
Write-StudioLine " The environment is incomplete rather than out of date. Re-run the installer" -ForegroundColor Yellow
@@ -7669,17 +6840,7 @@ if (-not (Test-Path -LiteralPath $VenvDir)) {
if ($_venvPyVer) { substep $_venvPyVer }
} catch {}
} else {
- # Stop here, because nothing downstream would: the activation below is a dot-source, and a
- # MISSING script is a NON-terminating error at the "Continue" the pip section runs at, so
- # setup would print one red line and carry on, resolving every `python` and `uv pip` that
- # follows against whatever interpreter is on PATH, installing the whole stack outside the
- # environment it was asked to build, and exiting 0 over a venv with not one package in it.
- #
- # An interpreter-less venv is incomplete, not out of date, so none of the decisions above
- # apply: the in-place torch repair has no interpreter to repair through, and the rebuild
- # path deletes the directory only to hit "Virtual environment not found" a few lines up.
- # Unlike the abort this replaced upstream, re-creating the environment genuinely changes
- # this state -- install.ps1 still holds the rollback copy of the previous one.
+ # Stop here: with no python.exe, setup would install the whole stack on PATH python and exit 0.
Write-StudioLine "[ERROR] $VenvDir has no interpreter at Scripts\python.exe." -ForegroundColor Red
Write-StudioLine " The environment is incomplete rather than out of date. Re-run the installer" -ForegroundColor Yellow
Write-StudioLine " to rebuild it: irm https://unsloth.ai/install.ps1 | iex" -ForegroundColor Yellow
@@ -7691,38 +6852,18 @@ if (-not (Test-Path -LiteralPath $VenvDir)) {
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
-# Existence is not activation. The two refusals above check that a file is THERE; neither can tell
-# whether dot-sourcing it took effect, and the ways it silently does not are ordinary damage on a
-# half-written venv. Activate.ps1 prepends the venv to PATH in its LAST statement, 28 lines after
-# it sets $env:VIRTUAL_ENV, so a copy truncated by an interrupted or out-of-disk `python -m venv`
-# parses, runs to its last complete statement and returns without printing anything at all, and an
-# unparseable one is a ParserError, non-terminating at the "Continue" set just above. Either way
-# the dot-source "succeeds" with the ambient interpreter still first on PATH -- the system or
-# Microsoft Store python, since install.ps1 keeps the venv's Scripts directory off PATH on purpose.
-# Fast-Install hands exactly that to `uv pip install --python`, the whole stack lands outside the
-# venv, every Exit-SetupFailure below keys off that wrong interpreter's exit code, and setup exits
-# 0 -- at which point install.ps1 commits over the rollback copy and the previous working
-# environment is gone for good.
-#
-# So assert the post-condition instead of a third pre-condition: the `python` now in effect has to
-# live under $VenvDir. $env:VIRTUAL_ENV would not do, precisely because Activate.ps1 sets it
-# before the line that matters.
+# A truncated or unparseable Activate.ps1 silently leaves the ambient python first on PATH, and
+# install.ps1 would then commit over its rollback. Assert the post-condition, not VIRTUAL_ENV.
function Assert-VenvActivated {
param([Parameter(Mandatory = $true)][string]$VenvDir)
- # Both sides normalised through Get-Item, which is what Activate.ps1 itself uses to build the
- # PATH entry ($VenvExecDir = Get-Item -Path $VenvExecPath): agreeing on the normaliser keeps a
- # short 8.3 path, a substituted drive, a junction or a differently cased drive letter from
- # reading as "outside". A guard that false-positives here would break every install, so every
- # branch that cannot PROVE the interpreter is wrong returns.
+ # Normalise both sides through Get-Item as Activate.ps1 does. Return unless provably wrong.
$venvRoot = $null
try { $venvRoot = (Get-Item -LiteralPath $VenvDir -Force -ErrorAction Stop).FullName.TrimEnd('\', '/') } catch { $venvRoot = $null }
if (-not $venvRoot) { return }
$_pyCmd = Get-Command python -ErrorAction SilentlyContinue | Select-Object -First 1
- # A function or alias named python carries no Source to judge, and judging it wrong would
- # refuse an install that works. Only an application resolved off PATH is decidable, and that
- # is also the only shape Fast-Install's -- python hand-off can be aimed at.
+ # Only an Application resolved off PATH is decidable.
if ($_pyCmd -and $_pyCmd.CommandType -ne 'Application') { return }
$_pyPath = $null
if ($_pyCmd -and $_pyCmd.Source) {
@@ -7743,9 +6884,7 @@ function Assert-VenvActivated {
Exit-SetupFailure "Activating $VenvDir did not put its interpreter on PATH (python resolves to $_where)"
}
-# Mirrors install.ps1's Install-UvFromRelease: same archive, destination priority and user-PATH
-# prepend as astral's installer, but it fetches a data file with a pinned SHA-256 instead of
-# running remote script text in-process.
+# Mirrors install.ps1's Install-UvFromRelease with a pinned SHA-256 instead of remote script.
# tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
# Bumping the version means bumping all 3 hashes, and each Wheel/WheelSha256 as in install.ps1:
# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/uv-<arch>-pc-windows-msvc.zip.sha256
@@ -7759,8 +6898,7 @@ $UvPinnedAssets = @{
Wheel = "packages/00/7c/e38b312abaae1bd59ff5886126f48e9e223fbb9a8edf9e236ede976f67cb/uv-0.13.5-py3-none-win32.whl"; WheelSha256 = "F4E55A6E2A1089FE74ED50FBDF2DF0F6F336EE148AD232B05932DB5DEEE8007E" }
}
-# Not Get-HostMachineArch: it answers arm64/other for the VC++ and prebuilt probes, and "other"
-# cannot pick between the x86_64 and i686 archives. install.ps1's resolution order.
+# Not Get-HostMachineArch: "other" cannot pick between x86_64 and i686.
function Get-UvHostArch {
$osArch = ""
try { $osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { $osArch = "" }
@@ -7782,15 +6920,10 @@ function Get-UvHostArch {
}
function Get-SetupUvExecutableVerdict {
- # Mirrors Get-UvExecutableVerdict in install.ps1: "ok", "failed" or "unknown". Only the
- # binary answering non-zero is "failed"; a launch that throws or a wait that times out got
- # no verdict, and the digest already proved the bytes are astral's pinned release.
- # Returns the verdict ONLY: a reason on the pipeline made the caller read [reason, verdict]
- # and take the last element, so substep carries them instead. A cached exit code decides;
- # with none (the timed wait can return first), a printed version is "ok".
+ # Mirrors install.ps1 Get-UvExecutableVerdict: "ok", "failed" or "unknown". Returns ONLY the verdict;
+ # only a non-zero exit is "failed".
param([string]$Path)
- # What the binary printed, for the caller that has to know WHICH uv answered. A second
- # pipeline value would undo the paragraph above; re-running it would be a chance to hang.
+ # Which uv answered, without a second pipeline value.
$script:SetupUvVersionLine = ""
if (-not $Path -or -not (Test-Path -LiteralPath $Path)) { return "failed" }
$outFile = [System.IO.Path]::GetTempFileName()
@@ -7803,8 +6936,7 @@ function Get-SetupUvExecutableVerdict {
substep "uv did not answer --version within 20s; installing it unprobed."
return "unknown"
}
- # The timed overload can return before the exit code is cached (arm64 and the Windows
- # containers read a working uv as broken); the parameterless wait settles it at once.
+ # The timed wait can return before the exit code is cached; the parameterless wait settles it.
try { $proc.WaitForExit() } catch {}
$answer = ""
try { $answer = Get-Content -LiteralPath $outFile -Raw -ErrorAction SilentlyContinue } catch {}
@@ -7812,12 +6944,10 @@ function Get-SetupUvExecutableVerdict {
$code = $null
try { $code = $proc.ExitCode } catch {}
if ($null -eq $code -or "$code" -eq "") {
- # No exit code: a printed version is "ok"; nothing printed gets no verdict.
if ($answer -and ($answer.Trim() -match '^uv \d+\.\d+')) { return "ok" }
substep "uv --version gave no exit code; installing it unprobed."
return "unknown"
}
- # A code decides: a printed version with a non-zero exit is the binary's own failure.
if ($code -eq 0) { return "ok" }
$detail = ""
try {
@@ -7836,13 +6966,11 @@ function Get-SetupUvExecutableVerdict {
}
function Get-UvInstallDir {
- # astral's destination priority. Shared with the probe below, so "where uv was put" and "where
- # uv is looked for" cannot drift.
+ # astral's destination priority, shared so install and lookup cannot drift.
foreach ($candidate in @($env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)) {
if ($candidate) { return $candidate }
}
- # Only if Join-Path actually produced one: on a nonexistent drive it returns null under
- # ErrorActionPreference Continue, and the inline original fell through to the home fallback.
+ # Join-Path returns null for a nonexistent drive under Continue.
if ($env:XDG_DATA_HOME) {
$fromData = Join-Path $env:XDG_DATA_HOME "../bin" -ErrorAction SilentlyContinue
if ($fromData) { return $fromData }
@@ -7864,18 +6992,13 @@ function Install-UvFromPinnedRelease {
$remote = $asset
$wheelDir = $null
- # astral's destination priority, so an existing uv is replaced in place and the Get-Command
- # probe after Refresh-Environment still finds it.
$destDir = Get-UvInstallDir
if (-not $destDir) {
Write-Output "Could not determine a home directory to install uv into."
return $false
}
- # astral's sources in astral's order, each exclusive when set. UV_DOWNLOAD_URL (and its older
- # alias INSTALLER_DOWNLOAD_URL) outrank the mirror variables there, and a host that sets one
- # usually cannot reach the public endpoints at all, so trying those first would stall. The pin
- # still applies: a source serving a different build fails the digest and the caller falls back.
+ # astral's sources in astral's order, each exclusive when set; the digest still applies.
$uvBase = if ($env:UV_DOWNLOAD_URL) {
@("$($env:UV_DOWNLOAD_URL.TrimEnd('/'))")
} elseif ($env:INSTALLER_DOWNLOAD_URL) {
@@ -7898,8 +7021,7 @@ function Install-UvFromPinnedRelease {
$zip = Join-Path $work $asset
try {
[System.IO.Directory]::CreateDirectory($work) | Out-Null
- # Digest per mirror, as install.ps1 does: a proxy answering 200 with its own body is a
- # successful download by every measure Invoke-WebRequest has.
+ # Digest per mirror: a proxy can answer 200 with its own body.
$downloaded = $false
$script:UvPinnedUnfetched = $true
foreach ($base in $uvBase) {
@@ -7931,17 +7053,13 @@ function Install-UvFromPinnedRelease {
Write-Output "uv.exe was not present in $asset."
return $false
}
- # Run it where it landed, before the destination is touched: a host can have a working
- # older uv while a policy refuses this one, and copying first leaves it with neither.
+ # Run the staged binary first: policy may refuse it while an older uv works.
if ((Get-SetupUvExecutableVerdict -Path $stagedUv) -eq "failed") {
Write-Output "the downloaded uv $UvPinnedVersion could not run on this machine."
return $false
}
- # uvw.exe is the windowless launcher and has no console to answer a probe on, so the
- # staged uv.exe above stands for the set: it came from the same verified archive.
- # Copy-Item under Stop so a locked or ACL-denied destination fails the install rather
- # than leaving half a set behind quietly.
+ # uvw.exe has no console to probe; the staged uv.exe stands for the verified set.
$haveUv = $true
foreach ($exe in @("uv.exe", "uvx.exe", "uvw.exe")) {
$src = Join-Path $srcRoot $exe
@@ -7954,8 +7072,7 @@ function Install-UvFromPinnedRelease {
break
}
if ($exe -eq "uv.exe") {
- # Invoke-SetupCommand sets ErrorActionPreference to Continue, so compare
- # against the archive we verified: a stale uv.exe must not pass for ours.
+ # Invoke-SetupCommand uses Continue, so compare against the archive: a stale uv.exe must not pass.
$copied = $false
try {
$copied = (Test-Path -LiteralPath $dst) -and
@@ -7973,15 +7090,12 @@ function Install-UvFromPinnedRelease {
Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
}
- # astral's PATH treatment and opt-outs: an unmanaged install forces no-modify-path there, so
- # it must here too. The user-PATH prepend is what survives the Refresh-Environment below.
+ # astral's PATH opt-outs: an unmanaged install implies no-modify-path.
if (-not $env:UV_NO_MODIFY_PATH -and -not $env:UV_UNMANAGED_INSTALL) {
Add-ToUserPath -Directory $destDir -Position Prepend | Out-Null
}
$env:PATH = "$destDir;$env:PATH"
- # Recorded on the script scope as well as returned: the caller runs this through
- # Invoke-SetupCommand, which hands back [int]$LASTEXITCODE rather than the pipeline value,
- # so the return alone cannot tell the fallback whether to run.
+ # Invoke-SetupCommand returns $LASTEXITCODE, not the pipeline value, so record on script scope.
$script:UvPinnedInstalled = $true
return $true
}
@@ -8002,29 +7116,20 @@ Enter-StudioVenv
Assert-VenvActivated -VenvDir $VenvDir
function Find-InstalledUv {
- # The uv a previous run installed but this process's PATH lacks (a desktop shell launched
- # before the install, a CI step): the miss re-downloaded the pinned archive every update,
- # 42 of a 53 s Windows no-op. Install-UvFromPinnedRelease's own priority list plus
- # install.ps1's winget alias directory; it has to run, not merely exist.
- # .NET Combine, not the path cmdlet: under ErrorActionPreference Stop, before the
- # installation branch's try, the cmdlet terminates on a missing drive (XDG_DATA_HOME=Z:\xdg).
- # Get-UvInstallDir first, so the installer's own destination leads however that helper
- # changes. It joins with the cmdlet, hence the try: here that is outside the branch's own.
+ # Find a uv a previous run installed but this PATH lacks, to avoid re-downloading every update.
+ # .NET Combine, not the path cmdlet: it terminates on a missing drive under Stop.
$installerDest = $null
try { $installerDest = Get-UvInstallDir } catch { $installerDest = $null }
$candidates = @($installerDest, $env:UV_INSTALL_DIR, $env:UV_UNMANAGED_INSTALL, $env:XDG_BIN_HOME)
if ($env:XDG_DATA_HOME) { $candidates += [System.IO.Path]::Combine($env:XDG_DATA_HOME, "..", "bin") }
$userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
if ($userHome) { $candidates += [System.IO.Path]::Combine($userHome, ".local", "bin") }
- # winget's alias directory reaches PATH only via the registry, so a process started before
- # install.ps1's winget route never saw it and downloaded the pinned release over it.
+ # winget's alias dir reaches PATH only via the registry.
if ($env:LOCALAPPDATA) { $candidates += [System.IO.Path]::Combine($env:LOCALAPPDATA, "Microsoft", "WinGet", "Links") }
$script:InstalledUvLooked = @()
- # Assigned even when no uv.exe exists: unassigned, it terminates under a caller's Set-StrictMode.
+ # Assigned even when no uv.exe exists (StrictMode).
$script:InstalledUvProbeMiss = $null
$script:InstalledUvTooOld = $null
- # Two variables commonly name one directory, which would then be launched and reported twice.
- # Ordinal, since a path differing only in case is the same directory here.
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($dir in $candidates) {
if (-not $dir) { continue }
@@ -8032,12 +7137,8 @@ function Find-InstalledUv {
$exe = [System.IO.Path]::Combine($dir, "uv.exe")
$script:InstalledUvLooked += $exe
if (-not (Test-Path -LiteralPath $exe -PathType Leaf -ErrorAction SilentlyContinue)) { continue }
- # "ok" only: no digest vouches for a found binary, and a launch that threw or timed out
- # would reach an unbounded uv pip. Asked twice: one miss (a scanner holding a fresh
- # binary) sent setup to the pinned download, which put an OLDER uv over this one.
+ # "ok" only, asked twice: no digest vouches for a found binary, and one miss downgraded uv.
if ((Get-InstalledUvVerdict -Path $exe) -ne "ok") { continue }
- # install.ps1's UvMinVersion: reuse accepts what the Windows installer accepts, no more.
- # Unreadable leaves the candidate alone.
if (-not (Test-SetupUvVersionAtLeast -VersionLine $script:SetupUvVersionLine -Minimum $SetupUvMinVersion)) {
$script:InstalledUvTooOld = $exe
continue
@@ -8053,28 +7154,22 @@ function Find-InstalledUv {
$SetupUvMinVersion = "0.13.4"
function Test-SetupUvVersionAtLeast {
- # "uv 0.12.1 (abcdef0 2026-01-01)" -> $true when 0.12.1 is at least $Minimum. Unparseable is
- # $false: the download that follows is what ran before the reuse existed.
+ # Unparseable is $false.
param([string]$VersionLine, [string]$Minimum)
if (-not $VersionLine) { return $false }
if ($VersionLine -notmatch '(?m)^\s*uv\s+(\d+(?:\.\d+){0,2})([-+]\S*)?') { return $false }
$found = $Matches[1]
- # A group that did not participate is absent from $Matches, and reading it would throw under
- # a caller's Set-StrictMode rather than read as "no suffix".
+ # Reading an absent group throws under StrictMode.
$pre = if ($Matches.ContainsKey(2)) { $Matches[2] } else { "" }
try {
if ([version]$found -gt [version]$Minimum) { return $true }
- # A prerelease of the floor itself is the floor minus something, so it does not clear it.
- # install.sh's _uv_version_ok refuses the same shape.
+ # A prerelease of the floor does not clear it, as install.sh's _uv_version_ok.
if ([version]$found -eq [version]$Minimum) { return (-not $pre) }
return $false
} catch { return $false }
}
function Get-InstalledUvVerdict {
- # The verdict alone, asked twice. The last element, not the value itself: the verdict
- # function is shared with the staged-uv check, and this keeps reading it correctly if a
- # reason is ever written to the pipeline again.
param([string]$Path)
$verdict = @(Get-SetupUvExecutableVerdict -Path $Path)[-1]
if ($verdict -eq "ok") { return "ok" }
@@ -8108,8 +7203,7 @@ $pathUvOld = Get-SetupPathUvTooOld
if ((Get-Command uv -ErrorAction SilentlyContinue) -and -not $pathUvOld) {
$UseUv = $true
} elseif (($installedUvDir = Find-InstalledUv)) {
- # Read-only reuse, fine under a stage root. Appended: a python.exe beside uv must not
- # step in front of the staged interpreter.
+ # Appended: a python.exe beside uv must not step in front of the staged interpreter.
$env:PATH = "$env:PATH;$installedUvDir"
if ($pathUvOld) {
# Re-entering the venv restores the pre-venv PATH first, so it goes before the current uv
@@ -8126,7 +7220,6 @@ if ((Get-Command uv -ErrorAction SilentlyContinue) -and -not $pathUvOld) {
} elseif ($script:InstalledUvProbeMiss) {
substep "the uv at $($script:InstalledUvProbeMiss) did not answer --version twice; installing the pinned release"
} elseif ($script:InstalledUvLooked) {
- # Names the destinations searched, so a re-download can be read.
substep "no installed uv at $($script:InstalledUvLooked -join ', '); installing the pinned release"
}
substep "installing uv package manager..."
@@ -8136,10 +7229,7 @@ if ((Get-Command uv -ErrorAction SilentlyContinue) -and -not $pathUvOld) {
if (-not $script:UvPinnedInstalled -and $script:UvPinnedUnfetched -and (Use-MirrorSpare uvbin)) {
Invoke-SetupCommand { Install-UvFromPinnedRelease } | Out-Null
}
- # The merge base ran astral's installer here, so a failed pinned install needs somewhere
- # to go: with no fallback the setup drops to pip for torch, bitsandbytes and Triton, which
- # is a different resolver rather than a different download. winget, not the remote script,
- # which is the shape this branch removes and is what install.ps1 already tries first.
+ # Fallback to winget after a failed pinned install, never the remote installer script.
if (-not $script:UvPinnedInstalled -and (Get-Command winget -ErrorAction SilentlyContinue)) {
Invoke-SetupCommand {
winget install --id astral-sh.uv --source winget --accept-source-agreements `
@@ -8147,13 +7237,9 @@ if ((Get-Command uv -ErrorAction SilentlyContinue) -and -not $pathUvOld) {
} | Out-Null
}
Refresh-Environment
- # Re-activate venv since Refresh-Environment rebuilds PATH from
- # registry and drops the venv's Scripts directory
+ # Refresh-Environment drops the venv's Scripts dir from PATH.
Enter-StudioVenv
- # Refresh-Environment rebuilds PATH from the registry, where the user-PATH prepend does
- # not always land (UV_NO_MODIFY_PATH, UV_UNMANAGED_INSTALL, a runner pinning its own
- # environment). Without this the installing run falls back to pip and writes a manifest
- # with no uv_version, which the next run rewrites.
+ # Refresh-Environment may drop the uv dir; without it the run falls back to pip.
$uvDir = Get-UvInstallDir
if ($uvDir -and (Test-Path -LiteralPath (Join-Path $uvDir "uv.exe"))) {
$env:PATH = $uvDir + ";" + $env:PATH
@@ -8180,13 +7266,10 @@ if ((Get-Command uv -ErrorAction SilentlyContinue) -and -not $pathUvOld) {
if (-not $env:UV_SYSTEM_CERTS) { $env:UV_SYSTEM_CERTS = "1" }
if (-not $env:UV_NATIVE_TLS) { $env:UV_NATIVE_TLS = "1" }
}
-# Refresh-Environment rebuilt PATH from the registry, and the re-activation meant to put the venv
-# back sits inside a catch that swallows everything -- including a dot-source that died after
-# Activate.ps1's own `deactivate -nondestructive` had restored the pre-venv PATH. Re-check outside
-# the catch: this is the last statement before Fast-Install starts resolving `python`.
+# The re-activation above sits in a catch that swallows failures; re-check before Fast-Install.
Assert-VenvActivated -VenvDir $VenvDir
-# pip does not understand uv's resolver flags, so they are dropped with any value that follows. Of --prerelease's five values only allow maps to pip (--pre); the rest drop rather than invert.
+# Only --prerelease allow maps to pip (--pre); other uv resolver flags and values are dropped.
function Remove-UvOnlyResolverFlags {
param([object[]]$Arguments)
$kept = @()
@@ -8209,10 +7292,9 @@ function Remove-UvOnlyResolverFlags {
return ,$kept
}
-# Helper: install a package, preferring uv with pip fallback
function Fast-Install {
param([Parameter(ValueFromRemainingArguments=$true)]$Args_)
- # An explicit --index-url must win: inherited index vars pull CPU torch over GPU (#6898).
+ # An explicit --index-url must win: inherited index vars pull CPU torch over GPU.
$saved = @{}
$pinned = @($Args_) -contains '--index-url'
if ($pinned) {
@@ -8224,7 +7306,7 @@ function Fast-Install {
Remove-Item "Env:$n" -ErrorAction SilentlyContinue
}
$env:UV_NO_CONFIG = '1'
- # PIP_CONFIG_FILE = 'nul' stops a `pip config` extra-index-url reaching the pip fallback.
+ # 'nul' stops a `pip config` extra-index-url reaching the pip fallback.
$env:PIP_CONFIG_FILE = 'nul'
}
try {
@@ -8245,8 +7327,6 @@ function Fast-Install {
}
}
-# uv first, pip as the fallback -- the shape install.sh uses to prune a dependency-pulled wheel.
-# No index scrub: an uninstall reads no index.
function Fast-Uninstall {
param([Parameter(ValueFromRemainingArguments=$true)]$Args_)
if ($UseUv) {
@@ -8257,9 +7337,7 @@ function Fast-Uninstall {
& python -m pip uninstall -y @Args_ 2>&1
}
-# Fetch a wheel without installing it, so a destructive step can be staged behind a download.
-# pip only: uv has no `pip download` (astral-sh/uv#3163). Scrubbed like Fast-Install, minus the
-# UV_* pip cannot read: an inherited PIP_INDEX_URL or user pip.conf would outrank --index-url.
+# pip only: uv has no `pip download`. Scrubbed like Fast-Install.
function Fast-Download {
param([Parameter(ValueFromRemainingArguments=$true)]$Args_)
$saved = @{}
@@ -8278,10 +7356,7 @@ function Fast-Download {
}
# ── Check if Python deps need updating ──
-# Compare installed package version against PyPI latest.
-# Skip all Python dependency work if versions match (fast update path).
-# Does the venv prove a finished install? One implementation for the incomplete-install guard
-# and the offline rule, so they cannot disagree about "complete".
+# One definition of a verified install for the incomplete-install guard and the offline rule.
function Test-StudioInstallVerified {
try {
& python -c "
@@ -8301,37 +7376,29 @@ import inspect
deep = {'deep': True} if 'deep' in inspect.signature(install_manifest.verify_install).parameters else {}
sys.exit(0 if install_manifest.verify_install(**deep)['ok'] else 1)
" "$PSScriptRoot" 2>$null | Out-Null
- # Out-Null, not just 2>$null: an unassigned native call leaves stdout in the
- # success stream, so `return $false` came back as @("...", $false), which is truthy.
+ # Out-Null: stdout left in the success stream would make the return value truthy.
return ($LASTEXITCODE -eq 0)
} catch { return $false }
}
-# UV_OFFLINE is uv's own "no network" switch, and every install here goes through uv.
function Test-UvOfflineRequested {
- # uv's boolish parser (uv 0.10.7). One reading of the set for the whole script, so a
- # correction lands on every UV_* switch at once rather than on whichever site was
- # remembered. Mirrors _uv_offline_requested in setup.sh.
+ # Mirrors _uv_offline_requested in setup.sh.
return (Test-UvEnvFlag "UV_OFFLINE")
}
function Invoke-FastPathEscapes {
- # Every reason an "up to date" package is still not a working install. Both fast-path callers
- # run it, so an offline skip meets the online bar. Test-StudioInstallVerified and the AMD/ROCm
- # probe stay out: each caller words them differently. A plain assignment in a function is LOCAL,
- # so the flag is copied in and published once on the way out.
+ # Every reason an up-to-date package is still not a working install. Function assignments are
+ # local, so the flag is copied in and published on the way out.
$SkipPythonDeps = $script:SkipPythonDeps
- # The documented escape hatch, first: install_python_stack.py honours
- # UNSLOTH_STUDIO_FULL_DEPS but never runs once the version compare skips, so it did nothing
- # for exactly the up-to-date broken install it exists for.
+ # UNSLOTH_STUDIO_FULL_DEPS must work here: install_python_stack.py never runs once the compare skips.
$_fullDepsRequested = "$($env:UNSLOTH_STUDIO_FULL_DEPS)".Trim()
if (@('1', 'true', 'yes', 'on') -contains $_fullDepsRequested.ToLowerInvariant()) {
substep "UNSLOTH_STUDIO_FULL_DEPS is set -- forcing dependency pass..." "Cyan"
$SkipPythonDeps = $false
}
- # A pre-#6483 install stuck on anyio>=4.14 would skip the repair (#6797), so force it.
+ # Pre-pin installs stuck on anyio>=4.14 need the repair.
$_anyioBad = $false
try {
& python -c "
@@ -8351,8 +7418,7 @@ sys.exit(0 if (major, minor) >= (4, 14) else 1)
substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..." "Cyan"
$SkipPythonDeps = $false
}
- # As setup.sh: a pre-pin tokenizers the installed transformers rejects breaks every `import
- # transformers` while $_PkgName is current. Ask the metadata, not the broken import.
+ # A pre-pin tokenizers breaks `import transformers`; ask the metadata, not the import.
$_tokenizersBad = $false
try {
& python -c "
@@ -8376,11 +7442,8 @@ sys.exit(0 if windows and installed not in windows[0] else 1)
substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..." "Cyan"
$SkipPythonDeps = $false
}
- # If the desktop app specifies a minimum required backend version and the installed
- # package is older than that requirement, force the dependency pass to upgrade it.
if ($env:UNSLOTH_DESKTOP_BACKEND_VERSION) {
- # Cleared only on a confirmed exit 0, mirroring setup.sh's `if !`: an invocation that
- # throws left it false, so an install under the floor kept the fast path.
+ # Cleared only on a confirmed exit 0, as setup.sh does.
$_desktopVerBad = $true
try {
& python -c "
@@ -8402,8 +7465,7 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
$SkipPythonDeps = $false
}
}
- # As setup.sh: the pinned Diffusers main build is installed only by the pass, so an install
- # that never ran that step (updated by an installer that predates it) kept the release.
+ # The pinned Diffusers build is installed only by the pass.
if ($SkipPythonDeps) {
$_diffusersMainMissing = $false
try {
@@ -8419,21 +7481,17 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
}
}
}
- # ...and for an Intel GPU, or a CPU wheel stays forever. Both escapes reach the XPU install,
- # gated on $XpuIndexUrl, so $_xpuIsReachable holds them back where a pin or no-torch mode
- # sends this host elsewhere and they would re-fire forever.
+ # Intel GPU escapes, gated on the XPU index being reachable or they re-fire forever.
$_pinLeafNow = Get-TorchIndexLeaf (Get-PinnedTorchIndexUrl)
$_xpuIsReachable = (-not $NoTorchMode) -and ((-not $_pinLeafNow) -or ($_pinLeafNow -eq "xpu"))
if ($script:IsIntelXpu -and $SkipPythonDeps -and $_xpuIsReachable) {
- # The WHEEL, not the runtime: a wedged driver also fails torch.xpu.is_available(), and the
- # pass cannot repair a driver.
+ # The WHEEL, not the runtime: the pass cannot repair a driver.
if (-not (Test-VenvTorchIsXpuSupported -VenvPath $VenvDir)) {
substep "Intel GPU detected but installed PyTorch is not a supported XPU build -- reinstalling XPU PyTorch" "Cyan"
$SkipPythonDeps = $false
}
}
- # The promotion runs after the fast path, so clear $SkipPythonDeps here or CPU torch is kept
- # forever. Only when a CUDA family is reachable (not pinned, no-torch, or pre-R450).
+ # The promotion runs after the fast path, so clear $SkipPythonDeps here or CPU torch is kept.
$_nvidiaIsReachable = (-not $NoTorchMode) -and
((-not $_pinLeafNow) -or (Test-CudaFamilyLeaf $_pinLeafNow))
$_nvidiaPreR450 = ($null -ne $script:NvidiaPresenceDriverRelease -and
@@ -8448,9 +7506,7 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
substep "NVIDIA GPU found on the PCI bus but the installed PyTorch is a $installedTorchTag build that sees no GPU -- running the dependency pass" "Cyan"
$SkipPythonDeps = $false
}
- # The installed wheel as well as the scan: an explicit xpu pin on a mixed NVIDIA + Intel box
- # ends up on XPU with $script:IsIntelXpu false, fast-pathing past the bitsandbytes floor and
- # the Triton replacement forever.
+ # An explicit xpu pin can leave IsIntelXpu false, so check the installed wheel too.
if ($SkipPythonDeps -and $_xpuIsReachable -and ($script:IsIntelXpu -or $installedTorchTag -eq "xpu")) {
$_xpuDepsCode = "import importlib.metadata as m; " +
"print('BNB=' + next((d.version for d in m.distributions() " +
@@ -8459,13 +7515,11 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
"if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), ''))"
$_xpuDeps = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_xpuDepsCode
if (-not $_xpuDeps.Ok) {
- # A probe that did not answer is not "current": one extra pass, as for an unparseable
- # version.
substep "Intel XPU dependencies could not be read -- running the dependency pass" "Cyan"
$SkipPythonDeps = $false
} else {
$_bnbVer = if ($_xpuDeps.Output -match '(?m)^BNB=(\S+)\s*$') { $Matches[1] } else { "" }
- # Unreadable is stale, the safe direction. Trailing suffixes (0.51.0.dev0) are dropped.
+ # Unreadable is stale, the safe direction.
$_bnbNum = ($_bnbVer -replace '[^0-9.].*$', '').TrimEnd('.')
$_bnbStale = $true
if ($_bnbNum -match '^\d+\.\d+') {
@@ -8486,7 +7540,6 @@ $_PkgName = if ($env:STUDIO_PACKAGE_NAME) { $env:STUDIO_PACKAGE_NAME } else { "u
$SkipPythonDeps = $false
if ($env:SKIP_STUDIO_BASE -ne "1" -and $env:STUDIO_LOCAL_INSTALL -ne "1") {
- # Only check when NOT called from install.ps1 (which just installed the package)
$_InstalledVersionProbeExit = 1
$InstalledVer = try {
$_installedVersionOutput = & python -c "
@@ -8511,22 +7564,17 @@ sys.exit(2 if conflict else (0 if version else 1))
} elseif ($InstalledVer -and $LatestVer -and ($InstalledVer -eq $LatestVer)) {
step "python" "$_PkgName $InstalledVer is up to date"
$SkipPythonDeps = $true
- # An interrupted install leaves $_PkgName current while studio.txt never finished, so update
- # and the Repair button no-op on a venv that cannot boot.
+ # An interrupted install leaves the package current but studio.txt unfinished.
$_studioInstallIncomplete = -not (Test-StudioInstallVerified)
if ($_studioInstallIncomplete) {
substep "studio install incomplete -- forcing dependency pass to repair..." "Cyan"
$SkipPythonDeps = $false
}
- # ...and every remaining escape, shared with the offline rule below.
Invoke-FastPathEscapes
} elseif ($InstalledVer -and $LatestVer) {
substep "$_PkgName $InstalledVer -> $LatestVer available, updating..."
} elseif (-not $LatestVer) {
- # PyPI unreachable: updating to be safe stays the default, since it is usually a blip.
- # UV_OFFLINE is not a blip, so a verified tree is kept instead, on the incomplete-install
- # guard's evidence and held to the up-to-date branch's escapes (it can still be below the
- # floor).
+ # PyPI unreachable updates anyway, but UV_OFFLINE keeps a verified tree.
if ($InstalledVer -and (Test-UvOfflineRequested) -and (Test-StudioInstallVerified)) {
substep "PyPI is unreachable and UV_OFFLINE is set -- keeping the verified install"
$SkipPythonDeps = $true
@@ -8537,20 +7585,11 @@ sys.exit(2 if conflict else (0 if version else 1))
}
}
- # A current package can still have CPU torch on an AMD host. After the chain and gated on the
- # flag, as setup.sh keeps it, so it covers the UV_OFFLINE branch too.
+ # After the chain, as setup.sh keeps it, so it also covers the UV_OFFLINE branch.
if ($SkipPythonDeps) {
- # ...but not if an AMD GPU is present and installed PyTorch is CPU-only
- # (host predates ROCm-wheel support, or GPU added later): the fast "up to
- # date" path would leave the user on CPU torch with Train/Export disabled.
- # Force the dependency pass so the ROCm wheels get installed.
+ # A current package can still have CPU torch on an AMD host; force the pass for ROCm wheels.
if ($script:ROCmGfxArch) {
- # Bounded, like every other torch probe here and for the reason the disk-based ROCm
- # rescue above exists: on a faulted HIP runtime `import torch` never comes back, and
- # the rescue now KEEPS that venv rather than deleting it, so this is the first
- # `import torch` such a host reaches and an unbounded call would hang setup forever.
- # A probe that does not answer keeps $_torchIsCpu true, the same safe direction as
- # before: one dependency pass, never a silent skip.
+ # Bounded: on a faulted HIP runtime the import never returns. No answer forces one pass.
$_rocmTorchProbe = Invoke-BoundedPythonProbe -PythonExe "python" `
-Code "import torch, sys; sys.exit(0 if torch.cuda.is_available() else 1)"
$_torchIsCpu = -not $_rocmTorchProbe.Ok
@@ -8572,53 +7611,20 @@ sys.exit(2 if conflict else (0 if version else 1))
}
}
-# if (-not $IsPipInstall) {
-# # Running from repo: copy requirements and do editable install
-# $RepoRoot = (Resolve-Path (Join-Path $ScriptDir "..\..")).Path
-# $ReqsSrc = Join-Path $RepoRoot "backend\requirements"
-# $ReqsDst = Join-Path $PackageDir "requirements"
-# if (-not (Test-Path $ReqsDst)) { New-Item -ItemType Directory -Path $ReqsDst | Out-Null }
-# Copy-Item (Join-Path $ReqsSrc "*.txt") $ReqsDst -Force
-
-# Write-Host " Installing CLI entry point..." -ForegroundColor Cyan
-# pip install -e $RepoRoot 2>&1 | Out-Null
-# } else {
-# # Running from pip install: the package is in system Python but not in
-# # the fresh .venv. Install it so run_install() can find its modules
-# # and bundled requirements files.
-# Write-Host " Installing package into venv..." -ForegroundColor Cyan
-# pip install unsloth 2>&1 | Out-Null
-# }
-
-# A torch-index pin change repairs in place: force the dependency pass so the torch install
-# below force-reinstalls from the new pin (else the fast path keeps the old wheel).
-# A torch that will not import needs the same pass for the same reason, and it is the only
-# thing that can act on it: every --force-reinstall that reads the flag lives INSIDE this
-# block, so on a current core package with a valid manifest the fast path announced a
-# reinstall it then skipped, and setup exited successfully over an unusable wheel.
+# A pin change or a torch that will not import needs the pass: every --force-reinstall lives inside it.
if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {
$SkipPythonDeps = $false
}
-# An upgrade has to take the old value away, not merely stop writing a new one: every setup
-# before the refusal existed wrote an apostrophe-named account's contained path to the USER
-# environment, so it is already there for exactly the account the refusal exists for. The backend
-# refuses such a value too, but only for its own process; this is what stops it being handed to
-# everything else on the account.
-#
-# Outside the dependency block on purpose, since a current core package and a verified UV_OFFLINE
-# tree both skip that block, and clearing needs none of its work. Only a value the builders
-# cannot read AND that this installer wrote is cleared.
+# Remove the unparseable (apostrophe) torch cache path older setups wrote to the USER environment.
+# Outside the dependency block, which the fast paths skip.
function Test-UnparseableManagedTorchCache {
param([string]$Value, [string]$Managed)
if (-not $Value) { return $false }
$trimmed = $Value.Trim().Replace('/', '\').TrimEnd('\')
- # Shape first: a path the builders CAN read is working for somebody and is never touched.
+ # A path the builders CAN read is never touched.
if ($trimmed -notmatch '[\s'']') { return $false }
- # Then provenance. The only unparseable value any setup has ever persisted is the contained
- # path this same run computes, so anything else was configured by something we did not
- # install and is not ours to delete: an older Torch quoted its compiler arguments, and such a
- # value can still be working there.
+ # Only clear the exact value this installer would have written.
return $trimmed -ieq $Managed.Trim().Replace('/', '\').TrimEnd('\')
}
@@ -8641,11 +7647,10 @@ if (-not $SkipPythonDeps) {
if (-not ($env:STUDIO_LOCAL_INSTALL -eq '1' -and (Test-Path -LiteralPath (Join-Path $VenvDir 'Scripts\python.exe') -PathType Leaf))) { Invoke-MirrorFallback }
-# Recover what a fresh shell lost, BEFORE the manifest is dropped below: recovery reads that file.
+# Before the manifest is dropped below: recovery reads that file.
$WinArm64Venv = Test-WinArm64Venv
-# Read BEFORE the re-export overwrites it: the flags install.ps1 left describe THAT index.
+# Read before the re-export overwrites it.
$_woaHandoffIndex = if ($env:UNSLOTH_WOA_SELECTED_TORCH_INDEX) { $env:UNSLOTH_WOA_SELECTED_TORCH_INDEX.Trim().TrimEnd('/') } else { "" }
-# The index install.ps1 probed, or the CUDA branch takes a driver-derived family with no wheel.
$WinArm64TorchIndexUrl = if ($WinArm64Venv -and $env:UNSLOTH_WOA_TORCH_INDEX_URL) {
$env:UNSLOTH_WOA_TORCH_INDEX_URL.Trim().TrimEnd('/')
} elseif ($WinArm64Venv -and $env:UNSLOTH_WOA_SELECTED_TORCH_INDEX) {
@@ -8654,10 +7659,10 @@ $WinArm64TorchIndexUrl = if ($WinArm64Venv -and $env:UNSLOTH_WOA_TORCH_INDEX_URL
$_woaFromManifest = Get-PersistedWoaTorchIndex -VenvPath $VenvDir
if ($_woaFromManifest) { $_woaFromManifest } else { Get-WoaTorchIndexMarker }
} else { "" }
-# Re-exported, not just held locally: the manifest rewrite reads it, so a fresh-shell update would erase the index for good. Either record opens the block: the WoA chain alone lost a mirror pin.
+# Re-exported: the manifest rewrite reads it, so a fresh-shell update would erase the index.
$_woaPinnedIndex = if ($WinArm64Venv) { Get-PinnedTorchIndexUrl } else { $null }
if ($WinArm64TorchIndexUrl -or $_woaPinnedIndex) {
- # RECORD the index the torch steps will USE, the generic pin when there is one, in BOTH records since the read chain prefers the manifest. An unpersistable pin is refused rather than left stale.
+ # Record the index the torch steps will USE in BOTH records; an unpersistable pin is refused.
$_woaMarkerIndex = $_woaPinnedIndex
if ($_woaMarkerIndex) { $_woaMarkerIndex = $_woaMarkerIndex.Trim().TrimEnd('/') }
else { $_woaMarkerIndex = $WinArm64TorchIndexUrl }
@@ -8667,17 +7672,14 @@ if ($WinArm64TorchIndexUrl -or $_woaPinnedIndex) {
Remove-Item Env:UNSLOTH_WOA_TORCH_PRERELEASE -ErrorAction SilentlyContinue
}
$env:UNSLOTH_WOA_SELECTED_TORCH_INDEX = $_woaMarkerIndex
- # Written BEFORE the manifest is dropped below, so an interrupted run still leaves this index.
+ # Before the manifest is dropped, so an interrupted run still leaves this index.
Save-WoaTorchIndexMarker -IndexUrl $_woaMarkerIndex
}
-# A terminating error after this point reaches neither Exit-SetupFailure nor the last statement, so the merged override file, which can carry the caller's credentials, would stay on disk. The trap removes it.
+# The merged override file can carry credentials; the trap removes it on a terminating error.
trap { Remove-WoaMergedOverrides; break }
Restore-WoaResolverEnvironment
-# install_python_stack.py drops the manifest before its own dependency pass, but
-# pip, torch and triton are replaced first here. Drop it now so a run killed in
-# those leaves the venv marked half-built, not behind a marker that verifies.
-# remove_manifest parks the file, so the dependency pass can still read the last completed pass.
+# Drop the manifest now: pip, torch and triton are replaced before the dependency pass.
$_ManifestDropped = $true
try {
& python -c "
@@ -8703,22 +7705,9 @@ if ($script:UnslothVerbose) {
Fast-Install --upgrade pip | Out-Null
}
-# The default Windows PyPI torch wheel is CPU-only; CUDA-index wheels bundle their own runtime.
-
-# Triton/inductor filenames are long and can hit Windows MAX_PATH (260). With long
-# paths on, cache under Unsloth home; else use a short drive-root dir for headroom.
-#
-# Persisted to the USER environment below, so every later Studio process inherits it and
-# _setup_cache_env's fill-if-unset default never applies on Windows: it has to name the
-# directory the resolver would have chosen, or the containment does not happen here at all.
-#
-# Two things outrank that. Long paths off keeps the short drive-root directory, since Inductor's
-# filenames hit MAX_PATH and a contained cache that cannot be written is worse than an
-# uncontained one. And whitespace or an apostrophe is refused exactly as
-# storage_roots.toolchain_path_unparseable refuses it, "C:\Users\First Last" and
-# "C:\Users\O'Brien" both being ordinary account names. The other two characters that predicate
-# rejects cannot arise here: a double quote is illegal in an NTFS name, and a backslash is the
-# separator, which cpp_builder rewrites to "/" before it builds the command.
+# Triton/inductor paths can exceed MAX_PATH (260): use the Unsloth home with long paths on,
+# else a short drive-root dir. Persisted to USER env, so it must match the resolver's choice.
+# Whitespace or an apostrophe is refused as storage_roots.toolchain_path_unparseable does.
$TorchCacheDir = $null
$TorchCacheUnparseable = $false
if ($StageRoot) {
@@ -8728,17 +7717,11 @@ if ($StageRoot) {
if ($candidate -notmatch '[\s'']') {
$TorchCacheDir = $candidate
} elseif ($candidate -notmatch '\s') {
- # Apostrophe only, which is the population this change added. A spaced path keeps
- # falling through to the drive-root directory it has always used.
+ # Apostrophe only; a spaced path keeps the drive-root dir it always used.
$TorchCacheUnparseable = $true
}
}
-# C:\tc is shared and predictable at a drive root, where the default ACL lets any account
-# create, so persisting it for a NEW population would hand an O'Brien account an Inductor cache
-# another local user could have made first. The widened refusal publishes nothing and leaves the
-# choice to storage_roots, which puts it under the per-account %LOCALAPPDATA%\Temp or declines.
-# The pre-existing triggers, long paths off and a spaced path, keep the drive-root directory
-# they have always used: that is not this change's to move.
+# C:\tc is predictable and creatable by any account, so never publish it for the apostrophe case.
if (-not $TorchCacheDir -and -not $TorchCacheUnparseable) {
$TorchCacheDir = "C:\tc"
}
@@ -8756,8 +7739,7 @@ if ($TorchCacheDir) {
$PinnedTorchIndexUrl = Get-PinnedTorchIndexUrl
$TorchIndexPinned = [bool]$PinnedTorchIndexUrl
-# An inconclusive XPU probe keeps the wheel, so keep its dependency route too.
-# Only a definitive no-device answer permits the presence-only CUDA conversion.
+# Only a definitive no-device XPU answer permits the presence-only CUDA conversion.
if (-not $TorchIndexPinned -and $script:NvidiaPresenceOnly -and $installedTorchTag -eq "xpu" -and
-not (Test-NvidiaPresenceStaleGpuWheel -InstalledTag $installedTorchTag -PythonExe (Join-Path $VenvDir "Scripts\python.exe"))) {
$script:PreservedXpuVenv = $true
@@ -8765,20 +7747,10 @@ if (-not $TorchIndexPinned -and $script:NvidiaPresenceOnly -and $installedTorchT
if ($PinnedTorchIndexUrl) {
$CuTag = Get-TorchIndexLeaf $PinnedTorchIndexUrl
} elseif ($script:PreservedXpuVenv) {
- # The stale check kept an installed +xpu venv rather than wiping it, which a hybrid
- # NVIDIA + Arc host reaches. Ahead of the NVIDIA arm deliberately: converting halfway leaves
- # +xpu torch under triton-windows and no XPU index to swap it back. install.ps1 converts.
+ # Kept +xpu venv on hybrid NVIDIA+Arc: stay on xpu ahead of the NVIDIA arm. install.ps1 converts.
$CuTag = "xpu"
} elseif ($script:PreservedInstallerTorchTag) {
- # The stale check kept the GPU wheel install.ps1 placed here minutes ago. That decision has to
- # reach the install arms below or it is undone there: the AMD arm force-reinstalls
- # unconditionally and the XPU arm whenever the installed tag is not xpu, so neither is held off
- # by $script:PinChangedForceReinstall staying false. Selecting the family already installed
- # keeps both out of the way -- a cu* tag skips the AMD reroute below (it needs $CuTag -eq
- # "cpu") and the XPU arm (it needs "xpu") and lands on the CUDA arm, which forces nothing; a
- # kept +rocm venv reads as "cpu" here and lands on the CPU arm, whose bare torch range a +rocm
- # build already satisfies. The +xpu case is the branch above. Behind the pin check, like every
- # other arm: an explicit pin repairs in place before the guard runs anyway.
+ # Select the family the stale check kept, so the AMD and XPU arms do not force-reinstall over it.
$CuTag = if (Test-CudaFamilyLeaf $script:PreservedInstallerTorchTag) { $script:PreservedInstallerTorchTag } else { "cpu" }
} elseif ($HasNvidiaSmi) {
$CuTag = Get-PytorchCudaTag
@@ -8795,7 +7767,7 @@ if ($PinnedTorchIndexUrl) {
}
if (-not $CuTag -and -not (Test-CudaFamilyLeaf $installedTorchTag) -and
$script:NvidiaPresenceCudaFloor) {
- # Only for a fresh install: the floor is a FLOOR, and an existing cu* venv must not be pulled back (#9255).
+ # Fresh installs only: an existing cu* venv must not be pulled back to the floor.
$floorMajor = [int]$script:NvidiaPresenceCudaFloor[0]
$floorMinor = [int]$script:NvidiaPresenceCudaFloor[1]
# Same pre-Turing cap as install.ps1: unknown capability stops at cu126.
@@ -8807,28 +7779,23 @@ if ($PinnedTorchIndexUrl) {
substep "nvidia-smi and the NVIDIA driver library are both unavailable; the display driver supports at least CUDA $floorMajor.$floorMinor, installing torch $CuTag" "Yellow"
}
if (-not $CuTag) {
- # Unknown driver version: the installed family, else the widest wheel.
$CuTag = if (Test-CudaFamilyLeaf $installedTorchTag) { $installedTorchTag } else { "cu126" }
substep "could not read the CUDA driver version; installing torch $CuTag" "Yellow"
}
} elseif ($script:IsIntelXpu) {
- # XPU (SYCL) wheels ship under the /xpu leaf, so $TorchInstallIndexUrl below resolves to
- # <mirror>/xpu. A pin above still wins; the AMD reroute below needs $CuTag -eq "cpu".
+ # XPU wheels ship under the /xpu leaf, so TorchInstallIndexUrl resolves to mirror/xpu.
$CuTag = "xpu"
} else {
$CuTag = "cpu"
}
-# AMD's arch-specific pip index (repo.amd.com/rocm/whl/{arch}/); wheels bundle their runtime.
$ROCmGfxArch = $script:ROCmGfxArch
$ROCmIndexUrl = $null
$script:ROCmMultiArch = $false
# Also on a name-inferred gfx: the wheels bundle the runtime, so no HIP SDK is needed.
if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $CuTag -eq "cpu") {
$amdIndexBase = if ($env:UNSLOTH_ROCM_WINDOWS_MIRROR) { $env:UNSLOTH_ROCM_WINDOWS_MIRROR.TrimEnd('/') } else { "https://repo.amd.com/rocm/whl" }
- # gfx120X, Strix, gfx103X, gfx110X: null _grouped_mm kernel on torch <2.11.0 (unslothai/unsloth#11814).
- # Mirrors the $torchFloorMap in install.ps1 so both installers enforce
- # the same floor and ceiling when pulling from AMD's per-arch index.
+ # gfx120X, Strix, gfx103X, gfx110X: null _grouped_mm on torch <2.11.0; mirrors install.ps1 floor.
$torchFloorMap = @{
"gfx1201" = "torch>=2.11.0,<2.12.0"; "gfx1200" = "torch>=2.11.0,<2.12.0"
"gfx1151" = "torch>=2.11.0,<2.12.0"; "gfx1150" = "torch>=2.11.0,<2.12.0"
@@ -8840,7 +7807,7 @@ if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $CuTag -eq "cpu
"gfx1101" = "torch>=2.11.0,<2.12.0"; "gfx1102" = "torch>=2.11.0,<2.12.0"
"gfx1103" = "torch>=2.11.0,<2.12.0"
}
- # Companions bounded to the torch ceiling for a consistent trio (AMD publishes each alone).
+ # Companions bounded to the torch ceiling for a consistent trio.
$torchvisionFloorMap = @{
"gfx1201" = "torchvision>=0.26.0,<0.27.0"; "gfx1200" = "torchvision>=0.26.0,<0.27.0"
"gfx1151" = "torchvision>=0.26.0,<0.27.0"; "gfx1150" = "torchvision>=0.26.0,<0.27.0"
@@ -8867,7 +7834,6 @@ if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $CuTag -eq "cpu
$ROCmTorchSpec = if ($ROCmGfxArch -and $torchFloorMap.ContainsKey($ROCmGfxArch)) { $torchFloorMap[$ROCmGfxArch] } else { "torch" }
$ROCmVisionSpec = if ($ROCmGfxArch -and $torchvisionFloorMap.ContainsKey($ROCmGfxArch)) { $torchvisionFloorMap[$ROCmGfxArch] } else { "torchvision" }
$ROCmAudioSpec = if ($ROCmGfxArch -and $torchaudioFloorMap.ContainsKey($ROCmGfxArch)) { $torchaudioFloorMap[$ROCmGfxArch] } else { "torchaudio" }
- # A family-layout mirror (and no multi-arch mirror) keeps the family route for arches that have one.
$_familyMirrorPinned = [bool]($env:UNSLOTH_ROCM_WINDOWS_MIRROR) -and -not [bool]($env:UNSLOTH_ROCM_WINDOWS_MULTIARCH_MIRROR)
$script:ROCmMultiArch = [bool]($ROCmGfxArch -and $multiArchGfx -contains $ROCmGfxArch -and -not ($archFamily -and $_familyMirrorPinned))
if ($script:ROCmMultiArch) {
@@ -8891,11 +7857,11 @@ if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $CuTag -eq "cpu
if ($TorchIndexPinned -and -not $ROCmIndexUrl -and $PinnedTorchIndexUrl) {
$_pinLeaf = Get-TorchIndexLeaf $PinnedTorchIndexUrl
$_pinRocm211 = $false
- # Anchor ($) so a suffixed custom leaf (rocm7.2-private) falls through to verbatim install.
+ # Anchored so a suffixed custom leaf (rocm7.2-private) installs verbatim.
if ($_pinLeaf -match '^rocm(\d+)\.(\d+)$') {
$_pinRocm211 = Test-RocmKnown211Version -Major ([int]$Matches[1]) -Minor ([int]$Matches[2])
}
- # Reuse Test-RocmGfx211Leaf so this allowlist and the stale-venv check cannot diverge.
+ # Reuse Test-RocmGfx211Leaf so this and the stale-venv check cannot diverge.
$_pinGfx211 = Test-RocmGfx211Leaf $_pinLeaf
if ($_pinGfx211 -or $_pinRocm211) {
$ROCmIndexUrl = $PinnedTorchIndexUrl
@@ -8916,15 +7882,13 @@ $PyTorchWhlBase = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR
# On a ROCm-install failure the fallback uses the CPU index, not the ROCm pin.
$TorchInstallIndexUrl = if ($ROCmIndexUrl) { "$PyTorchWhlBase/cpu" } elseif ($PinnedTorchIndexUrl) { $PinnedTorchIndexUrl } else { "$PyTorchWhlBase/$CuTag" }
-# Declared outside the guard: the bitsandbytes and Triton passes read it from outside too, and
-# no-torch mode never reaches the assignment below.
+# Declared outside the guard: later passes read it and no-torch mode never assigns it.
$XpuIndexUrl = $null
$_effectiveTorchIndexUrl = $TorchInstallIndexUrl
if (-not $NoTorchMode) {
-# Windows on ARM has win_arm64 torch and torchvision wheels but no torchaudio on any index,
-# Absent install.ps1's answer assume no torchaudio: an absent wheel makes the trio unresolvable. $WinArm64EffectiveTorchIndexUrl is which index the torch steps ACTUALLY use.
+# Windows on ARM has no torchaudio wheel on any index; absent install.ps1's answer, assume none.
$WinArm64EffectiveTorchIndexUrl = if ($PinnedTorchIndexUrl) { ([string]$PinnedTorchIndexUrl).Trim().TrimEnd('/') }
elseif ($WinArm64TorchIndexUrl) { $WinArm64TorchIndexUrl }
else { "" }
@@ -8933,7 +7897,7 @@ $WinArm64HandoffApplies = [bool]($WinArm64EffectiveTorchIndexUrl -and $_woaHando
$WinArm64NoAudio = $WinArm64Venv -and -not ($WinArm64HandoffApplies -and $env:UNSLOTH_WOA_HAS_TORCHAUDIO -eq "1")
if ($WinArm64NoAudio) { substep "windows on arm: skipping torchaudio (no win_arm64 wheel on this index)" }
elseif ($WinArm64Venv) { substep "windows on arm: this index publishes torchaudio; keeping it in the torch trio" }
-# The ceilings below are for x64 wheels; every win_arm64 build sits above them, so floors only.
+# The ceilings below are for x64 wheels; win_arm64 builds sit above them, so floors only.
$WinArm64TorchSpec = "torch>=2.4"
$WinArm64VisionSpec = "torchvision>=0.19"
$WinArm64AudioSpec = "torchaudio>=2.4"
@@ -8949,7 +7913,6 @@ if ($WinArm64Venv -and $WinArm64EffectiveTorchIndexUrl) {
if ($_woaTorchV) {
$WinArm64TorchSpec = "torch==$_woaTorchV"
$_woaVisionV = Get-WoaCudaWheelVersionParity -IndexUrl $WinArm64EffectiveTorchIndexUrl -PyTag $_woaPyTag -AbiTag $_woaAbi -Project "torchvision" -PairWith $_woaTorchV
- # As install.ps1 selects: the newest COMPLETE pair, searched a few torch versions deep, before falling back to what is installed.
$_woaBacktracks = 0
while (-not $_woaVisionV -and $_woaBacktracks -lt 5) {
$_woaOlderTorch = Get-WoaCudaWheelVersionParity -IndexUrl $WinArm64EffectiveTorchIndexUrl -PyTag $_woaPyTag -AbiTag $_woaAbi -Below $_woaTorchV
@@ -8963,7 +7926,7 @@ if ($WinArm64Venv -and $WinArm64EffectiveTorchIndexUrl) {
if ($_woaVisionV) {
$WinArm64VisionSpec = "torchvision==$_woaVisionV"
} else {
- # The venv already exists, so a lagging index keeps the installed pair rather than pinning a torch whose torchvision would resolve against a build it was not made for.
+ # Keep the installed pair rather than pin a torch whose torchvision would resolve wrong.
$_woaInstalledPair = ""
try {
$_woaInstalledPair = (& (Join-Path $VenvDir "Scripts\python.exe") -c "import importlib.metadata as m; print(m.version('torch') + '|' + m.version('torchvision'))" 2>$null | Out-String).Trim()
@@ -8981,7 +7944,6 @@ if ($WinArm64Venv -and $WinArm64EffectiveTorchIndexUrl) {
}
$_woaAudioV = Get-WoaCudaWheelVersionParity -IndexUrl $WinArm64EffectiveTorchIndexUrl -PyTag $_woaPyTag -AbiTag $_woaAbi -Project "torchaudio" -PairWith $_woaTorchV
if ($_woaAudioV) { $WinArm64AudioSpec = "torchaudio==$_woaAudioV" }
- # This probe is the same one install.ps1 ran, so it decides: a fresh shell has no handoff, and the handoff alone would drop an audio wheel the index does pair with this torch.
$_woaProbeHasAudio = [bool]($_woaAudioV -and (Test-WoaAudioMatchesTorchParity -TorchVersion $_woaTorchV -AudioVersion $_woaAudioV))
if ($WinArm64NoAudio -eq $_woaProbeHasAudio) {
$WinArm64NoAudio = -not $_woaProbeHasAudio
@@ -8992,7 +7954,7 @@ if ($WinArm64Venv -and $WinArm64EffectiveTorchIndexUrl) {
}
}
}
-# <3.7 everywhere except Windows on ARM, whose first win_arm64 wheel is 3.8.0.post28.
+# win_arm64's first triton-windows wheel is 3.8.0.post28.
$_tritonSpec = if ($WinArm64Venv) { "triton-windows>=3.8.0.post28" } else { "triton-windows<3.7" }
# triton-windows follows the Triton each torch pins: 2.12 and 2.13 -> 3.7 (2.12.0 -> 3.7.0), 2.14 -> 3.8, older keeps <3.7.
function Get-TritonWindowsSpec {
@@ -9010,7 +7972,7 @@ function Get-TritonWindowsSpec {
# 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" }
- # Stop rather than guess: Fast-Install sets UV_NO_CONFIG and scrubs UV_* whenever --index-url is passed, so an unreadable uv policy would leave the trio index as the only source here.
+ # Fast-Install scrubs UV_* with --index-url, so an unreadable uv policy would leave only the trio index.
if ($_woaResolver -eq "uv" -and (Test-WoaUvIndexPolicyUnreadable)) {
$_woaCfgPath = [string](Get-WoaUvConfigIndexPolicy).UnreadablePath
if (-not $_woaCfgPath) { $_woaCfgPath = "your uv configuration" }
@@ -9027,7 +7989,7 @@ $WinArm64IndexArgs = if ($WinArm64Venv) {
Exit-SetupFailure "Unreadable uv index policy in $_woaCfgPath"
}
$_woaIndexArgs = @("--index-strategy", "unsafe-best-match") + @(Get-WoaDependencyIndexArgs -Resolver $_woaResolver)
- # Fast-Install clears UV_FIND_LINKS and PIP_FIND_LINKS whenever --index-url is given, so the staged wheelhouse is named on the command line. Only when it exists: uv fails on a missing directory.
+ # Fast-Install clears *_FIND_LINKS with --index-url; uv fails on a missing directory.
$_woaWheels = Join-Path (Join-Path $StudioHome "woa") "wheels"
if (Test-Path -LiteralPath $_woaWheels -PathType Container) {
$_woaIndexArgs += @("--find-links", (Get-UvSafePath $_woaWheels))
@@ -9047,7 +8009,6 @@ if ($ROCmIndexUrl) {
} elseif ($ROCmTorchSpec -ne "torch") {
substep " enforcing $ROCmTorchSpec $ROCmVisionSpec $ROCmAudioSpec (known _grouped_mm bug in older wheels)" "Cyan"
}
- # Release preservation: keep UNSLOTH_KEPT_TORCH unless it conflicts with a >=2.11 floor.
$_rocmKeptActive = $false
$_rocmOrigTorch = $ROCmTorchSpec; $_rocmOrigVision = $ROCmVisionSpec; $_rocmOrigAudio = $ROCmAudioSpec
if (-not $script:ROCmMultiArch -and $env:UNSLOTH_KEPT_TORCH -match '^\d+\.\d+(\.\d+)?$') {
@@ -9059,18 +8020,13 @@ if ($ROCmIndexUrl) {
$_rocmKeptActive = $true
}
}
- # As the XPU and CPU arms: force only when the resident torch is not this family, the pin moved
- # or the import failed. Unconditional --force-reinstall re-resolved the trio every update.
+ # Force only on a family change, pin move or failed import; always forcing re-resolved every update.
$rocmForce = @()
- # The same escape hatch the Python pass honours, in the same spellings: a skip nobody can turn
- # off is a bug nobody can work around, and this arm is reached before the pass runs.
if (@("1", "true", "yes", "on") -contains "$($env:UNSLOTH_STUDIO_FULL_DEPS)".Trim().ToLowerInvariant()) { $rocmForce = @("--force-reinstall") }
if ($installedTorchTag -ne "rocm") { $rocmForce = @("--force-reinstall") }
if ($script:PinChangedForceReinstall) { $rocmForce = @("--force-reinstall") }
if ($script:TorchImportDefinitivelyFailed) { $rocmForce = @("--force-reinstall") }
- # +rocm names the family, not the architecture: a changed UNSLOTH_ROCM_GFX_ARCH or replaced
- # card moves $ROCmIndexUrl while the trio still satisfies its pins, so the index it came from
- # is recorded. Another index, or no record, takes the reinstall.
+ # +rocm names the family, not the arch, so record the index the trio came from.
$script:RocmIndexRecord = Join-Path $VenvDir ".unsloth-rocm-index"
$_rocmIndexIdentity = Get-IndexIdentity $ROCmIndexUrl
$_recordedRocmIndex = ""
@@ -9086,15 +8042,8 @@ if ($ROCmIndexUrl) {
$rocmForce = @("--force-reinstall")
}
if ($installedTorchTag -eq "rocm" -and $rocmForce.Count -eq 0 -and $VenvPyExe -and (Test-Path -LiteralPath $VenvPyExe)) {
- # torch alone names the family: a companion re-resolved from PyPI (+cpu, +cuNNN or no
- # tag) satisfies its pin without linking ROCm, and the pinned install leaves it. AMD tags
- # all three +rocm. Payload too, since a dist-info without its package or a RECORD row gone
- # or resized is damage the pinned install would not repair; rows, not Distribution.files
- # (3.13 filters to existing files), bytecode left out. No answer forces the trio. Only the
- # companions the trio installs: Windows on ARM has no torchaudio to repair.
- # The ROCm release is compared too: +rocm6.2 beside a +rocm6.4 torch still satisfies its
- # pin. Numeric versions only, so the community wheels tagged with a bare git hash keep the
- # fast path rather than reinstalling on every update.
+ # torch alone names the family: companions from PyPI satisfy their pins without ROCm. Also check
+ # payload (RECORD rows) and ROCm release. No answer forces the trio.
$_companionNames = if ($WinArm64NoAudio) { "('torchvision',)" } else { "('torchvision', 'torchaudio')" }
$_companionProbe = Invoke-BoundedPythonProbe -PythonExe $VenvPyExe -Code "import csv, io, re, importlib.util as u, importlib.metadata as m, os`ndef rocmver(s):`n hit = re.search(r'rocm(\d+(?:\.\d+)*)', s.lower())`n return hit.group(1) if hit else ''`ntry:`n torchrocm = rocmver(m.distribution('torch').version)`nexcept m.PackageNotFoundError:`n torchrocm = ''`nout = []`nfor n in $($_companionNames):`n try:`n d = m.distribution(n)`n except m.PackageNotFoundError:`n continue`n v = d.version`n if u.find_spec(n) is None:`n out.append(n + '==' + v + ' (payload missing)')`n continue`n rec = d.read_text('RECORD')`n damaged = not rec`n for row in csv.reader(io.StringIO(rec or '')):`n if damaged or len(row) < 3 or not row[0] or row[0].endswith('.pyc') or not row[2]:`n continue`n try:`n damaged = os.stat(d.locate_file(row[0])).st_size != int(row[2])`n except (OSError, ValueError):`n damaged = True`n if damaged:`n out.append(n + '==' + v + ' (payload damaged)')`n continue`n t = (v.split('+', 1) + [''])[1].lower()`n if not t or t.startswith('cpu') or t.startswith('cu') or t.startswith('xpu'):`n out.append(n + '==' + v)`n elif torchrocm and rocmver(t) and rocmver(t) != torchrocm:`n out.append(n + '==' + v + ' (rocm' + rocmver(t) + ' beside torch rocm' + torchrocm + ')')`nprint(' '.join(out))"
$_companionMismatch = if ($_companionProbe.Ok) { $_companionProbe.Output.Trim() } else { "probe did not answer" }
@@ -9104,7 +8053,7 @@ if ($ROCmIndexUrl) {
}
}
while ($true) {
- # Built here, not in the verbose branch (a splat assigned there is unset on the other path).
+ # A splat assigned only in the verbose branch is unset on the other path.
$_rocmTrio = @($ROCmTorchSpec, $ROCmVisionSpec, $ROCmAudioSpec)
if ($WinArm64NoAudio -or -not $ROCmAudioSpec) { $_rocmTrio = @($ROCmTorchSpec, $ROCmVisionSpec) }
if ($script:UnslothVerbose) {
@@ -9127,9 +8076,7 @@ if ($ROCmIndexUrl) {
$ROCmIndexUrl = $null
$ROCmCpuFallback = $true
} else {
- # Tell install_python_stack.py to skip the probe and the manual-install warning.
$env:UNSLOTH_ROCM_TORCH_INSTALLED = "1"
- # Recorded after the trio landed (see $rocmForce).
try {
if ($script:RocmIndexRecord) { Set-Content -LiteralPath $script:RocmIndexRecord -Value (Get-IndexIdentity $ROCmIndexUrl) -Encoding ascii -NoNewline }
} catch { }
@@ -9138,28 +8085,19 @@ if ($ROCmIndexUrl) {
}
# ── Intel XPU (SYCL) ─────────────────────────────────────────────────────────
-# Its own index leaf, so it must not fall into the CUDA branch below ("CUDA support (xpu)").
-# Reached on an Arc / Data Center host and on an explicit xpu pin.
+# Intel XPU has its own index leaf and must not fall into the CUDA branch.
$XpuCpuFallback = $false
if (-not $ROCmIndexUrl -and $CuTag -eq "xpu") { $XpuIndexUrl = $TorchInstallIndexUrl }
if ($XpuIndexUrl) {
substep "installing PyTorch (Intel XPU)..."
- # Bounded like install.ps1's XPU install: the xpu index serves torch past what Unsloth
- # supports. The floor is 2.6, not the usual 2.4 -- unsloth/models/_utils.py raises at import
- # for an XPU device below that, and an older wheel would be kept as satisfying the range.
+ # unsloth raises at import for XPU below torch 2.6, so the floor is 2.6.
$_xpuTrio = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0", "torchaudio>=2.6,<2.11.0")
if ($WinArm64NoAudio) { $_xpuTrio = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0") }
- # Gated like $cpuForce below, NOT unconditional: install.ps1 already installed the XPU trio
- # before calling setup, so forcing every pass re-downloads GB there and on every update.
- # Force only on a flavor change -- a CPU (or cu*/rocm) wheel satisfies the range, so uv would
- # keep it and never migrate. An unreadable flavor forces too, the safe direction.
+ # Force only on a flavor change: install.ps1 already installed the XPU trio.
$xpuForce = @()
if ($installedTorchTag -ne "xpu") { $xpuForce = @("--force-reinstall") }
- # A changed pin repairs in place, so the existing +xpu wheel must be replaced too.
if ($script:PinChangedForceReinstall) { $xpuForce = @("--force-reinstall") }
- # And a +xpu wheel that no longer imports: its on-disk tag is still "xpu", so the check
- # above sees no flavour change and the range is satisfied, which leaves the resolver
- # holding the broken wheel and the run writing a completion manifest over it.
+ # A +xpu wheel that no longer imports still satisfies the range.
if ($script:TorchImportDefinitivelyFailed) { $xpuForce = @("--force-reinstall") }
if ($script:UnslothVerbose) {
Fast-Install @_xpuTrio @xpuForce --index-url $XpuIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host
@@ -9170,8 +8108,6 @@ if ($XpuIndexUrl) {
$torchInstallExit = $LASTEXITCODE
}
if ($torchInstallExit -ne 0) {
- # Transient XPU-index failure: fall back to a CPU base rather than leaving no torch
- # (same shape as ROCm above).
Write-StudioLine "[WARN] Intel XPU PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow
Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Yellow
$XpuIndexUrl = $null
@@ -9179,40 +8115,33 @@ if ($XpuIndexUrl) {
$TorchInstallIndexUrl = "$PyTorchWhlBase/cpu"
} else {
substep "GPU XPU PyTorch installed -- training and GPU inference will use the GPU" "Cyan"
- # The wheel being in place does not mean the runtime initializes -- see the helper.
Assert-XpuRuntimeReady -PythonExe "python" | Out-Null
}
}
if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback -or $XpuCpuFallback)) {
substep "installing PyTorch (CPU-only)..."
- # force-reinstall after a ROCm fallback; build the array directly, as an @splat enumerates chars.
+ # Build the array directly: an @splat of a string enumerates chars.
$cpuForce = @()
if ($ROCmCpuFallback) { $cpuForce = @("--force-reinstall") }
- # Same after an Intel XPU fallback: a partial +xpu torch satisfies the CPU torch>= range.
+ # A partial +xpu torch satisfies the CPU torch>= range.
if ($XpuCpuFallback) { $cpuForce = @("--force-reinstall") }
- # --force-reinstall on a pin change: a stale +cu / +rocm wheel still satisfies the CPU
- # torch>= range, so uv would keep it and only swap companions.
+ # A stale +cu / +rocm wheel still satisfies the CPU torch>= range.
if ($script:PinChangedForceReinstall) { $cpuForce = @("--force-reinstall") }
- # Same for a wheel that no longer imports. Nothing else here distinguishes it: the tag is
- # rescued from disk and still reads "cpu", so the range is satisfied and it is kept.
if ($script:TorchImportDefinitivelyFailed) { $cpuForce = @("--force-reinstall") }
if ($script:NvidiaPreR450CpuFallback) { $cpuForce = @("--force-reinstall") }
- # A PINNED cpu index installs the bounded trio (parity with _CPU_TORCH_PKG_SPEC): the /cpu
- # index serves newer torch and _ensure_cpu_torch keeps any CPU build. Unpinned keeps the bare trio.
+ # A pinned cpu index installs the bounded trio (parity with _CPU_TORCH_PKG_SPEC).
$cpuTorchSpec = "torch"; $cpuVisionSpec = "torchvision"; $cpuAudioSpec = "torchaudio"
if ($TorchIndexPinned) {
$cpuTorchSpec = "torch>=2.4,<2.12.0"
$cpuVisionSpec = "torchvision>=0.19,<0.27.0"
$cpuAudioSpec = "torchaudio>=2.4,<2.12.0"
}
- # Bound an XPU fallback too: this is not the plain CPU box the bare trio was preserved for.
if ($XpuCpuFallback) {
$cpuTorchSpec = "torch>=2.4,<2.12.0"
$cpuVisionSpec = "torchvision>=0.19,<0.27.0"
$cpuAudioSpec = "torchaudio>=2.4,<2.12.0"
}
- # Release preservation: the kept release resolves to the right cpu build off the /cpu index.
$_cpuKeptActive = $false
$_cpuOrigTorch = $cpuTorchSpec; $_cpuOrigVision = $cpuVisionSpec; $_cpuOrigAudio = $cpuAudioSpec
if ($env:UNSLOTH_KEPT_TORCH -match '^\d+\.\d+(\.\d+)?$') {
@@ -9247,21 +8176,18 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
} elseif (-not $ROCmIndexUrl -and -not $XpuIndexUrl) {
substep "installing PyTorch with CUDA support ($CuTag)..."
substep "(This download is ~2.8 GB -- may take a few minutes)"
- # PEP 440 ignores +cuXXX, so a cu126 -> cu128 change never applies without --force-reinstall.
+ # PEP 440 ignores +cuXXX, so a cu126 -> cu128 change needs --force-reinstall.
$cudaForce = @()
if ($script:PinChangedForceReinstall -or $script:TorchImportDefinitivelyFailed) {
$cudaForce = @("--force-reinstall")
}
- # The installed CPU wheel satisfies bare torch and the stale check reads unknown here, so force it.
if ($script:NvidiaPresenceOnly -and $installedTorchTag -eq "cpu") {
$cudaForce = @("--force-reinstall")
}
if (Test-NvidiaPresenceStaleGpuWheel -InstalledTag $installedTorchTag -PythonExe (Join-Path $VenvDir "Scripts\python.exe")) {
$cudaForce = @("--force-reinstall")
}
- # An unknown-leaf custom pin (/simple, /current) routes here with $CuTag as that leaf. Bound
- # the trio like the fresh custom-pin paths so a mirror can't pull an ABI-newer companion
- # against the capped torch. Known cu* leaves keep bare specs.
+ # Unknown-leaf custom pins: bound the trio so a mirror cannot pull an ABI-newer companion.
$cudaTorchSpec = "torch"
$cudaVisionSpec = "torchvision"
$cudaAudioSpec = "torchaudio"
@@ -9270,8 +8196,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
$cudaVisionSpec = "torchvision>=0.19,<0.27.0"
$cudaAudioSpec = "torchaudio>=2.4,<2.12.0"
}
- # 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.
+ # Not on win_arm64: NVIDIA's channel does not publish the kept release.
$_cudaKeptActive = $false
$_cudaKeptRelease = $env:UNSLOTH_KEPT_TORCH
$_cudaKeptFromResident = $false
@@ -9298,7 +8223,6 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
$_cudaKeptActive = $true
}
while ($true) {
- # An unknown-leaf pin lands an ARM64 host here on builds above the ceilings, so drop them.
$_cudaTrio = @($cudaTorchSpec, $cudaVisionSpec, $cudaAudioSpec)
if ($WinArm64Venv) {
$_cudaTrio = @($WinArm64TorchSpec, $WinArm64VisionSpec)
@@ -9306,7 +8230,6 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
} elseif ($WinArm64NoAudio) {
$_cudaTrio = @($cudaTorchSpec, $cudaVisionSpec)
}
- # An explicit pin outranks the persisted index, which is only a memory of an earlier run.
$_cudaIndexUrl = if ($PinnedTorchIndexUrl) { $TorchInstallIndexUrl }
elseif ($WinArm64TorchIndexUrl) { $WinArm64TorchIndexUrl }
else { $TorchInstallIndexUrl }
@@ -9329,7 +8252,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
substep "windows on arm: $_woaCutoffName is not applied to the exact CUDA pins (the index carries no upload dates)."
}
}
- # Our own UV_NO_INDEX convention (uv defines no such variable) means the operator wants no registry index, and we honour it by naming none. The CUDA trio is published nowhere else, so it yields for this one command: the trio from the CUDA index, dependencies from the wheelhouse. Saved and restored, because the rest of the run still reads it.
+ # UV_NO_INDEX is our convention; the CUDA trio exists nowhere else, so it yields for this command.
$_woaNoIndexValue = [string][Environment]::GetEnvironmentVariable("UV_NO_INDEX")
if (Test-NoIndexRequested) {
$_woaCutoffSaved["UV_NO_INDEX"] = $_woaNoIndexValue
@@ -9369,7 +8292,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
Exit-SetupFailure "PyTorch CUDA installation failed (exit code $torchInstallExit)"
}
- # torchaudio left out of the trio: uv would leave it linked against the previous libtorch.
+ # Otherwise uv leaves torchaudio linked against the previous libtorch.
if ($WinArm64Venv -and $WinArm64NoAudio) {
$_woaAudioCode = "import importlib.metadata as m; " +
"print('T=' + next((d.version for d in m.distributions() " +
@@ -9380,7 +8303,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
if ($_woaAudioProbe.Ok) {
$_woaTorchVer = if ($_woaAudioProbe.Output -match '(?m)^T=(\S+)\s*$') { $Matches[1] } else { "" }
$_woaAudioVer = if ($_woaAudioProbe.Output -match '(?m)^A=(\S+)\s*$') { $Matches[1] } else { "" }
- # The whole pairing, as at selection: major.minor, and the build (dev stamp, CUDA tag) too, since the extension is linked against one libtorch.
+ # The extension is linked against one libtorch, so compare the full build too.
if ($_woaAudioVer -and $_woaTorchVer -and -not (
(Test-WoaAudioMatchesTorchParity -TorchVersion $_woaTorchVer -AudioVersion $_woaAudioVer) -and
(Test-WoaPairsWithTorchParity -TorchVersion $_woaTorchVer -OtherVersion $_woaAudioVer -Project "torchaudio"))) {
@@ -9417,30 +8340,20 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
substep "skipping direct PyTorch and Triton installation (no-torch mode)." "Yellow"
}
-# No unsloth.exe rename needed. install.ps1 no longer starts the generated console
-# script at all (it runs the CLI through the venv's python.exe, #8490), so the rename
-# would now target a file nothing is holding -- but it was never needed either:
-# install.ps1 sets SKIP_STUDIO_BASE=1 (base never reinstalled) and 'studio update'
-# goes through uv (--upgrade-package), whose pip fallback no-ops on the
-# already-satisfied bare unsloth/unsloth-zoo. Either way unsloth.exe stays.
-# Duplicate metadata repair is the one pass that DOES reinstall unsloth under
-# SKIP_STUDIO_BASE, so the CLI wraps this script in its launcher transaction.
+# No unsloth.exe rename needed: install.ps1 runs the CLI through python.exe and the base is not
+# reinstalled. Duplicate metadata repair is wrapped in the CLI launcher transaction.
# ── Publish the torch flavor this run settled on ──
-# so install_python_stack.py can enforce it: its dependency steps resolve torch from PyPI, whose
-# Windows wheel is 2.11.0+cpu, and only install.ps1 -- never on the updater's path -- repaired
-# that. Vocabulary is Get-InstalledTorchTag's; an unknown leaf publishes nothing.
+# so install_python_stack.py can enforce it; PyPI's Windows torch wheel is +cpu.
if (-not $NoTorchMode) {
$_expectedLeaf = Get-TorchIndexLeaf $_effectiveTorchIndexUrl
- # $ROCmIndexUrl first: on the AMD path $TorchInstallIndexUrl still points at /cpu.
+ # On the AMD path $TorchInstallIndexUrl still points at /cpu.
$_expectedTag = if ($ROCmIndexUrl) { "rocm" }
elseif (Test-CudaFamilyLeaf $_expectedLeaf) { $_expectedLeaf }
elseif ($_expectedLeaf -eq "cpu" -or $_expectedLeaf -eq "xpu") { $_expectedLeaf }
elseif (Test-PipRocmFamilyLeaf $_expectedLeaf) { "rocm" }
else { $null }
- # Remove-Item, NOT `= ""`: PowerShell 7.5 took .NET 9's change and KEEPS a name
- # assigned an empty string. Deleting also stops a value inherited from the caller's
- # shell surviving a run that decided it cannot name this host's flavor.
+ # Remove-Item, NOT `= ""`: PowerShell 7.5 keeps a name assigned an empty string.
if ($_expectedTag) {
$env:UNSLOTH_EXPECTED_TORCH_TAG = $_expectedTag
} else {
@@ -9459,16 +8372,8 @@ python "$PSScriptRoot\install_python_stack.py"
$stackExit = $LASTEXITCODE
# ── Intel XPU: bitsandbytes must carry XPU kernels ──
-# unsloth/bnb_availability.py binds cgemv_4bit_inference_fp16/bf16 for device_type "xpu" and only
-# bitsandbytes' XPU library exports those, so a wheel without it turns 4-bit QLoRA off. 0.48.2 is
-# the first win_amd64 build carrying that library, but the floor is 0.50.0, the AMD paths' floor:
-# <=0.49.2 NaNs at 4-bit decode on AMD, and an Arc card can sit next to a Radeon. unsloth's own
-# floor (>=0.45.5) lets a MIGRATED venv keep its old wheel while the stack above upgrades unsloth
-# alone, so run after it for the last word. --no-deps (torch and numpy are in), and never the
-# curated unsloth[intel-gpu-torch*] extra: it pins torch to one +xpu wheel URL, unpinning the
-# trio above, and carries a preview bitsandbytes wheel uv refuses. $XpuIndexUrl is the "ended up
-# on XPU" gate. Must stay ABOVE the $ErrorActionPreference restore below: Fast-Install needs
-# EAP=Continue or PS 5.1 turns pip's stderr into a terminating error. Best-effort.
+# Only bitsandbytes' XPU library exports the 4-bit kernels; floor 0.50.0 (<=0.49.2 NaNs on AMD).
+# Never the unsloth[intel-gpu-torch*] extra. Must stay above the EAP restore below (5.1 needs Continue).
if ($stackExit -eq 0 -and $XpuIndexUrl) {
substep "installing bitsandbytes with Intel XPU kernels..."
if ($script:UnslothVerbose) {
@@ -9486,42 +8391,28 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
}
# ── Intel XPU: triton-windows must not shadow torch's XPU triton ──
-# triton-windows and torch's XPU triton BOTH own the top-level `triton` package (80 to 160 shared
-# paths, __init__.py and _C/libtriton.pyd among them), so a cu*-to-xpu pin repair leaves the CUDA
-# build shadowing the XPU one. AFTER the stack, since unsloth declares triton-windows a win32
-# core dependency install reinstalls anything removed earlier. Uninstall always paired with a
-# reinstall: removing one drops the shared paths the other overwrote. The spec is read from the
-# installed torch (renamed pytorch-triton-xpu -> triton-xpu in torch 2.10).
+# Both own the `triton` package. Run after the stack (it reinstalls triton-windows); always
+# pair the uninstall with a reinstall.
if ($stackExit -eq 0 -and $XpuIndexUrl) {
- # One -c line, so no double quotes (Invoke-BoundedPythonProbe wraps $Code in them).
+ # No double quotes: Invoke-BoundedPythonProbe wraps $Code in them.
$_tritonCode = "import importlib.metadata as m; " +
"print('TRITONWIN=' + next((d.version for d in m.distributions() " +
"if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), '')); " +
"print('TRITONXPU=' + next((r.split(';')[0].strip() " +
"for r in (m.requires('torch') or []) if 'triton' in r.lower()), ''))"
$_tritonProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_tritonCode
- # Line-anchored like the other probes so a stdout banner ahead of the answer hides nothing.
$_tritonWinVer = if ($_tritonProbe.Ok -and $_tritonProbe.Output -match '(?m)^TRITONWIN=(\S+)\s*$') { $Matches[1] } else { "" }
$_tritonXpuSpec = if ($_tritonProbe.Ok -and $_tritonProbe.Output -match '(?m)^TRITONXPU=(\S+)\s*$') { $Matches[1] } else { "" }
- # The spec must itself be an XPU triton (pytorch-triton-xpu / triton-xpu); anything else means
- # torch is not the +xpu wheel this branch assumes.
+ # Anything but an XPU triton spec means torch is not the +xpu wheel.
if ($_tritonWinVer -and $_tritonXpuSpec -match '(?i)xpu') {
substep "replacing triton-windows $_tritonWinVer with $_tritonXpuSpec (Intel XPU)..." "Cyan"
- # install_manifest.manifest_path() is venv_root()/MANIFEST_NAME and venv_root() is
- # sys.prefix, which is $VenvDir here -- the same join Get-PersistedNoTorch does. Assembled
- # rather than asked for: a subprocess to learn a constant can hang or fail in a way
- # indistinguishable from "there is no manifest", which reopens the window this closes.
- # test_intel_registry_fallback.ps1 asserts this literal still matches MANIFEST_NAME.
+ # test_intel_registry_fallback.ps1 asserts this literal matches MANIFEST_NAME.
$_manifestPath = Join-Path $VenvDir "unsloth_install_manifest.json"
- # Fetch, THEN uninstall, THEN install the file. The uninstall cannot go last -- it drops
- # the paths in triton-windows' OWN record, which are the shared ones -- so pre-fetching
- # keeps a dead mirror from stranding the venv between the two steps. uv has no
- # `pip download`, hence Fast-Download.
+ # Fetch, then uninstall, then install, so a dead mirror cannot strand the venv between steps.
$_tritonTmp = Join-Path ([System.IO.Path]::GetTempPath()) "unsloth_triton_xpu_$([guid]::NewGuid().ToString('N').Substring(0,8))"
try {
New-Item -ItemType Directory -Force -Path $_tritonTmp -ErrorAction SilentlyContinue | Out-Null
- # Fast-Download is an advanced function, so PowerShell binds `-d` to `-Debug`
- # instead of forwarding it to pip. Use the long `--dest` flag (#10018).
+ # Advanced function: PowerShell binds `-d` to -Debug, so use `--dest`.
if ($script:UnslothVerbose) {
Fast-Download --no-deps --only-binary=:all: --dest $_tritonTmp $_tritonXpuSpec --index-url $XpuIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host
$tritonDlExit = $LASTEXITCODE
@@ -9530,19 +8421,12 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
$tritonDlOutput = Fast-Download --no-deps --only-binary=:all: --dest $_tritonTmp $_tritonXpuSpec --index-url $XpuIndexUrl | Out-String
$tritonDlExit = $LASTEXITCODE
}
- # The exit code alone is not enough: no wheel on disk means nothing to install from.
$_tritonWheel = @(Get-ChildItem -LiteralPath $_tritonTmp -Filter "*.whl" -ErrorAction SilentlyContinue) | Select-Object -First 1 -ExpandProperty FullName
if ($tritonDlExit -ne 0 -or -not $_tritonWheel) {
substep "[WARN] could not fetch $_tritonXpuSpec (exit $tritonDlExit); triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"
Write-StudioLine (Redact-InstallOutput $tritonDlOutput) -ForegroundColor Yellow
} else {
- # From here to the reinstall below is a window where a kill leaves a venv with
- # no triton that the next update still reads as complete and fast-paths past.
- # MOVE the manifest into the wheel's temp dir for the swap, never read and
- # rewrite it: PS 5.1's Set-Content defaults to ANSI and its -Encoding utf8 emits
- # a BOM read_manifest's json.load rejects, so either corrupts a manifest with a
- # non-ASCII path. The finally below deletes the dir, so an unrestored manifest
- # stays gone -- which is the truth while the venv has no triton.
+ # Move (never rewrite) the manifest aside during the swap: 5.1 encodings would corrupt it.
$_manifestHeld = $null
$_manifestBlocked = $false
$_uninstallExit = 0
@@ -9550,9 +8434,7 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
$_held = Join-Path $_tritonTmp "held_manifest.json"
try {
Move-Item -LiteralPath $_manifestPath -Destination $_held -Force -ErrorAction Stop
- # Move-Item across volumes is a copy plus a delete and reports success
- # even when only the delete fails, leaving the original in place. The
- # manifest must be GONE for the swap, so confirm rather than trust.
+ # Cross-volume Move-Item can report success while the original remains; confirm it is gone.
if (Test-Path -LiteralPath $_manifestPath -PathType Leaf) {
Remove-Item -LiteralPath $_held -Force -ErrorAction SilentlyContinue
$_manifestBlocked = $true
@@ -9562,17 +8444,13 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
} catch { $_manifestBlocked = $true }
}
if ($_manifestBlocked) {
- # A manifest that will not move (locked, read-only) would stay valid right
- # through the destructive window, so do not open one. Leaving triton-windows
- # costs torch.compile on the XPU, which the next run can still fix.
+ # An unmovable manifest stays valid through the destructive window, so skip the swap.
substep "[WARN] could not set the install manifest aside; triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"
} else {
Fast-Uninstall "triton-windows" | Out-Null
$_uninstallExit = $LASTEXITCODE
}
- # A triton-windows that would not uninstall (Unsloth running and holding
- # _C/libtriton.pyd open) still shadows the XPU triton, so installing over it
- # achieves nothing and would restore the manifest onto an unchanged venv.
+ # An uninstall that failed (file held open) leaves the shadowing in place.
if (-not $_manifestBlocked -and $_uninstallExit -ne 0) {
substep "[WARN] could not remove triton-windows $_tritonWinVer (exit $_uninstallExit); it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"
if ($_manifestHeld) {
@@ -9589,9 +8467,7 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
}
$_tritonPresent = ($tritonXpuExit -eq 0)
if ($tritonXpuExit -ne 0) {
- # Off the network by now, so this is disk/permissions. triton-windows is
- # already gone and took the shared paths with it, so put SOME working
- # triton back rather than leave the venv unable to import one.
+ # Put SOME triton back rather than leave the venv without one.
Fast-Install --force-reinstall --no-deps $_tritonSpec | Out-Null
$tritonBackExit = $LASTEXITCODE
$_tritonPresent = ($tritonBackExit -eq 0)
@@ -9599,25 +8475,17 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
if ($tritonBackExit -eq 0) {
substep "[WARN] could not install $_tritonXpuSpec (exit $tritonXpuExit); restored triton-windows, so triton still imports -- but torch.compile will not use the XPU." "Yellow"
} else {
- # Redacted: a mirror pin can carry a token, and this is the only place
- # setup.ps1 shows an index URL. A tokenless URL survives verbatim.
+ # Redacted: a mirror pin can carry a token.
$_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl
Write-StudioLine "[ERROR] triton-windows was removed and neither triton would reinstall -- torch.compile is broken." -ForegroundColor Red
Write-StudioLine " Repair with: python -m pip install --force-reinstall --no-deps $_tritonXpuSpec --index-url $_tritonRepairUrl" -ForegroundColor Red
- # Printing alone left $stackExit at 0, so setup reported success and
- # install.ps1 COMMITTED this venv over its rollback copy. It has no
- # importable triton at all; the caller must not accept it.
+ # Fail, or install.ps1 commits this triton-less venv over its rollback copy.
$stackExit = $tritonBackExit
}
}
- # Moved back, never rewritten, and only once a triton is importable again. If
- # neither would reinstall the venv really is incomplete, and losing the
- # manifest with the temp dir is what makes the next update repair it.
+ # Restore only once a triton imports; a lost manifest makes the next update repair.
if ($_manifestHeld -and $_tritonPresent) {
try { Move-Item -LiteralPath $_manifestHeld -Destination $_manifestPath -Force -ErrorAction Stop } catch {}
- # The finally below deletes the held copy either way, so an unreported
- # failure loses the manifest silently and the next run does a full
- # dependency pass with nothing on screen explaining why.
if (-not (Test-Path -LiteralPath $_manifestPath -PathType Leaf)) {
substep "[WARN] could not restore the install manifest; the next update will re-run the dependency pass." "Yellow"
}
@@ -9625,13 +8493,11 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {
}
}
} finally {
- # The wheel is ~300 MB, so it never outlives the install.
Remove-Item -Recurse -Force -LiteralPath $_tritonTmp -ErrorAction SilentlyContinue
}
}
}
-# Restore ErrorActionPreference after pip/python work
$ErrorActionPreference = $prevEAP
if ($stackExit -ne 0) {
Write-StudioLine "[FAILED] Python dependency installation failed (exit code $stackExit)" -ForegroundColor Red
@@ -9671,7 +8537,6 @@ if (Test-SetupScriptReplaced) {
} else {
step "python" "dependencies up to date"
- # Restore ErrorActionPreference (was lowered for pip/python section)
$ErrorActionPreference = $prevEAP
}
Complete-FrontendBuildBackground -IfDone
@@ -9686,7 +8551,7 @@ if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) {
$_mxcInstallDir = Join-Path $StudioHome "mxc-runtime\$_mxcArchDir"
if (Test-Path -LiteralPath $_mxcInstaller -PathType Leaf) {
substep "installing Windows MXC Preview runtime..."
- # Optional, so a nonzero exit or stderr line must reach the fallback below, not stop setup.
+ # Optional: a nonzero exit or stderr must reach the fallback, not stop setup.
$_mxcPrevEAP = $ErrorActionPreference
$ErrorActionPreference = "Continue"
$_mxcRestoreNative = $PSVersionTable.PSVersion.Major -ge 7
@@ -9749,11 +8614,10 @@ function Test-TargetPackageVersion {
return $false
}
-# Audited AND installed from here; mirrors _SIDECAR_COMMON_PINS in setup.sh. A name the audit
-# cannot reach on disk reads stale forever.
+# Mirrors _SIDECAR_COMMON_PINS in setup.sh.
$SidecarCommonPins = @("huggingface_hub==1.8.0", "hf_xet==1.4.2")
-# Mirrors fast_install_sidecar: an inherited UV_OVERRIDE would replace the pin and force rebuilds.
+# An inherited UV_OVERRIDE would replace the pin and force rebuilds.
function Fast-Install-Sidecar {
param([Parameter(ValueFromRemainingArguments=$true)]$Args_)
$savedOverride = $env:UV_OVERRIDE
@@ -9761,7 +8625,7 @@ function Fast-Install-Sidecar {
try {
Remove-Item Env:UV_OVERRIDE -ErrorAction SilentlyContinue
Fast-Install @Args_
- # A pin the PyPI mirror has not synced yet: one rerun with pypi.org behind it, armed only after a slow pypi.org was switched.
+ # A pin the PyPI mirror has not synced yet: one rerun against pypi.org.
$unsynced = @(-split "$env:_UNSLOTH_MIRROR_SPARE" | Where-Object { $_ -like 'unsynced|*' })
if ($LASTEXITCODE -ne 0 -and $unsynced) {
foreach ($pair in @($unsynced[0].Split('|') | Select-Object -Skip 1)) {
@@ -9780,7 +8644,7 @@ function Fast-Install-Sidecar {
}
function Remove-SidecarTiktoken {
- # Remnants of a failed tiktoken install shadow the ambient copy and nothing else clears them.
+ # Remnants of a failed tiktoken install shadow the ambient copy.
param([Parameter(Mandatory = $true)][string]$TargetDir)
foreach ($name in @("tiktoken", "tiktoken_ext", "tiktoken.libs")) {
$entry = Join-Path $TargetDir $name
@@ -9809,13 +8673,10 @@ function Repair-SidecarTiktoken {
[Parameter(Mandatory = $true)][string]$TargetDir,
[Parameter(Mandatory = $true)][string]$DirName
)
- # Under the offline keep this would reach the network through Fast-Install's pip fallback, and
- # give a deferred tier a directory holding tiktoken alone.
+ # Offline keep: Fast-Install's pip fallback would reach the network.
if ($script:OfflineFastPath) { return }
- # And under UV_OFFLINE without the fast path: the pip fallback would reach for the network.
if (Test-UvOfflineRequested) { return }
- # Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the
- # other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.
+ # RECORD is written last; a recordless dist-info goes first since uv cannot uninstall it.
Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |
Where-Object { -not (Test-Path -LiteralPath (Join-Path $_.FullName "RECORD") -PathType Leaf) } |
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }
@@ -9823,12 +8684,11 @@ function Repair-SidecarTiktoken {
Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "RECORD") -PathType Leaf })
$payload = Join-Path $TargetDir "tiktoken"
if ($present.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $payload "__init__.py") -PathType Leaf)) { return }
- # Dropping the metadata is what makes uv reinstall instead of calling the pin satisfied.
+ # Dropping the metadata makes uv reinstall instead of calling the pin satisfied.
Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }
Invoke-MirrorFallback
- # Cleared first: an install that runs no native command would retire the sidecar on a stale
- # nonzero (unresolvable uv is non-terminating under "Continue").
+ # Cleared first, or a stale nonzero would retire the sidecar.
$global:LASTEXITCODE = 0
$output = Fast-Install-Sidecar --target $TargetDir --no-deps --upgrade tiktoken 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
@@ -9841,7 +8701,6 @@ function Repair-SidecarTiktoken {
}
function Test-SidecarCurrent {
- # One predicate for both shells: the shell reimplementation called a half-written sidecar current.
param(
[Parameter(Mandatory = $true)][string]$TargetDir,
[Parameter(Mandatory = $true)][string]$Version
@@ -9853,9 +8712,8 @@ function Test-SidecarCurrent {
}
$pins = @("transformers==$Version") + $SidecarCommonPins
$out = ""
- # A bounded process, not a native command: a native nonzero exit terminates under
- # $PSNativeCommandUseErrorActionPreference. argv is base64 so quoting cannot break -c, and the
- # venv interpreter comes first, as in setup.sh: a PATH `python` can be the Store alias stub.
+ # Bounded process: a native nonzero exit can terminate under $PSNativeCommandUseErrorActionPreference.
+ # argv is base64; venv interpreter first since PATH python can be the Store stub.
$pythonExe = $null
$probe = $null
if ($VenvPyExe -and (Test-Path -LiteralPath $VenvPyExe -PathType Leaf)) {
@@ -9876,16 +8734,14 @@ function Test-SidecarCurrent {
}
if ($out -eq "sidecar: current") { return $true }
if ($out -like "sidecar:*") {
- # A regex, not Substring: `-like` matches the bare marker too and Substring would throw.
if ($script:UnslothVerbose) { substep "sidecar $TargetDir`: $($out -replace '^sidecar:\s*', '')" }
return $false
}
- # A failure with no marker is a dead audit, not the legacy silent exit 0.
if ($null -ne $probe -and -not $probe.Ok) {
if ($script:UnslothVerbose) { substep "sidecar $TargetDir`: audit failed" }
return $false
}
- # An old shim exits 0 silently: fall back to the grep this replaced.
+ # An old shim exits 0 silently: fall back to the version grep.
return (Test-TargetPackageVersion -TargetDir $TargetDir -PackageName "transformers" -ExpectedVersion $Version)
}
@@ -9903,7 +8759,6 @@ function Install-T5Sidecar {
if (Test-Path -LiteralPath $TargetDir) { Remove-Item -LiteralPath $TargetDir -Recurse -Force }
[System.IO.Directory]::CreateDirectory($TargetDir) | Out-Null
Mark-StudioOwned -Path $TargetDir
- # From $SidecarCommonPins, not a copy: a pin demanded but never installed reads stale forever.
foreach ($pkg in @("transformers==$Version") + $SidecarCommonPins) {
if ($script:UnslothVerbose) {
Fast-Install-Sidecar --target $TargetDir --no-deps $pkg
@@ -9941,12 +8796,11 @@ function Install-T5Sidecar {
$_NeedT5_530 = $false
$_NeedT5_550 = $false
$_NeedT5_510 = $false
-# The migration is a wipe and three rebuilds from a cache that may be cold, and the legacy tree is
-# the only sidecar, so under UV_OFFLINE it waits for the next online update.
+# The migration needs the network; under UV_OFFLINE it waits for the next online update.
if ((Test-Path -LiteralPath $VenvT5Legacy) -and ($script:OfflineFastPath -or (Test-UvOfflineRequested))) {
substep "legacy transformers sidecar left in place -- UV_OFFLINE is set, migration waits for the next online update" "Yellow"
} elseif (Test-Path -LiteralPath $VenvT5Legacy) {
- # Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.
+ # A staged run's venvs may never be activated, so only the live update migrates.
if (-not $StageRoot) {
Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"
Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force
@@ -9958,15 +8812,10 @@ if ((Test-Path -LiteralPath $VenvT5Legacy) -and ($script:OfflineFastPath -or (Te
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_530Dir -Version "5.3.0")) { $_NeedT5_530 = $true }
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_550Dir -Version "5.5.0")) { $_NeedT5_550 = $true }
if (-not (Test-SidecarCurrent -TargetDir $VenvT5_510Dir -Version "5.10.2")) { $_NeedT5_510 = $true }
-# A sidecar rebuild is a wipe and four fetches, through a pip fallback that reaches the network,
-# so under the offline keep it waits for the next online update; the runtime self-heal covers a
-# missing tier meanwhile. Mirrors setup.sh. A deferred tier keeps its own flag so it is not
-# reported "current".
+# Offline keep: defer sidecar rebuilds; the runtime self-heal covers a missing tier. Mirrors setup.sh.
$_DeferT5_530 = $false
$_DeferT5_550 = $false
$_DeferT5_510 = $false
-# UV_OFFLINE without the fast path: the same wipe and fetches, through a pip fallback that does not
-# read UV_OFFLINE. Every stale or missing tier is left for the next online update.
if (-not $script:OfflineFastPath -and (Test-UvOfflineRequested)) {
foreach ($tier in @(@("530", "5.3.0"), @("550", "5.5.0"), @("510", "5.10.2"))) {
$flag = "_NeedT5_$($tier[0])"
@@ -10030,7 +8879,6 @@ $NeedLlamaSourceBuild = $false
$script:LlamaSourceBuildIsFallback = $false
$SkipPrebuiltInstall = $false
$RequestedLlamaTag = if ($env:UNSLOTH_LLAMA_TAG) { $env:UNSLOTH_LLAMA_TAG } else { $DefaultLlamaTag }
-# Every host installs the fork's app-* prebuilts; ggml-org artifacts are no longer the default.
$HelperReleaseRepo = "unslothai/llama.cpp"
$LlamaPr = if ($env:UNSLOTH_LLAMA_PR) { $env:UNSLOTH_LLAMA_PR.Trim() } else { "" }
@@ -10074,7 +8922,7 @@ function Invoke-LlamaHelper {
}
try {
- # Capture all output (2>&1) so PS does not make ErrorRecords; split afterwards.
+ # Capture all output (2>&1) so PS does not make ErrorRecords.
$allOutput = & python "$PSScriptRoot\install_llama_prebuilt.py" @Arguments 2>&1
$exitCode = $LASTEXITCODE
$stdoutLines = @()
@@ -10103,22 +8951,8 @@ function Invoke-LlamaHelper {
function Test-LlamaTreeStillHealthy {
<#
- Whether a tree the reuse shortcut is about to keep is one preflight will accept.
-
- llama-server.exe existing is not enough. Quarantine and a truncated extract both
- take a library and leave the entrypoint in place, and this branch is only reached
- once the prebuilt path has already failed, so keeping such a tree returns it byte
- for byte identical and reports success. Desktop preflight grades the same tree on
- every launch, so an update that repaired nothing left it offering the same repair
- forever, which is the loop installed_runtime_health exists to prevent.
-
- The setup.sh side of this gate is the same call. Both go through
- install_llama_prebuilt so there is one definition of healthy rather than two that
- can disagree.
-
- Healthy on any failure to ask. A helper that cannot run, or a python that is not
- there yet, must not turn into a rebuild: that trades a wrong keep for a
- multi-gigabyte source build on a machine whose only fault was an unreadable tree.
+ Whether a tree the reuse shortcut keeps would pass preflight; llama-server.exe existing is
+ not enough. Same check as setup.sh via install_llama_prebuilt. Healthy on any failure to ask.
#>
param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$TreeRoot)
if ([string]::IsNullOrWhiteSpace($TreeRoot)) { return $true }
@@ -10162,8 +8996,7 @@ if ($LlamaPr) {
$LocalLlamaCppLinked = $false
$LocalLlamaCppSrc = $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR
if ($LocalLlamaCppSrc) {
- # Unreadable is not missing: reporting "does not exist" would send the user
- # looking for the wrong problem.
+ # Unreadable is not missing.
$localSrcState = Get-PathState -Path $LocalLlamaCppSrc -PathType Container
if ($localSrcState -eq "Denied") {
Exit-PathAccessDenied -Path $LocalLlamaCppSrc -Label "the UNSLOTH_LOCAL_LLAMA_CPP_DIR directory" -UserSupplied
@@ -10180,23 +9013,16 @@ if ($LocalLlamaCppSrc) {
(Join-Path $ResolvedLocal "llama-server.exe"),
(Join-Path $ResolvedLocal "build\bin\llama-server.exe"),
(Join-Path $ResolvedLocal "build\bin\Release\llama-server.exe"))) {
- # Denied must not read as "nothing built here": the canonical branch
- # below would then hand the tree to the prebuilt installer, which
- # replaces the very build this flag asked to reuse.
+ # Denied must not read as "nothing built here", or the prebuilt installer replaces the user's build.
$candState = Get-PathState -Path $_cand
if ($candState -eq "Denied") {
- # -UserSupplied even when this is the canonical location: the
- # override says the tree is the user's build, so never advise
- # deleting it, managed path or not.
+ # -UserSupplied: never advise deleting the user's build.
Exit-PathAccessDenied -Path $ResolvedLocal -Label "the UNSLOTH_LOCAL_LLAMA_CPP_DIR build" -UserSupplied
}
if ($candState -eq "Present") { $LocalLlamaServerFound = $true; break }
}
if ($LocalIsCanonical) {
- # Points at the canonical install location itself: never delete-then-link
- # onto itself. Reuse an existing build here (skip prebuilt + source) so the
- # staged prebuilt installer can't replace a build the user asked to reuse;
- # if nothing is built yet, fall through to the normal install.
+ # Pointing at the canonical location: reuse an existing build, never link onto itself.
if ($LocalLlamaServerFound) {
substep "UNSLOTH_LOCAL_LLAMA_CPP_DIR is the canonical install location and already holds a build; reusing it" "Yellow"
$LocalLlamaCppLinked = $true
@@ -10212,8 +9038,6 @@ if ($LocalLlamaCppSrc) {
# Delete only the link: -Recurse can traverse a reparse point and wipe the real dir.
$existing = Get-Item -LiteralPath $LlamaCppDir -Force -ErrorAction SilentlyContinue
if ($existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
- # A link reads Present, so the probe below cannot cover a denied
- # unlink; report it here rather than terminate on the raw throw.
try { $existing.Delete() }
catch {
if (Test-AccessDeniedError $_) { Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install" }
@@ -10223,19 +9047,13 @@ if ($LocalLlamaCppSrc) {
if ($RuntimeRootIsCustom) {
Assert-StudioOwnedOrAbsent -Path $LlamaCppDir -Label "llama.cpp install" -IsCustom $RuntimeRootIsCustom
}
- # The destination is about to be deleted and replaced, so a denial here
- # must stop rather than throw raw: under a default home nothing above
- # has probed it three-state.
$destState = Get-PathState -Path $LlamaCppDir
if ($destState -eq "Denied") {
Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install"
}
if ($destState -eq "Present") {
Remove-Item -Recurse -Force -LiteralPath $LlamaCppDir -ErrorAction SilentlyContinue
- # A locked/in-use tree can silently survive removal (SilentlyContinue
- # masks it). Don't then junction/copy over a half-present dir; mirror the
- # prebuilt path's blocked-install handling and stop with a clear message.
- # Denied counts as surviving (unreadable is not gone), so name no single cause (#9928).
+ # A locked or denied tree can survive removal; do not link/copy over it.
if ((Get-PathState -Path $LlamaCppDir) -ne "Absent") {
step "llama.cpp" "install blocked; existing install could not be replaced" "Yellow"
substep "Close Unsloth or other llama.cpp users, or repair the ACLs on $LlamaCppDir, then retry" "Yellow"
@@ -10271,7 +9089,6 @@ if ($LocalLlamaCppLinked) {
substep "Skipping prebuilt install -- falling back to source build" "Yellow"
} else {
Write-StudioLine ""
- # Keep this late guard as defense in depth before the prebuilt installer.
$llamaDirState = Get-LlamaCppInstallReadState -Path $LlamaCppDir
if ($llamaDirState -eq "Denied") {
Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install" -OwnershipUnverified:$RuntimeRootIsCustom
@@ -10279,18 +9096,17 @@ if ($LocalLlamaCppLinked) {
if ($llamaDirState -eq "Readable") {
substep "Existing llama.cpp install detected -- validating staged prebuilt update before replacement"
$existingMetaPath = Join-Path $LlamaCppDir "UNSLOTH_PREBUILT_INFO.json"
- # Readable state leaves only marker presence to decide here.
if (Test-PathQuiet -Path $existingMetaPath -PathType Leaf) {
try {
$existingMeta = Get-Content -LiteralPath $existingMetaPath -Raw | ConvertFrom-Json
$existingKind = $existingMeta.install_kind
- # windows-vulkan is in every branch: any x64 Windows host can land there, and a guard without it deletes a working Vulkan install on every run. The VENV's arch, not the machine's.
+ # windows-vulkan is in every branch, or a working Vulkan install is deleted every run.
+ # The VENV's arch, not the machine's.
$_arm64CudaOptOut = ("$env:UNSLOTH_LLAMA_ARM64_CUDA").Trim().ToLowerInvariant() -in @("0", "false", "no", "off")
- # Still valid unopted: the selector falls back to it when no ARM64 CUDA asset exists.
$_nvidiaKinds = if (Test-WinArm64Venv) {
if ($_arm64CudaOptOut) { @("windows-arm64", "windows-vulkan") } else { @("windows-arm64-cuda", "windows-arm64", "windows-vulkan") }
} else { @("windows-cuda", "windows-vulkan") }
- # A probe that did not answer is not evidence the GPU is gone. Read here, not from the dependency pass, which $SkipPythonDeps skips whole.
+ # A probe that did not answer is not evidence the GPU is gone.
$_woaEvidenceIndex = if ($WinArm64EffectiveTorchIndexUrl) { $WinArm64EffectiveTorchIndexUrl }
else {
$_p = Get-PinnedTorchIndexUrl
@@ -10302,12 +9118,11 @@ if ($LocalLlamaCppLinked) {
}
$_nvidiaEvidence = $HasNvidiaDriverEvidence -or ((Test-WinArm64Venv) -and $_woaEvidenceIndex -and
(Test-WoaPersistableIndex $_woaEvidenceIndex))
- # No ROCm bundle exists for Windows ARM64 (upstream's is hip-radeon-x64), so the selector falls through to the ARM64 CPU bundle; without that kind here the gate refetches it every update.
+ # No Windows ARM64 ROCm bundle, so include the CPU kind or the gate refetches every update.
$_rocmKinds = if (Test-WinArm64Venv) {
@("windows-rocm", "windows-hip", "windows-arm64", "windows-vulkan")
} else { @("windows-rocm", "windows-hip", "windows-vulkan") }
$expectedKinds = if ($HasROCm -or $script:ROCmGfxArch) { $_rocmKinds } elseif ($_nvidiaEvidence) { $_nvidiaKinds } else { @("windows-cpu", "windows-arm64", "windows-vulkan") }
- # A pre-CUDA 11 library still proves physical NVIDIA presence, even when AMD/Intel selects torch.
if ($script:NvidiaDriverLibraryOnly) { $expectedKinds += $_nvidiaKinds }
# ARM64 Vulkan (a Vulkan GPU found, or UNSLOTH_LLAMA_CPP_BACKEND=vulkan) can land on any ARM64 host.
if (Test-WinArm64Venv) { $expectedKinds += "windows-arm64-vulkan" }
@@ -10321,7 +9136,7 @@ if ($LocalLlamaCppLinked) {
}
}
substep "installing prebuilt llama.cpp bundle (preferred path)..."
- # install_llama_prebuilt.py's os.replace() would displace a custom-home llama.cpp first.
+ # install_llama_prebuilt.py's os.replace() would displace a custom-home llama.cpp.
if ($RuntimeRootIsCustom) {
Assert-StudioOwnedOrAbsent -Path $LlamaCppDir -Label "llama.cpp install" -IsCustom $RuntimeRootIsCustom
}
@@ -10341,10 +9156,7 @@ if ($LocalLlamaCppLinked) {
if ($env:UNSLOTH_LLAMA_RELEASE_TAG) {
$prebuiltArgs += @("--published-release-tag", $env:UNSLOTH_LLAMA_RELEASE_TAG)
}
- # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself, and
- # it is also the only side that can see a choice recorded in the install
- # marker, so forwarding a second copy from here could only ever disagree
- # with it. The override does not change the torch backend.
+ # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself; do not forward a copy.
$llamaBackend = $sourceLlamaBackend
if ($llamaBackend -eq "vulkan" -or $explicitLlamaSourceBackend -eq "vulkan") {
if ($IsMacOS) {
@@ -10386,9 +9198,7 @@ if ($LocalLlamaCppLinked) {
if ($prebuiltOutput -match "already matches") {
step "llama.cpp" "prebuilt up to date and validated"
} elseif ($prebuiltOutput -match "keeping the existing complete install") {
- # Exit 0 can also mean the installer kept the tree already on disk after a
- # transient failure. "installed and validated" would name a release nothing
- # fetched.
+ # Exit 0 can also mean the existing tree was kept after a transient failure.
step "llama.cpp" "update unavailable, existing prebuilt kept" "Yellow"
} else {
step "llama.cpp" "prebuilt installed and validated"
@@ -10401,7 +9211,7 @@ if ($LocalLlamaCppLinked) {
substep $installedRelease
}
} elseif ($prebuiltExit -eq 3) {
- # WinError 5 is both an in-use file and an unreadable ACL: name ACLs only if repair lines were printed.
+ # WinError 5 is both an in-use file and an ACL denial.
step "llama.cpp" "install blocked; existing install could not be replaced" "Yellow"
Write-LlamaFailureLog -Output $prebuiltOutput
if (Test-Path -LiteralPath $LlamaCppDir) {
@@ -10425,9 +9235,7 @@ if ($LocalLlamaCppLinked) {
if (Test-PathQuiet $_cand) { $PreservedLlamaServerFound = $true; break }
}
if (-not $PreservedLlamaServerFound) { $script:LlamaCppDegraded = $true }
- # A preserved server may not satisfy an explicit backend request, and
- # it leaves LlamaCppDegraded false. Never report success on an
- # unverified backend after the requested replacement ran out of space.
+ # Never report success on an unverified backend for an explicit request.
if ($explicitLlamaSourceBackend) {
step "llama.cpp" "$explicitLlamaSourceBackend was explicitly requested, so the installer will not keep an unverified existing backend" "Red"
Exit-SetupFailure "$explicitLlamaSourceBackend was explicitly requested, so the installer will not keep an unverified existing llama.cpp backend."
@@ -10443,8 +9251,7 @@ if ($LocalLlamaCppLinked) {
} elseif ($prebuiltExit -eq 2) {
$keptBackend = Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $LlamaCppDir
if ($keptBackend) {
- # The source fallback needs MSVC and nvcc and builds for the CPU without a
- # compute capability, so it must not replace a working GPU prebuilt (#9255).
+ # The source fallback builds for CPU without a compute capability; keep a working GPU prebuilt.
$script:LlamaKeptGpuPrebuilt = $keptBackend
step "llama.cpp" "update failed ($(Get-LlamaUpdateFailReason $prebuiltOutput)); keeping the installed $keptBackend prebuilt, the next update will retry" "Yellow"
Write-LlamaFailureLog -Output $prebuiltOutput
@@ -10454,9 +9261,6 @@ if ($LocalLlamaCppLinked) {
if (Test-Path -LiteralPath $LlamaCppDir) {
substep "Prebuilt update failed; existing install was restored or cleaned before source build fallback" "Yellow"
}
- # Exit 2 means no concrete backend was in play: a request the installer
- # could not honour -- named here or recorded in the install marker,
- # which this script cannot see -- exits 5 above instead.
substep "Prebuilt llama.cpp path unavailable or failed validation -- falling back to source build" "Yellow"
$NeedLlamaSourceBuild = $true
$script:LlamaSourceBuildIsFallback = $true
@@ -10480,21 +9284,17 @@ if ($LocalLlamaCppLinked) {
# llama. Failure is never fatal: local dictation falls back to Transformers STT.
$WhisperCppDir = Join-Path $UnslothHome "whisper.cpp"
$WhisperInstaller = Join-Path $PSScriptRoot "install_whisper_prebuilt.py"
-# Same opt-outs as setup.sh: a user-configured binary/dir or an explicit skip
-# disables the managed install entirely.
+# A user-configured whisper binary/dir or an explicit skip disables the managed install entirely.
if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {
substep "whisper.cpp: using a user-configured binary/dir; skipping managed install"
} elseif ($env:UNSLOTH_SKIP_WHISPER_INSTALL -eq "1") {
substep "whisper.cpp: install skipped (UNSLOTH_SKIP_WHISPER_INSTALL=1)"
} elseif ($RuntimeRootIsCustom -and (Test-Path -LiteralPath $WhisperInstaller) -and
(Assert-StudioOwnedOrAbsent -Path $WhisperCppDir -Label "whisper.cpp install" -NonFatal -IsCustom $RuntimeRootIsCustom) -eq "Denied") {
- # Never fatal, per the phase header: the guard below would exit the whole run
- # on an unreadable tree, taking llama.cpp down with it. Only the denial is
- # caught here; an unowned tree still stops.
+ # Never fatal: only the denial is caught here; an unowned tree still stops.
step "whisper.cpp" "install directory cannot be read: access is denied; curated whisper.cpp dictation is unavailable; restore access to $WhisperCppDir or move it aside, then re-run setup; browser and Transformers dictation remain available" "Yellow"
} elseif (Test-Path -LiteralPath $WhisperInstaller) {
- # The installer replaces the whole directory during activation, so the
- # custom-home ownership guard must run first (mirrors the llama block).
+ # The installer replaces the whole directory, so the ownership guard runs first.
if ($RuntimeRootIsCustom) {
Assert-StudioOwnedOrAbsent -Path $WhisperCppDir -Label "whisper.cpp install" -IsCustom $RuntimeRootIsCustom
}
@@ -10529,9 +9329,6 @@ if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {
if ($whisperOutput -match "already matches") {
step "whisper.cpp" "prebuilt up to date"
} elseif ($whisperOutput -match "keeping the existing complete install") {
- # Exit 0 can also mean a kept tree after a lookup that could not answer; "prebuilt
- # installed" would name a release nothing fetched. Same wording and token as llama's
- # arm.
step "whisper.cpp" "update unavailable, existing prebuilt kept" "Yellow"
} else {
step "whisper.cpp" "prebuilt installed"
@@ -10561,10 +9358,8 @@ if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {
}
# ==========================================================================
-# PHASE 3.4b: Install the audio.cpp prebuilt (speech, music and dictation runtime)
# ==========================================================================
-# audio.cpp vendors its own patched ggml, so its bundles are self-contained and do not
-# pair with the llama install. Failure is never fatal: every other audio engine keeps working.
+# PHASE 3.4b: audio.cpp prebuilt. Self-contained bundles; failure is never fatal.
$AudioCppDir = Join-Path $UnslothHome "audio.cpp"
$AudioCppInstaller = Join-Path $PSScriptRoot "install_audio_cpp_prebuilt.py"
if ($env:AUDIOCPP_SERVER_PATH -or $env:UNSLOTH_AUDIO_CPP_PATH) {
@@ -10579,7 +9374,6 @@ if ($env:AUDIOCPP_SERVER_PATH -or $env:UNSLOTH_AUDIO_CPP_PATH) {
Assert-StudioOwnedOrAbsent -Path $AudioCppDir -Label "audio.cpp install" -IsCustom $RuntimeRootIsCustom
}
$audioCppArgs = @($AudioCppInstaller, "--install-dir", $AudioCppDir)
- # A host whose GPU is invisible at install time names its bundle here.
if ($env:UNSLOTH_AUDIO_CPP_ACCELERATOR) {
$audioCppArgs += @("--accelerator", $env:UNSLOTH_AUDIO_CPP_ACCELERATOR)
}
@@ -10605,8 +9399,6 @@ if ($env:AUDIOCPP_SERVER_PATH -or $env:UNSLOTH_AUDIO_CPP_PATH) {
if ($audioCppOutput -match "already matches") {
step "audio.cpp" "prebuilt up to date"
} elseif ($audioCppOutput -match "keeping the existing complete install") {
- # The release lookup could not answer and the install on disk is complete; "prebuilt
- # installed" would name a release nothing fetched. whisper.cpp's wording.
step "audio.cpp" "update unavailable, existing prebuilt kept" "Yellow"
} else {
step "audio.cpp" "prebuilt installed"
@@ -10687,7 +9479,7 @@ if ($NeedLlamaSourceBuild -and -not $script:LlamaBuildToolsDeclined) {
}
# ==========================================================================
-# PHASE 4: Build llama.cpp with CUDA for GGUF inference + export
+# PHASE 4: Build llama.cpp from source
# ==========================================================================
$OriginalLlamaCppDir = $LlamaCppDir
$BuildDir = Join-Path $LlamaCppDir "build"
@@ -10696,12 +9488,8 @@ $LlamaServerBin = Join-Path $BuildDir "bin\Release\llama-server.exe"
$HasCmakeForBuild = $null -ne (Get-Command cmake -ErrorAction SilentlyContinue)
$HasGitForBuild = $null -ne (Get-Command git -ErrorAction SilentlyContinue)
-# A CUDA binary on a now-CPU-only machine, or the reverse, must be rebuilt.
$NeedRebuild = $false
-# A forced compile, a pinned PR or a custom source skips the prebuilt path and its
-# phase 3.4 denial guard, so this can be the first probe to read inside the tree.
-# A linked local dir is skipped: it reads through the junction into the user's own
-# checkout, and nothing here is consumed on that path anyway.
+# Forced or custom source builds skip the phase 3.4 guard, so this may be the first read of the tree.
$llamaBinState = if ($LocalLlamaCppLinked) { "Absent" } else { Get-PathState -Path $LlamaServerBin -PathType Leaf }
if ($llamaBinState -eq "Denied") {
# Nothing proved this tree is ours here, so do not advise deleting it.
@@ -10727,13 +9515,7 @@ if ($llamaBinState -eq "Present") {
}
}
-# One predicate for the plan and the shortcut. The health gate belongs in both: read only
-# by the shortcut, a tree it refuses left $WillBuildLlamaFromSource false, so the git
-# install and Ensure-BuildToolsForLlamaSourceBuild below were skipped and the rebuild the
-# refusal forces then reached cmake on a prebuilt-only box with no toolchain.
-# Asked once, so the helper runs once and its "incomplete" line is printed once. A linked
-# local dir is excluded here as it is everywhere else on this route: nothing reads into the
-# user's own checkout, and the branch below takes it before the shortcut anyway.
+# One predicate for the plan and the shortcut, so a refused tree also plans the toolchain.
$CanReuseLlamaBuild = (Test-PathQuiet $LlamaServerBin "Leaf") -and -not $NeedRebuild -and `
$RequestedLlamaTag -ne "master"
if ($CanReuseLlamaBuild -and $NeedLlamaSourceBuild -and -not $LocalLlamaCppLinked) {
@@ -10743,9 +9525,7 @@ $WillBuildLlamaFromSource = $NeedLlamaSourceBuild -and -not $CanReuseLlamaBuild
if ($script:LlamaBuildToolsDeclined -and -not $CanReuseLlamaBuild) { $WillBuildLlamaFromSource = $false }
if ($WillBuildLlamaFromSource) {
if (-not $HasGitForBuild) {
- # Phase 1 keeps git optional, so only the automatic fallback after a failed prebuilt
- # download arrives here without it. Last chance to install: Invoke-SetupCommand
- # returns 0 for command-not-found, so a git-less clone misreports as a cmake failure.
+ # Invoke-SetupCommand returns 0 for command-not-found, so a git-less clone misreports as cmake failure.
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
try {
Invoke-SetupCommand { winget install Git.Git --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
@@ -10754,31 +9534,22 @@ if ($WillBuildLlamaFromSource) {
}
$HasGitForBuild = $null -ne (Get-Command git -ErrorAction SilentlyContinue)
}
- # Git first, then the toolchain: Ensure-BuildToolsForLlamaSourceBuild exits setup when
- # Build Tools cannot be installed, so running it first made the degraded path below
- # unreachable on a no-winget box, and elsewhere spent a multi-GB download on a clone
- # that cannot happen.
+ # Git first: Ensure-BuildToolsForLlamaSourceBuild exits setup when Build Tools cannot be installed.
if ($HasGitForBuild) {
Ensure-BuildToolsForLlamaSourceBuild
- # refresh so the chain below sees a newly installed cmake
$HasCmakeForBuild = $null -ne (Get-Command cmake -ErrorAction SilentlyContinue)
}
}
if ($LocalLlamaCppLinked) {
- # Local dir linked above -- honor the flag's contract: skip BOTH the prebuilt
- # download and the source build. Falling through here would run CMake inside
- # the user's checkout (via the junction) when it lacks build\bin\Release\llama-server.exe.
+ # Honour the local-dir contract: skip BOTH prebuilt and source build.
Write-StudioLine ""
step "llama.cpp" "linked (skipping build)"
} elseif (-not $NeedLlamaSourceBuild) {
Write-StudioLine ""
step "llama.cpp" "prebuilt (validated)"
} elseif ($CanReuseLlamaBuild) {
- # Skip rebuild only for pinned tags (e.g. b8635). When the requested
- # tag is "master" (a moving target), always rebuild so the binary picks
- # up new model architecture support (e.g. Gemma 4). Health is folded into
- # $CanReuseLlamaBuild above, so refusing here also planned the toolchain.
+ # Skip rebuild only for pinned tags; "master" moves, so always rebuild.
Write-StudioLine ""
step "llama.cpp" "already built"
} elseif ($script:LlamaBuildToolsDeclined) {
@@ -10789,9 +9560,7 @@ if ($LocalLlamaCppLinked) {
substep "To install them and build from source, set UNSLOTH_INSTALL_BUILD_TOOLS=1 and re-run setup." "Yellow"
$script:LlamaCppDegraded = $true
} elseif (-not $HasGitForBuild) {
- # Before cmake: the toolchain install is skipped without git, so cmake may be missing
- # purely as a consequence. Degrade rather than abort; the opt-in source triggers already
- # required git in Phase 1, so only the automatic fallback lands here.
+ # cmake may be missing only because git was; degrade rather than abort.
Write-StudioLine ""
step "llama.cpp" "build skipped (git not available)" "Yellow"
substep "The prebuilt download failed and a source build clones llama.cpp." "Yellow"
@@ -10810,9 +9579,7 @@ if ($LocalLlamaCppLinked) {
substep "Install CMake from https://cmake.org/download/ and re-run setup." "Yellow"
$script:LlamaCppDegraded = $true
} else {
- # Finalize the VS generator BEFORE Resolve-CudaToolkit, which copies the CUDA .targets into
- # the current generator's dir. The CMake 4.2 gate for VS 2026 is checked only here, so a
- # VS 2026 + cmake < 4.2 host can still use the prebuilt. (#6473)
+ # Finalize the VS generator before Resolve-CudaToolkit, which copies the CUDA .targets into it.
if ($CmakeGenerator -match 'Visual Studio 18\b') {
if (-not (Test-CmakeCanDriveGenerator -Generator $CmakeGenerator)) {
$cmakeVerObj = Get-CmakeVersion
@@ -10824,7 +9591,7 @@ if ($LocalLlamaCppLinked) {
Refresh-Environment
} catch { substep "CMake winget upgrade failed: $($_.Exception.Message)" "Yellow" }
Add-DefaultCmakeToPath | Out-Null
- # upgrade no-ops for a Scoop/Chocolatey/VS cmake; install to get a 4.2+ one.
+ # upgrade no-ops for a Scoop/Chocolatey/VS cmake.
if (-not (Test-CmakeCanDriveGenerator -Generator $CmakeGenerator)) {
try {
Invoke-SetupCommand { winget install Kitware.CMake --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
@@ -10849,14 +9616,13 @@ if ($LocalLlamaCppLinked) {
substep "CMake can drive the $CmakeGenerator generator"
}
- # After the final VS generator, so the CUDA .targets land in the toolset cmake uses.
if ($HasNvidiaDriverEvidence) { Resolve-CudaToolkit -RequireOrExit }
Write-StudioLine ""
if ($HasNvidiaDriverEvidence) {
substep "building llama.cpp with CUDA support..."
} elseif ($HasROCm -or $script:ROCmGfxArch) {
- # A HIP source build needs the full HIP SDK; the per-gfx ROCm prebuilt already failed here.
+ # A HIP source build needs the full HIP SDK.
$_amdArch = if ($script:ROCmGfxArch) { $script:ROCmGfxArch } else { "ROCm" }
substep "[WARN] AMD GPU ($_amdArch) detected, but the GPU-accelerated ROCm" "Yellow"
substep " llama.cpp prebuilt could not be installed -- falling back to a CPU build." "Yellow"
@@ -10870,7 +9636,6 @@ if ($LocalLlamaCppLinked) {
substep "This typically takes 5-10 minutes on first build."
Write-StudioLine ""
- # Start total build timer
$totalSw = [System.Diagnostics.Stopwatch]::StartNew()
$prevEAP = $ErrorActionPreference
@@ -10889,7 +9654,6 @@ if ($LocalLlamaCppLinked) {
if ($tkDirName2 -match '^v(\d+)\.(\d+)') {
[Environment]::SetEnvironmentVariable("CUDA_PATH_V$($Matches[1])_$($Matches[2])", $CudaToolkitRoot, 'Process')
}
- # Also re-assert CUDA_PATH and CudaToolkitDir in case they were overwritten
[Environment]::SetEnvironmentVariable('CUDA_PATH', $CudaToolkitRoot, 'Process')
[Environment]::SetEnvironmentVariable('CudaToolkitDir', "$CudaToolkitRoot\", 'Process')
}
@@ -10935,29 +9699,22 @@ if ($LocalLlamaCppLinked) {
}
# -- Step A: Clone or pull llama.cpp --
-
$UseConcreteRef = ($ResolvedSourceRef -ne "latest" -and -not [string]::IsNullOrWhiteSpace($ResolvedSourceRef))
# --depth 1 makes llama.cpp stamp build 1 (#12798); set only once the tag is checked out.
$TagBuildNumber = if ($ResolvedSourceRef -match '^b(\d+)$') { $Matches[1] } else { $null }
$LlamaBuildNumber = $null
- # Denied must not read as "no checkout here": the fresh-clone branch ends in
- # a swap that recursively removes this tree and moves the temp one over it,
- # under "Continue" and unchecked, so an unreadable child would leave a
- # half-deleted install behind. Stop while that is still avoidable.
+ # Denied must not read as "no checkout": the swap would half-delete an unreadable tree.
$llamaGitState = Get-PathState -Path (Join-Path $LlamaCppDir ".git")
if ($llamaGitState -eq "Denied") {
Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install"
}
if ($llamaGitState -eq "Present") {
- # why: in-place git mutation (remote set-url, checkout -B, clean -fdx)
- # rewrites $LlamaCppDir; mirror the prebuilt and temp-dir-swap guards
- # so an unrelated workspace .git tree is never silently overwritten.
+ # In-place git mutation rewrites $LlamaCppDir, so require ownership on a custom root.
if ($RuntimeRootIsCustom) {
Assert-StudioOwnedOrAbsent -Path $LlamaCppDir -Label "llama.cpp install" -IsCustom $RuntimeRootIsCustom
}
Write-StudioLine " Syncing llama.cpp to $ResolvedSourceRef..." -ForegroundColor Gray
- # Always sync the remote URL so switching between default/fork sources works
Invoke-SetupCommand -AlwaysQuiet { git -C $LlamaCppDir remote set-url origin "$ResolvedSourceUrl.git" } | Out-Null
if ($LlamaPr) {
$gitFetchExit = Invoke-SetupCommand -AlwaysQuiet { git -C $LlamaCppDir fetch --depth 1 origin "pull/$LlamaPr/head" }
@@ -11027,7 +9784,7 @@ if ($LocalLlamaCppLinked) {
}
}
}
- # In-place git-sync must mark the tree, else a later Assert-StudioOwnedOrAbsent exits.
+ # Mark the tree, else a later Assert-StudioOwnedOrAbsent exits.
if ($BuildOk -and $RuntimeRootIsCustom) {
Mark-StudioOwned -Path $LlamaCppDir
}
@@ -11120,13 +9877,11 @@ if ($LocalLlamaCppLinked) {
$LlamaBuildNumber = $TagBuildNumber
}
}
- # Use temp dir for build; swap into $LlamaCppDir only after build succeeds
if ($BuildOk) {
$LlamaCppDir = $buildTmp
$BuildDir = Join-Path $LlamaCppDir "build"
}
}
-
# -- Step B: cmake configure --
if ($BuildOk) {
@@ -11142,7 +9897,6 @@ if ($LocalLlamaCppLinked) {
if ($VsInstallPath) {
$CmakeArgs += "-DCMAKE_GENERATOR_INSTANCE=$VsInstallPath"
}
- # Common flags
$CmakeArgs += '-DBUILD_SHARED_LIBS=OFF'
$CmakeArgs += '-DLLAMA_BUILD_TESTS=OFF'
$CmakeArgs += '-DLLAMA_BUILD_EXAMPLES=OFF'
@@ -11159,12 +9913,10 @@ if ($LocalLlamaCppLinked) {
$CmakeArgs += '-DLLAMA_CURL=OFF'
}
$CmakeArgs += '-DCMAKE_EXE_LINKER_FLAGS=/NODEFAULTLIB:LIBCMT'
- # CUDA flags -- only if GPU available, otherwise explicitly disable
if ($HasNvidiaDriverEvidence -and $NvccPath) {
- # UNSLOTH_LLAMA_CUDA_ARCHS ("120" or "89;86") forces the build arch, as setup.sh does.
$CudaArchOverride = if ($env:UNSLOTH_LLAMA_CUDA_ARCHS) { ($env:UNSLOTH_LLAMA_CUDA_ARCHS -replace '\s', '') } else { '' }
if ((-not $CudaArch) -and (-not $CudaArchOverride)) {
- # No compute capability (#5854): -DGGML_CUDA=ON with no arch builds PTX-only.
+ # -DGGML_CUDA=ON with no arch builds PTX-only.
substep "could not detect a CUDA compute capability; building CPU llama.cpp instead of a PTX-only binary (set UNSLOTH_LLAMA_CUDA_ARCHS=120 to force a CUDA build)." "Yellow"
$CmakeArgs += '-DGGML_CUDA=OFF'
} else {
@@ -11185,21 +9937,18 @@ if ($LocalLlamaCppLinked) {
$CmakeArgs += "-DCUDA_TOOLKIT_ROOT_DIR=$CudaToolkitRoot"
$CmakeArgs += "-DCMAKE_CUDA_COMPILER=$NvccPath"
if ($CudaArchOverride) {
- # Forced arch wins verbatim (no nvcc validation), matching setup.sh.
$CmakeArgs += "-DCMAKE_CUDA_ARCHITECTURES=$CudaArchOverride"
} elseif ($CudaArch) {
- # Validate nvcc actually supports this architecture
if (Test-NvccArchSupport -NvccExe $NvccPath -Arch $CudaArch) {
$CmakeArgs += "-DCMAKE_CUDA_ARCHITECTURES=$CudaArch"
} else {
- # Arch too new for this toolkit: fall back to the highest supported (PTX JITs).
+ # Arch too new for this toolkit: use the highest supported (PTX JITs).
$maxArch = Get-NvccMaxArch -NvccExe $NvccPath
if ($maxArch) {
$CmakeArgs += "-DCMAKE_CUDA_ARCHITECTURES=$maxArch"
substep "GPU is sm_$CudaArch but nvcc only supports up to sm_$maxArch" "Yellow"
substep "Building with sm_$maxArch (PTX will JIT for your GPU at runtime)" "Yellow"
}
- # else: omit flag entirely, let cmake pick defaults
}
}
}
@@ -11256,7 +10005,6 @@ if ($LocalLlamaCppLinked) {
}
# -- Step E: Build the DiffusionGemma visual server (optional, best-effort) --
- # Example target from llama.cpp PR #24423.
if ($BuildOk) {
$null = cmake --build $BuildDir --config Release --target llama-diffusion-gemma-visual-server -j $NumCpu 2>&1 | Out-String
}
@@ -11266,10 +10014,7 @@ if ($LocalLlamaCppLinked) {
Assert-StudioOwnedOrAbsent -Path $OriginalLlamaCppDir -Label "llama.cpp install" -IsCustom $RuntimeRootIsCustom
if ((Get-PathState -Path $OriginalLlamaCppDir) -ne "Absent") {
Remove-Item -LiteralPath $OriginalLlamaCppDir -Recurse -Force -ErrorAction SilentlyContinue
- # Any unreadable or locked child survives the removal, and Move-Item
- # then nests the build *inside* the leftovers instead of replacing
- # them. Both are non-terminating here, so check before destroying
- # more: the temp build is still whole at this point.
+ # Unreadable or locked leftovers would make Move-Item nest the build inside them.
$swapState = Get-PathState -Path $OriginalLlamaCppDir
if ($swapState -eq "Denied") {
Exit-PathAccessDenied -Path $OriginalLlamaCppDir -Label "llama.cpp install"
@@ -11282,8 +10027,7 @@ if ($LocalLlamaCppLinked) {
}
}
Move-Item -LiteralPath $LlamaCppDir -Destination $OriginalLlamaCppDir
- # A failed move is non-terminating too; without this setup would report
- # a build it never installed.
+ # A failed move is non-terminating too.
if ((Get-PathState -Path $LlamaCppDir) -ne "Absent") {
step "llama.cpp" "could not move the new build into $OriginalLlamaCppDir" "Red"
Exit-SetupFailure "llama.cpp build at $LlamaCppDir could not be moved into $OriginalLlamaCppDir" 3
@@ -11293,17 +10037,14 @@ if ($LocalLlamaCppLinked) {
$LlamaServerBin = Join-Path $BuildDir "bin\Release\llama-server.exe"
Mark-StudioOwned -Path $LlamaCppDir
} elseif (-not $BuildOk -and $LlamaCppDir -ne $OriginalLlamaCppDir) {
- # Build failed -- clean up temp dir, preserve existing install
if (Test-Path -LiteralPath $LlamaCppDir) { Remove-Item -LiteralPath $LlamaCppDir -Recurse -Force }
$LlamaCppDir = $OriginalLlamaCppDir
$BuildDir = Join-Path $LlamaCppDir "build"
$LlamaServerBin = Join-Path $BuildDir "bin\Release\llama-server.exe"
}
- # Restore ErrorActionPreference
$ErrorActionPreference = $prevEAP
- # Stop timer
$totalSw.Stop()
$totalMin = [math]::Floor($totalSw.Elapsed.TotalMinutes)
$totalSec = [math]::Round($totalSw.Elapsed.TotalSeconds % 60, 1)
@@ -11370,17 +10111,10 @@ substep "(add -H 0.0.0.0 for LAN / cloud access; exposes the raw port only, not
substep "(add -H 0.0.0.0 --cloudflare for a public Cloudflare HTTPS link, or --secure to keep the raw port private; anyone with the API key can run code)"
Write-StudioLine ""
-# Exit non-zero for degraded llama.cpp only under install.ps1; 'studio update' stays successful.
+# Non-zero for degraded llama.cpp only under install.ps1; 'studio update' stays successful.
if ($script:LlamaCppDegraded -and $env:SKIP_STUDIO_BASE -eq "1") {
- # Tauri mode reports instead of aborting, exactly as setup.sh does. install.ps1
- # turns any non-zero status from here into Exit-InstallFailure, and install.rs
- # turns that into "Installation failed", so on Windows too a single transient
- # prebuilt download failure would throw away a first-launch install whose own
- # footer just said complete. [TAURI:PROGRESS] (not [TAURI:STEP], which would
- # push the frontend step counter past the seven INSTALL_STEPS entries) reaches
- # the user as install-progress-detail text.
- # DIAG as well: the progress detail is cleared by the next install-step, so only the
- # marker can still answer "why is GGUF missing" afterwards.
+ # Tauri mode reports instead of aborting, as setup.sh does: a non-zero exit fails the whole install.
+ # [TAURI:PROGRESS], not [TAURI:STEP], which would push the step counter past INSTALL_STEPS.
if (@("1", "true") -contains $env:UNSLOTH_TAURI_MODE) {
[Console]::Out.WriteLine("[TAURI:PROGRESS] llama.cpp unavailable; GGUF inference is disabled until 'unsloth studio update' succeeds")
[Console]::Out.WriteLine("[TAURI:DIAG] llama_cpp=unavailable")
diff --git a/studio/setup.sh b/studio/setup.sh
index 0edd7f91fa9..0368157f831 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -37,9 +37,7 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
RULE=$(printf '\342\224\200%.0s' {1..52})
# ── Parse flags ──
-# --local: install from the local repo checkout (overlays unsloth as editable
-# and unsloth-zoo from git main). Mirrors install.sh --local for the Colab
-# path that runs setup.sh directly without going through install.sh.
+# --local: overlay unsloth editable and unsloth-zoo from git main (mirrors install.sh --local).
# ── Parse flags ──
if [ "$#" -gt 0 ]; then
for _arg in "$@"; do
@@ -53,21 +51,8 @@ if [ "$#" -gt 0 ]; then
fi
# ── Maintainer-editable defaults ──────────────────────────────────────────
-# Change these in the GitHub-hosted script so all users get updated defaults.
-# User environment variables always override these baked-in values.
-# _DEFAULT_LLAMA_PR_FORCE : PR number to build by default ("" = normal path)
-# _DEFAULT_LLAMA_SOURCE : git clone URL for source builds
-# _DEFAULT_LLAMA_TAG : llama.cpp ref to build ("latest" = newest release,
-# "master" = bleeding-edge, "bNNNN" = specific tag)
-# Prefer "latest" over "master" -- "master" bypasses
-# the prebuilt resolver (no matching GitHub release),
-# forces a source build, and causes HTTP 422 errors.
-# Only use "master" temporarily when the latest release
-# is missing support for a new model architecture.
-# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "cuda", "vulkan",
-# "hip", or "rocm". Concrete values select and persist a
-# backend across updates; "auto" restores detection.
-# Overrides Unsloth's Settings > System selection.
+# Maintainer-editable defaults; user env vars override.
+# Prefer _DEFAULT_LLAMA_TAG=latest: master bypasses the prebuilt resolver and forces a source build.
# ──────────────────────────────────────────────────────────────────────────
_DEFAULT_LLAMA_PR_FORCE=""
_DEFAULT_LLAMA_SOURCE="https://github.com/ggml-org/llama.cpp"
@@ -89,9 +74,7 @@ else
fi
# ── Output helpers ──
-# Consistent column layout: 2-space indent, 15-char label (fits llama-quantize), then value.
-# Usage: step <label> <message> [color] (color defaults to C_OK)
-# Usage: substep <message> [color] (color defaults to C_DIM)
+# Usage: step <label> <message> [color]; substep <message> [color]
step() { printf " ${C_DIM}%-15.15s${C_RST}${3:-$C_OK}%s${C_RST}\n" "$1" "$2"; }
substep() { printf " %-15s${2:-$C_DIM}%s${C_RST}\n" "" "$1"; }
@@ -101,9 +84,8 @@ setup_fail() {
[ "$exit_code" -ne 0 ] || exit_code=1
local message
message=$(printf '%s' "$*" | tr '\r\n' ' ')
- # Match setup.ps1: update.rs sets UNSLOTH_TAURI_UPDATE everywhere and promotes
- # this line over the generic "Update exited with code N". Test each variable
- # separately: one joined subject lets a comma in either value alias the other arm.
+ # Mirrors setup.ps1 (update.rs promotes this line). Test each variable separately: one
+ # joined subject lets a comma alias the other arm.
local tauri_marker=0
case "${UNSLOTH_TAURI_MODE:-0}" in 1|true) tauri_marker=1 ;; esac
case "${UNSLOTH_TAURI_UPDATE:-0}" in 1|true) tauri_marker=1 ;; esac
@@ -114,10 +96,8 @@ setup_fail() {
}
# ── Helper: can the controlling terminal actually be opened for reading? ──
-# `test -r` only checks permission bits, which look fine in containers and
-# systemd units where open() then fails with ENXIO. Probe with a real open.
-# Mirrors install.sh's _can_read_tty; defined here too because setup.sh runs
-# as its own process (install.sh invokes it, it does not source it).
+# `test -r` passes in containers where open() fails with ENXIO; probe with a real open.
+# Mirrors install.sh's _can_read_tty (setup.sh runs as its own process).
_can_read_tty() {
( : </dev/tty ) >/dev/null 2>&1
}
@@ -305,8 +285,7 @@ _SETUP_PROBE_TARGET=""
_SETUP_PROBE_PID=""
_SETUP_PROBE_PREV_TRAP=""
-# Bash needs `--` before a negative process-group ID.
-# Omit it for positive PIDs to support dash, which rejects `--`.
+# Bash needs `--` before a negative process-group ID; dash rejects it.
_setup_probe_signal_target() {
case "$2" in
-*) kill "-$1" -- "$2" 2>/dev/null || : ;;
@@ -314,7 +293,6 @@ _setup_probe_signal_target() {
esac
}
-# Send TERM, then KILL after $3 seconds. $1 is the target PID/group; $2 is the PID to watch.
_setup_probe_terminate() {
_supt_grace=0
_setup_probe_signal_target TERM "$1"
@@ -322,12 +300,10 @@ _setup_probe_terminate() {
sleep 1
_supt_grace=$((_supt_grace + 1))
done
- # Recheck before KILL to reduce the risk of signalling a reused PID.
if kill -0 "$2" 2>/dev/null; then _setup_probe_signal_target KILL "$1"; fi
unset _supt_grace
}
-# Preserve the caller's signal handlers while the watchdog owns probe cleanup.
_setup_probe_restore_trap() {
_SETUP_PROBE_TARGET=""
_SETUP_PROBE_PID=""
@@ -340,39 +316,31 @@ _setup_probe_restore_trap() {
}
_setup_probe_on_signal() {
- # Stop the probe on cancellation, with a shorter grace period.
if [ -n "${_SETUP_PROBE_TARGET:-}" ] && [ -n "${_SETUP_PROBE_PID:-}" ]; then
_setup_probe_terminate "$_SETUP_PROBE_TARGET" "$_SETUP_PROBE_PID" 2
wait "$_SETUP_PROBE_PID" 2>/dev/null || :
fi
_setup_probe_restore_trap
- # Re-deliver the signal to the restored handler or default action.
kill -s "$1" "$$" 2>/dev/null || :
}
-# Probe $1 with stdin closed and a 20 s timeout, plus 5 s to terminate.
-# Save stdout to $2 (default /dev/null) to avoid re-probing for the version.
-# Use a file so lingering children cannot hold an output pipe open.
+# Bounded --version probe; output goes to a file so lingering children cannot hold a pipe.
_setup_probe_version() {
_supe_secs="${_SETUP_PROBE_SECONDS:-20}"
_supe_out="${2:-/dev/null}"
- # Use GNU timeout when available, otherwise the watchdog below.
if command -v timeout >/dev/null 2>&1 && timeout -k 1 5 true >/dev/null 2>&1; then
timeout -k 5 "$_supe_secs" "$1" --version >"$_supe_out" 2>/dev/null </dev/null
_supe_rc=$?
- # Normalize SIGKILL after the grace period to the watchdog's timeout status.
if [ "$_supe_rc" -eq 137 ]; then _supe_rc=124; fi
return $_supe_rc
fi
- # Temporarily enable monitor mode to signal the probe and its children as a group.
_supe_monitor=off
case "$-" in *m*) _supe_monitor=on ;; esac
[ "$_supe_monitor" = on ] || set -m 2>/dev/null || :
"$1" --version >"$_supe_out" 2>/dev/null </dev/null &
_supe_pid=$!
[ "$_supe_monitor" = on ] || set +m 2>/dev/null || :
- # Signal a group only if it differs from setup's own group; otherwise use the PID.
- # Strip spaces without external tools so this works on a minimal PATH.
+ # Signal a group only if it differs from setup's own group.
_supe_target="$_supe_pid"
if command -v ps >/dev/null 2>&1; then
_supe_pgid=$(ps -o pgid= -p "$_supe_pid" 2>/dev/null)
@@ -723,19 +691,12 @@ _mirror_spare_export() {
# ── END mirror fallback ──
# ── Corporate-mirror / proxy escape hatch for the frontend npm/bun install (#6491) ──
-# studio/frontend/.npmrc pins registry=https://registry.npmjs.org/ as a supply-chain
-# lock. A project-level pin overrides a corporate user's ~/.npmrc proxy, so the install
-# hits npmjs.org directly and a firewall returns 403. UNSLOTH_NPM_REGISTRY is a
-# deliberate opt-in: when set we thread it as `--registry <url>` into every npm/bun
-# install. `--registry` is the highest-precedence override for BOTH tools and leaves
-# min-release-age / save-exact in force. Empty array (the default) expands to nothing
-# under `set -u`, so normal installs are unchanged.
+# studio/frontend/.npmrc pins the registry (supply-chain lock); UNSLOTH_NPM_REGISTRY opts into
+# --registry for npm/bun installs. Empty array expands to nothing under set -u.
_NPM_REGISTRY_ARGS=()
if [ -n "${UNSLOTH_NPM_REGISTRY:-}" ]; then
_NPM_REGISTRY_ARGS=(--registry "$UNSLOTH_NPM_REGISTRY")
fi
-# Failure-path capture log consumed by _suggest_npm_registry. Set to a temp file
-# around the npm/bun installs; "" elsewhere so unrelated run_quiet calls don't capture.
_CAPTURE_LOG=""
_npm_mirror_retry() {
@@ -745,13 +706,10 @@ _npm_mirror_retry() {
_NPM_REGISTRY_ARGS=(--registry "$UNSLOTH_NPM_REGISTRY")
}
-# Local errno is matched on npm's code line only (cleanup warnings carry EPERM after
-# network failures too) and before the network check, since FetchError names
-# registry.npmjs.org even on a local error (#8725). Keep in sync with setup.ps1.
+# Match local errno on npm's code line only, before the network check (FetchError names the
+# registry even on local errors). Keep in sync with setup.ps1.
_NPM_LOCAL_FAILURE_RE='npm (error|ERR!) code (EACCES|EPERM|EBUSY|ENOSPC|ENFILE|EMFILE)|operation was rejected by your operating system'
-# $1 = "socket": FetchError with no "npm error path" line, i.e. the OS refused node's
-# socket (per-program firewall / antivirus rule). A cache write failure has a path.
_suggest_npm_local_failure() {
printf '\n' >&2
if [ "${1:-}" = socket ]; then
@@ -764,15 +722,10 @@ _suggest_npm_local_failure() {
return 0
}
-# Print actionable guidance when a frontend/OXC npm/bun install fails and the registry
-# lock is the likely cause (corporate firewall/proxy). No-op once the user has opted in
-# via UNSLOTH_NPM_REGISTRY. This only guides; the mirror fallback does any switching.
-# $1 = path to a captured install log (may be empty/missing).
+# Guidance only when the registry lock is the likely cause; the mirror fallback does any switching.
_suggest_npm_registry() {
local _log="${1:-}"
- # Before the UNSLOTH_NPM_REGISTRY opt-out: a mirror does not unlock a cache.
local _plain=""
- # Strip ANSI colour (npm color=always) so the code-line match still sees "npm error code".
if [ -n "$_log" ] && [ -s "$_log" ]; then _plain="$(sed "s/$(printf '\033')\[[0-9;]*m//g" "$_log")"; fi
if [ -n "$_plain" ] && grep -Eq "$_NPM_LOCAL_FAILURE_RE" <<<"$_plain"; then
if grep -q 'FetchError' <<<"$_plain" && ! grep -Eq 'npm (error|ERR!) path ' <<<"$_plain"; then
@@ -783,16 +736,11 @@ _suggest_npm_registry() {
return 0
fi
[ -n "${UNSLOTH_NPM_REGISTRY:-}" ] && return 0
- # If we captured output and it does NOT look like a registry/network problem, stay
- # quiet -- the raw error already shown is more useful than a misleading hint.
if [ -n "$_log" ] && [ -s "$_log" ] \
&& ! grep -Eqi '40[13]|ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ConnectionRefused|failed to resolve|registry\.npmjs\.org|getaddrinfo|tunneling socket|network|proxy|self.?signed|unable to (get|verify)' "$_log"; then
return 0
fi
- # Best-effort: surface a mirror the user already configured (env or ~/.npmrc).
- # Read npm config from / (a dir with no project .npmrc) so the frontend's pinned
- # registry= does not mask the user's ~/.npmrc / global mirror -- the caller is
- # still inside studio/frontend when this runs.
+ # Read npm config from / so the frontend's pinned registry does not mask the user's mirror.
local _mirror="${NPM_CONFIG_REGISTRY:-${npm_config_registry:-}}"
if [ -z "$_mirror" ] && command -v npm >/dev/null 2>&1; then
_mirror="$( (cd / 2>/dev/null && npm config get registry) 2>/dev/null || true )"
@@ -878,8 +826,7 @@ run_quiet_no_exit() {
}
_nvcc_meets_llama_minimum() {
- # Echo "ok|too_old|unknown" then the parsed "X.Y" version, one per line.
- # llama.cpp needs CUDA toolkit >= 12.4 (#4437; setup.ps1 aborts via #4517).
+ # Echo ok|too_old|unknown then X.Y. llama.cpp needs CUDA toolkit >= 12.4.
_nvcc_bin=$1
[ -n "$_nvcc_bin" ] || { echo "unknown"; echo ""; return 0; }
_raw=$("$_nvcc_bin" --version 2>/dev/null \
@@ -901,13 +848,7 @@ _nvcc_meets_llama_minimum() {
echo "$_raw"
}
-# Echo a ';'-separated CUDA arch list (e.g. "86;120"). Override ($2,
-# UNSLOTH_LLAMA_CUDA_ARCHS) wins verbatim; else parse+dedupe compute_cap text
-# ($1). Empty means "no arch detected", so the caller builds CPU instead of a
-# PTX-only binary that fails on an old driver (#5854).
-# Every GPU's capability from nvidia_probe.py, one per line; nothing when the probe is off or
-# absent, or when one listed GPU has no readable capability (a partial list would build kernels
-# for part of the machine).
+# Empty capability list means build CPU, not a PTX-only binary; a partial list yields nothing.
_probe_compute_caps() {
[ -f "$SCRIPT_DIR/nvidia_probe.py" ] && command -v python3 >/dev/null 2>&1 || return 0
_setup_run_smi python3 -I "$SCRIPT_DIR/nvidia_probe.py" 2>/dev/null | awk '
@@ -939,15 +880,8 @@ _resolve_cuda_archs() {
printf '%s' "$_archs"
}
-# Reserved for the OS, and budgeted per compile job, both in MiB. Measured on
-# llama.cpp with CUDA 13.1, the heaviest translation units (flash-attention
-# template instances) peak at ~400 MiB RSS each, and -j20 peaked at 8.2 GiB
-# across ~30 processes, since nvcc forks cicc and ptxas. 2048 is deliberately
-# above that: it must also cover MSVC and hipcc, older and far heavier CUDA
-# toolkits (ggml-org/llama.cpp#17844 climbs past 16 GiB), and the link step.
-# Erring high costs build time; erring low costs the machine.
-# The build dir is renamed into place, so CMake's build-tree RUNPATH dies at the mv (#12392):
-# $ORIGIN finds the sibling libllama*.so; USE_LINK_PATH keeps toolchain dirs (ROCm, CUDA, Nix).
+# The build dir is renamed into place, so CMake's build-tree RUNPATH dies; use $ORIGIN.
+# USE_LINK_PATH keeps toolchain dirs (ROCm, CUDA, Nix).
_llama_relocatable_rpath_args() {
case "$(uname -s 2>/dev/null)" in
Linux) printf '%s' '-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH=$ORIGIN -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON' ;;
@@ -955,12 +889,11 @@ _llama_relocatable_rpath_args() {
esac
}
+# MiB for the OS and per compile job; 2048 is above measured nvcc peaks to cover MSVC, hipcc, link.
_LLAMA_BUILD_RESERVE_MB=2048
_LLAMA_BUILD_MB_PER_JOB=2048
-# Echo the cmake -j count. Args: core count, total RAM MiB ("" = unreadable,
-# which keeps the old core-count behaviour). UNSLOTH_LLAMA_BUILD_JOBS wins.
-# Pure, so the tests can drive it without faking hardware.
+# Pure (args: cores, RAM MiB) so tests can drive it. UNSLOTH_LLAMA_BUILD_JOBS wins.
_llama_jobs_for() {
local _cores=$1 _mem_mb=$2 _jobs
if [[ "${UNSLOTH_LLAMA_BUILD_JOBS:-}" =~ ^[0-9]+$ ]] && [ "$UNSLOTH_LLAMA_BUILD_JOBS" -ge 1 ]; then
@@ -978,11 +911,7 @@ _llama_jobs_for() {
printf '%s' "$_jobs"
}
-# Echo the first line of $1 with whitespace stripped, or nothing. A builtin read
-# plus an expansion, not `head | tr`: this is best-effort on the install's
-# critical path under `set -euo pipefail`, and a failing pipeline took the whole
-# install down. -r alone does not rule that out (a directory passes it, and a
-# cgroup can be torn down between the test and the open); -f does.
+# Builtin read, not `head | tr`: a failing pipeline under set -euo pipefail aborted installs.
_cg_read() {
local _v=""
[ -f "$1" ] && [ -r "$1" ] || return 0
@@ -991,20 +920,14 @@ _cg_read() {
return 0
}
-# Echo $1 when it is a real limit. v2 writes "max"; v1 a near-2^63 sentinel.
-# Zero is a limit, not the absence of one: memory.high throttles and never
-# invokes the OOM killer (cgroup-v2.rst), so a process runs happily under
-# MemoryHigh=0 and must not then be handed its full core count.
+# v2 writes "max", v1 a near-2^63 sentinel. Zero is a real limit (memory.high).
_cg_limit() {
[[ "$1" =~ ^[0-9]+$ ]] || return 0
[ "$1" -lt 4611686018427387904 ] && printf '%s' "$1"
return 0
}
-# Echo "$1/$2" and every ancestor up to $1, innermost first, NUL-delimited: a
-# mount point may contain a newline, so a line-delimited list would split one
-# path into two. dirname is inlined for the same reason ($() eats a trailing
-# newline).
+# NUL-delimited: a mount point may contain a newline.
_cg_dirs() {
local _root=$1 _cur
if [ -n "${2:-}" ] && [ "$2" != "/" ]; then
@@ -1020,10 +943,7 @@ _cg_dirs() {
printf '%s\0' "$_root"
}
-# The mountinfo path decoder as an awk function, in one place so its two callers
-# cannot drift. mountinfo escapes space, tab, newline and backslash as \040 and
-# friends; strtonum is a gawk extension, so the octal maths is done by hand to
-# also run under the mawk and BSD awk that Debian and macOS ship.
+# Shared awk decoder for mountinfo escapes; no strtonum so it runs under mawk and BSD awk.
_cg_unesc_prog() {
cat <<'_CG_AWK_UNESC'
function unesc(s, out, i, c, o, v) {
@@ -1041,22 +961,14 @@ _cg_unesc_prog() {
_CG_AWK_UNESC
}
-# Echo $1 with its mountinfo escapes decoded. Decoding is deliberately late:
-# \011 and \012 decode to the very tab and newline that delimit the records
-# below, so decoding at the read would split one record into two. An escaped
-# path holds neither, so it travels intact and is decoded here.
+# Decode late: \011 and \012 decode to the delimiters of the records below.
_cg_unesc() {
[ -n "$1" ] || return 0
printf '%s\n' "$1" | awk "$(_cg_unesc_prog)"'{ printf "%s", unesc($0); exit }' || true
return 0
}
-# Echo every matching cgroup hierarchy as "<mount root><tab><mount point>", both
-# still escaped. $1 = a mountinfo file, $2 = "cgroup2" or a v1 controller name.
-# mountinfo is "... <root> <mountpoint> <opts> [tags] - <fstype> <source>
-# <superopts>", and a v1 hierarchy lists its controllers in the super options,
-# so a co-mounted or relocated one is found by name rather than assumed to sit
-# at <root>/<name>.
+# v1 hierarchies are found by controller name in super options, not assumed at <root>/<name>.
_cg_mounts() {
[ -r "$1" ] || return 0
awk -v want="$2" '
@@ -1074,11 +986,7 @@ _cg_mounts() {
return 0
}
-# Echo the process's path within a mount, or nothing when the mount does not
-# expose it. Args: mount root, process cgroup path. A bind-mounted subtree shows
-# a mount root like /slice while /proc/self/cgroup reports /slice/job and the
-# files sit at <mountpoint>/job, so joining the two unmapped walks a path that
-# does not exist and settles on an outer limit instead of the binding one.
+# Map the process cgroup path under a bind-mounted subtree root.
_cg_rel() {
local _root=$1 _rel=$2
[ -n "$_rel" ] || return 0
@@ -1086,25 +994,17 @@ _cg_rel() {
case "$_rel" in
"$_root") printf '%s' "/" ;;
"$_root"/*) printf '%s' "${_rel#"$_root"}" ;;
- # Not under this mount's root: nothing here describes this process.
*) : ;;
esac
return 0
}
-# Echo EVERY "<root><tab><point>" on stdin whose root contains the process path
-# ($1), still escaped, one per line; or the first seen when none does. A
-# hierarchy can be mounted twice with different subtree roots (rootless podman
-# inside rootless podman): taking the first steps past the binding mount, and
-# taking only the most specific hides a limit above the narrower mount's root.
-# So every containing mount is inspected and the smallest allowance wins, which
-# makes the answer order-independent.
+# Every containing mount is inspected and the smallest allowance wins (nested rootless podman).
_cg_pick_mounts() {
local _rel=$1 _root _point _droot _any="" _firstroot="" _firstpoint=""
while IFS=$'\t' read -r _root _point; do
[ -n "$_point" ] || continue
if [ -z "$_firstpoint" ]; then _firstroot=$_root; _firstpoint=$_point; fi
- # /proc/self/cgroup is not escaped, so the root is compared decoded.
_droot=$(_cg_unesc "$_root")
[ -n "$(_cg_rel "$_droot" "$_rel")" ] || continue
printf '%s\t%s\n' "$_root" "$_point"
@@ -1114,14 +1014,8 @@ _cg_pick_mounts() {
return 0
}
-# Echo the memory free under the binding cgroup limit in MiB, or nothing. Args:
-# fallback cgroup root, /proc/self/cgroup path, /proc/self/mountinfo path; all
-# arguments so the tests can drive a real tree. Mirrors dataset_num_proc.py:
-# reading the hierarchy root alone only works with a private cgroup namespace,
-# and under Slurm, systemd or --cgroupns=host the binding limit is the process's
-# own path or an ancestor's. Each limit pairs with the usage of the directory
-# that set it, since an ancestor's usage counts siblings this process cannot
-# see, and the smallest remaining allowance wins.
+# Free MiB under the binding cgroup limit. Mirrors dataset_num_proc.py: each limit pairs with
+# its own directory's usage, and the smallest remaining allowance wins.
_cgroup_free_mb() {
local _root=$1 _proc=$2 _mnt=${3:-} _rel _dir _used _limit _free _name _min=""
local _v2rel _v1rel _v2mnts _v1mnts _mroot _mpoint
@@ -1132,9 +1026,7 @@ _cgroup_free_mb() {
if [ -z "$_min" ] || [ "$_free" -lt "$_min" ]; then _min=$_free; fi
return 0
}
- # The process path is read first so the right mount can be chosen among
- # several. Only the first two colons are delimiters: a systemd unit name may
- # contain one, and -F: with $3 would truncate the path there.
+ # Only the first two colons delimit: a systemd unit name may contain one.
_v2rel=$(awk '/^0::/ { print substr($0, 4); exit }' "$_proc" 2>/dev/null || true)
_v1rel=$(awk '
{
@@ -1145,16 +1037,12 @@ _cgroup_free_mb() {
}' "$_proc" 2>/dev/null || true)
_v2mnts=$(_cg_mounts "$_mnt" cgroup2 | _cg_pick_mounts "$_v2rel")
_v1mnts=$(_cg_mounts "$_mnt" memory | _cg_pick_mounts "$_v1rel")
- # Fall back to the conventional layout when mountinfo is unreadable.
[ -n "$_v2mnts" ] || _v2mnts=$(printf '/\t%s' "$_root")
[ -n "$_v1mnts" ] || _v1mnts=$(printf '/\t%s' "$_root/memory")
- # The v2 line is "0::<path>"; systemd hybrid mode adds v1 lines alongside.
while IFS=$'\t' read -r _mroot _mpoint; do
[ -n "$_mpoint" ] || continue
- # Decode now that a single path is in hand, after it survived the tab-
- # and newline-delimited transport. The sentinel keeps $() from eating a
- # trailing newline.
+ # The sentinel keeps $() from eating a trailing newline.
_mroot=$(_cg_unesc "$_mroot"; printf X); _mroot=${_mroot%X}
_mpoint=$(_cg_unesc "$_mpoint"; printf X); _mpoint=${_mpoint%X}
[ -d "$_mpoint" ] || continue
@@ -1168,7 +1056,6 @@ _cgroup_free_mb() {
done < <(_cg_dirs "$_mpoint" "$_rel")
done <<< "$_v2mnts"
- # v1 is "<id>:<controllers>:<path>", and mounts are often combined.
while IFS=$'\t' read -r _mroot _mpoint; do
[ -n "$_mpoint" ] || continue
_mroot=$(_cg_unesc "$_mroot"; printf X); _mroot=${_mroot%X}
@@ -1186,15 +1073,8 @@ _cgroup_free_mb() {
return 0
}
-# macOS available memory in MiB, read from vm_stat on stdin; empty when the
-# output does not parse. free + inactive is the reclaim-aware equivalent of
-# MemAvailable, and the page size is read from the header rather than assumed to
-# be 4096, which is wrong on Apple Silicon. Only those two: xnu's
-# osfmk/mach/vm_statistics.h says speculative pages "are already accounted for
-# in free_count", and purgeable is an attribute of a page rather than a queue,
-# so a volatile page is already counted on active or inactive. Adding either
-# double-counts. Under-counting is the safe direction for a cap: it costs build
-# time on a busy Mac rather than the machine.
+# free + inactive, page size from the header (not 4096 on Apple Silicon); speculative and
+# purgeable are already counted, so adding them double-counts.
_vm_stat_avail_mb() {
awk '
/page size of/ {
@@ -1208,27 +1088,16 @@ _vm_stat_avail_mb() {
return 0
}
-# Usable RAM in MiB; empty when it cannot be read. MemAvailable, not MemTotal: a
-# workstation with 8 GiB already resident cannot host a 14 GiB compile just
-# because 16 GiB is fitted. /proc is not namespaced either, so a lower cgroup
-# allowance wins. $1 is the meminfo file, an argument like every other reader's
-# path here so the tests can pin a number instead of racing the live one.
+# MemAvailable, not MemTotal; a lower cgroup allowance wins.
_usable_ram_mb() {
local _meminfo=${1:-/proc/meminfo} _bytes _mb="" _free _avail
if [ -r "$_meminfo" ]; then
- # MemAvailable counts reclaimable page cache; MemFree does not. Absent
- # before Linux 3.14, where MemTotal is the only thing to go on. `|| true`
- # because bash applies errexit to a failing assignment in POSIX mode, and
- # an unreadable meminfo must cost the cap, not the install.
+ # Absent before Linux 3.14. `|| true`: errexit applies to a failing assignment in POSIX mode.
_mb=$(awk '/^MemAvailable:/ { printf "%d", $2 / 1024; exit }' "$_meminfo") || true
[ -n "$_mb" ] || _mb=$(awk '/^MemTotal:/ { printf "%d", $2 / 1024; exit }' "$_meminfo") || true
elif _bytes=$(sysctl -n hw.memsize 2>/dev/null); then
[[ "$_bytes" =~ ^[0-9]+$ ]] && _mb=$(( _bytes / 1048576 ))
- # macOS has no MemAvailable, so hw.memsize is installed RAM and would
- # hand a busy Mac a budget it cannot honour; vm_stat is the equivalent,
- # with installed RAM as the fallback when it does not parse. Zero is
- # kept: a Mac with nothing reclaimable should build at 1 job, not take
- # its full core count.
+ # macOS: vm_stat, falling back to hw.memsize. Zero is kept so a busy Mac builds at 1 job.
_avail=$(vm_stat 2>/dev/null | _vm_stat_avail_mb || true)
if [[ "$_avail" =~ ^[0-9]+$ ]]; then _mb=$_avail; fi
fi
@@ -1246,9 +1115,7 @@ _llama_build_jobs() {
"$(_usable_ram_mb)"
}
-# Opt-in staged GPU smoke test after a source build (#5854 gap 2). Default off:
-# llama-server's first GPU forward pass JIT-compiles CUDA kernels and stalls
-# installs for minutes on Blackwell. Same env as install_llama_prebuilt.py.
+# Opt-in: llama-server's first GPU pass JIT-compiles CUDA kernels and stalls installs.
_staged_validation_enabled() {
local _raw="${UNSLOTH_LLAMA_STAGED_VALIDATION:-}"
# Match install_llama_prebuilt.py staged_validation_enabled(): strip + lowercase.
@@ -1259,8 +1126,6 @@ _staged_validation_enabled() {
esac
}
-# Map the source-build GPU backend to install_llama_prebuilt --install-kind so
-# validate_server enables --n-gpu-layers for the right backends.
_source_smoke_install_kind() {
if [ "${_TRY_METAL_CPU_FALLBACK:-false}" = true ]; then
printf '%s' "macos-arm64"
@@ -1278,8 +1143,7 @@ _source_smoke_install_kind() {
esac
}
-# Run a GPU probe under a 10s timeout when `timeout` is available so a wedged
-# NVIDIA driver cannot hang setup; fall back to a bare call where it is not.
+# 10s timeout so a wedged NVIDIA driver cannot hang setup.
_setup_run_smi() {
if command -v timeout >/dev/null 2>&1; then
timeout 10 "$@"
@@ -1288,28 +1152,15 @@ _setup_run_smi() {
fi
}
-# Returns 0 when CUDA_VISIBLE_DEVICES is set to "" or "-1", i.e. every NVIDIA
-# device is deliberately hidden (mixed AMD+NVIDIA hosts steering work to the
-# AMD card). Unset means all devices visible. nvidia-smi ignores this env var,
-# so the probes below cannot see the distinction on their own.
+# CUDA_VISIBLE_DEVICES "" or "-1" hides every NVIDIA device; nvidia-smi ignores it.
_setup_cvd_hides_nvidia() {
[ "${CUDA_VISIBLE_DEVICES+set}" = "set" ] || return 1
_setup_cvd_trim=$(printf '%s' "$CUDA_VISIBLE_DEVICES" | tr -d '[:space:]')
[ -z "$_setup_cvd_trim" ] || [ "$_setup_cvd_trim" = "-1" ]
}
-# Returns 0 when an NVIDIA GPU is present and usable. Primary probe is
-# `nvidia-smi -L` (timeout-bounded). Fallback is /proc/driver/nvidia/gpus,
-# which the driver populates per GPU regardless of nvidia-smi state -- handles
-# PATH gaps and driver init races. Mirrors install.sh _has_usable_nvidia_gpu
-# (PR 6174) so setup routes the same way as the torch installer. A GPU hidden
-# via CUDA_VISIBLE_DEVICES=""/-1 counts as NOT usable (matches
-# install_llama_prebuilt.py has_usable_nvidia), so the AMD probes still run
-# and a mixed host steered to its AMD card keeps the ROCm route.
-# Present, mask or no mask. The usable probe is this plus the CUDA_VISIBLE_DEVICES check.
+# Present regardless of mask; falls back to /proc/driver/nvidia/gpus. Mirrors install.sh.
_setup_has_physical_nvidia_gpu() {
- # Reset here rather than in the usable wrapper: this is where the bounded -L call
- # lives, and both entry points reach the probe through it.
_setup_nv_smi_wedged=""
_setup_nvsmi=""
if command -v nvidia-smi >/dev/null 2>&1; then
@@ -1318,9 +1169,7 @@ _setup_has_physical_nvidia_gpu() {
_setup_nvsmi="/usr/bin/nvidia-smi"
fi
if [ -n "$_setup_nvsmi" ]; then
- # Captured rather than piped so `timeout`'s own 124 stays visible. A wedged
- # driver still detects as a GPU through /proc below, and the banner must not
- # then pay the 10s bound a second time asking a hung nvidia-smi for a name.
+ # Captured, not piped, so timeout's 124 stays visible.
_setup_nv_l_rc=0
_setup_nv_l_out=$(_setup_run_smi "$_setup_nvsmi" -L 2>/dev/null) || _setup_nv_l_rc=$?
if [ "$_setup_nv_l_rc" = "124" ]; then
@@ -1343,42 +1192,26 @@ _setup_has_physical_nvidia_gpu() {
return 1
}
-# Row index of the GPU whose UUID starts with $1, or empty. NVIDIA allows a UUID to
-# be abbreviated to any unique leading portion, hence the prefix match.
+# NVIDIA allows a UUID abbreviated to any unique leading portion.
_setup_nv_idx_from_uuid() {
- # NVIDIA accepts an abbreviation only when it is a UNIQUE leading portion, so a
- # prefix matching two cards selects NO device. Counting instead of stopping at the
- # first hit keeps the banner from naming one of them.
+ # A prefix matching two cards selects no device, so count matches.
_setup_run_smi "$_setup_nvsmi" --query-gpu=uuid --format=csv,noheader 2>/dev/null \
| awk -v want="$1" '
NF { gsub(/^[[:space:]]+|[[:space:]]+$/,""); if (index($0, want) == 1) { hits++; idx = NR-1 } }
END { if (hits == 1) print idx }' || true
}
-# Resolves the banner's NVIDIA fields into _setup_nv_name / _setup_nv_sm /
-# _setup_nv_driver, each empty when it could not be read. Mirrors install.sh's
-# _nv_banner_fields. Bounded, and fed the executable _setup_has_usable_nvidia_gpu
-# already resolved into $_setup_nvsmi: a wedged driver blocks nvidia-smi indefinitely,
-# and detection also succeeds via /usr/bin/nvidia-smi off PATH or via
-# /proc/driver/nvidia/gpus with no nvidia-smi at all.
+# Bounded, and uses the nvidia-smi already resolved: a wedged driver blocks it indefinitely.
_setup_nv_banner_fields() {
_setup_nv_name=""; _setup_nv_sm=""; _setup_nv_driver=""
_setup_nv_row=""; _setup_nv_cc=""; _setup_nv_ambiguous=""
[ -n "${_setup_nvsmi:-}" ] || return 0
- # Detection already waited out the full bound on this binary. Asking again cannot
- # succeed and would double the stall, so the banner keeps the vendor-only wording.
[ -z "${_setup_nv_smi_wedged:-}" ] || return 0
- # nvidia-smi ignores CUDA_VISIBLE_DEVICES, so its rows are the physical devices and
- # the mask has to be resolved against them by hand.
+ # nvidia-smi ignores CUDA_VISIBLE_DEVICES, so resolve the mask against its rows.
_setup_nv_idx=0
- # Set while nothing has IDENTIFIED a device: an ordinal, or a failed identity lookup
- # that fell back to one. Only an ordinal is order-dependent.
_setup_nv_by_ordinal=1
_setup_nv_vis="${CUDA_VISIBLE_DEVICES:-}"
- # Only the FIRST entry selects the device, and only IT decides the form of the mask.
- # CUDA truncates enumeration at the first invalid index, so the documented `2,-1`
- # means "device 2, then stop"; classifying the whole string would see the `-1`, call
- # it non-numeric, and send a plain ordinal down the UUID path.
+ # Only the first entry decides: CUDA stops at the first invalid index (`2,-1` = device 2).
_setup_nv_tok="${_setup_nv_vis%%,*}"
case "$_setup_nv_tok" in
'') ;;
@@ -1386,47 +1219,31 @@ _setup_nv_banner_fields() {
_setup_nv_by_ordinal=""
case "$_setup_nv_tok" in
MIG-GPU-*)
- # Pre-R470 MIG name, MIG-<GPU-UUID>/<gi>/<ci>: the parent UUID is
- # embedded, so it still matches a --query-gpu=uuid row.
+ # Pre-R470 MIG name embeds the parent UUID.
_setup_nv_tok="${_setup_nv_tok#MIG-}"; _setup_nv_tok="${_setup_nv_tok%%/*}"
_setup_nv_idx=$(_setup_nv_idx_from_uuid "$_setup_nv_tok") ;;
MIG-*)
- # R470 and later give each MIG instance its OWN opaque UUID, which
- # carries nothing of the parent, so --query-gpu=uuid can never match
- # it. `nvidia-smi -L` nests the instances under their GPU.
+ # R470+ MIG UUIDs carry nothing of the parent; `nvidia-smi -L` nests them.
_setup_nv_idx=$(_setup_run_smi "$_setup_nvsmi" -L 2>/dev/null | awk -v want="$_setup_nv_tok" '
/^GPU[[:space:]]+[0-9]+:/ { cur = $2 + 0 }
index($0, want) > 0 { print cur; exit }' || true) ;;
*)
_setup_nv_idx=$(_setup_nv_idx_from_uuid "$_setup_nv_tok") ;;
esac
- # An identity mask that does not resolve means CUDA selected NO device: an
- # abbreviation short enough to match two cards, or a UUID for a card that is
- # not here. Row 0 is not a fallback for that -- it is a different card.
+ # An unresolved identity mask selects no device; row 0 is a different card.
case "$_setup_nv_idx" in ''|*[!0-9]*) _setup_nv_idx=0; _setup_nv_ambiguous=1 ;; esac
;;
*) _setup_nv_idx="$_setup_nv_tok" ;;
esac
- # Canonicalise the ordinal before anything compares or subscripts with it.
- # `[` parses with strtol and ERRORS on a value wider than a long, printing a
- # shell diagnostic and skipping the range check below, so an absurd ordinal
- # would have named row 0. Clamped rather than rejected: 9999 is past any real
- # host, so it stays out of range and declines, which is the right answer.
+ # Clamp: `[` errors on values wider than a long and skips the range check.
_setup_nv_idx=$(printf '%s' "$_setup_nv_idx" \
| awk '{ n = $0 + 0; if (n < 0) n = 0; if (n > 9999) n = 9999; printf "%d", n }')
_setup_nv_all=$(_setup_run_smi "$_setup_nvsmi" --query-gpu=name,compute_cap,driver_version --format=csv,noheader 2>/dev/null || true)
_setup_nv_row=$(printf '%s\n' "$_setup_nv_all" \
| awk -v idx="$_setup_nv_idx" 'NF { a[n++]=$0 } END { if(idx>=n) idx=0; if(n>0) print a[idx+0] }')
[ -n "$_setup_nv_row" ] || return 0
- # A numeric entry is a CUDA ordinal, and CUDA's default CUDA_DEVICE_ORDER=FASTEST_FIRST
- # puts the fastest card at 0 and leaves the rest "unspecified", while nvidia-smi always
- # lists in PCI order. So an ordinal identifies an nvidia-smi row only when the order is
- # pinned to PCI_BUS_ID, or when the cards are interchangeable and every row gives the
- # same answer anyway. Compared on name and compute_cap, not the driver, which is
- # host-wide and identical on every row.
- # CUDA stops enumerating at the first invalid index, so an ordinal past the last
- # row exposes NO device at all. The awk above clamps to row 0 so the driver still
- # reads, but row 0 is not the selected card -- nothing is.
+ # CUDA defaults to FASTEST_FIRST but nvidia-smi lists in PCI order, so an ordinal maps to a row
+ # only under PCI_BUS_ID or identical cards. An ordinal past the last row exposes no device.
_setup_nv_rowcount=$(printf '%s\n' "$_setup_nv_all" | awk 'NF { n++ } END { print n+0 }')
if [ -n "$_setup_nv_by_ordinal" ] && [ "$_setup_nv_idx" -ge "$_setup_nv_rowcount" ]; then
_setup_nv_ambiguous=1
@@ -1439,18 +1256,14 @@ _setup_nv_banner_fields() {
_setup_nv_ambiguous=1
fi
fi
- # Split from the right: nvidia-smi does not quote, so a comma in a device name
- # would otherwise shift every field.
+ # Split from the right: nvidia-smi does not quote commas in names.
_setup_nv_driver=$(printf '%s' "$_setup_nv_row" | awk -F, 'NF>=3 { gsub(/^[[:space:]]+|[[:space:]]+$/,"",$NF); print $NF }')
_setup_nv_cc=$(printf '%s' "$_setup_nv_row" | awk -F, 'NF>=3 { gsub(/^[[:space:]]+|[[:space:]]+$/,"",$(NF-1)); print $(NF-1) }')
_setup_nv_name=$(printf '%s' "$_setup_nv_row" | awk -F, 'NF>=3 { out=$1; for(i=2;i<=NF-2;i++) out=out","$i; gsub(/^[[:space:]]+|[[:space:]]+$/,"",out); print out }')
- # Short row: keep field 1 only, or the compute capability lands in the name.
[ -n "$_setup_nv_name" ] || _setup_nv_name=$(printf '%s' "$_setup_nv_row" | awk -F, '{ gsub(/^[[:space:]]+|[[:space:]]+$/,"",$1); print $1 }')
- # An nvidia-smi too old for a field answers with a placeholder rather than failing.
+ # Old nvidia-smi answers unsupported fields with a placeholder.
case "$_setup_nv_name" in '[N/A]'|'[Not Supported]'|'[Unknown Error]') _setup_nv_name="" ;; esac
case "$_setup_nv_driver" in '[N/A]'|'[Not Supported]'|'[Unknown Error]') _setup_nv_driver="" ;; esac
- # Keep the driver, drop the identity: the banner falls back to the vendor-only wording
- # rather than claiming a card that may not be the one CUDA will use.
if [ -n "$_setup_nv_ambiguous" ]; then _setup_nv_name=""; _setup_nv_cc=""; fi
case "$_setup_nv_cc" in
[0-9]*.[0-9]*) _setup_nv_sm="sm_$(printf '%s' "$_setup_nv_cc" | awk -F. '{ print ($1*10)+$2 }')" ;;
@@ -1652,30 +1465,21 @@ rm -rf "$REPO_ROOT/unsloth_compiled_cache"
rm -rf "$SCRIPT_DIR/backend/unsloth_compiled_cache"
rm -rf "$SCRIPT_DIR/tmp/unsloth_compiled_cache"
-# WebView caches keyed by the bundle id can keep serving the previous frontend
-# after an update. Cache-only: storage, cookies, settings, models and the studio
-# database are untouched.
+# Cache-only: storage, cookies, settings, models and the database are untouched.
_clear_webview_caches() {
# No HOME: bail rather than let `set -u` abort or "" expand to /Library and /.cache.
[ -n "${HOME:-}" ] || return 0
_wvc_bid="ai.unsloth.studio"
_wvc_paths=()
- # The app's version stamp dir (main.rs webview_profile_root), which on macOS
- # is not the cache dir, so it is tracked separately.
_wvc_root=""
case "$(uname -s 2>/dev/null)" in
Darwin)
- # WKWebView keeps every cache-typed store under Library/Caches/<bid>;
# Library/WebKit/<bid> is user storage and is left alone.
_wvc_paths=("$HOME/Library/Caches/$_wvc_bid")
_wvc_root="$HOME/Library/Application Support/$_wvc_bid"
;;
Linux)
- # wry points WebKitGTK's base-cache dir at the app data dir, so the
- # caches sit beside localstorage/, databases/ and cookies, which stay.
- # A relative XDG_DATA_HOME is invalid per the XDG spec and dropped by
- # dirs, so match Tauri and use the default rather than rm -rf under
- # whatever directory the installer runs from.
+ # A relative XDG_DATA_HOME is invalid per XDG: use the default, never rm -rf under the cwd.
_wvc_data="${XDG_DATA_HOME:-$HOME/.local/share}"
case "$_wvc_data" in /*) ;; *) _wvc_data="$HOME/.local/share" ;; esac
_wvc_data="$_wvc_data/$_wvc_bid"
@@ -1688,12 +1492,7 @@ _clear_webview_caches() {
;;
*) return 0 ;;
esac
- # Drop the version stamp first. An update runs while the old WebView still holds
- # these files, so the rm below can fail; the app's own clear is the retry, and it
- # is skipped while the stamp matches the running version. Unconditional, since a
- # repair or a local rebuild leaves the version unchanged and a redundant clear on
- # the next launch is the cheap side. An `if`, not `[ ... ] && rm`: under `set -e`
- # that compound returns 1 when the guard is false and would abort the install.
+ # Drop the version stamp first so the app retries the clear. `if`, not `&&`, under set -e.
if [ -n "$_wvc_root" ]; then
rm -f "$_wvc_root/.webview-cache-cleared" 2>/dev/null || true
fi
@@ -1708,8 +1507,7 @@ _clear_webview_caches() {
fi
return 0
}
-# Not called here: under `set -e` with no trap, clearing before the UNSLOTH_STUDIO_HOME
-# / STUDIO_HOME override is validated lets a typo'd override delete the cache, then abort.
+# Not called here: a typo'd STUDIO_HOME override must be validated before clearing.
# ── Detect Colab ──
IS_COLAB=false
@@ -1743,9 +1541,7 @@ case "$_studio_override" in
"~/"*) _studio_override="$HOME/${_studio_override#'~/'}" ;;
esac
if [ -n "$_studio_override" ]; then
- # setup.sh runs against an existing install (via 'unsloth studio update');
- # a typo in the override must fail fast instead of materializing an
- # empty workspace dir. Mirrors setup.ps1 behavior.
+ # A typo in the override must fail fast instead of creating an empty dir. Mirrors setup.ps1.
if [ ! -d "$_studio_override" ]; then
echo "ERROR: $_studio_override_var=$_studio_override does not exist." >&2
echo " Run install.sh to create the install root before 'unsloth studio update'." >&2
@@ -1771,20 +1567,8 @@ if _mirror_enabled; then
cd "$_mirror_spare_pwd" 2>/dev/null || :
fi
-# Same uv cache install.sh chose, for the same reasons.
-#
-# This script is also the standalone entry point: `unsloth studio update` runs it
-# directly, without install.sh, so an export made only there covers the first install and
-# nothing after it. A redirected STUDIO_HOME would then download a SECOND cache to
-# $HOME/.cache/uv on the very first update and copy every wheel across the filesystem
-# boundary, which is exactly the disk cost the co-location exists to avoid -- deferred by
-# one run rather than fixed. Pointing at the same path also means the update reuses the
-# cache the install filled instead of refetching it.
-#
-# STUDIO_HOME, not RUNTIME_ROOT: the cache has to be the one install.sh created, and the
-# two agree whenever UNSLOTH_STUDIO_STAGE_ROOT is unset, which is every non-staged run.
-# The LIVE marker, even under a stage root: the CLI promotes its parked choice on acceptance,
-# so an unactivated stage cannot move the live cache. setup.sh only infers; it never writes.
+# Same uv cache install.sh chose: `unsloth studio update` runs this script alone, and a
+# second cache would copy every wheel across filesystems. Reads the LIVE marker; never writes.
_uv_no_cache_requested() {
# --no-cache outranks --cache-dir. Same spelling as install.sh's _uv_no_cache_requested.
case "$(printf '%s' "${UV_NO_CACHE:-}" | tr '[:upper:]' '[:lower:]')" in
@@ -1811,8 +1595,7 @@ _uv_is_bucket_name() {
}
_uv_cache_probe_writable() {
- # As install.sh's _uv_cache_root_is_writable: a real create, and mktemp (O_EXCL) not $$,
- # since a predictable name can be pre-created as a symlink.
+ # mktemp (O_EXCL), not $$: a predictable name can be pre-created as a symlink.
_uv_cache_probe=""
if ! mkdir -p "$1" 2>/dev/null \
|| ! _uv_cache_probe=$(mktemp "$1/.unsloth-write-probe.XXXXXX" 2>/dev/null); then
@@ -1820,10 +1603,7 @@ _uv_cache_probe_writable() {
unset _uv_cache_probe
return 1
fi
- # Creating is not enough: an ACL granting create but denying unlink leaves uv's renames to
- # fail later. GONE is the answer, not rm's exit status, since a scanner holding the handle
- # makes one delete fail and the next succeed. Retry, then believe the filesystem. Same
- # bounded loop as install.sh's _uv_cache_root_is_writable.
+ # An ACL may allow create but deny unlink; retry, then trust whether the file is gone.
_uv_cache_tries=0
while :; do
rm -f "$_uv_cache_probe" 2>/dev/null || true
@@ -1840,9 +1620,7 @@ _uv_cache_probe_writable() {
}
_uv_cache_folds_case() { # <dir>
- # Measured on the cache filesystem, not assumed from the platform, as install.sh does it:
- # default APFS folds and ext4 does not, and a Mac can have either mounted. A cache we
- # cannot write answers "no", which is the conservative reading.
+ # Measured, not assumed: a Mac can mount APFS (folds) or ext4.
_uvf_probe="$1/.unsloth-case-probe.$$-A"
mkdir "$_uvf_probe" 2>/dev/null || { unset _uvf_probe; return 1; }
if [ -d "$1/.unsloth-case-probe.$$-a" ]; then
@@ -1856,8 +1634,6 @@ _uv_cache_folds_case() { # <dir>
}
_uv_store_key() { # <entry name> <folds:1|0> -> the name uv opens it as, or nonzero
- # Only the NAME folds; what the entry IS is the caller's business. Both scans go through
- # here so they cannot disagree about which entries are uv's.
if _uv_is_bucket_name "$1"; then
printf '%s' "$1"
return 0
@@ -1875,33 +1651,19 @@ _uv_store_key() { # <entry name> <folds:1|0> -> the name uv opens it as, or no
}
_uv_cache_usable() {
- # The stores uv owns: a 0555 archive-* or interpreter-v4 aborts uv. Not every subdirectory,
- # or an unrelated read-only one disqualifies a usable cache. install.sh's
- # _uv_cache_is_writable is the same check.
+ # Only uv's stores: a 0555 archive-* or interpreter-v4 aborts uv.
_uv_cache_probe_writable "$1" || return 1
_uv_cache_folds_case "$1" && _uvu_fold=1 || _uvu_fold=0
for _uvu_bucket in "$1"/*; do
_uvu_name=$(_uv_store_key "${_uvu_bucket##*/}" "$_uvu_fold") || continue
- # Only the stores `uv pip install` CREATES, which is the one uv command this file runs
- # (line 2053). The rule is what uv is measured to write, not what a 0555 directory
- # happens to survive: a `git+` requirement creates git-v0 and builds-v0, so those stay,
- # while flat-index-v2 is not created even by `--find-links --no-index`, and binaries,
- # environments, osv and python belong to uv self-update, uv venv and uv python.
- #
- # A store is probed even where one trivial install tolerates it read-only, because that
- # tolerance is the WORKLOAD, not the cache. On the pinned uv 0.12.1 a 0555 sdists-v9
- # passes a wheel-only install and aborts the moment a source build needs it, and a 0555
- # interpreter-v4 passes while its entry is cached and aborts on a new interpreter. An
- # update installs a large, varying set, so a store it cannot write is a cache that
- # breaks later rather than one that is fine. Re-measure on a pin bump.
+ # Only stores `uv pip install` creates. Probed even if a trivial install tolerates read-only:
+ # a later source build or new interpreter aborts. Re-measure on a uv pin bump.
case "${_uvu_name%-v*}" in
archive|builds|built-wheels|git|interpreter|sdists|simple|wheels) ;;
*) continue ;;
esac
if [ ! -d "$_uvu_bucket" ]; then
- # A file, or a symlink dangling or not, is an existing path to mkdir(2), so uv
- # cannot make the store and aborts. Measured on uv 0.10.7: a plain file at any of
- # archive-v0, interpreter-v4, sdists-v9, simple-v20 or wheels-v6 exits 1 or 2.
+ # A file or symlink at a store path makes uv's mkdir fail.
if [ -e "$_uvu_bucket" ] || [ -L "$_uvu_bucket" ]; then
unset _uvu_bucket
return 1
@@ -1912,33 +1674,15 @@ _uv_cache_usable() {
unset _uvu_bucket _uvu_name _uvu_fold _uvu_ctl
return 1
fi
- # Inside the store, and only inside one uv owns: a `*-v[0-9]*` glob also reaches
- # `unused-v999/.git`, and a read-only file there condemned a cache real uv uses fine.
- # sdists-* only: that is the one store measured to abort on a read-only .git, and
- # rejecting a cache uv accepts costs the warm cache this path exists to find.
- # One level inside the index stores, and only those. uv REWRITES this metadata on every
- # resolve, so a shard another account owns aborts it. Measured on BOTH the pinned uv
- # 0.12.1 and 0.10.7: a 0555 `simple-*/pypi` or `wheels-*/pypi` gives "Failed to write to
- # the client cache", exit 2. One level is the leaf on both: 0.12.1 lays this out as
- # `simple-v24/pypi`, not `simple-v24/index/<hash>`, and a 0555 `wheels-v6/pypi/requests`
- # one level deeper installs fine. Bounded on purpose: the index level holds one entry per
- # index, while the level below it grows with every package.
+ # sdists-* .git is the one measured to abort when read-only. Index stores are probed one level
+ # deep: uv rewrites that metadata on every resolve (0.12.1 and 0.10.7).
case "$_uvu_name" in
simple-* | wheels-*)
for _uvu_shard in "$_uvu_bucket"/* "$_uvu_bucket"/index/*; do
- # `index/<hash>`, one per CUSTOM index, is where uv puts metadata when
- # --index-url is set, which Studio does for the torch wheels. Measured on
- # the pinned uv 0.12.1: a 0555 `simple-v24/index/<hash>` is adopted by a
- # one-level probe and then aborts `uv pip install --refresh` with "Failed
- # to write to the client cache". The literal `index` level is still bounded:
- # one entry per index, where the level below THAT is one per package.
+ # index/<hash> is used with --index-url (torch wheels) and must be writable too.
[ "${_uvu_shard#"$_uvu_bucket"/index/}" != "*" ] || continue
if [ ! -d "$_uvu_shard" ]; then
- # Same rule as the store level: a file, or a symlink dangling or not, is
- # an existing path uv can neither open nor mkdir. Measured on the pinned
- # uv 0.12.1, a plain file OR a dangling symlink at simple-v24/pypi or
- # wheels-v6/pypi aborts with "Failed to write to the client cache",
- # exit 2. A `*/` glob skips both, which called the cache usable.
+ # A file or dangling symlink at a shard also aborts uv; a `*/` glob would skip it.
{ [ -e "$_uvu_shard" ] || [ -L "$_uvu_shard" ]; } || continue
unset _uvu_bucket _uvu_name _uvu_fold _uvu_ctl _uvu_shard
return 1
@@ -1963,20 +1707,14 @@ _uv_cache_usable() {
}
_uv_control_files_writable() { # <dir> <name>...
- # Only the names uv is measured to need writable, because rejecting more throws away the
- # warm cache this whole path exists to find. Every control file at 0444 against uv 0.10.7:
- # root .lock ABORTS (exit 2) and sdists-v9/.git ABORTS (exit 2); root CACHEDIR.TAG and
- # .gitignore, and .git/.gitignore/.lock under archive-v0, interpreter-v4, simple-v20 and
- # wheels-v6, all install fine. uv itself creates only the three root files, so a per-store
- # .git is someone else's, and one of them is proven to break uv. Re-measure on a pin bump.
+ # Only names uv needs writable (root .lock, sdists-v9/.git); rejecting more loses the warm cache.
+ # Re-measure on a pin bump.
_uvc_dir=$1
shift
for _uvc_name in "$@"; do
_uvc_path="$_uvc_dir/$_uvc_name"
{ [ -e "$_uvc_path" ] || [ -L "$_uvc_path" ]; } || continue
- # Not a regular file, so uv cannot open it at all: measured on uv 0.10.7, a `.lock`
- # DIRECTORY (or a symlink to one) exits 2 with "Could not acquire lock ... Is a
- # directory". `-f` alone skipped it and called the cache usable.
+ # A .lock directory also breaks uv; -f alone missed it.
if [ ! -f "$_uvc_path" ] || [ ! -r "$_uvc_path" ] || [ ! -w "$_uvc_path" ]; then
unset _uvc_dir _uvc_name _uvc_path
return 1
@@ -1987,34 +1725,25 @@ _uv_control_files_writable() { # <dir> <name>...
}
_uv_cache_warm() {
- # Package BYTES, not metadata (wheels-* is .msgpack/.http after a bare resolve). Mirrors
- # install.sh's scan and unsloth_cli's _uv_cache_has_packages.
+ # Package bytes, not metadata. Mirrors install.sh and unsloth_cli's _uv_cache_has_packages.
[ -n "${1:-}" ] && [ -d "$1" ] && [ -r "$1" ] || return 1
- # One pass over the entries, not five lowercase globs: on a folding filesystem `Archive-V0`
- # IS the store uv opens as `archive-v0`, and a glob does not fold, so a cache holding every
- # wheel read as cold and the offline update failed. _uv_cache_usable normalises the same way.
+ # On a case-folding filesystem Archive-V0 is archive-v0, and a glob does not fold.
_uv_cache_folds_case "$1" && _uvw_fold=1 || _uvw_fold=0
for _uvw_bucket in "$1"/*; do
[ -d "$_uvw_bucket" ] || continue
- # Stricter than the probe, deliberately, and exactly as install.sh's scan: `archive-*`
- # also matches `archive-v0.backup`, whose bytes uv cannot reuse. Counting those reads a
- # cache as warm that then fails an offline update (measured: uv exit 1, not in cache).
+ # Stricter than the probe, as install.sh: archive-v0.backup is not reusable.
_uvw_base=$(_uv_store_key "${_uvw_bucket##*/}" "$_uvw_fold") || continue
case "${_uvw_base%-v*}" in
archive|builds|built-wheels|wheels|sdists) ;;
*) continue ;;
esac
- # Unreadable is not empty, but it is also not proof of warmth.
[ -r "$_uvw_bucket" ] && [ -x "$_uvw_bucket" ] || continue
- # -L: a bucket can be a symlink, as Get-ChildItem -Recurse follows. -print -quit, never
- # `| head -n 1`: under this file's pipefail head's early exit SIGPIPEs find on a bucket
- # over 64K of names, and the warm cache then reads as cold.
+ # -print -quit, not `| head`: under pipefail SIGPIPE on a large bucket reads as cold.
_uvw_hit=$(find -L "$_uvw_bucket" -type f \
! -name CACHEDIR.TAG ! -name .git ! -name .gitignore \
! -name '*.lock' ! -name '*.msgpack' ! -name '*.http' ! -name '*.rev' \
-print -quit 2>/dev/null) || true
- # `|| true`: find exits nonzero after an unreadable leaf even once it printed the hit,
- # and the hit is already assigned.
+ # find exits nonzero after an unreadable leaf even after printing the hit.
if [ -n "$_uvw_hit" ]; then
unset _uvw_bucket _uvw_hit _uvw_base _uvw_fold
return 0
@@ -2025,17 +1754,14 @@ _uv_cache_warm() {
}
_recorded_uv_cache() {
- # The marker as unsloth_cli writes it: one absolute path, one trailing newline. Tolerates a
- # BOM (PowerShell 5.1) and a CR, otherwise byte-for-byte. The sentinel keeps the bytes, and
- # exactly one delimiter is removed, so a pathname ending in a newline round-trips.
+ # One absolute path plus newline; tolerates a BOM and CR. The sentinel preserves trailing newlines.
_ruc_raw=$(cat "$STUDIO_HOME/cache/uv-cache-dir" 2>/dev/null && printf x) || return 1
_ruc_raw=${_ruc_raw%x}
_ruc_raw=${_ruc_raw%"$_UV_MARKER_LF"}
_ruc_raw=${_ruc_raw#"$_UV_MARKER_BOM"}
_ruc_raw=${_ruc_raw%"$_UV_MARKER_CR"}
case "$_ruc_raw" in
- # Absolute only, as install.sh records (_absolutize_uv_cache_dir): setup.sh has already
- # changed directory. No [:print:] filter: in the C locale it rejects every non-ASCII home.
+ # Absolute only: setup.sh has already changed directory.
"") unset _ruc_raw; return 1 ;;
/*) ;;
*) unset _ruc_raw; return 1 ;;
@@ -2049,37 +1775,29 @@ _UV_MARKER_CR=$(printf '\r')
_UV_MARKER_LF=$(printf '\n.')
_UV_MARKER_LF=${_UV_MARKER_LF%.}
-# Three tiers: a caller value, --no-cache, then the recorded marker or the Studio cache. No
-# "uv's default if warm" tier, unlike install.sh, which decides before anything is recorded:
-# here it would move an update off the installer's cache with nothing recording the change.
+# Tiers: caller value, --no-cache, then the recorded marker or the Studio cache.
_uv_caller_value=false
-# `*[![:space:]]*`, not `-n`: install.sh's test, so an all-whitespace value is not a caller's
-# choice here and `--cache-dir ' '` there. The two selectors have to answer alike.
+# All-whitespace is not a caller's choice; must agree with install.sh's test.
case "${UV_CACHE_DIR-}" in
*[![:space:]]*) _uv_caller_value=true ;;
esac
if [ "$_uv_caller_value" = true ]; then
- # A caller value wins outright, here as in install.sh and in the CLI.
:
elif _uv_no_cache_requested; then
# Unset, not left alone: uv parses an exported EMPTY value as `--cache-dir ''` and fails.
unset UV_CACHE_DIR
else
- # Same sentinel as the reader: substitution would strip the newline it preserved.
_uv_recorded=$(_recorded_uv_cache && printf x) || _uv_recorded=""
_uv_recorded=${_uv_recorded%x}
if [ -n "$_uv_recorded" ] && _uv_cache_warm "$_uv_recorded" \
&& _uv_cache_usable "$_uv_recorded"; then
- # Only while it holds packages and uv can write to it: an emptied cache would refetch
- # everything, and uv aborts on a read-only one (a share remounted since the install).
+ # Only while it holds packages and is writable: uv aborts on a read-only cache.
UV_CACHE_DIR="$_uv_recorded"
export UV_CACHE_DIR
else
UV_CACHE_DIR="$STUDIO_HOME/cache/uv"
export UV_CACHE_DIR
- # The whole cache, not just its root, and the same check the recorded branch gets: a
- # Studio cache whose archive-v0 went read-only passes a root probe and then aborts uv
- # (measured: exit 1, "Permission denied"). Leaving it unset lets uv use its own.
+ # Check the whole cache: a read-only archive-v0 passes a root probe and aborts uv.
if ! _uv_cache_usable "$UV_CACHE_DIR"; then
echo "[WARN] Cannot write to $UV_CACHE_DIR -- using uv's default cache." >&2
unset UV_CACHE_DIR
@@ -2092,10 +1810,7 @@ VENV_T5_530_DIR="$RUNTIME_ROOT/.venv_t5_530"
VENV_T5_550_DIR="$RUNTIME_ROOT/.venv_t5_550"
VENV_T5_510_DIR="$RUNTIME_ROOT/.venv_t5_510"
-# The override is validated, so a typo can no longer cost the cache. Venv-gated because
-# a writable-but-empty override still aborts at the venv check below, and clearing first
-# would cost the cache for a run that then does nothing; a fresh install has neither venv
-# nor cache. Still before any install work, while the old frontend is the one on disk.
+# Venv-gated: an empty override aborts at the venv check below, so do not clear first.
if [ -z "$STAGE_ROOT" ] && [ -x "$VENV_DIR/bin/python" ]; then
_clear_webview_caches
fi
@@ -2115,50 +1830,32 @@ _STUDIO_HOME_IS_CUSTOM=false
if [ "$_studio_home_canon" != "$_LEGACY_STUDIO_HOME" ]; then
_STUDIO_HOME_IS_CUSTOM=true
fi
-# The master root storage_roots.unsloth_home() reads. llama.cpp, node and whisper.cpp sit BESIDE
-# studio/ under it, so installing them under $STUDIO_HOME would put them one level below where
-# every runtime resolver looks. Captured here because section 7 assigns over UNSLOTH_HOME.
-# Stripped before anything else, like _studio_override above: " " counts as unset and " /opt/uns "
-# names /opt/uns, which is what the Python resolver and the CLI both see.
+# Runtimes sit beside studio/ under UNSLOTH_HOME; captured before section 7 reassigns it.
+# Stripped before anything else, like _studio_override above: " " counts as unset.
_MASTER_ROOT=$(printf '%s' "${UNSLOTH_HOME:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_MASTER_ROOT" ]; then
case "$_MASTER_ROOT" in
"~") _MASTER_ROOT="$HOME" ;;
"~/"*) _MASTER_ROOT="$HOME/${_MASTER_ROOT#'~/'}" ;;
esac
- # Absolute against the CALLER's directory even when it does not exist yet, as Path.resolve()
- # does: node is chosen before the first `cd "$SCRIPT_DIR"` and llama.cpp after it, so a
- # relative value names two different directories and matches the backend's neither.
+ # Absolutised against the caller's cwd: node and llama.cpp are chosen from different cwds.
case "$_MASTER_ROOT" in
/*) ;;
*) _MASTER_ROOT="$PWD/$_MASTER_ROOT" ;;
esac
if [ -d "$_MASTER_ROOT" ]; then
- # Keep the expanded value when it cannot be canonicalized, as the Python resolver does:
- # dropping it here would send the runtimes to a root nothing else agrees on.
+ # Keep the expanded value when it cannot be canonicalised, as the Python resolver does.
_master_root_canon=$(CDPATH= cd -P -- "$_MASTER_ROOT" 2>/dev/null && pwd -P) || _master_root_canon=""
[ -z "$_master_root_canon" ] || _MASTER_ROOT="$_master_root_canon"
unset _master_root_canon
fi
fi
-# Ownership applies to node/, llama.cpp/ and whisper.cpp/ whenever a master root moves them,
-# even with STUDIO_HOME left at the legacy path, where _STUDIO_HOME_IS_CUSTOM is false and
-# "false" licenses the installers to os.replace() and rm -rf unmarked trees. The Studio home
-# and its venvs keep the other flag.
+# "false" licenses installers to replace/rm unmarked runtime trees, so track it separately.
_RUNTIME_ROOT_IS_CUSTOM="$_STUDIO_HOME_IS_CUSTOM"
-# Keyed on where the runtimes LAND, not on whether a master root was named: UNSLOTH_HOME set to
-# the root an install already uses moves nothing, and calling that custom would demand an owner
-# marker from a legacy source-built ~/.unsloth/llama.cpp that predates markers.
-#
-# Staging is excluded for the same reason, not as an exception to it: the placement below gives
-# STAGE_ROOT precedence over the master root, so during a staged update the master root is not
-# where anything lands and must not decide ownership. Assigned rather than raised, or a custom
-# STUDIO_HOME kept the flag true while the runtimes went to the legacy root, which demanded
-# markers from exactly the pre-marker trees this comparison exists to spare.
+# Keyed on where runtimes land; staging excluded because STAGE_ROOT takes precedence.
if [ -z "${STAGE_ROOT:-}" ] && [ -n "$_MASTER_ROOT" ]; then
- # Canonicalised like _MASTER_ROOT, or a symlinked $HOME compares unequal to itself and the
- # legacy root reads as custom after all.
+ # Canonicalised like _MASTER_ROOT, or a symlinked $HOME reads as custom.
_rrc_legacy="$HOME/.unsloth"
if [ -d "$_rrc_legacy" ]; then
_rrc_canon=$(CDPATH= cd -P -- "$_rrc_legacy" 2>/dev/null && pwd -P) || _rrc_canon=""
@@ -2172,11 +1869,8 @@ if [ -z "${STAGE_ROOT:-}" ] && [ -n "$_MASTER_ROOT" ]; then
fi
unset _rrc_legacy
fi
-# Directory-local evidence Unsloth created "$1": only prebuilt-installer metadata
-# counts (UNSLOTH_PREBUILT_INFO.json for llama.cpp, UNSLOTH_NODE_PREBUILT_INFO.json
-# for Node, UNSLOTH_WHISPER_PREBUILT_INFO.json for whisper.cpp), all written only
-# by our installers. Mirrors the setup.ps1 Node guard. A markerless source build
-# stays strict since this runs right before an rm -rf.
+# Directory-local evidence Unsloth created "$1": only prebuilt-installer metadata counts,
+# since this runs right before an rm -rf.
_studio_owned_adoptable() {
[ -f "$1/UNSLOTH_PREBUILT_INFO.json" ] && return 0
[ -f "$1/UNSLOTH_NODE_PREBUILT_INFO.json" ] && return 0
@@ -2198,8 +1892,7 @@ _studio_dir_unreadable() {
return 0
}
-# Mirrors Exit-PathAccessDenied in setup.ps1. owner-unverified means the marker
-# was unreadable, so do not claim the tree is ours or advise deleting it.
+# Mirrors Exit-PathAccessDenied in setup.ps1. owner-unverified: do not claim or advise deleting.
_path_access_denied() {
_pad_dir="$1"
_pad_label="$2"
@@ -2230,14 +1923,12 @@ _studio_rstrip_slash() {
printf '%s' "$_srs_path"
}
-# An unsearchable ancestor makes a real path read as missing. Walk up to the deepest
-# ancestor we can stat and report it as the blocker; stay quiet if the path is just absent.
+# An unsearchable ancestor makes a real path read as missing; report the deepest stat-able one.
_report_denied_ancestor() {
_rda_probe="$(_studio_rstrip_slash "$1")"
_rda_hops=0
while [ ! -e "$_rda_probe" ] && [ "$_rda_probe" != "/" ] && [ "$_rda_probe" != "." ]; do
- # An unfollowable symlink is the deepest name we have, so walk its target:
- # the denied ancestor lives there. The hop cap breaks symlink cycles.
+ # The hop cap breaks symlink cycles.
if [ -L "$_rda_probe" ] && [ "$_rda_hops" -lt 40 ]; then
_rda_hops=$((_rda_hops + 1))
_rda_target="$(readlink -- "$_rda_probe")" || break
@@ -2248,7 +1939,6 @@ _report_denied_ancestor() {
_rda_probe="$(_studio_rstrip_slash "$_rda_probe")"
continue
fi
- # -- keeps a leading-dash path an operand, not a dirname option.
_rda_probe="$(dirname -- "$_rda_probe")"
done
if _studio_dir_unsearchable "$_rda_probe"; then
@@ -2256,8 +1946,6 @@ _report_denied_ancestor() {
fi
}
-# What is at "$1", for the refusal message. A user told the path is "not an Unsloth install"
-# when it is their own dangling symlink has no idea what to move aside.
_studio_path_shape() {
if [ -L "$1" ]; then
if [ -e "$1" ]; then printf 'a symlink'; else printf 'a dangling symlink'; fi
@@ -2267,21 +1955,15 @@ _studio_path_shape() {
fi
}
-# $3 is the ownership flag: the runtime children pass _RUNTIME_ROOT_IS_CUSTOM, everything
-# under the Studio home keeps _STUDIO_HOME_IS_CUSTOM.
_assert_studio_owned_or_absent() {
_aso_dir="$1"
_aso_label="$2"
_aso_custom="${3:-$_STUDIO_HOME_IS_CUSTOM}"
- # -d alone read a dangling symlink or a regular file as "nothing is here", and the caller
- # then rm -rf'd it or os.replace()d over it. A dangling link is the ordinary case: its
- # volume is simply not mounted, and following it later installs onto somebody's other disk.
+ # -d alone treated a dangling symlink or file as absent and the caller rm -rf'd it.
if [ ! -d "$_aso_dir" ] && [ ! -e "$_aso_dir" ] && [ ! -L "$_aso_dir" ]; then
return 0
fi
if [ "$_aso_custom" = true ] && [ ! -f "$_aso_dir/$_STUDIO_OWNED_MARKER" ]; then
- # Only a directory can carry the marker or the prebuilt metadata, so anything else here
- # is unowned by construction and the adoption path below cannot apply to it.
if [ ! -d "$_aso_dir" ]; then
echo "ERROR: $_aso_dir already exists and is not an Unsloth-owned $_aso_label." >&2
echo " It is $(_studio_path_shape "$_aso_dir"). Move it aside before re-running." >&2
@@ -2291,8 +1973,7 @@ _assert_studio_owned_or_absent() {
: > "$_aso_dir/$_STUDIO_OWNED_MARKER" 2>/dev/null || true
return 0
fi
- # An unsearchable tree hides its own marker and so looks like someone else's:
- # report permissions, not ownership.
+ # An unsearchable tree hides its own marker: report permissions, not ownership.
if _studio_dir_unsearchable "$_aso_dir"; then
_path_access_denied "$_aso_dir" "$_aso_label" owner-unverified
fi
@@ -2304,19 +1985,8 @@ _assert_studio_owned_or_absent() {
_packaged_frontend_available() {
- # install.sh and `unsloth studio update` explicitly set 0 for PyPI installs.
- # Wheel extraction mtimes do not preserve build ordering, so source files can
- # appear newer than the release-built dist even though both came from the
- # same wheel. Trust the packaged artifact when its entry point is present;
- # local/source installs set 1 (or leave the mode unset) and still rebuild.
- #
- # The mode alone is not enough. It records where the Python package came
- # from, not which tree this script is running out of, and an editable
- # overlay separates the two: UNSLOTH_CI_SOURCE_OVERLAY (and a venv left
- # editable by an earlier --local run) leaves the mode at 0 while
- # $SCRIPT_DIR is a checkout, whose dist is a stale build artifact rather
- # than a release one. A wheel ships no top-level files, so a pyproject.toml
- # next to studio/ means source tree -- keep the mtime rebuild there.
+ # Mode 0 trusts the wheel's dist (extraction mtimes are meaningless), unless a pyproject.toml
+ # beside studio/ shows a source checkout (editable overlay).
[ "${STUDIO_LOCAL_INSTALL:-}" = "0" ] &&
[ ! -f "$REPO_ROOT/pyproject.toml" ] &&
[ -f "$SCRIPT_DIR/frontend/dist/index.html" ]
@@ -2356,8 +2026,7 @@ fi
if [ "$_LLAMA_ONLY" != "1" ]; then
# ── Detect whether frontend needs building ──
-# Tauri owns its frontend bundle. Standard PyPI installs use the release-built
-# dist shipped in the wheel. Only local/source installs use mtime-based rebuilds.
+# Tauri owns its bundle; PyPI installs use the wheel's dist; only source installs rebuild by mtime.
if [ "${SKIP_STUDIO_FRONTEND:-0}" = "1" ]; then
_NEED_FRONTEND_BUILD=false
step "frontend" "bundled (Tauri)"
@@ -2380,8 +2049,7 @@ fi
[ ! -e "$_FRONTEND_BUILD_MARK" ] || _NEED_FRONTEND_BUILD=true
fi # end packaged/Tauri guard
-# OXC validator runtime (below) needs node/npm whenever its dir exists, regardless
-# of dist staleness; provision Node when the frontend builds OR the OXC dir exists.
+# OXC validator runtime needs node/npm whenever its dir exists, regardless of dist staleness.
_OXC_DIR="$SCRIPT_DIR/backend/core/data_recipe/oxc-validator"
if [ "$_NEED_FRONTEND_BUILD" = false ] && [ ! -d "$_OXC_DIR" ]; then
step "frontend" "up to date"
@@ -2389,18 +2057,12 @@ if [ "$_NEED_FRONTEND_BUILD" = false ] && [ ! -d "$_OXC_DIR" ]; then
else
# ── Node (isolated; never touches the system Node/npm) ──
-# Unsloth's frontend (Vite 8) needs Node ^20.19 || >=22.12 || >=23 and npm >= 11.
-# Three sources:
-# system -- system Node + npm already satisfy both; used read-only.
-# bundled -- install a pinned isolated Node under $UNSLOTH_HOME/node, build-only.
-# skip -- UNSLOTH_SKIP_NODE_INSTALL=1 and system unsuitable; print manual fix.
-# decide_node_source(node_v, npm_v, skip_flag) -> system | bundled | skip
-# (pure; unit-tested in tests/sh/test_node_decision.sh).
+# Vite 8 needs Node ^20.19 || >=22.12 || >=23 and npm >= 11.
+# decide_node_source -> system | bundled | skip (unit-tested in tests/sh/test_node_decision.sh).
decide_node_source() {
_dns_node="${1#v}"
_dns_npm="$2"
_dns_skip="$3"
- # Treat empty or non-numeric versions as "missing".
case "$_dns_node" in ''|*[!0-9.]*) _dns_node='' ;; esac
case "$_dns_npm" in ''|*[!0-9.]*) _dns_npm='' ;; esac
if [ -n "$_dns_node" ] && [ -n "$_dns_npm" ]; then
@@ -2439,8 +2101,7 @@ else
fi
NODE_DIR="$_NODE_PARENT/node"
-# Bound system node/npm probes so a broken binary on PATH cannot stall setup (#11709).
-# Sets _PROBED_VER, or leaves it empty if the tool is missing, fails or times out.
+# Bound system node/npm probes so a broken binary on PATH cannot stall setup.
_probe_system_node_tool() {
_PROBED_VER=""
command -v "$1" >/dev/null 2>&1 || return 0
@@ -2457,7 +2118,6 @@ _probe_system_node_tool() {
_probe_system_node_tool node
_SYS_NODE_VER="$_PROBED_VER"
_SYS_NPM_VER=""
-# npm requires Node, so skip its probe if Node failed.
if [ -n "$_SYS_NODE_VER" ]; then
_probe_system_node_tool npm
_SYS_NPM_VER="$_PROBED_VER"
@@ -2469,14 +2129,12 @@ if [ "$NODE_SOURCE" = system ]; then
step "node" "$_SYS_NODE_VER | npm $_SYS_NPM_VER (system)"
elif [ "$NODE_SOURCE" = bundled ]; then
mkdir -p "$_NODE_PARENT"
- # install_node_prebuilt.py uses os.replace(); guard a custom-home dir so we
- # never displace a user-owned $UNSLOTH_STUDIO_HOME/node.
+ # install_node_prebuilt.py uses os.replace(); never displace a user-owned node dir.
if [ "$_RUNTIME_ROOT_IS_CUSTOM" = true ]; then
_assert_studio_owned_or_absent "$NODE_DIR" "Node install" "$_RUNTIME_ROOT_IS_CUSTOM"
fi
substep "installing isolated Node (system Node/npm left untouched)..."
- # Runs before the venv is activated, so bare `python` may be absent; resolve
- # venv python, then python3, then python.
+ # Runs before venv activation, so bare `python` may be absent.
if [ -x "$VENV_DIR/bin/python" ]; then
_NODE_PY="$VENV_DIR/bin/python"
elif command -v python3 >/dev/null 2>&1; then
@@ -2494,7 +2152,7 @@ elif [ "$NODE_SOURCE" = bundled ]; then
"$_NODE_PY" "$SCRIPT_DIR/install_node_prebuilt.py" --install-dir "$NODE_DIR" >>"$_NODE_LOG" 2>&1
_NODE_STATUS=$?
fi
- # A failed download gets one retry through the mirror; 3 (another install holds the lock) and 4 (permission denied) are not network failures.
+ # Exit 3 (lock held) and 4 (permission denied) are not network failures.
[ "$_NODE_STATUS" -ne 0 ] && [ "$_NODE_STATUS" -ne 3 ] && [ "$_NODE_STATUS" -ne 4 ] && [ "$_node_try" = default ] || break
_mirror_switch node || break
done
@@ -2510,7 +2168,6 @@ elif [ "$NODE_SOURCE" = bundled ]; then
substep "install Node >= 20.19 (with npm >= 11) yourself and re-run, or check your network"
setup_fail 1 "Could not install an isolated Node runtime"
elif grep -Fq "keeping existing isolated Node" "$_NODE_LOG"; then
- # Exit 0 also covers a failed update that kept a working Node; relay any repair lines.
if grep -Fq 'takeown /F' "$_NODE_LOG"; then
sed 's/^/ | /' "$_NODE_LOG" >&2
fi
@@ -2521,9 +2178,7 @@ elif [ "$NODE_SOURCE" = bundled ]; then
if [ "$_RUNTIME_ROOT_IS_CUSTOM" = true ] && [ -d "$NODE_DIR" ]; then
: > "$NODE_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true
fi
- # Prepend the isolated bin (this process only) so node/npm/bun resolve here.
export PATH="$NODE_DIR/bin:$PATH"
- # Keep npm and module resolution inside the isolated Node.
export NPM_CONFIG_PREFIX="$NODE_DIR"
export npm_config_prefix="$NODE_DIR"
unset NODE_PATH
@@ -2540,22 +2195,19 @@ verbose_substep "node source: $NODE_SOURCE (sys node=${_SYS_NODE_VER:-none} npm=
if [ "$_FRONTEND_SKIP" = true ]; then
: # no suitable Node (skip source): message already shown above; nothing to build
elif [ "$_NEED_FRONTEND_BUILD" = false ]; then
- # Node was provisioned only for the OXC runtime; the dist is already current.
step "frontend" "up to date"
verbose_substep "frontend dist is newer than source inputs"
else
# ── Install bun (optional, faster package installs) ──
-# Install bun via npm only when we manage the isolated Node (npm -g lands in the
-# isolated prefix); on a system Node we install nothing global. Build falls back to npm.
+# Install bun only into the isolated Node prefix; never globally on a system Node.
if command -v bun &>/dev/null; then
substep "bun already installed ($(bun --version))"
elif [ -f "$SCRIPT_DIR/frontend/package-lock.json" ]; then
verbose_substep "skipping global bun install (package-lock.json installs with npm ci)"
elif [ "$NODE_SOURCE" = bundled ]; then
substep "installing bun..."
- # --allow-scripts=bun: npm >=11.16 gates install scripts and bun's
- # postinstall fetches its binary; without it the install is a broken stub.
+ # --allow-scripts=bun: npm >=11.16 gates install scripts and bun's postinstall fetches its binary.
if run_maybe_quiet npm install -g bun --allow-scripts=bun "${_NPM_REGISTRY_ARGS[@]+"${_NPM_REGISTRY_ARGS[@]}"}" && command -v bun &>/dev/null; then
substep "bun installed ($(bun --version))"
else
@@ -2587,23 +2239,14 @@ _restore_gitignores() {
}
trap _frontend_build_cleanup EXIT
-# package-lock.json always wins (`npm ci`); bun only without one, since bun.lock is gitignored.
-# Build always uses npm (Node runtime -- avoids bun runtime issues on some platforms).
-# NOTE: We intentionally avoid run_quiet for the bun install attempt because
-# run_quiet calls exit on failure, which would kill the script before the npm
-# fallback can run. Instead we capture output manually and only show it on failure.
-#
-# IMPORTANT: bun's package cache can become corrupt -- packages get stored
-# with only metadata (package.json, README) but no actual content (bin/,
-# lib/). When this happens bun install exits 0 but leaves binaries missing.
-# We verify critical binaries after install. If missing, we clear the cache
-# and retry once before falling back to npm.
+# package-lock.json wins (`npm ci`); bun only without one. Not run_quiet: it exits on failure.
+# bun's cache can corrupt and exit 0 with missing binaries, so verify, clear, and retry once.
_try_bun_install() {
local _log _exit_code=0
_log=$(mktemp)
bun install --frozen-lockfile "${_NPM_REGISTRY_ARGS[@]+"${_NPM_REGISTRY_ARGS[@]}"}" >"$_log" 2>&1 || _exit_code=$?
- # bun may create .exe shims on Windows (Git Bash / MSYS2) instead of plain scripts
+ # bun may create .exe shims on Windows (Git Bash / MSYS2)
if [ "$_exit_code" -eq 0 ] \
&& { [ -x node_modules/.bin/tsc ] || [ -f node_modules/.bin/tsc.exe ] || [ -f node_modules/.bin/tsc.bunx ]; } \
&& { [ -x node_modules/.bin/vite ] || [ -f node_modules/.bin/vite.exe ] || [ -f node_modules/.bin/vite.bunx ]; }; then
@@ -2611,7 +2254,6 @@ _try_bun_install() {
return 0
fi
- # Either bun install failed or it exited 0 but left packages missing
if [ "$_exit_code" -ne 0 ]; then
echo " bun install failed (exit code $_exit_code):"
else
@@ -2624,7 +2266,6 @@ _try_bun_install() {
return 1
}
-# Capture install output (bun + npm fallback) so we can detect a registry block.
_FRONTEND_INSTALL_LOG=$(mktemp)
_CAPTURE_LOG="$_FRONTEND_INSTALL_LOG"
_bun_install_ok=false
@@ -2635,8 +2276,6 @@ if [ ! -f package-lock.json ] && [ -f bun.lock ] && command -v bun &>/dev/null;
if _try_bun_install; then
_bun_install_ok=true
else
- # First attempt failed, likely due to corrupt cache entries.
- # Clear the cache and retry once.
echo " Clearing bun cache and retrying..."
run_maybe_quiet bun pm cache rm || true
if _try_bun_install; then
@@ -2645,9 +2284,7 @@ if [ ! -f package-lock.json ] && [ -f bun.lock ] && command -v bun &>/dev/null;
fi
fi
if [ "$_bun_install_ok" = false ]; then
- # `|| _npm_install_rc=$?` keeps this off `set -e`'s exit path (run_quiet_no_exit
- # returns non-zero on failure) so the hint branch is reachable; it also captures
- # the exact exit code. Mirrors the `|| BUILD_OK=false` idiom used below.
+ # `|| rc=$?` keeps this off set -e's exit path so the hint branch is reachable.
_npm_install_rc=0
run_quiet_no_exit "npm $_NPM_INSTALL" npm "$_NPM_INSTALL" --no-fund --no-audit --loglevel=error "${_NPM_REGISTRY_ARGS[@]+"${_NPM_REGISTRY_ARGS[@]}"}" || _npm_install_rc=$?
if [ "$_npm_install_rc" -ne 0 ] && _npm_mirror_retry "npm $_NPM_INSTALL"; then
@@ -2705,15 +2342,12 @@ fi
[ -d "$REPO_ROOT/.venv_t5" ] && rm -rf "$REPO_ROOT/.venv_t5"
[ -d "$REPO_ROOT/.venv_t5_530" ] && rm -rf "$REPO_ROOT/.venv_t5_530"
[ -d "$REPO_ROOT/.venv_t5_550" ] && rm -rf "$REPO_ROOT/.venv_t5_550"
-# Note: do NOT delete $STUDIO_HOME/.venv here — install.sh handles migration
+# Do NOT delete $STUDIO_HOME/.venv here: install.sh handles migration.
_COLAB_NO_VENV=false
if [ ! -x "$VENV_DIR/bin/python" ]; then
if [ "$IS_COLAB" = true ]; then
- # On Colab there is no Unsloth venv -- install backend deps into system Python.
- # Strip all version constraints so pip keeps Colab's pre-installed
- # packages (huggingface-hub, datasets, transformers) and only pulls
- # in genuinely missing ones (structlog, fastapi, etc.).
+ # Colab: strip version constraints so pip keeps pre-installed packages.
substep "Colab detected, installing Unsloth backend dependencies..."
_COLAB_REQS_TMP="$(mktemp)"
sed 's/[><=!~;].*//' "$SCRIPT_DIR/backend/requirements/studio.txt" \
@@ -2792,12 +2426,7 @@ _setup_http_get() {
fi
}
-# Same, with a deadline, for the checks that must not hang the install.
-# wget has nothing like curl's total-transfer --max-time: --timeout is per
-# operation and it retries 20 times, so a stalled server took minutes and a slow
-# drip never ended. --tries=1 plus an outer `timeout` restores the 5s ceiling;
-# without timeout (base macOS, which ships curl anyway) the per-operation bound
-# stands rather than the check being dropped.
+# wget --timeout is per operation with 20 retries; --tries=1 plus outer timeout gives 5s.
_setup_http_get_timed() {
if command -v curl >/dev/null 2>&1; then
curl -fsSL --max-time 5 "$1"
@@ -2813,10 +2442,9 @@ _setup_http_get_timed() {
}
# ── uv from a pinned release ──
-# Same archive and destination as astral's installer, but it fetches a data file with a
-# pinned SHA-256 instead of piping remote script text into a shell. Mirrors install.sh.
+# Pinned uv release with SHA-256 instead of piping a remote script into a shell. Mirrors install.sh.
# See tests/studio/test_installer_av_shapes.py (AV_SHAPES_RECORD)
-# Bumping the version means bumping every hash, and every _setup_uv_pinned_wheel entry:
+# Bumping the version means bumping every hash, and every _setup_uv_pinned_wheel entry.
# curl -sL https://github.com/astral-sh/uv/releases/download/<ver>/<asset>.sha256
#
# Only the four mainstream targets are pinned; the rest fall through to the existing path
@@ -2825,8 +2453,7 @@ _SETUP_UV_PINNED_VERSION="0.13.5"
# sha256 of astral's versioned install.sh for that release; the fallback below runs only those exact bytes.
_SETUP_UV_INSTALLER_SH_SHA256="1c6e7f025499664633ac2dce43a210800510e9ef0625c52e034a8afdf8bf177a"
-# Mirrors _uv_glibc_minor in install.sh: "not musl" is not the same as "a glibc new enough to
-# run the GNU build", and astral drops to its musl-static archive below its floor.
+# Mirrors _uv_glibc_minor in install.sh: astral uses musl-static below its glibc floor.
_setup_uv_glibc_minor() {
_sugm_line=$( (ldd --version 2>/dev/null || true) | head -1 )
case "$_sugm_line" in *[Mm]usl*) return 1 ;; esac
@@ -2893,7 +2520,7 @@ _setup_uv_pinned_wheel() {
esac
}
-# Mirrors _uv_unzip in install.sh: GNU tar cannot read a wheel and minimal images lack unzip.
+# GNU tar cannot read a wheel and minimal images lack unzip.
_setup_uv_unzip() {
if command -v unzip >/dev/null 2>&1 && unzip -qo "$1" -d "$2" >/dev/null 2>&1; then return 0; fi
case "$(tar --version 2>/dev/null)" in
@@ -2911,10 +2538,7 @@ _setup_uv_sha256() {
fi
}
-# The function's own cleanup only runs when it returns, so an interrupt left the unpacked
-# archive behind plus a staging file inside a directory on PATH. No trap is active here (the
-# gitignore EXIT trap is cleared well above), so the pinned install owns these four for its
-# duration and hands them back on the way out.
+# Cleanup on interrupt: no other trap is active here.
_setup_uv_cleanup_temporaries() {
[ -n "${_SIUP_WORK:-}" ] && rm -rf "$_SIUP_WORK" 2>/dev/null || true
[ -n "${_SIUP_STAGE:-}" ] && rm -f "$_SIUP_STAGE" 2>/dev/null || true
@@ -2927,7 +2551,6 @@ _setup_uv_on_signal() {
exit "$1"
}
-# The PATH a new shell inherits, captured before the uv destination can be prepended to it.
_SETUP_LOGIN_PATH="$PATH"
_SIUP_WORK=""
_SIUP_STAGE=""
@@ -2943,13 +2566,10 @@ _setup_install_uv_pinned() {
[ -n "$(_setup_uv_sha256 /dev/null)" ] || return 1
[ -n "${HOME:-}" ] || return 1
- # astral's full destination priority, including the XDG_DATA_HOME tier that sits between
- # XDG_BIN_HOME and the home default. Dropping it would leave uv under ~/.local/bin on a
- # host that configured an XDG location, where no later shell looks for it.
+ # astral's full destination priority, including XDG_DATA_HOME.
_siup_dest="${UV_INSTALL_DIR:-${UV_UNMANAGED_INSTALL:-${XDG_BIN_HOME:-}}}"
if [ -z "$_siup_dest" ] && [ -n "${XDG_DATA_HOME:-}" ]; then _siup_dest="$XDG_DATA_HOME/../bin"; fi
[ -n "$_siup_dest" ] || _siup_dest="$HOME/.local/bin"
- # 2>/dev/null, as install.sh does: a speculative attempt whose failure falls back.
_siup_work=$(mktemp -d 2>/dev/null) || return 1
_SIUP_WORK="$_siup_work"
trap _setup_uv_cleanup_temporaries EXIT
@@ -2957,9 +2577,7 @@ _setup_install_uv_pinned() {
trap '_setup_uv_on_signal 130' INT
trap '_setup_uv_on_signal 143' TERM
_siup_rc=1
- # A configured mirror is EXCLUSIVE, matching astral's installer and the PowerShell side: a
- # restricted network sets one because the public hosts are unreachable, so trying those first
- # would stall instead of falling through.
+ # A configured mirror is exclusive, matching astral's installer.
if [ -n "${UV_DOWNLOAD_URL:-}" ]; then
_siup_bases="${UV_DOWNLOAD_URL%/}"
elif [ -n "${INSTALLER_DOWNLOAD_URL:-}" ]; then
@@ -2991,27 +2609,19 @@ https://github.com/astral-sh/uv/releases/download/$_SETUP_UV_PINNED_VERSION"
*) tar -xzf "$_siup_work/$_siup_asset" -C "$_siup_work" 2>/dev/null || continue ;;
esac
mkdir -p "$_siup_dest" 2>/dev/null || break
- # Stage both, then publish both, as install.sh does: the renames sit next to each
- # other so the pair is replaced as one.
_siup_ready=1
for _siup_exe in uv uvx; do
- # `mv f d` moves f INTO d and reports success, and a searchable directory passes -x
- # too, so a directory called uv at the destination would look like a published
- # binary and skip the fallback. The installer already refuses one for its own shim.
+ # `mv f d` moves into a directory named uv and reports success.
if [ -d "$_siup_dest/$_siup_exe" ]; then _siup_ready=0; break; fi
_siup_src=$(find "$_siup_work" -type f -name "$_siup_exe" 2>/dev/null | head -1)
if [ -z "$_siup_src" ]; then _siup_ready=0; break; fi
- # cp writes through a symlinked destination, and a per-process staging name keeps
- # two racing installers from publishing each other's half-written file.
+ # Per-process staging name so racing installers cannot publish each other's file.
_siup_stage=$(mktemp "$_siup_dest/.$_siup_exe.XXXXXX" 2>/dev/null) || { _siup_ready=0; break; }
if [ "$_siup_exe" = "uv" ]; then _SIUP_STAGE="$_siup_stage"; else _SIUP_STAGE2="$_siup_stage"; fi
if ! cp -f "$_siup_src" "$_siup_stage" 2>/dev/null; then _siup_ready=0; break; fi
- # 0755, not +x: the staging file carries the umask default and +x only adds execute
- # where read was allowed, so umask 077 would leave uv unusable for every other
- # account. astral ships these 0755.
+ # 0755, not +x: umask 077 would leave uv unusable for other accounts.
chmod 0755 "$_siup_stage" 2>/dev/null || true
- # Validate before publishing: the rename destroys the incumbent, so a binary that
- # cannot run here must never replace one that could.
+ # Validate before publishing: the rename destroys the incumbent.
if [ "$_siup_exe" = "uv" ] && ! _setup_probe_version "$_siup_stage"; then _siup_ready=0; break; fi
done
if [ "$_siup_ready" = "1" ] &&
@@ -3029,7 +2639,6 @@ https://github.com/astral-sh/uv/releases/download/$_SETUP_UV_PINNED_VERSION"
_SIUP_STAGE=""
_SIUP_STAGE2=""
trap - EXIT HUP INT TERM
- # The staged binary already answered --version above, before it replaced anything.
[ -x "$_siup_dest/uv" ] || _siup_rc=1
if [ "$_siup_rc" = "0" ]; then
export PATH="$_siup_dest:$PATH"
@@ -3083,26 +2692,17 @@ _setup_path_has_dir() {
return "$_sphd_found"
}
-# Is a conda environment ACTIVE in this shell? Both variables, matching install.ps1: a hook
-# exporting only CONDA_DEFAULT_ENV still leaves the caller inside conda's PATH ordering.
-# A prepend a previous run persisted is repositioned, not accepted: otherwise a rerun
-# inside conda leaves our directory ahead of it for ever (#5871).
-# Only an exact whole-line match on what this writer writes is touched, and the content is
-# copied back into the ORIGINAL file so a symlinked rc keeps its link, mode and owner.
+# Repoint a persisted prepend inside conda (#5871). Exact whole-line match only; content is
+# copied back into the original file so a symlinked rc keeps its link, mode and owner.
_unsloth_repoint_rc_line() {
[ -f "$1" ] || return 1
- # OURS, not merely matching: a hand-written `export PATH="$HOME/.local/bin:$PATH"` is a
- # line users have too, and demoting theirs would move that whole directory behind the
- # rest of PATH for good. The `# Added by Unsloth` marker above the line is the ownership
- # record, so a line without one is left alone.
+ # Only lines under our `# Added by Unsloth` marker; never demote a user's own export.
_URRL_OLD="$2" awk '
$0 == ENVIRON["_URRL_OLD"] && prev ~ /^# Added by Unsloth/ { found = 1 }
{ prev = $0 }
END { exit(found ? 0 : 1) }
' "$1" 2>/dev/null || return 1
- # Staged and renamed, because `cat tmp > file` truncates the profile first and an
- # interrupt leaves wreckage. Onto the RESOLVED path: renaming over a chezmoi or stow
- # symlink would replace it with a regular file. `readlink -f` is GNU-only, hence the walk.
+ # Staged and renamed onto the resolved path; `readlink -f` is GNU-only, hence the walk.
_urrl_real="$1"
_urrl_hops=0
while [ -L "$_urrl_real" ] && [ "$_urrl_hops" -lt 40 ]; do
@@ -3116,9 +2716,7 @@ _unsloth_repoint_rc_line() {
done
[ -f "$_urrl_real" ] || return 1
_urrl_tmp="$_urrl_real.unsloth-tmp.$$"
- # `cp -p` keeps the original's mode; without it the umask masks it and a 0644 .bashrc
- # comes back 0600. ENVIRON, not `-v`: POSIX awk decodes backslash escapes in `-v`, so an
- # escaped path arrived as something else and renamed an unchanged file.
+ # `cp -p` keeps the mode. ENVIRON, not `-v`: awk decodes backslash escapes in `-v`.
if { cp -p -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null \
|| cp -- "$_urrl_real" "$_urrl_tmp" 2>/dev/null; } \
&& _URRL_OLD="$2" _URRL_NEW="$3" awk '
@@ -3128,7 +2726,6 @@ _unsloth_repoint_rc_line() {
&& mv -f -- "$_urrl_tmp" "$_urrl_real" 2>/dev/null; then
return 0
fi
- # The original is untouched on every failure above; only the staged copy needs removing.
rm -f -- "$_urrl_tmp" 2>/dev/null
return 1
}
@@ -3143,47 +2740,30 @@ _setup_persist_uv_path() {
[ -n "${HOME:-}" ] || return 0
[ -z "${UV_NO_MODIFY_PATH:-}" ] || return 0
[ -z "${UV_UNMANAGED_INSTALL:-}" ] || return 0
- # The PATH a new shell inherits, not the one this process has already prepended to, and
- # compared entry by entry: a directory holding *, ? or [ is a glob inside a case pattern.
- # Already on the login PATH BECAUSE a previous run wrote the line, and inside a conda
- # environment that line is in the wrong place, so the repointing pass has to run before
- # this early return rather than after it. `_setup_repoint_only` makes the rest of the
- # function a no-op: it repositions what is there and adds nothing.
+ # Compare against the login PATH entry by entry (globs in case patterns). Repoint before
+ # the early return; _setup_repoint_only makes the rest a no-op.
_setup_repoint_only=false
if _setup_path_has_dir "${_SETUP_LOGIN_PATH:-$PATH}" "$_supp_dir"; then
_unsloth_conda_env_active || return 0
_setup_repoint_only=true
fi
- # ~/.config, not XDG_CONFIG_HOME, because that is where astral's installer put its own fish
- # file, and it is written regardless of the current shell for the same reason.
+ # ~/.config, not XDG_CONFIG_HOME: where astral's installer put its fish file.
_supp_fish_dir="$HOME/.config/fish/conf.d"
if mkdir -p "$_supp_fish_dir" 2>/dev/null; then
_supp_fish="$_supp_fish_dir/unsloth.fish"
- # Single-quoted: an unquoted path with a space is two arguments to fish_add_path.
_supp_quoted=$(printf '%s' "$_supp_dir" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")
- # fish_add_path PREPENDS, and that ordering outlives the conda activation (#5871),
- # so the conda arm appends. All three flags are load-bearing:
- # -a alone appends to $fish_user_paths, which fish prepends to PATH, so -P is what
- # makes it an append to PATH at all
- # -P edits $PATH for the session, right for a conf.d drop-in read after conda.fish
- # -m moves an entry a bare `fish_add_path` from an older install already put in
- # the universal $fish_user_paths; without it the append is a no-op
- # https://fishshell.com/docs/current/cmds/fish_add_path.html
+ # fish_add_path prepends; the conda arm appends. -a -P makes it a PATH append, -m moves an
+ # existing universal entry. https://fishshell.com/docs/current/cmds/fish_add_path.html
_supp_fish_line="fish_add_path '$_supp_quoted'"
if _unsloth_conda_env_active; then
_supp_fish_line="fish_add_path -a -P -m '$_supp_quoted'"
- # Every earlier spelling puts the directory in front of PATH, the bare -a by way of
- # $fish_user_paths, and the -a -P line without -m cannot move an entry already in PATH,
- # so any of them left by a previous run is repointed rather than accepted as present.
+ # Earlier spellings all prepend, so they are repointed rather than accepted.
for _supp_stale in "fish_add_path '$_supp_quoted'" "fish_add_path -a '$_supp_quoted'" \
"fish_add_path -a -P '$_supp_quoted'"; do
_unsloth_repoint_rc_line "$_supp_fish" "$_supp_stale" "$_supp_fish_line" || true
done
fi
- # The exact line, not any occurrence: /opt/uv-old must not pass for /opt/uv. EVERY
- # spelling counts as present, or a run outside conda adds a second line for a
- # directory a run inside it already registered; the bare -a one is kept because an
- # install from before this fix wrote it.
+ # Exact line, any spelling counts as present, so no duplicate line is added.
if [ "$_setup_repoint_only" != true ] && ! grep -v '^[[:space:]]*#' "$_supp_fish" 2>/dev/null \
| grep -qxF -e "fish_add_path '$_supp_quoted'" -e "fish_add_path -a '$_supp_quoted'" \
-e "fish_add_path -a -P '$_supp_quoted'" \
@@ -3192,26 +2772,15 @@ _setup_persist_uv_path() {
echo "$_supp_fish_line" >> "$_supp_fish"
fi
fi
- # An entry has to be active, whole and on a line that SETS PATH: a commented-out export,
- # /opt/uv-old when we want /opt/uv, and PYTHONPATH=/opt/uv are none of them, and taking any
- # for an entry leaves the next shell unable to resolve uv.
+ # Must be active, whole and on a line that sets PATH (not PYTHONPATH or a comment).
_supp_path_line='(^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper)'
_supp_grep=$(printf '%s' "$_supp_dir" | sed 's/[].[\\()*+?{}|^$\/]/\\&/g')
- # Escaped: the line is double-quoted, so a path holding $, ` or " would be expanded or
- # terminated by the shell that reads it.
+ # Escaped: the line is double-quoted in the profile.
_supp_literal=$(printf '%s' "$_supp_dir" | sed 's/[\\"$`]/\\&/g')
- # A persisted PREPEND outlives the activation and leaves conda resolving out of our
- # directory in every later shell (#5871). Inside one, write the same line as an APPEND;
- # the grep below matches either spelling, so no second line is added. install.ps1 makes
- # the same choice for the Windows registry.
+ # Inside conda, write an APPEND so conda's ordering survives (#5871).
_supp_export_line="export PATH=\"$_supp_literal:\$PATH\""
_supp_export_prepend="$_supp_export_line"
- # And the $HOME-relative spelling of the same prepend, because install.sh writes the shim
- # line that way and this script runs standalone on an update: _SETUP_LOGIN_PATH holds the
- # EXPANDED directory, which is what selects the repoint-only branch below, while the line
- # sitting in the profile says $HOME. Matching only the expanded form meant the rewrite
- # never fired and the stale prepend stayed ahead of the active conda environment. $HOME is
- # left unexpanded on purpose; only the rest of the path is escaped.
+ # Also match install.sh's $HOME-relative prepend; $HOME stays unexpanded.
_supp_export_home_prepend=""
case "$_supp_dir" in
"$HOME"/*)
@@ -3223,8 +2792,6 @@ _setup_persist_uv_path() {
_supp_export_line="export PATH=\"\$PATH:$_supp_literal\""
fi
if [ "$_setup_repoint_only" = true ]; then
- # The POSIX repointing pass, then out: nothing here may append a line the caller's
- # guard decided against.
for _supp_profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \
"$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do
[ -f "$_supp_profile" ] || continue
@@ -3237,19 +2804,11 @@ _setup_persist_uv_path() {
done
return 0
fi
- # Every startup file astral's installer wired, because it is the installer this replaced:
- # ~/.profile always, each bash file that exists, and zsh under ZDOTDIR. Writing only the
- # file for the shell that happens to be running would leave a bash user whose .bash_profile
- # does not source .bashrc, or anyone who later switches shells, without uv on PATH.
+ # Every startup file astral's installer wired: ~/.profile, each existing bash file, zsh under ZDOTDIR.
for _supp_profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" \
"$HOME/.bash_login" "${ZDOTDIR:-$HOME}/.zshrc" "${ZDOTDIR:-$HOME}/.zshenv"; do
if [ "$_supp_profile" != "$HOME/.profile" ] && [ ! -f "$_supp_profile" ]; then continue; fi
- # Repointing comes BEFORE the presence check, not inside it. The check below matches
- # the EXPANDED directory, so it cannot see the $HOME-relative prepend install.sh
- # writes: gating the rewrite on it left that spelling in place and appended a second
- # line underneath it, which is both a duplicate entry and the original ordering bug,
- # since the surviving prepend still resolves ahead of the active conda environment.
- # Rewriting first also makes the check find the append it just produced.
+ # Repoint before the presence check: the check cannot see the $HOME-relative prepend.
if _unsloth_conda_env_active; then
_unsloth_repoint_rc_line "$_supp_profile" "$_supp_export_prepend" \
"$_supp_export_line" || true
@@ -3258,8 +2817,6 @@ _setup_persist_uv_path() {
"$_supp_export_line" || true
fi
fi
- # Only lines that actually set PATH count: `UV_CACHE=/opt/uv` and `PYTHONPATH=/opt/uv`
- # are not PATH entries, and taking one for an entry leaves the next shell without uv.
if grep -v '^[[:space:]]*#' "$_supp_profile" 2>/dev/null \
| grep -E "$_supp_path_line" \
| grep -qE "(^|[^[:alnum:]_.~/-])$_supp_grep([^[:alnum:]_.~/-]|\$)"; then
@@ -3279,8 +2836,6 @@ _SETUP_UV_TOO_OLD=""
# compromised emSign CAs (GHSA-hq85-5cpj-mr62).
_SETUP_UV_MIN_VERSION="0.13.4"
-# True when uv's --version line names a release at least as new as $2. Unreadable is false: the
-# candidate is left alone and the download runs, as it did before this search existed.
_setup_uv_version_at_least() {
[ -n "$1" ] || return 1
printf '%s\n' "$1" | awk -v floor="$2" '
@@ -3312,22 +2867,16 @@ _setup_uv_version_at_least() {
'
}
-# Answers in _SETUP_UV_DIR: under command substitution the miss diagnostics above would die
-# with the subshell.
+# Answers in _SETUP_UV_DIR: diagnostics would die with a command-substitution subshell.
_setup_find_installed_uv() {
- # The uv a previous run installed but this process's PATH lacks (a desktop shell launched
- # before the install, a CI step, an unread profile line): the miss re-downloaded the pinned
- # archive on every update, 42 of a 53 s Windows no-op. Same priority list
- # _setup_install_uv_pinned writes to; it has to run, not merely exist.
- # Cleared on entry: a second search would otherwise report the first one's destinations.
+ # Find a uv a previous run installed but this PATH lacks; it must run, not merely exist.
+ # Cleared on entry so a second search does not report the first one's misses.
_SETUP_UV_PROBE_MISS=""
_SETUP_UV_LOOKED=""
_SETUP_UV_DIR=""
_SETUP_UV_TOO_OLD=""
_sfu_seen=""
- # A file, not a command substitution: whatever the candidate starts inherits the probe's
- # stdout, so a pipe holds this open until the last descendant lets go, which is the hang the
- # ceiling exists to prevent. No file means no version, so no reuse: the old download path.
+ # A file, not $(): a descendant holding the pipe open is the hang the ceiling prevents.
_sfu_ver_file=""
if command -v mktemp >/dev/null 2>&1; then
_sfu_ver_file=$(mktemp 2>/dev/null) || _sfu_ver_file=""
@@ -3335,19 +2884,15 @@ _setup_find_installed_uv() {
for _sfu_dir in "${UV_INSTALL_DIR:-}" "${UV_UNMANAGED_INSTALL:-}" "${XDG_BIN_HOME:-}" \
"${XDG_DATA_HOME:+$XDG_DATA_HOME/../bin}" "${HOME:+$HOME/.local/bin}"; do
[ -n "$_sfu_dir" ] || continue
- # Once per directory however many variables name it, as the PowerShell finder does: a
- # hanging candidate costs the ceiling once per name (126 s over four tiers, 42 s for one).
+ # Once per directory, so a hanging candidate costs the ceiling once.
case "$_sfu_seen" in *"|$_sfu_dir|"*) continue ;; esac
_sfu_seen="$_sfu_seen|$_sfu_dir|"
_SETUP_UV_LOOKED="${_SETUP_UV_LOOKED:+$_SETUP_UV_LOOKED, }$_sfu_dir/uv"
[ -x "$_sfu_dir/uv" ] || continue
- # Bounded, like the pinned installer's probe. Asked twice: one miss (an antivirus scan
- # holding a fresh binary) sent setup to the pinned download, which put an OLDER uv
- # over this one and moved the manifest's uv_version on the next pass.
+ # Asked twice: one transient miss would downgrade uv via the pinned download.
if _setup_probe_version "$_sfu_dir/uv" "${_sfu_ver_file:-/dev/null}" ||
{ sleep 2; _setup_probe_version "$_sfu_dir/uv" "${_sfu_ver_file:-/dev/null}"; }; then
- # `read`, not `cat`: this branch has to hold on a bare PATH, and an empty file
- # returning non-zero is not a reason for `set -e` to end setup.
+ # `read`, not `cat`: must work on a bare PATH and not trip set -e on an empty file.
_sfu_ver=""
if [ -n "$_sfu_ver_file" ]; then
read -r _sfu_ver < "$_sfu_ver_file" 2>/dev/null || _sfu_ver=""
@@ -3393,8 +2938,7 @@ if command -v uv &>/dev/null && [ -z "$_SETUP_UV_PATH_OLD" ]; then
USE_UV=true
elif _setup_find_installed_uv; then
_setup_uv_dir="$_SETUP_UV_DIR"
- # Read-only reuse, fine under a stage root. Appended: a python beside uv (~/.local/bin
- # often has one) must not step in front of the staged $VENV_DIR/bin/python.
+ # Appended: a python beside uv must not shadow the staged $VENV_DIR/bin/python.
export PATH="$PATH:$_setup_uv_dir"
if [ -n "$_SETUP_UV_PATH_OLD" ]; then
# In front of the old uv on PATH, with the venv's bin still first.
@@ -3463,7 +3007,7 @@ fast_install_sidecar() (
unset UV_OVERRIDE
fast_install "$@" && return 0
_fis_rc=$?
- # A pin the PyPI mirror has not synced yet: one rerun with pypi.org behind it, armed only after a slow pypi.org was switched.
+ # A pin the PyPI mirror has not synced yet: one rerun with pypi.org behind it.
for _fis_entry in ${_UNSLOTH_MIRROR_SPARE:-}; do
[ "${_fis_entry%%|*}" = unsynced ] || continue
for _fis_pair in $(printf '%s' "${_fis_entry#*|}" | tr '|' ' '); do export "$_fis_pair"; done
@@ -3475,21 +3019,15 @@ fast_install_sidecar() (
cd "$SCRIPT_DIR"
-# On Colab without a venv, skip venv-dependent Python deps sections but
-# continue to llama.cpp install so GGUF inference is available.
if [ "$_COLAB_NO_VENV" = true ]; then
step "python" "backend deps installed into system Python"
substep "continuing to llama.cpp install for GGUF inference support"
fi
# ── Check if Python deps need updating ──
-# Compare installed package version against PyPI latest.
-# Skip all Python dependency work if versions match (fast update path).
-# On Colab (no venv), skip this version check (it needs $VENV_DIR/bin/python)
-# but still run install_python_stack below (it uses sys.executable).
+# Fast update path: skip Python deps when the installed version matches PyPI.
_setup_install_is_verified() {
- # Does the venv prove a finished install? Exit 0 yes, 1 no. One implementation for the
- # incomplete-install guard and the offline rule, so they cannot disagree about "complete".
+ # Single definition of a complete install, shared by the incomplete-install guard and offline rule.
"$VENV_DIR/bin/python" -c "
import os, sys
sys.path.insert(0, sys.argv[1])
@@ -3510,8 +3048,7 @@ sys.exit(0 if install_manifest.verify_install(**deep)['ok'] else 1)
}
_uv_offline_requested() {
- # UV_OFFLINE is uv's own "no network" switch, and every install here goes through uv. uv's
- # boolish spellings (uv 0.10.7): y, yes, t, true, on, 1.
+ # uv's boolish UV_OFFLINE spellings (uv 0.10.7): y, yes, t, true, on, 1.
_uvo=${UV_OFFLINE:-}
_uvo=${_uvo#"${_uvo%%[![:space:]]*}"}
_uvo=${_uvo%"${_uvo##*[![:space:]]}"}
@@ -3523,13 +3060,8 @@ _uv_offline_requested() {
}
_fast_path_escapes() {
- # Every reason an "up to date" package is still not a working install. Both fast-path
- # callers run it, so an offline skip meets the online bar. The incomplete-install check
- # stays out: each caller words it differently.
- # First, costing no probe: the user asked by hand. This branch never starts
- # install_python_stack.py, whose hatch this is, so the variable did nothing here. Values are
- # that module's ("1", "true", "yes", "on"), NOT _uv_offline_requested's bare `t` and `y`.
+ # Values are install_python_stack.py's ("1", "true", "yes", "on"), not _uv_offline_requested's.
_fpe_full=${UNSLOTH_STUDIO_FULL_DEPS:-}
_fpe_full=${_fpe_full#"${_fpe_full%%[![:space:]]*}"}
_fpe_full=${_fpe_full%"${_fpe_full##*[![:space:]]}"}
@@ -3556,8 +3088,7 @@ sys.exit(0 if (major, minor) >= (4, 14) else 1)
substep "anyio >=4.14 found (#6483) -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
fi
- # Same shape: a pre-pin tokenizers the installed transformers rejects breaks every `import
- # transformers` while $_PKG_NAME is current. Ask the metadata, not the broken import.
+ # A pre-pin tokenizers breaks `import transformers`; ask the metadata, not the import.
if "$VENV_DIR/bin/python" -c "
import sys
from importlib.metadata import PackageNotFoundError, requires, version
@@ -3576,7 +3107,7 @@ sys.exit(0 if windows and installed not in windows[0] else 1)
substep "installed transformers rejects the installed tokenizers -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
fi
- # Failures and timeouts keep the fast path, as for the ROCm probe below.
+ # Failures and timeouts keep the fast path.
_fpe_missing_torch=false
if command -v timeout >/dev/null 2>&1; then
timeout -k 5 180 "$VENV_DIR/bin/python" \
@@ -3589,7 +3120,6 @@ sys.exit(0 if windows and installed not in windows[0] else 1)
if [ "$_fpe_missing_torch" = true ]; then
# Offline the pass can only fail, and failing it loses the verified install.
if [ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; then
- # Silent once another escape forced the pass: torch comes back with it.
if [ "$_SKIP_PYTHON_DEPS" = true ]; then
substep "PyTorch is not installed but UV_OFFLINE is set -- left for the next online update"
fi
@@ -3599,8 +3129,7 @@ sys.exit(0 if windows and installed not in windows[0] else 1)
fi
fi
unset _fpe_missing_torch
- # The pinned Diffusers main build is installed only by the pass, so an install that never ran
- # that step (updated by an installer that predates it) kept the release while current.
+ # The pinned Diffusers main build is installed only by the pass.
_fpe_diffusers=false
if command -v timeout >/dev/null 2>&1; then
timeout -k 5 180 "$VENV_DIR/bin/python" \
@@ -3619,8 +3148,6 @@ sys.exit(0 if windows and installed not in windows[0] else 1)
fi
fi
unset _fpe_diffusers
- # If the desktop app specifies a minimum required backend version and the installed
- # package is older than that requirement, force the dependency pass to upgrade it.
if [ -n "${UNSLOTH_DESKTOP_BACKEND_VERSION:-}" ]; then
if ! "$VENV_DIR/bin/python" -c "
import re, sys
@@ -3638,19 +3165,16 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
_SKIP_PYTHON_DEPS=false
fi
fi
- # An XPU pin the venv does not satisfy: only the dependency pass acts on it, so a CPU install
- # switched to UNSLOTH_TORCH_INDEX_FAMILY=xpu kept its wheel forever. Mirrors setup.ps1.
+ # Only the dependency pass acts on an XPU pin. Mirrors setup.ps1.
_setup_pin="${UNSLOTH_TORCH_INDEX_URL:-${UNSLOTH_TORCH_INDEX_FAMILY:-}}"
# Strip query/fragment first: an authenticated mirror (…/whl/xpu?token=...) is a supported pin.
_setup_pin="${_setup_pin%%\#*}"
_setup_pin="${_setup_pin%%\?*}"
# ALL trailing slashes, like the shared leaf parsers: a single %/ leaves "…/xpu/" behind.
while [ "${_setup_pin%/}" != "$_setup_pin" ]; do _setup_pin="${_setup_pin%/}"; done
- # Exact, lowercased leaf, like every other leaf parser: a suffix match (…/private-xpu) would
- # force a pass _ensure_xpu_torch declines to act on.
+ # Exact, lowercased leaf: a suffix match (…/private-xpu) would force a pass _ensure_xpu_torch declines.
_setup_pin_leaf=$(printf '%s' "${_setup_pin##*/}" | tr '[:upper:]' '[:lower:]')
- # Disk, no interpreter: a wedged Intel driver cannot hang `import torch`. Read unconditionally:
- # the pin is one-shot, the installed wheel is the durable signal.
+ # Read from disk with no interpreter: a wedged Intel driver cannot hang import torch.
_setup_pin_ok=false
_setup_pin_is_xpu=false
for _setup_pin_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
@@ -3671,9 +3195,7 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
esac
break
done
- # Correct torch is not enough: a leftover generic triton shadows the XPU build and only the
- # pass swaps it. Non-XPU leaves matched EXACTly, as install_python_stack does: a prefixed leaf
- # (cu128-private) is a custom pin it never repairs.
+ # A leftover generic triton shadows the XPU build. Non-XPU leaves matched exactly.
_setup_known_nonxpu_leaf() {
case "$1" in
cpu|gfx[0-9]*) return 0 ;;
@@ -3709,13 +3231,10 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
substep "generic triton shadows the XPU build -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_pin_known_nonxpu" = true ]; then
- # Migrating AWAY from XPU: only install_python_stack acts on the pin.
substep "$_setup_pin_leaf pinned over an XPU wheel -- forcing dependency pass to migrate..."
_SKIP_PYTHON_DEPS=false
fi
- # An explicit cu*/rocm*/cpu pin over a torch labelled with ANOTHER family: only the
- # dependency pass reinstalls from the pin, and the compare above would keep the old wheel.
- # Labelled wheels only (an untagged torch names no family), custom leaves left alone.
+ # Explicit cu*/rocm*/cpu pin over a torch labelled with another family; untagged torch is left alone.
_setup_pin_have_family=""
case "${_setup_pin_ver:-}" in
*+cu[0-9]*) _setup_pin_have_family=cu ;;
@@ -3737,22 +3256,19 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
substep "$_setup_pin_leaf pinned over a +$_setup_pin_have_family torch wheel -- forcing dependency pass to reinstall torch from the pin..."
_SKIP_PYTHON_DEPS=false
fi
- # Explicit under `set -e`: an arm ending in a false command would abort the update. The decision
- # is in _SKIP_PYTHON_DEPS; the exit status carries nothing.
+ # Explicit under `set -e`: the decision is in _SKIP_PYTHON_DEPS.
return 0
}
_SKIP_PYTHON_DEPS=false
_SKIP_VERSION_CHECK=false
-# Set here, not left to `${_OFFLINE_FAST_PATH:-false}`, so an exported value from the caller's
-# environment cannot reach it. setup.ps1 already initialises $script:OfflineFastPath the same way.
+# Set here so an exported value from the caller cannot reach it.
_OFFLINE_FAST_PATH=false
if [ "$_COLAB_NO_VENV" = true ]; then
_SKIP_VERSION_CHECK=true
fi
_PKG_NAME="${STUDIO_PACKAGE_NAME:-unsloth}"
if [ "$_SKIP_VERSION_CHECK" != true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ] && [ "${STUDIO_LOCAL_INSTALL:-0}" != "1" ]; then
- # Only check when NOT called from install.sh (which just installed the package)
_INSTALLED_VERSION_PROBE_EXIT=0
if INSTALLED_VER=$("$VENV_DIR/bin/python" -c "
import sys
@@ -3777,21 +3293,16 @@ sys.exit(2 if conflict else (0 if version else 1))
elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then
step "python" "$_PKG_NAME $INSTALLED_VER is up to date"
_SKIP_PYTHON_DEPS=true
- # An interrupted install leaves $_PKG_NAME current while studio.txt never finished, so
- # update and the Repair button no-op on a venv that cannot boot.
+ # An interrupted install leaves the package current while studio.txt never finished.
if ! _setup_install_is_verified; then
substep "studio install incomplete -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
fi
- # ...and every remaining escape, shared with the offline rule below.
_fast_path_escapes
elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ]; then
substep "$_PKG_NAME $INSTALLED_VER -> $LATEST_VER available, updating..."
elif [ -z "$LATEST_VER" ]; then
- # PyPI unreachable: updating to be safe stays the default, since it is usually a blip.
- # UV_OFFLINE is not a blip, so a verified tree is kept instead, on the incomplete-install
- # guard's evidence and held to the up-to-date branch's escapes (it can still be below the
- # floor).
+ # UV_OFFLINE is not a blip: keep a verified tree, still held to the fast-path escapes.
if [ -n "$INSTALLED_VER" ] && _uv_offline_requested && _setup_install_is_verified; then
substep "PyPI is unreachable and UV_OFFLINE is set -- keeping the verified install"
_SKIP_PYTHON_DEPS=true
@@ -3803,8 +3314,7 @@ sys.exit(2 if conflict else (0 if version else 1))
fi
fi
-# A current package can still have CPU/CUDA torch because the fast path skips ROCm repair.
-# Exit 0 forces the dependency pass; failures and timeouts keep the fast path.
+# The fast path skips ROCm repair. Exit 0 forces the pass; failures keep the fast path.
if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
_setup_amd_torch_stale=false
if command -v timeout >/dev/null 2>&1; then
@@ -3822,10 +3332,7 @@ if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
fi
fi
-# Same for an NVIDIA host left on a CPU wheel (GPU hidden or driver broken when it was
-# installed, a dependency step that resolved torch from PyPI, or a GPU added since). The
-# CUDA repair is inside the pass too, so without this the wheel survives every "up to
-# date" update. setup.ps1 heals this at its stale-venv check; this is the POSIX half.
+# Same for an NVIDIA host left on a CPU wheel. setup.ps1 heals this at its stale-venv check.
if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
_setup_cuda_torch_stale=false
if command -v timeout >/dev/null 2>&1; then
@@ -3880,10 +3387,7 @@ fi
_frontend_bg_reap
# ── 6b. Pre-install transformers 5.x into .venv_t5_530/, .venv_t5_550/, and .venv_t5_510/ ──
-# Models like GLM-4.7-Flash, Qwen3 MoE need transformers>=5.3.0.
-# Gemma 4 models need transformers>=5.5.0; Gemma 4 Unified needs 5.10.x.
-# Pre-install into separate directories to avoid runtime pip overhead.
-# The training subprocess prepends the appropriate dir to sys.path.
+# Separate dirs avoid runtime pip overhead; training prepends the right one to sys.path.
_target_has_pkg_version() {
_thpv_dir="$1"
_thpv_pkg="$2"
@@ -3921,7 +3425,6 @@ _sidecar_drop_tiktoken() {
}
_sidecar_retire_after_failed_tiktoken() {
- # `|| true`: best effort under `set -e`, or an undeletable file fails an otherwise fine update.
rm -rf "$1" 2>/dev/null || true
substep "the $2 sidecar kept part of a failed tiktoken install; retired, rebuilt on the next update"
}
@@ -3929,13 +3432,10 @@ _sidecar_retire_after_failed_tiktoken() {
_sidecar_top_up_tiktoken() {
_stt_dir="$1"
_stt_label="$2"
- # Under the offline keep this would reach the network through fast_install's pip fallback,
- # and give a deferred tier a directory holding tiktoken alone.
+ # Offline: fast_install's pip fallback would reach the network.
[ "${_OFFLINE_FAST_PATH:-false}" = true ] && return 0
- # And under UV_OFFLINE without the fast path: the pip fallback would reach for the network.
_uv_offline_requested && return 0
- # Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the
- # other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.
+ # RECORD is written last; a recordless dist-info goes first since uv cannot uninstall it.
for _stt_info in "$_stt_dir"/tiktoken-*.dist-info; do
if [ -d "$_stt_info" ] && [ ! -f "$_stt_info/RECORD" ]; then
rm -rf "$_stt_info" || true # `|| true`: set -e; the reinstall below handles a leftover
@@ -3949,7 +3449,7 @@ _sidecar_top_up_tiktoken() {
fi
done
unset _stt_meta
- # Dropping the metadata is what makes uv reinstall instead of calling the pin satisfied.
+ # Dropping the metadata makes uv reinstall instead of calling the pin satisfied.
for _stt_info in "$_stt_dir"/tiktoken-*.dist-info; do
[ -d "$_stt_info" ] && { rm -rf "$_stt_info" || true; }
done
@@ -3966,16 +3466,14 @@ _sidecar_top_up_tiktoken() {
}
_sidecar_current() {
- # One predicate for both shells: the version grep called a half-written sidecar current.
_sc_dir="$1"
_sc_ver="$2"
[ -d "$_sc_dir" ] || return 1
- # No shim: answer from the grep, as setup.ps1 does, or every tier reads stale.
+ # No shim: answer from the grep, as setup.ps1 does.
if [ ! -f "$SCRIPT_DIR/install_manifest.py" ]; then
_target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"
return $?
fi
- # Colab has no venv interpreter but the stdlib-only shim runs under its own python.
_sc_python="$VENV_DIR/bin/python"
if [ ! -x "$_sc_python" ]; then
_sc_python=$(command -v python 2>/dev/null || command -v python3 2>/dev/null || true)
@@ -3985,7 +3483,7 @@ _sidecar_current() {
_target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"
return $?
fi
- # Bounded where timeout exists: the shim cannot interrupt a stalled read. A timeout is stale.
+ # Bounded where timeout exists: the shim cannot interrupt a stalled read.
# shellcheck disable=SC2086 # the pins are a deliberate word-split list
if command -v timeout >/dev/null 2>&1; then
_sc_out=$(timeout -k 5 60 "$_sc_python" "$SCRIPT_DIR/install_manifest.py" sidecar "$_sc_dir" \
@@ -4013,14 +3511,13 @@ _sidecar_current() {
;;
esac
unset _sc_out
- # A failure with no marker is a dead audit, not the legacy silent exit 0.
if [ "$_sc_rc" -ne 0 ]; then
verbose_substep "sidecar $_sc_dir: audit failed (exit $_sc_rc)"
unset _sc_rc
return 1
fi
unset _sc_rc
- # An old shim exits 0 silently: fall back to the grep this replaced.
+ # An old shim exits 0 silently: fall back to the grep.
_target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"
}
@@ -4053,12 +3550,11 @@ _install_sidecar() {
_NEED_T5_530=false
_NEED_T5_550=false
_NEED_T5_510=false
-# The migration is a wipe and three rebuilds from a cache that may be cold, and the legacy tree is
-# the only sidecar, so under UV_OFFLINE it waits for the next online update.
+# Under UV_OFFLINE the legacy-tree migration (wipe + rebuilds) waits for an online update.
if [ -d "$STUDIO_HOME/.venv_t5" ] && { [ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; }; then
substep "legacy transformers sidecar left in place -- UV_OFFLINE is set, migration waits for the next online update"
elif [ -d "$STUDIO_HOME/.venv_t5" ]; then
- # Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.
+ # A staged run's venvs may never be activated, so only the live update migrates.
if [ -z "$STAGE_ROOT" ]; then
_assert_studio_owned_or_absent "$STUDIO_HOME/.venv_t5" "legacy transformers sidecar venv"
rm -rf "$STUDIO_HOME/.venv_t5"
@@ -4070,17 +3566,14 @@ fi
_sidecar_current "$VENV_T5_530_DIR" "5.3.0" || _NEED_T5_530=true
_sidecar_current "$VENV_T5_550_DIR" "5.5.0" || _NEED_T5_550=true
_sidecar_current "$VENV_T5_510_DIR" "5.10.2" || _NEED_T5_510=true
-# A sidecar rebuild is a wipe and four fetches, through a pip fallback that reaches the network,
-# so under the offline keep it waits for the next online update; the runtime self-heal covers a
-# missing tier meanwhile. A deferred tier keeps its own flag so it is not reported "current".
+# Sidecar rebuilds reach the network; defer under offline keep. Deferred tiers are not reported current.
_DEFER_T5_530=false
_DEFER_T5_550=false
_DEFER_T5_510=false
-# UV_OFFLINE without the fast path: the same wipe and fetches, through a pip fallback that does not
-# read UV_OFFLINE. Every stale or missing tier is left for the next online update.
+# The pip fallback does not read UV_OFFLINE.
if [ "${_OFFLINE_FAST_PATH:-false}" != true ] && _uv_offline_requested; then
for _ofp in "530 5.3.0" "550 5.5.0" "510 5.10.2"; do
- # Not `set --`: this runs at top-level scope, where that overwrites the script's own "$@".
+ # Not `set --`: at top-level scope that overwrites the script's own "$@".
_ofp_key=${_ofp%% *}; _ofp_ver=${_ofp#* }
if eval "[ \"\$_NEED_T5_$_ofp_key\" = true ]"; then
substep "transformers $_ofp_ver sidecar is stale or missing but UV_OFFLINE is set -- left for the next online update"
@@ -4129,10 +3622,8 @@ fi
fi
# ── GPU detection summary (mirrors setup.ps1 step "gpu" block) ──
-# WSL2 ROCDXG: the system rocminfo enumerates the GPU over /dev/dxg only when
-# HSA_ENABLE_DXG_DETECTION=1 (a no-op on bare metal), and /opt/rocm/bin can be
-# off PATH outside login shells (the profile.d drop-in). Seed both before the
-# probes or a ROCDXG WSL host is misdetected as CPU-only.
+# WSL2 ROCDXG: rocminfo sees the GPU over /dev/dxg only with HSA_ENABLE_DXG_DETECTION=1,
+# and /opt/rocm/bin may be off PATH.
export HSA_ENABLE_DXG_DETECTION="${HSA_ENABLE_DXG_DETECTION:-1}"
if ! command -v rocminfo >/dev/null 2>&1 && [ -x /opt/rocm/bin/rocminfo ]; then
PATH="$PATH:/opt/rocm/bin"
@@ -4148,9 +3639,7 @@ _setup_rocr_uuid_declined=0
_setup_mkt=""
_setup_amd_records=""
-# Pair each rocminfo GPU gfx id with its marketing name instead of using the CPU-first
-# global name (#7307). Blank names keep device ordinals; no GPU keeps the old fallback.
-# Keep in sync with install.sh.
+# Pair each rocminfo gfx id with its marketing name. Keep in sync with install.sh.
_setup_rocminfo_gpu_records() {
awk '
# Split at the first colon so embedded colons survive.
@@ -4185,13 +3674,8 @@ _setup_rocminfo_gpu_records() {
'
}
-# amd-smi enumerates in discovery order over its KFD view; HIP_VISIBLE_DEVICES and
-# ROCR_VISIBLE_DEVICES index HIP/ROCr order, which the library derives from the KFD node
-# id instead. The two disagree on real hardware (MI350X SPX/NPS1), and _gfx here becomes
-# --rocm-gfx, so an untranslated ordinal can fetch a prebuilt for another card's arch.
-# `amd-smi list -e` is the map AMD publishes for this (HIP_ID, ROCm 6.4.0+); the Python
-# side reads the same field in utils/hardware/amd.py get_hip_id_by_gpu_index.
-# Keep in sync with install.sh.
+# amd-smi lists in discovery order but HIP/ROCR masks index HIP order; map via `amd-smi list -e`
+# (HIP_ID). Keep in sync with install.sh.
_setup_amd_smi_hip_order() {
# POSIX awk forbids a newline in a -v value (fatal under gawk --posix), so records arrive
# on stdin before the map, sentinel-separated. Line 1 names the index space.
@@ -4224,10 +3708,7 @@ _setup_amd_smi_hip_order() {
'
}
-# One `gfx|marketing name` per adapter, in `GPU: N` order, so the mask picks both halves
-# of one device. Was: arch indexed, name always adapter 0's -- and on amd-smi 6.1.1, which
-# has no TARGET_GRAPHICS_VERSION, that name is what --rocm-gfx is inferred from.
-# Keep in sync with install.sh.
+# One `gfx|name` per adapter in `GPU: N` order. Keep in sync with install.sh.
_setup_amd_smi_gpu_records() {
awk '
function value(line, v) {
@@ -4268,11 +3749,7 @@ for _setup_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
[ -f "$_setup_tv" ] || continue
grep -q "^__version__ = '[^']*+xpu" "$_setup_tv" 2>/dev/null || continue
_setup_torch_is_xpu=true
- # A +xpu wheel installs fine on a host whose driver never initialises, so only the runtime
- # answer reaches the summary below. Bounded, because a stalled Intel driver wedges inside
- # `import torch`: 60s rather than the smi probes' 10s, since a cold import is seconds on its
- # own. The SIGALRM deadline lives inside the probe too, for hosts without `timeout` (base
- # macOS, minimal Linux images). Either deadline expiring means "no XPU", as a failure does.
+ # Bounded: a stalled Intel driver wedges `import torch`. SIGALRM covers hosts without timeout.
_setup_xpu_probe='import signal; signal.alarm(60); import torch,sys; sys.exit(0 if torch.xpu.is_available() else 1)'
if command -v timeout >/dev/null 2>&1; then
timeout 60 "$VENV_DIR/bin/python" -c "$_setup_xpu_probe" >/dev/null 2>&1 && _setup_xpu_ready=true
@@ -4282,19 +3759,13 @@ for _setup_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do
break
done
-# bitsandbytes carries XPU kernels (libbitsandbytes_xpu2025.so, _xpu2026.so) only from 0.50.0,
-# and unsloth's own floor is 0.45.5, so a pre-XPU wheel satisfies it forever. install.sh raises
-# the floor, but `unsloth studio update` runs THIS file, so an existing XPU user would keep a
-# kernel-less bitsandbytes and lose 4-bit QLoRA. Keyed on the wheel, not the runtime: a stalled
-# driver is no reason to skip the upgrade. --no-deps (torch and numpy are in), best effort.
+# bitsandbytes has XPU kernels only from 0.50.0; `studio update` runs this file, not install.sh.
if [ "$_setup_torch_is_xpu" = true ]; then
- # run_quiet_no_exit, NOT run_quiet: the latter exits via setup_fail, aborting an otherwise
- # fine `studio update` over a best-effort step and leaving the warning below unreachable.
+ # run_quiet_no_exit, NOT run_quiet: the latter aborts the update on a best-effort step.
run_quiet_no_exit "install bitsandbytes (xpu)" fast_install --no-deps "bitsandbytes>=0.50.0" || \
substep "[WARN] could not install an XPU-capable bitsandbytes; 4-bit QLoRA may be unavailable."
fi
-# The supported name table, as a matcher so the report below can ask it about a PEER adapter
-# without disturbing $_setup_gfx. Kept in sync with install.sh (and the PS nameArchTable).
+# Kept in sync with install.sh (and the PS nameArchTable).
# gfx1102 before gfx1100 so the spaceless "RX 7700S" lands on gfx1102 (case has no lookahead).
_setup_supported_gfx_from_name() {
_sup_gfx_in="$1"
@@ -4317,8 +3788,8 @@ _setup_supported_gfx_from_name() {
printf '%s\n' "$_sup_gfx_out"
}
-# Mirror of install.sh's table, held to it by tests/studio/install/test_rocm_arch_table_parity.py,
-# which looks both helpers up by install.sh's names: keep the _amd_* prefix, not this file's _setup_*.
+# Held to install.sh by tests/studio/install/test_rocm_arch_table_parity.py, which looks
+# helpers up by install.sh's names: keep the _amd_* prefix.
_amd_gfx_is_shadowing_integrated() {
case "$1" in
gfx90c|gfx1013|gfx1033|gfx1035|gfx1036|gfx1103|gfx1153) return 0 ;;
@@ -4326,10 +3797,7 @@ _amd_gfx_is_shadowing_integrated() {
return 1
}
-# Pick the card to install for when enumeration put an integrated GPU first (#7776). gfx906 is
-# never a candidate: naming it on a mixed host strands BOTH cards. install.sh also requires a
-# torch wheel route; deliberately omitted, since this arch selects a llama.cpp bundle resolved
-# per gfx installer-side, not a repo.amd.com wheel family. Do not "restore" that filter.
+# gfx906 is never a candidate. No torch-wheel-route filter here, unlike install.sh: do not "restore" it.
_amd_prefer_discrete_gfx() {
_apdg_devs="$1"
_apdg_sel="$2"
@@ -4354,15 +3822,11 @@ _amd_prefer_discrete_gfx() {
done <<EOF
$_apdg_devs
EOF
- # All-integrated host, or no list: keep the pick. Never returns empty for a nonempty selection.
[ -n "$_apdg_pick" ] || _apdg_pick="$_apdg_sel"
printf '%s' "$_apdg_pick"
}
-# NVIDIA priority: classify NVIDIA first and skip the AMD probes entirely on
-# a usable-NVIDIA host (mirrors _has_rocm_gpu in install_python_stack.py).
-# This also keeps a wedged rocminfo/amd-smi from hanging setup before the
-# host is classified; the AMD probes themselves run under _setup_run_smi.
+# Skip AMD probes on a usable-NVIDIA host (mirrors _has_rocm_gpu in install_python_stack.py).
if _setup_has_physical_nvidia_gpu; then
_setup_nvidia_physical=true
fi
@@ -4380,7 +3844,6 @@ if [ "$_setup_nvidia_usable" != true ]; then
elif command -v amd-smi >/dev/null 2>&1 && \
_setup_run_smi amd-smi list 2>/dev/null | awk '/^GPU[[:space:]]*[:\[][[:space:]]*[0-9]/{ found=1 } END{ exit !found }'; then
_setup_amd_detected=true
- # amd-smi owns the device list here, so its indexed records replace rocminfo's.
_setup_amd_records=$(_setup_run_smi amd-smi static --asic 2>/dev/null | _setup_amd_smi_gpu_records || true)
if [ -n "$_setup_amd_records" ]; then
_setup_amd_smi_out=$(_setup_run_smi amd-smi list -e 2>/dev/null \
@@ -4388,13 +3851,7 @@ if [ "$_setup_nvidia_usable" != true ]; then
# Expansion, not `| head -n 1`: head exiting early SIGPIPEs printf under pipefail.
_setup_amd_space=${_setup_amd_smi_out%%$'\n'*}
_setup_amd_records=$(printf '%s\n' "$_setup_amd_smi_out" | tail -n +2)
- # No map, and the adapters are not interchangeable: the mask indexes HIP order
- # while these records are in discovery order, so any ordinal is a guess. Decline
- # rather than forward a guessed --rocm-gfx to the llama.cpp and whisper
- # prebuilts. amd-smi 6.1.1 reports no TARGET_GRAPHICS_VERSION at all and the
- # arch is then inferred from the name, so an archless record is compared on its
- # name instead. Interchangeable adapters are unaffected: every ordinal gives the
- # same answer, and UNSLOTH_ROCM_GFX_ARCH still overrides below.
+ # No HIP map and unlike adapters: any ordinal is a guess, so decline rather than forward --rocm-gfx.
if [ "$_setup_amd_space" != hip ] && \
[ "$(printf '%s\n' "$_setup_amd_records" | awk -F'|' \
'NF { k = ($1 != "" ? $1 : "name:" $2); if (!(k in seen)) { seen[k]; n++ } }
@@ -4410,12 +3867,7 @@ if [ "$_setup_nvidia_usable" != true ]; then
elif [ -e /dev/kfd ] && \
awk '/vendor_id/ && $2 == 4098 { found = 1 } END { exit !found }' \
/sys/class/kfd/kfd/topology/nodes/*/properties 2>/dev/null; then
- # KFD sysfs fallback, AMD vendor_id 4098 only (mirrors install.sh
- # _has_amd_rocm_gpu): covers AMD hosts where rocminfo/amd-smi are
- # missing but the kernel exposes the GPU, so the source-build gate
- # below does not drop them to a CPU llama.cpp build. Neither a gfx arch
- # nor a marketing name is available from this path, so the report below
- # reads lspci rather than _setup_mkt when it needs to name the card.
+ # KFD sysfs fallback, AMD vendor_id 4098 only (mirrors install.sh _has_amd_rocm_gpu).
_setup_amd_detected=true
_setup_amd_records=""
fi
@@ -4430,12 +3882,10 @@ if [ "$_setup_nvidia_usable" = true ]; then
else
step "gpu" "NVIDIA GPU detected"
fi
- # An `if`, not `[ ... ] && substep ...`: the AND-list form leaves a non-zero status
- # behind on the common path where there is no driver string to print.
+ # `if`, not `&&`: the AND-list leaves a non-zero status behind.
if [ -n "$_setup_nv_driver" ]; then substep "Driver: $_setup_nv_driver"; fi
elif [ "$_setup_amd_detected" = true ]; then
- # As install.sh: ROCr picks survivors (rocminfo is already filtered, amd-smi is not), then the
- # first SET HIP-layer mask (HIP, then CUDA; empty still shadows) indexes them.
+ # As install.sh: ROCr picks survivors, then the first set HIP-layer mask indexes them.
if [ "$_setup_amd_probe" != rocminfo ] && [ -n "${ROCR_VISIBLE_DEVICES:-}" ] && [ "$ROCR_VISIBLE_DEVICES" != "-1" ]; then
_setup_rocr_keep() {
_setup_kept=$(printf '%s\n' "$1" | awk -v m="$ROCR_VISIBLE_DEVICES" '
@@ -4443,7 +3893,6 @@ elif [ "$_setup_amd_detected" = true ]; then
END { k = split(m, t, ","); for (i = 1; i <= k; i++) { gsub(/[[:space:]]/, "", t[i]); if (t[i] !~ /^[0-9]+$/) continue; x = t[i] + 0; if (x >= n || (x in s)) break; s[x] = 1; print v[x] } }')
if [ -n "$_setup_kept" ]; then printf '%s\n' "$_setup_kept"; else printf '%s\n' "$1"; fi
}
- # A UUID has no position in amd-smi's list: with unlike adapters, decline as install.sh does.
if [ -n "$(printf '%s' "$ROCR_VISIBLE_DEVICES" | tr -d '0-9, \t')" ] && \
[ "$(printf '%s\n' "${_setup_amd_records:-$_setup_gfx_all}" | awk -F'|' \
'NF { k = ($1 != "" ? $1 : "name:" $2); if (!(k in seen)) { seen[k]; n++ } } END { print n + 0 }')" -gt 1 ]; then
@@ -4465,22 +3914,16 @@ elif [ "$_setup_amd_detected" = true ]; then
case "$_setup_first" in ''|*[!0-9]*) ;; *) _setup_vis_idx=$_setup_first ;; esac
fi
if [ -n "$_setup_amd_records" ]; then
- # Records already preserve device ordinals, including duplicate arches.
_setup_amd_record=$(printf '%s\n' "$_setup_amd_records" | awk -v idx="$_setup_vis_idx" \
'NF { a[n++]=$0 } END { if(idx>=n) idx=0; if(n>0) print a[idx+0] }')
_setup_gfx=${_setup_amd_record%%|*}
_setup_mkt=${_setup_amd_record#*|}
fi
- # Only pre-TARGET_GRAPHICS_VERSION amd-smi lands here: names but no arch in the record.
if [ -z "$_setup_gfx" ]; then
_setup_gfx=$(printf '%s\n' "$_setup_gfx_all" | awk -v idx="$_setup_vis_idx" \
'NF && !seen[$0]++ { a[n++]=$0 } END { if(idx>=n) idx=0; if(n>0) print a[idx+0] }')
fi
- # The arch resolved above is what --rocm-gfx forwards below, so an iGPU enumerated first
- # takes the ROCm bundle while torch targets the dGPU (#7776; #11143 saw gfx1036 ahead of a
- # gfx1200). Runs before, and is skipped under, the UNSLOTH_ROCM_GFX_ARCH override, so a
- # declared arch wins with no repick line printed above the line that overrules it.
- # Candidates: the records, else $_setup_gfx_all, the only inventory left on the amd-smi path.
+ # An iGPU enumerated first would take the ROCm bundle (#7776). Skipped under UNSLOTH_ROCM_GFX_ARCH.
_setup_gfx_pref=""
if [ -z "${UNSLOTH_ROCM_GFX_ARCH:-}" ]; then
_setup_gfx_cands="$_setup_gfx_all"
@@ -4493,7 +3936,6 @@ elif [ "$_setup_amd_detected" = true ]; then
substep "Integrated $_setup_gfx enumerated first; installing for discrete $_setup_gfx_pref"
substep "Set UNSLOTH_ROCM_GFX_ARCH=$_setup_gfx to target the integrated GPU instead."
_setup_gfx="$_setup_gfx_pref"
- # Re-pair the banner name; empty beats pairing the new arch with the APU's name.
_setup_mkt=$(printf '%s\n' "$_setup_amd_records" | awk -F'|' -v gfx="$_setup_gfx" \
'$1 == gfx { print $2; exit }')
fi
@@ -4531,7 +3973,6 @@ EOF
substep "Tip: set UNSLOTH_ROCM_GFX_ARCH=$_setup_gfx to skip inference next time"
fi
fi
- # Say why the arch is missing, since the user can supply it and amd-smi cannot.
if [ -z "$_setup_gfx" ] && [ "$_setup_hip_map_missing" = 1 ]; then
substep "Unlike AMD adapters and no HIP id map (amd-smi list -e needs ROCm 6.4+):"
substep "cannot tell which one this session selects. Set UNSLOTH_ROCM_GFX_ARCH to pick."
@@ -4540,7 +3981,6 @@ EOF
substep "ROCR_VISIBLE_DEVICES names a GPU by UUID, which amd-smi cannot place, and the"
substep "adapters differ. Set UNSLOTH_ROCM_GFX_ARCH to pick."
fi
- # ROCm version via hipconfig, then amd-smi
_setup_rocm_ver=""
if command -v hipconfig >/dev/null 2>&1; then
_setup_rocm_ver=$(hipconfig --version 2>/dev/null | awk 'NR==1 && /^[0-9]/{print; exit}' || true)
@@ -4549,16 +3989,8 @@ EOF
_setup_rocm_ver=$(amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
'NF>1{gsub(/[[:space:]]/,"", $2); print $2; exit}' || true)
fi
- # GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1
- # and Polaris 10/20/30 (unslothai#8529). Kept apart from the inference table above on
- # purpose: it only words the report below, never selects a wheel index or prebuilt.
- # AMD's TheRock ships RDNA 1 wheels, but not on the repo.amd.com indexes routed here,
- # and never gfx803. Order is load-bearing: `case` has no negative lookahead, so the
- # RDNA 1 arms must precede Polaris or *"RX 570"* would swallow an "RX 5700 XT".
- # Names from LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14
- # professional parts LLVM omits; nothing is guessed, so Polaris 11/12 is left out.
- # Case-sensitive, unlike the regex copies: every source here (WMI, amd-smi, lspci)
- # spells these names as pci.ids does.
+ # Report-only table for arches Unsloth's ROCm wheels do not cover; never selects a wheel or prebuilt.
+ # Order matters: RDNA 1 arms precede Polaris, or *"RX 570"* would swallow "RX 5700 XT".
_setup_unsupported_gfx_from_name() {
case "$1" in
*"Radeon Pro V520"*|*"Radeon Pro 5600M"*) echo gfx1011 ;; # RDNA 1
@@ -4568,11 +4000,7 @@ EOF
*) return 1 ;;
esac
}
- # The KFD sysfs fallback above detects the GPU with neither rocminfo nor amd-smi, so it
- # leaves _setup_mkt empty -- and a runtime-less host is precisely the one this report
- # exists for. lspci still names the card there, the source install.sh already reads.
- # Deliberately NOT written back into _setup_mkt: the supported table keys on it and
- # would start feeding --rocm-gfx to the prebuilt and whisper commands on the KFD path.
+ # Not written back into _setup_mkt: that would feed --rocm-gfx on the KFD path.
_setup_unsupported_gfx_any() {
_setup_k2_ere='820M|Krackan ?(Point ?)?2|AI 5 (PRO )?330' # install.sh's _krackan2_ere
# Peer guard FIRST, so it covers the named hit too: amd-smi reports one market name,
@@ -4672,13 +4100,8 @@ EOF
step "gpu" "AMD ROCm ($_setup_gfx)"
elif [ -n "$_setup_unsup_gfx" ] || _setup_unsup_gfx=$(_setup_unsupported_gfx_any "$_setup_mkt"); then
step "gpu" "AMD GPU detected ($_setup_unsup_gfx) -- no ROCm PyTorch wheels Unsloth installs"
- # Not "training runs on CPU": with no CUDA/XPU visible, unsloth raises
- # NotImplementedError at import (unsloth/device_type.py).
- # Both lines are false under an explicit index pin, which install_python_stack.py
- # honours for any arch, so a pinned run says what it is doing instead.
- # Whitespace-trimmed, as get_torch_index_url trims them: a blank value is unset
- # there, so treating it as a pin would drop the CPU warning for nothing.
- # Distinct name: _setup_pin is the XPU block's, and these are globals in POSIX sh.
+ # unsloth raises at import without CUDA/XPU (unsloth/device_type.py). An explicit index pin
+ # changes that. Trimmed like get_torch_index_url; distinct name from the XPU block's _setup_pin.
_setup_unsup_pin="${UNSLOTH_TORCH_INDEX_URL:-}${UNSLOTH_TORCH_INDEX_FAMILY:-}"
_setup_unsup_pin=$(printf '%s' "$_setup_unsup_pin" | tr -d '[:space:]')
if [ -n "$_setup_unsup_pin" ]; then
@@ -4702,18 +4125,12 @@ EOF
_setup_gfx=gfx1153
fi
elif [ -n "$_setup_mkt" ]; then
- # Name without an arch, as install.sh does. Deliberately BELOW the unsupported
- # arm above: a card with no ROCm wheels also reaches here with a name, and
- # naming it quietly would drop the warning that training will not run.
+ # Deliberately below the unsupported arm, so the training warning is not dropped.
step "gpu" "$_setup_mkt"
else
step "gpu" "AMD ROCm"
fi
- # Only claim a path that is really there, matching install.sh. /opt/rocm is a
- # FALLBACK, not a detection, so a runtime-only ROCm host reaches here with nothing at
- # it -- and this script runs after install.sh on every install and alone on every
- # `unsloth studio update`, so leaving it unconditional here meant the run still ended
- # by advertising the directory install.sh had just stopped claiming.
+ # /opt/rocm is a fallback, not a detection: only claim a path that exists, matching install.sh.
_setup_rocm_root="${ROCM_PATH:-${HIP_PATH:-/opt/rocm}}"
if [ -d "$_setup_rocm_root" ]; then
substep "ROCm: $_setup_rocm_root"
@@ -4722,19 +4139,13 @@ EOF
fi
[ -n "$_setup_rocm_ver" ] && substep "hipconfig: $_setup_rocm_ver"
elif [ "$_setup_xpu_ready" = true ]; then
- # Ranks below NVIDIA and AMD, as in setup.ps1: those hosts get their own wheels.
step "gpu" "Intel GPU detected (XPU runtime)"
substep "PyTorch XPU (SYCL) provides training and GPU inference on this GPU."
elif [ "$_setup_torch_is_xpu" = true ]; then
- # +xpu wheel installed but torch.xpu.is_available() said no: the Intel compute driver is
- # missing or too old. Falling through would call the hardware unsupported instead.
step "gpu" "Intel GPU (XPU runtime unavailable)" "$C_WARN"
substep "PyTorch has the XPU build but cannot initialise it -- update the Intel GPU compute driver."
- # Not "runs on CPU": with neither CUDA nor XPU, unsloth/device_type.py raises at import.
- # llama.cpp is unaffected, which is what chat and GGUF run on.
substep "Until then training and GPU inference are unavailable; chat and GGUF still work."
elif [ "$(uname -s 2>/dev/null)" = "Darwin" ] && [ "$(uname -m 2>/dev/null)" = "arm64" ]; then
- # Apple Silicon: llama.cpp builds with Metal over unified memory, so not a CPU-only host.
step "gpu" "Apple Silicon (Metal, unified memory)"
else
step "gpu" "none (chat-only / GGUF)" "$C_WARN"
@@ -4756,30 +4167,15 @@ else
UNSLOTH_HOME="$HOME/.unsloth"
fi
mkdir -p "$UNSLOTH_HOME"
-# Record the master root inside the Studio tree, for the uninstaller: UNSLOTH_HOME can be set
-# for a single command, and without the note the uninstaller removed the Studio tree and
-# stranded multi-gigabyte llama.cpp, node and whisper.cpp trees beside it.
-#
-# Only for a master root (the other branches derive UNSLOTH_HOME from paths the uninstaller
-# already knows), and only when a reader will honour it: both rejected shapes were being
-# written, so the file on disk claimed a recorded root while every reader refused it.
+# Record the master root inside the Studio tree, for the uninstaller, only when readers honour it.
_master_root_note_is_honoured() {
- # Canonicalised here rather than trusting the value from the top of the script: that one was
- # resolved before the mkdir above, so a root created by this run kept its uncanonical
- # spelling, and the containment test below is textual.
+ # Re-canonicalised: the root may have been created after the earlier resolution.
_mrn_root=$(CDPATH= cd -P -- "$1" 2>/dev/null && pwd -P) || _mrn_root=""
[ -n "$_mrn_root" ] || return 1
- # The legacy default is the one root every reader finds without help, and both uninstallers
- # refuse it outright. Writing it turned a one-command `UNSLOTH_HOME=$HOME/.unsloth` into a
- # permanent portable install: every later bare launch read the note back and HF_HUB_CACHE
- # moved off ~/.cache/huggingface, the one cache this change promises not to move.
+ # The legacy default root is refused by both uninstallers; writing it would enable portable mode.
_mrn_legacy=$(CDPATH= cd -P -- "${HOME:-}/.unsloth" 2>/dev/null && pwd -P) || _mrn_legacy="${HOME:-}/.unsloth"
[ "$_mrn_root" != "$_mrn_legacy" ] || return 1
- # Keyed on the TREE as well, because that is what the readers key on: storage_roots'
- # _is_legacy_studio_tree and the CLI both decline ANY note found in ~/.unsloth/studio,
- # whatever it records. Without this, UNSLOTH_HOME=$HOME passed containment (the legacy tree
- # is inside $HOME) and the value is not the legacy root, so the note was written, warned
- # about nothing, and then honoured by nobody.
+ # Readers decline any note in ~/.unsloth/studio, so do not write one there.
_mrn_studio=$(CDPATH= cd -P -- "$STUDIO_HOME" 2>/dev/null && pwd -P) || _mrn_studio="$STUDIO_HOME"
_mrn_legacy_studio=$(CDPATH= cd -P -- "${HOME:-}/.unsloth/studio" 2>/dev/null && pwd -P) \
|| _mrn_legacy_studio="${HOME:-}/.unsloth/studio"
@@ -4803,10 +4199,7 @@ _master_root_note_is_honoured() {
}
if [ -n "$_MASTER_ROOT" ] && [ -z "$STAGE_ROOT" ] && _master_root_note_is_honoured "$UNSLOTH_HOME"; then
if mkdir -p "$STUDIO_HOME/share" 2>/dev/null; then
- # Staged then renamed: a reader catching a half-written note would name a truncated
- # path, and this note licenses deletions. mktemp rather than "$$", as
- # _uv_cache_root_is_writable states above: a redirection into a predictable name follows
- # a symlink anyone who can write share/ could have precreated there.
+ # Staged then renamed via mktemp: this note licenses deletions.
if ! _mrn_tmp=$(mktemp "$STUDIO_HOME/share/.unsloth-master-root.XXXXXX" 2>/dev/null); then
_mrn_tmp=""
fi
@@ -4819,14 +4212,7 @@ if [ -n "$_MASTER_ROOT" ] && [ -z "$STAGE_ROOT" ] && _master_root_note_is_honour
unset _mrn_tmp
fi
fi
-# Clear a note an earlier run left naming the legacy default root, whatever this run was asked
-# to do. The gate above stops new ones, but an install that already has one keeps reading it
-# back on every bare launch -- portable mode on, the Hugging Face hub cache moved off
-# ~/.cache/huggingface -- and no later `unsloth studio update` would ever pass through the write
-# block to correct it, since that block only runs when UNSLOTH_HOME is set again. Narrow on
-# purpose: this is the single value both uninstallers already refuse, so removing it takes
-# nothing any reader was entitled to act on. A note naming any other root is left alone, since
-# an unreadable or unexpected one may simply describe an install this run cannot see.
+# Clear a stale note naming the legacy default root; it would keep portable mode on forever.
if [ -f "$STUDIO_HOME/share/.unsloth-master-root" ]; then
_mrn_old=$(head -n 1 "$STUDIO_HOME/share/.unsloth-master-root" 2>/dev/null \
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') || _mrn_old=""
@@ -4850,10 +4236,8 @@ _NEED_LLAMA_SOURCE_BUILD=false
_LLAMA_CPP_DEGRADED=false
_LLAMA_CPP_NO_SPACE=false
_LLAMA_KEEP_PREBUILT_ACTIVE=false
-# The installed GPU prebuilt was kept because the source fallback could only build CPU.
_LLAMA_KEPT_GPU_PREBUILT=""
_LLAMA_UPDATE_FAIL_REASON=""
-# A GPU host ended on a CPU-only llama.cpp: named in the footer, not just mid-log (#9255).
_LLAMA_CPU_ONLY_ON_GPU_HOST=false
_LLAMA_FORCE_COMPILE="${UNSLOTH_LLAMA_FORCE_COMPILE:-0}"
_REQUESTED_LLAMA_TAG="${UNSLOTH_LLAMA_TAG:-${_DEFAULT_LLAMA_TAG}}"
@@ -4875,16 +4259,9 @@ if [ "$_HOST_SYSTEM" != "Darwin" ]; then
esac
fi
-# Pick the release repo install_llama_prebuilt.py plans against. Every host this
-# installer supports now pulls its llama.cpp prebuilt from the unslothai fork: it
-# ships the CUDA (Linux x64/arm64, Windows), ROCm (Linux/Windows) and macOS
-# bundles, plus the CPU bundles for Linux/Windows on both x86_64 and arm64.
-# ggml-org artifacts are no longer used by default.
+# Every supported host pulls its llama.cpp prebuilt from the unslothai fork.
_HELPER_RELEASE_REPO="unslothai/llama.cpp"
-# UNSLOTH_ROCM_GFX_ARCH may be set on a host where no probe fired, so the override
-# nested in the AMD-detected branch above never ran and _setup_gfx is still empty.
-# Honour it here so the --rocm-gfx forwarding below still sees it
-# (install_llama_prebuilt.py reads the same env var as the --rocm-gfx default).
+# UNSLOTH_ROCM_GFX_ARCH may be set where no probe fired; honour it for --rocm-gfx.
if [ "${_setup_nvidia_usable:-}" != true ] && [ -z "${_setup_gfx:-}" ] && [ -n "${UNSLOTH_ROCM_GFX_ARCH:-}" ]; then
_setup_gfx="${UNSLOTH_ROCM_GFX_ARCH}"
fi
@@ -4903,7 +4280,6 @@ if [ "$_LLAMA_FORCE_COMPILE" = "1" ]; then
_SKIP_PREBUILT_INSTALL=true
fi
-# Baked-in PR_FORCE promotes to _LLAMA_PR when user hasn't set one.
if [ -z "$_LLAMA_PR" ] && [ -n "$_LLAMA_PR_FORCE" ] && \
[[ "$_LLAMA_PR_FORCE" =~ ^[0-9]+$ ]] && [ "$_LLAMA_PR_FORCE" -gt 0 ]; then
_LLAMA_PR="$_LLAMA_PR_FORCE"
@@ -4926,11 +4302,7 @@ fi
verbose_substep "requested llama.cpp tag: $_REQUESTED_LLAMA_TAG (repo: $_HELPER_RELEASE_REPO)"
-# GGUF export's check_llama_cpp() looks for a llama-quantize shim at the root of
-# the install dir, but a source build keeps the binary under build/bin/. Mirror
-# the source-build-reuse step and create the shim when the reused tree has one
-# but no root shim yet. Best-effort: the tree may be read-only (shared/CI cache),
-# and under `set -e` a failed ln would otherwise abort an good reuse.
+# check_llama_cpp() looks for a root llama-quantize shim. Best-effort: tree may be read-only.
_link_local_llama_quantize_shim() {
if [ -x "$1/build/bin/llama-quantize" ] && [ ! -e "$1/llama-quantize" ]; then
ln -sf build/bin/llama-quantize "$1/llama-quantize" 2>/dev/null || \
@@ -4938,18 +4310,12 @@ _link_local_llama_quantize_shim() {
fi
}
-# Accept any layout LlamaCppBackend._layout_candidates() resolves so the flag
-# never rejects a tree Unsloth could actually run: a root-level llama-server (a
-# `make` build or a flat-extracted release) or the CMake build/bin/llama-server.
+# Accept any layout LlamaCppBackend._layout_candidates() resolves.
_has_local_llama_server() {
[ -x "$1/llama-server" ] || [ -x "$1/build/bin/llama-server" ]
}
-# The backend the installed prebuilt's marker records (cuda/rocm/vulkan/cpu), or nothing.
-# `backend` arrived with #8520; older markers name it in llama_backend or only in the asset.
-# Whether the install marker's $2 names the pinned ref $3: exact, or ($4 = refs) the installer's
-# own alias and commit-prefix matching (a short commit pin matches the recorded full one). A
-# published release tag is a name, not a ref, so it compares exactly.
+# $4 = refs: installer alias and commit-prefix matching; a release tag compares exactly.
_installed_prebuilt_ref_matches() {
[ -f "$1/UNSLOTH_PREBUILT_INFO.json" ] || return 1
python - "$SCRIPT_DIR/install_llama_prebuilt.py" "$1/UNSLOTH_PREBUILT_INFO.json" "$2" "$3" "${4:-exact}" <<'PY' 2>/dev/null
@@ -5007,9 +4373,6 @@ print(answer)
PY
}
-# The updater's own completeness check, offline: a marker and an executable do not prove the
-# tree loads. Not --validate-install, which downloads a probe model the failed update cannot.
-# Why the prebuilt update failed, in a few words, from the helper's log.
_llama_update_fail_reason() {
if grep -qiE "429|rate limit" "$1" 2>/dev/null; then
echo "GitHub rate limit"
@@ -5024,26 +4387,20 @@ _installed_prebuilt_runs() {
python "$SCRIPT_DIR/install_llama_prebuilt.py" --check-installed "$1" >/dev/null 2>&1
}
-# An Intel GPU by DRM vendor id, the probe the prebuilt router uses for the Vulkan route.
_setup_has_intel_gpu() {
grep -qs -i "^0x8086" /sys/class/drm/card*/device/vendor 2>/dev/null
}
-# A CPU-only source build must not replace a working GPU prebuilt while the GPU is still
-# there (#9255). Prints the backend to keep; false when there is nothing to keep, the GPU
-# the marker names is gone, or the build was asked for by hand. Vulkan fits any vendor.
+# A CPU-only source build must not replace a working GPU prebuilt while the GPU is there (#9255).
_gpu_prebuilt_to_keep_over_cpu_build() {
local install_dir=$1 backend
[ "$_LLAMA_FORCE_COMPILE" != "1" ] || return 1
[ -z "$_LLAMA_PR" ] || return 1
- # An explicit version pin asked for that version; the old install satisfies it only
- # when its marker records the same one.
if [ -n "${UNSLOTH_LLAMA_RELEASE_TAG:-}" ]; then
_installed_prebuilt_ref_matches "$install_dir" release_tag "$UNSLOTH_LLAMA_RELEASE_TAG" || return 1
fi
case "${UNSLOTH_LLAMA_TAG:-}" in
""|latest|master) ;;
- # A commit pin is recorded beside the build tag, in the source ref fields.
*) _installed_prebuilt_ref_matches "$install_dir" \
tag,requested_source_ref,resolved_source_ref,source_commit "$UNSLOTH_LLAMA_TAG" refs || return 1 ;;
esac
@@ -5061,8 +4418,7 @@ _gpu_prebuilt_to_keep_over_cpu_build() {
printf '%s' "$backend"
}
-# UNSLOTH_LLAMA_KEEP_PREBUILT=1: keep an installed GPU prebuilt already matching the requested tag/fork.
-# The Docker Studio build sets it -- no GPU is visible there, so detection installs a CPU bundle over the baked CUDA one.
+# UNSLOTH_LLAMA_KEEP_PREBUILT=1 (Docker build sees no GPU and would install CPU over CUDA).
_keep_installed_gpu_prebuilt() {
local install_dir=$1 requested_tag=$2 repo=$3 release_pin=${4:-}
case "$(printf '%s' "${UNSLOTH_LLAMA_KEEP_PREBUILT:-}" | awk '{$1=$1; print tolower($0)}')" in
@@ -5135,8 +4491,6 @@ PY
_LOCAL_LLAMA_CPP_LINKED=false
if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
if [ ! -d "$UNSLOTH_LOCAL_LLAMA_CPP_DIR" ]; then
- # A build under an unsearchable ancestor cannot be stat'd, so report permissions
- # rather than sending the user to fix a path that is already correct.
_report_denied_ancestor "$UNSLOTH_LOCAL_LLAMA_CPP_DIR" "UNSLOTH_LOCAL_LLAMA_CPP_DIR"
step "llama.cpp" "UNSLOTH_LOCAL_LLAMA_CPP_DIR does not exist: $UNSLOTH_LOCAL_LLAMA_CPP_DIR" "$C_ERR"
setup_fail 1 "UNSLOTH_LOCAL_LLAMA_CPP_DIR does not exist: $UNSLOTH_LOCAL_LLAMA_CPP_DIR"
@@ -5146,17 +4500,10 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
# owner-unverified: this is the user's own tree, never advise deleting it.
_path_access_denied "$UNSLOTH_LOCAL_LLAMA_CPP_DIR" "UNSLOTH_LOCAL_LLAMA_CPP_DIR" owner-unverified
fi
- # Canonicalize the install path the same way before comparing: _RESOLVED_LOCAL
- # is fully resolved, but LLAMA_CPP_DIR is textual ($UNSLOTH_HOME/llama.cpp). If
- # $HOME (or UNSLOTH_HOME) contains a symlink, the two never match even when the
- # user pointed the flag at the canonical install itself -- and the rm -rf below
- # would then wipe the very tree they asked to reuse. Resolve via the parent so
- # this works whether or not the leaf currently exists.
+ # Canonicalise before comparing, or a symlinked $HOME makes the rm -rf below wipe the tree.
_CANON_LLAMA_CPP_DIR="$LLAMA_CPP_DIR"
_LLAMA_CPP_PARENT="$(dirname "$LLAMA_CPP_DIR")"
if [ -d "$_LLAMA_CPP_PARENT" ]; then
- # Nothing can be written under a parent we cannot search, so report here
- # rather than let the link below abort raw a few lines later.
if _canon_parent="$(CDPATH= cd -P -- "$_LLAMA_CPP_PARENT" 2>/dev/null && pwd -P)"; then
_CANON_LLAMA_CPP_DIR="$_canon_parent/$(basename "$LLAMA_CPP_DIR")"
else
@@ -5164,12 +4511,7 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
fi
fi
if [ "$_RESOLVED_LOCAL" = "$_CANON_LLAMA_CPP_DIR" ]; then
- # Points at the canonical install location itself: never delete-then-link
- # it onto itself. If a usable build is already there, reuse it and skip
- # both the prebuilt download and the source build -- the prebuilt installer
- # uses os.replace() and would otherwise clobber an existing source build at
- # this path. If nothing is built there yet, fall through to the normal
- # install so it gets built in place exactly as it would without the flag.
+ # Flag points at the install itself: reuse a build there, never delete-then-link onto itself.
if _has_local_llama_server "$LLAMA_CPP_DIR"; then
substep "UNSLOTH_LOCAL_LLAMA_CPP_DIR is the canonical install location and already holds a build; reusing it"
_link_local_llama_quantize_shim "$LLAMA_CPP_DIR"
@@ -5180,27 +4522,19 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
substep "UNSLOTH_LOCAL_LLAMA_CPP_DIR points to the canonical install location with nothing built there yet; running the normal install"
fi
else
- # Reusing disables BOTH the prebuilt download and the source build, so the
- # linked tree must already contain a runnable llama-server in one of the
- # layouts the backend resolves (root-level or build/bin/). Fail clearly
- # rather than link an unbuilt or wrong-platform checkout and leave Unsloth
- # with no usable binary.
+ # Reuse skips both prebuilt and source build, so require a runnable llama-server.
if ! _has_local_llama_server "$_RESOLVED_LOCAL"; then
step "llama.cpp" "no llama-server under $_RESOLVED_LOCAL (looked for ./llama-server and ./build/bin/llama-server) -- build llama.cpp there first, or drop --with-llama-cpp-dir" "$C_ERR"
setup_fail 1 "No llama-server was found under $_RESOLVED_LOCAL"
fi
- # A stale link from a previous --with-llama-cpp-dir run isn't Unsloth-owned
- # content; drop it before the ownership check so re-runs stay idempotent
- # for a custom UNSLOTH_STUDIO_HOME (the assert would otherwise follow the
- # link into the user's dir and reject it as unowned).
+ # Drop a stale link from a previous run before the ownership check.
[ -L "$LLAMA_CPP_DIR" ] && rm -f "$LLAMA_CPP_DIR"
if [ "$_RUNTIME_ROOT_IS_CUSTOM" = true ]; then
_assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install" "$_RUNTIME_ROOT_IS_CUSTOM"
fi
rm -rf "$LLAMA_CPP_DIR" || true
if [ -e "$LLAMA_CPP_DIR" ]; then
- # Unreadable, not just unsearchable: mode 111 defeats the rm above and
- # would fall through to the generic message.
+ # Unreadable, not just unsearchable: mode 111 defeats the rm above.
if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
fi
@@ -5216,9 +4550,7 @@ if [ -n "${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}" ]; then
fi
fi
-# Every branch below replaces $LLAMA_CPP_DIR or builds into it, and the source-build
-# swap only reaches its own guards after the whole build, so check here instead.
-# Local-link paths are excluded: they already replaced or reused the tree above.
+# Check here: the source-build swap only reaches its guards after the whole build.
if [ "$_LOCAL_LLAMA_CPP_LINKED" != true ]; then
if [ "$_RUNTIME_ROOT_IS_CUSTOM" = true ]; then
_assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install" "$_RUNTIME_ROOT_IS_CUSTOM"
@@ -5248,14 +4580,10 @@ else
if [ -d "$LLAMA_CPP_DIR" ]; then
substep "existing install detected -- validating update"
fi
- # why: install_llama_prebuilt.py uses os.replace(), which would displace
- # an unrelated $UNSLOTH_STUDIO_HOME/llama.cpp before the source-build
- # ownership check below ever runs.
+ # install_llama_prebuilt.py uses os.replace(), which would displace an unrelated tree.
if [ "$_RUNTIME_ROOT_IS_CUSTOM" = true ]; then
_assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install" "$_RUNTIME_ROOT_IS_CUSTOM"
fi
- # The ownership check above misses the default cache; stop before pathlib
- # turns an unreadable one into a traceback.
if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
fi
@@ -5268,25 +4596,16 @@ else
if [ -n "${UNSLOTH_LLAMA_RELEASE_TAG:-}" ]; then
_PREBUILT_CMD+=(--published-release-tag "$UNSLOTH_LLAMA_RELEASE_TAG")
fi
- # Forward the gfx arch resolved above so the per-gfx ROCm prebuilt is picked
- # even when the installer's own probe cannot report it (amd-smi-only hosts,
- # name-inferred arch). Implies --has-rocm on the installer side.
+ # Forward the gfx arch so the per-gfx ROCm prebuilt is picked (implies --has-rocm).
if [ -n "${_setup_gfx:-}" ]; then
_PREBUILT_CMD+=(--rocm-gfx "$_setup_gfx")
elif [ "$_setup_amd_detected" = true ] && \
{ command -v hipcc >/dev/null 2>&1 || [ -x /opt/rocm/bin/hipcc ] || \
ls /opt/rocm-*/bin/hipcc >/dev/null 2>&1; }; then
- # AMD detected but gfx unknown (KFD-only host): forward --has-rocm only when
- # hipcc can actually build llama.cpp (incl. a versioned /opt/rocm-*/bin, the
- # same paths the source build uses). With no gfx the prebuilt resolver finds
- # no ROCm bundle and the source build would fail, so without hipcc fall
- # through to the CPU prebuilt instead of breaking the install.
+ # No gfx: forward --has-rocm only when hipcc can build, else fall through to CPU prebuilt.
_PREBUILT_CMD+=(--has-rocm)
fi
- # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself, and it
- # is also the only side that can see a choice recorded in the install marker,
- # so forwarding a second copy from here could only ever disagree with it. The
- # override affects llama.cpp alone, not the training backend.
+ # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself.
case "$_source_backend_choice" in
cpu)
if [ "$_HOST_SYSTEM" = "Darwin" ]; then
@@ -5318,9 +4637,7 @@ else
if grep -Fq "already matches" "$_PREBUILT_LOG"; then
step "llama.cpp" "prebuilt up to date and validated"
elif grep -Fq "keeping the existing complete install" "$_PREBUILT_LOG"; then
- # Exit 0 can also mean the installer kept the tree already on disk after a
- # transient failure. "installed and validated" would name a release nothing
- # fetched.
+ # Exit 0 can also mean the existing tree was kept after a transient failure.
step "llama.cpp" "update unavailable, existing prebuilt kept" "$C_WARN"
else
step "llama.cpp" "prebuilt installed and validated"
@@ -5347,9 +4664,7 @@ else
substep "free up disk or move UNSLOTH_STUDIO_HOME/TMPDIR to a larger volume, then re-run"
_LLAMA_CPP_NO_SPACE=true
_has_local_llama_server "$LLAMA_CPP_DIR" || _LLAMA_CPP_DEGRADED=true
- # A preserved server may not satisfy an explicit backend request, and it
- # leaves _LLAMA_CPP_DEGRADED false. Never report success on an unverified
- # backend after the requested replacement ran out of space.
+ # A preserved server may not satisfy an explicit backend request; never report success.
if [ -n "$_explicit_llama_source_backend" ]; then
step "llama.cpp" "$_explicit_llama_source_backend was explicitly requested, so the installer will not keep an unverified existing backend" "$C_ERR"
setup_fail 1 "$_explicit_llama_source_backend was explicitly requested, so the installer will not keep an unverified existing llama.cpp backend."
@@ -5371,9 +4686,6 @@ else
if [ -d "$LLAMA_CPP_DIR" ]; then
substep "prebuilt update failed; existing install restored"
fi
- # Exit 2 means no concrete backend was in play: a request the installer
- # could not honour -- named here or recorded in the install marker, which
- # this script cannot see -- exits 5 above instead.
# A working GPU prebuilt beats any source build: keep it and retry next time.
if _LLAMA_KEPT_GPU_PREBUILT="$(_gpu_prebuilt_to_keep_over_cpu_build "$LLAMA_CPP_DIR")"; then
step "llama.cpp" "update failed ($_LLAMA_UPDATE_FAIL_REASON); keeping the installed $_LLAMA_KEPT_GPU_PREBUILT prebuilt, the next update will retry" "$C_WARN"
@@ -5393,16 +4705,7 @@ else
fi
fi
-# Source-built llama.cpp installs do not have the prebuilt metadata used above
-# for exact release matching. Reuse a complete local source build unless the
-# caller explicitly requested a rebuild or a PR-specific llama.cpp checkout.
-# The two entrypoints being executable is not enough on its own. Quarantine and
-# a truncated extract both take a library and leave llama-server in place, and
-# this branch only runs once the prebuilt path has already failed, so keeping
-# such a tree returns it byte for byte identical and reports success. Desktop
-# preflight asks about the same tree on every launch, so an update that repaired
-# nothing left it asking forever. A tree with no prebuilt marker is a real source
-# build and keeps the old test.
+# Reuse a complete source build; a tree with a prebuilt marker must also pass the completeness check.
_LLAMA_REUSE_EXISTING=true
if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && [ -d "$LLAMA_CPP_DIR" ]; then
python "$SCRIPT_DIR/install_llama_prebuilt.py" \
@@ -5429,8 +4732,7 @@ if [ -n "$STAGE_ROOT" ] && [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then
fi
# ── 8. WSL: pre-install GGUF build dependencies for fallback source builds ──
-# On WSL, sudo requires a password and can't be entered during GGUF export
-# (runs in a non-interactive subprocess). Install build deps here instead.
+# WSL: sudo needs a password unavailable during GGUF export, so install build deps here.
if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && grep -qi microsoft /proc/version 2>/dev/null; then
_GGUF_DEPS="pciutils build-essential cmake curl git libcurl4-openssl-dev"
apt-get update -y >/dev/null 2>&1 || true
@@ -5463,9 +4765,7 @@ if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && grep -qi microsoft /proc/version 2>
_SKIP_GGUF_BUILD=true
;;
*)
- # Degrade like the no-sudo branch below rather than letting
- # set -e abort setup on a bare apt error: missing GGUF build
- # deps are recoverable, not fatal.
+ # Missing GGUF build deps are recoverable; do not let set -e abort on apt.
if sudo apt-get update -y </dev/null &&
sudo apt-get install -y $_STILL_MISSING </dev/null; then
step "gguf deps" "installed"
@@ -5477,11 +4777,7 @@ if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && grep -qi microsoft /proc/version 2>
;;
esac
else
- # Nobody can answer a prompt or type a password here, so -n makes
- # sudo refuse rather than prompt into a closed stdin, and -k ignores
- # any cached timestamp so only a real NOPASSWD rule gets through.
- # Same treatment as install.sh's _smart_apt_install. This is the WSL
- # GGUF-export case noted above, where sudo does want a password.
+ # -n refuses to prompt, -k ignores a cached timestamp: only NOPASSWD gets through.
if sudo -n -k apt-get update -y </dev/null &&
sudo -n -k apt-get install -y $_STILL_MISSING </dev/null; then
step "gguf deps" "installed (non-interactive sudo)"
@@ -5626,9 +4922,7 @@ else
_IS_MACOS_ARM64=true
fi
- # macOS: pin a low deployment target so the source build loads on
- # older macOS too (else a macOS 26 host stamps minos=26). Set before
- # CPU_FALLBACK_CMAKE_ARGS copies CMAKE_ARGS so both paths inherit it.
+ # macOS: pin a low deployment target before CPU_FALLBACK_CMAKE_ARGS copies CMAKE_ARGS.
if [ "$_HOST_SYSTEM" = "Darwin" ]; then
_MACOS_DEPLOYMENT_TARGET="${UNSLOTH_MACOS_DEPLOYMENT_TARGET:-13.3}"
CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_OSX_DEPLOYMENT_TARGET=${_MACOS_DEPLOYMENT_TARGET}"
@@ -5642,11 +4936,7 @@ else
GPU_BACKEND=""
NVCC_PATH=""
- # A CUDA toolkit alone (CPU-only build container, leftover packages) is not
- # proof of a GPU: -DGGML_CUDA=ON there yields a binary that fails at runtime.
- # So both callers gate on a real card first.
- # One search, two callers: the usable-NVIDIA pass below and the masked-NVIDIA
- # retry after ROCm. Sets NVCC_PATH / GPU_BACKEND, or leaves both untouched.
+ # A CUDA toolkit alone is not proof of a GPU; callers gate on a real card first.
_select_nvcc() {
if command -v nvcc &>/dev/null; then
NVCC_PATH="$(command -v nvcc)"
@@ -5656,7 +4946,6 @@ else
export PATH="/usr/local/cuda/bin:$PATH"
GPU_BACKEND="cuda"
elif ls /usr/local/cuda-*/bin/nvcc &>/dev/null 2>&1; then
- # Pick the newest cuda-XX.X directory
NVCC_PATH="$(ls -d /usr/local/cuda-*/bin/nvcc 2>/dev/null | sort -V | tail -1)"
export PATH="$(dirname "$NVCC_PATH"):$PATH"
GPU_BACKEND="cuda"
@@ -5667,11 +4956,7 @@ else
_select_nvcc
fi
- # Check for ROCm (AMD) only if CUDA was not already selected, and
- # only when an AMD GPU was actually detected (_setup_amd_detected).
- # hipcc presence alone (HIP SDK, no GPU) must not select a HIP build.
- # NVIDIA-usable hosts never build HIP (defense in depth: the AMD
- # probes above are already skipped when NVIDIA is usable).
+ # ROCm only when an AMD GPU was detected: hipcc alone must not select a HIP build.
ROCM_HIPCC=""
if [ -z "$GPU_BACKEND" ] && [ "$_setup_nvidia_usable" != true ] && [ "$_setup_amd_detected" = true ]; then
if command -v hipcc &>/dev/null; then
@@ -5688,25 +4973,18 @@ else
fi
fi
- # A card hidden by CUDA_VISIBLE_DEVICES is still a card, and the CPU-only binary
- # built without this is activated over the tree for good. It runs after ROCm on
- # purpose: on a mixed host the visible AMD GPU is the one the user asked for.
- # Retrying here rather than gating the pass above on "no AMD detected" also
- # covers AMD detected with no hipcc anywhere, which sent a GPU host to a CPU
- # build with nvcc sitting right there.
+ # Retry CUDA for a masked NVIDIA card after ROCm, so a mixed host prefers the visible AMD GPU.
if [ -z "$GPU_BACKEND" ] && [ "$_setup_nvidia_physical" = true ]; then
_select_nvcc
fi
_BUILD_DESC="building"
if [ "$_IS_MACOS_ARM64" = true ]; then
- # Metal takes precedence on Apple Silicon (CUDA/ROCm not functional on macOS)
_BUILD_DESC="building (Metal)"
CMAKE_ARGS="$CMAKE_ARGS -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DGGML_METAL_USE_BF16=ON -DCMAKE_INSTALL_RPATH=@loader_path -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON"
CPU_FALLBACK_CMAKE_ARGS="$CPU_FALLBACK_CMAKE_ARGS -DGGML_METAL=OFF"
_TRY_METAL_CPU_FALLBACK=true
elif [ -n "$NVCC_PATH" ]; then
- # Returns "ok|too_old|unknown\nX.Y" on stdout.
_NVCC_CHECK="$(_nvcc_meets_llama_minimum "$NVCC_PATH")"
_NVCC_STATUS="$(printf '%s\n' "$_NVCC_CHECK" | sed -n '1p')"
_NVCC_VER="$(printf '%s\n' "$_NVCC_CHECK" | sed -n '2p')"
@@ -5741,12 +5019,9 @@ else
fi
if [ "$_CUDA_TOOLKIT_ALLOWED" = true ]; then
- # Resolve the arch list before committing to a CUDA build;
- # an empty list means CPU instead of a PTX-only binary (#5854).
+ # An empty arch list means CPU instead of a PTX-only binary.
_raw_caps=""
- # Resolve nvidia-smi as _setup_has_usable_nvidia_gpu does
- # (PATH, then /usr/bin); `command -v` alone would miss an
- # off-PATH binary and wrongly drop a CUDA host to CPU.
+ # Resolve nvidia-smi off PATH too, or a CUDA host drops to CPU.
_smi_bin=""
if command -v nvidia-smi >/dev/null 2>&1; then
_smi_bin="nvidia-smi"
@@ -5757,7 +5032,6 @@ else
_raw_caps=$(_setup_run_smi "$_smi_bin" --query-gpu=compute_cap --format=csv,noheader 2>/dev/null || true)
fi
CUDA_ARCHS="$(_resolve_cuda_archs "$_raw_caps" "${UNSLOTH_LLAMA_CUDA_ARCHS:-}")"
- # nvidia-smi absent, stale or answering N/A: the driver library lists the capabilities.
if [ -z "$CUDA_ARCHS" ] && [ "${UNSLOTH_NVIDIA_LIBRARY_PROBE:-1}" != "0" ]; then
CUDA_ARCHS="$(_resolve_cuda_archs "$(_probe_compute_caps)" "")"
fi
@@ -5771,12 +5045,9 @@ else
fi
_BUILD_DESC="building (CUDA, sm_${CUDA_ARCHS//;/+sm_})"
- # Allow a host gcc/clang newer than nvcc's whitelist (else a fresh
- # toolkit aborts with "unsupported GNU version"); via env to avoid word-splitting.
+ # Allow a host gcc newer than nvcc's whitelist; via env to avoid word-splitting.
export NVCC_PREPEND_FLAGS="${NVCC_PREPEND_FLAGS:+$NVCC_PREPEND_FLAGS }-allow-unsupported-compiler"
else
- # No detectable arch: build CPU (CMAKE_ARGS has no
- # -DGGML_CUDA=ON yet, so clearing GPU_BACKEND yields CPU).
substep "could not detect a CUDA compute capability; building CPU llama.cpp instead of a PTX-only binary (set UNSLOTH_LLAMA_CUDA_ARCHS, e.g. \"120\", to force a CUDA build)." "$C_WARN"
GPU_BACKEND=""
_BUILD_DESC="building (CPU, CUDA arch undetectable)"
@@ -5784,7 +5055,6 @@ else
fi
fi
elif [ "$GPU_BACKEND" = "rocm" ]; then
- # Resolve hipcc symlinks to find the real ROCm root
_HIPCC_REAL="$(readlink -f "$ROCM_HIPCC" 2>/dev/null || printf '%s' "$ROCM_HIPCC")"
ROCM_ROOT=""
if command -v hipconfig &>/dev/null; then
@@ -5825,29 +5095,19 @@ else
export ROCM_PATH="$ROCM_ROOT"
export HIP_PATH="$ROCM_ROOT"
- # Use upstream-recommended HIP compiler (not legacy hipcc-as-CXX)
if command -v hipconfig &>/dev/null; then
_HIP_CLANG_DIR="$(hipconfig -l 2>/dev/null || true)"
[ -n "$_HIP_CLANG_DIR" ] && export HIPCXX="$_HIP_CLANG_DIR/clang"
fi
- # Detect AMD GPU architecture (gfx target)
GPU_TARGETS=""
if command -v rocminfo &>/dev/null; then
_gfx_list=$(rocminfo 2>/dev/null | grep -oE 'gfx[0-9]{2,4}[a-z]?' | sort -u || true)
_valid_gfx=""
for _gfx in $_gfx_list; do
if [[ "$_gfx" =~ ^gfx[0-9]{2,4}[a-z]?$ ]]; then
- # Drop bare family-level targets (gfx10, gfx11, gfx12, ...)
- # when a specific sibling is present in the same list.
- # rocminfo on ROCm 6.1+ emits both the specific GPU and
- # the LLVM generic family line (e.g. gfx1100 alongside
- # gfx11-generic), and the outer grep above captures the
- # bare family prefix from the generic line. Passing that
- # bare prefix to -DGPU_TARGETS breaks the HIP/llama.cpp
- # build because clang only accepts specific gfxNNN ids.
- # No real AMD GPU has a 2-digit gfx id, so this filter
- # can only ever drop family prefixes, never real targets.
+ # Drop bare family ids (gfx11) from rocminfo's generic lines; clang accepts only gfxNNN.
+ # No real AMD GPU has a 2-digit gfx id.
if [[ "$_gfx" =~ ^gfx[0-9]{2}$ ]] \
&& echo "$_gfx_list" | grep -qE "^${_gfx}[0-9][0-9a-z]?$"; then
continue
@@ -5870,7 +5130,6 @@ else
_BUILD_DESC="building (CPU)"
fi
- # Decided before the compile: a CPU build adds nothing to a kept GPU prebuilt.
if [ -z "$GPU_BACKEND" ] && [ "$_IS_MACOS_ARM64" != true ] \
&& _LLAMA_KEPT_GPU_PREBUILT="$(_gpu_prebuilt_to_keep_over_cpu_build "$LLAMA_CPP_DIR")"; then
step "llama.cpp" "keeping the installed $_LLAMA_KEPT_GPU_PREBUILT prebuilt: the source fallback could only build for the CPU" "$C_WARN"
@@ -5886,8 +5145,6 @@ else
CMAKE_GENERATOR_ARGS="-G Ninja"
fi
- # GPU label for the CPU-fallback message: Metal, else GPU_BACKEND
- # (cuda/rocm). Empty on a bare CPU build (nothing to fall back from).
_gpu_fallback_label() {
if [ "$_TRY_METAL_CPU_FALLBACK" = true ]; then
echo "Metal"
@@ -5904,8 +5161,7 @@ else
rm -rf "$_BUILD_TMP/build"
if run_quiet_no_exit "cmake llama.cpp (cpu fallback)" cmake $CMAKE_GENERATOR_ARGS -S "$_BUILD_TMP" -B "$_BUILD_TMP/build" $CPU_FALLBACK_CMAKE_ARGS; then
_BUILD_DESC="building (CPU fallback after $_FB_LABEL configure failed)"
- # Now configured for CPU; clear GPU_BACKEND so a later
- # build-step failure won't re-enter fallback on this config.
+ # Clear so a later build failure won't re-enter fallback.
GPU_BACKEND=""
else
BUILD_OK=false
@@ -5938,14 +5194,11 @@ else
if [ "$BUILD_OK" = true ]; then
run_quiet_no_exit "build llama-quantize" cmake --build "$_BUILD_TMP/build" --config Release --target llama-quantize -j"$NCPU" || true
- # Best-effort: the DiffusionGemma visual server (an example target, present
- # on llama.cpp PR #24423). No-op when the diffusion example is not configured.
+ # Best-effort: the target exists only on llama.cpp trees carrying the diffusion example.
run_quiet_no_exit "build diffusion visual server" cmake --build "$_BUILD_TMP/build" --config Release --target llama-diffusion-gemma-visual-server -j"$NCPU" || true
fi
- # Opt-in post-build GPU smoke test (#5854 gap 2). Default off (Blackwell
- # CUDA JIT stalls). On failure, reuse the CPU fallback path so the user
- # still gets a working llama-server. Runs before the install swap.
+ # Opt-in smoke test (CUDA JIT stalls); runs before the install swap.
if [ "$BUILD_OK" = true ] && _staged_validation_enabled; then
_FB_LABEL="$(_gpu_fallback_label)"
_SMOKE_KIND="$(_source_smoke_install_kind)"
@@ -5957,8 +5210,7 @@ else
[ -n "$_SMOKE_KIND" ] && _SMOKE_CMD+=(--install-kind "$_SMOKE_KIND")
_SMOKE_RC=0
run_quiet_no_exit "validate source llama.cpp" "${_SMOKE_CMD[@]}" || _SMOKE_RC=$?
- # Exit 4 is a full disk, not a bad build: the CPU rebuild needs even
- # more space, so keep what we already have.
+ # Exit 4 is a full disk: a CPU rebuild needs more space, so keep what we have.
if [ "$_SMOKE_RC" -eq 4 ]; then
substep "not enough disk space to validate the $_FB_LABEL build; keeping it" "$C_WARN"
_LLAMA_CPP_NO_SPACE=true
@@ -5994,12 +5246,9 @@ else
# Swap only after build succeeds -- preserves existing install on failure
if [ "$BUILD_OK" = true ]; then
_assert_studio_owned_or_absent "$LLAMA_CPP_DIR" "llama.cpp install" "$_RUNTIME_ROOT_IS_CUSTOM"
- # || true: without it a raw rm error aborts under errexit to a bare exit
- # code, build stranded. Keep stderr: rm names the exact subpath, we cannot.
+ # || true so errexit does not strand the build; rm's stderr names the subpath.
rm -rf "$LLAMA_CPP_DIR" || true
if [ -e "$LLAMA_CPP_DIR" ]; then
- # Same probe as the other replace sites: the hoisted guard covers a
- # tree already denied, this catches one denied mid-build.
if _studio_dir_unreadable "$LLAMA_CPP_DIR"; then
_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"
fi
@@ -6013,8 +5262,6 @@ else
if [ -f "$QUANTIZE_BIN" ]; then
ln -sf build/bin/llama-quantize "$LLAMA_CPP_DIR/llama-quantize"
fi
- # DiffusionGemma visual server, if it was built (PR #24423): link next to
- # llama-server so Unsloth serves DiffusionGemma GGUFs without DG_VISUAL_BIN.
if [ -f "$LLAMA_CPP_DIR/build/bin/llama-diffusion-gemma-visual-server" ]; then
ln -sf build/bin/llama-diffusion-gemma-visual-server "$LLAMA_CPP_DIR/llama-diffusion-gemma-visual-server"
fi
@@ -6029,7 +5276,6 @@ else
step "llama.cpp" "binary not found after build" "$C_WARN"
_LLAMA_CPP_DEGRADED=true
elif [ -n "$_LLAMA_KEPT_GPU_PREBUILT" ]; then
- # Not a failure: the kept prebuilt is a root-level llama-server, not $LLAMA_SERVER_BIN.
print_installed_llama_prebuilt_release "$LLAMA_CPP_DIR"
else
step "llama.cpp" "build failed" "$C_ERR"
@@ -6040,11 +5286,7 @@ else
fi # end _SKIP_GGUF_BUILD check
# ── arm64 Linux GPU: CPU prebuilt as a last resort ──
-# An arm64 Linux GPU host source-builds for the GPU above. If that produced no
-# binary, install the fork's arm64 CPU prebuilt (app-<tag>-linux-arm64-cpu.tar.gz)
-# instead of leaving the host without llama.cpp. --cpu-fallback drops the GPU
-# attributes so the CPU bundle is selected rather than re-attempting CUDA. Skipped
-# on a full disk: the retry fails the same way and buries the hint.
+# Source build produced nothing: install the CPU prebuilt. Skipped on a full disk.
if [ "$_LLAMA_CPP_DEGRADED" = true ] \
&& [ "$_LLAMA_CPP_NO_SPACE" != true ] \
&& [ "$_LLAMA_KEEP_PREBUILT_ACTIVE" != true ] \
@@ -6058,8 +5300,6 @@ if [ "$_LLAMA_CPP_DEGRADED" = true ] \
--published-repo "unslothai/llama.cpp"
--cpu-fallback
)
- # Trust the installer's exit code: it validates the server before exiting 0,
- # the same signal the primary prebuilt path above relies on.
if run_quiet_no_exit "arm64 CPU prebuilt" "${_ARM64_CPU_CMD[@]}"; then
step "llama.cpp" "arm64 CPU prebuilt installed (GPU build unavailable)" "$C_WARN"
_LLAMA_CPP_DEGRADED=false
@@ -6079,11 +5319,7 @@ if [ ! -L "$LLAMA_CPP_DIR" ] && {
fi
# ── whisper.cpp (local speech-to-text dictation engine) ──
-# Optional runtime for local dictation. Fail-open: any failure leaves the
-# Transformers STT engine and browser dictation working, so it never aborts
-# setup (unlike llama.cpp). Runs in 'unsloth studio update' too so the runtime
-# installs/refreshes without a compiler. Installs beside llama.cpp under the
-# same managed home the sidecar's _managed_whisper_cpp_dir() resolves.
+# whisper.cpp: optional, fail-open; installs beside llama.cpp as _managed_whisper_cpp_dir() expects.
WHISPER_CPP_DIR="$UNSLOTH_HOME/whisper.cpp"
if [ -n "${WHISPER_SERVER_PATH:-}" ] || [ -n "${UNSLOTH_WHISPER_CPP_PATH:-}" ]; then
verbose_substep "whisper.cpp: using a user-configured binary/dir; skipping managed install"
@@ -6116,9 +5352,6 @@ else
if grep -Fq "already matches" "$_WHISPER_LOG"; then
step "whisper.cpp" "prebuilt up to date"
elif grep -Fq "keeping the existing complete install" "$_WHISPER_LOG"; then
- # Exit 0 can also mean a kept tree after a lookup that could not answer; "prebuilt
- # installed" would name a release nothing fetched. Same wording and token as llama's
- # arm.
step "whisper.cpp" "update unavailable, existing prebuilt kept" "$C_WARN"
else
step "whisper.cpp" "prebuilt installed"
@@ -6128,23 +5361,16 @@ else
fi
rm -f "$_WHISPER_LOG"
elif [ "$_WHISPER_STATUS" -eq 3 ]; then
- # A warm dictation server holds the binary; keep the old install.
step "whisper.cpp" "install busy; keeping existing runtime" "$C_WARN"
rm -f "$_WHISPER_LOG"
else
- # A source build is opt-in. Keep the installer log until fallback has
- # finished so setup can distinguish release skew from an operational
- # installer failure and report the exact pairing when available.
_WHISPER_RECOVERED=false
_WHISPER_BUILD="$SCRIPT_DIR/../scripts/build_whisper_cpp.sh"
if [ "${UNSLOTH_WHISPER_FORCE_COMPILE:-0}" = "1" ] && [ -f "$_WHISPER_BUILD" ] \
&& command -v cmake >/dev/null 2>&1 && command -v git >/dev/null 2>&1; then
_frontend_bg_join
substep "whisper.cpp prebuilt unavailable; building from source (UNSLOTH_WHISPER_FORCE_COMPILE=1)..."
- # The source build overwrites whisper-server in the managed dir but
- # knows nothing about the prebuilt marker; a stale marker would make
- # a later setup run report "already matches" and skip repairing the
- # prebuilt over the source binary. Drop it before building.
+ # A stale marker would report "already matches" over the source binary.
rm -f "$WHISPER_CPP_DIR/UNSLOTH_WHISPER_PREBUILT_INFO.json" 2>/dev/null || true
if run_quiet_no_exit "whisper.cpp source build" \
env UNSLOTH_HOME="$UNSLOTH_HOME" sh "$_WHISPER_BUILD"; then
@@ -6179,8 +5405,7 @@ PY
fi
# ── audio.cpp (speech, music and dictation engine) ──
-# audio.cpp vendors its own patched ggml, so its bundles are self-contained and do not pair with
-# the llama install. Fail-open like whisper.cpp: every other audio engine keeps working.
+# audio.cpp vendors its own ggml, so it does not pair with llama. Fail-open.
AUDIO_CPP_DIR="$UNSLOTH_HOME/audio.cpp"
if [ -n "${AUDIOCPP_SERVER_PATH:-}" ] || [ -n "${UNSLOTH_AUDIO_CPP_PATH:-}" ]; then
verbose_substep "audio.cpp: using a user-configured binary/dir; skipping managed install"
@@ -6191,7 +5416,6 @@ elif [ -f "$SCRIPT_DIR/install_audio_cpp_prebuilt.py" ]; then
_assert_studio_owned_or_absent "$AUDIO_CPP_DIR" "audio.cpp install" "$_RUNTIME_ROOT_IS_CUSTOM"
fi
_AUDIO_CPP_CMD=(python "$SCRIPT_DIR/install_audio_cpp_prebuilt.py" --install-dir "$AUDIO_CPP_DIR")
- # A host whose GPU is invisible at install time (a Docker image build) names its bundle here.
if [ -n "${UNSLOTH_AUDIO_CPP_ACCELERATOR:-}" ]; then
_AUDIO_CPP_CMD+=(--accelerator "$UNSLOTH_AUDIO_CPP_ACCELERATOR")
fi
@@ -6209,8 +5433,6 @@ elif [ -f "$SCRIPT_DIR/install_audio_cpp_prebuilt.py" ]; then
if grep -Fq "already matches" "$_AUDIO_CPP_LOG"; then
step "audio.cpp" "prebuilt up to date"
elif grep -Fq "keeping the existing complete install" "$_AUDIO_CPP_LOG"; then
- # The release lookup could not answer and the install on disk is complete; "prebuilt
- # installed" would name a release nothing fetched. whisper.cpp's wording.
step "audio.cpp" "update unavailable, existing prebuilt kept" "$C_WARN"
else
step "audio.cpp" "prebuilt installed"
@@ -6226,7 +5448,7 @@ elif [ -f "$SCRIPT_DIR/install_audio_cpp_prebuilt.py" ]; then
rm -f "$_AUDIO_CPP_LOG"
fi
-# Named in the footer: every path to a lost GPU exits 0, and a mid-log line is what #9255's reporters scrolled past.
+# Named in the footer: every path to a lost GPU exits 0.
_print_llama_gpu_notes() {
if [ -n "$_LLAMA_KEPT_GPU_PREBUILT" ]; then
printf " ${C_WARN}%-15s%s${C_RST}\n" "llama.cpp" "update failed (${_LLAMA_UPDATE_FAIL_REASON:-the source fallback could only build for the CPU}); the installed $_LLAMA_KEPT_GPU_PREBUILT prebuilt was kept and the next update will retry"
@@ -6281,11 +5503,7 @@ else
fi
echo ""
-# When called from install.sh (SKIP_STUDIO_BASE=1), exit non-zero so the
-# installer can report the GGUF failure after finishing PATH/shortcut setup.
-# When called directly via 'unsloth studio update', keep the install
-# successful -- the footer above already reports the limitation and Unsloth
-# is still usable for non-GGUF workflows.
+# From install.sh exit non-zero so it can report GGUF failure; `studio update` stays successful.
if [ "$_LLAMA_CPP_DEGRADED" = true ] && [ "${SKIP_STUDIO_BASE:-0}" = "1" ]; then
# In Tauri mode a non-zero exit is not "report", it is "abort": install.rs turns the
# error into "Installation failed", so one transient prebuilt download failure (a
@@ -6315,9 +5533,8 @@ if [ "$_LLAMA_CPP_DEGRADED" = true ] && [ "${SKIP_STUDIO_BASE:-0}" = "1" ]; then
esac
fi
-# A desktop repair runs update.rs, which sets UNSLOTH_TAURI_UPDATE alone, so the
-# block above is skipped and a degraded repair recorded nothing. update.rs parses
-# [TAURI:DIAG] the same way. Marker only: the update contract stays successful.
+# A desktop repair runs update.rs, which sets UNSLOTH_TAURI_UPDATE alone; record the DIAG
+# marker. Exit stays successful.
if [ "$_LLAMA_CPP_DEGRADED" = true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ]; then
case "${UNSLOTH_TAURI_UPDATE:-0}" in
1|true) printf '[TAURI:DIAG] %s\n' "llama_cpp=unavailable" ;;