Skip to content
122 changes: 8 additions & 114 deletions install.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8328,49 +8328,6 @@ exit 0
return (Exit-InstallFailure "Managed Python is unavailable at $VenvPython (recorded base home: $recordedBaseHome)")
}

# -- Helper: run amd-smi without triggering a UAC elevation prompt --
# __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,
[Parameter(Position = 1)][string[]]$SmiArgs = @(),
[int]$TimeoutSec = 30
)
# RunAsInvoker blocks auto-elevation; the timeout bounds a flaky amd-smi (30s, as amd.py).
$prevCompat = [Environment]::GetEnvironmentVariable('__COMPAT_LAYER', 'Process')
$env:__COMPAT_LAYER = 'RunAsInvoker'
try {
# [Process]::Start, not Start-Process: PS 5.1 leaves .ExitCode $null and detection dies.
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($SmiArgs -join ' ')
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$proc = [System.Diagnostics.Process]::Start($psi)
$outTask = $proc.StandardOutput.ReadToEndAsync()
$errTask = $proc.StandardError.ReadToEndAsync()
if (-not $proc.WaitForExit($TimeoutSec * 1000)) {
try { $proc.Kill() } catch {}
$global:LASTEXITCODE = 124
return ""
}
$global:LASTEXITCODE = $proc.ExitCode
return ($outTask.Result + "`n" + $errTask.Result)
} catch {
$global:LASTEXITCODE = 1
return ""
} finally {
if ($null -eq $prevCompat) {
Remove-Item Env:__COMPAT_LAYER -ErrorAction SilentlyContinue
} else {
$env:__COMPAT_LAYER = $prevCompat
}
}
}

