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
62 changes: 4 additions & 58 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 @@ -3153,8 +3101,6 @@ def _resolve_exe(name: str) -> str | None:
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve AMD detection when hipinfo crashes after reporting an arch

If the Windows HIP SDK's hipinfo prints gcnArchName and then crashes with 0xC0000005, the remaining probe still discards the valid arch because it requires returncode == 0. Removing the fallback therefore prevents _auto_host_following_rocm_torch() from confirming AMD on a mixed AMD+NVIDIA host without a manual gfx environment override: Automatic updates now take the CUDA branch even when ROCm torch is installed/requested, and the updater's forwarded gfx does not clear the NVIDIA flags. Accept arch-bearing partial output here, as setup.ps1 and install_python_stack._detect_windows_gfx_arch() already do, to preserve this route without running amd-smi.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in d514274: detect_host and the Windows notice probe now accept hipinfo output that names gcnArchName whatever the exit code, as setup.ps1 / install.ps1 do; regression test test_a_crashed_hipinfo_counts_only_when_it_named_an_arch fails without the fix.

_exe = _resolve_exe(_cmd[0])
if not _exe:
Expand Down
Loading