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.

Windows installers find an NVIDIA GPU on the PCI bus, and say which CUDA it can use (#11166)

Daniel Han268b771b953a
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index c3f3dc6485e..25930cf2a3c 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -112,6 +112,8 @@ on:
- 'tests/studio/test_early_python_path_resolver.ps1'
- 'tests/studio/test_early_python_process_image.ps1'
- 'tests/studio/test_early_python_icon_refresh.ps1'
+ - 'tests/studio/test_nvidia_adapter_presence.ps1'
+ - 'tests/studio/test_nvidia_presence_xpu_timeout.ps1'
- 'tests/studio/test_application_control_cli_fallback.ps1'
# test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against
# process.rs's, so a change to either spelling has to run here.
@@ -230,6 +232,8 @@ on:
- 'tests/studio/test_early_python_path_resolver.ps1'
- 'tests/studio/test_early_python_process_image.ps1'
- 'tests/studio/test_early_python_icon_refresh.ps1'
+ - 'tests/studio/test_nvidia_adapter_presence.ps1'
+ - 'tests/studio/test_nvidia_presence_xpu_timeout.ps1'
- 'tests/studio/test_application_control_cli_fallback.ps1'
# test_application_control_cli_fallback.ps1 pins install.ps1's trampoline against
# process.rs's, so a change to either spelling has to run here.
@@ -442,6 +446,20 @@ jobs:
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -File tests\studio\test_install_lock_excludes_aliases.ps1
+ - name: NVIDIA adapter presence tests
+ shell: pwsh
+ run: pwsh -NoProfile -File tests/studio/test_nvidia_adapter_presence.ps1
+ - name: NVIDIA presence XPU update route tests
+ shell: pwsh
+ run: pwsh -NoProfile -File tests/studio/test_nvidia_presence_xpu_timeout.ps1
+ - name: NVIDIA adapter presence tests (Windows PowerShell 5.1)
+ if: runner.os == 'Windows'
+ shell: powershell
+ run: powershell -NoProfile -File tests\studio\test_nvidia_adapter_presence.ps1
+ - name: NVIDIA presence XPU update route tests (Windows PowerShell 5.1)
+ if: runner.os == 'Windows'
+ shell: powershell
+ run: powershell -NoProfile -File tests\studio\test_nvidia_presence_xpu_timeout.ps1
# AST-extracted helpers plus a real .cmd written to a temp dir, so no venv and no
# Windows needed. The 1260 classification is exercised against crafted exceptions:
# a hosted runner has no Application Control policy to be denied by. The enforced
diff --git a/install.ps1 b/install.ps1
index e1cdb39fff2..025b955259f 100644
--- a/install.ps1
+++ b/install.ps1
@@ -8727,6 +8727,11 @@ exit 0
# 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.
$script:NvidiaSmiWedged = $false
+ # Reset per run: streamed execution shares the caller's script scope.
+ $script:NvidiaPresenceOnly = $false
+ $script:NvidiaPresenceCudaFloor = $null
+ $script:NvidiaPresenceDriverRelease = $null
+ $script:VideoControllerScanResult = $null
function Test-NvidiaSmiHasGpu {
param([Parameter(Mandatory = $true)][string]$Exe)
@@ -9154,6 +9159,284 @@ main()
$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.
+ function Invoke-BoundedVideoControllerScan {
+ param([int]$TimeoutSec = 15)
+ # Cached even when Ok = $false: that is the hang case, and a retry would hang again.
+ if ($null -ne $script:VideoControllerScanResult) { return $script:VideoControllerScanResult }
+ $result = [pscustomobject]@{ Ok = $false; Names = @(); Adapters = @() }
+ $job = $null
+ try {
+ $job = Start-Job -ScriptBlock {
+ Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |
+ Select-Object -Property Name, PNPDeviceID, ConfigManagerErrorCode, DriverVersion
+ }
+ if (Wait-Job -Job $job -Timeout $TimeoutSec) {
+ $rows = @(Receive-Job -Job $job -ErrorAction SilentlyContinue)
+ $result.Adapters = @($rows | Where-Object { $_ })
+ $names = @($rows | ForEach-Object { $_.Name })
+ $result.Names = @($names | Where-Object { $_ })
+ $result.Ok = ($result.Names.Count -gt 0)
+ } else {
+ Stop-Job -Job $job -ErrorAction SilentlyContinue
+ }
+ } catch {
+ } finally {
+ # -ErrorAction does not stop a terminating error, which would abort the run.
+ if ($job) { try { Remove-Job -Job $job -Force -ErrorAction SilentlyContinue } catch {} }
+ }
+ $script:VideoControllerScanResult = $result
+ 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.
+ function Get-IntelRegistryAdapterNames {
+ $names = @()
+ $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
+ try {
+ $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
+ } catch { return @() }
+ foreach ($sub in $subs) {
+ # Guarded per subkey, not around the loop: one unreadable entry must not discard the
+ # adapters found after it. Matches windows_intel_gpu_in_registry()'s per-key skip.
+ try {
+ # Numeric subkeys only: "Properties" is ACL-restricted and not an adapter.
+ if ("$($sub.PSChildName)" -match '^\d+$') {
+ $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
+ if ($props) {
+ $desc = "$($props.DriverDesc)"
+ # Callers re-filter on "Intel", so a vendor-ID hit with a localized or
+ # OEM-branded DriverDesc would be found here and dropped there. Tag it
+ # instead; still only XPU-capable if the name says Arc / Data Center GPU.
+ if ("$($props.MatchingDeviceId)" -match '(?i)ven_8086') {
+ $names += if ($desc -match '(?i)intel') { $desc }
+ elseif ($desc) { "Intel $desc" }
+ else { "Intel Graphics" }
+ } elseif ($desc -match '(?i)intel') {
+ $names += $desc
+ }
+ }
+ }
+ } catch { }
+ }
+ return $names
+ }
+
+ # Returns the entry, not a bool: the version ladder needs its DriverVersion.
+ function Get-NvidiaRegistryAdapter {
+ $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
+ try {
+ $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
+ } catch { return $null }
+ # These keys outlive hardware, so only a UNANIMOUS release is used; disagreement reads as unknown.
+ $present = $false
+ $versions = @()
+ foreach ($sub in $subs) {
+ try {
+ if ("$($sub.PSChildName)" -notmatch '^\d+$') { continue }
+ $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
+ if (-not $props) { continue }
+ if ("$($props.MatchingDeviceId)" -notmatch '(?i)ven_10de') { continue }
+ $present = $true
+ $version = "$($props.DriverVersion)"
+ if ([string]::IsNullOrWhiteSpace($version)) { continue }
+ $release = Get-NvidiaDriverRelease -DriverVersion $version
+ if ($null -eq $release) { continue }
+ if ($versions -notcontains $release) { $versions += $release }
+ } catch {}
+ }
+ if (-not $present) { return $null }
+ if ($versions.Count -ne 1) { return [pscustomobject]@{ Release = $null } }
+ 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 }
+ $foreign = $false
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $version = "$($adapter.DriverVersion)"
+ if ([string]::IsNullOrWhiteSpace($version)) { $foreign = $true; continue }
+ if ($null -ne (Get-NvidiaDriverRelease -DriverVersion $version)) { return $false }
+ $foreign = $true
+ }
+ return $foreign
+ }
+
+ # VEN_10DE and ConfigManagerErrorCode 0 only, never names: a false yes sets $HasNvidiaSmi and
+ # switches off AMD and Intel detection.
+
+ function Test-NvidiaAdapterPresent {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ # $null is not evidence of health.
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ return $true
+ }
+ # No registry fallback: stale class keys would promote a GPU that is gone.
+ 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.
+ function Get-XpuCapableNameRegex { return "(?i)Intel.*(Arc|Data Center GPU)" }
+
+ function Test-IntelXpuRuntimeProven {
+ param($Scan = $null, [string]$PythonExe = "")
+ # The Intel route also serves non-Arc Intel GPUs once the existing torch proves XPU works, with no
+ # WMI precondition, so this asks the same thing. Any failure reads as not proven.
+ if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $false }
+ try {
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'
+ return [bool]($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$')
+ } catch {
+ return $false
+ }
+ }
+
+ 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.
+ 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) {
+ $scanNames = @($Scan.Names | Where-Object { $_ } | ForEach-Object { "$_" })
+ if (@($scanNames | Where-Object { $_ -match (Get-XpuCapableNameRegex) }).Count -gt 0) { return $true }
+ try {
+ foreach ($regName in @(Get-IntelRegistryAdapterNames)) {
+ if ("$regName" -notmatch (Get-XpuCapableNameRegex)) { continue }
+ foreach ($wmiName in $scanNames) {
+ if ("$regName".Contains($wmiName)) { return $true }
+ }
+ }
+ } catch {}
+ }
+ foreach ($adapter in @($Scan.Adapters)) {
+ # AMD vetoes on the AMD route's own test (name or 1002, any status: it keeps parked and
+ # PNP-less cards). Intel was answered above; UHD/Iris do not block.
+ if ("$($adapter.Name)" -match "AMD|Radeon" -or "$($adapter.PNPDeviceID)" -match '(?i)ven_1002') { return $true }
+ }
+ # Registry fallback here is deliberate: staleness only DECLINES a promotion. Without it, broken WMI
+ # hid the Arc on a hybrid host and cost it its XPU wheels.
+ if ($Scan.Ok) { return $false }
+ # Same normalized names as the Intel route (it prefixes "Intel" to a VEN_8086 DriverDesc).
+ try {
+ if (@(Get-IntelRegistryAdapterNames | Where-Object { "$_" -match (Get-XpuCapableNameRegex) }).Count -gt 0) { return $true }
+ } catch {}
+ $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
+ try {
+ $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
+ } catch { return $false }
+ foreach ($sub in $subs) {
+ try {
+ if ("$($sub.PSChildName)" -notmatch '^\d+$') { continue }
+ $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
+ if (-not $props) { continue }
+ $match = "$($props.MatchingDeviceId)"
+ if ($match -match '(?i)ven_1002') { return $true }
+ } catch {}
+ }
+ return $false
+ }
+
+ # 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 }
+ # NVIDIA's scheme only (32.0.15.6094 is 560.94). Basic Display versions like 10.0.19041.3636 must
+ # not read as releases, or a working CUDA venv gets replaced with CPU wheels.
+ $m = [regex]::Match($DriverVersion, '^\s*\d+\.\d+\.(1\d)\.(\d{4})\s*$')
+ if ($m.Success) {
+ $digits = ($m.Groups[1].Value + $m.Groups[2].Value)
+ if ($digits.Length -ge 5) {
+ $tail = $digits.Substring($digits.Length - 5)
+ return [int]$tail.Substring(0, 3)
+ }
+ return $null
+ }
+ # At least three digits: "1.2.3" is malformed, and a low release now selects CPU wheels.
+ $m2 = [regex]::Match($DriverVersion, '^\s*(\d+)\.')
+ if ($m2.Success) {
+ $parsed = [int]$m2.Groups[1].Value
+ if ($parsed -ge 100) { return $parsed }
+ }
+ return $null
+ }
+
+ function Get-NvidiaCudaFloorForRelease {
+ param($Release)
+ if ($null -eq $Release) { return $null }
+ # Same order and values as _DRIVER_MAJOR_CUDA.
+ foreach ($row in @(
+ @(580, 13, 0), @(570, 12, 8), @(560, 12, 6), @(555, 12, 5), @(550, 12, 4),
+ @(545, 12, 3), @(535, 12, 2), @(525, 12, 0), @(450, 11, 0)
+ )) {
+ if ([int]$Release -ge $row[0]) { return @($row[1], $row[2]) }
+ }
+ return $null
+ }
+
+ function Get-NvidiaDriverCudaFloor {
+ param([string]$DriverVersion)
+ return (Get-NvidiaCudaFloorForRelease -Release (Get-NvidiaDriverRelease -DriverVersion $DriverVersion))
+ }
+
+ function Get-NvidiaAdapterDriverRelease {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $release = Get-NvidiaDriverRelease -DriverVersion "$($adapter.DriverVersion)"
+ if ($null -ne $release) { return $release }
+ }
+ if (-not $Scan.Ok) {
+ $registryAdapter = Get-NvidiaRegistryAdapter
+ if ($registryAdapter) { return $registryAdapter.Release }
+ }
+ return $null
+ }
+
+ function Get-NvidiaAdapterCudaFloor {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $floor = Get-NvidiaDriverCudaFloor -DriverVersion "$($adapter.DriverVersion)"
+ if ($floor) { return $floor }
+ }
+ if (-not $Scan.Ok) {
+ $registryAdapter = Get-NvidiaRegistryAdapter
+ if ($registryAdapter) { return (Get-NvidiaCudaFloorForRelease -Release $registryAdapter.Release) }
+ }
+ return $null
+ }
+
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.
@@ -9163,6 +9446,35 @@ main()
Write-StudioLine " NVIDIA GPU found through the driver library; nvidia-smi is unavailable" -ForegroundColor Gray
}
}
+ # Last resort for #9255: presence only, gated on no healthy AMD or Intel adapter. The CUDA
+ # version is decided separately by the version ladder.
+ if (-not $HasNvidiaSmi) {
+ $presenceScan = Invoke-BoundedVideoControllerScan
+ $_presenceXpuPy = $VenvPython
+ if ($script:StudioVenvRollbackDir) {
+ $_presenceRollbackPy = Join-Path $script:StudioVenvRollbackDir "Scripts\python.exe"
+ if (Test-Path -LiteralPath $_presenceRollbackPy) { $_presenceXpuPy = $_presenceRollbackPy }
+ }
+ # Any throw declines the promotion; flags are set only once every answer is in hand.
+ try {
+ if ((Test-NvidiaAdapterPresent -Scan $presenceScan) -and
+ (Test-NvidiaAdapterWithoutNvidiaDriver -Scan $presenceScan)) {
+ Write-StudioLine " NVIDIA GPU found without the NVIDIA driver; install the NVIDIA driver and re-run for GPU support" -ForegroundColor Yellow
+ } elseif ((Test-NvidiaAdapterPresent -Scan $presenceScan) -and
+ -not (Test-OtherVendorAdapterPresent -Scan $presenceScan) -and
+ -not $script:StudioPreservedXpuVerdict -and
+ -not (Test-IntelXpuRuntimeProven -Scan $presenceScan -PythonExe $_presenceXpuPy)) {
+ $_presenceFloor = Get-NvidiaAdapterCudaFloor -Scan $presenceScan
+ # The floor is $null both for too-old and unreadable, which want opposite answers.
+ $_presenceRelease = Get-NvidiaAdapterDriverRelease -Scan $presenceScan
+ $HasNvidiaSmi = $true
+ $script:NvidiaPresenceOnly = $true
+ $script:NvidiaPresenceCudaFloor = $_presenceFloor
+ $script:NvidiaPresenceDriverRelease = $_presenceRelease
+ Write-StudioLine " NVIDIA GPU found on the PCI bus; nvidia-smi and the driver library are both unavailable" -ForegroundColor Gray
+ }
+ } 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
@@ -9660,71 +9972,6 @@ main()
# true on unmapped arches too, and those install CPU torch.
$AmdHasGpuWheels = [bool]($ROCmGfxArch -and $archFamilyMap.ContainsKey($ROCmGfxArch))
- # 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 setup.ps1's copy.
- function Invoke-BoundedVideoControllerScan {
- param([int]$TimeoutSec = 15)
- $result = [pscustomobject]@{ Ok = $false; Names = @() }
- $job = $null
- try {
- $job = Start-Job -ScriptBlock {
- Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |
- Select-Object -ExpandProperty Name
- }
- if (Wait-Job -Job $job -Timeout $TimeoutSec) {
- $names = @(Receive-Job -Job $job -ErrorAction SilentlyContinue)
- $result.Names = @($names | Where-Object { $_ })
- $result.Ok = ($result.Names.Count -gt 0)
- } else {
- Stop-Job -Job $job -ErrorAction SilentlyContinue
- }
- } catch {
- } finally {
- if ($job) { Remove-Job -Job $job -Force -ErrorAction SilentlyContinue }
- }
- 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 setup.ps1.
- function Get-IntelRegistryAdapterNames {
- $names = @()
- $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
- try {
- $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
- } catch { return @() }
- foreach ($sub in $subs) {
- # Guarded per subkey, not around the loop: one unreadable entry must not discard the
- # adapters found after it. Matches windows_intel_gpu_in_registry()'s per-key skip.
- try {
- # Numeric subkeys only: "Properties" is ACL-restricted and not an adapter.
- if ("$($sub.PSChildName)" -match '^\d+$') {
- $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
- if ($props) {
- $desc = "$($props.DriverDesc)"
- # Callers re-filter on "Intel", so a vendor-ID hit with a localized or
- # OEM-branded DriverDesc would be found here and dropped there. Tag it
- # instead; still only XPU-capable if the name says Arc / Data Center GPU.
- if ("$($props.MatchingDeviceId)" -match '(?i)ven_8086') {
- $names += if ($desc -match '(?i)intel') { $desc }
- elseif ($desc) { "Intel $desc" }
- else { "Intel Graphics" }
- } elseif ($desc -match '(?i)intel') {
- $names += $desc
- }
- }
- }
- } catch { }
- }
- return $names
- }
-
# ── 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
@@ -9995,6 +10242,26 @@ main()
$inventory = Get-NvidiaLibraryInventory
if ($inventory) {
$major = $inventory.CudaMajor; $minor = $inventory.CudaMinor; $caps = $inventory.ComputeCaps
+ } elseif ($script:NvidiaPresenceOnly) {
+ # Reached only after the bus promotion, so warning here cannot reach a host with no NVIDIA GPU.
+ if ($script:NvidiaPresenceCudaFloor) {
+ $major = [int]$script:NvidiaPresenceCudaFloor[0]
+ $minor = [int]$script:NvidiaPresenceCudaFloor[1]
+ substep "nvidia-smi and the NVIDIA driver library are both unavailable; the display driver supports at least CUDA $major.$minor, selecting wheels for it" "Yellow"
+ # Unknown compute capability: cap at cu126, the widest family still built for sm_70 (pre-Turing).
+ if ($major -gt 12 -or ($major -eq 12 -and $minor -gt 6)) {
+ $major = 12; $minor = 6
+ substep "no source could name the GPU's compute capability, so the family stops at cu126; set UNSLOTH_TORCH_INDEX_FAMILY to override" "Yellow"
+ }
+ } 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 {
+ $major = 12; $minor = 6
+ substep "an NVIDIA GPU is present but no source could name its CUDA version; defaulting to cu126. Set UNSLOTH_TORCH_INDEX_FAMILY to override" "Yellow"
+ }
} elseif (-not $NvidiaSmiExe) {
return "$baseUrl/cpu"
} else {
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 75a2e94d939..0a1516086a6 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1185,7 +1185,7 @@ function Get-GpuPrebuiltToKeepOverSourceBuild {
if ("$($env:UNSLOTH_LLAMA_TAG)".Trim() -notin @("", "latest")) { return "" }
$backend = Get-PrebuiltMarkerBackend -Marker (Join-Path $InstallDir "UNSLOTH_PREBUILT_INFO.json")
if (-not $backend) { return "" }
- $nvidia = $HasNvidiaSmi -or [bool]$script:NvidiaDriverLibraryOnly
+ $nvidia = $HasNvidiaDriverEvidence -or [bool]$script:NvidiaDriverLibraryOnly
$amd = $HasROCm -or [bool]$script:ROCmGfxArch
$present = switch ($backend) {
"cuda" { $nvidia }
@@ -2076,6 +2076,18 @@ 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".
+function Get-CudaFamilyForVersion {
+ param([int]$Major, [int]$Minor)
+ if ($Major -ge 13) { return "cu130" }
+ elseif ($Major -eq 12 -and $Minor -ge 8) { return "cu128" }
+ elseif ($Major -eq 12 -and $Minor -ge 6) { return "cu126" }
+ elseif ($Major -ge 12) { return "cu124" }
+ elseif ($Major -ge 11) { return "cu118" }
+ 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
@@ -2107,13 +2119,8 @@ function Get-PytorchCudaTag {
$minor = $inventory.CudaMinor
$caps = $inventory.ComputeCaps
}
- # PyTorch 2.10 offers: cu124, cu126, cu128, cu130
- if ($major -ge 13) { $family = "cu130" }
- elseif ($major -eq 12 -and $minor -ge 8) { $family = "cu128" }
- elseif ($major -eq 12 -and $minor -ge 6) { $family = "cu126" }
- elseif ($major -ge 12) { $family = "cu124" }
- elseif ($major -ge 11) { $family = "cu118" }
- else { return "cpu" }
+ $family = Get-CudaFamilyForVersion -Major $major -Minor $minor
+ if ($family -eq "cpu") { return "cpu" }
return (Get-CudaFamilyCappedForPreTuring $family $smiExe $caps)
}
@@ -2310,6 +2317,19 @@ function Test-TorchXpuAvailable {
return ($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$')
}
+# Stale only when the installed +rocm / +xpu wheel ANSWERED it sees no device; doubt keeps the venv.
+function Test-NvidiaPresenceStaleGpuWheel {
+ param([string]$InstalledTag, [string]$PythonExe)
+ if (-not $script:NvidiaPresenceOnly) { return $false }
+ if ($InstalledTag -ne "rocm" -and $InstalledTag -ne "xpu") { return $false }
+ if ($null -ne $script:NvidiaPresenceStaleGpuWheel) { return $script:NvidiaPresenceStaleGpuWheel }
+ $code = "import torch; x = getattr(torch, 'xpu', None); " +
+ "print('DEV=' + str(bool(torch.cuda.is_available() or (x is not None and x.is_available()))))"
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code $code
+ $script:NvidiaPresenceStaleGpuWheel = [bool]($probe.Ok -and $probe.Output -match '(?m)^DEV=False\s*$')
+ 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
@@ -2332,15 +2352,19 @@ function Assert-XpuRuntimeReady {
# Mirrors install.ps1's copy.
function Invoke-BoundedVideoControllerScan {
param([int]$TimeoutSec = 15)
- $result = [pscustomobject]@{ Ok = $false; Names = @() }
+ # Cached even when Ok = $false: that is the hang case, and a retry would hang again.
+ if ($null -ne $script:VideoControllerScanResult) { return $script:VideoControllerScanResult }
+ $result = [pscustomobject]@{ Ok = $false; Names = @(); Adapters = @() }
$job = $null
try {
$job = Start-Job -ScriptBlock {
Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |
- Select-Object -ExpandProperty Name
+ Select-Object -Property Name, PNPDeviceID, ConfigManagerErrorCode, DriverVersion
}
if (Wait-Job -Job $job -Timeout $TimeoutSec) {
- $names = @(Receive-Job -Job $job -ErrorAction SilentlyContinue)
+ $rows = @(Receive-Job -Job $job -ErrorAction SilentlyContinue)
+ $result.Adapters = @($rows | Where-Object { $_ })
+ $names = @($rows | ForEach-Object { $_.Name })
$result.Names = @($names | Where-Object { $_ })
$result.Ok = ($result.Names.Count -gt 0)
} else {
@@ -2348,8 +2372,10 @@ function Invoke-BoundedVideoControllerScan {
}
} catch {
} finally {
- if ($job) { Remove-Job -Job $job -Force -ErrorAction SilentlyContinue }
+ # -ErrorAction does not stop a terminating error, which would abort the run.
+ if ($job) { try { Remove-Job -Job $job -Force -ErrorAction SilentlyContinue } catch {} }
}
+ $script:VideoControllerScanResult = $result
return $result
}
@@ -3585,6 +3611,13 @@ function Get-NvidiaSmiCandidatePaths {
# 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.
$script:NvidiaSmiWedged = $false
+# Reset per run: streamed execution shares the caller's script scope.
+$script:NvidiaPresenceOnly = $false
+$script:NvidiaPresenceCudaFloor = $null
+$script:NvidiaPresenceDriverRelease = $null
+$script:VideoControllerScanResult = $null
+$script:NvidiaPreR450CpuFallback = $false
+$script:NvidiaPresenceStaleGpuWheel = $null
function Test-NvidiaSmiHasGpu {
param([Parameter(Mandatory = $true)][string]$Exe)
@@ -3684,6 +3717,219 @@ if (-not $HasNvidiaSmi) {
Write-StudioLine " Found nvidia-smi at $(Split-Path $firstListing -Parent)" -ForegroundColor Gray
}
}
+# Returns the entry, not a bool: the version ladder needs its DriverVersion.
+function Get-NvidiaRegistryAdapter {
+ $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
+ try {
+ $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
+ } catch { return $null }
+ # These keys outlive hardware, so only a UNANIMOUS release is used; disagreement reads as unknown.
+ $present = $false
+ $versions = @()
+ foreach ($sub in $subs) {
+ try {
+ if ("$($sub.PSChildName)" -notmatch '^\d+$') { continue }
+ $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
+ if (-not $props) { continue }
+ if ("$($props.MatchingDeviceId)" -notmatch '(?i)ven_10de') { continue }
+ $present = $true
+ $version = "$($props.DriverVersion)"
+ if ([string]::IsNullOrWhiteSpace($version)) { continue }
+ $release = Get-NvidiaDriverRelease -DriverVersion $version
+ if ($null -eq $release) { continue }
+ if ($versions -notcontains $release) { $versions += $release }
+ } catch {}
+ }
+ if (-not $present) { return $null }
+ if ($versions.Count -ne 1) { return [pscustomobject]@{ Release = $null } }
+ 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 }
+ $foreign = $false
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $version = "$($adapter.DriverVersion)"
+ if ([string]::IsNullOrWhiteSpace($version)) { $foreign = $true; continue }
+ if ($null -ne (Get-NvidiaDriverRelease -DriverVersion $version)) { return $false }
+ $foreign = $true
+ }
+ return $foreign
+}
+
+# VEN_10DE and ConfigManagerErrorCode 0 only, never names: a false yes sets $HasNvidiaSmi and
+# switches off AMD and Intel detection.
+
+function Test-NvidiaAdapterPresent {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ # $null is not evidence of health.
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ return $true
+ }
+ # No registry fallback: stale class keys would promote a GPU that is gone.
+ 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.
+function Get-XpuCapableNameRegex { return "(?i)Intel.*(Arc|Data Center GPU)" }
+
+function Test-IntelXpuRuntimeProven {
+ param($Scan = $null, [string]$PythonExe = "")
+ # The Intel route also serves non-Arc Intel GPUs once the existing torch proves XPU works, with no
+ # WMI precondition, so this asks the same thing. Any failure reads as not proven.
+ if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $false }
+ try {
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'
+ return [bool]($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$')
+ } catch {
+ return $false
+ }
+}
+
+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.
+ 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) {
+ $scanNames = @($Scan.Names | Where-Object { $_ } | ForEach-Object { "$_" })
+ if (@($scanNames | Where-Object { $_ -match (Get-XpuCapableNameRegex) }).Count -gt 0) { return $true }
+ try {
+ foreach ($regName in @(Get-IntelRegistryAdapterNames)) {
+ if ("$regName" -notmatch (Get-XpuCapableNameRegex)) { continue }
+ foreach ($wmiName in $scanNames) {
+ if ("$regName".Contains($wmiName)) { return $true }
+ }
+ }
+ } catch {}
+ }
+ foreach ($adapter in @($Scan.Adapters)) {
+ # AMD vetoes on the AMD route's own test (name or 1002, any status: it keeps parked and
+ # PNP-less cards). Intel was answered above; UHD/Iris do not block.
+ if ("$($adapter.Name)" -match "AMD|Radeon" -or "$($adapter.PNPDeviceID)" -match '(?i)ven_1002') { return $true }
+ }
+ # Registry fallback here is deliberate: staleness only DECLINES a promotion. Without it, broken WMI
+ # hid the Arc on a hybrid host and cost it its XPU wheels.
+ if ($Scan.Ok) { return $false }
+ # Same normalized names as the Intel route (it prefixes "Intel" to a VEN_8086 DriverDesc).
+ try {
+ if (@(Get-IntelRegistryAdapterNames | Where-Object { "$_" -match (Get-XpuCapableNameRegex) }).Count -gt 0) { return $true }
+ } catch {}
+ $classKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
+ try {
+ $subs = @(Get-ChildItem -LiteralPath $classKey -ErrorAction SilentlyContinue)
+ } catch { return $false }
+ foreach ($sub in $subs) {
+ try {
+ if ("$($sub.PSChildName)" -notmatch '^\d+$') { continue }
+ $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
+ if (-not $props) { continue }
+ $match = "$($props.MatchingDeviceId)"
+ if ($match -match '(?i)ven_1002') { return $true }
+ } catch {}
+ }
+ return $false
+}
+
+# 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 }
+ # NVIDIA's scheme only (32.0.15.6094 is 560.94). Basic Display versions like 10.0.19041.3636 must
+ # not read as releases, or a working CUDA venv gets replaced with CPU wheels.
+ $m = [regex]::Match($DriverVersion, '^\s*\d+\.\d+\.(1\d)\.(\d{4})\s*$')
+ if ($m.Success) {
+ $digits = ($m.Groups[1].Value + $m.Groups[2].Value)
+ if ($digits.Length -ge 5) {
+ $tail = $digits.Substring($digits.Length - 5)
+ return [int]$tail.Substring(0, 3)
+ }
+ return $null
+ }
+ # At least three digits: "1.2.3" is malformed, and a low release now selects CPU wheels.
+ $m2 = [regex]::Match($DriverVersion, '^\s*(\d+)\.')
+ if ($m2.Success) {
+ $parsed = [int]$m2.Groups[1].Value
+ if ($parsed -ge 100) { return $parsed }
+ }
+ return $null
+}
+
+function Get-NvidiaCudaFloorForRelease {
+ param($Release)
+ if ($null -eq $Release) { return $null }
+ # Same order and values as _DRIVER_MAJOR_CUDA.
+ foreach ($row in @(
+ @(580, 13, 0), @(570, 12, 8), @(560, 12, 6), @(555, 12, 5), @(550, 12, 4),
+ @(545, 12, 3), @(535, 12, 2), @(525, 12, 0), @(450, 11, 0)
+ )) {
+ if ([int]$Release -ge $row[0]) { return @($row[1], $row[2]) }
+ }
+ return $null
+}
+
+function Get-NvidiaDriverCudaFloor {
+ param([string]$DriverVersion)
+ return (Get-NvidiaCudaFloorForRelease -Release (Get-NvidiaDriverRelease -DriverVersion $DriverVersion))
+}
+
+function Get-NvidiaAdapterDriverRelease {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $release = Get-NvidiaDriverRelease -DriverVersion "$($adapter.DriverVersion)"
+ if ($null -ne $release) { return $release }
+ }
+ if (-not $Scan.Ok) {
+ $registryAdapter = Get-NvidiaRegistryAdapter
+ if ($registryAdapter) { return $registryAdapter.Release }
+ }
+ return $null
+}
+
+function Get-NvidiaAdapterCudaFloor {
+ param($Scan = $null)
+ if ($null -eq $Scan) { $Scan = Invoke-BoundedVideoControllerScan }
+ foreach ($adapter in @($Scan.Adapters)) {
+ if ("$($adapter.PNPDeviceID)" -notmatch '(?i)ven_10de') { continue }
+ if ($null -eq $adapter.ConfigManagerErrorCode) { continue }
+ if ([int]$adapter.ConfigManagerErrorCode -ne 0) { continue }
+ $floor = Get-NvidiaDriverCudaFloor -DriverVersion "$($adapter.DriverVersion)"
+ if ($floor) { return $floor }
+ }
+ if (-not $Scan.Ok) {
+ $registryAdapter = Get-NvidiaRegistryAdapter
+ if ($registryAdapter) { return (Get-NvidiaCudaFloorForRelease -Release $registryAdapter.Release) }
+ }
+ return $null
+}
+
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.
@@ -3698,6 +3944,37 @@ if (-not $HasNvidiaSmi -and (Get-NvidiaLibraryInventory)) {
$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.
+if (-not $HasNvidiaSmi) {
+ $presenceScan = Invoke-BoundedVideoControllerScan
+ # Any throw declines the promotion; flags are set only once every answer is in hand.
+ try {
+ $_presenceXpuVenvs = @(@($VenvDir, (Get-ProbableStudioVenvDir)) | Where-Object { $_ } | Select-Object -Unique)
+ if ((Test-NvidiaAdapterPresent -Scan $presenceScan) -and
+ (Test-NvidiaAdapterWithoutNvidiaDriver -Scan $presenceScan)) {
+ Write-StudioLine " NVIDIA GPU found without the NVIDIA driver; install the NVIDIA driver and re-run for GPU support" -ForegroundColor Yellow
+ } elseif ((Test-NvidiaAdapterPresent -Scan $presenceScan) -and
+ -not (Test-OtherVendorAdapterPresent -Scan $presenceScan) -and
+ -not (@($_presenceXpuVenvs | Where-Object {
+ (Test-VenvTorchIsXpu $_) -and
+ (Test-IntelXpuRuntimeProven -Scan $presenceScan -PythonExe (Join-Path $_ "Scripts\python.exe")) }).Count -gt 0)) {
+ $_presenceFloor = Get-NvidiaAdapterCudaFloor -Scan $presenceScan
+ # The floor is $null both for too-old and unreadable, which want opposite answers.
+ $_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
+ Write-StudioLine " NVIDIA GPU found on the PCI bus; nvidia-smi and the driver library are both unavailable" -ForegroundColor Gray
+ }
+ } 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.
+$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
@@ -7743,6 +8020,22 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
$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).
+ $_nvidiaIsReachable = (-not $NoTorchMode) -and
+ ((-not $_pinLeafNow) -or (Test-CudaFamilyLeaf $_pinLeafNow))
+ $_nvidiaPreR450 = ($null -ne $script:NvidiaPresenceDriverRelease -and
+ $script:NvidiaPresenceDriverRelease -lt 450)
+ if ($SkipPythonDeps -and $script:NvidiaPresenceOnly -and $_nvidiaIsReachable -and
+ (-not $_nvidiaPreR450) -and $installedTorchTag -eq "cpu") {
+ substep "NVIDIA GPU found on the PCI bus but the installed PyTorch is a CPU build -- reinstalling CUDA PyTorch" "Cyan"
+ $SkipPythonDeps = $false
+ }
+ if ($SkipPythonDeps -and $script:NvidiaPresenceOnly -and $_nvidiaIsReachable -and
+ (Test-NvidiaPresenceStaleGpuWheel -InstalledTag $installedTorchTag -PythonExe (Join-Path $VenvDir "Scripts\python.exe"))) {
+ 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.
@@ -8041,6 +8334,12 @@ 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.
+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
+}
if ($PinnedTorchIndexUrl) {
$CuTag = Get-TorchIndexLeaf $PinnedTorchIndexUrl
} elseif ($script:PreservedXpuVenv) {
@@ -8061,6 +8360,30 @@ if ($PinnedTorchIndexUrl) {
$CuTag = if (Test-CudaFamilyLeaf $script:PreservedInstallerTorchTag) { $script:PreservedInstallerTorchTag } else { "cpu" }
} elseif ($HasNvidiaSmi) {
$CuTag = Get-PytorchCudaTag
+ if (-not $CuTag -and $null -ne $script:NvidiaPresenceDriverRelease -and
+ $script:NvidiaPresenceDriverRelease -lt 450) {
+ # Pre-R450: CPU, matching install.ps1; cu126 would not load.
+ $CuTag = "cpu"
+ # An installed +cu wheel satisfies the bare CPU range, so force the reinstall.
+ if (Test-CudaFamilyLeaf $installedTorchTag) { $script:NvidiaPreR450CpuFallback = $true }
+ if (Test-NvidiaPresenceStaleGpuWheel -InstalledTag $installedTorchTag -PythonExe (Join-Path $VenvDir "Scripts\python.exe")) {
+ $script:NvidiaPreR450CpuFallback = $true
+ }
+ 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"
+ }
+ 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).
+ $floorMajor = [int]$script:NvidiaPresenceCudaFloor[0]
+ $floorMinor = [int]$script:NvidiaPresenceCudaFloor[1]
+ # Same pre-Turing cap as install.ps1: unknown capability stops at cu126.
+ if ($floorMajor -gt 12 -or ($floorMajor -eq 12 -and $floorMinor -gt 6)) {
+ $floorMajor = 12; $floorMinor = 6
+ }
+ # Never "cu$major$minor": CUDA 11.0 is served by cu118; cu110 does not exist.
+ $CuTag = Get-CudaFamilyForVersion -Major $floorMajor -Minor $floorMinor
+ 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" }
@@ -8427,6 +8750,7 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# 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.
$cpuTorchSpec = "torch"; $cpuVisionSpec = "torchvision"; $cpuAudioSpec = "torchaudio"
@@ -8481,6 +8805,13 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
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.
@@ -9460,7 +9791,7 @@ if ($LocalLlamaCppLinked) {
if ($_m) { $_m } else { Get-WoaTorchIndexMarker }
}
}
- $_nvidiaEvidence = $HasNvidiaSmi -or ((Test-WinArm64Venv) -and $_woaEvidenceIndex -and
+ $_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.
$_rocmKinds = if (Test-WinArm64Venv) {
@@ -9802,10 +10133,10 @@ if ($llamaBinState -eq "Present") {
if (-not (Test-AccessDeniedError $_)) { throw }
Exit-PathAccessDenied -Path $LlamaCppDir -Label "llama.cpp install" -OwnershipUnverified:$RuntimeRootIsCustom
}
- if ($HasNvidiaSmi -and -not $cachedCuda) {
+ if ($HasNvidiaDriverEvidence -and -not $cachedCuda) {
Write-StudioLine " Existing llama-server is CPU-only but GPU is available -- rebuilding" -ForegroundColor Yellow
$NeedRebuild = $true
- } elseif (-not $HasNvidiaSmi -and $cachedCuda) {
+ } elseif (-not $HasNvidiaDriverEvidence -and $cachedCuda) {
Write-StudioLine " Existing llama-server was built with CUDA but no GPU detected -- rebuilding" -ForegroundColor Yellow
$NeedRebuild = $true
}
@@ -9877,7 +10208,7 @@ if ($LocalLlamaCppLinked) {
$script:LlamaCppDegraded = $true
} elseif (-not $HasCmakeForBuild) {
Write-StudioLine ""
- if (-not $HasNvidiaSmi) {
+ if (-not $HasNvidiaDriverEvidence) {
substep "CMake is required to build llama-server for GGUF chat mode." "Yellow"
substep "Continuing setup without llama.cpp build." "Yellow"
substep "Install CMake from https://cmake.org/download/ and re-run setup." "Yellow"
@@ -9927,10 +10258,10 @@ if ($LocalLlamaCppLinked) {
}
# After the final VS generator, so the CUDA .targets land in the toolset cmake uses.
- if ($HasNvidiaSmi) { Resolve-CudaToolkit -RequireOrExit }
+ if ($HasNvidiaDriverEvidence) { Resolve-CudaToolkit -RequireOrExit }
Write-StudioLine ""
- if ($HasNvidiaSmi) {
+ 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.
@@ -9957,7 +10288,7 @@ if ($LocalLlamaCppLinked) {
$FailedStep = ""
# Refresh-Environment may have repopulated conflicting CUDA_PATH_V* from the registry.
- if ($HasNvidiaSmi -and $CudaToolkitRoot) {
+ if ($HasNvidiaDriverEvidence -and $CudaToolkitRoot) {
$cudaPathVars2 = @([Environment]::GetEnvironmentVariables('Process').Keys | Where-Object { $_ -match '^CUDA_PATH_V' })
foreach ($v2 in $cudaPathVars2) {
[Environment]::SetEnvironmentVariable($v2, $null, 'Process')
@@ -10228,7 +10559,7 @@ if ($LocalLlamaCppLinked) {
}
$CmakeArgs += '-DCMAKE_EXE_LINKER_FLAGS=/NODEFAULTLIB:LIBCMT'
# CUDA flags -- only if GPU available, otherwise explicitly disable
- if ($HasNvidiaSmi -and $NvccPath) {
+ 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)) {
diff --git a/tests/studio/install/test_llama_kind_gate_matches_selector.py b/tests/studio/install/test_llama_kind_gate_matches_selector.py
index e0ff00f36b2..fc557b3a5fd 100644
--- a/tests/studio/install/test_llama_kind_gate_matches_selector.py
+++ b/tests/studio/install/test_llama_kind_gate_matches_selector.py
@@ -128,6 +128,7 @@ def _expected_kinds(*, arm64_venv: bool, nvidia: bool, rocm: bool, opt_out: bool
"function Test-WoaPersistableIndex { param($i) return ($i -like '*nvidia*') }",
f"$env:UNSLOTH_LLAMA_ARM64_CUDA = '{'0' if opt_out else '1'}'",
f"$HasNvidiaSmi = ${str(nvidia).lower()}",
+ f"$HasNvidiaDriverEvidence = ${str(nvidia).lower()}",
f"$HasROCm = ${str(rocm).lower()}",
"$script:ROCmGfxArch = " + ("'gfx1201'" if rocm else "$null"),
block,
diff --git a/tests/studio/install/test_pr4562_bugfixes.py b/tests/studio/install/test_pr4562_bugfixes.py
index d8508dbb3e6..4afe20718a2 100644
--- a/tests/studio/install/test_pr4562_bugfixes.py
+++ b/tests/studio/install/test_pr4562_bugfixes.py
@@ -735,7 +735,7 @@ class TestSourceCodePatterns:
# GGML_CUDA=OFF (undetectable-arch CPU fallback, #5854), so anchor on GGML_CUDA=ON and the final (no-GPU)
# GGML_CUDA=OFF.
flag_idx = content.index("-allow-unsupported-compiler")
- cuda_guard_idx = content.index("if ($HasNvidiaSmi -and $NvccPath)")
+ cuda_guard_idx = content.index("if ($HasNvidiaDriverEvidence -and $NvccPath)")
cuda_on_idx = content.index("'-DGGML_CUDA=ON'")
cpu_else_idx = content.rindex("'-DGGML_CUDA=OFF'")
assert cuda_guard_idx < cuda_on_idx < flag_idx < cpu_else_idx, (
diff --git a/tests/studio/install/test_woa_torch_index_persistence.py b/tests/studio/install/test_woa_torch_index_persistence.py
index 1bb49c580ed..a0caf32b2b5 100644
--- a/tests/studio/install/test_woa_torch_index_persistence.py
+++ b/tests/studio/install/test_woa_torch_index_persistence.py
@@ -3691,7 +3691,7 @@ class TestATransientProbeFailureKeepsTheCudaBundle:
selector with no NVIDIA evidence, which installs the CPU bundle instead."""
def test_the_persisted_cuda_index_counts_as_evidence(self):
- assert "$_nvidiaEvidence = $HasNvidiaSmi -or ((Test-WinArm64Venv)" in SETUP_SRC
+ assert "$_nvidiaEvidence = $HasNvidiaDriverEvidence -or ((Test-WinArm64Venv)" in SETUP_SRC
assert "elseif ($_nvidiaEvidence) { $_nvidiaKinds }" in SETUP_SRC
def test_only_a_persistable_index_counts(self):
diff --git a/tests/studio/test_ci_shell_suite_coverage.py b/tests/studio/test_ci_shell_suite_coverage.py
index cc07c875f8f..1d76cea0567 100644
--- a/tests/studio/test_ci_shell_suite_coverage.py
+++ b/tests/studio/test_ci_shell_suite_coverage.py
@@ -316,3 +316,69 @@ class TestPowerShellTestsRunOnAPr:
if not (REPO_ROOT / test).is_file()
]
assert not missing, f"workflows invoke PowerShell tests that do not exist: {missing}"
+
+
+class TestWindowsPowerShellStepsAreGated:
+ """A step that runs powershell.exe on a multi-OS job must say so.
+
+ Windows PowerShell 5.1 is the host the Desktop app launches the installer in, so the .ps1
+ suites here have a second leg that runs it. `powershell` does not exist on a hosted Linux or
+ macOS runner, and a step without the guard fails the whole job for a reason that has nothing
+ to do with the change under test. Observed exactly that way: a merge dropped the `if:` line
+ from one such step because an identical line already appeared above it.
+
+ A job pinned to windows-latest needs no guard, so the rule is about jobs whose runner is not
+ provably Windows: a matrix expression, or anything else that is not a windows-* literal.
+ """
+
+ @staticmethod
+ def _multi_os_jobs(doc):
+ for name, job in (doc.get("jobs") or {}).items():
+ runs_on = job.get("runs-on")
+ labels = runs_on if isinstance(runs_on, list) else [runs_on]
+ if all(
+ isinstance(l, str) and l.startswith("windows-") for l in labels if l is not None
+ ):
+ continue
+ yield name, job
+
+ @staticmethod
+ def _windows_powershell_steps(job):
+ for step in job.get("steps") or []:
+ if not isinstance(step, dict):
+ continue
+ run = str(step.get("run") or "")
+ if "powershell -NoProfile" not in run:
+ continue
+ if "pwsh -NoProfile" in run:
+ continue
+ yield step
+
+ def test_every_windows_powershell_step_is_gated_on_windows(self):
+ for workflow in sorted(_WORKFLOWS.glob("*.yml")):
+ doc = yaml.safe_load(workflow.read_text(encoding = "utf-8"))
+ if not isinstance(doc, dict):
+ continue
+ for job_name, job in self._multi_os_jobs(doc):
+ for step in self._windows_powershell_steps(job):
+ condition = str(step.get("if") or "")
+ assert "runner.os == 'Windows'" in condition, (
+ f"{workflow.name}: job {job_name}, step {step.get('name')!r} runs "
+ f"powershell.exe on a job that is not pinned to a Windows runner, with no "
+ f"`if: runner.os == 'Windows'`. That executable does not exist on the "
+ f"Linux and macOS legs."
+ )
+
+ def test_the_rule_finds_the_steps_it_is_about(self):
+ """Without this, a walk that matched nothing would leave the rule above vacuous."""
+ found = 0
+ for workflow in sorted(_WORKFLOWS.glob("*.yml")):
+ doc = yaml.safe_load(workflow.read_text(encoding = "utf-8"))
+ if not isinstance(doc, dict):
+ continue
+ for _, job in self._multi_os_jobs(doc):
+ found += len(list(self._windows_powershell_steps(job)))
+ assert found >= 5, (
+ f"only {found} Windows PowerShell steps found on multi-OS jobs; the walk above is "
+ f"looking in the wrong place"
+ )
diff --git a/tests/studio/test_nvidia_adapter_presence.ps1 b/tests/studio/test_nvidia_adapter_presence.ps1
new file mode 100644
index 00000000000..fff33232353
--- /dev/null
+++ b/tests/studio/test_nvidia_adapter_presence.ps1
@@ -0,0 +1,734 @@
+#!/usr/bin/env pwsh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# $HasNvidiaSmi suppresses AMD and Intel detection, so the presence source must say yes only for a
+# healthy VEN_10DE adapter (names are deliberately adversarial) and must lead to a real index.
+# Run: pwsh -NoProfile -File tests/studio/test_nvidia_adapter_presence.ps1
+
+$ErrorActionPreference = "Stop"
+$root = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path
+$installPs1 = Join-Path $root "install.ps1"
+$setupPs1 = Join-Path $root "studio/setup.ps1"
+$installText = [System.IO.File]::ReadAllText($installPs1)
+$setupText = [System.IO.File]::ReadAllText($setupPs1)
+$texts = @{ $installPs1 = $installText; $setupPs1 = $setupText }
+
+$failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" }
+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+# Passes when $text is non-empty, matches every $re and none of $not.
+function CheckText($name, $text, [string[]]$re = @(), [string[]]$not = @()) {
+ $ok = -not [string]::IsNullOrEmpty($text)
+ foreach ($r in $re) { $ok = $ok -and ($text -match $r) }
+ foreach ($r in $not) { $ok = $ok -and ($text -notmatch $r) }
+ Check $name $ok
+}
+
+function Get-FunctionText($file, $name) {
+ $errors = $null
+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$null, [ref]$errors)
+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$file has parse errors" }
+ $fn = $ast.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name
+ }, $true)
+ if ($fn.Count -lt 1) { throw "expected $name in $file, found none" }
+ return $fn[0].Extent.Text
+}
+function Get-PromotionBlock($file) {
+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$null, [ref]$null)
+ return @($ast.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.IfStatementAst] -and
+ $n.Extent.Text -match '^if \(-not \$HasNvidiaSmi\) \{\s*\$presenceScan = Invoke-BoundedVideoControllerScan' }, $true))[0].Extent.Text
+}
+
+# install.ps1 nests one level deeper, so compare without indentation.
+$strip = { param($t) (($t -split "`n") | ForEach-Object { $_.TrimStart() }) -join "`n" }
+$shared = @(
+ "Invoke-BoundedVideoControllerScan", "Test-NvidiaAdapterPresent",
+ "Test-OtherVendorAdapterPresent", "Get-XpuCapableNameRegex",
+ "Get-NvidiaDriverRelease", "Get-NvidiaCudaFloorForRelease", "Get-NvidiaDriverCudaFloor",
+ "Get-NvidiaAdapterDriverRelease", "Get-NvidiaAdapterCudaFloor",
+ "Get-NvidiaRegistryAdapter", "Test-NvidiaAdapterWithoutNvidiaDriver", "Test-IntelXpuRuntimeProven"
+)
+foreach ($name in $shared) {
+ Check "install.ps1 and setup.ps1 carry the same $name" (
+ (& $strip (Get-FunctionText $installPs1 $name)) -eq (& $strip (Get-FunctionText $setupPs1 $name)))
+ if ($name -ne "Invoke-BoundedVideoControllerScan") { Invoke-Expression (Get-FunctionText $setupPs1 $name) }
+}
+
+# The gate also takes AMD evidence from the host (HIP SDK, ROCm variables, hipinfo or amd-smi on
+# PATH), which an AMD machine running this test really has. Only the fakes below may answer.
+foreach ($v in @("UNSLOTH_ROCM_GFX_ARCH", "_UNSLOTH_ROCM_GFX_ARCH_HANDOFF", "HIP_PATH", "HIP_PATH_57", "ROCM_PATH", "UNSLOTH_ENABLE_AMD_SMI")) {
+ [Environment]::SetEnvironmentVariable($v, $null)
+}
+# [IO.Path]::Combine, not Join-Path: Windows PowerShell 5.1's Join-Path throws on an entry whose
+# drive does not exist, which a real PATH can carry.
+$env:PATH = (@("$env:PATH" -split [System.IO.Path]::PathSeparator | Where-Object {
+ $dir = $_
+ $keep = [bool]$dir
+ foreach ($tool in @("hipinfo.exe", "amd-smi.exe")) {
+ if ($keep) { try { $keep = -not [System.IO.File]::Exists([System.IO.Path]::Combine($dir, $tool)) } catch { } }
+ }
+ $keep
+}) -join [System.IO.Path]::PathSeparator)
+$script:FakeRegistryNames = @()
+$script:FakeRegistryThrows = $false
+function Get-IntelRegistryAdapterNames {
+ if ($script:FakeRegistryThrows) { throw "registry unreadable" }
+ return $script:FakeRegistryNames
+}
+$script:FakeAdapters = @()
+$script:FakeScanOk = $null # $null derives Ok from the fixture
+function Invoke-BoundedVideoControllerScan {
+ param([int]$TimeoutSec = 15)
+ return [pscustomobject]@{
+ Ok = $(if ($null -eq $script:FakeScanOk) { $script:FakeAdapters.Count -gt 0 } else { $script:FakeScanOk })
+ Names = @($script:FakeAdapters | ForEach-Object { $_.Name })
+ Adapters = $script:FakeAdapters
+ }
+}
+# No HKLM on Linux: the class keys are stubbed from $script:RegKeys so rows cannot pass for the wrong reason.
+$script:RegKeys = @()
+$script:RegistryConsulted = $false
+function Get-ChildItem {
+ param([string]$LiteralPath, [switch]$Directory, [string]$Filter, $ErrorAction)
+ if ("$LiteralPath" -notmatch 'Control\\Class') { return @() }
+ $script:RegistryConsulted = $true
+ return @(for ($i = 0; $i -lt @($script:RegKeys).Count; $i++) {
+ [pscustomobject]@{ PSChildName = "{0:D4}" -f $i; PSPath = "fake::{0:D4}" -f $i } })
+}
+function Get-ItemProperty {
+ param([string]$LiteralPath, $ErrorAction)
+ if ("$LiteralPath" -match '^fake::(\d{4})$') { return [pscustomobject]@($script:RegKeys)[[int]$Matches[1]] }
+ return $null
+}
+$script:ProbeCalls = 0
+$script:ProbeThrows = $false
+$script:ProbeAnswer = @{ Ok = $true; Output = "True" }
+function Invoke-BoundedPythonProbe {
+ param($PythonExe, $Code, $TimeoutSec)
+ $script:ProbeCalls++
+ if ($script:ProbeThrows) { throw "probe failed" }
+ return [pscustomobject]$script:ProbeAnswer
+}
+function Adapter($name, $id, $code, $driver = "32.0.15.6094") {
+ return [pscustomobject]@{ Name = $name; PNPDeviceID = $id; ConfigManagerErrorCode = $code; DriverVersion = $driver }
+}
+function NvAdapter($code = 0, $driver = "32.0.15.6094") { Adapter "NVIDIA GeForce RTX 4090" "PCI\VEN_10DE&DEV_2684" $code $driver }
+$nv = NvAdapter
+$amd = Adapter "AMD Radeon RX 7900 XTX" "PCI\VEN_1002&DEV_744C" 0
+$basic = Adapter "Microsoft Basic Display Adapter" "ROOT\BASICDISPLAY" 0
+# "Intel" in katakana, by code point so the file stays ASCII.
+$jp = -join [char[]](0x30A4, 0x30F3, 0x30C6, 0x30EB)
+
+# Names are the trap: only the vendor ID and a healthy status count.
+foreach ($case in @(
+ @{ N = "nothing on the bus"; A = @(); P = $false },
+ @{ N = "a healthy NVIDIA adapter"; A = @(Adapter "NVIDIA GeForce RTX 4090" "PCI\VEN_10DE&DEV_2684&SUBSYS_00000000" 0); P = $true },
+ @{ N = "an AMD-only machine"; A = @($amd); P = $false },
+ @{ N = "an Intel-only machine"; A = @(Adapter "Intel Arc A770" "PCI\VEN_8086&DEV_56A0" 0); P = $false },
+ @{ N = "a hybrid AMD and Intel machine"; A = @((Adapter "Intel UHD Graphics" "PCI\VEN_8086&DEV_9A60" 0), (Adapter "AMD Radeon 780M" "PCI\VEN_1002&DEV_15BF" 0)); P = $false },
+ @{ N = "a virtual adapter"; A = @($basic); P = $false },
+ @{ N = "a non-NVIDIA card whose NAME says NVIDIA"; A = @(Adapter "NVIDIA compatible display" "PCI\VEN_1002&DEV_744C" 0); P = $false },
+ @{ N = "an NVIDIA card with an unrecognisable name"; A = @(Adapter "Carte graphique" "PCI\VEN_10DE&DEV_2684" 0); P = $true },
+ @{ N = "a disabled adapter (code 22)"; A = @(NvAdapter 22); P = $false },
+ @{ N = "a device-problem adapter (code 43)"; A = @(NvAdapter 43); P = $false },
+ @{ N = "a driver record with no status"; A = @(NvAdapter $null); P = $false },
+ @{ N = "a healthy card after a faulted one"; A = @((Adapter "NVIDIA GeForce GTX 1060" "PCI\VEN_10DE&DEV_1C03" 43), $nv); P = $true },
+ @{ N = "a lower-case vendor ID"; A = @(Adapter "NVIDIA GeForce RTX 4090" "pci\ven_10de&dev_2684" 0); P = $true },
+ @{ N = "a lookalike vendor ID"; A = @(Adapter "Some Card" "PCI\VEN_110D&DEV_E10D" 0); P = $false }
+)) {
+ $script:FakeAdapters = $case.A
+ Check "NVIDIA presence on $($case.N) is $($case.P)" ((Test-NvidiaAdapterPresent) -eq $case.P)
+}
+
+foreach ($case in @(
+ @{ N = "a healthy AMD adapter"; A = @($amd); Want = $true },
+ @{ N = "a healthy Intel adapter"; A = @(Adapter "Intel Arc A770" "PCI\VEN_8086&DEV_56A0" 0); Want = $true },
+ # The AMD route keeps faulted, parked and PNP-less Radeons, so each must veto the promotion.
+ @{ N = "a faulted AMD adapter"; A = @(Adapter "AMD Radeon RX 7900 XTX" "PCI\VEN_1002&DEV_744C" 43); Want = $true },
+ @{ N = "a parked AMD adapter"; A = @(Adapter "AMD Radeon RX 7900 XTX" "PCI\VEN_1002&DEV_744C" 45); Want = $true },
+ @{ N = "an AMD adapter with no PNP ID"; A = @(Adapter "AMD Radeon RX 7900 XTX" "" 0); Want = $true },
+ @{ N = "a faulted Intel UHD adapter"; A = @(Adapter "Intel(R) UHD Graphics 770" "PCI\VEN_8086&DEV_4680" 43); Want = $false },
+ @{ N = "an NVIDIA adapter only"; A = @($nv); Want = $false },
+ @{ N = "a virtual adapter only"; A = @($basic); Want = $false }
+)) {
+ $script:FakeAdapters = $case.A
+ Check "other-vendor gate sees $($case.N) as $($case.Want)" ((Test-OtherVendorAdapterPresent) -eq $case.Want)
+}
+
+# AMD evidence outside WMI: the AMD route queries HIP (or an override / opted-in amd-smi) even when WMI omits the card.
+$hipRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("hip-" + [guid]::NewGuid().ToString("N"))
+New-Item -ItemType Directory -Force -Path (Join-Path $hipRoot "bin") | Out-Null
+Set-Content -LiteralPath (Join-Path $hipRoot "bin\hipinfo.exe") -Value ""
+$savedAmdEnv = @{}
+foreach ($v in @("UNSLOTH_ROCM_GFX_ARCH", "_UNSLOTH_ROCM_GFX_ARCH_HANDOFF", "HIP_PATH", "HIP_PATH_57", "ROCM_PATH", "UNSLOTH_ENABLE_AMD_SMI")) {
+ $savedAmdEnv[$v] = [Environment]::GetEnvironmentVariable($v)
+ [Environment]::SetEnvironmentVariable($v, $null)
+}
+$script:FakeCommands = @()
+function Get-Command { param([string]$Name, $CommandType, $ErrorAction) if ($script:FakeCommands -contains $Name) { [pscustomobject]@{ Source = $Name } } }
+$script:FakeAdapters = @($nv)
+try {
+ Check "no AMD evidence anywhere leaves the gate open" ((Test-OtherVendorAdapterPresent) -eq $false)
+ foreach ($case in @(
+ @{ N = "an UNSLOTH_ROCM_GFX_ARCH override"; Env = @{ UNSLOTH_ROCM_GFX_ARCH = "gfx1100" } },
+ @{ N = "an arch the installer forwarded"; Env = @{ _UNSLOTH_ROCM_GFX_ARCH_HANDOFF = "gfx1100" } },
+ @{ N = "hipinfo on PATH"; Cmd = @("hipinfo") },
+ @{ N = "a HIP SDK under HIP_PATH"; Env = @{ HIP_PATH = $hipRoot } },
+ @{ N = "a HIP SDK under ROCM_PATH"; Env = @{ ROCM_PATH = $hipRoot } },
+ @{ N = "an opted-in amd-smi"; Env = @{ UNSLOTH_ENABLE_AMD_SMI = "1" }; Cmd = @("amd-smi") }
+ )) {
+ if ($case.Env) { foreach ($k in @($case.Env.Keys)) { [Environment]::SetEnvironmentVariable($k, $case.Env[$k]) } }
+ $script:FakeCommands = @($case.Cmd)
+ Check "WMI without the AMD card: $($case.N) vetoes the promotion" ((Test-OtherVendorAdapterPresent) -eq $true)
+ if ($case.Env) { foreach ($k in @($case.Env.Keys)) { [Environment]::SetEnvironmentVariable($k, $null) } }
+ $script:FakeCommands = @()
+ }
+ $script:FakeCommands = @("amd-smi")
+ Check "amd-smi without the opt-in does not veto (the AMD route would not run it)" ((Test-OtherVendorAdapterPresent) -eq $false)
+} finally {
+ Remove-Item Function:\Get-Command -ErrorAction SilentlyContinue
+ foreach ($v in $savedAmdEnv.Keys) { [Environment]::SetEnvironmentVariable($v, $savedAmdEnv[$v]) }
+ Remove-Item -LiteralPath $hipRoot -Recurse -Force -ErrorAction SilentlyContinue
+}
+
+# NVIDIA plus one other adapter. UHD / Iris get no XPU wheels, so they must not block; a localized Arc is
+# reconciled through the registry names (R), as the Intel route does.
+$i4680 = "PCI\VEN_8086&DEV_4680"; $i56a0 = "PCI\VEN_8086&DEV_56A0"
+foreach ($case in @(
+ @{ N = "AMD Radeon 780M"; W = "AMD Radeon 780M"; Id = "PCI\VEN_1002&DEV_15BF"; Blocks = $true },
+ @{ N = "an integrated AMD Radeon(TM) Graphics"; W = "AMD Radeon(TM) Graphics"; Id = "PCI\VEN_1002&DEV_15BF"; Blocks = $true },
+ @{ N = "Intel UHD Graphics"; W = "Intel(R) UHD Graphics 770"; Id = $i4680; Blocks = $false },
+ @{ N = "Intel Iris Xe"; W = "Intel(R) Iris(R) Xe Graphics"; Id = $i4680; Blocks = $false },
+ @{ N = "Intel HD Graphics"; W = "Intel(R) HD Graphics 630"; Id = $i4680; Blocks = $false },
+ @{ N = "Intel Arc A770"; W = "Intel(R) Arc(TM) A770 Graphics"; Id = $i4680; Blocks = $true },
+ @{ N = "Intel Arc B580"; W = "Intel(R) Arc(TM) B580 Graphics"; Id = $i4680; Blocks = $true },
+ @{ N = "Intel Data Center GPU"; W = "Intel(R) Data Center GPU Max 1100"; Id = $i4680; Blocks = $true },
+ @{ N = "a nameless Intel adapter"; W = ""; Id = $i4680; Blocks = $false },
+ @{ N = "a Japanese Arc reconciled by the registry"; W = "$jp(R) Arc(TM) A770 Graphics"; Id = $i56a0;
+ R = @("Intel $jp(R) Arc(TM) A770 Graphics"); Blocks = $true },
+ @{ N = "an OEM-branded Arc reconciled by the registry"; W = "OEM Graphics A750"; Id = $i56a0;
+ R = @("Intel(R) UHD Graphics 770", "Intel OEM Graphics A750 (Arc)"); Blocks = $true },
+ @{ N = "a localized UHD whose registry entry is also UHD"; W = "$jp(R) UHD Graphics 770"; Id = $i56a0;
+ R = @("Intel $jp(R) UHD Graphics 770"); Blocks = $false },
+ @{ N = "a UHD next to a stale Arc key it does not name"; W = "Intel(R) UHD Graphics 770"; Id = $i56a0;
+ R = @("Intel(R) UHD Graphics 770", "Intel(R) Arc(TM) A770 Graphics"); Blocks = $false },
+ @{ N = "a localized Arc with no registry entry"; W = "$jp(R) Arc(TM) A770 Graphics"; Id = $i56a0; Blocks = $false },
+ @{ N = "a localized Arc and an unreadable registry (no throw)"; W = "$jp(R) Arc(TM) A770 Graphics"; Id = $i56a0;
+ R = @("Intel $jp(R) Arc(TM) A770 Graphics"); Throws = $true; Blocks = $false }
+)) {
+ $script:FakeRegistryNames = if ($case.R) { $case.R } else { @() }
+ $script:FakeRegistryThrows = [bool]$case.Throws
+ $script:FakeAdapters = @($nv, (Adapter $case.W $case.Id 0))
+ Check "NVIDIA plus $($case.N): the gate $(if ($case.Blocks) { 'blocks' } else { 'allows' }) promotion" (
+ (Test-OtherVendorAdapterPresent) -eq $case.Blocks)
+ Check " and NVIDIA presence is unaffected either way" ((Test-NvidiaAdapterPresent) -eq $true)
+}
+$script:FakeRegistryThrows = $false; $script:FakeRegistryNames = @()
+
+CheckText "the gate defers to the shared XPU-capable pattern" (Get-FunctionText $installPs1 "Test-OtherVendorAdapterPresent") 'Get-XpuCapableNameRegex'
+# @() around the WHOLE pipeline: one unique string would make [0] its first character.
+$patternDefs = @(@([regex]::Matches($installText, 'function Get-XpuCapableNameRegex \{ return "([^"]+)" \}') |
+ ForEach-Object { $_.Groups[1].Value }) | Sort-Object -Unique)
+$routeDefs = @(@([regex]::Matches($installText, '\$_xpuNameRe = "([^"]+)"') |
+ ForEach-Object { $_.Groups[1].Value }) | Sort-Object -Unique)
+Check "the extracted patterns are whole strings, not characters" ($patternDefs[0].Length -gt 5 -and $routeDefs[0].Length -gt 5)
+Check "both patterns are defined exactly once" ($patternDefs.Count -eq 1 -and $routeDefs.Count -eq 1)
+Check "the gate pattern and the XPU route pattern are identical" ($patternDefs[0] -ceq $routeDefs[0])
+
+foreach ($case in @(
+ @{ V = "32.0.15.6094"; Want = "12.6" }, # 560.94
+ @{ V = "32.0.15.7020"; Want = "12.8" }, # 570.20
+ @{ V = "32.0.15.8000"; Want = "13.0" }, # 580.00
+ @{ V = "31.0.15.5222"; Want = "12.4" }, # 552.22 -> 550 floor
+ @{ V = "31.0.15.3667"; Want = "12.2" }, # 536.67 -> 535 floor
+ @{ V = "30.0.14.4568"; Want = "" }, # 445.68 is BELOW 450: no floor
+ @{ V = "570.20"; Want = "12.8" }, # already NVIDIA-shaped, as nvidia-smi reports
+ @{ V = ""; Want = "" },
+ @{ V = "not a version"; Want = "" },
+ @{ V = "junk"; Want = "" }
+)) {
+ Check "driver $($case.V) floors at '$($case.Want)'" ((@(Get-NvidiaDriverCudaFloor -DriverVersion $case.V) -join '.') -eq $case.Want)
+}
+foreach ($case in @(
+ @{ V = "32.0.15.6094"; R = 560; N = "a Windows display-driver version" },
+ @{ V = "30.0.14.4568"; R = 445; N = "a pre-R450 Windows version" },
+ @{ V = "580.65.06"; R = 580; N = "an nvidia-smi style version" },
+ @{ V = "445.68"; R = 445; N = "a pre-R450 nvidia-smi style version" },
+ @{ V = ""; R = $null; N = "an empty version" },
+ @{ V = "not a version"; R = $null; N = "an unparseable version" },
+ @{ V = "junk"; R = $null; N = "another unparseable version" },
+ @{ V = "1.2.3"; R = $null; N = "a three-field version" },
+ @{ V = "99.1"; R = $null; N = "a two-digit release" },
+ @{ V = "100.1"; R = 100; N = "the lowest release shape NVIDIA actually ships" },
+ # Microsoft Basic Display versions are not NVIDIA releases.
+ @{ V = "10.0.19041.3636"; R = $null; N = "a Microsoft Basic Display driver version" },
+ @{ V = "10.0.22621.1"; R = $null; N = "a Windows 11 Basic Display driver version" },
+ @{ V = "10.0.19041.1"; R = $null; N = "a Windows 10 Basic Display driver version" },
+ @{ V = "31.0.15.3623"; R = 536; N = "a WDDM 3.1 NVIDIA version" },
+ @{ V = "26.21.14.4250"; R = 442; N = "a WDDM 2.6 NVIDIA version" },
+ @{ V = "21.21.13.7892"; R = 378; N = "a WDDM 2.1 NVIDIA version" }
+)) {
+ Check "$($case.N) reads as release $($case.R)" ((Get-NvidiaDriverRelease -DriverVersion $case.V) -eq $case.R)
+}
+foreach ($case in @(
+ @{ N = "a healthy NVIDIA adapter"; A = (NvAdapter 0 "32.0.15.7020"); Want = "12.8" },
+ @{ N = "an AMD adapter"; A = (Adapter "AMD Radeon" "PCI\VEN_1002&DEV_744C" 0 "32.0.15.7020"); Want = "" },
+ @{ N = "a faulted NVIDIA adapter"; A = (NvAdapter 43 "32.0.15.7020"); Want = "" }
+)) {
+ $script:FakeAdapters = @($case.A)
+ Check "the CUDA floor read from $($case.N) is '$($case.Want)'" ((@(Get-NvidiaAdapterCudaFloor) -join '.') -eq $case.Want)
+}
+
+# Generated from studio/nvidia_probe.py so the tables cannot drift.
+$probeText = [System.IO.File]::ReadAllText((Join-Path $root "studio/nvidia_probe.py"))
+$tableMatch = [regex]::Match($probeText, '(?s)_DRIVER_MAJOR_CUDA\s*=\s*\((.*?)\)\s*\n\s*\n')
+Check "the python floor table was found" ($tableMatch.Success)
+$pyRows = @([regex]::Matches($tableMatch.Groups[1].Value, '\((\d+),\s*\((\d+),\s*(\d+)\)\)') |
+ ForEach-Object { "$($_.Groups[1].Value):$($_.Groups[2].Value).$($_.Groups[3].Value)" })
+Check "the python table has rows to compare (bites)" ($pyRows.Count -ge 5)
+# Get-NvidiaDriverCudaFloor no longer holds the table; reading it would pass on an empty list.
+$psRows = @([regex]::Matches((Get-FunctionText $setupPs1 "Get-NvidiaCudaFloorForRelease"), '@\((\d+),\s*(\d+),\s*(\d+)\)') |
+ ForEach-Object { "$($_.Groups[1].Value):$($_.Groups[2].Value).$($_.Groups[3].Value)" })
+Check "the PowerShell floor table matches nvidia_probe.py exactly" (($pyRows -join ",") -eq ($psRows -join ","))
+
+foreach ($file in @($installPs1, $setupPs1)) {
+ $text = $texts[$file]
+ $name = Split-Path $file -Leaf
+ $library = $text.IndexOf('if (-not $HasNvidiaSmi -and (Get-NvidiaLibraryInventory))')
+ $presence = $text.IndexOf('Test-NvidiaAdapterPresent -Scan $presenceScan')
+ $promoAt = $text.IndexOf('$presenceScan = Invoke-BoundedVideoControllerScan')
+ $busAt = $text.IndexOf('if (-not $HasNvidiaSmi) {', $library)
+ Check "$name promotes on the driver library before falling back to the bus" (
+ $library -gt 0 -and $presence -gt 0 -and $library -lt $presence)
+ Check "$name only reaches the bus when nothing else answered" ($busAt -gt 0 -and $busAt -lt $presence)
+ CheckText "$name gates the promotion on no other vendor being present" $text '-not \(Test-OtherVendorAdapterPresent -Scan \$presenceScan\)'
+ # PowerShell does not hoist, and the pwsh suites define functions in dependency order themselves.
+ foreach ($fn in $shared) {
+ $def = $text.IndexOf("function $fn")
+ Check "$name defines $fn before the promotion that uses it" ($def -gt 0 -and $def -lt $presence)
+ }
+ $scanDef = $text.IndexOf("function Invoke-BoundedVideoControllerScan")
+ $scanCalls = 0
+ foreach ($m in [regex]::Matches($text, '(?<!function )Invoke-BoundedVideoControllerScan')) {
+ $lineStart = $text.LastIndexOf("`n", [Math]::Max($m.Index - 1, 0)) + 1
+ if ($text.Substring($lineStart, $m.Index - $lineStart).Contains("#")) { continue }
+ $scanCalls++
+ Check "$name calls Invoke-BoundedVideoControllerScan at offset $($m.Index) after its definition" ($m.Index -gt $scanDef)
+ }
+ Check "$name has real calls to the bounded scan to order (bites)" ($scanCalls -gt 0)
+ # Release rows below set the release directly, so check the promotion site records it.
+ CheckText "$name records the driver release at the promotion site" $text '\$_presenceRelease = Get-NvidiaAdapterDriverRelease -Scan \$presenceScan[\s\S]{0,800}?\$script:NvidiaPresenceDriverRelease = \$_presenceRelease'
+ CheckText "$name records it beside the floor, from the same scan" $text 'Get-NvidiaAdapterCudaFloor -Scan \$presenceScan[\s\S]{0,400}?Get-NvidiaAdapterDriverRelease -Scan \$presenceScan'
+ CheckText "$name initialises the release to null" $text '\$script:NvidiaPresenceDriverRelease = \$null'
+ CheckText "$name never reads presence from the class keys" (Get-FunctionText $file "Test-NvidiaAdapterPresent") @() 'Get-NvidiaRegistryAdapter|Control\\Class'
+ $gate = Get-FunctionText $file "Test-OtherVendorAdapterPresent"
+ CheckText "$name gates the other-vendor fallback on a failed scan too" $gate 'if \(\$Scan\.Ok\) \{ return \$false \}'
+ CheckText "$name asks the shared XPU pattern of the Intel route's registry names" $gate 'Get-IntelRegistryAdapterNames \| Where-Object \{ "\$_" -match \(Get-XpuCapableNameRegex\)'
+ $reset = $text.IndexOf('$script:VideoControllerScanResult = $null')
+ Check "$name resets the cached scan before the promotion takes it" ($reset -gt 0 -and $reset -lt $promoAt)
+ Check "$name's Intel route still goes through the (now shared) scan" (
+ $text.IndexOf('$_gpuScan = Invoke-BoundedVideoControllerScan', $promoAt) -gt $promoAt)
+ $def = $text.IndexOf("function Get-IntelRegistryAdapterNames")
+ Check "$name defines Get-IntelRegistryAdapterNames before the promotion that now needs it" ($def -gt 0 -and $def -lt $promoAt)
+ Check "$name defines it exactly once" (([regex]::Matches($text, 'function Get-IntelRegistryAdapterNames')).Count -eq 1)
+ $promo = $text.Substring($promoAt)
+ $promo = $promo.Substring(0, $promo.IndexOf('NvidiaPresenceOnly = $true'))
+ CheckText "$name declines the promotion where PyTorch has proven XPU" $promo 'Test-IntelXpuRuntimeProven -Scan \$presenceScan'
+ if ($file -eq $installPs1) { CheckText "install.ps1 declines it on a preserved XPU verdict too" $promo '-not \$script:StudioPreservedXpuVerdict' }
+}
+
+# setup.ps1 must NOT guess: "" keys the do-not-wipe escape (#9255); install.ps1 is where floor and release are consumed.
+$setupTag = Get-FunctionText $setupPs1 "Get-PytorchCudaTag"
+$installIdx = Get-FunctionText $installPs1 "Get-TorchIndexUrl"
+CheckText "setup.ps1 still returns empty for unknown rather than flooring" $setupTag @() 'NvidiaPresenceCudaFloor'
+CheckText "setup.ps1's tag helper does not act on the release either" $setupTag @() 'NvidiaPresenceDriverRelease'
+CheckText "install.ps1 is where the floor and the release are consumed" $installIdx @('NvidiaPresenceCudaFloor', 'NvidiaPresenceDriverRelease')
+CheckText "install.ps1 answers pre-R450 the same way (CPU)" $installIdx '(?s)NvidiaPresenceDriverRelease -lt 450[\s\S]{0,1200}?/cpu'
+CheckText "install.ps1 has no rejection latch to set (bites)" $installText @() 'NvidiaSmiRejected'
+
+$busBlock = [regex]::Match($setupText, '(?s)if \(-not \$HasNvidiaSmi\) \{\s*\$presenceScan = Invoke-BoundedVideoControllerScan.*?\n\}').Value
+CheckText "setup.ps1's bus promotion marks nvidia-smi rejected" $busBlock '\$script:NvidiaSmiRejected = \$true'
+CheckText "and still records presence-only separately" $busBlock '\$script:NvidiaPresenceOnly = \$true'
+CheckText "the driver-library promotion already did, which is the precedent" $setupText '(?s)Get-NvidiaLibraryInventory\)\) \{[\s\S]{0,600}?\$script:NvidiaSmiRejected = \$true'
+
+# Anchored on ORDER: an arm after the cu126 fallback is dead code.
+$arm = [regex]::Match($setupText, '(?s)\} elseif \(\$HasNvidiaSmi\) \{.*?\n\} elseif \(\$script:IsIntelXpu\)').Value
+CheckText "setup.ps1 routes a pre-R450 presence-only host to CPU" $arm @('\$script:NvidiaPresenceDriverRelease -lt 450', '(?s)-lt 450\)? \{[^}]*\$CuTag = "cpu"')
+$preR450 = $arm.IndexOf('NvidiaPresenceDriverRelease'); $cu126 = $arm.IndexOf('"cu126"')
+Check "and it decides before the cu126 fallback rather than after it" ($preR450 -ge 0 -and $cu126 -ge 0 -and $preR450 -lt $cu126)
+CheckText "and says why, rather than silently installing CPU wheels" $arm 'predates R450'
+CheckText "and marks the demotion so the CPU arm really replaces the CUDA wheel" $arm '(?s)-lt 450\)? \{[^}]*NvidiaPreR450CpuFallback = \$true'
+CheckText "and only when a CUDA wheel is actually installed" $arm 'Test-CudaFamilyLeaf \$installedTorchTag\) \{ \$script:NvidiaPreR450CpuFallback = \$true \}'
+CheckText "setup.ps1 selects from the recorded floor" $arm '\$script:NvidiaPresenceCudaFloor'
+CheckText "and only when no CUDA family is already installed" $arm '-not \(Test-CudaFamilyLeaf \$installedTorchTag\)[\s\S]{0,80}?NvidiaPresenceCudaFloor'
+CheckText "through the shared ladder rather than by formatting the digits" $arm 'Get-CudaFamilyForVersion -Major \$floorMajor' 'cu\$floorMajor'
+CheckText "and applies the same pre-Turing cap" $arm '\$floorMajor -gt 12 -or \(\$floorMajor -eq 12 -and \$floorMinor -gt 6\)'
+Check "and the pre-R450 arm still decides first" ($preR450 -ge 0 -and $preR450 -lt $arm.IndexOf('NvidiaPresenceCudaFloor'))
+CheckText "the flag starts false on every run" $setupText '(?m)^\$script:NvidiaPreR450CpuFallback = \$false$'
+
+$escapes = Get-FunctionText $setupPs1 "Invoke-FastPathEscapes"
+CheckText "a bus-only NVIDIA host with CPU torch forces the dependency pass" $escapes @('\$script:NvidiaPresenceOnly', '(?s)NvidiaPresenceOnly[^}]*\$SkipPythonDeps = \$false')
+CheckText "and only when the installed wheel is a CPU one" $escapes '\$installedTorchTag -eq "cpu"'
+CheckText "a pre-R450 driver does not trigger it" $escapes @('\$_nvidiaPreR450', 'NvidiaPresenceDriverRelease -lt 450')
+CheckText "nor does a pin that sends this host somewhere else" $escapes @('\$_nvidiaIsReachable', 'Test-CudaFamilyLeaf \$_pinLeafNow')
+$cudaArm = [regex]::Match($setupText, '(?s)substep "installing PyTorch with CUDA support.{0,1500}').Value
+CheckText "the CUDA arm replaces an installed CPU wheel on a bus-only host" $cudaArm '(?s)\$script:NvidiaPresenceOnly -and \$installedTorchTag -eq "cpu"[^}]*--force-reinstall'
+CheckText "the CUDA arm forces the reinstall off a stale +rocm/+xpu wheel" $cudaArm '(?s)if \(Test-NvidiaPresenceStaleGpuWheel [^{]*\) \{\s*\$cudaForce = @\("--force-reinstall"\)'
+$cpuArm = [regex]::Match($setupText, '(?s)substep "installing PyTorch \(CPU-only\)\.\.\.".{0,3000}').Value
+CheckText "the CPU arm force-reinstalls after a pre-R450 demotion" $cpuArm 'if \(\$script:NvidiaPreR450CpuFallback\) \{ \$cpuForce = @\("--force-reinstall"\) \}'
+CheckText "the same way it does after the ROCm and XPU fallbacks (bites)" $cpuArm 'if \(\$ROCmCpuFallback\) \{ \$cpuForce = @\("--force-reinstall"\) \}'
+$preArm = [regex]::Match($setupText, '(?s)NvidiaPresenceDriverRelease -lt 450\) \{.{0,2500}?predates R450').Value
+CheckText "a pre-R450 demotion replaces a stale +rocm/+xpu wheel too" $preArm '(?s)if \(Test-NvidiaPresenceStaleGpuWheel [^{]*\) \{\s*\$script:NvidiaPreR450CpuFallback = \$true'
+CheckText "the cached answer starts empty on every run" $setupText '(?m)^\$script:NvidiaPresenceStaleGpuWheel = \$null$'
+
+$staleHelper = Get-FunctionText $setupPs1 "Test-NvidiaPresenceStaleGpuWheel"
+$escAst = [System.Management.Automation.Language.Parser]::ParseInput($escapes, [ref]$null, [ref]$null)
+$staleEscape = @($escAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.IfStatementAst] -and
+ $n.Clauses[0].Item1.Extent.Text -match 'Test-NvidiaPresenceStaleGpuWheel' }, $true))[0]
+Check "the fast-path escape asks Test-NvidiaPresenceStaleGpuWheel (bites)" ($null -ne $staleEscape)
+if ($staleEscape) {
+ foreach ($case in @(
+ # tag, presence-only, probe answer ($null = no answer), pre-R450, want stale, want skip afterwards
+ @{ T = "rocm"; P = $true; A = "DEV=False"; R = $false; Stale = $true; Skip = $false; N = "+rocm that sees no GPU" },
+ @{ T = "xpu"; P = $true; A = "DEV=False"; R = $false; Stale = $true; Skip = $false; N = "+xpu that sees no GPU" },
+ @{ T = "rocm"; P = $true; A = "DEV=False"; R = $true; Stale = $true; Skip = $false; N = "+rocm on a pre-R450 driver (goes to CPU)" },
+ @{ T = "xpu"; P = $true; A = "DEV=True"; R = $false; Stale = $false; Skip = $true; N = "+xpu that still sees its GPU (kept, as the base did)" },
+ @{ T = "rocm"; P = $true; A = "DEV=True"; R = $false; Stale = $false; Skip = $true; N = "+rocm that still sees a GPU" },
+ @{ T = "rocm"; P = $true; A = $null; R = $false; Stale = $false; Skip = $true; N = "+rocm whose probe did not answer" },
+ @{ T = "cu128"; P = $true; A = "DEV=False"; R = $false; Stale = $false; Skip = $true; N = "a CUDA wheel" },
+ @{ T = "cpu"; P = $true; A = "DEV=False"; R = $true; Stale = $false; Skip = $true; N = "a CPU wheel on pre-R450 (this escape)" },
+ @{ T = "rocm"; P = $false; A = "DEV=False"; R = $false; Stale = $false; Skip = $true; N = "+rocm on a host with no bus promotion" })) {
+ $script:ProbeAnswer = if ($null -eq $case.A) { @{ Ok = $false; Output = ""; TimedOut = $true } }
+ else { @{ Ok = $true; Output = "$($case.A)`n"; TimedOut = $false } }
+ $got = & {
+ param($c)
+ $script:NvidiaPresenceOnly = $c.P; $script:NvidiaPresenceStaleGpuWheel = $null; $script:ProbeCalls = 0
+ function substep { param($a, $b) }
+ . ([scriptblock]::Create($staleHelper))
+ $VenvDir = "venv"; $installedTorchTag = $c.T
+ $_nvidiaIsReachable = $true; $_nvidiaPreR450 = $c.R; $SkipPythonDeps = $true
+ . ([scriptblock]::Create($staleEscape.Extent.Text))
+ $again = Test-NvidiaPresenceStaleGpuWheel -InstalledTag $c.T -PythonExe "C:\venv\Scripts\python.exe"
+ [pscustomobject]@{ Skip = $SkipPythonDeps; Stale = $again; Calls = $script:ProbeCalls }
+ } $case
+ Check "bus-only escape, $($case.N): dependency pass = $(-not $case.Skip)" ($got.Skip -eq $case.Skip)
+ Check "bus-only helper, $($case.N): stale = $($case.Stale), probed at most once" ($got.Stale -eq $case.Stale -and $got.Calls -le 1)
+ }
+ $script:NvidiaPresenceOnly = $false; $script:NvidiaPresenceStaleGpuWheel = $null
+}
+
+$ladderFn = Get-FunctionText $setupPs1 "Get-CudaFamilyForVersion"
+Check "setup.ps1 names the ladder once (bites)" ($ladderFn.Length -gt 50)
+$installLadder = [regex]::Matches($installIdx, '(?m)^\s*(?:if|elseif)[^\r\n]*\$family = "cu\d+"[^\r\n]*$')
+Check "install.ps1's inline ladder was found (bites)" ($installLadder.Count -ge 5)
+$conds = { param($rows) @($rows | ForEach-Object {
+ $m = [regex]::Match($_.Value, '\((?<c>[^)]*(?:\([^)]*\)[^)]*)*)\)\s*\{')
+ if ($m.Success) { ((($m.Groups['c'].Value -replace '(?i)\$Major', '$major') -replace '(?i)\$Minor', '$minor') -replace '\s+', ' ').Trim() }
+}) }
+$setupConds = & $conds ([regex]::Matches($ladderFn, '(?m)^\s*(?:if|elseif|return)[^\r\n]*cu\d+[^\r\n]*$'))
+$installConds = & $conds $installLadder
+Check "both ladders have the same number of rungs" ($setupConds.Count -eq $installConds.Count)
+Check "and the rungs test the same conditions in the same order" (($setupConds -join '|') -eq ($installConds -join '|'))
+Invoke-Expression $ladderFn
+foreach ($row in @(@(10, 2, "cpu"), @(11, 0, "cu118"), @(11, 8, "cu118"), @(12, 0, "cu124"), @(12, 5, "cu124"),
+ @(12, 6, "cu126"), @(12, 7, "cu126"), @(12, 8, "cu128"), @(12, 9, "cu128"), @(13, 0, "cu130"))) {
+ Check "CUDA $($row[0]).$($row[1]) is served by $($row[2])" ((Get-CudaFamilyForVersion -Major $row[0] -Minor $row[1]) -eq $row[2])
+}
+
+# Presence never comes from the class keys; a failed scan may only borrow a unanimous driver release from them.
+$nvKey = @{ MatchingDeviceId = "PCI\\VEN_10DE&DEV_1DB1" }
+$nv536 = @{ MatchingDeviceId = "PCI\\VEN_10DE&DEV_1DB1"; DriverVersion = "31.0.15.3699" } # R536: floor 12.2
+foreach ($case in @(
+ # A = answered scan with these adapters; no A = a scan that could not answer.
+ @{ N = "a failed scan with an NVIDIA class key"; K = @($nvKey); P = $false; Reg = $false },
+ @{ N = "a scan that answered with no adapters at all"; K = @($nvKey); A = @(); P = $false; Reg = $false },
+ @{ N = "a scan that answered with an AMD adapter only"; K = @($nvKey); A = @($amd); P = $false; Reg = $false },
+ @{ N = "a scan that answered with a faulted NVIDIA adapter"; K = @($nvKey); A = @(NvAdapter 43); P = $false; Reg = $false },
+ @{ N = "a scan that answered with a disabled NVIDIA adapter"; K = @($nvKey); A = @(NvAdapter 22); P = $false; Reg = $false },
+ @{ N = "a healthy NVIDIA adapter from WMI alone"; K = @($nvKey); A = @($nv); P = $true; Reg = $false },
+ @{ N = "a failed scan with only an AMD class key"; K = @(@{ MatchingDeviceId = "PCI\\VEN_1002&DEV_744C" }); P = $false },
+ @{ N = "a failed scan with a versioned NVIDIA key"; K = @($nv536); P = $false; Rel = 536; Floor = "12.2" },
+ @{ N = "an unversioned then a versioned NVIDIA key"; K = @($nvKey, $nv536); P = $false; Rel = 536 },
+ @{ N = "two NVIDIA keys naming different releases"; K = @($nv536, @{ MatchingDeviceId = "PCI\\VEN_10DE&DEV_1DB1"; DriverVersion = "30.0.14.4568" });
+ P = $false; Rel = $null; Floor = "" },
+ @{ N = "two spellings of one release"; K = @($nv536, @{ MatchingDeviceId = "PCI\\VEN_10DE&DEV_1DB1"; DriverVersion = "536.99" }); Rel = 536 },
+ @{ N = "two NVIDIA keys with no version"; K = @($nvKey, $nvKey); P = $false; Rel = $null },
+ @{ N = "one NVIDIA key with no version"; K = @($nvKey); Rel = $null; Floor = "" },
+ @{ N = "a scan that answered, beside a versioned key"; K = @($nv536); A = @(); Rel = $null; Reg = $false }
+)) {
+ $script:RegKeys = $case.K
+ $script:FakeAdapters = if ($case.ContainsKey('A')) { $case.A } else { @() }
+ $script:FakeScanOk = $case.ContainsKey('A')
+ $script:RegistryConsulted = $false
+ if ($case.ContainsKey('P')) { Check "registry: $($case.N) is presence = $($case.P)" ((Test-NvidiaAdapterPresent) -eq $case.P) }
+ if ($case.ContainsKey('Rel')) { Check "registry: $($case.N) reads release '$($case.Rel)'" ("$(Get-NvidiaAdapterDriverRelease)" -eq "$($case.Rel)") }
+ if ($case.ContainsKey('Floor')) { Check "registry: $($case.N) floors at '$($case.Floor)'" ((@(Get-NvidiaAdapterCudaFloor) -join '.') -eq $case.Floor) }
+ if ($case.ContainsKey('Reg')) { Check "registry: $($case.N) consulted the registry = $($case.Reg)" ($script:RegistryConsulted -eq $case.Reg) }
+}
+
+# The real helper, so the fallback reads the class keys through the Intel route's normalization.
+$registryNamesStub = ${function:Get-IntelRegistryAdapterNames}
+Invoke-Expression (Get-FunctionText $setupPs1 "Get-IntelRegistryAdapterNames")
+foreach ($case in @(
+ @{ N = "an Arc named without the vendor"; Id = "PCI\\VEN_8086&DEV_56A0"; Desc = "Arc A770 Graphics"; Want = $true },
+ @{ N = "an Arc in the class keys"; Id = "PCI\\VEN_8086&DEV_56A0"; Desc = "Intel(R) Arc(TM) A770 Graphics"; Want = $true },
+ @{ N = "a Data Center GPU"; Id = "PCI\\VEN_8086&DEV_0BD5"; Desc = "Intel(R) Data Center GPU Max 1100"; Want = $true },
+ @{ N = "integrated Intel UHD"; Id = "PCI\\VEN_8086&DEV_9A49"; Desc = "Intel(R) UHD Graphics"; Want = $false },
+ @{ N = "an AMD adapter of any kind"; Id = "PCI\\VEN_1002&DEV_744C"; Desc = "AMD Radeon RX 7900 XTX"; Want = $true },
+ @{ N = "an NVIDIA adapter, which is not an alternative"; Id = "PCI\\VEN_10DE&DEV_1DB1"; Desc = "NVIDIA Tesla V100"; Want = $false }
+)) {
+ $script:RegKeys = @(@{ MatchingDeviceId = $case.Id; DriverDesc = $case.Desc })
+ $script:FakeAdapters = @(); $script:FakeScanOk = $false; $script:RegistryConsulted = $false
+ Check "registry fallback: $($case.N) reads as $(if ($case.Want) { 'an alternative' } else { 'no alternative' })" (
+ (Test-OtherVendorAdapterPresent) -eq $case.Want)
+ Check " and the registry really was the source" ($script:RegistryConsulted -eq $true)
+}
+${function:Get-IntelRegistryAdapterNames} = $registryNamesStub
+$script:RegKeys = @(@{ MatchingDeviceId = "PCI\\VEN_1002&DEV_744C"; DriverDesc = "AMD Radeon RX 7900 XTX" })
+$script:FakeAdapters = @($nv); $script:FakeScanOk = $true; $script:RegistryConsulted = $false
+Check "a scan that answered is not second-guessed by the registry" ((Test-OtherVendorAdapterPresent) -eq $false)
+Check "and the registry was never consulted" ($script:RegistryConsulted -eq $false)
+$script:RegKeys = @(); $script:FakeScanOk = $null
+
+# Runs the real Get-TorchIndexUrl: promoting without a version used to still yield a CPU index.
+# ParseInput on the UTF-8 text: 5.1's ParseFile reads a BOM-less file as ANSI, so its offsets would not index it.
+$idxAst = [System.Management.Automation.Language.Parser]::ParseInput($installText, $installPs1, [ref]$null, [ref]$null)
+foreach ($n in @("Get-TorchIndexUrl", "Trim-IndexPathSlashes", "Get-CudaFamilyCappedForPreTuring")) {
+ $f = @($idxAst.FindAll({ param($x) $x -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $x.Name -eq $n }, $true))
+ if ($f.Count -ge 1) { Invoke-Expression $f[0].Extent.Text }
+}
+function Get-NvidiaCu126Verdict { param($a, $b) return "" }
+function Get-NvidiaLibraryInventory { return $script:Inv }
+function Invoke-NvidiaSmiBounded { param($Exe, $Arguments) return $script:Banner }
+function substep { param($a, $b) $script:Said = "$a" }
+$libInv = [pscustomobject]@{ CudaMajor = 12; CudaMinor = 8; ComputeCaps = @() }
+foreach ($case in @(
+ # Must stay SILENT: every AMD, Intel and CPU-only host reaches this.
+ @{ N = "an AMD, Intel or CPU-only host"; Pres = $false; Want = "cpu"; Loud = $false },
+ # No compute capability, so unknown stops at cu126 (pre-Turing). Unknown is NOT too old.
+ @{ N = "presence-only with a 12.8 driver"; Pres = $true; Floor = @(12, 8); Want = "cu126"; Loud = $true },
+ @{ N = "presence-only with a 12.6 driver"; Pres = $true; Floor = @(12, 6); Want = "cu126"; Loud = $true },
+ @{ N = "presence-only with a 13.0 driver"; Pres = $true; Floor = @(13, 0); Want = "cu126"; Loud = $true },
+ @{ N = "presence-only with an 11.0 driver"; Pres = $true; Floor = @(11, 0); Want = "cu118"; Loud = $true },
+ @{ N = "presence-only with no or an unreadable driver version"; Pres = $true; Want = "cu126"; Loud = $true },
+ @{ N = "presence-only on a pre-R450 driver"; Pres = $true; Release = 445; Want = "cpu"; Loud = $true },
+ @{ N = "presence-only on R450 exactly"; Pres = $true; Floor = @(11, 0); Release = 450; Want = "cu118"; Loud = $true },
+ @{ N = "the capped R580 row, which explains the cap and names the override"; Pres = $true; Floor = @(13, 0); Release = 580;
+ Want = "cu126"; Loud = $true; Said = @('compute capability', 'UNSLOTH_TORCH_INDEX_FAMILY') },
+ @{ N = "an R580 11.0 floor (the cap lowers and never raises)"; Pres = $true; Floor = @(11, 0); Release = 580; Want = "cu118" },
+ @{ N = "unchanged: nvidia-smi with a readable banner"; Exe = "C:\it.exe"; Banner = "CUDA Version: 12.8"; Want = "cu128"; Loud = $false },
+ @{ N = "unchanged: nvidia-smi with an unreadable banner"; Exe = "C:\it.exe"; Banner = "broken"; Want = "cu126"; Loud = $true },
+ @{ N = "unchanged: the driver library answering"; Inv = $libInv; Want = "cu128"; Loud = $false },
+ @{ N = "an explicit family override over the bus floor"; Inv = $libInv; Pres = $true; Floor = @(13, 0); Env = "cu118"; Want = "cu118" }
+)) {
+ $NvidiaSmiExe = $case.Exe; $script:Inv = $case.Inv; $script:Banner = "$($case.Banner)"
+ $script:NvidiaPresenceOnly = [bool]$case.Pres
+ $script:NvidiaPresenceCudaFloor = $case.Floor
+ $script:NvidiaPresenceDriverRelease = $case.Release
+ $script:Said = ""
+ if ($case.Env) { $env:UNSLOTH_TORCH_INDEX_FAMILY = $case.Env }
+ try { $leaf = ("" + (Get-TorchIndexUrl)) -replace '^.*/', '' }
+ finally { if ($case.Env) { Remove-Item Env:UNSLOTH_TORCH_INDEX_FAMILY -ErrorAction SilentlyContinue } }
+ Check "$($case.N) selects $($case.Want)" ($leaf -eq $case.Want)
+ if ($case.ContainsKey('Loud')) {
+ Check "and it $(if ($case.Loud) { 'says so' } else { 'stays silent' })" ([bool]$script:Said -eq $case.Loud)
+ }
+ foreach ($re in @($case.Said | Where-Object { $_ })) { Check "and the message matches '$re'" ($script:Said -match $re) }
+}
+
+# install_llama_prebuilt.py never sees the bus, so llama.cpp sites read $HasNvidiaDriverEvidence.
+$setupAstErrors = $null
+$setupAst = [System.Management.Automation.Language.Parser]::ParseInput($setupText, $setupPs1, [ref]$null, [ref]$setupAstErrors)
+Check "setup.ps1 parses" (-not $setupAstErrors)
+$llamaStart = $setupText.IndexOf('$_arm64CudaOptOut = ')
+$keepFn = $setupAst.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq "Get-GpuPrebuiltToKeepOverSourceBuild" }, $true)[0]
+$llamaReads = @($setupAst.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.VariableExpressionAst] -and $n.VariablePath.UserPath -eq "HasNvidiaSmi" }, $true) |
+ Where-Object { $_.Extent.StartOffset -gt $llamaStart -or
+ ($_.Extent.StartOffset -ge $keepFn.Extent.StartOffset -and $_.Extent.EndOffset -le $keepFn.Extent.EndOffset) })
+Check "the llama.cpp section exists where this test looks for it" ($llamaStart -gt 0)
+Check "no llama.cpp or CUDA-toolkit site reads the promoted `$HasNvidiaSmi" ($llamaReads.Count -eq 0)
+foreach ($needle in @(
+ '$_nvidiaEvidence = $HasNvidiaDriverEvidence -or',
+ 'if ($HasNvidiaDriverEvidence) { Resolve-CudaToolkit -RequireOrExit }',
+ 'if ($HasNvidiaDriverEvidence -and -not $cachedCuda) {',
+ 'if ($HasNvidiaDriverEvidence -and $NvccPath) {',
+ '$nvidia = $HasNvidiaDriverEvidence')) {
+ Check "setup.ps1 carries: $needle" ($setupText.Contains($needle))
+}
+$defAst = @($setupAst.FindAll({ param($n)
+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and "$($n.Left)" -eq '$HasNvidiaDriverEvidence' }, $true))
+Check "setup.ps1 defines `$HasNvidiaDriverEvidence exactly once" ($defAst.Count -eq 1)
+Check "and defines it after the presence promotion" ($defAst[0].Extent.StartOffset -gt $setupText.IndexOf('$script:NvidiaPresenceOnly = $true'))
+foreach ($case in @(
+ @{ Smi = $true; Only = $true; Want = $false; N = "a presence-only promotion" },
+ @{ Smi = $true; Only = $false; Want = $true; N = "nvidia-smi or the driver library" },
+ @{ Smi = $false; Only = $false; Want = $false; N = "no NVIDIA at all" })) {
+ $got = & { param($smi, $only) $HasNvidiaSmi = $smi; $script:NvidiaPresenceOnly = $only
+ . ([scriptblock]::Create("$($defAst[0].Extent.Text)")); $HasNvidiaDriverEvidence } $case.Smi $case.Only
+ Check "$($case.N) reads as driver evidence = $($case.Want)" ($got -eq $case.Want)
+}
+$script:NvidiaPresenceOnly = $false
+
+# One bounded scan per run (Start-Job counted on the REAL function), and a terminating Remove-Job must not escape it.
+function Invoke-ScanHarness($scanText, $mode) {
+ $script:StartJobs = 0
+ function Start-Job { param($ScriptBlock) $script:StartJobs++; return [pscustomobject]@{ Id = 1 } }
+ function Wait-Job { param($Job, $Timeout) if ($mode -eq 'hang') { return $null } else { return $Job } }
+ function Receive-Job { param($Job, $ErrorAction) NvAdapter }
+ function Stop-Job { param($Job, $ErrorAction) }
+ function Remove-Job { param($Job, [switch]$Force, $ErrorAction) if ($mode -eq 'throw') { throw "job cleanup failed" } }
+ . ([scriptblock]::Create($scanText))
+ $script:VideoControllerScanResult = $null
+ $a = Invoke-BoundedVideoControllerScan
+ $b = Invoke-BoundedVideoControllerScan
+ $afterTwo = $script:StartJobs
+ $script:VideoControllerScanResult = $null
+ $null = Invoke-BoundedVideoControllerScan
+ return [pscustomobject]@{ A = $a; B = $b; AfterTwo = $afterTwo; AfterReset = $script:StartJobs }
+}
+foreach ($file in @($installPs1, $setupPs1)) {
+ $leaf = Split-Path -Leaf $file
+ $scanText = Get-FunctionText $file "Invoke-BoundedVideoControllerScan"
+ $r = Invoke-ScanHarness $scanText 'hang'
+ Check "${leaf}: a hung scan is waited out once, not twice" ($r.AfterTwo -eq 1)
+ Check "${leaf}: and the reused answer is the hang answer (Ok false)" ($r.A.Ok -eq $false -and $r.B.Ok -eq $false)
+ Check "${leaf}: a reset starts a fresh scan (bites: the cache is per run, not forever)" ($r.AfterReset -eq 2)
+ $r = Invoke-ScanHarness $scanText 'ok'
+ Check "${leaf}: an answered scan is reused with the same adapters" (
+ $r.AfterTwo -eq 1 -and $r.B.Ok -eq $true -and @($r.B.Names)[0] -eq "NVIDIA GeForce RTX 4090")
+ $r = try { Invoke-ScanHarness $scanText 'throw' } catch { "threw: $($_.Exception.Message)" }
+ Check "${leaf}: a throwing job cleanup does not escape the scan" ($r -isnot [string])
+ Check "${leaf}: and the answer it already had is kept" ($r -isnot [string] -and $r.A.Ok -eq $true)
+}
+$script:VideoControllerScanResult = $null
+
+# Basic Display or no version: no promotion, same as base.
+foreach ($case in @(
+ @{ N = "an NVIDIA adapter with Basic Display 10.0.19041.3636"; A = @(NvAdapter 0 "10.0.19041.3636"); Want = $true },
+ @{ N = "an NVIDIA adapter with Basic Display 10.0.22621.1"; A = @(NvAdapter 0 "10.0.22621.1"); Want = $true },
+ @{ N = "an NVIDIA adapter with an NVIDIA driver 560.94"; A = @(NvAdapter 0 "32.0.15.6094"); Want = $false },
+ @{ N = "an NVIDIA adapter with a pre-R450 NVIDIA driver 442.50"; A = @(NvAdapter 0 "26.21.14.4250"); Want = $false },
+ @{ N = "an NVIDIA adapter with no DriverVersion at all"; A = @(NvAdapter 0 $null); Want = $true },
+ @{ N = "an NVIDIA adapter with an empty DriverVersion"; A = @(NvAdapter 0 ""); Want = $true },
+ @{ N = "an NVIDIA adapter with a blank DriverVersion"; A = @(NvAdapter 0 " "); Want = $true },
+ @{ N = "a Basic Display adapter beside one on the NVIDIA driver"; Want = $false;
+ A = @((Adapter "Microsoft Basic Display Adapter" "PCI\VEN_10DE&DEV_1C03" 0 "10.0.19041.3636"), $nv) },
+ @{ N = "a versionless adapter beside one on the NVIDIA driver"; Want = $false;
+ A = @((Adapter "Microsoft Basic Display Adapter" "PCI\VEN_10DE&DEV_1C03" 0 $null), $nv) },
+ @{ N = "a disabled Basic Display NVIDIA adapter"; A = @(NvAdapter 22 "10.0.19041.3636"); Want = $false },
+ @{ N = "a non-NVIDIA Basic Display adapter"; A = @(Adapter "Microsoft Basic Display Adapter" "ROOT\BASICDISPLAY" 0 "10.0.19041.3636"); Want = $false }
+)) {
+ $script:FakeAdapters = $case.A
+ Check "$($case.N) reads as no-NVIDIA-driver = $($case.Want)" ((Test-NvidiaAdapterWithoutNvidiaDriver) -eq $case.Want)
+}
+
+function Get-NvidiaAdapterCudaFloor { param($Scan) return $null }
+$promoVenv = Join-Path ([System.IO.Path]::GetTempPath()) ("promo-venv-" + [guid]::NewGuid().ToString("N"))
+$promoPy = Join-Path $promoVenv "Scripts\python.exe"
+$promoTorch = Join-Path $promoVenv "Lib\site-packages\torch"
+New-Item -ItemType Directory -Force -Path (Split-Path -Parent $promoPy), $promoTorch | Out-Null
+Set-Content -LiteralPath $promoPy -Value "" -NoNewline
+Set-Content -LiteralPath (Join-Path $promoTorch "version.py") -Value "__version__ = '2.8.0+xpu'"
+Invoke-Expression (Get-FunctionText $setupPs1 "Test-VenvTorchIsXpu")
+$script:FakeProbableVenv = $null
+function Get-ProbableStudioVenvDir { return $script:FakeProbableVenv }
+function Invoke-Promotion($promo, $adapters, $venv, $py) {
+ try { & {
+ $VenvDir = $venv; $VenvPython = $py
+ $script:StudioPreservedXpuVerdict = $false; $script:StudioVenvRollbackDir = $null
+ $script:FakeAdapters = $adapters; $script:FakeScanOk = $null
+ $script:Lines = @()
+ function Write-StudioLine { param([string]$Line, [string]$ForegroundColor = "") $script:Lines += $Line }
+ $HasNvidiaSmi = $false; $script:NvidiaPresenceOnly = $false; $script:NvidiaSmiRejected = $false
+ . ([scriptblock]::Create($promo))
+ [pscustomobject]@{ Has = $HasNvidiaSmi; Only = $script:NvidiaPresenceOnly; Lines = @($script:Lines) }
+ } } catch { [pscustomobject]@{ Has = "threw: $($_.Exception.Message)"; Only = $null; Lines = @() } }
+}
+function Rtx4060 { Adapter "NVIDIA GeForce RTX 4060 Laptop GPU" "PCI\VEN_10DE&DEV_28E0" 0 "32.0.15.6094" }
+function Mtl($id = "PCI\VEN_8086&DEV_7D55", $code = 0) { Adapter "Intel(R) Graphics" $id $code "32.0.101.6078" }
+function Arc($id = "PCI\VEN_8086&DEV_56A0", $code = 0) { Adapter "Intel(R) Arc(TM) A770 Graphics" $id $code "32.0.101.6078" }
+function BasicNv($v) { Adapter "Microsoft Basic Display Adapter" "PCI\VEN_10DE&DEV_2684" 0 $v }
+foreach ($file in @($installPs1, $setupPs1)) {
+ $leaf = Split-Path -Leaf $file
+ $promo = Get-PromotionBlock $file
+ Check "$leaf's promotion block was found (bites)" ([bool]$promo)
+ foreach ($case in @(
+ @{ N = "Basic Display (10.0.19041.3636)"; A = @(BasicNv "10.0.19041.3636"); Want = $false; Hint = $true },
+ @{ N = "an NVIDIA driver (560.94)"; A = @(NvAdapter 0 "32.0.15.6094"); Want = $true; Hint = $false },
+ @{ N = "no DriverVersion"; A = @(NvAdapter 0 $null); Want = $false; Hint = $true },
+ @{ N = "Basic Display with no DriverVersion"; A = @(BasicNv $null); Want = $false; Hint = $true },
+ @{ N = "Basic Display with an empty DriverVersion"; A = @(BasicNv ""); Want = $false; Hint = $true },
+ @{ N = "Basic Display plus Intel UHD"; Want = $false; Hint = $true;
+ A = @((BasicNv "10.0.19041.3636"), (Adapter "Intel(R) UHD Graphics" "PCI\VEN_8086&DEV_9A49" 0 "31.0.101.1")) },
+ @{ N = "an NVIDIA driver plus a Meteor Lake GPU whose PyTorch has proven XPU"; A = @((Rtx4060), (Mtl)); Want = $false; Xpu = "True" },
+ @{ N = "an NVIDIA driver plus a Meteor Lake GPU with no XPU runtime"; A = @((Rtx4060), (Mtl)); Want = $true },
+ # Base's Intel route ignored PNP ID and status, so these must still decline.
+ @{ N = "an NVIDIA driver plus a Meteor Lake with no status, PyTorch XPU proven"; A = @((Rtx4060), (Mtl -code $null)); Want = $false; Xpu = "True" },
+ @{ N = "an NVIDIA driver plus a Meteor Lake with no PNP ID, PyTorch XPU proven"; A = @((Rtx4060), (Mtl $null)); Want = $false; Xpu = "True" },
+ @{ N = "an NVIDIA driver and no Intel row at all, PyTorch XPU proven"; A = @(Rtx4060); Want = $false; Xpu = "True" },
+ @{ N = "an NVIDIA driver plus an Arc with no status, no XPU runtime"; A = @((Rtx4060), (Arc -code $null)); Want = $false },
+ @{ N = "an NVIDIA driver plus an Arc with no PNP ID, no XPU runtime"; A = @((Rtx4060), (Arc $null)); Want = $false },
+ @{ N = "an NVIDIA driver plus a disabled Arc, no XPU runtime"; A = @((Rtx4060), (Arc -code 22)); Want = $false },
+ @{ N = "an NVIDIA driver plus an AMD adapter with no status"; Want = $false;
+ A = @((Rtx4060), (Adapter "AMD Radeon(TM) Graphics" "PCI\VEN_1002&DEV_15BF" $null "31.0.21001.45002")) },
+ @{ N = "an NVIDIA driver plus a UHD with no status, no XPU runtime"; Want = $true;
+ A = @((Rtx4060), (Adapter "Intel(R) UHD Graphics 770" "PCI\VEN_8086&DEV_4680" $null "31.0.101.1")) },
+ @{ N = "an unreadable status"; A = @(NvAdapter "bogus" "32.0.15.6094"); Want = $false }
+ )) {
+ $script:ProbeAnswer = @{ Ok = $true; Output = $(if ($case.Xpu) { $case.Xpu } else { "False" }) }
+ $got = Invoke-Promotion $promo $case.A $promoVenv $promoPy
+ Check "$leaf, NVIDIA on $($case.N): promoted = $($case.Want)" ($got.Has -eq $case.Want -and $got.Only -eq $case.Want)
+ $hint = [bool]$case.Hint
+ Check "$leaf, NVIDIA on $($case.N): driver hint printed = $hint" ([bool](@($got.Lines) -match 'without the NVIDIA driver') -eq $hint)
+ }
+}
+# Base asked Get-ProbableStudioVenvDir, which is not $VenvDir under a stage root.
+$emptyVenv = Join-Path ([System.IO.Path]::GetTempPath()) ("promo-empty-" + [guid]::NewGuid().ToString("N"))
+New-Item -ItemType Directory -Force -Path $emptyVenv | Out-Null
+$script:ProbeAnswer = @{ Ok = $true; Output = "True" }
+$script:FakeProbableVenv = $promoVenv
+$got = Invoke-Promotion (Get-PromotionBlock $setupPs1) @((Rtx4060), (Mtl)) $emptyVenv (Join-Path $emptyVenv "Scripts\python.exe")
+Check "setup.ps1 declines where the studio-home environment has proven XPU and the stage root has none" ($got.Has -eq $false)
+$script:FakeProbableVenv = $null
+Remove-Item -LiteralPath $emptyVenv, $promoVenv -Recurse -Force -ErrorAction SilentlyContinue
+$script:NvidiaPresenceOnly = $false
+
+$fakePy = Join-Path ([System.IO.Path]::GetTempPath()) ("xpu-py-" + [guid]::NewGuid().ToString("N"))
+Set-Content -LiteralPath $fakePy -Value "" -NoNewline
+$mtl = Adapter "Intel(R) Graphics" "PCI\VEN_8086&DEV_7D55" 0
+$rtx = Adapter "NVIDIA GeForce RTX 4060 Laptop GPU" "PCI\VEN_10DE&DEV_28E0" 0
+foreach ($case in @(
+ @{ N = "a Meteor Lake GPU whose PyTorch reports XPU is proven"; Want = $true },
+ @{ N = "an XPU runtime that answers False is not proven"; Ans = @{ Ok = $true; Output = "False" }; Want = $false },
+ @{ N = "a probe that times out is not proven"; Ans = @{ Ok = $false; Output = "" }; Want = $false },
+ @{ N = "a probe that throws is not proven and does not throw out"; Throws = $true; Want = $false },
+ @{ N = "no environment to ask is not proven"; Py = (Join-Path $fakePy "missing"); Want = $false },
+ @{ N = "a proven XPU runtime is proven with no Intel row at all"; A = @($rtx); Want = $true; Calls = 1 },
+ @{ N = "a proven XPU runtime is proven with an Intel row with no status";
+ A = @((Adapter "Intel(R) Graphics" "PCI\VEN_8086&DEV_7D55" $null), $rtx); Want = $true; Calls = 1 },
+ @{ N = "a proven XPU runtime is proven with an Intel row with no PNP ID";
+ A = @((Adapter "Intel(R) Graphics" $null 0), $rtx); Want = $true; Calls = 1 },
+ @{ N = "a proven XPU runtime is proven with a scan that did not answer"; A = @(); Want = $true; Calls = 1 }
+)) {
+ $list = if ($case.ContainsKey('A')) { @($case.A) } else { @($mtl, $rtx) }
+ $scan = [pscustomobject]@{ Ok = $list.Count -gt 0; Adapters = $list; Names = @($list | ForEach-Object { $_.Name }) }
+ $script:ProbeAnswer = if ($case.Ans) { $case.Ans } else { @{ Ok = $true; Output = "True" } }
+ $script:ProbeThrows = [bool]$case.Throws
+ $script:ProbeCalls = 0
+ $got = Test-IntelXpuRuntimeProven -Scan $scan -PythonExe $(if ($case.Py) { $case.Py } else { $fakePy })
+ Check $case.N ($got -eq $case.Want -and (-not $case.Calls -or $script:ProbeCalls -eq $case.Calls))
+}
+$script:ProbeThrows = $false
+Remove-Item -LiteralPath $fakePy -Force -ErrorAction SilentlyContinue
+
+if ($failures -gt 0) {
+ Write-Host "$failures check(s) failed" -ForegroundColor Red
+ exit 1
+}
+Write-Host "all checks passed" -ForegroundColor Green
diff --git a/tests/studio/test_nvidia_library_inventory.ps1 b/tests/studio/test_nvidia_library_inventory.ps1
index 62355b6f125..7f5e4e39136 100644
--- a/tests/studio/test_nvidia_library_inventory.ps1
+++ b/tests/studio/test_nvidia_library_inventory.ps1
@@ -197,7 +197,7 @@ function Get-NvidiaLibraryInventory { param([int]$TimeoutSec = 10) return $scrip
Write-Host ""
Write-Host "=== studio/setup.ps1 ==="
foreach ($src in (Get-HelperSources $setupPs1 @("Get-NvidiaCu126Verdict", "Get-CudaFamilyCappedForPreTuring",
- "Get-PytorchCudaTag", "Get-CudaComputeCapability", "Get-LlamaUpdateFailReason",
+ "Get-CudaFamilyForVersion", "Get-PytorchCudaTag", "Get-CudaComputeCapability", "Get-LlamaUpdateFailReason",
"Get-PrebuiltMarkerBackend", "Get-GpuPrebuiltToKeepOverSourceBuild"))) {
Invoke-Expression $src
}
@@ -250,6 +250,7 @@ Set-Content -LiteralPath (Join-Path $install "UNSLOTH_PREBUILT_INFO.json") -Valu
function python { $global:LASTEXITCODE = $script:FakePythonRc }
$script:FakePythonRc = 0
$HasNvidiaSmi = $true
+$HasNvidiaDriverEvidence = $true
$HasROCm = $false
$script:ROCmGfxArch = $null
$script:IsIntelXpu = $false
@@ -276,7 +277,13 @@ $script:FakePythonRc = 1
Check "an install that no longer runs is not kept" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "")
$script:FakePythonRc = 0
$HasNvidiaSmi = $false
+$HasNvidiaDriverEvidence = $false
Check "a CUDA prebuilt with the GPU gone is not kept" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "")
+# Presence-only is not a CUDA host for llama.cpp.
+$HasNvidiaSmi = $true
+$HasNvidiaDriverEvidence = $false
+Check "a CUDA prebuilt on a presence-only NVIDIA host is not kept" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "")
+$HasNvidiaSmi = $false
Set-Content -LiteralPath (Join-Path $install "UNSLOTH_PREBUILT_INFO.json") -Value '{"backend": "vulkan"}'
$HasROCm = $true
Check "a Vulkan prebuilt is kept for any GPU vendor" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "vulkan")
@@ -296,6 +303,7 @@ Set-Content -LiteralPath (Join-Path $install "UNSLOTH_PREBUILT_INFO.json") -Valu
Check "a CPU prebuilt has nothing to keep" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "")
# Markers from before the backend field, read as setup.sh reads them.
$HasNvidiaSmi = $true
+$HasNvidiaDriverEvidence = $true
Set-Content -LiteralPath (Join-Path $install "UNSLOTH_PREBUILT_INFO.json") -Value '{"llama_backend": "cuda"}'
Check "a legacy marker naming the request is kept" ((Get-GpuPrebuiltToKeepOverSourceBuild -InstallDir $install) -eq "cuda")
Set-Content -LiteralPath (Join-Path $install "UNSLOTH_PREBUILT_INFO.json") -Value '{"asset": "app-b8508-mix-windows-x64-cuda13-newer.zip"}'
@@ -372,7 +380,7 @@ function Test-WinArm64Venv { $false }
function Get-PinnedTorchIndexUrl { $null }
function Get-PersistedWoaTorchIndex { $null }
function Get-WoaTorchIndexMarker { $null }
-$WinArm64EffectiveTorchIndexUrl = $null; $HasROCm = $false; $script:ROCmGfxArch = $null; $HasNvidiaSmi = $false
+$WinArm64EffectiveTorchIndexUrl = $null; $HasROCm = $false; $script:ROCmGfxArch = $null; $HasNvidiaSmi = $false; $HasNvidiaDriverEvidence = $false
foreach ($case in @(@{ Flag = $true; Want = $true }, @{ Flag = $false; Want = $false })) {
$script:NvidiaDriverLibraryOnly = $case.Flag
Invoke-Expression $kindBlock
diff --git a/tests/studio/test_nvidia_presence_xpu_timeout.ps1 b/tests/studio/test_nvidia_presence_xpu_timeout.ps1
new file mode 100644
index 00000000000..677fcaeb4e4
--- /dev/null
+++ b/tests/studio/test_nvidia_presence_xpu_timeout.ps1
@@ -0,0 +1,78 @@
+#!/usr/bin/env pwsh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# An update whose XPU runtime probe times out keeps the XPU route even when the NVIDIA presence promotion fires.
+param([string]$RepoRoot = (Join-Path $PSScriptRoot "../.."))
+$ErrorActionPreference='Stop'
+$repo=(Resolve-Path $RepoRoot).Path
+$path=Join-Path $repo 'studio/setup.ps1'
+$text=[IO.File]::ReadAllText($path)
+# Parse the text that is sliced below: Windows PowerShell 5.1 reads a BOM-less file as ANSI, which shifts offsets.
+$ast=[System.Management.Automation.Language.Parser]::ParseInput($text,$path,[ref]$null,[ref]$null)
+$functions=@($ast.FindAll({param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst]},$true))
+foreach($f in $functions){. ([scriptblock]::Create($f.Extent.Text))}
+$ifs=@($ast.FindAll({param($n) $n -is [System.Management.Automation.Language.IfStatementAst]},$true))
+$promo=@($ifs|Where-Object {$_.Extent.Text -match '^if \(-not \$HasNvidiaSmi\) \{\s*\$presenceScan = Invoke-BoundedVideoControllerScan'})[0]
+$selector=@($ifs|Where-Object {$_.Extent.Text -match '^if \(\$PinnedTorchIndexUrl\)' -and $_.Extent.Text -match 'Get-PytorchCudaTag'})[0]
+$selectorStart=$text.LastIndexOf('$PinnedTorchIndexUrl = Get-PinnedTorchIndexUrl', $selector.Extent.StartOffset)
+$selectorBlock=$text.Substring($selectorStart,$selector.Extent.EndOffset-$selectorStart)
+$gate=@($ifs|Where-Object {$_.Extent.Text -match '^if \(-not \$ROCmIndexUrl -and \$CuTag -eq "xpu"\)'})[0]
+$ss=$text.IndexOf('$shouldRebuild = $false',$text.IndexOf('$installedTorchTag = $null'))
+$se=$text.IndexOf('# Outside the rebuild branch:',$ss)
+$stale=$text.Substring($ss,$se-$ss)
+$cs=$text.IndexOf('$cudaForce = @()',$text.IndexOf('substep "installing PyTorch with CUDA support'))
+$ce=$text.IndexOf('$cudaTorchSpec =',$cs)
+$cudaForceBlock=$text.Substring($cs,$ce-$cs)
+$fixture=Join-Path ([IO.Path]::GetTempPath()) ('xpu-update-venv-' + [guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Force -Path "$fixture/Scripts"|Out-Null
+Set-Content "$fixture/Scripts/python.exe" ''
+foreach($n in @('UNSLOTH_TORCH_INDEX_URL','UNSLOTH_TORCH_INDEX_FAMILY','UNSLOTH_ROCM_GFX_ARCH','_UNSLOTH_ROCM_GFX_ARCH_HANDOFF','HIP_PATH','HIP_PATH_57','ROCM_PATH','UNSLOTH_ENABLE_AMD_SMI')){[Environment]::SetEnvironmentVariable($n,$null)}
+function python { $global:LASTEXITCODE=1 }
+function substep {param($Message,$Color)}
+function Write-StudioLine {param($Line,$ForegroundColor)}
+function Get-Command {param($Name,$CommandType,$ErrorAction) $null}
+function Get-NvidiaLibraryInventory {$null}
+function Get-ProbableStudioVenvDir {$fixture}
+function Test-VenvTorchIsXpu {param($VenvPath) $true}
+function Test-WinArm64Venv {$false}
+function Get-SetupHostInterpreterInVenv {param($VenvDir) "$VenvDir/Scripts/python.exe"}
+function Get-IntelRegistryAdapterNames {@('Intel Graphics')}
+function Invoke-BoundedVideoControllerScan {
+ [pscustomobject]@{Ok=$true;Names=@('NVIDIA RTX 4060','Intel Graphics');Adapters=@(
+ [pscustomobject]@{Name='NVIDIA RTX 4060';PNPDeviceID='PCI\VEN_10DE&DEV_2882';ConfigManagerErrorCode=0;DriverVersion='32.0.15.8000'},
+ [pscustomobject]@{Name='Intel Graphics';PNPDeviceID='PCI\VEN_8086&DEV_7D55';ConfigManagerErrorCode=0;DriverVersion='32.0.101.6739'})}
+}
+function Invoke-BoundedPythonProbe {
+ param($PythonExe,$Code,$TimeoutSec)
+ if($Code -match '__version__'){return [pscustomobject]@{Ok=$true;Output='2.11.0+xpu';TimedOut=$false}}
+ if($script:Mode -eq 'timeout'){return [pscustomobject]@{Ok=$false;Output='';TimedOut=$true}}
+ $value=if($script:Mode -eq 'live'){'True'}else{'False'}
+ [pscustomobject]@{Ok=$true;Output=$(if($Code -match 'DEV='){"DEV=$value"}else{$value});TimedOut=$false}
+}
+$failures=0
+foreach($mode in @('live','timeout','unavailable')){
+ $script:Mode=$mode
+ $HasNvidiaSmi=$false;$HasROCm=$false;$AmdHasGpuWheels=$false
+ $script:IsIntelXpu=$false;$script:NvidiaPresenceOnly=$false;$script:NvidiaPresenceCudaFloor=$null;$script:NvidiaPresenceDriverRelease=$null;$script:NvidiaPresenceStaleGpuWheel=$null
+ $script:NvidiaSmiExe=$null;$script:NvidiaSmiRejected=$true;$script:PreservedXpuVenv=$false;$script:PreservedInstallerTorchTag=$null;$script:PinChangedForceReinstall=$false;$script:TorchImportDefinitivelyFailed=$false
+ $VenvDir=$fixture;$VenvPyExe="$fixture/Scripts/python.exe";$installedTorchTag='xpu';$InstallerManagedSetup=$false;$PinnedTorchIndexUrl=$null;$NoTorchMode=$false;$script:ROCmGfxArch=$null
+ if($promo){. ([scriptblock]::Create($promo.Extent.Text))}
+ . ([scriptblock]::Create($stale))
+ $env:UNSLOTH_STUDIO_FULL_DEPS='1';$script:SkipPythonDeps=$true
+ Invoke-FastPathEscapes
+ . ([scriptblock]::Create($selectorBlock))
+ $ROCmIndexUrl=$null;$TorchInstallIndexUrl="https://download.pytorch.org/whl/$CuTag";$XpuIndexUrl=$null
+ . ([scriptblock]::Create($gate.Extent.Text))
+ $cudaForce=@()
+ if(-not $XpuIndexUrl){. ([scriptblock]::Create($cudaForceBlock))}
+ # A definitive False may intentionally convert the stale XPU wheel. Uncertainty must keep XPU's dependency route.
+ $expected=if($mode -eq 'unavailable' -and $promo){'cu126'}else{'xpu'}
+ $ok=($CuTag -eq $expected) -and -not $script:SkipPythonDeps
+ if($mode -eq 'timeout'){$ok=$ok -and [bool]$XpuIndexUrl -and $cudaForce.Count -eq 0}
+ $result=[pscustomobject]@{Arm=$RepoRoot;Probe=$mode;Promoted=$script:NvidiaPresenceOnly;DependencyPass=(-not $script:SkipPythonDeps);CuTag=$CuTag;XpuIndexUrl=$XpuIndexUrl;CudaForce=@($cudaForce);PreservedXpu=$script:PreservedXpuVenv;Expected=$expected;Pass=$ok}
+ $result|ConvertTo-Json -Compress|Write-Output
+ if(-not $ok){$failures++}
+}
+Remove-Item -LiteralPath $fixture -Recurse -Force -ErrorAction SilentlyContinue
+if($failures){Write-Host "$failures checks failed";exit 1}
+Write-Host 'all checks passed';exit 0