# -- A driverless nvidia-smi exits 0 listing no GPU, so require a "GPU <n>:" row. --
# 124 means Invoke-NvidiaSmiBounded killed the probe; recorded so the banner skips a
# second query.
Expand Down Expand Up @@ -8908,16 +8865,14 @@ main()
function Test-OtherVendorAdapterPresent {
param($Scan = $null)
if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
# AMD evidence the AMD route finds without WMI (override, the installer's forwarded arch, HIP SDK,
# opted-in amd-smi) vetoes too.
# AMD evidence the AMD route finds without WMI (override, the installer's forwarded arch, HIP SDK)
# vetoes too.
if ("$env:UNSLOTH_ROCM_GFX_ARCH".Trim() -or "$env:_UNSLOTH_ROCM_GFX_ARCH_HANDOFF".Trim()) { return $true }
try {
if (Get-Command hipinfo -CommandType Application -ErrorAction SilentlyContinue) { return $true }
foreach ($hipEnv in @($env:HIP_PATH, $env:HIP_PATH_57, $env:ROCM_PATH)) {
if ($hipEnv -and (Test-Path -LiteralPath (Join-Path $hipEnv "bin\hipinfo.exe"))) { return $true }
}
if ($env:UNSLOTH_ENABLE_AMD_SMI -match '^(?i)(1|true|yes|on)$' -and
(Get-Command amd-smi -ErrorAction SilentlyContinue)) { return $true }
} catch {}
# Same classification as the Intel route, which ignores PNP ID and status.
if ($Scan.Ok) {
Expand Down Expand Up @@ -9233,7 +9188,7 @@ main()
# Declared with its neighbours, not inside the block below: the arms that read
# it are outside that gate, so an NVIDIA host would leave it undefined.
$ROCmUnsupportedGfxArch = $null
$_hipAllArches = @(); $_smiGfxTokens = @(); $_asicGfxTokens = @(); $amdAdapters = @()
$_hipAllArches = @(); $amdAdapters = @()
# Mixed hosts are probed too (flag, mask, notice); a pin skips it, as in install.sh.
$ProbeAmdBesideNvidia = $HasNvidiaSmi -and -not $SkipTorch -and
[string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL) -and
Expand All @@ -9242,7 +9197,7 @@ main()
$script:StudioMuteLines = $ProbeAmdBesideNvidia -and -not $nvMaskHidesAll -and -not (Test-RocmTorchExplicitlyRequested)
try {
if (-not $HasNvidiaSmi -or $ProbeAmdBesideNvidia) {
# Ignore the venv hipInfo.exe: an AMD wheel, not a HIP SDK, so amd-smi still auto-elevates.
# Ignore the venv hipInfo.exe: an AMD wheel, not a HIP SDK.
function Test-HipinfoIsVenvInternal {
param([AllowNull()][string]$HipinfoPath)
if ([string]::IsNullOrWhiteSpace($HipinfoPath)) { return $false }
Expand Down Expand Up @@ -9340,57 +9295,8 @@ main()
}
} catch {}
}
# amd-smi pops an unsuppressable UAC prompt without HIP, so probe only with a SDK or opt-in.
$amdSmiOptOut = $env:UNSLOTH_ENABLE_AMD_SMI -match '^(?i)(0|false|no|off)$'
# Not for the notice-only probe: amd-smi can raise UAC, and hipinfo / WMI name the card.
$amdSmiAllowed = (-not $amdSmiOptOut) -and -not $script:StudioMuteLines -and ($HipSdkInstalled -or ($env:UNSLOTH_ENABLE_AMD_SMI -match '^(?i)(1|true|yes|on)$'))
if (-not $HasROCm -and $amdSmiAllowed) {
$amdSmiExe = Get-Command "amd-smi" -ErrorAction SilentlyContinue
if ($amdSmiExe) {
try {
$smiOut = Invoke-AmdSmiNoElevate $amdSmiExe.Source @('list')
if ($LASTEXITCODE -eq 0 -and $smiOut -match "(?im)^GPU\s*[:\[]\s*\d") {
$HasROCm = $true
# gfx tokens in enumeration order, picked via HIP_VISIBLE_DEVICES.
# Beside NVIDIA (a ROCm route) HIP applies a CUDA mask too, as setup.ps1's Resolve-VisibleGpuIndex reads it.
$_smiVisIdx = if ($env:HIP_VISIBLE_DEVICES -match '^\d') { [int]($env:HIP_VISIBLE_DEVICES -split ',')[0] } elseif ($env:ROCR_VISIBLE_DEVICES -match '^\d') { [int]($env:ROCR_VISIBLE_DEVICES -split ',')[0] } elseif ($ProbeAmdBesideNvidia -and $env:CUDA_VISIBLE_DEVICES -match '^\d') { [int]($env:CUDA_VISIBLE_DEVICES -split ',')[0] } else { 0 }
# Attempt 1: newer amd-smi versions embed the gfx arch in list output.
$_smiGfxTokens = @([regex]::Matches($smiOut, "(?i)\b(gfx\d+[a-z]?)\b") | ForEach-Object { $_.Groups[1].Value.ToLower() })
# Market names, when this amd-smi prints them, indexed like the gfx
# tokens above. Banner only; the arch that selects the wheel is never
# taken from here.
$_smiNames = @([regex]::Matches($smiOut, "(?im)Market.?Name\s*[:\|]\s*([^\r\n]+)") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_smiGfxTokens.Count -gt 0) {
$ROCmGfxArch = if ($_smiVisIdx -lt $_smiGfxTokens.Count) { $_smiGfxTokens[$_smiVisIdx] } else { $_smiGfxTokens[0] }
$ROCmGpuLabel = "AMD ROCm ($ROCmGfxArch)"
if ($_smiNames.Count -eq $_smiGfxTokens.Count) {
$ROCmGpuName = if ($_smiVisIdx -lt $_smiNames.Count) { $_smiNames[$_smiVisIdx] } else { $_smiNames[0] }
}
} else {
# Attempt 2: 'static --asic' exposes the GFX target on ROCm 6+.
$smiAsicOut = ""
try { $smiAsicOut = Invoke-AmdSmiNoElevate $amdSmiExe.Source @('static','--asic') } catch {}
$_asicGfxTokens = @([regex]::Matches($smiAsicOut, "(?i)\b(gfx\d+[a-z]?)\b") | ForEach-Object { $_.Groups[1].Value.ToLower() })
$_asicNames = @([regex]::Matches($smiAsicOut, "(?im)Market.?Name\s*[:\|]\s*([^\r\n]+)") | ForEach-Object { $_.Groups[1].Value.Trim() })
if ($_asicGfxTokens.Count -gt 0) {
$ROCmGfxArch = if ($_smiVisIdx -lt $_asicGfxTokens.Count) { $_asicGfxTokens[$_smiVisIdx] } else { $_asicGfxTokens[0] }
$ROCmGpuLabel = "AMD ROCm ($ROCmGfxArch)"
if ($_asicNames.Count -eq $_asicGfxTokens.Count) {
$ROCmGpuName = if ($_smiVisIdx -lt $_asicNames.Count) { $_asicNames[$_smiVisIdx] } else { $_asicNames[0] }
}
} elseif ($_asicNames.Count -gt 0) {
$ROCmGpuName = if ($_smiVisIdx -lt $_asicNames.Count) { $_asicNames[$_smiVisIdx] } else { $_asicNames[0] }
$ROCmGpuLabel = "AMD ROCm ($ROCmGpuName)"
} else {
$ROCmGpuLabel = "AMD ROCm"
}
}
}
} catch {}
}
}
# This scan fills the LABEL the arch inference reads, so its gate is load-bearing:
# widening it turned a CPU install into a ROCm one on hosts amd-smi had already
# widening it turned a CPU install into a ROCm one on hosts hipinfo had already
# claimed. CIM, not Get-WmiObject, which PowerShell 7 removed: the catch below is
# silent, so a supported Radeon named only by Windows took the CPU path there, and
# the report-only peer scan cannot undo that. Same class and fields as every other
Expand Down Expand Up @@ -9539,17 +9445,6 @@ main()
}
} catch {}
}
if (-not $ROCmVersion -and $amdSmiAllowed) {
$amdSmiVer = Get-Command "amd-smi" -ErrorAction SilentlyContinue
if ($amdSmiVer) {
try {
$smiVerOut = Invoke-AmdSmiNoElevate $amdSmiVer.Source @('version')
if ($LASTEXITCODE -eq 0 -and $smiVerOut -match 'ROCm version:\s*(\d+\.\d+)') {
$ROCmVersion = $Matches[1]
}
} catch {}
}
}
}
}
} finally { $script:StudioMuteLines = $false }
Expand Down Expand Up @@ -9621,7 +9516,7 @@ main()
$MixedHostRoute = $null
$MixedHostAmdArch = $null
if ($ProbeAmdBesideNvidia) {
$_mixedArches = @(@($_hipAllArches) + @($_smiGfxTokens) + @($_asicGfxTokens) | Where-Object { $_ })
$_mixedArches = @(@($_hipAllArches) | Where-Object { $_ })
if ($_mixedArches.Count -eq 0 -and $wmiAmdNames -and $nameArchTable -and -not $env:UNSLOTH_ROCM_GFX_ARCH) {
# WMI-only: every adapter's inferred arch ("" when unmapped, so indexes line up), as setup.ps1 scores them.
$_wmiArchAt = @(foreach ($n in $wmiAmdNames) { $a = ""; foreach ($row in $nameArchTable) { if ($n -match $row.P) { $a = $row.A; break } }; $a })
Expand All @@ -9646,8 +9541,8 @@ main()
$ROCmGfxArch = $_mixedPicked; $ROCmGpuLabel = "AMD ROCm ($ROCmGfxArch)"; $ROCmGpuName = $null
$AmdHasGpuWheels = $true
}
# UNSLOTH_ROCM_GFX_ARCH names an arch, not a card: hipinfo, amd-smi or WMI must see one.
$_amdSeen = $HasROCm -or @($amdAdapters).Count -gt 0 -or @($_hipAllArches + $_smiGfxTokens + $_asicGfxTokens).Count -gt 0
# UNSLOTH_ROCM_GFX_ARCH names an arch, not a card: hipinfo or WMI must see one.
$_amdSeen = $HasROCm -or @($amdAdapters).Count -gt 0 -or @($_hipAllArches).Count -gt 0
$MixedHostRoute = Get-MixedHostTorchRoute -AmdHasGpuWheels ($AmdHasGpuWheels -and $_amdSeen) `
-ForceRocm (Test-RocmTorchExplicitlyRequested) -CudaMaskHidesNvidia $nvMaskHidesAll `
-NoticeArch $(if ($_amdSeen) { Get-MixedHostNoticeArch -Arches (@($ROCmGfxArch) + @($_mixedArches)) })
Expand Down Expand Up @@ -9743,7 +9638,6 @@ main()
# Above every AMD branch: true only when AMD gets no GPU wheel, so those would end on CPU.
step "gpu" $IntelGpuDisplay "Green"
} elseif ($HasROCm -and -not $ROCmUnsupportedGfxArch) {
# 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"
Expand Down
89 changes: 14 additions & 75 deletions studio/install_llama_prebuilt.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,63 +174,11 @@ def cuda_version_for_driver(driver_version: str) -> tuple[int, int] | None:
os.environ.setdefault("__COMPAT_LAYER", "RunAsInvoker")


def _path_inside_venv(path: str) -> bool:
"""True if ``path`` is inside the active venv (sys.prefix).
The venv hipInfo.exe (AMD wheel, put on PATH by the bnb fix) is NOT a HIP SDK
(_amd_smi_allowed)."""
try:
_root = os.path.normcase(os.path.realpath(sys.prefix))
# Root-dir prefix: commonpath would match every path, and a venv is never at root.
if os.path.dirname(_root) == _root:
return False
return os.path.normcase(os.path.commonpath([os.path.realpath(path), _root])) == _root
except (ValueError, OSError):
return False


def _external_hipinfo_on_path() -> bool:
"""True if a hipinfo OUTSIDE the venv is on PATH.
shutil.which returns only the first hit, so the venv hipInfo could shadow a
real HIP SDK's; scan every PATH entry and skip the venv copy."""
for _dir in os.environ.get("PATH", "").split(os.pathsep):
_dir = _dir.strip('"') # PATH entries can be quoted on Windows
if not _dir:
continue
_candidate = os.path.join(_dir, "hipinfo.exe")
if os.path.isfile(_candidate) and not _path_inside_venv(_candidate):
return True
return False


def _amd_smi_allowed() -> bool:
"""Whether it is safe to spawn amd-smi here.
On Windows w/o a working HIP runtime, amd-smi elevates a child and pops a
UAC/DiskPart prompt RunAsInvoker can't suppress. Only call it on Windows
when a HIP SDK is detectable (hipinfo present) or UNSLOTH_ENABLE_AMD_SMI=1;
Linux/macOS always allowed. When skipped, the gfx arch still arrives via the
forwarded --rocm-gfx, so prebuilt selection is unaffected.
"""
if platform.system() != "Windows":
return True
flag = os.environ.get("UNSLOTH_ENABLE_AMD_SMI", "").strip().lower()
if flag in ("1", "true", "yes", "on"):
return True
if flag in ("0", "false", "no", "off"):
return False
# A real HIP SDK lets amd-smi run un-elevated; ignore the venv hipInfo.exe (not an SDK).
if _external_hipinfo_on_path():
return True
for _var in ("HIP_PATH", "HIP_PATH_57", "ROCM_PATH"):
_root = os.environ.get(_var)
if not _root:
continue
_candidate = os.path.join(_root, "bin", "hipinfo.exe")
if os.path.isfile(_candidate) and not _path_inside_venv(_candidate):
return True
return False
"""Never on Windows: amd-smi.exe elevates a child and pops a UAC/DiskPart prompt RunAsInvoker
cannot suppress, with or without a HIP SDK.
The gfx arch still arrives via the forwarded --rocm-gfx, so prebuilt selection is unaffected."""
return platform.system() != "Windows"


windows_hidden_subprocess_kwargs = _core.windows_hidden_subprocess_kwargs
Expand Down Expand Up @@ -3152,25 +3100,16 @@ def _resolve_exe(name: str) -> str | None:
return _venv_candidate
return None

_win_probes = [(["hipinfo"], lambda out: "gcnarchname" in out.lower())]
if _amd_smi_allowed():
_win_probes.append((["amd-smi", "list"], _amd_smi_has_gpu))
for _cmd, _check in _win_probes:
_exe = _resolve_exe(_cmd[0])
if not _exe:
continue
try:
_result = run_capture([_exe, *_cmd[1:]], timeout = 10)
except Exception:
continue
if _result.returncode == 0 and _result.stdout.strip():
if _check(_result.stdout):
has_rocm = True
rocm_gfx_targets = _list_rocm_gfx_targets(_result.stdout)
rocm_gfx_target = _pick_rocm_gfx_target(
_result.stdout, hip_filtered = _cmd[0] == "hipinfo"
)
break
_exe = _resolve_exe("hipinfo")
try:
_out = run_capture([_exe], timeout = 10).stdout if _exe else ""
except Exception:
_out = ""
# Any exit code: hipinfo can crash (0xC0000005, some RDNA 4) after printing gcnArchName (#6043).
if "gcnarchname" in _out.lower():
has_rocm = True
rocm_gfx_targets = _list_rocm_gfx_targets(_out)
rocm_gfx_target = _pick_rocm_gfx_target(_out, hip_filtered = True)
# amdhip64.dll alone is not GPU evidence: the HIP SDK installs without an AMD GPU.

# Only probed with no usable NVIDIA and no ROCm, so "without_rocm" holds by construction.
Expand Down
Loading