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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Add Intel Arc GPU detection and XPU PyTorch install to Windows installer (#7706)
benj6a58ea0f0ec4
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex c5c2b98955a..71a7beebd6f 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -26,6 +26,14 @@ on:- 'tests/python/test_windows_python_venv_hardening.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'+ - 'tests/studio/test_intel_registry_fallback.ps1'+ - 'studio/setup.ps1'+ - 'tests/studio/test_setup_xpu_runtime_prereport.ps1'+ - 'tests/studio/test_xpu_arm64_torchaudio.ps1'+ - 'tests/sh/test_install_sh_xpu_flavor_probe.sh'+ - 'tests/sh/test_setup_xpu_fastpath_escape.sh'+ - 'tests/sh/test_setup_xpu_posix_summary.sh'+ - 'studio/setup.sh'- '.github/workflows/cross-platform-parity-ci.yml'push:branches: [main]@@ -39,6 +47,14 @@ on:- 'tests/python/test_windows_python_venv_hardening.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'+ - 'tests/studio/test_intel_registry_fallback.ps1'+ - 'studio/setup.ps1'+ - 'tests/studio/test_setup_xpu_runtime_prereport.ps1'+ - 'tests/studio/test_xpu_arm64_torchaudio.ps1'+ - 'tests/sh/test_install_sh_xpu_flavor_probe.sh'+ - 'tests/sh/test_setup_xpu_fastpath_escape.sh'+ - 'tests/sh/test_setup_xpu_posix_summary.sh'+ - 'studio/setup.sh'- '.github/workflows/cross-platform-parity-ci.yml'workflow_dispatch:@@ -81,6 +97,29 @@ jobs:if: runner.os == 'Windows'shell: pwshrun: pwsh -NoProfile -File tests/studio/test_install_rollback_lifecycle.ps1+ # Mocks the registry cmdlets rather than reading a hive, so it runs on all three.+ - name: Intel registry fallback tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_intel_registry_fallback.ps1+ # Same reason: the filesystem is mocked, so no real venv or Windows is needed.+ - name: Setup XPU pre-report tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_setup_xpu_runtime_prereport.ps1+ # Parses install.ps1 with the AST and executes the extracted builder, so no venv.+ - name: XPU arm64 torchaudio tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_xpu_arm64_torchaudio.ps1- name: POSIX rollback lifecycle testsif: runner.os == 'Linux'run: sh tests/sh/test_install_rollback_lifecycle.sh+ # bash, not sh: the helper under test is extracted from install.sh, which is bash.+ - name: install.sh XPU flavor probe tests+ if: runner.os != 'Windows'+ run: bash tests/sh/test_install_sh_xpu_flavor_probe.sh+ # Same reason: the escape and the hardware summary are extracted from setup.sh and run+ # against built venv trees, so no real install is needed.+ - name: setup.sh XPU fast-path + summary tests+ if: runner.os != 'Windows'+ run: |+ bash tests/sh/test_setup_xpu_fastpath_escape.sh+ bash tests/sh/test_setup_xpu_posix_summary.shdiff --git a/install.ps1 b/install.ps1index cc850d69a81..332933a26f3 100644--- a/install.ps1+++ b/install.ps1@@ -112,7 +112,7 @@ function Install-UnslothStudio {if ([string]::IsNullOrWhiteSpace($TorchIndexUrl)) { return "none" }# Drop query/fragment first so a token-authenticated pin classifies by family.$leaf = (($TorchIndexUrl -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1].ToLowerInvariant()- if (@("cpu", "cu118", "cu124", "cu126", "cu128", "cu130") -contains $leaf) { return $leaf }+ if (@("cpu", "xpu", "cu118", "cu124", "cu126", "cu128", "cu130") -contains $leaf) { return $leaf }if ($leaf -match '^rocm[0-9]+\.[0-9]+$') { return $leaf }return "auto"}@@ -123,6 +123,7 @@ function Install-UnslothStudio {# Require a digit after "cu" so /current or /custom isn't branded CUDA (parity ^cu[0-9]).if ($TorchIndexFamily -match '^cu[0-9]') { return "cuda" }if ($TorchIndexFamily -like "rocm*") { return "rocm" }+ if ($TorchIndexFamily -eq "xpu") { return "xpu" }if ($TorchIndexFamily -eq "cpu") { return "cpu" }return "unknown"}@@ -2344,8 +2345,195 @@ exit 0} catch {}}+ # ── AMD gfx arch → AMD pip index family (repo.amd.com/rocm/whl/<family>) ──+ # Hoisted above the Intel scan, which needs it: an arch missing here gets CPU torch, so it+ # must not outrank a usable Arc card. The AMD reroute below consumes it too.+ $archFamilyMap = @{+ "gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4+ "gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)+ "gfx1152" = "gfx1152" # RDNA 3.5 (Krackan Point)+ "gfx1103" = "gfx110X-all"; "gfx1102" = "gfx110X-all" # RDNA 3+ "gfx1101" = "gfx110X-all"; "gfx1100" = "gfx110X-all"+ "gfx1036" = "gfx103X-all"; "gfx1035" = "gfx103X-all" # RDNA 2 (RX 6000)+ "gfx1034" = "gfx103X-all"; "gfx1033" = "gfx103X-all"+ "gfx1032" = "gfx103X-all"; "gfx1031" = "gfx103X-all"+ "gfx1030" = "gfx103X-all"+ "gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100+ }+ # "AMD gets GPU wheels here", NOT "an AMD GPU is present": $HasROCm / $ROCmGfxArch are+ # true on unmapped arches too, and those install CPU torch.+ $AmdHasGpuWheels = [bool]($ROCmGfxArch -and $archFamilyMap.ContainsKey($ROCmGfxArch))++ # ── Bounded "ask the venv python" probe ──+ # A wedged torch import or a hanging Intel driver init -- what the XPU probes below exist to+ # detect -- would block a bare `& python -c ...` forever. ProcessStartInfo, not &, so stderr+ # cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import cannot+ # deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure+ # (timeout, crash, exception) reads as .Ok = $false. Defined above the Intel scan, since+ # PowerShell binds a function only when its definition runs.+ function Invoke-BoundedPythonProbe {+ param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)+ $result = [pscustomobject]@{ Ok = $false; Output = "" }+ if (-not $PythonExe -or -not $Code) { return $result }+ try {+ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = $PythonExe+ $psi.Arguments = "-c `"$Code`""+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $proc = [System.Diagnostics.Process]::Start($psi)+ $outTask = $proc.StandardOutput.ReadToEndAsync()+ $errTask = $proc.StandardError.ReadToEndAsync()+ if (-not $proc.WaitForExit($TimeoutSec * 1000)) {+ try { $proc.Kill() } catch {}+ return $result+ }+ $result.Output = $outTask.GetAwaiter().GetResult()+ [void]$errTask.GetAwaiter().GetResult()+ $result.Ok = ($proc.ExitCode -eq 0)+ return $result+ } catch { return $result }+ }++ # 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+ # present"; $script:IsIntelXpu is "XPU wheels suit it" -- only Arc / Data Center parts+ # qualify, UHD / HD / Iris Xe do not.+ $HasIntelGpu = $false+ $IntelGpuLabel = $null+ # Reset every invocation: under "irm ... | iex" $script: is the caller's session scope, so a+ # second run would inherit a stale $true and reroute a now-NVIDIA host to the xpu index.+ $script:IsIntelXpu = $false+ # $AmdHasGpuWheels keeps a wheel-served AMD host out of the XPU reroute below; an AMD host+ # with no wheels is heading for CPU torch, so a neighbouring Arc card wins.+ if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {+ try {+ # Bounded, registry as the fallback when WMI does not answer; same match either way.+ $_gpuScan = Invoke-BoundedVideoControllerScan+ # @() wraps the WHOLE if, not each branch: a one-element array unrolls on its way+ # out, making $_gpuNames a String on a single-adapter host and turning the += below+ # into string concatenation.+ $_gpuNames = @(if ($_gpuScan.Ok) { $_gpuScan.Names } else { Get-IntelRegistryAdapterNames })+ # One definition for both the reconciliation gate and the classification below.+ $_xpuNameRe = "(?i)Intel.*(Arc|Data Center GPU)"+ # On non-English Windows the WMI name carries no ASCII "Intel" for the+ # classification below. The registry helper resolves the PCI vendor id, so use it to+ # RE-LABEL an adapter WMI already reported, never to add one (an unmatched entry is a+ # driver record outliving its card). Gated on the absence of an XPU match, not of any+ # Intel name: a hybrid laptop reports "Intel UHD" next to a localized Arc.+ if ($_gpuScan.Ok -and -not ($_gpuNames | Where-Object { $_ -match $_xpuNameRe })) {+ foreach ($_reg in @(Get-IntelRegistryAdapterNames)) {+ foreach ($_wmiName in $_gpuNames) {+ if ($_wmiName -and $_reg.Contains($_wmiName)) { $_gpuNames += $_reg; break }+ }+ }+ }+ $intelGpus = @($_gpuNames | Where-Object { $_ -match "(?i)Intel" })+ if ($intelGpus.Count -gt 0) {+ $HasIntelGpu = $true+ $xpuGpu = $intelGpus | Where-Object { $_ -match $_xpuNameRe } | Select-Object -First 1+ $IntelGpuLabel = if ($xpuGpu) { $xpuGpu } else { $intelGpus[0] }+ if ($xpuGpu) { $script:IsIntelXpu = $true }+ }+ } catch {}+ # A migrated env's torch can only CONFIRM the match, never veto it: an unavailable+ # runtime means a stale driver, not unsuitable hardware, and the /cpu fallback could not+ # displace the installed +xpu wheel anyway (PEP 440 ignores the local label). Bounded,+ # and a timeout reads as "no XPU" -- the WMI verdict stands.+ # A rerun has already moved the old venv to $script:StudioVenvRollbackDir and put an+ # empty one in its place, so probing $VenvPython would ask an interpreter with no torch.+ # Ask the preserved environment instead -- that is the migrated runtime this rescues.+ $_xpuProbePy = $VenvPython+ if ($script:StudioVenvRollbackDir) {+ $_rollbackPy = Join-Path $script:StudioVenvRollbackDir "Scripts\python.exe"+ if (Test-Path -LiteralPath $_rollbackPy) { $_xpuProbePy = $_rollbackPy }+ }+ if (Test-Path -LiteralPath $_xpuProbePy) {+ $xpuCheck = Invoke-BoundedPythonProbe -PythonExe $_xpuProbePy -Code 'import torch; print(torch.xpu.is_available())'+ if ($xpuCheck.Ok -and $xpuCheck.Output -match '(?m)^\s*True\s*$') {+ $HasIntelGpu = $true+ $script:IsIntelXpu = $true+ if (-not $IntelGpuLabel) { $IntelGpuLabel = "Intel GPU (detected by PyTorch XPU)" }+ }+ }+ }+if ($HasNvidiaSmi) {step "gpu" "NVIDIA GPU detected"+ } elseif ($script:IsIntelXpu) {+ # Ranks above every AMD branch: only true when AMD gets no GPU wheel ($AmdHasGpuWheels+ # gates the scan above), so those branches would all end on CPU.+ step "gpu" "Intel GPU detected" "Green"+ substep "$IntelGpuLabel"+ # The reroute below prints the index: only it knows the mirror URL and any pin.} elseif ($HasROCm) {step "gpu" $ROCmGpuLabel$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }@@ -2374,7 +2562,8 @@ exit 0substep "https://rocm.docs.amd.com/en/latest/deploy/windows/index.html" "Yellow"} else {step "gpu" "none (chat-only / GGUF)" "Yellow"- substep "Training and GPU inference require an NVIDIA or AMD ROCm GPU." "Yellow"+ if ($HasIntelGpu) { substep "Detected: $IntelGpuLabel (not XPU-capable)" "Yellow" }+ substep "Training and GPU inference require an NVIDIA, AMD ROCm, or Intel Arc GPU." "Yellow"}# On an AMD GPU (no NVIDIA), surface the optional WSL-ROCm driver hint.if (-not $HasNvidiaSmi -and ($ROCmGfxArch -or $ROCmGpuLabel)) { Show-AmdWslDriverHint }@@ -2391,6 +2580,14 @@ exit 0return $value.Substring(0, $idx).TrimEnd('/') + $value.Substring($idx)}+ # Index leaf (cpu / cu128 / xpu / gfx1201), ?query and #fragment stripped so a+ # token-authenticated mirror still classifies by family.+ function Get-TorchIndexLeafName {+ param([string]$Url)+ if ([string]::IsNullOrWhiteSpace($Url)) { return "" }+ return ((($Url -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1]).ToLowerInvariant()+ }+# ── Choose the correct PyTorch index URL based on driver CUDA version ──# Mirrors Get-PytorchCudaTag in setup.ps1.function Get-TorchIndexUrl {@@ -2453,6 +2650,7 @@ exit 0if (-not $TorchVersion) { return $null }if ($TorchVersion -match '\+(cu\d+)') { return $Matches[1] }if ($TorchVersion -match '\+rocm') { return 'rocm' }+ if ($TorchVersion -match '\+xpu') { return 'xpu' }if ($TorchVersion -match '\+cpu') { return 'cpu' }return 'cpu'}@@ -2467,41 +2665,61 @@ exit 0$leaf = (($TorchIndexUrl -split '[?#]', 2)[0].TrimEnd('/') -split '/')[-1].ToLowerInvariant()if ($leaf -match '^cu\d+$') { return $leaf }if ($leaf -eq 'cpu') { return 'cpu' }+ if ($leaf -eq 'xpu') { return 'xpu' }if ($leaf -match '^rocm') { return 'rocm' }# gfx must be followed by a digit (an architecture leaf); gfx-private is custom.if ($leaf -match '^gfx[0-9]') { return 'rocm' }return $null}- # Installed torch flavor tag in $PythonExe's venv, or $null if absent. Uses- # ProcessStartInfo (not &) so stderr doesn't trip $ErrorActionPreference.+ # sysconfig platform of $PythonExe's venv, lowercased ("" when it cannot be asked). Windows+ # on ARM has no torchaudio wheel on any index, so every XPU spec list is built from this.+ function Get-VenvPlatformTag {+ param([string]$PythonExe)+ if (-not $PythonExe) { return "" }+ try {+ return (& $PythonExe -c "import sysconfig; print(sysconfig.get_platform())" 2>$null | Out-String).Trim().ToLowerInvariant()+ } catch { return "" }+ }++ # The XPU trio for $Platform: floor 2.6 (unsloth/models/_utils.py raises at import for an+ # XPU device below it) and no torchaudio on win-arm64.+ function Get-XpuTorchSpecs {+ param([string]$Platform)+ $specs = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0")+ if ($Platform -eq "win-arm64") { return $specs }+ return $specs + @("torchaudio>=2.6,<2.11.0")+ }++ # Installed torch flavor tag in $PythonExe's venv, or $null if absent. Bounded, so a wedged+ # "import torch" cannot stall the flavor repair.function Get-InstalledTorchTag {param([string]$PythonExe)if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }- try {- $psi = New-Object System.Diagnostics.ProcessStartInfo- $psi.FileName = $PythonExe- $psi.Arguments = '-c "import torch; print(torch.__version__)"'- $psi.RedirectStandardOutput = $true- $psi.RedirectStandardError = $true- $psi.UseShellExecute = $false- $psi.CreateNoWindow = $true- $proc = [System.Diagnostics.Process]::Start($psi)- # Drain BOTH streams async, then WaitForExit. A synchronous ReadToEnd()- # before the wait would block forever if a wedged "import torch" never- # closes stdout; leaving the redirected stderr undrained would deadlock a- # child that floods it past the pipe buffer. Async reads let a noisy-but-- # exiting probe finish, while a truly hung one still hits the 30s timeout- # and is killed -- bounded either way.- $outTask = $proc.StandardOutput.ReadToEndAsync()- $errTask = $proc.StandardError.ReadToEndAsync()- $finished = $proc.WaitForExit(30000)- if (-not $finished) { try { $proc.Kill() } catch {}; return $null }- $torchVer = $outTask.GetAwaiter().GetResult().Trim()- [void]$errTask.GetAwaiter().GetResult()- if ($proc.ExitCode -ne 0 -or -not $torchVer) { return $null }- return ConvertTo-TorchFlavorTag $torchVer- } catch { return $null }+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.__version__)'+ if (-not $probe.Ok) { return $null }+ $torchVer = $probe.Output.Trim()+ if (-not $torchVer) { return $null }+ return ConvertTo-TorchFlavorTag $torchVer+ }++ # Post-install XPU runtime check. A +xpu wheel installing is not proof the GPU is usable: on+ # an old Intel compute driver torch.xpu.is_available() is False and Unsloth then dies at+ # import. Warn, never fall back -- a driver update fixes it.+ function Assert-XpuRuntimeReady {+ param([string]$PythonExe)+ # No interpreter to ask means something bigger already broke; do not blame the driver.+ if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $true }+ # Line-anchored so a stdout banner ahead of the answer hides nothing. Every failure,+ # timeout included, reads as not-ready and warns rather than hanging the installer.+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'+ if ($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$') { return $true }+ substep "[WARN] PyTorch XPU is installed but torch.xpu.is_available() is False." "Yellow"+ substep " The Intel GPU driver is most likely too old -- PyTorch XPU on Windows" "Yellow"+ substep " needs Intel Graphics Driver 32.0.101.6739 (WHQL) or newer." "Yellow"+ substep " Update the driver, then re-run. See:" "Yellow"+ substep " https://unsloth.ai/docs/get-started/install/intel" "Yellow"+ return $false}# An explicit pin is authoritative: the AMD ROCm reroute below must not rewrite it@@ -2510,6 +2728,14 @@ exit 0(-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_FAMILY))$TorchIndexUrl = Get-TorchIndexUrl+ # Intel XPU reroute. Must run AFTER the Get-TorchIndexUrl call above, or that call overwrites+ # it. An explicit pin still wins, like the AMD ROCm reroute below.+ if ($script:IsIntelXpu -and -not $TorchIndexPinned -and -not $SkipTorch) {+ $XpuBaseUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/') } else { "https://download.pytorch.org/whl" }+ $TorchIndexUrl = "$XpuBaseUrl/xpu"+ substep "PyTorch XPU (SYCL) wheels will be installed from $(Remove-IndexUrlCredentials $TorchIndexUrl)"+ }+# ── GPU arch → newest compatible Windows ROCm wheel release ──# Wheels bundle their own ROCm runtime; the installed HIP SDK version does# not constrain which release to use. Always picks the newest release that@@ -2523,18 +2749,7 @@ exit 0$PinnedRocmAudioSpec = $nullif (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $TorchIndexUrl -like "*/cpu" -and -not $SkipTorch) {$amdIndexBase = if ($env:UNSLOTH_ROCM_WINDOWS_MIRROR) { $env:UNSLOTH_ROCM_WINDOWS_MIRROR.TrimEnd('/') } else { "https://repo.amd.com/rocm/whl" }- $archFamilyMap = @{- "gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4- "gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)- "gfx1152" = "gfx1152" # RDNA 3.5 (Krackan Point)- "gfx1103" = "gfx110X-all"; "gfx1102" = "gfx110X-all" # RDNA 3- "gfx1101" = "gfx110X-all"; "gfx1100" = "gfx110X-all"- "gfx1036" = "gfx103X-all"; "gfx1035" = "gfx103X-all" # RDNA 2 (RX 6000)- "gfx1034" = "gfx103X-all"; "gfx1033" = "gfx103X-all"- "gfx1032" = "gfx103X-all"; "gfx1031" = "gfx103X-all"- "gfx1030" = "gfx103X-all"- "gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100- }+ # $archFamilyMap is defined above the Intel scan (the scan needs it too).# gfx120X (RDNA 4) and gfx1151/gfx1150 (Strix) have a null-pointer bug in# torch._C._grouped_mm on torch <2.11.0 (rocm7.12 and rocm7.1 respectively).# TheRock issues #5284 and #3284. Force torch>=2.11.0 so pip never resolves@@ -2627,6 +2842,10 @@ exit 0} elseif ($ROCmGpuLabel) {substep "Installing CPU-only PyTorch (AMD GPU arch unknown -- install the HIP SDK" "Yellow"substep "or set UNSLOTH_ROCM_GFX_ARCH to enable GPU ROCm)." "Yellow"+ } elseif ($HasIntelGpu -and -not $script:IsIntelXpu) {+ substep "Intel GPU detected but not XPU-capable. Installing CPU-only PyTorch." "Yellow"+ substep "PyTorch XPU needs Intel Arc or Data Center GPU plus a current driver." "Yellow"+ substep "See: https://unsloth.ai/docs/get-started/install/intel" "Yellow"} else {substep "No NVIDIA GPU detected." "Yellow"}@@ -2741,6 +2960,46 @@ exit 0$ROCmIndexUrl = $null$ROCmTorchFloor = $null}+ # Keyed off the index leaf alone, like the bitsandbytes gate below: a FAMILY=xpu or URL+ # pin lands here on a host whose Intel scan never ran (a mixed NVIDIA box), and requiring+ # $script:IsIntelXpu sent it to the generic branch and its 2.4 floor.+ } elseif ((Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") {+ # ── Intel Arc / XPU PyTorch install ──+ # XPU wheels carry their own oneAPI runtime (intel-sycl-rt et al.), published under+ # PEP 503 at https://download.pytorch.org/whl/xpu.+ Write-TauriLog "STEP" "Installing PyTorch (Intel XPU)"+ substep "installing PyTorch from $(Remove-IndexUrlCredentials $TorchIndexUrl)..."+ # Bound the trio like every other index: the xpu index serves torch past our ceiling+ # (up to 2.13.0), and torchaudio dropped its exact torch pin. The floor is 2.6, not+ # the usual 2.4: unsloth/models/_utils.py raises at import for an XPU device below+ # that. Windows on ARM has no torchaudio wheel on any index, so drop that pin here+ # rather than abort -- the pin-only route reaches this branch on an arm64 interpreter.+ $VenvPlatform = Get-VenvPlatformTag -PythonExe $VenvPython+ $_xpuSpecs = Get-XpuTorchSpecs -Platform $VenvPlatform+ $_xpuCpuSpecs = @("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0", "torchaudio>=2.4,<2.11.0")+ if ($VenvPlatform -eq "win-arm64") {+ substep "windows on arm: skipping torchaudio (upstream publishes no win_arm64 wheel)."+ $_xpuCpuSpecs = @("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0")+ }+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (Intel XPU)" { uv pip install --python $VenvPython --force-reinstall @_xpuSpecs --default-index $TorchIndexUrl }+ if ($torchInstallExit -ne 0) {+ # Transient XPU-index failure: fall back to CPU base.+ $CpuFallbackIndexUrl = if ($env:UNSLOTH_PYTORCH_MIRROR) { "$($env:UNSLOTH_PYTORCH_MIRROR.TrimEnd('/'))/cpu" } else { "https://download.pytorch.org/whl/cpu" }+ substep "XPU PyTorch install failed (exit $torchInstallExit); using a CPU base." "Yellow"+ $torchInstallExit = Invoke-InstallCommandRetry -Label "install PyTorch (CPU fallback)" { uv pip install --python $VenvPython --force-reinstall @_xpuCpuSpecs --default-index $CpuFallbackIndexUrl }+ if ($torchInstallExit -ne 0) {+ Write-Host "[ERROR] Failed to install PyTorch (XPU and CPU base both failed, exit code $torchInstallExit)" -ForegroundColor Red+ return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)+ }+ # Drop the XPU expectation so flavor-repair below skips the failed index (as ROCm does).+ $script:IsIntelXpu = $false+ $TorchIndexUrl = $CpuFallbackIndexUrl+ } else {+ # A WMI name match says XPU-capable, not that the runtime initializes: on a stale+ # driver unsloth/device_type.py raises NotImplementedError at import. The helper+ # warns and deliberately does NOT fall back to CPU.+ Assert-XpuRuntimeReady -PythonExe $VenvPython | Out-Null+ }} else {Write-TauriLog "STEP" "Installing PyTorch"# Windows on ARM lacks only torchaudio (whl/cpu win_arm64: torch 42,@@ -2841,6 +3100,26 @@ exit 0}}+ # ── Intel XPU: bitsandbytes must carry XPU kernels ──+ # unsloth/bnb_availability.py binds cgemv_4bit_inference_fp16/bf16 for device_type "xpu" and+ # only bitsandbytes' XPU library exports those, so a wheel without it turns 4-bit QLoRA off.+ # 0.48.2 is the first win_amd64 build carrying that library, but the floor is 0.50.0, the AMD+ # paths' floor: <=0.49.2 NaNs at 4-bit decode on AMD, and an Arc card can sit next to a+ # Radeon. unsloth's own floor (>=0.45.5) lets a MIGRATED venv keep an older wheel, so run+ # after that install for the last word. --no-deps (torch/numpy are in), and never the curated+ # unsloth[intel-gpu-torch*] extra: it pins torch to a single +xpu wheel URL, unpinning the+ # bounded trio, and carries a preview bitsandbytes wheel uv refuses.+ # Keyed off the index leaf, not $script:IsIntelXpu: a FAMILY=xpu pin on a non-Intel host+ # skips the XPU branch above yet still installs +xpu torch. The CPU fallback there rewrites+ # $TorchIndexUrl, so a failed XPU install reads as "cpu" here. Best-effort: a failure warns.+ if (-not $SkipTorch -and (Get-TorchIndexLeafName $TorchIndexUrl) -eq "xpu") {+ substep "installing bitsandbytes with Intel XPU kernels..."+ $bnbXpuExit = Invoke-InstallCommandRetry -Label "install bitsandbytes (Intel XPU)" { uv pip install --python $VenvPython --no-deps "bitsandbytes>=0.50.0" }+ if ($bnbXpuExit -ne 0) {+ substep "[WARN] could not install an XPU-capable bitsandbytes (exit $bnbXpuExit); 4-bit QLoRA may be unavailable." "Yellow"+ }+ }+$installedPackageVersion = (& $VenvPython -c "from importlib.metadata import version; import sys; print(version(sys.argv[1]))" $PackageName 2>$null | Out-String).Trim()if ($LASTEXITCODE -eq 0 -and $installedPackageVersion) {step $PackageName "$installedPackageVersion installed"@@ -2878,7 +3157,12 @@ exit 0} elseif ($expectedTorchTag -ne 'rocm') {# CUDA: stale +cpu (or wrong cuXXX) against a CUDA index -> reinstall triplet.substep "PyTorch flavor mismatch (installed $installedTorchTag, need $expectedTorchTag) -- reinstalling correct build..." "Yellow"- $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch ($expectedTorchTag)" { uv pip install --python $VenvPython "torch>=2.4,<2.11.0" "torchvision>=0.19,<0.26.0" "torchaudio>=2.4,<2.11.0" --default-index $TorchIndexUrl --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio }+ # Same trio builder as the XPU install above: a migrated win-arm64 venv+ # reaches THIS path, and asking for a torchaudio the index has no wheel for+ # fails the repair before setup.ps1's ARM-aware fallback.+ $_fixSpecs = if ($expectedTorchTag -eq 'xpu') { Get-XpuTorchSpecs -Platform (Get-VenvPlatformTag -PythonExe $VenvPython) }+ else { @("torch>=2.4,<2.11.0", "torchvision>=0.19,<0.26.0", "torchaudio>=2.4,<2.11.0") }+ $torchFixExit = Invoke-InstallCommand -Label "reinstall PyTorch ($expectedTorchTag)" { uv pip install --python $VenvPython @_fixSpecs --default-index $TorchIndexUrl --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio }if ($torchFixExit -ne 0) {Write-Host "[ERROR] Failed to reinstall PyTorch with the correct CUDA build (exit code $torchFixExit)" -ForegroundColor Redreturn (Exit-InstallFailure "Failed to reinstall PyTorch ($expectedTorchTag) (exit code $torchFixExit)" $torchFixExit)diff --git a/install.sh b/install.shindex 7ea17153dfc..25d71224e2a 100755--- a/install.sh+++ b/install.sh@@ -337,6 +337,9 @@ _gfx906_bnb_prune() {# and, on PyPI, first in 0.50.0. Keep this floor in step with the amd extra in# pyproject.toml and studio/install_python_stack.py._BNB_ROCM_PYPI_FALLBACK="bitsandbytes>=0.50.0"+# Intel XPU: separate constant, same floor by coincidence. 0.50.0 manylinux is the first with+# libbitsandbytes_xpu2025.so / _xpu2026.so; studio/setup.ps1's XPU pass uses the same floor.+_BNB_XPU_SPEC="bitsandbytes>=0.50.0"# bitsandbytes ships no ROCm binary in its aarch64 wheel at any version: the PyPI# 0.50.0 and continuous-release_main aarch64 wheels both carry only# libbitsandbytes_cpu.so plus CUDA variants. So neither install path below gives@@ -487,6 +490,7 @@ _tauri_torch_index_family() {*/cu128) echo "cu128" ;;*/cu130) echo "cu130" ;;*/cpu) echo "cpu" ;;+ */xpu) echo "xpu" ;;*/rocm[0-9]*.[0-9]*)_diag_family=${_diag_url##*/}case "$_diag_family" in@@ -522,6 +526,7 @@ _tauri_gpu_branch() {echo "rocm"fi ;;radeon) echo "rocm_radeon" ;;+ xpu) echo "xpu" ;;cpu) echo "cpu" ;;none) echo "no_torch" ;;*) echo "unknown" ;;@@ -2310,7 +2315,16 @@ if [ -x "$VENV_DIR/bin/python" ]; then# rebuilds the venv for clean state, but must keep the torch release the user# already has (see _previous_torch_pin below). Last line only: sitecustomize or# import-hook noise on stdout must not corrupt the version.- _PREV_TORCH_VER=$("$VENV_DIR/bin/python" -c \+ # Disk first, no interpreter: `import torch` can block forever on a wedged Intel driver,+ # and this runs before setup.sh's bounded probes. version.py carries the same label; the+ # interpreter stays as the fallback for a layout without one.+ _PREV_TORCH_VER=""+ for _prev_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do+ [ -f "$_prev_tv" ] || continue+ _PREV_TORCH_VER=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_prev_tv" | head -n 1)+ break+ done+ [ -n "$_PREV_TORCH_VER" ] || _PREV_TORCH_VER=$("$VENV_DIR/bin/python" -c \"import torch; print(torch.__version__)" 2>/dev/null | tail -n 1 || true)# New layout already exists — replace only after preserving rollback copy.substep "preserving existing environment for rollback..."@@ -2856,11 +2870,14 @@ get_torch_index_url() {}# ── Torch flavor helpers (to repair a stale CPU / wrong-CUDA wheel) ──-# torch.__version__ ($1) -> flavor tag (cuXXX / rocm / cpu); untagged wheel = cpu.+# torch.__version__ ($1) -> flavor tag (cuXXX / rocm / xpu / cpu); untagged wheel = cpu.+# The xpu arm is load-bearing: without it a +xpu wheel reads as "cpu" and is force-reinstalled+# on every run. Parity with the ps1 side._torch_flavor_tag() {case "$1" in*+cu[0-9]*) printf '%s\n' "$1" | sed -n 's/.*+\(cu[0-9][0-9]*\).*/\1/p' ;;*+rocm*) echo "rocm" ;;+ *+xpu*) echo "xpu" ;;*+cpu*) echo "cpu" ;;"") echo "" ;;*) echo "cpu" ;;@@ -2998,7 +3015,7 @@ _install_torch_default_index() {fi}-# Expected tag from the index leaf ($1): cuXXX / cpu / rocm (rocmX.Y and gfx* ->+# Expected tag from the index leaf ($1): cuXXX / cpu / xpu / rocm (rocmX.Y and gfx* -># rocm). Empty on an unknown leaf (odd mirror) so the repair safely no-ops._expected_torch_flavor_tag() {_leaf=$(_torch_index_url_leaf "$1")@@ -3012,6 +3029,8 @@ _expected_torch_flavor_tag() {esac;;cpu) echo "cpu" ;;+ # Intel XPU (SYCL) is a GPU flavor, so a pinned xpu index repairs a stale CPU wheel.+ xpu) echo "xpu" ;;# Exact rocm/gfx families only; a custom rocm*-suffixed leaf -> "" (custom).*)if _is_pip_rocm_family_leaf "$_leaf"; then echo "rocm"; else echo ""; fi@@ -3019,8 +3038,23 @@ _expected_torch_flavor_tag() {esac}+# Installed torch's version label, for expected-flavor tag $1. The xpu path reads it off disk+# (as setup.sh's fast-path escape does): `import torch` can block forever on a wedged Intel+# driver. Other families keep the interpreter read.+_installed_torch_version_for_tag() {+ if [ "$1" = "xpu" ]; then+ for _itv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do+ [ -f "$_itv" ] || continue+ sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_itv" | head -n 1+ return+ done+ return+ fi+ "$_VENV_PY" -c "import torch; print(torch.__version__)" 2>/dev/null || true+}+# Whether index ($1) supports a plain --default-index reinstall. pytorch.org cuXXX /-# rocmX.Y AND the repo.amd.com gfx* indexes are all PEP 503 simple indexes that uv+# xpu / rocmX.Y AND the repo.amd.com gfx* indexes are all PEP 503 simple indexes that uv# resolves (torch + every transitive dep) via --default-index -- the same URLs the# fresh-install paths above already use -- so a stale wheel is auto-repairable.# Unknown/odd-mirror leaves -> no, so we warn rather than risk a wrong reinstall.@@ -3028,6 +3062,8 @@ _torch_index_repairable() {_leaf=$(_torch_index_url_leaf "$1")case "$_leaf" incu[0-9]*) echo "yes" ;;+ # /whl/xpu is a plain PEP 503 index (oneAPI runtime and triton-xpu are ordinary deps).+ xpu) echo "yes" ;;# Only EXACT rocm/gfx families resolve via --default-index; a suffixed leaf is verbatim.*)if _is_pip_rocm_family_leaf "$_leaf"; then echo "yes"; else echo "no"; fi@@ -3444,6 +3480,14 @@ case "$_torch_index_leaf" inTORCHVISION_CONSTRAINT="torchvision>=0.19,<0.27.0"TORCHAUDIO_CONSTRAINT="torchaudio>=2.4,<2.12.0";;+ # Floor 2.6, not the generic 2.4: unsloth/models/_utils.py raises at import for an XPU+ # device below it, so a mirror serving an older +xpu wheel would install something that+ # cannot run. Reached only through an explicit pin (no Intel autodetect on this side).+ xpu)+ TORCH_CONSTRAINT="torch>=2.6,<2.11.0"+ TORCHVISION_CONSTRAINT="torchvision>=0.21,<0.26.0"+ TORCHAUDIO_CONSTRAINT="torchaudio>=2.6,<2.11.0"+ ;;esac# A pinned custom/unknown-leaf index (/simple, /current, /cu128-private) has no curated@@ -4205,7 +4249,7 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; then_expected_torch_tag=$(_expected_torch_flavor_tag "$TORCH_INDEX_URL")# Only act when a GPU build is expected (cuXXX / rocm); cpu and unknown skip.if [ -n "$_expected_torch_tag" ] && [ "$_expected_torch_tag" != "cpu" ]; then- _installed_torch_ver=$("$_VENV_PY" -c "import torch; print(torch.__version__)" 2>/dev/null || true)+ _installed_torch_ver=$(_installed_torch_version_for_tag "$_expected_torch_tag")_installed_torch_tag=""[ -n "$_installed_torch_ver" ] && _installed_torch_tag=$(_torch_flavor_tag "$_installed_torch_ver")# Repair when flavor is wrong AND the index is plain --default-index reinstallable@@ -4215,7 +4259,7 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; thensubstep "PyTorch flavor mismatch (installed $_installed_torch_tag, need $_expected_torch_tag) -- reinstalling correct build..."_install_torch_default_index \--reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio- _installed_torch_ver=$("$_VENV_PY" -c "import torch; print(torch.__version__)" 2>/dev/null || true)+ _installed_torch_ver=$(_installed_torch_version_for_tag "$_expected_torch_tag")_installed_torch_tag=""[ -n "$_installed_torch_ver" ] && _installed_torch_tag=$(_torch_flavor_tag "$_installed_torch_ver")fi@@ -4229,6 +4273,20 @@ if [ "$SKIP_TORCH" = false ] && [ -n "${TORCH_INDEX_URL:-}" ]; thenfifi+# ── Intel XPU: bitsandbytes with XPU kernels ──+# manylinux 0.50.0 is the first with libbitsandbytes_xpu2025.so / _xpu2026.so, and nothing else+# here touches bitsandbytes on this index (both ROCm passes are gated on that family), so a+# migrated environment would keep a pre-XPU build and lose 4-bit QLoRA.+# Out here rather than in the install branches above: those are mutually exclusive, so a copy in+# the fresh arm never runs for a migrated env (which is how the ROCm passes ended up duplicated).+# --no-deps: torch and numpy are already in. Best effort, like the Windows pass.+if [ "$SKIP_TORCH" = false ] && [ "$(_torch_index_url_leaf "${TORCH_INDEX_URL:-}")" = "xpu" ]; then+ substep "installing bitsandbytes with Intel XPU kernels..."+ run_install_cmd "install bitsandbytes (xpu)" uv pip install --python "$_VENV_PY" \+ --no-deps "$_BNB_XPU_SPEC" || \+ substep "[WARN] could not install an XPU-capable bitsandbytes; 4-bit QLoRA may be unavailable." "$C_WARN"+fi+# ── CI only: overlay a source checkout over the package just installed ──# Not a consumer knob: no flag, absent from --help, ignored unless# UNSLOTH_CI_SOURCE_OVERLAY names a directory holding a pyproject.toml.diff --git a/studio/frontend/src/features/settings/tabs/about-tab.tsx b/studio/frontend/src/features/settings/tabs/about-tab.tsxindex c2436e606d5..46700983223 100644--- a/studio/frontend/src/features/settings/tabs/about-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/about-tab.tsx@@ -6,8 +6,8 @@ import { Button } from "@/components/ui/button";import { usePlatformStore } from "@/config/env";import { getAuthToken } from "@/features/auth";import { removeTrainingUnloadGuard } from "@/features/training";-import { useHardwareInfo } from "@/hooks/use-hardware-info";-import { useT } from "@/i18n";+import { type HardwareInfo, useHardwareInfo } from "@/hooks/use-hardware-info";+import { type TranslationKey, useT } from "@/i18n";import { apiUrl, isTauri } from "@/lib/api-base";import {ArrowUpRight01Icon,@@ -73,11 +73,31 @@ async function fetchInstallSource(): Promise<UpdateInstallSource> {}}+// Every accelerator runtime the backend reported, not just the first: a dual CUDA+XPU build in+// XPU mode reports both, so returning CUDA alone hid the XPU row. Module scope on purpose --+// inlining this pushes AboutTab past the cognitive-complexity ceiling.+type RuntimeRow = { labelKey: TranslationKey; version: string };++function acceleratorRuntimes(hw: HardwareInfo): RuntimeRow[] {+ const rows: RuntimeRow[] = [];+ if (hw.cuda) {+ rows.push({ labelKey: "settings.about.cuda", version: hw.cuda });+ }+ if (hw.rocm) {+ rows.push({ labelKey: "settings.about.rocm", version: hw.rocm });+ }+ if (hw.xpu) {+ rows.push({ labelKey: "settings.about.xpu", version: hw.xpu });+ }+ return rows;+}+export function AboutTab() {const t = useT();const deviceType = usePlatformStore((s) => s.deviceType);const defaultShell = deviceType === "windows" ? "windows" : "unix";const hw = useHardwareInfo();+ const runtimes = acceleratorRuntimes(hw);const updateSectionRef = useRef<HTMLDivElement | null>(null);const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);const consumeScrollTarget = useSettingsDialogStore(@@ -155,7 +175,7 @@ export function AboutTab() {</SettingsSection></div>- {hw.gpus.length > 0 || hw.cuda || hw.rocm ? (+ {hw.gpus.length > 0 || runtimes.length > 0 ? (<SettingsSection title={t("settings.about.hardware")}>{hw.gpus.map((gpu, i) => (<SettingsRow@@ -176,17 +196,13 @@ export function AboutTab() {</code></SettingsRow>))}- {hw.cuda || hw.rocm ? (- <SettingsRow- label={- hw.cuda ? t("settings.about.cuda") : t("settings.about.rocm")- }- >+ {runtimes.map((rt) => (+ <SettingsRow key={rt.labelKey} label={t(rt.labelKey)}><code className="font-mono text-xs text-muted-foreground">- {hw.cuda ?? hw.rocm}+ {rt.version}</code></SettingsRow>- ) : null}+ ))}</SettingsSection>) : null}diff --git a/studio/frontend/src/hooks/use-hardware-info.ts b/studio/frontend/src/hooks/use-hardware-info.tsindex 4d63d4d6af7..1db96016d93 100644--- a/studio/frontend/src/hooks/use-hardware-info.ts+++ b/studio/frontend/src/hooks/use-hardware-info.ts@@ -22,6 +22,9 @@ export interface HardwareInfo {torch: string | null;cuda: string | null;rocm: string | null;+ // Intel XPU (SYCL). The backend always emitted this; without it the About tab shows no+ // runtime row at all on an Arc host, where cuda and rocm are both null.+ xpu: string | null;transformers: string | null;unsloth: string | null;llamaCpp: string | null;@@ -42,6 +45,7 @@ const DEFAULT: HardwareInfo = {torch: null,cuda: null,rocm: null,+ xpu: null,transformers: null,unsloth: null,llamaCpp: null,@@ -95,6 +99,7 @@ async function fetchOnce(): Promise<HardwareInfo> {torch: data?.versions?.torch ?? null,cuda: data?.versions?.cuda ?? null,rocm: data?.versions?.rocm ?? null,+ xpu: data?.versions?.xpu ?? null,transformers: data?.versions?.transformers ?? null,unsloth: data?.versions?.unsloth ?? null,llamaCpp: data?.llama_cpp ?? null,diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 13e00196000..aa40f2fb612 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -956,6 +956,7 @@ export const ar = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "التحديث",help: "مساعدة",documentation: "الوثائق",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 8af7de7081a..b903b529c3f 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -993,6 +993,7 @@ export const de = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Update",help: "Hilfe",documentation: "Dokumentation",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 79a9b62040d..c9d86d1756d 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -953,6 +953,7 @@ export const en = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Update",help: "Help",documentation: "Documentation",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex dcaa1c9fbe8..91da418333b 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -985,6 +985,7 @@ export const es = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Actualizar",help: "Ayuda",documentation: "Documentación",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 10d2e66f888..137846d197e 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -989,6 +989,7 @@ export const fr = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Mise à jour",help: "Aide",documentation: "Documentation",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 2f46ae4d6aa..1860e23cec9 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -960,6 +960,7 @@ export const hi = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "अपडेट",help: "सहायता",documentation: "दस्तावेज़",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex db02522913f..34c1b5e3ed7 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -925,6 +925,7 @@ export const ja = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "アップデート",help: "ヘルプ",documentation: "ドキュメント",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex c715c61cdb8..db19c0e88b1 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -955,6 +955,7 @@ export const ko = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "업데이트",help: "도움말",documentation: "문서",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 426dd1a682d..99ef522cea8 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -966,6 +966,7 @@ export const ptBR = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Atualização",help: "Ajuda",documentation: "Documentação",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex fbb35a62911..4e302f00ead 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -964,6 +964,7 @@ export const ru = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "Обновление",help: "Справка",documentation: "Документация",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex b5f0e2c50c3..2a6c85e3895 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -930,6 +930,7 @@ export const zhCN = {gpu: "GPU",cuda: "CUDA",rocm: "ROCm",+ xpu: "XPU",updates: "更新",help: "帮助",documentation: "文档",diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 86d87cbb08b..4378f111186 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -12,6 +12,7 @@ activated. Expects `pip` and `python` on PATH to point at the venv.from __future__ import annotationsimport glob+import importlib.utilimport osimport platformimport re@@ -1476,6 +1477,27 @@ def _rocm_pin_family_mismatch(pin_url: str, installed_ver: str) -> bool:return _pin_is_211 != _inst_is_211+# Intel XPU wheels. Own range, not the CUDA spec above: the xpu index serves past our tested+# ceiling, and the floor is 2.6 because unsloth/models/_utils.py raises at import for an XPU+# device below it. Kept in step with install.sh by tests/sh/test_xpu_torch_spec_parity.sh.+_XPU_TORCH_PKG_SPEC: tuple[str, str, str] = (+ "torch>=2.6,<2.11.0",+ "torchvision>=0.21,<0.26.0",+ "torchaudio>=2.6,<2.11.0",+)+++def _explicit_xpu_torch_index_url() -> "str | None":+ """The pinned wheel index URL when it names the XPU family (leaf == xpu), else None.++ Intel support is a pin, never autodetection, so the pin is the only signal there is.+ """+ url = _explicit_torch_index_url()+ if url is None:+ return None+ return url if _torch_index_leaf(url) == "xpu" else None++def _explicit_cpu_torch_index_url() -> "str | None":"""The pinned wheel index URL when it names the CPU family (leaf == cpu), else None.@@ -1657,6 +1679,342 @@ def _ensure_cuda_torch() -> None:)+def _ensure_xpu_torch() -> None:+ """Install XPU torch when an explicit XPU pin is set but the venv has another build.++ Counterpart to _ensure_cpu_torch for Intel. `unsloth studio update` runs setup.sh, never+ install.sh, so its XPU install path is unreachable there; and an xpu leaf names no family+ the cuda/rocm helpers know, so they skip it and the CPU wheel survives the pin forever.++ Windows is excluded on purpose: setup.ps1 owns torch there and already installs the XPU+ trio itself, so acting here would fight it. macOS has no XPU at all.+ """+ if NO_TORCH or IS_MACOS or IS_WINDOWS:+ return+ pin = _explicit_xpu_torch_index_url()+ if pin is None:+ return++ # A non-zero exit means torch is missing or un-importable; the pin installs it below+ # either way. Bounded like every other probe here.+ try:+ probe = subprocess.run(+ [+ sys.executable,+ "-c",+ (+ # Flavour AND range: a migrated 2.5+xpu venv is broken, not correct, so the+ # tag alone is not enough. Range matches _XPU_TORCH_PKG_SPEC.+ "import torch; "+ "ver = getattr(torch, '__version__', '').lower(); "+ "rel = ver.split('+')[0].split('.'); "+ "n = tuple(int(x) for x in rel[:2] if x.isdigit()); "+ "ok = '+xpu' in ver and len(n) == 2 and (2, 6) <= n < (2, 11); "+ "print('ok' if ok else 'repair')"+ ),+ ],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ timeout = 90,+ )+ except (OSError, subprocess.TimeoutExpired):+ # Inconclusive, so ask the disk, which answers without loading SYCL. An unsupported or+ # missing wheel does need the reinstall (the resolver keeps a too-old +xpu wheel because+ # it satisfies the base range). A supported one means the Intel DRIVER is stalled, and+ # reinstalling never fixes a driver -- it would just re-download the trio twice per+ # update, since this helper runs at two repair points.+ if _xpu_wheel_supported_on_disk():+ print(+ _red(+ " torch did not respond in time; the installed XPU build is supported, "+ "so this is the Intel GPU compute driver -- update it and re-run"+ )+ )+ return+ probe = None+ _lines = (+ [+ line.strip()+ for line in probe.stdout.decode(errors = "replace").splitlines()+ if line.strip()+ ]+ if probe is not None+ else []+ )+ if probe is None:+ _why = "torch could not be probed"+ elif probe.returncode == 0:+ if not _lines:+ return # unreadable -- the base install step handles a missing torch+ if _lines[-1] == "ok":+ return # already the pinned family, in the supported range+ _why = "torch is not a supported XPU build"+ else:+ _why = "torch cannot import"++ print(+ f" {_why} but an explicit XPU index is pinned -- reinstalling XPU torch from "+ f"{_strip_index_url_credentials(pin)}"+ )+ _torch_pkg, _vision_pkg, _audio_pkg = _XPU_TORCH_PKG_SPEC+ pip_install(+ "XPU torch repair",+ "--force-reinstall",+ "--no-cache-dir",+ _torch_pkg,+ _vision_pkg,+ _audio_pkg,+ "--index-url",+ pin,+ constrain = False,+ )+++def _installed_torch_version_label() -> str:+ """torch's full version string, read OFF DISK without importing torch.++ Neither obvious route works here: importlib.metadata drops the local label (it reports+ 2.9.1 for a 2.9.1+xpu wheel, so the flavour is gone), and `import torch` loads the SYCL+ runtime, which can block indefinitely on a wedged Intel driver. find_spec locates the+ package without executing it. Empty when torch is absent or unreadable.+ """+ try:+ # torch may have been installed earlier in THIS run, after the path finders cached+ # site-packages' directory listing.+ importlib.invalidate_caches()+ spec = importlib.util.find_spec("torch")+ except (ImportError, ValueError):+ return ""+ if spec is None or not spec.origin:+ return ""+ try:+ text = (+ Path(spec.origin).with_name("version.py").read_text(encoding = "utf-8", errors = "replace")+ )+ except OSError:+ return ""+ match = re.search(r"""^__version__\s*=\s*['"]([^'"]*)['"]""", text, re.MULTILINE)+ return match.group(1) if match else ""+++def _xpu_wheel_supported_on_disk() -> bool:+ """True when torch ON DISK is a +xpu wheel inside the supported release range.++ The same flavour-and-range test the interpreter probe runs, but off version.py, so it+ still answers when `import torch` cannot. Floor 2.6 because unsloth/models/_utils.py+ raises at import for an XPU device below it; ceiling from _XPU_TORCH_PKG_SPEC.+ """+ label = _installed_torch_version_label().lower()+ if "+xpu" not in label:+ return False+ nums = tuple(int(p) for p in label.split("+")[0].split(".")[:2] if p.isdigit())+ return len(nums) == 2 and (2, 6) <= nums < (2, 11)+++def _ensure_venv_pip() -> bool:+ """Make `python -m pip` work in the target venv, bootstrapping it if needed.++ `uv venv` is created without --seed, so a fresh venv has no pip at all. Mirrors the+ bootstrap install.sh already does before its pre-release bitsandbytes wheel.+ """++ def _has_pip() -> bool:+ try:+ return (+ subprocess.run(+ [sys.executable, "-m", "pip", "--version"],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ timeout = 90,+ ).returncode+ == 0+ )+ except (OSError, subprocess.TimeoutExpired):+ return False++ if _has_pip():+ return True+ try:+ subprocess.run(+ [sys.executable, "-m", "ensurepip", "--upgrade"],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ timeout = 300,+ )+ except (OSError, subprocess.TimeoutExpired):+ pass+ if _has_pip():+ return True+ pip_install_try("pip (bootstrap)", "pip", constrain = False)+ return _has_pip()+++def _ensure_xpu_triton() -> None:+ """Replace generic Triton with the XPU build torch asks for.++ Generic `triton` and torch's `pytorch-triton-xpu` / `triton-xpu` both own the top-level+ `triton` package, and resolving unsloth against a pinned +xpu torch pulls BOTH (uv reports+ pytorch-triton-xpu 3.5.0 alongside triton 3.7.1), so the CUDA-oriented build can land last+ and torch.compile then loads the wrong library on an Intel GPU.++ Lives here, not in install.sh, because install.sh runs setup.sh which runs this file: one+ copy covers the fresh install AND `unsloth studio update`, which never touches install.sh.+ Windows is excluded -- studio/setup.ps1 owns the same swap there.+ """+ if NO_TORCH or IS_MACOS or IS_WINDOWS:+ return+ pin = _explicit_xpu_torch_index_url()+ if pin is None:+ # A one-shot pin (UNSLOTH_TORCH_INDEX_FAMILY=xpu ./install.sh) is gone by the next plain+ # update, but its +xpu wheel is not and a dependency pass can pull generic triton back+ # in, so the INSTALLED wheel is the pin. setup.sh keys its bnb floor on the same signal.+ if "+xpu" not in _installed_torch_version_label().lower():+ return+ pin = f"{_PYTORCH_WHL_BASE}/xpu"++ try:+ probe = subprocess.run(+ [+ sys.executable,+ "-c",+ (+ "import importlib.metadata as m\n"+ "try:\n"+ " reqs = m.requires('torch') or []\n"+ "except Exception:\n"+ " reqs = []\n"+ "print('SPEC=' + next((r.split(';')[0].strip() "+ "for r in reqs if 'triton' in r.lower()), ''))\n"+ "print('GENERIC=' + next((d.version for d in m.distributions() "+ "if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton'), ''))\n"+ ),+ ],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ timeout = 90,+ )+ except (OSError, subprocess.TimeoutExpired):+ return+ if probe.returncode != 0:+ return+ out = probe.stdout.decode(errors = "replace")+ spec = next((ln[5:].strip() for ln in out.splitlines() if ln.startswith("SPEC=")), "")+ generic = next((ln[8:].strip() for ln in out.splitlines() if ln.startswith("GENERIC=")), "")+ # Act only when generic triton is present AND torch asks for an XPU triton; anything else+ # means torch is not the +xpu wheel this assumes.+ if not generic or "xpu" not in spec.lower():+ return++ print(f" replacing triton {generic} with {spec} (Intel XPU)")+ if not _ensure_venv_pip():+ print(+ _red(+ f" no pip in the venv to fetch {spec}; generic triton {generic} left in "+ "place -- it shadows torch XPU triton, so torch.compile will not use the XPU"+ )+ )+ return++ # Fetch, THEN uninstall, THEN install from the file. The uninstall cannot go last: the shared+ # paths live in generic triton's OWN record, so removing it afterwards deletes what the XPU+ # build just wrote. Pre-fetching stops a dead mirror stranding the venv between the two+ # steps. uv has no `pip download`, hence pip here.+ tmp = tempfile.mkdtemp(prefix = "unsloth_triton_xpu_")+ try:+ _dl_cmd = [+ sys.executable,+ "-m",+ "pip",+ "download",+ "--no-deps",+ "--only-binary=:all:",+ "-d",+ tmp,+ spec,+ "--index-url",+ pin,+ ]+ try:+ dl = subprocess.run(+ _dl_cmd,+ # Same scrub every other pinned install gets: PIP_NO_INDEX would ignore+ # --index-url outright, and PIP_EXTRA_INDEX_URL / PIP_FIND_LINKS are consulted in+ # addition to it, so an inherited environment could serve the wheel from+ # somewhere the pin never named.+ env = _install_env_for_cmd(_dl_cmd),+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ timeout = 900,+ )+ except (OSError, subprocess.TimeoutExpired):+ dl = None+ wheels = glob.glob(os.path.join(tmp, "*.whl"))+ # The exit code alone is not enough: no wheel on disk means nothing to install from.+ if dl is None or dl.returncode != 0 or not wheels:+ print(+ _red(+ f" could not fetch {spec}; generic triton {generic} left in place -- "+ "it shadows torch XPU triton, so torch.compile will not use the XPU"+ )+ )+ return+ removed = subprocess.run(+ [sys.executable, "-m", "pip", "uninstall", "-y", "triton"],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ )+ if removed.returncode != 0:+ # A read-only or locked venv leaves generic triton REGISTERED; installing over it+ # would let a later upgrade or uninstall delete the shared files again. Change+ # nothing.+ print(+ _red(+ f" could not remove generic triton {generic}; leaving it in place -- it "+ "shadows torch XPU triton, so torch.compile will not use the XPU"+ )+ )+ return+ # Past this point the venv has NO triton: the uninstall took the shared top-level files+ # with it. pip_install, not pip_install_try -- a warning would let the caller write a+ # completion manifest over a venv whose torch.compile is broken, which the next update+ # then fast-paths past (no generic distribution is left to trigger on).+ pip_install(+ "triton (Intel XPU)",+ "--force-reinstall",+ "--no-deps",+ wheels[0],+ constrain = False,+ )+ finally:+ shutil.rmtree(tmp, ignore_errors = True)+++def _installed_torch_label_on_disk() -> str:+ """torch.__version__ read from torch/version.py, launching no interpreter.++ `import torch` loads the SYCL runtime and can block indefinitely on a wedged Intel driver+ -- which is the host an explicit pin is meant to rescue, so the classifier cannot depend+ on the import succeeding. find_spec locates the package without importing it.+ """+ try:+ spec = importlib.util.find_spec("torch")+ if spec is None or not spec.origin:+ return ""+ text = (Path(spec.origin).parent / "version.py").read_text(+ encoding = "utf-8", errors = "replace"+ )+ except Exception:+ return ""+ m = re.search(r"^__version__ = '([^']*)'", text, re.M)+ return m.group(1).lower() if m else ""+++def _is_gpu_torch_label(label: str) -> bool:+ """GPU build by local label alone. Weaker than the probe (which also reads+ torch.version.hip/cuda), so it is only used when the probe could not run."""+ return "+xpu" in label or "+rocm" in label or bool(re.search(r"\+cu\d+", label))++def _ensure_cpu_torch() -> None:"""Reinstall CPU torch when an explicit CPU pin is set but the venv has a GPU build.@@ -1682,7 +2040,10 @@ def _ensure_cpu_torch() -> None:"hip = getattr(torch.version, 'hip', '') or ''; ""cuda = getattr(torch.version, 'cuda', '') or ''; ""ver = getattr(torch, '__version__', '').lower(); "- "gpu = bool(hip) or 'rocm' in ver or bool(cuda) or bool(re.search(r'\\+cu\\d+', ver)); "+ # '+xpu' too: an XPU wheel sets neither torch.version.cuda nor .hip, so+ # without it a working Intel build reads as "cpu" and a CPU pin over it does+ # nothing. Local label, since torch.version.xpu is None on some builds.+ "gpu = bool(hip) or 'rocm' in ver or bool(cuda) or bool(re.search(r'\\+cu\\d+', ver)) or '+xpu' in ver; ""print('gpu' if gpu else 'cpu')"),],@@ -1691,8 +2052,13 @@ def _ensure_cpu_torch() -> None:timeout = 90,)except (OSError, subprocess.TimeoutExpired):- return- if probe.returncode != 0:+ # A hung import is the wedged-driver case this pin exists to rescue, so returning here+ # made the pin a no-op on exactly that host. Classify off disk instead, and only go on+ # for a GPU label: a merely slow CPU-only box must not reinstall torch every update.+ if not _is_gpu_torch_label(_installed_torch_label_on_disk()):+ return+ probe = None+ if probe is None or probe.returncode != 0:# torch present but can't import. The explicit CPU pin forces this pass (failed# probe) and the base update won't reinstall an already-installed torch, so# reinstall from the pin (self-resolving, no loop).@@ -1753,7 +2119,7 @@ def _ensure_rocm_torch() -> None:global _rocm_windows_torch_installed# install.sh's resolved backend is authoritative: skip ROCm when it already chose a# non-ROCm family (avoids re-detecting in a subprocess that may see a different env).- if _TORCH_BACKEND in ("cuda", "cpu"):+ if _TORCH_BACKEND in ("cuda", "cpu", "xpu"):return# An explicit unknown-family pin was applied VERBATIM at install time; leave it alone.if _explicit_unknown_family_torch_index_url() is not None:@@ -2296,6 +2662,10 @@ if not _TORCH_BACKEND:_TORCH_BACKEND = "rocm"elif _idx_leaf == "cpu":_TORCH_BACKEND = "cpu"+ elif _idx_leaf == "xpu":+ # Without this the leaf falls through as unknown and the standalone update never acts+ # on an authoritative XPU pin -- see _ensure_xpu_torch.+ _TORCH_BACKEND = "xpu"elif _is_cuda_family_leaf(_idx_leaf):# Require a digit after "cu" so /current or /custom is NOT branded CUDA (a wrong backend# makes _ensure_rocm_torch return early on AMD hosts). An unknown leaf keeps "" so the@@ -3142,7 +3512,11 @@ def install_python_stack() -> int:_progress(_torch_step_label("check"))_ensure_cuda_torch()_ensure_rocm_torch()+ _ensure_xpu_torch()_ensure_cpu_torch()+ # Last, after every torch migration: the swap keys off the installed +xpu label, so a+ # CPU pin over an XPU venv would leave XPU triton under a CPU torch.+ _ensure_xpu_triton()# Windows + AMD GPU: warn if ROCm torch was not installed (wrong Python# version or unknown ROCm version).@@ -3338,7 +3712,11 @@ def install_python_stack() -> int:_progress(_torch_step_label("final"))_ensure_cuda_torch()_ensure_rocm_torch()+ _ensure_xpu_torch()_ensure_cpu_torch()+ # Last, after every torch migration: the swap keys off the installed +xpu label, so a+ # CPU pin over an XPU venv would leave XPU triton under a CPU torch.+ _ensure_xpu_triton()# 14. Final check (silent; third-party conflicts are expected)subprocess.run(diff --git a/studio/setup.ps1 b/studio/setup.ps1index 86cae6274c6..433db7c46d0 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -760,6 +760,182 @@ function Get-RocmPinStaleTags {}}+# Bounded "ask python a question" probe, shared by every torch probe below: a wedged torch import+# or a hanging Intel driver init would block a bare `& python -c ...` forever. ProcessStartInfo,+# not &, so stderr cannot trip $ErrorActionPreference; BOTH streams drain async so a noisy import+# cannot deadlock on a full pipe; WaitForExit bounds the wait and kills the child. Every failure+# reads as .Ok = $false. Mirrors install.ps1's copy.+function Invoke-BoundedPythonProbe {+ param([string]$PythonExe, [string]$Code, [int]$TimeoutSec = 30)+ $result = [pscustomobject]@{ Ok = $false; Output = "" }+ if (-not $PythonExe -or -not $Code) { return $result }+ try {+ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = $PythonExe+ $psi.Arguments = "-c `"$Code`""+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $proc = [System.Diagnostics.Process]::Start($psi)+ $outTask = $proc.StandardOutput.ReadToEndAsync()+ $errTask = $proc.StandardError.ReadToEndAsync()+ if (-not $proc.WaitForExit($TimeoutSec * 1000)) {+ try { $proc.Kill() } catch {}+ return $result+ }+ $result.Output = $outTask.GetAwaiter().GetResult()+ [void]$errTask.GetAwaiter().GetResult()+ $result.Ok = ($proc.ExitCode -eq 0)+ return $result+ } catch { return $result }+}++# True when $PythonExe's torch can actually drive an Intel GPU. Quiet on purpose: the three+# callers read a False differently. Only an XPU build can answer True, so a CPU build never+# vetoes a migration.+function Test-TorchXpuAvailable {+ param([string]$PythonExe)+ if (-not $PythonExe) { return $false }+ # Line-anchored so a stdout banner cannot hide the answer; a timeout reads as "no XPU".+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.xpu.is_available())'+ return ($probe.Ok -and $probe.Output -match '(?m)^\s*True\s*$')+}++# Post-install XPU runtime check. A WMI name match says the part is XPU-capable, not that the+# compute runtime works: on an old Intel driver the wheel installs fine, never initializes, and+# unsloth/device_type.py raises NotImplementedError at import -- a hard crash, not a chat-only+# downgrade. Warn only: the wheel is correct and a driver update fixes it.+function Assert-XpuRuntimeReady {+ param([string]$PythonExe)+ if (Test-TorchXpuAvailable -PythonExe $PythonExe) { return $true }+ substep "[WARN] PyTorch XPU is installed but torch.xpu.is_available() is False." "Yellow"+ substep " The Intel GPU driver is most likely too old -- PyTorch XPU on Windows" "Yellow"+ substep " needs Intel Graphics Driver 32.0.101.6739 (WHQL) or newer." "Yellow"+ substep " Update the driver, then re-run. See:" "Yellow"+ substep " https://unsloth.ai/docs/get-started/install/intel" "Yellow"+ return $false+}++# Bounded Win32_VideoController scan: the query can block forever on a degraded WMI repository,+# -ErrorAction only suppresses reported errors, and -OperationTimeoutSec is not enforced for the+# local COM session this uses, so out of process with a wall-clock kill is the only bound that+# holds. Ok = $false on an empty answer too, since a Windows host always has an adapter.+# Mirrors install.ps1's copy.+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 install.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+}++# The studio venv directory, guessed from the environment alone. The canonical $VenvDir is+# resolved ~1100 lines below, far past the hardware report, so the Intel scan needs its own+# read-only guess. Returns $null when there is nothing to look at; never creates or validates.+function Get-ProbableStudioVenvDir {+ $root = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $env:UNSLOTH_STUDIO_HOME.Trim() }+ elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $env:STUDIO_HOME.Trim() }+ else { $null }+ # Expand a leading ~ like the canonical resolver; without it the path stays cwd-relative.+ if ($root -and ($root -eq "~" -or $root -like "~/*" -or $root -like "~\*")) {+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }+ $rest = $root.Substring(1).TrimStart('/', '\')+ $root = if ($rest) { Join-Path $env:USERPROFILE $rest } else { $env:USERPROFILE }+ }+ if (-not $root) {+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }+ $root = Join-Path $env:USERPROFILE ".unsloth\studio"+ }+ $venv = Join-Path $root "unsloth_studio"+ if (Test-Path -LiteralPath $venv -PathType Container) { return $venv }+ return $null+}++# Is this venv's torch an XPU wheel? Read off disk, not through the interpreter: version.py+# carries the full local label ("2.9.1+xpu") and costs nothing, so a CPU-only host never pays for+# an `import torch`. The dist-info name is NOT usable -- pip normalises the local label out of it.+function Test-VenvTorchIsXpu {+ param([string]$VenvPath)+ if (-not $VenvPath) { return $false }+ try {+ $verPy = Join-Path $VenvPath "Lib\site-packages\torch\version.py"+ if (-not (Test-Path -LiteralPath $verPy)) { return $false }+ return [bool]((Get-Content -LiteralPath $verPy -TotalCount 40 -ErrorAction Stop) -match "__version__\s*=\s*'[^']*\+xpu")+ } catch { return $false }+}++# Same free disk read, plus the supported range: unsloth/models/_utils.py raises at import for an+# XPU device on torch < 2.6, so flavour alone would call a 2.5+xpu venv fine; 2.11 is the trio's+# ceiling. Flavour and range ONLY -- whether the runtime reaches the GPU is a driver question.+function Test-VenvTorchIsXpuSupported {+ param([string]$VenvPath)+ if (-not $VenvPath) { return $false }+ try {+ $verPy = Join-Path $VenvPath "Lib\site-packages\torch\version.py"+ if (-not (Test-Path -LiteralPath $verPy)) { return $false }+ $line = @(Get-Content -LiteralPath $verPy -TotalCount 40 -ErrorAction Stop |+ Where-Object { $_ -match "^__version__\s*=\s*'[^']*'" })[0]+ if (-not $line -or $line -notmatch "^__version__\s*=\s*'([^']*)'") { return $false }+ $label = $Matches[1].ToLowerInvariant()+ if ($label -notmatch '\+xpu') { return $false }+ if ($label -notmatch '^(\d+)\.(\d+)\b') { return $false }+ return ([int]$Matches[1] -eq 2 -and [int]$Matches[2] -ge 6 -and [int]$Matches[2] -lt 11)+ } catch { return $false }+}+# VS generator -> MSBuild BuildCustomizations dir; toolset tracks the VS major# (18->v180, 17->v170), defaulting to v170 when unparseable.function Get-VcBuildCustomizationsDir {@@ -1782,8 +1958,85 @@ if (-not $HasNvidiaSmi) {}}+# gfx arches AMD publishes Windows ROCm wheels for (repo.amd.com/rocm/whl/<family>). Hoisted+# above the Intel scan, which needs it: an unlisted arch gets CPU torch, so it must not outrank a+# usable Arc card. test_rocm_arch_table_parity.py keeps it in sync with $archFamilyMap below.+$_rocmWheelArches = @(+ "gfx1201", "gfx1200", # RDNA 4+ "gfx1151", "gfx1150", "gfx1152", # RDNA 3.5 (Strix Halo/Point, Krackan Point)+ "gfx1103", "gfx1102", "gfx1101", "gfx1100", # RDNA 3+ "gfx1036", "gfx1035", "gfx1034", "gfx1033", "gfx1032", "gfx1031", "gfx1030", # RDNA 2 (RX 6000)+ "gfx90a", "gfx908" # MI200 / MI100+)+# "AMD gets GPU wheels here", NOT "an AMD GPU is present": $HasROCm / $ROCmGfxArch are true on+# unmapped arches (Vega, RDNA1) too, and those install CPU torch.+$AmdHasGpuWheels = [bool]($script:ROCmGfxArch -and ($_rocmWheelArches -contains $script:ROCmGfxArch))++# Mirrors the Intel scan in install.ps1 so setup does not report "none (chat-only)" right after+# install.ps1 reported a usable Arc GPU. Self-contained, because `studio update` runs setup.ps1+# standalone. Same $AmdHasGpuWheels gate (an Arc card wins over an AMD host heading for CPU torch+# anyway) and the same Arc / Data Center match.+$script:IsIntelXpu = $false+# Set when the stale check below keeps an installed +xpu venv instead of wiping it. Separate from+# $script:IsIntelXpu on purpose: it steers the INSTALL, not the hardware report, which must stay+# honest about the NVIDIA GPU that is also in the machine.+$script:PreservedXpuVenv = $false+$IntelGpuLabel = $null+if (-not $HasNvidiaSmi -and -not $AmdHasGpuWheels) {+ try {+ # Bounded, registry as the fallback when WMI does not answer: an unbounded query hangs+ # `studio update`, a swallowed one silently reports no GPU.+ $_gpuScan = Invoke-BoundedVideoControllerScan+ # @() wraps the WHOLE if, not each branch: a one-element array unrolls on its way out,+ # making $_gpuNames a String on a single-adapter host and turning the += below into+ # string concatenation.+ $_gpuNames = @(if ($_gpuScan.Ok) { $_gpuScan.Names } else { Get-IntelRegistryAdapterNames })+ # One definition for both the reconciliation gate and the classification below.+ $_xpuNameRe = "(?i)Intel.*(Arc|Data Center GPU)"+ # On non-English Windows the WMI name carries no ASCII "Intel" for the classification+ # below. The registry helper resolves the PCI vendor id, so use it to RE-LABEL an adapter+ # WMI already reported, never to add one (an unmatched entry is a driver record outliving+ # its card). Gated on the absence of an XPU match, not of any Intel name: a hybrid laptop+ # reports "Intel UHD" next to a localized Arc.+ if ($_gpuScan.Ok -and -not ($_gpuNames | Where-Object { $_ -match $_xpuNameRe })) {+ foreach ($_reg in @(Get-IntelRegistryAdapterNames)) {+ foreach ($_wmiName in $_gpuNames) {+ if ($_wmiName -and $_reg.Contains($_wmiName)) { $_gpuNames += $_reg; break }+ }+ }+ }+ $xpuGpu = $_gpuNames | Where-Object { $_ -match $_xpuNameRe } | Select-Object -First 1+ if ($xpuGpu) { $script:IsIntelXpu = $true; $IntelGpuLabel = $xpuGpu }+ } catch {}+ # Neither WMI nor the registry recognised an adapter, so ask the environment: an installed+ # +xpu wheel whose runtime initialises proves the host better than a marketing name. The same+ # check runs ~1300 lines below, but AFTER the report just below, so without this an Arc user+ # on a wedged WMI is told no training GPU exists and then watches setup keep the XPU+ # environment. Own try, so a throwing scan or a junk UNSLOTH_STUDIO_HOME cannot abort setup.+ if (-not $script:IsIntelXpu) {+ try {+ $_probeVenv = Get-ProbableStudioVenvDir+ if (Test-VenvTorchIsXpu $_probeVenv) {+ $_probePy = Join-Path $_probeVenv "Scripts\python.exe"+ if (Test-TorchXpuAvailable -PythonExe $_probePy) {+ $script:IsIntelXpu = $true+ $IntelGpuLabel = "Intel XPU runtime (reported by PyTorch)"+ }+ }+ } catch {}+ }+}+if ($HasNvidiaSmi) {step "gpu" "NVIDIA GPU detected"+} elseif ($script:IsIntelXpu) {+ # Ranks above every AMD branch: only true when AMD gets no GPU wheel ($AmdHasGpuWheels gates+ # the scan above), so those branches would all end on CPU torch.+ Write-Host ""+ step "gpu" "Intel GPU detected" "Green"+ substep "$IntelGpuLabel"+ substep "PyTorch XPU (SYCL) wheels provide training and GPU inference on this GPU." "Cyan"+ Write-Host ""} elseif ($HasROCm) {step "gpu" $ROCmGpuLabel$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }@@ -1818,7 +2071,7 @@ if ($HasNvidiaSmi) {} else {Write-Host ""step "gpu" "none (chat-only / GGUF)" "Yellow"- substep "Training and GPU inference require an NVIDIA or AMD ROCm GPU." "Yellow"+ substep "Training and GPU inference require an NVIDIA, AMD ROCm, or Intel Arc GPU." "Yellow"Write-Host ""}@@ -3069,6 +3322,10 @@ Set-PersistedNoTorch -VenvPath $VenvDir -NoTorch $NoTorchMode# every accepted spelling to one value both sides parse identically.$env:UNSLOTH_NO_TORCH = if ($NoTorchMode) { "true" } else { "false" }$InstallerManagedSetup = $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -match '^(?i:true|1|yes)$'+# Only the stale-venv block below assigns this, but the XPU install reads it to decide whether to+# force-reinstall and a fresh install never enters that block. Declaring it keeps a caller's+# Set-StrictMode from making the read fatal.+$installedTorchTag = $nullif ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode) {$VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"$installedTorchTag = $null@@ -3077,35 +3334,37 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode$script:PinChangedForceReinstall = $falseif (Test-Path -LiteralPath $VenvPyExe) {- try {- $psi = New-Object System.Diagnostics.ProcessStartInfo- $psi.FileName = $VenvPyExe- $psi.Arguments = '-c "import torch; print(torch.__version__)"'- $psi.RedirectStandardOutput = $true- $psi.RedirectStandardError = $true- $psi.UseShellExecute = $false- $psi.CreateNoWindow = $true- $proc = [System.Diagnostics.Process]::Start($psi)- $torchVer = $proc.StandardOutput.ReadToEnd().Trim()- $finished = $proc.WaitForExit(30000)- if ($finished -and $proc.ExitCode -eq 0 -and $torchVer) {- if ($torchVer -match '\+(cu\d+)') {- $installedTorchTag = $Matches[1]- } elseif ($torchVer -match '\+rocm') {- # Any +rocm / gfx wheel -> generic "rocm" flavor (the exact version is- # repaired later by install_python_stack.py; here we only need the flavor).- $installedTorchTag = "rocm"- } elseif ($torchVer -match '\+cpu') {- $installedTorchTag = "cpu"- } else {- # Untagged wheel (plain "2.x.y" from PyPI) -> cpu.- $installedTorchTag = "cpu"- }+ # Bounded like every other torch probe: reading stdout to EOF before waiting would hang+ # setup forever on a wedged `import torch`, and an undrained stderr deadlocks on a noisy+ # import. An unreadable flavor -> rebuild.+ $_verProbe = Invoke-BoundedPythonProbe -PythonExe $VenvPyExe -Code 'import torch; print(torch.__version__)'+ $torchVer = $_verProbe.Output.Trim()+ if ($_verProbe.Ok -and $torchVer) {+ if ($torchVer -match '\+(cu\d+)') {+ $installedTorchTag = $Matches[1]+ } elseif ($torchVer -match '\+rocm') {+ # Any +rocm / gfx wheel -> generic "rocm" flavor (the exact version is+ # repaired later by install_python_stack.py; here we only need the flavor).+ $installedTorchTag = "rocm"+ } elseif ($torchVer -match '\+xpu') {+ # Without this arm a +xpu wheel reads as "cpu" and an Arc venv looks correct+ # while being CPU-only. Matches ConvertTo-TorchFlavorTag.+ $installedTorchTag = "xpu"+ } elseif ($torchVer -match '\+cpu') {+ $installedTorchTag = "cpu"} else {- if (-not $finished) { try { $proc.Kill() } catch {} }- $shouldRebuild = $true+ # Untagged wheel (plain "2.x.y" from PyPI) -> cpu.+ $installedTorchTag = "cpu"}- } catch {+ } elseif (Test-VenvTorchIsXpu -VenvPath $VenvDir) {+ # Bounding this probe made a timeout mean "rebuild", and the host most likely to+ # time out inside `import torch` is an Arc box with a stalled driver -- where+ # version.py still names a good +xpu wheel, and the stale path would DELETE $VenvDir.+ # Trust the disk and warn about the driver; other families keep rebuilding.+ $installedTorchTag = "xpu"+ substep "PyTorch did not respond in time but this venv holds an XPU build -- keeping it." "Yellow"+ substep "If training fails, update the Intel GPU compute driver." "Yellow"+ } else {$shouldRebuild = $true}} else {@@ -3114,6 +3373,17 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode}if (-not $shouldRebuild) {+ # The scan above only matches a WMI marketing name, so a throwing Get-CimInstance -- or+ # an Intel part outside the Arc|Data Center regex -- leaves $script:IsIntelXpu false, and+ # the chain below would expect "cpu", see "xpu" and WIPE a working XPU venv.+ # torch.xpu.is_available() on a +xpu wheel proves the host, so re-evaluate before the+ # stale decision. This repeats the scan's own gate, so NVIDIA / AMD keep winning.+ if ($installedTorchTag -eq "xpu" -and -not $script:IsIntelXpu -and+ -not $HasNvidiaSmi -and -not $AmdHasGpuWheels -and+ (Test-TorchXpuAvailable -PythonExe $VenvPyExe)) {+ $script:IsIntelXpu = $true+ substep "Intel XPU runtime confirmed by PyTorch -- keeping this XPU environment." "Cyan"+ }$_pinnedIdx = Get-PinnedTorchIndexUrl$_expectedKnown = $trueif ($_pinnedIdx) {@@ -3127,9 +3397,9 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode$_rocmTags = Get-RocmPinStaleTags -PinLeaf $_pinLeaf -TorchVersion $torchVer$expectedTorchTag = $_rocmTags.Expected$installedTorchTag = $_rocmTags.Installed- } elseif ((Test-CudaFamilyLeaf $_pinLeaf) -or $_pinLeaf -eq 'cpu') {- # cu*/cpu leaves stay specific so a cu126-vs-cu128 mismatch rebuilds;- # /custom and /current fall through to the unknown-index branch below.+ } elseif ((Test-CudaFamilyLeaf $_pinLeaf) -or $_pinLeaf -eq 'cpu' -or $_pinLeaf -eq 'xpu') {+ # cu*/cpu/xpu leaves stay specific so a cu126-vs-cu128 (or cpu-vs-xpu) mismatch+ # is caught; /custom and /current fall through to the unknown-index branch below.$expectedTorchTag = $_pinLeaf} else {# Custom index whose leaf is not a torch flavor (a /simple mirror): the@@ -3139,19 +3409,19 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode}} elseif ($HasNvidiaSmi) {$expectedTorchTag = Get-PytorchCudaTag+ } elseif ($script:IsIntelXpu) {+ # Arc / Data Center host: the install below selects the xpu index. BEFORE the AMD+ # arm -- both can be true on an unmapped-arch AMD box, where xpu is what gets+ # installed. A CPU wheel is not wiped (the xpu install force-reinstalls over it in+ # place), so expect "cpu" there; a cu*/rocm wheel still rebuilds.+ $expectedTorchTag = if ($installedTorchTag -eq "cpu") { "cpu" } else { "xpu" }} elseif ($HasROCm -or $script:ROCmGfxArch) {# AMD/ROCm host with no explicit pin: an existing +rocm wheel is correct (gfx arch# counts even when $HasROCm is false). But only the arches the install path maps to a# repo.amd.com index get ROCm torch; an unmapped arch installs CPU, so expect "cpu"# for those or a correct CPU venv rebuilds every update.- $_rocmWheelArches = @(- "gfx1201", "gfx1200", # RDNA 4- "gfx1151", "gfx1150", "gfx1152", # RDNA 3.5 (Strix Halo/Point, Krackan Point)- "gfx1103", "gfx1102", "gfx1101", "gfx1100", # RDNA 3- "gfx1036", "gfx1035", "gfx1034", "gfx1033", "gfx1032", "gfx1031", "gfx1030", # RDNA 2 (RX 6000)- "gfx90a", "gfx908" # MI200 / MI100- )- if ($script:ROCmGfxArch -and ($_rocmWheelArches -contains $script:ROCmGfxArch)) {+ # $_rocmWheelArches is defined above the Intel scan (that gate needs it too).+ if ($AmdHasGpuWheels) {# A correct +rocm wheel is not stale. A CPU wheel on a supported AMD arch is# NOT wiped either (the AMD Windows ROCm override below upgrades it in place);# expect "cpu" for that case. A wrong CUDA wheel still rebuilds.@@ -3179,6 +3449,20 @@ if ((Test-Path -LiteralPath $VenvDir -PathType Container) -and -not $NoTorchMode$script:PinChangedForceReinstall = $true$shouldRebuild = $false}+ # A +xpu venv is never wiped by a DIRECT update: on a hybrid NVIDIA+Arc box the promotion+ # above is gated on -not $HasNvidiaSmi, so a later pinless update expects a cu* tag, calls the+ # working Arc venv stale and deletes it -- then exits, because only install.ps1 creates venvs.+ # Under install.ps1 ($InstallerManagedSetup) the rollback copy exists, so leave that alone.+ if ($shouldRebuild -and -not $InstallerManagedSetup -and $installedTorchTag -eq "xpu") {+ substep "Keeping the installed Intel XPU environment (this host expects $expectedTorchTag)." "Yellow"+ substep "Re-run install.ps1 to replace it -- that path rebuilds with a rollback copy." "Yellow"+ $shouldRebuild = $false+ # Keeping the venv is only half the job: the index selection below prefers NVIDIA, and+ # the CUDA arm does NOT --reinstall-package torch, so uv would keep the +xpu wheel as+ # satisfied while installing triton-windows over torch's XPU triton, with $XpuIndexUrl+ # null and nothing to swap it back. So the whole pass stays on the xpu index.+ $script:PreservedXpuVenv = $true+ }if ($shouldRebuild) {$reason = if ($installedTorchTag) { "torch $installedTorchTag != required $expectedTorchTag" } else { "torch could not be imported" }@@ -3294,6 +3578,38 @@ function Fast-Install {}}+# uv first, pip as the fallback -- the shape install.sh uses to prune a dependency-pulled wheel.+# No index scrub: an uninstall reads no index.+function Fast-Uninstall {+ param([Parameter(ValueFromRemainingArguments=$true)]$Args_)+ if ($UseUv) {+ $VenvPy = (Get-Command python).Source+ & uv pip uninstall --python $VenvPy @Args_ 2>&1+ if ($LASTEXITCODE -eq 0) { return }+ }+ & python -m pip uninstall -y @Args_ 2>&1+}++# Fetch a wheel without installing it, so a destructive step can be staged behind a download.+# pip only: uv has no `pip download` (astral-sh/uv#3163). Scrubbed like Fast-Install, minus the+# UV_* pip cannot read: an inherited PIP_INDEX_URL or user pip.conf would outrank --index-url.+function Fast-Download {+ param([Parameter(ValueFromRemainingArguments=$true)]$Args_)+ $saved = @{}+ foreach ($n in 'PIP_EXTRA_INDEX_URL', 'PIP_FIND_LINKS', 'PIP_NO_INDEX', 'PIP_INDEX_URL', 'PIP_CONFIG_FILE') {+ $saved[$n] = [Environment]::GetEnvironmentVariable($n)+ Remove-Item "Env:$n" -ErrorAction SilentlyContinue+ }+ $env:PIP_CONFIG_FILE = 'nul'+ try {+ & python -m pip download @Args_ 2>&1+ }+ finally {+ Remove-Item "Env:PIP_CONFIG_FILE" -ErrorAction SilentlyContinue+ foreach ($n in $saved.Keys) { if ($null -ne $saved[$n]) { Set-Item "Env:$n" $saved[$n] } }+ }+}+# ── Check if Python deps need updating ──# Compare installed package version against PyPI latest.# Skip all Python dependency work if versions match (fast update path).@@ -3369,6 +3685,57 @@ sys.exit(0 if install_manifest.verify_install()['ok'] else 1)$SkipPythonDeps = $false}}+ # ...and the same for an Intel Arc / Data Center GPU, or an up-to-date package on a CPU+ # wheel stays on CPU torch forever. $SkipPythonDeps is re-tested so an escape taken above+ # does not read twice. Both escapes below exist to reach the XPU install and its two+ # remediations, all three gated on $XpuIndexUrl (set only when the resolved leaf is xpu),+ # so $_xpuIsReachable holds them back where a pin or no-torch mode sends this host+ # elsewhere and clearing the fast path would install nothing and re-fire forever.+ $_pinLeafNow = Get-TorchIndexLeaf (Get-PinnedTorchIndexUrl)+ $_xpuIsReachable = (-not $NoTorchMode) -and ((-not $_pinLeafNow) -or ($_pinLeafNow -eq "xpu"))+ if ($script:IsIntelXpu -and $SkipPythonDeps -and $_xpuIsReachable) {+ # The WHEEL, not the runtime: torch.xpu.is_available() is also false for a supported+ # +xpu wheel on a wedged driver, and the dependency pass cannot repair a driver, so+ # keying on it would force a full resolution every update for nothing.+ if (-not (Test-VenvTorchIsXpuSupported -VenvPath $VenvDir)) {+ substep "Intel GPU detected but installed PyTorch is not a supported XPU build -- reinstalling XPU PyTorch" "Cyan"+ $SkipPythonDeps = $false+ }+ }+ # Keyed off the installed wheel as well as the scan: an explicit xpu pin on a host the+ # scan skips (a mixed NVIDIA + Intel box) still ends up on XPU with $script:IsIntelXpu+ # false. The bitsandbytes floor and the Triton replacement live in the dependency pass+ # below, so a venv that reached +xpu without them would fast-path past them forever.+ if ($SkipPythonDeps -and $_xpuIsReachable -and ($script:IsIntelXpu -or $installedTorchTag -eq "xpu")) {+ $_xpuDepsCode = "import importlib.metadata as m; " ++ "print('BNB=' + next((d.version for d in m.distributions() " ++ "if (d.metadata['Name'] or '').lower() == 'bitsandbytes'), '')); " ++ "print('TRITONWIN=' + next((d.version for d in m.distributions() " ++ "if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), ''))"+ $_xpuDeps = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_xpuDepsCode+ if (-not $_xpuDeps.Ok) {+ # A probe that did not answer says nothing about the venv, and reading that as+ # "dependencies are current" would fast-path past both remediations forever.+ # Same direction as an unparseable version below: one extra pass.+ substep "Intel XPU dependencies could not be read -- running the dependency pass" "Cyan"+ $SkipPythonDeps = $false+ } else {+ $_bnbVer = if ($_xpuDeps.Output -match '(?m)^BNB=(\S+)\s*$') { $Matches[1] } else { "" }+ # An unreadable version is treated as stale, the safe direction: one extra pass,+ # never a venv left without 4-bit kernels. Trailing suffixes (0.51.0.dev0) are+ # dropped, not cast.+ $_bnbNum = ($_bnbVer -replace '[^0-9.].*$', '').TrimEnd('.')+ $_bnbStale = $true+ if ($_bnbNum -match '^\d+\.\d+') {+ try { $_bnbStale = [version]$_bnbNum -lt [version]"0.50.0" } catch {}+ }+ $_tritonWinPresent = $_xpuDeps.Output -match '(?m)^TRITONWIN=\S+\s*$'+ if ($_bnbStale -or $_tritonWinPresent) {+ substep "Intel XPU dependencies are stale -- running the dependency pass" "Cyan"+ $SkipPythonDeps = $false+ }+ }+ }} elseif ($InstalledVer -and $LatestVer) {substep "$_PkgName $InstalledVer -> $LatestVer available, updating..."} elseif (-not $LatestVer) {@@ -3453,8 +3820,17 @@ $PinnedTorchIndexUrl = Get-PinnedTorchIndexUrl$TorchIndexPinned = [bool]$PinnedTorchIndexUrlif ($PinnedTorchIndexUrl) {$CuTag = Get-TorchIndexLeaf $PinnedTorchIndexUrl+} elseif ($script:PreservedXpuVenv) {+ # The stale check kept an installed +xpu venv rather than wiping it, which a hybrid+ # NVIDIA + Arc host reaches. Ahead of the NVIDIA arm deliberately: converting halfway leaves+ # +xpu torch under triton-windows and no XPU index to swap it back. install.ps1 converts.+ $CuTag = "xpu"} elseif ($HasNvidiaSmi) {$CuTag = Get-PytorchCudaTag+} elseif ($script:IsIntelXpu) {+ # XPU (SYCL) wheels ship under the /xpu leaf, so $TorchInstallIndexUrl below resolves to+ # <mirror>/xpu. A pin above still wins; the AMD reroute below needs $CuTag -eq "cpu".+ $CuTag = "xpu"} else {$CuTag = "cpu"}@@ -3571,6 +3947,10 @@ $PyTorchWhlBase = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR# goes through $ROCmIndexUrl; on failure the fallback uses the CPU index, not the ROCm pin.$TorchInstallIndexUrl = if ($ROCmIndexUrl) { "$PyTorchWhlBase/cpu" } elseif ($PinnedTorchIndexUrl) { $PinnedTorchIndexUrl } else { "$PyTorchWhlBase/$CuTag" }+# Declared outside the guard: the bitsandbytes and Triton passes read it from outside too, and+# no-torch mode never reaches the assignment below.+$XpuIndexUrl = $null+if (-not $NoTorchMode) {# Windows on ARM has win_arm64 torch and torchvision wheels but no torchaudio on any index,# so every branch below drops it. Ask the interpreter uv resolves for, not@@ -3612,7 +3992,50 @@ if ($ROCmIndexUrl) {}}-if (-not $ROCmIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback)) {+# ── Intel XPU (SYCL) ─────────────────────────────────────────────────────────+# Its own index leaf, so it must not fall into the CUDA branch below ("CUDA support (xpu)").+# Reached on an Arc / Data Center host and on an explicit xpu pin.+$XpuCpuFallback = $false+if (-not $ROCmIndexUrl -and $CuTag -eq "xpu") { $XpuIndexUrl = $TorchInstallIndexUrl }+if ($XpuIndexUrl) {+ substep "installing PyTorch (Intel XPU)..."+ # Bounded like install.ps1's XPU install: the xpu index serves torch past what Unsloth+ # supports. The floor is 2.6, not the usual 2.4 -- unsloth/models/_utils.py raises at import+ # for an XPU device below that, and an older wheel would be kept as satisfying the range.+ $_xpuTrio = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0", "torchaudio>=2.6,<2.11.0")+ if ($WinArm64NoAudio) { $_xpuTrio = @("torch>=2.6,<2.11.0", "torchvision>=0.21,<0.26.0") }+ # Gated like $cpuForce below, NOT unconditional: install.ps1 already installed the XPU trio+ # before calling setup, so forcing every pass re-downloads GB there and on every update.+ # Force only on a flavor change -- a CPU (or cu*/rocm) wheel satisfies the range, so uv would+ # keep it and never migrate. An unreadable flavor forces too, the safe direction.+ $xpuForce = @()+ if ($installedTorchTag -ne "xpu") { $xpuForce = @("--force-reinstall") }+ # A changed pin repairs in place, so the existing +xpu wheel must be replaced too.+ if ($script:PinChangedForceReinstall) { $xpuForce = @("--force-reinstall") }+ if ($script:UnslothVerbose) {+ Fast-Install @_xpuTrio @xpuForce --index-url $XpuIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ $torchInstallExit = $LASTEXITCODE+ $output = ""+ } else {+ $output = Fast-Install @_xpuTrio @xpuForce --index-url $XpuIndexUrl | Out-String+ $torchInstallExit = $LASTEXITCODE+ }+ if ($torchInstallExit -ne 0) {+ # Transient XPU-index failure: fall back to a CPU base rather than leaving no torch+ # (same shape as ROCm above).+ Write-Host "[WARN] Intel XPU PyTorch install failed -- falling back to CPU" -ForegroundColor Yellow+ Write-Host (Redact-InstallOutput $output) -ForegroundColor Yellow+ $XpuIndexUrl = $null+ $XpuCpuFallback = $true+ $TorchInstallIndexUrl = "$PyTorchWhlBase/cpu"+ } else {+ substep "GPU XPU PyTorch installed -- training and GPU inference will use the GPU" "Cyan"+ # The wheel being in place does not mean the runtime initializes -- see the helper.+ Assert-XpuRuntimeReady -PythonExe "python" | Out-Null+ }+}++if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback -or $XpuCpuFallback)) {substep "installing PyTorch (CPU-only)..."# After an AMD ROCm fallback, force-reinstall so a partial ROCm torch (which satisfies the# CPU torch>= range) is replaced by the CPU build; skip on a genuine CPU host to stay fast.@@ -3621,6 +4044,8 @@ if (-not $ROCmIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback)) {# enumerate char-by-char.$cpuForce = @()if ($ROCmCpuFallback) { $cpuForce = @("--force-reinstall") }+ # Same after an Intel XPU fallback: a partial +xpu torch satisfies the CPU torch>= range.+ if ($XpuCpuFallback) { $cpuForce = @("--force-reinstall") }# --force-reinstall on a pin change: a stale +cu / +rocm wheel still satisfies the CPU# torch>= range, so uv would keep it and only swap companions.if ($script:PinChangedForceReinstall) { $cpuForce = @("--force-reinstall") }@@ -3633,6 +4058,12 @@ if (-not $ROCmIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback)) {$cpuVisionSpec = "torchvision>=0.19,<0.27.0"$cpuAudioSpec = "torchaudio>=2.4,<2.12.0"}+ # Bound an XPU fallback too: this is not the plain CPU box the bare trio was preserved for.+ if ($XpuCpuFallback) {+ $cpuTorchSpec = "torch>=2.4,<2.12.0"+ $cpuVisionSpec = "torchvision>=0.19,<0.27.0"+ $cpuAudioSpec = "torchaudio>=2.4,<2.12.0"+ }$_torchTrio = @($cpuTorchSpec, $cpuVisionSpec, $cpuAudioSpec)if ($WinArm64NoAudio) { $_torchTrio = @($cpuTorchSpec, $cpuVisionSpec) }if ($script:UnslothVerbose) {@@ -3648,7 +4079,7 @@ if (-not $ROCmIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback)) {Write-Host (Redact-InstallOutput $output) -ForegroundColor RedExit-SetupFailure "PyTorch installation failed (exit code $torchInstallExit)"}-} elseif (-not $ROCmIndexUrl) {+} elseif (-not $ROCmIndexUrl -and -not $XpuIndexUrl) {substep "installing PyTorch with CUDA support ($CuTag)..."substep "(This download is ~2.8 GB -- may take a few minutes)"# --force-reinstall on a pin change: an installed cuXXX wheel satisfies the bare torch@@ -3716,6 +4147,178 @@ if (-not $ROCmIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCpuFallback)) {substep "running ordered dependency installation..."python "$PSScriptRoot\install_python_stack.py"$stackExit = $LASTEXITCODE++# ── Intel XPU: bitsandbytes must carry XPU kernels ──+# unsloth/bnb_availability.py binds cgemv_4bit_inference_fp16/bf16 for device_type "xpu" and only+# bitsandbytes' XPU library exports those, so a wheel without it turns 4-bit QLoRA off. 0.48.2 is+# the first win_amd64 build carrying that library, but the floor is 0.50.0, the AMD paths' floor:+# <=0.49.2 NaNs at 4-bit decode on AMD, and an Arc card can sit next to a Radeon. unsloth's own+# floor (>=0.45.5) lets a MIGRATED venv keep its old wheel while the stack above upgrades unsloth+# alone, so run after it for the last word. --no-deps (torch and numpy are in), and never the+# curated unsloth[intel-gpu-torch*] extra: it pins torch to one +xpu wheel URL, unpinning the+# trio above, and carries a preview bitsandbytes wheel uv refuses. $XpuIndexUrl is the "ended up+# on XPU" gate. Must stay ABOVE the $ErrorActionPreference restore below: Fast-Install needs+# EAP=Continue or PS 5.1 turns pip's stderr into a terminating error. Best-effort.+if ($stackExit -eq 0 -and $XpuIndexUrl) {+ substep "installing bitsandbytes with Intel XPU kernels..."+ if ($script:UnslothVerbose) {+ Fast-Install --no-deps "bitsandbytes>=0.50.0" | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ $bnbXpuExit = $LASTEXITCODE+ $bnbOutput = ""+ } else {+ $bnbOutput = Fast-Install --no-deps "bitsandbytes>=0.50.0" | Out-String+ $bnbXpuExit = $LASTEXITCODE+ }+ if ($bnbXpuExit -ne 0) {+ substep "[WARN] could not install an XPU-capable bitsandbytes (exit $bnbXpuExit); 4-bit QLoRA may be unavailable." "Yellow"+ Write-Host (Redact-InstallOutput $bnbOutput) -ForegroundColor Yellow+ }+}++# ── Intel XPU: triton-windows must not shadow torch's XPU triton ──+# triton-windows and torch's XPU triton BOTH own the top-level `triton` package (80 to 160 shared+# paths, __init__.py and _C/libtriton.pyd among them), so a cu*-to-xpu pin repair leaves the CUDA+# build shadowing the XPU one. AFTER the stack, since unsloth declares triton-windows a win32+# core dep and base.txt reinstalls anything removed earlier. Uninstall always paired with a+# reinstall: removing one drops the shared paths the other overwrote. The spec is read from the+# installed torch (renamed pytorch-triton-xpu -> triton-xpu in torch 2.10).+if ($stackExit -eq 0 -and $XpuIndexUrl) {+ # One -c line, so no double quotes (Invoke-BoundedPythonProbe wraps $Code in them).+ $_tritonCode = "import importlib.metadata as m; " ++ "print('TRITONWIN=' + next((d.version for d in m.distributions() " ++ "if (d.metadata['Name'] or '').lower().replace('_','-') == 'triton-windows'), '')); " ++ "print('TRITONXPU=' + next((r.split(';')[0].strip() " ++ "for r in (m.requires('torch') or []) if 'triton' in r.lower()), ''))"+ $_tritonProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_tritonCode+ # Line-anchored like the other probes so a stdout banner ahead of the answer hides nothing.+ $_tritonWinVer = if ($_tritonProbe.Ok -and $_tritonProbe.Output -match '(?m)^TRITONWIN=(\S+)\s*$') { $Matches[1] } else { "" }+ $_tritonXpuSpec = if ($_tritonProbe.Ok -and $_tritonProbe.Output -match '(?m)^TRITONXPU=(\S+)\s*$') { $Matches[1] } else { "" }+ # The spec must itself be an XPU triton (pytorch-triton-xpu / triton-xpu); anything else means+ # torch is not the +xpu wheel this branch assumes.+ if ($_tritonWinVer -and $_tritonXpuSpec -match '(?i)xpu') {+ substep "replacing triton-windows $_tritonWinVer with $_tritonXpuSpec (Intel XPU)..." "Cyan"+ # install_manifest.manifest_path() is venv_root()/MANIFEST_NAME and venv_root() is+ # sys.prefix, which is $VenvDir here -- the same join Get-PersistedNoTorch does. Assembled+ # rather than asked for: a subprocess to learn a constant can hang or fail in a way+ # indistinguishable from "there is no manifest", which reopens the window this closes.+ # test_intel_registry_fallback.ps1 asserts this literal still matches MANIFEST_NAME.+ $_manifestPath = Join-Path $VenvDir "unsloth_install_manifest.json"+ # Fetch, THEN uninstall, THEN install the file. The uninstall cannot go last -- it drops+ # the paths in triton-windows' OWN record, which are the shared ones -- so pre-fetching+ # keeps a dead mirror from stranding the venv between the two steps. uv has no+ # `pip download`, hence Fast-Download.+ $_tritonTmp = Join-Path ([System.IO.Path]::GetTempPath()) "unsloth_triton_xpu_$([guid]::NewGuid().ToString('N').Substring(0,8))"+ try {+ New-Item -ItemType Directory -Force -Path $_tritonTmp -ErrorAction SilentlyContinue | Out-Null+ if ($script:UnslothVerbose) {+ Fast-Download --no-deps --only-binary=:all: -d $_tritonTmp $_tritonXpuSpec --index-url $XpuIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ $tritonDlExit = $LASTEXITCODE+ $tritonDlOutput = ""+ } else {+ $tritonDlOutput = Fast-Download --no-deps --only-binary=:all: -d $_tritonTmp $_tritonXpuSpec --index-url $XpuIndexUrl | Out-String+ $tritonDlExit = $LASTEXITCODE+ }+ # The exit code alone is not enough: no wheel on disk means nothing to install from.+ $_tritonWheel = @(Get-ChildItem -LiteralPath $_tritonTmp -Filter "*.whl" -ErrorAction SilentlyContinue) | Select-Object -First 1 -ExpandProperty FullName+ if ($tritonDlExit -ne 0 -or -not $_tritonWheel) {+ substep "[WARN] could not fetch $_tritonXpuSpec (exit $tritonDlExit); triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"+ Write-Host (Redact-InstallOutput $tritonDlOutput) -ForegroundColor Yellow+ } else {+ # From here to the reinstall below is a window where a kill leaves a venv with+ # no triton that the next update still reads as complete and fast-paths past.+ # MOVE the manifest into the wheel's temp dir for the swap, never read and+ # rewrite it: PS 5.1's Set-Content defaults to ANSI and its -Encoding utf8 emits+ # a BOM read_manifest's json.load rejects, so either corrupts a manifest with a+ # non-ASCII path. The finally below deletes the dir, so an unrestored manifest+ # stays gone -- which is the truth while the venv has no triton.+ $_manifestHeld = $null+ $_manifestBlocked = $false+ $_uninstallExit = 0+ if ($_manifestPath -and (Test-Path -LiteralPath $_manifestPath -PathType Leaf)) {+ $_held = Join-Path $_tritonTmp "held_manifest.json"+ try {+ Move-Item -LiteralPath $_manifestPath -Destination $_held -Force -ErrorAction Stop+ # Move-Item across volumes is a copy plus a delete and reports success+ # even when only the delete fails, leaving the original in place. The+ # manifest must be GONE for the swap, so confirm rather than trust.+ if (Test-Path -LiteralPath $_manifestPath -PathType Leaf) {+ Remove-Item -LiteralPath $_held -Force -ErrorAction SilentlyContinue+ $_manifestBlocked = $true+ } else {+ $_manifestHeld = $_held+ }+ } catch { $_manifestBlocked = $true }+ }+ if ($_manifestBlocked) {+ # A manifest that will not move (locked, read-only) would stay valid right+ # through the destructive window, so do not open one. Leaving triton-windows+ # costs torch.compile on the XPU, which the next run can still fix.+ substep "[WARN] could not set the install manifest aside; triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"+ } else {+ Fast-Uninstall "triton-windows" | Out-Null+ $_uninstallExit = $LASTEXITCODE+ }+ # A triton-windows that would not uninstall (Studio running and holding+ # _C/libtriton.pyd open) still shadows the XPU triton, so installing over it+ # achieves nothing and would restore the manifest onto an unchanged venv.+ if (-not $_manifestBlocked -and $_uninstallExit -ne 0) {+ substep "[WARN] could not remove triton-windows $_tritonWinVer (exit $_uninstallExit); it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"+ if ($_manifestHeld) {+ try { Move-Item -LiteralPath $_manifestHeld -Destination $_manifestPath -Force -ErrorAction Stop } catch {}+ }+ } elseif (-not $_manifestBlocked) {+ if ($script:UnslothVerbose) {+ Fast-Install --force-reinstall --no-deps $_tritonWheel | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ $tritonXpuExit = $LASTEXITCODE+ $tritonOutput = ""+ } else {+ $tritonOutput = Fast-Install --force-reinstall --no-deps $_tritonWheel | Out-String+ $tritonXpuExit = $LASTEXITCODE+ }+ $_tritonPresent = ($tritonXpuExit -eq 0)+ if ($tritonXpuExit -ne 0) {+ # Off the network by now, so this is disk/permissions. triton-windows is+ # already gone and took the shared paths with it, so put SOME working+ # triton back rather than leave the venv unable to import one.+ Fast-Install --force-reinstall --no-deps "triton-windows<3.7" | Out-Null+ $tritonBackExit = $LASTEXITCODE+ $_tritonPresent = ($tritonBackExit -eq 0)+ Write-Host (Redact-InstallOutput $tritonOutput) -ForegroundColor Yellow+ if ($tritonBackExit -eq 0) {+ substep "[WARN] could not install $_tritonXpuSpec (exit $tritonXpuExit); restored triton-windows, so triton still imports -- but torch.compile will not use the XPU." "Yellow"+ } else {+ # Redacted: a mirror pin can carry a token, and this is the only place+ # setup.ps1 shows an index URL. A tokenless URL survives verbatim.+ $_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl+ Write-Host "[ERROR] triton-windows was removed and neither triton would reinstall -- torch.compile is broken." -ForegroundColor Red+ Write-Host " Repair with: python -m pip install --force-reinstall --no-deps $_tritonXpuSpec --index-url $_tritonRepairUrl" -ForegroundColor Red+ # Printing alone left $stackExit at 0, so setup reported success and+ # install.ps1 COMMITTED this venv over its rollback copy. It has no+ # importable triton at all; the caller must not accept it.+ $stackExit = $tritonBackExit+ }+ }+ # Moved back, never rewritten, and only once a triton is importable again. If+ # neither would reinstall the venv really is incomplete, and losing the+ # manifest with the temp dir is what makes the next update repair it.+ if ($_manifestHeld -and $_tritonPresent) {+ try { Move-Item -LiteralPath $_manifestHeld -Destination $_manifestPath -Force -ErrorAction Stop } catch {}+ # The finally below deletes the held copy either way, so an unreported+ # failure loses the manifest silently and the next run does a full+ # dependency pass with nothing on screen explaining why.+ if (-not (Test-Path -LiteralPath $_manifestPath -PathType Leaf)) {+ substep "[WARN] could not restore the install manifest; the next update will re-run the dependency pass." "Yellow"+ }+ }+ }+ }+ } finally {+ # The wheel is ~300 MB, so it never outlives the install.+ Remove-Item -Recurse -Force -LiteralPath $_tritonTmp -ErrorAction SilentlyContinue+ }+ }+}+# Restore ErrorActionPreference after pip/python work$ErrorActionPreference = $prevEAPif ($stackExit -ne 0) {diff --git a/studio/setup.sh b/studio/setup.shindex a49b8135851..c6c4ffcdf8f 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -1130,6 +1130,93 @@ sys.exit(0 if install_manifest.verify_install()['ok'] else 1)substep "studio install incomplete -- forcing dependency pass to repair..."_SKIP_PYTHON_DEPS=falsefi+ # An XPU pin the venv does not satisfy. Only the dependency pass acts on it+ # (install_python_stack's _ensure_xpu_torch), so without this escape a CPU install+ # switched to UNSLOTH_TORCH_INDEX_FAMILY=xpu keeps its CPU wheel forever: the package+ # version is current, so the fast path calls it up to date. Mirrors setup.ps1.+ _setup_pin="${UNSLOTH_TORCH_INDEX_URL:-${UNSLOTH_TORCH_INDEX_FAMILY:-}}"+ # Strip query/fragment first: an authenticated mirror (…/whl/xpu?token=...) is a+ # supported pin shape, and missing it reads as "no XPU pin" and skips the repair.+ _setup_pin="${_setup_pin%%\#*}"+ _setup_pin="${_setup_pin%%\?*}"+ # ALL trailing slashes, like the shared leaf parsers: a single %/ leaves "…/xpu/" behind.+ while [ "${_setup_pin%/}" != "$_setup_pin" ]; do _setup_pin="${_setup_pin%/}"; done+ # Exact, lowercased leaf, like every other leaf parser: a *xpu suffix match (…/private-xpu)+ # would force a pass every update that _ensure_xpu_torch then declines to act on, and an+ # uncased match would miss UNSLOTH_TORCH_INDEX_FAMILY=XPU that those parsers do accept.+ _setup_pin_leaf=$(printf '%s' "${_setup_pin##*/}" | tr '[:upper:]' '[:lower:]')+ # Disk first, no interpreter: version.py carries the local label, so a wedged Intel+ # driver cannot hang `studio update` inside `import torch`. Read unconditionally, not+ # only under a pin: the pin is one-shot, so the installed wheel is the only durable+ # signal -- the same one _ensure_xpu_triton keys on.+ _setup_pin_ok=false+ _setup_pin_is_xpu=false+ for _setup_pin_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do+ [ -f "$_setup_pin_tv" ] || continue+ _setup_pin_ver=$(sed -n "s/^__version__ = '\([^']*\)'.*/\1/p" "$_setup_pin_tv" | head -1)+ case "$_setup_pin_ver" in+ *+xpu)+ _setup_pin_is_xpu=true+ _setup_pin_maj=${_setup_pin_ver%%.*}+ _setup_pin_rest=${_setup_pin_ver#*.}+ _setup_pin_min=${_setup_pin_rest%%.*}+ case "$_setup_pin_maj$_setup_pin_min" in+ *[!0-9]*) ;;+ *) [ "$_setup_pin_maj" -eq 2 ] && [ "$_setup_pin_min" -ge 6 ] && \+ [ "$_setup_pin_min" -lt 11 ] && _setup_pin_ok=true ;;+ esac+ ;;+ esac+ break+ done+ # Correct torch is not enough: the Triton swap also lives in install_python_stack, so a+ # migrated +xpu venv with a leftover generic triton keeps the CUDA build shadowing the+ # XPU one. The dist-info glob below matches only generic "triton-<ver>" -- the XPU builds+ # are pytorch_triton_xpu-* / triton_xpu-*.+ # Leaves the shared classifiers recognise as a non-XPU family. EXACT families, mirroring+ # install.sh _is_pip_rocm_family_leaf and install_python_stack _is_cuda_family_leaf: a+ # merely prefixed leaf (cu128-private) is a custom verbatim pin they never repair, so+ # escaping on one would force a pass every update that changes nothing.+ _setup_known_nonxpu_leaf() {+ case "$1" in+ cpu|gfx[0-9]*) return 0 ;;+ cu[0-9]*) case "${1#cu}" in *[!0-9]*) return 1 ;; esac ;;+ rocm[0-9]*)+ # Both parts non-empty all-digits: rocm7., rocm7.2.1 are custom pins.+ _setup_rocm_rest="${1#rocm}"+ case "$_setup_rocm_rest" in+ *.*.*) return 1 ;;+ *.*)+ case "${_setup_rocm_rest%%.*}" in *[!0-9]*) return 1 ;; esac+ case "${_setup_rocm_rest#*.}" in "" | *[!0-9]*) return 1 ;; esac+ ;;+ *[!0-9]*) return 1 ;;+ esac+ ;;+ *) return 1 ;;+ esac+ return 0+ }+ _setup_pin_known_nonxpu=false+ _setup_known_nonxpu_leaf "$_setup_pin_leaf" && _setup_pin_known_nonxpu=true+ _setup_generic_triton=false+ if [ "$_setup_pin_is_xpu" = true ] || [ "$_setup_pin_leaf" = "xpu" ]; then+ for _setup_tri in "$VENV_DIR"/lib/python*/site-packages/triton-*.dist-info; do+ [ -d "$_setup_tri" ] && _setup_generic_triton=true && break+ done+ fi+ if [ "$_setup_pin_leaf" = "xpu" ] && [ "$_setup_pin_ok" = false ]; then+ substep "XPU index pinned but torch does not match -- forcing dependency pass to repair..."+ _SKIP_PYTHON_DEPS=false+ elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_generic_triton" = true ]; then+ substep "generic triton shadows the XPU build -- forcing dependency pass to repair..."+ _SKIP_PYTHON_DEPS=false+ elif [ "$_setup_pin_is_xpu" = true ] && [ "$_setup_pin_known_nonxpu" = true ]; then+ # Migrating AWAY from XPU: the pin is authoritative, but only install_python_stack+ # acts on it, so an up-to-date install kept its +xpu wheel over the requested family.+ substep "$_setup_pin_leaf pinned over an XPU wheel -- forcing dependency pass to migrate..."+ _SKIP_PYTHON_DEPS=false+ fielif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ]; thensubstep "$_PKG_NAME $INSTALLED_VER -> $LATEST_VER available, updating..."elif [ -z "$LATEST_VER" ]; then@@ -1226,6 +1313,40 @@ _setup_amd_detected=false_setup_nvidia_usable=false_setup_gfx_all=""_setup_mkt=""+# Intel XPU. There is no vendor probe here like nvidia-smi / rocminfo -- Linux Intel support is+# an explicit index pin, not autodetection -- so the installed runtime IS the signal. The local+# label is read off disk first so a CPU-only host never pays for an `import torch`.+_setup_torch_is_xpu=false+_setup_xpu_ready=false+for _setup_tv in "$VENV_DIR"/lib/python*/site-packages/torch/version.py; do+ [ -f "$_setup_tv" ] || continue+ grep -q "^__version__ = '[^']*+xpu" "$_setup_tv" 2>/dev/null || continue+ _setup_torch_is_xpu=true+ # A +xpu wheel installs fine on a host whose driver never initialises, so only the runtime+ # answer reaches the summary below. Bounded, because a stalled Intel driver wedges inside+ # `import torch`: 60s rather than the smi probes' 10s, since a cold import is seconds on its+ # own. The SIGALRM deadline lives inside the probe too, for hosts without `timeout` (base+ # macOS, minimal Linux images). Either deadline expiring means "no XPU", as a failure does.+ _setup_xpu_probe='import signal; signal.alarm(60); import torch,sys; sys.exit(0 if torch.xpu.is_available() else 1)'+ if command -v timeout >/dev/null 2>&1; then+ timeout 60 "$VENV_DIR/bin/python" -c "$_setup_xpu_probe" >/dev/null 2>&1 && _setup_xpu_ready=true+ elif "$VENV_DIR/bin/python" -c "$_setup_xpu_probe" >/dev/null 2>&1; then+ _setup_xpu_ready=true+ fi+ break+done++# bitsandbytes carries XPU kernels (libbitsandbytes_xpu2025.so, _xpu2026.so) only from 0.50.0,+# and unsloth's own floor is 0.45.5, so a pre-XPU wheel satisfies it forever. install.sh raises+# the floor, but `unsloth studio update` runs THIS file, so an existing XPU user would keep a+# kernel-less bitsandbytes and lose 4-bit QLoRA. Keyed on the wheel, not the runtime: a stalled+# driver is no reason to skip the upgrade. --no-deps (torch and numpy are in), best effort.+if [ "$_setup_torch_is_xpu" = true ]; then+ # run_quiet_no_exit, NOT run_quiet: the latter exits via setup_fail, aborting an otherwise+ # fine `studio update` over a best-effort step and leaving the warning below unreachable.+ run_quiet_no_exit "install bitsandbytes (xpu)" fast_install --no-deps "bitsandbytes>=0.50.0" || \+ substep "[WARN] could not install an XPU-capable bitsandbytes; 4-bit QLoRA may be unavailable."+fi# NVIDIA priority: classify NVIDIA first and skip the AMD probes entirely on# a usable-NVIDIA host (mirrors _has_rocm_gpu in install_python_stack.py).# This also keeps a wedged rocminfo/amd-smi from hanging setup before the@@ -1317,6 +1438,18 @@ elif [ "$_setup_amd_detected" = true ]; thensubstep "ROCm: $_setup_rocm_root"[ -n "$_setup_rocm_ver" ] && substep "hipconfig: $_setup_rocm_ver"[ -n "$_setup_mkt" ] && [ -n "$_setup_gfx" ] && substep "GPU: $_setup_mkt"+elif [ "$_setup_xpu_ready" = true ]; then+ # Ranks below NVIDIA and AMD, as in setup.ps1: those hosts get their own wheels.+ step "gpu" "Intel GPU detected (XPU runtime)"+ substep "PyTorch XPU (SYCL) provides training and GPU inference on this GPU."+elif [ "$_setup_torch_is_xpu" = true ]; then+ # +xpu wheel installed but torch.xpu.is_available() said no: the Intel compute driver is+ # missing or too old. Falling through would call the hardware unsupported instead.+ step "gpu" "Intel GPU (XPU runtime unavailable)" "$C_WARN"+ substep "PyTorch has the XPU build but cannot initialise it -- update the Intel GPU compute driver."+ # Not "runs on CPU": with neither CUDA nor XPU, unsloth/device_type.py raises at import.+ # llama.cpp is unaffected, which is what chat and GGUF run on.+ substep "Until then training and GPU inference are unavailable; chat and GGUF still work."elif [ "$(uname -s 2>/dev/null)" = "Darwin" ] && [ "$(uname -m 2>/dev/null)" = "arm64" ]; then# Apple Silicon: llama.cpp builds with Metal over unified memory, so not a CPU-only host.step "gpu" "Apple Silicon (Metal, unified memory)"diff --git a/tests/python/test_tokenizers_and_torch_constraint.py b/tests/python/test_tokenizers_and_torch_constraint.pyindex d42a2744784..ec30b284658 100644--- a/tests/python/test_tokenizers_and_torch_constraint.py+++ b/tests/python/test_tokenizers_and_torch_constraint.py@@ -176,7 +176,17 @@ class TestInstallShUvDefaultIndex:assert '--default-index "$TORCH_INDEX_URL"' in self._shdef test_torch_installs_do_not_use_deprecated_index_url(self):- assert '--index-url "$TORCH_INDEX_URL"' not in self._sh+ # uv deprecated --index-url in favour of --default-index; pip never had it, so the XPU+ # triton pre-fetch (`pip download`) legitimately uses --index-url. Checked per+ # occurrence so a uv invocation still cannot slip one through. Backslash continuations+ # are joined first, since the flag and its command are often on different lines.+ joined = self._sh.replace("\\\n", " ")+ offenders = [+ " ".join(line.split())+ for line in joined.splitlines()+ if '--index-url "$TORCH_INDEX_URL"' in line and "pip download" not in line+ ]+ assert not offenders, offendersdef test_torch_installs_neutralize_all_uv_index_env_vars(self):# --default-index installs run with all uv index env vars unset via `env -u`.diff --git a/tests/sh/test_install_sh_xpu_flavor_probe.sh b/tests/sh/test_install_sh_xpu_flavor_probe.shnew file mode 100755index 00000000000..b4a3c39edbb--- /dev/null+++ b/tests/sh/test_install_sh_xpu_flavor_probe.sh@@ -0,0 +1,97 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# install.sh's flavor guard must not launch an interpreter on the XPU path.+#+# Adding "xpu" to _expected_torch_flavor_tag made the guard reachable on an Intel pin, and+# `import torch` loads the SYCL runtime, which blocks forever on a wedged compute driver --+# on exactly the host this guard runs on, before setup.sh's bounded probes.+#+# The function is extracted and executed against built venv trees, so the glob, the sed and+# the interpreter/disk split are exercised rather than read.+set -u++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+INSTALL_SH="${1:-$SCRIPT_DIR/../../install.sh}"+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++awk '/^_installed_torch_version_for_tag\(\) \{/, /^\}$/' "$INSTALL_SH" > "$WORK/fn.sh"+[ -s "$WORK/fn.sh" ] || { echo "FATAL: _installed_torch_version_for_tag not found in $INSTALL_SH" >&2; exit 1; }+# An extraction that lost either arm would make every case below pass vacuously.+grep -q 'torch/version.py' "$WORK/fn.sh" || { echo "FATAL: extraction lost the disk read" >&2; exit 1; }+grep -q 'import torch' "$WORK/fn.sh" || { echo "FATAL: extraction lost the interpreter read" >&2; exit 1; }++PASS=0+FAIL=0+check() {+ if [ "$2" = "$3" ]; then+ PASS=$((PASS + 1))+ else+ printf ' FAIL %-42s got=[%s] want=[%s]\n' "$1" "$2" "$3"+ FAIL=$((FAIL + 1))+ fi+}++# A venv whose torch/version.py (if $1 is non-empty) reports $1, under python$2.+make_venv() {+ _v="$WORK/venv_$3"+ rm -rf "$_v"+ mkdir -p "$_v/bin"+ if [ -n "$1" ]; then+ mkdir -p "$_v/lib/python$2/site-packages/torch"+ printf "from typing import Optional\n__version__ = '%s'\ndebug = False\n" "$1" \+ > "$_v/lib/python$2/site-packages/torch/version.py"+ fi+ # Stands in for the venv interpreter: any use of it on the XPU path is a bug, so it+ # reports a value nothing else could produce.+ printf '#!/bin/sh\necho INTERPRETER_WAS_LAUNCHED\n' > "$_v/bin/python"+ chmod +x "$_v/bin/python"+ printf '%s' "$_v"+}++probe() {+ (+ VENV_DIR="$1"+ _VENV_PY="$1/bin/python"+ # shellcheck disable=SC1091+ . "$WORK/fn.sh"+ _installed_torch_version_for_tag "$2"+ )+}++echo "the xpu path reads the label off disk, never from the interpreter"+check "xpu wheel" "$(probe "$(make_venv '2.9.1+xpu' 3.12 a)" xpu)" "2.9.1+xpu"+# A migrated venv can hold a CPU wheel under an xpu pin -- the mismatch the guard repairs --+# so the label has to come back accurately, not empty.+check "stale cpu wheel" "$(probe "$(make_venv '2.9.1+cpu' 3.12 b)" xpu)" "2.9.1+cpu"+check "untagged wheel" "$(probe "$(make_venv '2.9.1' 3.12 c)" xpu)" "2.9.1"+check "no torch installed" "$(probe "$(make_venv '' 3.12 d)" xpu)" ""+check "no venv at all" "$(probe "$WORK/nope" xpu)" ""+# Only one tree exists and it is 3.10, so this catches a hardcoded python3.12 path.+check "any python minor" "$(probe "$(make_venv '2.9.1+xpu' 3.10 e)" xpu)" "2.9.1+xpu"+# The whole point: the interpreter stub prints a token no disk read can produce.+check "xpu launches nothing" "$(probe "$(make_venv '2.9.1+xpu' 3.12 f)" xpu | grep -c INTERPRETER)" "0"+check "missing torch launches nothing" \+ "$(probe "$(make_venv '' 3.12 g)" xpu | grep -c INTERPRETER)" "0"++echo "every other family keeps the interpreter read it has always used"+# Non-Intel behaviour is unchanged: no SYCL runtime to wedge on, and a source install does+# not report from torch/version.py.+for _tag in cu128 cu118 rocm ""; do+ check "tag '${_tag:-<empty>}' still asks python" \+ "$(probe "$(make_venv '2.9.1+cu128' 3.12 h)" "$_tag")" "INTERPRETER_WAS_LAUNCHED"+done++echo "the guard is wired to the helper at BOTH reads"+# The second read runs after the repair reinstall; a raw `import torch` there would+# reintroduce the hang one line later.+check "no raw import torch left in the guard" \+ "$(awk '/^# ── Enforce the installed torch flavor matches/, /^fi$/' "$INSTALL_SH" \+ | grep -c 'import torch; print')" "0"+check "helper used twice in the guard" \+ "$(awk '/^# ── Enforce the installed torch flavor matches/, /^fi$/' "$INSTALL_SH" \+ | grep -c '_installed_torch_version_for_tag')" "2"++echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/sh/test_previous_torch_pin.sh b/tests/sh/test_previous_torch_pin.shindex f910affc2f3..7231187f63d 100644--- a/tests/sh/test_previous_torch_pin.sh+++ b/tests/sh/test_previous_torch_pin.sh@@ -11,7 +11,7 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-INSTALL_SH="$SCRIPT_DIR/../../install.sh"+INSTALL_SH="${1:-$SCRIPT_DIR/../../install.sh}"PASS=0FAIL=0@@ -89,6 +89,34 @@ echo "=== _previous_torch_pin: UNSLOTH_TORCH_UPGRADE=1 opts out ==="assert_eq "upgrade env set" "" "$(UNSLOTH_TORCH_UPGRADE=1 _previous_torch_pin '2.10.0+cu126' 'torch>=2.4,<2.12.0')"assert_eq "upgrade env 0" "torch==2.10.0" "$(UNSLOTH_TORCH_UPGRADE=0 _previous_torch_pin '2.10.0+cu126' 'torch>=2.4,<2.12.0')"+echo "=== the preservation probe reads off disk, not through the interpreter ==="+# `import torch` can block forever on a wedged Intel driver, and this probe runs before+# setup.sh's bounded ones. Executed, not grepped: the stub interpreter records being called.+_PREVBLK=$(mktemp)+awk '/^ _PREV_TORCH_VER=""$/{on=1} on{print} on && /tail -n 1 \|\| true\)$/{exit}' \+ "$INSTALL_SH" > "$_PREVBLK"+grep -q 'version.py' "$_PREVBLK" || { echo "FATAL: probe block not extracted"; exit 1; }+grep -q 'import torch' "$_PREVBLK" || { echo "FATAL: extraction lost the fallback"; exit 1; }++_prev_probe() { # $1 = torch label to put on disk ("" for no version.py)+ _d=$(mktemp -d)+ mkdir -p "$_d/bin"+ printf '#!/bin/sh\ntouch "%s/CALLED"\necho 9.9.9+fromimport\n' "$_d" > "$_d/bin/python"+ chmod +x "$_d/bin/python"+ if [ -n "$1" ]; then+ mkdir -p "$_d/lib/python3.12/site-packages/torch"+ printf "__version__ = '%s'\n" "$1" > "$_d/lib/python3.12/site-packages/torch/version.py"+ fi+ ( VENV_DIR="$_d"; . "$_PREVBLK"; printf '%s|%s' "$_PREV_TORCH_VER" "$([ -f "$_d/CALLED" ] && echo called || echo not-called)" )+ rm -rf "$_d"+}+assert_eq "xpu wheel read off disk" "2.9.1+xpu|not-called" "$(_prev_probe '2.9.1+xpu')"+assert_eq "cuda wheel read off disk" "2.9.1+cu128|not-called" "$(_prev_probe '2.9.1+cu128')"+assert_eq "untagged wheel read off disk" "2.9.1|not-called" "$(_prev_probe '2.9.1')"+# No version.py means no torch, so the interpreter fallback is free to run and fails fast.+assert_eq "falls back with no version.py" "9.9.9+fromimport|called" "$(_prev_probe '')"+rm -f "$_PREVBLK"+echo "=== install.sh wiring ==="# The probe must run against the OLD venv, before it is moved aside for rollback._probe_line=$(grep -n '_PREV_TORCH_VER=\$(' "$INSTALL_SH" | head -1 | cut -d: -f1)diff --git a/tests/sh/test_setup_xpu_fastpath_escape.sh b/tests/sh/test_setup_xpu_fastpath_escape.shnew file mode 100755index 00000000000..fe0cd330771--- /dev/null+++ b/tests/sh/test_setup_xpu_fastpath_escape.sh@@ -0,0 +1,200 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The manifest fast path must not strand an Intel venv.+#+# `unsloth studio update` skips install_python_stack when the package version is current, and+# that pass is the ONLY thing that repairs an XPU wheel or swaps generic Triton out. Two ways+# that goes wrong:+#+# * the pin is ONE-SHOT, so every later update sees none. Keying the escape on the pin alone+# leaves a migrated +xpu venv on generic triton forever, and torch.compile then loads the+# CUDA-oriented library on an Arc GPU.+# * the leaf must match EXACTLY: the shared parsers treat only a bare `xpu` leaf as the curated+# family, so a mirror ending in `-xpu` would clear the skip flag on every up-to-date run+# while the repair helpers decline to act.+#+# The block is extracted and EXECUTED against built venv trees; no interpreter is launched (a+# wedged Intel driver would hang one).+set -u++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+SETUP_SH="${1:-$SCRIPT_DIR/../../studio/setup.sh}"+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++# From the pin read to the end of the acting if/elif chain.+# Stop at the `fi` that closes the escape chain, NOT after the Nth _SKIP_PYTHON_DEPS=false:+# counting assignments truncates the block as soon as an arm is added, silently.+awk '/_setup_pin="\$\{UNSLOTH_TORCH_INDEX_URL/{on=1} on && /^ elif \[ -n "\$INSTALLED_VER"/{exit} on{print}' \+ "$SETUP_SH" > "$WORK/blk.sh"+[ -s "$WORK/blk.sh" ] || { echo "FATAL: escape block not found in $SETUP_SH" >&2; exit 1; }+# An extraction that lost any of the three moving parts would make cases below pass vacuously.+_arms=$(grep -c '_SKIP_PYTHON_DEPS=false' "$WORK/blk.sh")+[ "$_arms" = "3" ] || { echo "FATAL: expected 3 escape arms, extracted $_arms" >&2; exit 1; }+for _need in _setup_pin_leaf _setup_pin_is_xpu _setup_generic_triton _setup_pin_known_nonxpu \+ _setup_known_nonxpu_leaf; do+ grep -q "$_need" "$WORK/blk.sh" || { echo "FATAL: extraction lost $_need" >&2; exit 1; }+done+bash -n "$WORK/blk.sh" || { echo "FATAL: extracted block does not parse" >&2; exit 1; }++PASS=0+FAIL=0+check() {+ if [ "$2" = "$3" ]; then+ PASS=$((PASS + 1))+ else+ printf ' FAIL %-46s got=%s want=%s\n' "$1" "$2" "$3"+ FAIL=$((FAIL + 1))+ fi+}++# venv with torch label $1 (empty for none) and generic triton present when $2 is yes.+make_venv() {+ _v="$WORK/venv_$3"+ rm -rf "$_v"+ _sp="$_v/lib/python3.12/site-packages"+ mkdir -p "$_sp"+ if [ -n "$1" ]; then+ mkdir -p "$_sp/torch"+ printf "from typing import Optional\n__version__ = '%s'\ndebug = False\n" "$1" \+ > "$_sp/torch/version.py"+ fi+ # The XPU distributions must NOT count as the shadowing one.+ [ "$2" = "yes" ] && mkdir -p "$_sp/triton-3.7.1.dist-info"+ [ "$2" = "xpuonly" ] && mkdir -p "$_sp/pytorch_triton_xpu-3.5.0.dist-info" "$_sp/triton_xpu-3.6.0.dist-info"+ printf '%s' "$_v"+}++# Echoes the resulting _SKIP_PYTHON_DEPS. $2 is the pin (empty for none).+escape() {+ (+ VENV_DIR="$1"+ UNSLOTH_TORCH_INDEX_URL="$2"+ UNSLOTH_TORCH_INDEX_FAMILY="${3-}"+ _SKIP_PYTHON_DEPS=true+ # shellcheck disable=SC2317+ substep() { :; }+ # shellcheck disable=SC1091+ . "$WORK/blk.sh"+ echo "$_SKIP_PYTHON_DEPS"+ )+}++XPU=https://download.pytorch.org/whl/xpu++echo "the installed wheel is the pin -- no environment variable needed"+# The headline case: one-shot pin, gone by the next update, generic triton crept back in.+check "no pin, +xpu wheel, generic triton" \+ "$(escape "$(make_venv '2.9.1+xpu' yes a)" "")" false+check "no pin, +xpu wheel, clean venv" \+ "$(escape "$(make_venv '2.9.1+xpu' no b)" "")" true+# Only the generic distribution shadows; torch's own XPU builds must not retrigger forever.+check "no pin, +xpu wheel, xpu triton only" \+ "$(escape "$(make_venv '2.9.1+xpu' xpuonly c)" "")" true+# A CUDA or CPU venv owns its generic triton; removing it would break torch.compile there.+check "no pin, cuda wheel, generic triton" \+ "$(escape "$(make_venv '2.9.1+cu128' yes d)" "")" true+check "no pin, cpu wheel, generic triton" \+ "$(escape "$(make_venv '2.9.1+cpu' yes e)" "")" true+check "no pin, untagged wheel" "$(escape "$(make_venv '2.9.1' yes f)" "")" true+check "no pin, no torch at all" "$(escape "$(make_venv '' yes g)" "")" true+check "no pin, no venv at all" "$(escape "$WORK/nope" "")" true++echo "an explicit xpu pin still repairs a mismatched wheel"+check "pin + cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no h)" "$XPU")" false+check "pin + no torch" "$(escape "$(make_venv '' no i)" "$XPU")" false+# 2.6 is the floor (unsloth raises at import for an XPU device below it) and 2.11 the ceiling.+check "pin + 2.5+xpu below floor" "$(escape "$(make_venv '2.5.1+xpu' no j)" "$XPU")" false+check "pin + 2.11+xpu above ceiling" "$(escape "$(make_venv '2.11.0+xpu' no k)" "$XPU")" false+check "pin + supported wheel, clean" "$(escape "$(make_venv '2.9.1+xpu' no l)" "$XPU")" true+check "pin + supported wheel, generic triton" \+ "$(escape "$(make_venv '2.9.1+xpu' yes m)" "$XPU")" false+# The FAMILY spelling is a bare leaf with no slashes at all.+check "FAMILY=xpu + cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no n)" "" "xpu")" false+# Authenticated / fragmented / double-slashed mirrors are supported pin shapes.+check "pin with query" "$(escape "$(make_venv '2.9.1+cpu' no o)" "$XPU?token=x")" false+check "pin with fragment" "$(escape "$(make_venv '2.9.1+cpu' no p)" "$XPU#f")" false+check "pin with two trailing slashes" "$(escape "$(make_venv '2.9.1+cpu' no q)" "$XPU//")" false+# Case. Every other leaf parser lowercases, so those accept FAMILY=XPU and migrate the wheel;+# this one kept the fast path on and the repair never ran.+check "FAMILY=XPU uppercase" "$(escape "$(make_venv '2.9.1+cpu' no w)" "" "XPU")" false+check "FAMILY=Xpu mixed case" "$(escape "$(make_venv '2.9.1+cpu' no x)" "" "Xpu")" false+check "pin URL ending /XPU" "$(escape "$(make_venv '2.9.1+cpu' no y)" "https://download.pytorch.org/whl/XPU")" false+# Lowercasing must not widen the match: a custom leaf that merely ends in xpu stays unknown+# whatever its case.+check "custom leaf PRIVATE-XPU" "$(escape "$(make_venv '2.9.1+cpu' no z)" "https://mirror/simple/PRIVATE-XPU")" true++echo "migrating AWAY from xpu escapes too -- the pin is authoritative"+# An up-to-date +xpu install with the pin switched to another family: only install_python_stack+# applies the pin, so without this the user asked for CUDA and kept the XPU wheel.+check "cu128 pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no A)" "https://download.pytorch.org/whl/cu128")" false+check "rocm pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no B)" "https://download.pytorch.org/whl/rocm6.4")" false+check "cpu pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no C)" "https://download.pytorch.org/whl/cpu")" false+check "gfx pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no D)" "https://repo.radeon.com/whl/gfx1151")" false+check "FAMILY=cu128 over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no E)" "" "cu128")" false+check "rocm7.2 dotted pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no B2)" "https://download.pytorch.org/whl/rocm7.2")" false+# gfx is a PREFIX family on every side, because gfx120x-all is a real Radeon index leaf.+check "gfx120x-all pin over xpu wheel" "$(escape "$(make_venv '2.9.1+xpu' no D2)" "https://repo.radeon.com/whl/gfx120x-all")" false+# EXACT families only: a leaf that merely STARTS with one is a custom verbatim pin the shared+# classifiers never repair, so escaping on it would force a pass every update for nothing. A+# loose cu[0-9]*/rocm[0-9]* glob passes every one of these.+check "custom rocm-current over xpu" "$(escape "$(make_venv '2.9.1+xpu' no F)" "https://mirror/whl/rocm-current")" true+check "custom cu-private over xpu" "$(escape "$(make_venv '2.9.1+xpu' no G)" "https://mirror/whl/cu-private")" true+check "custom cu128-private over xpu" "$(escape "$(make_venv '2.9.1+xpu' no G2)" "https://mirror/whl/cu128-private")" true+check "custom cu128rc1 over xpu" "$(escape "$(make_venv '2.9.1+xpu' no G3)" "https://mirror/whl/cu128rc1")" true+check "custom rocm7.2-private over xpu" "$(escape "$(make_venv '2.9.1+xpu' no F2)" "https://mirror/whl/rocm7.2-private")" true+check "custom rocm7. over xpu" "$(escape "$(make_venv '2.9.1+xpu' no F3)" "https://mirror/whl/rocm7.")" true+check "custom rocm7.2.1 over xpu" "$(escape "$(make_venv '2.9.1+xpu' no F4)" "https://mirror/whl/rocm7.2.1")" true+check "custom cpu-private over xpu" "$(escape "$(make_venv '2.9.1+xpu' no F5)" "https://mirror/whl/cpu-private")" true+# ...and a non-XPU wheel must not be dragged in by a non-XPU pin.+check "cu128 pin over cuda wheel" "$(escape "$(make_venv '2.9.1+cu128' no H)" "https://download.pytorch.org/whl/cu128")" true++echo "a leaf that merely ends in xpu is NOT the curated family"+# The shared parsers call this an unknown family and refuse to act, so clearing the skip flag+# would force a pass every update that repairs nothing.+for _odd in "https://mirror/simple/private-xpu" "https://mirror/whl/cu128-xpu" "https://mirror/whl/rocm-xpu"; do+ check "custom leaf $(basename "$_odd") + cpu wheel" \+ "$(escape "$(make_venv '2.9.1+cpu' no r)" "$_odd")" true+ # ...but the wheel still decides: an xpu wheel with generic triton is owed the swap+ # whatever the odd pin says.+ check "custom leaf $(basename "$_odd") + xpu wheel + triton" \+ "$(escape "$(make_venv '2.9.1+xpu' yes s)" "$_odd")" false+done+# Non-XPU families must not be touched by any of this.+check "cuda pin + cuda wheel" "$(escape "$(make_venv '2.9.1+cu128' yes t)" "https://download.pytorch.org/whl/cu128")" true+check "rocm pin + rocm wheel" "$(escape "$(make_venv '2.9.1+rocm6.4' yes u)" "https://download.pytorch.org/whl/rocm6.4")" true+check "cpu pin + cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' yes v)" "https://download.pytorch.org/whl/cpu")" true++# --- parity with the helpers that would actually do the repair --------------------------------+# The escape only pays off if the leaf it calls "known" is one install_python_stack acts on, so+# ask both predicates rather than trust them to stay in step.+PY_STACK="$SCRIPT_DIR/../../studio/install_python_stack.py"+if [ -f "$PY_STACK" ] && command -v python3 >/dev/null 2>&1; then+ awk '/^ _setup_known_nonxpu_leaf\(\) \{/{on=1} on{print} on && /^ \}$/{exit}' \+ "$WORK/blk.sh" > "$WORK/leaf.sh"+ grep -q 'rocm\[0-9\]' "$WORK/leaf.sh" || { echo "FATAL: predicate not extracted" >&2; exit 1; }+ # shellcheck disable=SC1091+ . "$WORK/leaf.sh"+ _corpus="cpu cu118 cu126 cu128 cu130 rocm6.3 rocm6.4 rocm7.0 rocm7.2 gfx90a gfx1151+ gfx120x-all xpu cu128-private cu128rc1 cu128.1 cu-private rocm-current rocm7.+ rocm7.2.1 rocm7.2-private rocm.4 cpu-private gfx-private private-xpu cu rocm gfx"+ _pyout=$(cd "$(dirname "$PY_STACK")" && python3 -c '+import sys, install_python_stack as m+for leaf in sys.argv[1:]:+ known = m._is_pip_rocm_family_leaf(leaf) or leaf == "cpu" or m._is_cuda_family_leaf(leaf)+ print(leaf, "true" if known else "false")+' $_corpus) || { echo "FATAL: python predicate did not run" >&2; exit 1; }+ echo "the shell predicate agrees with install_python_stack leaf for leaf"+ while read -r _leaf _want; do+ [ -n "$_leaf" ] || continue+ _got=false+ _setup_known_nonxpu_leaf "$_leaf" && _got=true+ check "leaf $_leaf" "$_got" "$_want"+ done <<EOF+$_pyout+EOF+fi++echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/sh/test_setup_xpu_posix_summary.sh b/tests/sh/test_setup_xpu_posix_summary.shnew file mode 100755index 00000000000..56649370e32--- /dev/null+++ b/tests/sh/test_setup_xpu_posix_summary.sh@@ -0,0 +1,202 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The POSIX hardware summary must recognise a working Intel XPU runtime, and `studio update`+# must raise the bitsandbytes floor for it. The summary only tested NVIDIA / AMD / Apple, and+# `studio update` runs setup.sh, never install.sh, where the XPU bnb floor used to live.+#+# Unlike the Windows half this runs for real: the venv tree, torch/version.py and the+# interpreter are built here, so the disk read and the runtime probe are executed, not mocked.+set -u++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+SETUP_SH="${1:-$SCRIPT_DIR/../../studio/setup.sh}"+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++# The detection + floor block verbatim, from the Intel banner to the end of the bnb install.+awk '/^# Intel XPU\. There is no vendor probe here/, /^fi$/' "$SETUP_SH" > "$WORK/blk.sh"+[ -s "$WORK/blk.sh" ] || { echo "FATAL: XPU detection block not found in $SETUP_SH" >&2; exit 1; }+# An extraction that lost either half would make the cases below pass vacuously.+grep -q '_setup_xpu_ready=true' "$WORK/blk.sh" || { echo "FATAL: extraction lost the runtime probe" >&2; exit 1; }+grep -q 'bitsandbytes>=0.50.0' "$WORK/blk.sh" || { echo "FATAL: extraction lost the bnb floor" >&2; exit 1; }++PASS=0+FAIL=0+check() {+ if [ "$2" = "$3" ]; then+ PASS=$((PASS + 1))+ else+ printf ' FAIL %-34s got=%s want=%s\n' "$1" "$2" "$3"+ FAIL=$((FAIL + 1))+ fi+}++# Builds a venv whose torch reports $1 and whose xpu runtime answers $2 (ok|broken|none).+make_venv() {+ _v="$WORK/venv_$3"+ rm -rf "$_v"+ mkdir -p "$_v/bin"+ if [ -n "$1" ]; then+ mkdir -p "$_v/lib/python3.12/site-packages/torch"+ printf "from typing import Optional\n__version__ = '%s'\ndebug = False\n" "$1" \+ > "$_v/lib/python3.12/site-packages/torch/version.py"+ fi+ # Stands in for the interpreter: exit 0 only when the runtime is meant to initialise.+ case "$2" in+ ok) printf '#!/bin/sh\nexit 0\n' > "$_v/bin/python" ;;+ broken) printf '#!/bin/sh\nexit 1\n' > "$_v/bin/python" ;;+ none) : ;;+ esac+ [ -f "$_v/bin/python" ] && chmod +x "$_v/bin/python"+ printf '%s' "$_v"+}++# Runs the block against a venv and echoes "<is_xpu> <ready> <bnb_fired>".+run_case() {+ (+ VENV_DIR="$1"+ # shellcheck disable=SC2317+ fast_install() { echo "BNB_FIRED" >> "$WORK/fired"; return 0; }+ # shellcheck disable=SC2317+ run_quiet() { shift; "$@"; }+ # shellcheck disable=SC2317+ run_quiet_no_exit() { shift; "$@"; }+ # shellcheck disable=SC2317+ timeout() { shift; "$@"; }+ # shellcheck disable=SC2317+ substep() { :; }+ : > "$WORK/fired"+ # shellcheck disable=SC1091+ . "$WORK/blk.sh"+ _fired=no+ [ -s "$WORK/fired" ] && _fired=yes+ echo "$_setup_torch_is_xpu $_setup_xpu_ready $_fired"+ )+}++echo "a working XPU runtime is recognised, and only a real one"+check "xpu wheel + runtime ok" "$(run_case "$(make_venv '2.9.1+xpu' ok a)")" "true true yes"+# A +xpu wheel installs fine on a host whose driver never initialises: it must raise the bnb+# floor but must NOT claim a GPU in the summary.+check "xpu wheel + runtime dead" "$(run_case "$(make_venv '2.9.1+xpu' broken b)")" "true false yes"+check "cuda wheel" "$(run_case "$(make_venv '2.9.1+cu128' ok c)")" "false false no"+check "rocm wheel" "$(run_case "$(make_venv '2.9.1+rocm6.4' ok d)")" "false false no"+check "untagged wheel" "$(run_case "$(make_venv '2.9.1' ok e)")" "false false no"+check "no torch installed" "$(run_case "$(make_venv '' ok f)")" "false false no"+check "no venv at all" "$(run_case "$WORK/nope")" "false false no"+# The interpreter is missing but the wheel is there: no crash, no GPU claim, floor still raised.+check "xpu wheel, no interpreter" "$(run_case "$(make_venv '2.9.1+xpu' none g)")" "true false yes"++echo "the summary has an XPU arm, ranked below NVIDIA and AMD"+# Anchored at column 0: both flags are re-tested later inside indented blocks, and matching one+# of those would compare the arm against the wrong line.+_arm=$(grep -n '^elif \[ "\$_setup_xpu_ready" = true \]; then' "$SETUP_SH" | head -1 | cut -d: -f1)+_nv=$(grep -n '^if \[ "\$_setup_nvidia_usable" = true \]; then' "$SETUP_SH" | head -1 | cut -d: -f1)+_amd=$(grep -n '^elif \[ "\$_setup_amd_detected" = true \]; then' "$SETUP_SH" | head -1 | cut -d: -f1)+_none=$(grep -n 'none (chat-only / GGUF)' "$SETUP_SH" | head -1 | cut -d: -f1)+check "arm exists" "$([ -n "$_arm" ] && echo yes || echo no)" "yes"+check "ranked after NVIDIA" "$([ -n "$_arm" ] && [ -n "$_nv" ] && [ "$_arm" -gt "$_nv" ] && echo yes || echo no)" "yes"+check "ranked after AMD" "$([ -n "$_arm" ] && [ -n "$_amd" ] && [ "$_arm" -gt "$_amd" ] && echo yes || echo no)" "yes"+check "ranked before the CPU arm" "$([ -n "$_arm" ] && [ -n "$_none" ] && [ "$_arm" -lt "$_none" ] && echo yes || echo no)" "yes"+# The unavailable-runtime arm must not promise CPU training: with neither CUDA nor XPU,+# unsloth/device_type.py raises NotImplementedError, so importing unsloth fails outright.+# Anchored on the ELIF at column 0 and stopped at the next arm: a plain awk range on the flag+# name matches the bitsandbytes `if` block, whose own "unavailable" warning would pass on any+# wording. Comment lines are dropped, since the arm quotes the wording it must NOT use.+_warn_arm=$(awk '/^elif \[ "\$_setup_torch_is_xpu" = true \]; then$/{on=1;next} on && /^elif|^else/{exit} on' "$SETUP_SH" | grep -v '^[[:space:]]*#')+check "warn arm was extracted" "$(printf '%s' "$_warn_arm" | grep -ci 'XPU runtime unavailable')" "1"+check "no CPU-training promise" "$(printf '%s' "$_warn_arm" | grep -ci 'run on CPU\|runs on CPU')" "0"+check "says training is unavailable" "$(printf '%s' "$_warn_arm" | grep -ci 'are unavailable')" "1"++# The floor must run before the summary; the other order would report on a stale venv.+_bnb=$(grep -n 'install bitsandbytes (xpu)' "$SETUP_SH" | head -1 | cut -d: -f1)+check "floor precedes the summary" "$([ -n "$_bnb" ] && [ -n "$_none" ] && [ "$_bnb" -lt "$_none" ] && echo yes || echo no)" "yes"+# run_quiet routes failure to setup_fail and EXITS, which would abort an otherwise fine+# `studio update` over a best-effort step and make the warning below unreachable.+check "floor uses the nonfatal wrapper" \+ "$(grep -q 'run_quiet_no_exit "install bitsandbytes (xpu)"' "$SETUP_SH" && echo yes || echo no)" "yes"+# An unbounded `import torch` hangs forever on a stalled Intel driver, the host this classifies.+check "runtime probe is bounded" \+ "$(grep -q 'timeout 60 "\$VENV_DIR/bin/python" -c "\$_setup_xpu_probe"' "$SETUP_SH" && echo yes || echo no)" "yes"+# ...and `timeout` is not everywhere (base macOS, minimal Linux images), so the fallback arm+# ran the very probe this bounds with no deadline at all.+_probe=$(sed -n "s/^ *_setup_xpu_probe='\(.*\)'$/\1/p" "$SETUP_SH" | head -1)+check "probe was extracted" "$([ -n "$_probe" ] && echo yes || echo no)" "yes"+check "probe carries its own deadline" \+ "$(printf '%s' "$_probe" | grep -q 'signal.alarm(' && echo yes || echo no)" "yes"+# Both arms must run the SAME string, or only one is bounded. Comment lines are excluded: the+# summary arm below names the same call.+check "no second probe literal" \+ "$(grep -v '^ *#' "$SETUP_SH" | grep -c "torch.xpu.is_available()")" "1"+check "fallback arm reuses the probe" \+ "$(grep -q 'elif "\$VENV_DIR/bin/python" -c "\$_setup_xpu_probe"' "$SETUP_SH" && echo yes || echo no)" "yes"+# Execute it against a torch that never returns, alarm shortened: python installs no SIGALRM+# handler, so the default action kills the process even while a stalled driver blocks in C.+if command -v python3 >/dev/null 2>&1; then+ mkdir -p "$WORK/fakemod"+ printf 'import ctypes\nctypes.CDLL(None).sleep(60)\n' > "$WORK/fakemod/torch.py"+ _fast_probe=$(printf '%s' "$_probe" | sed 's/signal\.alarm([0-9]*)/signal.alarm(2)/')+ # Own watchdog, not GNU timeout: macOS ships none, and a missing one exits 127 instantly,+ # which reads as "the probe was killed" and passed both checks below without python running.+ _t0=$(date +%s)+ ( cd "$WORK/fakemod" && PYTHONPATH="$WORK/fakemod" python3 -c "$_fast_probe" ) >/dev/null 2>&1 &+ _probe_pid=$!+ ( sleep 30; kill -9 "$_probe_pid" ) >/dev/null 2>&1 &+ _watchdog_pid=$!+ # Silenced: the shell reports "Alarm clock" for a signal-killed job here.+ { wait "$_probe_pid"; _rc=$?; } 2>/dev/null+ kill "$_watchdog_pid" >/dev/null 2>&1+ _elapsed=$(( $(date +%s) - _t0 ))+ check "a wedged driver is killed, not waited on" "$([ "$_rc" -ne 0 ] && echo yes || echo no)" "yes"+ # Lower bound too: the alarm is 2s, so an instant return means the probe never ran.+ check "killed at the deadline, not after" \+ "$([ "$_elapsed" -ge 1 ] && [ "$_elapsed" -lt 10 ] && echo yes || echo no)" "yes"+fi++# The dependency pass is the ONLY thing that acts on an XPU pin, so a CPU install switched to+# the xpu family would keep its CPU wheel forever once the fast path skips that pass.+_esc=$(grep -n 'XPU index pinned but torch does not match' "$SETUP_SH" | head -1 | cut -d: -f1)+_gate=$(grep -n '^if \[ "\$_SKIP_PYTHON_DEPS" = false \]; then' "$SETUP_SH" | head -1 | cut -d: -f1)+check "fast path has an XPU escape" "$([ -n "$_esc" ] && echo yes || echo no)" "yes"+check "escape precedes the skip gate" \+ "$([ -n "$_esc" ] && [ -n "$_gate" ] && [ "$_esc" -lt "$_gate" ] && echo yes || echo no)" "yes"+# It must clear the flag, not merely warn.+check "escape forces the dependency pass" \+ "$(awk -v a="$_esc" 'NR>=a && NR<=a+2 && /_SKIP_PYTHON_DEPS=false/{f=1} END{print (f?"yes":"no")}' "$SETUP_SH")" "yes"++# An authenticated or fragmented mirror is a supported pin shape; a raw suffix test reads it as+# "no XPU pin" and skips the repair.+check "pin match strips the query" \+ "$(grep -q '_setup_pin="\${_setup_pin%%\\?\*}"' "$SETUP_SH" && echo yes || echo no)" "yes"+check "pin match strips the fragment" \+ "$(grep -q '_setup_pin="\${_setup_pin%%\\#\*}"' "$SETUP_SH" && echo yes || echo no)" "yes"+# The escape must not launch an interpreter: a wedged driver hangs inside `import torch`, and+# this runs before the bounded probes. Bounded by the acting chain, not a line offset, so a new+# check inside cannot move the window. What it DECIDES is test_setup_xpu_fastpath_escape.sh.+_blk=$(awk '/_setup_pin="\$\{UNSLOTH_TORCH_INDEX_URL/{on=1} on{print} on && /_SKIP_PYTHON_DEPS=false$/{n++} n==2{exit}' "$SETUP_SH")+check "escape block was found" "$([ -n "$_blk" ] && echo yes || echo no)" "yes"+check "escape reads the flavour off disk" \+ "$(printf '%s' "$_blk" | grep -q 'site-packages/torch/version.py' && echo yes || echo no)" "yes"+check "escape launches no interpreter" \+ "$(printf '%s' "$_blk" | grep -q '\$VENV_DIR/bin/python' && echo no || echo yes)" "yes"+# One %/ leaves a slash on ".../xpu//", which reads as "no XPU pin".+check "pin match strips every trailing slash" \+ "$(printf '%s' "$_blk" | grep -q 'while \[ "\${_setup_pin%/}" != "\$_setup_pin" \]' && echo yes || echo no)" "yes"++echo "an installed +xpu wheel whose runtime is dead gets its own arm"+# is_available() false on a real +xpu install means the compute DRIVER is missing or too old;+# falling through to "none (chat-only / GGUF)" hides the one action that fixes it.+_dead=$(grep -n '^elif \[ "\$_setup_torch_is_xpu" = true \]; then' "$SETUP_SH" | head -1 | cut -d: -f1)+check "dead-runtime arm exists" "$([ -n "$_dead" ] && echo yes || echo no)" "yes"+check "ranked after the ready arm" \+ "$([ -n "$_dead" ] && [ -n "$_arm" ] && [ "$_dead" -gt "$_arm" ] && echo yes || echo no)" "yes"+check "ranked before the CPU arm" \+ "$([ -n "$_dead" ] && [ -n "$_none" ] && [ "$_dead" -lt "$_none" ] && echo yes || echo no)" "yes"+# Matched on the substep ARGUMENT, not any line in the window: the comment above the arm says+# "compute driver" too, so a looser match stayed green with the message itself gutted.+check "arm names the driver fix" \+ "$(awk -v a="$_dead" 'NR>a && NR<a+8 && /substep "[^"]*compute driver/{f=1} END{print (f?"yes":"no")}' "$SETUP_SH")" "yes"++echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/sh/test_torch_flavor.sh b/tests/sh/test_torch_flavor.shindex 55da2c0f070..2737357b6ce 100755--- a/tests/sh/test_torch_flavor.sh+++ b/tests/sh/test_torch_flavor.sh@@ -52,6 +52,9 @@ assert_eq "nightly cu130" "cu130" "$(_torch_flavor_tag '2.10.0.dev20250601+assert_eq "cu130 with suffix" "cu130" "$(_torch_flavor_tag '2.10.0+cu130.post1')"assert_eq "empty -> empty" "" "$(_torch_flavor_tag '')"assert_eq "garbage -> cpu" "cpu" "$(_torch_flavor_tag 'not-a-version')"+# Intel XPU wheels carry a +xpu local label; without this arm a correct XPU build reads as "cpu".+assert_eq "xpu wheel" "xpu" "$(_torch_flavor_tag '2.10.0+xpu')"+assert_eq "nightly xpu" "xpu" "$(_torch_flavor_tag '2.11.0.dev20260401+xpu')"echo "=== _expected_torch_flavor_tag ==="assert_eq "cu130 index" "cu130" "$(_expected_torch_flavor_tag 'https://download.pytorch.org/whl/cu130')"@@ -83,6 +86,13 @@ assert_eq "suffixed rocm7.2-private" "" "$(_expected_torch_flavor_tag 'https://cassert_eq "suffixed rocm7-current" "" "$(_expected_torch_flavor_tag 'https://co.internal/whl/rocm7-current')"assert_eq "two-dot rocm7.2.1" "" "$(_expected_torch_flavor_tag 'https://co.internal/whl/rocm7.2.1')"assert_eq "bare rocm7 stays" "rocm" "$(_expected_torch_flavor_tag 'https://download.pytorch.org/whl/rocm7')"+# The xpu leaf is a GPU flavor, so a pinned xpu index repairs a stale CPU wheel. A suffixed+# xpu-* leaf is a custom mirror pin -> "" (custom), like cu128-private.+assert_eq "xpu index" "xpu" "$(_expected_torch_flavor_tag 'https://download.pytorch.org/whl/xpu')"+assert_eq "xpu trailing /" "xpu" "$(_expected_torch_flavor_tag 'https://download.pytorch.org/whl/xpu/')"+assert_eq "mirror xpu leaf" "xpu" "$(_expected_torch_flavor_tag 'https://my.mirror/pytorch/whl/xpu')"+assert_eq "query-bearing xpu" "xpu" "$(_expected_torch_flavor_tag 'https://m/whl/xpu?token=x')"+assert_eq "suffixed xpu-private" "" "$(_expected_torch_flavor_tag 'https://co.internal/whl/xpu-private')"echo "=== _torch_index_repairable ==="assert_eq "cu130 repairable" "yes" "$(_torch_index_repairable 'https://download.pytorch.org/whl/cu130')"@@ -93,6 +103,10 @@ assert_eq "cpu NOT repairable" "no" "$(_torch_index_repairable 'https://downlassert_eq "unknown NOT repair" "no" "$(_torch_index_repairable 'https://my.mirror/whl/simple')"# A suffixed rocm leaf is a verbatim pin, not a --default-index repairable family.assert_eq "rocm-private NOT repair" "no" "$(_torch_index_repairable 'https://co.internal/whl/rocm7.2-private')"+# whl/xpu is a plain PEP 503 index, so a stale CPU wheel under an xpu pin is repairable.+assert_eq "xpu repairable" "yes" "$(_torch_index_repairable 'https://download.pytorch.org/whl/xpu')"+assert_eq "xpu mirror repair" "yes" "$(_torch_index_repairable 'https://my.mirror/pytorch/whl/xpu/')"+assert_eq "xpu-private NOT repair" "no" "$(_torch_index_repairable 'https://co.internal/whl/xpu-private')"echo "=== _is_pip_rocm_family_leaf ==="assert_family() {diff --git a/tests/sh/test_xpu_bitsandbytes_reachable.sh b/tests/sh/test_xpu_bitsandbytes_reachable.shnew file mode 100755index 00000000000..ff7f75a95c4--- /dev/null+++ b/tests/sh/test_xpu_bitsandbytes_reachable.sh@@ -0,0 +1,82 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The Intel XPU bitsandbytes pass must run on BOTH install paths.+#+# It first shipped inside the `elif [ -n "$TORCH_INDEX_URL" ]` arm, which a migrated+# environment never enters, so exactly the environment it existed for missed it. The AMD+# passes solve that by existing twice; this one sits past the chain instead. Asserted here:+# the block is placed where every arm reaches it, and it still fires only on the xpu leaf.+set -u++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+INSTALL_SH="${1:-$SCRIPT_DIR/../../install.sh}"+BANNER='# ── Intel XPU: bitsandbytes with XPU kernels ──'+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT++# Indentation-tolerant: a block indented back INTO an install arm must still extract, so the+# placement check below reports it rather than a blunt "not found".+awk -v b="^[[:space:]]*$BANNER\$" '$0 ~ b, /^[[:space:]]*fi$/' "$INSTALL_SH" > "$WORK/blk.sh"+[ -s "$WORK/blk.sh" ] || { echo "FATAL: XPU bitsandbytes block not found in $INSTALL_SH" >&2; exit 1; }+# An extraction that lost the payload would make every case below pass vacuously.+grep -q '_BNB_XPU_SPEC' "$WORK/blk.sh" || { echo "FATAL: extraction lost the spec" >&2; exit 1; }++# The real leaf parser, so the gate is tested against the shipped one.+awk '/^_torch_index_url_leaf\(\) \{/,/^\}/' "$INSTALL_SH" > "$WORK/leaf.sh"+[ -s "$WORK/leaf.sh" ] || { echo "FATAL: could not extract _torch_index_url_leaf" >&2; exit 1; }++PASS=0+FAIL=0++# Reachability is a property of the chain: confirm the block sits after the fi that closes+# `if _MIGRATED / elif TORCH_INDEX_URL / else`.+_chain_start=$(grep -n '^if \[ "\$_MIGRATED" = true \]; then$' "$INSTALL_SH" | head -1 | cut -d: -f1)+_chain_fi=$(grep -n '^fi$' "$INSTALL_SH" | awk -F: -v s="$_chain_start" '$1 > s { print $1; exit }')+_blk_line=$(grep -n "^[[:space:]]*$BANNER\$" "$INSTALL_SH" | head -1 | cut -d: -f1)+if [ -n "$_chain_fi" ] && [ -n "$_blk_line" ] && [ "$_blk_line" -gt "$_chain_fi" ]; then+ echo " PASS placed past the install chain (block $_blk_line, chain closes $_chain_fi)"+ PASS=$((PASS + 1))+else+ echo " FAIL block at ${_blk_line:-?} is inside an install arm (chain closes ${_chain_fi:-?})"+ FAIL=$((FAIL + 1))+fi++run_case() {+ _migrated="$1"; _skip="$2"; _url="$3"; _want="$4"+ _got=$(+ export _MIGRATED="$_migrated" SKIP_TORCH="$_skip" TORCH_INDEX_URL="$_url"+ _VENV_PY=/nonexistent/python; C_WARN=""; _BNB_XPU_SPEC="bitsandbytes>=0.50.0"+ substep() { :; }+ run_install_cmd() { shift; echo "FIRED: $*"; }+ # shellcheck disable=SC1090+ . "$WORK/leaf.sh"; . "$WORK/blk.sh"+ )+ _fired=no+ case "$_got" in *FIRED:*) _fired=yes ;; esac+ if [ "$_fired" = "$_want" ]; then+ PASS=$((PASS + 1))+ else+ printf ' FAIL migrated=%s skip_torch=%s index=%s fired=%s want=%s\n' \+ "$_migrated" "$_skip" "${_url:-<empty>}" "$_fired" "$_want"+ FAIL=$((FAIL + 1))+ fi+}++# [migrated, fresh] x [xpu, mirrored xpu, cuda, rocm, cpu, none] x [torch, no-torch]. The+# mirror row is the point of the leaf parser: an xpu leaf behind a private index still counts.+for m in true false; do+ for s in false true; do+ want_xpu=yes+ [ "$s" = true ] && want_xpu=no+ run_case "$m" "$s" "https://download.pytorch.org/whl/xpu" "$want_xpu"+ run_case "$m" "$s" "https://mirror.internal/pytorch/whl/xpu/" "$want_xpu"+ run_case "$m" "$s" "https://download.pytorch.org/whl/cu128" no+ run_case "$m" "$s" "https://download.pytorch.org/whl/rocm6.4" no+ run_case "$m" "$s" "https://download.pytorch.org/whl/cpu" no+ run_case "$m" "$s" "" no+ done+done++echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/sh/test_xpu_torch_spec_parity.sh b/tests/sh/test_xpu_torch_spec_parity.shnew file mode 100755index 00000000000..5fc6c2cc735--- /dev/null+++ b/tests/sh/test_xpu_torch_spec_parity.sh@@ -0,0 +1,69 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The Intel XPU torch trio must be identical in every place that installs it: install.sh,+# studio/install_python_stack.py (the `unsloth studio update` route) and install.ps1. A drifted+# floor gives a different torch depending on which command the user ran, and the 2.6 floor is+# not cosmetic -- unsloth/models/_utils.py raises at import for an XPU device below it.+#+# Windows on ARM legitimately drops torchaudio (no win_arm64 wheel), so install.ps1 is checked+# for the floors rather than for an identical trio.+set -u++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+ROOT="$SCRIPT_DIR/../.."+INSTALL_SH="$ROOT/install.sh"+STACK_PY="$ROOT/studio/install_python_stack.py"+INSTALL_PS1="$ROOT/install.ps1"++PASS=0+FAIL=0+check() {+ if [ "$2" = "$3" ]; then+ PASS=$((PASS + 1))+ else+ printf ' FAIL %-38s got=%s want=%s\n' "$1" "$2" "$3"+ FAIL=$((FAIL + 1))+ fi+}++TORCH='torch>=2.6,<2.11.0'+VISION='torchvision>=0.21,<0.26.0'+AUDIO='torchaudio>=2.6,<2.11.0'++# install.sh sets these in the xpu arm of its index-leaf case.+sh_has() { grep -qF "\"$1\"" "$INSTALL_SH" && echo yes || echo no; }+check "install.sh torch floor" "$(sh_has "$TORCH")" yes+check "install.sh torchvision" "$(sh_has "$VISION")" yes+check "install.sh torchaudio" "$(sh_has "$AUDIO")" yes++# The shared stack keeps them in _XPU_TORCH_PKG_SPEC. Read the tuple rather than grepping the+# whole file: a stray match elsewhere would hide a drifted spec.+spec=$(awk '/^_XPU_TORCH_PKG_SPEC/, /^\)/' "$STACK_PY")+[ -n "$spec" ] || { echo "FATAL: _XPU_TORCH_PKG_SPEC not found in $STACK_PY" >&2; exit 1; }+py_has() { printf '%s' "$spec" | grep -qF "\"$1\"" && echo yes || echo no; }+check "install_python_stack torch" "$(py_has "$TORCH")" yes+check "install_python_stack torchvision" "$(py_has "$VISION")" yes+check "install_python_stack torchaudio" "$(py_has "$AUDIO")" yes++# install.ps1 builds the trio in $_xpuSpecs and drops torchaudio only on win-arm64.+ps_has() { grep -qF "\"$1\"" "$INSTALL_PS1" && echo yes || echo no; }+check "install.ps1 torch floor" "$(ps_has "$TORCH")" yes+check "install.ps1 torchvision" "$(ps_has "$VISION")" yes+check "install.ps1 torchaudio" "$(ps_has "$AUDIO")" yes++# The pin must be acted on from the update route: an xpu leaf names no family the cuda/rocm+# helpers know, so without this the CPU wheel survives forever.+check "stack classifies the xpu leaf" \+ "$(grep -q '_TORCH_BACKEND = "xpu"' "$STACK_PY" && echo yes || echo no)" yes+check "stack repairs an xpu pin" \+ "$(grep -q 'def _ensure_xpu_torch' "$STACK_PY" && echo yes || echo no)" yes+# Wired in at BOTH repair points, or the final pass silently undoes the first.+check "repair runs at both call sites" \+ "$(grep -c '^ _ensure_xpu_torch()' "$STACK_PY")" 2+# The ROCm helper must skip an xpu backend, or it treats the pin as an AMD host.+check "rocm helper skips xpu" \+ "$(grep -q '_TORCH_BACKEND in ("cuda", "cpu", "xpu")' "$STACK_PY" && echo yes || echo no)" yes++echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ] || exit 1diff --git a/tests/studio/test_about_tab_xpu_runtime_contract.py b/tests/studio/test_about_tab_xpu_runtime_contract.pynew file mode 100644index 00000000000..7a101334663--- /dev/null+++ b/tests/studio/test_about_tab_xpu_runtime_contract.py@@ -0,0 +1,68 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""The About tab must show a runtime row on an Intel XPU host.++`hardware.py` has always emitted `versions["xpu"]`, but the frontend only ever read `cuda`+and `rocm`. On an Arc host both of those are null, so the runtime row vanished entirely+while the GPU name and VRAM rows still rendered -- a host that looks half-detected. That+was unreachable on Windows until the installer learned to select XPU wheels, which is what+makes it worth a guard now.+"""++from pathlib import Path+++REPO = Path(__file__).resolve().parents[2]+HARDWARE = REPO / "studio/backend/utils/hardware/hardware.py"+HOOK = REPO / "studio/frontend/src/hooks/use-hardware-info.ts"+ABOUT = REPO / "studio/frontend/src/features/settings/tabs/about-tab.tsx"+LOCALES = REPO / "studio/frontend/src/i18n/locales"+++def test_backend_still_emits_an_xpu_version():+ # If this stops being true the frontend field below is dead weight; fail loudly.+ src = HARDWARE.read_text(encoding = "utf-8")+ assert 'versions["xpu"]' in src+++def test_hardware_info_declares_and_maps_xpu():+ src = HOOK.read_text(encoding = "utf-8")+ assert "xpu: string | null;" in src, "HardwareInfo must declare xpu"+ assert "xpu: data?.versions?.xpu ?? null," in src, "xpu must be mapped from the API response"+ # The default must carry the key too, or the first render is `undefined` and the row flickers.+ assert src.count("xpu: null,") >= 1+++def test_about_tab_renders_the_xpu_runtime_row():+ src = ABOUT.read_text(encoding = "utf-8")+ assert 'labelKey: "settings.about.xpu"' in src, "About tab must offer an xpu runtime label"+ assert "hw.xpu" in src+ # The section itself must open for an xpu-only host, not just for cuda/rocm.+ assert "hw.gpus.length > 0 || runtimes.length > 0" in src+++def test_about_tab_shows_every_runtime_not_just_the_first():+ # hardware.py sets versions["cuda"] and versions["xpu"] independently, so a dual build in+ # forced-XPU mode reports both; returning the first match hid the xpu row on that host.+ src = ABOUT.read_text(encoding = "utf-8")+ assert "acceleratorRuntimes" in src, "the runtime picker must return all matches"+ assert src.count("rows.push(") == 3, "cuda, rocm and xpu must each be pushed"+ assert "runtimes.map(" in src, "every reported runtime must be rendered"+ # An early return is what caused the bug; the picker must collect instead.+ picker = src.split("function acceleratorRuntimes")[1].split("\n}")[0]+ assert picker.count("return") == 1, "the picker must not return early on the first hit"+++def test_the_xpu_label_resolves_in_every_locale():+ # en is the fallback source, so it is the only file that MUST carry the key (check-parity.ts+ # allows partial overlays). Requiring it everywhere would break the next locale added for no+ # gain: the label is a proper noun, so the fallback equals a translation.+ assert 'xpu: "XPU",' in (LOCALES / "en.ts").read_text(encoding = "utf-8")+ # Overlays must not DISAGREE with en. check-parity.ts rejects a key absent from en; this+ # catches the value.+ wrong = [+ p.name+ for p in sorted(LOCALES.glob("*.ts"))+ for line in p.read_text(encoding = "utf-8").splitlines()+ if line.strip().startswith("xpu:") and line.strip() != 'xpu: "XPU",'+ ]+ assert not wrong, f"locales whose xpu label diverges from en: {wrong}"diff --git a/tests/studio/test_intel_registry_fallback.ps1 b/tests/studio/test_intel_registry_fallback.ps1new file mode 100644index 00000000000..5345543465a--- /dev/null+++ b/tests/studio/test_intel_registry_fallback.ps1@@ -0,0 +1,147 @@+#!/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+# Unit tests for Get-IntelRegistryAdapterNames, the display-class-key fallback used when the+# bounded CIM scan does not answer. AST-extracted from both installers (which must stay+# identical) and run in-process with Get-ChildItem / Get-ItemProperty mocked, so the hive is a+# fixture and no Windows registry is touched. Its oracle is windows_intel_gpu_in_registry() in+# studio/install_llama_prebuilt.py, which reads the same key: the two must agree on "is an+# Intel display adapter present".+# Run: pwsh -NoProfile -File tests/studio/test_intel_registry_fallback.ps1++$ErrorActionPreference = "Stop"+$repo = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$fnName = "Get-IntelRegistryAdapterNames"++function Get-FunctionText {+ param([string] $Path, [string] $Name)+ $tokens = $null; $errors = $null+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors)+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$Path has parse errors" }+ $fn = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name+ }, $true)+ if ($fn.Count -ne 1) { throw "expected exactly one $Name in $Path, found $($fn.Count)" }+ return $fn[0].Extent.Text+}++$installText = Get-FunctionText (Join-Path $repo "install.ps1") $fnName+$setupText = Get-FunctionText (Join-Path $repo "studio/setup.ps1") $fnName++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++# Both installers carry their own copy (install.ps1 nests it in a function, setup.ps1 does+# not), so compare with indentation normalised.+function Normalize($text) { (($text -replace "`r", "") -split "`n" | ForEach-Object { $_.Trim() }) -join "`n" }++Write-Host "$fnName is identical in both installers"+Check "install.ps1 and studio/setup.ps1 agree" ((Normalize $installText) -eq (Normalize $setupText))+# An empty or wrong extraction would make every case below pass vacuously.+Check "extraction kept the display class key" ($installText -match '4d36e968-e325-11ce-bfc1-08002be10318')+Check "extraction kept the PCI vendor id" ($installText -match 'ven_8086')++# --- registry fixture -----------------------------------------------------------------------+# Throw='prop' models a provider blow-up on one subkey (corrupt hive); NullProps models the+# ordinary access-denied read, which is non-terminating and yields $null under -EA SilentlyContinue.+function New-Adapter {+ param([string] $Key, [string] $Desc, [string] $DevId, [string] $Throw = "none", [switch] $NullProps)+ [pscustomobject]@{ Key = $Key; Desc = $Desc; DevId = $DevId; Throw = $Throw; NullProps = [bool]$NullProps }+}++function Get-AdapterNames {+ param([object[]] $Adapters, [switch] $RootThrows)+ $sb = [scriptblock]::Create(@"+param(`$Adapters, `$RootThrows)+function Get-ChildItem {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ if (`$RootThrows) { throw "class key unreadable" }+ foreach (`$a in `$Adapters) { [pscustomobject]@{ PSChildName = `$a.Key; PSPath = "MOCK::`$(`$a.Key)" } }+}+function Get-ItemProperty {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ `$a = `$Adapters | Where-Object { `$_.Key -eq (`$LiteralPath -replace '^MOCK::', '') } | Select-Object -First 1+ if (-not `$a) { return `$null }+ if (`$a.Throw -eq 'prop') { throw "access denied" }+ if (`$a.NullProps) { return `$null }+ `$o = [pscustomobject]@{}+ if (`$null -ne `$a.Desc) { `$o | Add-Member DriverDesc `$a.Desc }+ if (`$null -ne `$a.DevId) { `$o | Add-Member MatchingDeviceId `$a.DevId }+ return `$o+}+$installText+@($fnName)+"@)+ # The caller wraps this in try/catch, so a throw here means "no adapters", not a crash.+ try { return , @(& $sb $Adapters $RootThrows) } catch { return @() }+}++# The caller's own filter, verbatim from install.ps1 and studio/setup.ps1.+function Test-Xpu { param([object[]] $Names)+ [bool]($Names | Where-Object { $_ -match "(?i)Intel.*(Arc|Data Center GPU)" } | Select-Object -First 1)+}++$VEN = "PCI\VEN_8086&DEV_56A0"+$ARC = "Intel(R) Arc(TM) A770 Graphics"+# Non-English Windows ships localized brand strings, leaving the vendor id as the only ASCII+# anchor -- which is why the match arm cannot rely on DriverDesc alone.+$ARC_JP = [char]0x30A4 + [char]0x30F3 + [char]0x30C6 + [char]0x30EB + "(R) Arc(TM) A770"++Write-Host "Intel adapters are found and classified"+Check "Arc, English DriverDesc" (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" $ARC $VEN)))+Check "Arc, localized DriverDesc" (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" $ARC_JP $VEN)))+Check "Data Center GPU Max" (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" "Intel(R) Data Center GPU Max 1550" $VEN)))+Check "Arc behind an NVIDIA primary" (Test-Xpu (Get-AdapterNames @((New-Adapter "0000" "NVIDIA GeForce RTX 4090" "PCI\VEN_10DE&DEV_2684"), (New-Adapter "0001" $ARC $VEN))))+Check "Arc behind an AMD primary" (Test-Xpu (Get-AdapterNames @((New-Adapter "0000" "AMD Radeon RX 7900 XTX" "PCI\VEN_1002&DEV_744C"), (New-Adapter "0001" $ARC $VEN))))++Write-Host "Intel without XPU wheels stays off the xpu index"+Check "iGPU, English DriverDesc" (-not (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" "Intel(R) UHD Graphics 770" $VEN))))+Check "iGPU, OEM DriverDesc" (-not (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" "OEM Display Adapter" $VEN))))+Check "vendor id, empty DriverDesc" (-not (Test-Xpu (Get-AdapterNames @(New-Adapter "0000" "" $VEN))))+# A vendor-id hit with a localized or OEM-branded name must still count as an Intel GPU, or+# the caller's Intel filter discards it.+Check "OEM DriverDesc still an adapter" ((Get-AdapterNames @(New-Adapter "0000" "OEM Display Adapter" $VEN)).Count -eq 1)++Write-Host "Non-Intel hosts report nothing"+Check "NVIDIA only" ((Get-AdapterNames @(New-Adapter "0000" "NVIDIA GeForce RTX 4090" "PCI\VEN_10DE&DEV_2684")).Count -eq 0)+Check "AMD only" ((Get-AdapterNames @(New-Adapter "0000" "AMD Radeon RX 7900 XTX" "PCI\VEN_1002&DEV_744C")).Count -eq 0)+Check "empty class key" ((Get-AdapterNames @()).Count -eq 0)+Check "class key unreadable" ((Get-AdapterNames @(New-Adapter "0000" $ARC $VEN) -RootThrows).Count -eq 0)+# "Properties" is ACL-restricted on every Windows install; only numeric subkeys are adapters.+Check "non-numeric subkey ignored" ((Get-AdapterNames @(New-Adapter "Configuration" $ARC $VEN)).Count -eq 0)++Write-Host "One unreadable subkey does not hide the rest"+Check "throwing subkey before the Arc" (Test-Xpu (Get-AdapterNames @((New-Adapter "0000" $null $null "prop"), (New-Adapter "0001" $ARC $VEN))))+Check "throwing subkey after the Arc" (Test-Xpu (Get-AdapterNames @((New-Adapter "0000" $ARC $VEN), (New-Adapter "0001" $null $null "prop"))))+Check "ACL Properties beside an Arc" (Test-Xpu (Get-AdapterNames @((New-Adapter "Properties" $null $null "prop"), (New-Adapter "0000" $ARC $VEN))))+Check "denied read before the Arc" (Test-Xpu (Get-AdapterNames @((New-Adapter "0000" $null $null -NullProps), (New-Adapter "0001" $ARC $VEN))))+Check "every subkey unreadable" ((Get-AdapterNames @((New-Adapter "0000" $null $null "prop"), (New-Adapter "0001" $null $null "prop"))).Count -eq 0)++# --- drift guards on the two constants the installers assemble rather than ask for ---+$setupText = Get-Content -Raw (Join-Path $repo "studio/setup.ps1")+$installText2 = Get-Content -Raw (Join-Path $repo "install.ps1")+$manifestPy = Get-Content -Raw (Join-Path $repo "studio/install_manifest.py")++Write-Host "constants the installers hard-code stay in step with their source of truth"+# setup.ps1 joins this onto $VenvDir instead of asking install_manifest, so a rename there+# would silently stop the Triton swap from holding the manifest.+$manifestName = if ($manifestPy -match '(?m)^MANIFEST_NAME\s*=\s*"([^"]+)"') { $Matches[1] } else { "" }+Check "install_manifest exposes MANIFEST_NAME" ($manifestName -ne "")+Check "setup.ps1 uses that exact file name" ($manifestName -and $setupText.Contains("`"$manifestName`""))++# The reconciliation gate must key off the XPU match, not off "any Intel name": a hybrid laptop+# reports an ASCII "Intel UHD" next to a localized Arc, and keying on Intel stops at the UHD.+foreach ($pair in @(@("install.ps1", $installText2), @("studio/setup.ps1", $setupText))) {+ Check "$($pair[0]) gates reconciliation on the XPU regex" ($pair[1] -match '\$_xpuNameRe\s*=\s*"\(\?i\)Intel\.\*\(Arc\|Data Center GPU\)"')+ Check "$($pair[0]) reuses it for the gate" ($pair[1] -match 'Where-Object \{ \$_ -match \$_xpuNameRe \}')+ # @() must wrap the WHOLE if: per-branch, a one-element array unrolls on its way out,+ # making $_gpuNames a String on a single-adapter host, and the += then concatenates.+ Check "$($pair[0]) forces an array for the WMI names" ($pair[1] -match '\$_gpuNames = @\(if \(\$_gpuScan\.Ok\)')+}++Write-Host ""+if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }+Write-Host "All checks passed" -ForegroundColor Greendiff --git a/tests/studio/test_setup_xpu_runtime_prereport.ps1 b/tests/studio/test_setup_xpu_runtime_prereport.ps1new file mode 100644index 00000000000..daf6addd0e9--- /dev/null+++ b/tests/studio/test_setup_xpu_runtime_prereport.ps1@@ -0,0 +1,284 @@+#!/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+# The hardware report must not say "none (chat-only / GGUF)" on a working XPU environment.+#+# The WMI scan and the registry fallback can both miss a real Arc host, and setup.ps1's+# torch.xpu.is_available() re-check runs AFTER the report. These two helpers let the scan reach+# the same answer before it prints.+#+# Test-VenvTorchIsXpu is FREE by design: a CPU-only host must not pay for an `import torch` on+# every update. So the tests check both the answer and that the cheap gate is what decides.+# Run: pwsh -NoProfile -File tests/studio/test_setup_xpu_runtime_prereport.ps1++$ErrorActionPreference = "Stop"+$repo = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$setup = Join-Path $repo "studio/setup.ps1"++function Get-FunctionText {+ param([string] $Path, [string] $Name)+ $tokens = $null; $errors = $null+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors)+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$Path has parse errors" }+ $fn = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name+ }, $true)+ if ($fn.Count -ne 1) { throw "expected exactly one $Name in $Path, found $($fn.Count)" }+ return $fn[0].Extent.Text+}++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++$venvDirFn = Get-FunctionText $setup "Get-ProbableStudioVenvDir"+$isXpuFn = Get-FunctionText $setup "Test-VenvTorchIsXpu"+# An empty or wrong extraction would make every case below pass vacuously.+Check "extraction kept the home override" ($venvDirFn -match 'UNSLOTH_STUDIO_HOME')+Check "extraction kept the version file" ($isXpuFn -match 'version\.py')++# --- Get-ProbableStudioVenvDir -------------------------------------------------------------+# Runs on Linux CI too, so Test-Path is shadowed: the helper builds Windows paths, and this+# asserts the path it BUILT, not what the OS resolves.+function Invoke-VenvDir {+ param([hashtable] $Env, [string[]] $Exists = @())+ $sb = [scriptblock]::Create(@"+param(`$Exists)+function Join-Path {+ [CmdletBinding()] param([Parameter(Position=0)] [string] `$Path, [Parameter(Position=1)] [string] `$ChildPath)+ # Shadowed: the real cmdlet validates the drive qualifier, so "C:\..." throws on Linux CI.+ # Windows semantics for the only shape used here -- join with a single backslash.+ if (-not `$ChildPath) { return `$Path }+ return (`$Path.TrimEnd('\', '/') + '\' + `$ChildPath.TrimStart('\', '/'))+}+function Test-Path {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ return (`$Exists -contains `$LiteralPath)+}+$venvDirFn+Get-ProbableStudioVenvDir+"@)+ $saved = @{}+ foreach ($k in 'UNSLOTH_STUDIO_HOME', 'STUDIO_HOME', 'USERPROFILE') {+ $saved[$k] = [Environment]::GetEnvironmentVariable($k)+ if ($Env.ContainsKey($k)) { Set-Item "Env:$k" $Env[$k] } else { Remove-Item "Env:$k" -ErrorAction SilentlyContinue }+ }+ try { return (& $sb $Exists) }+ finally {+ foreach ($k in $saved.Keys) {+ if ($null -eq $saved[$k]) { Remove-Item "Env:$k" -ErrorAction SilentlyContinue } else { Set-Item "Env:$k" $saved[$k] }+ }+ }+}++$DEFAULT = "C:\Users\me\.unsloth\studio\unsloth_studio"+Write-Host "the venv directory is found where the canonical resolver would put it"+Check "default location" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me" } @($DEFAULT)) -eq $DEFAULT)+Check "UNSLOTH_STUDIO_HOME" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; UNSLOTH_STUDIO_HOME = "D:\alt" } @("D:\alt\unsloth_studio")) -eq "D:\alt\unsloth_studio")+Check "STUDIO_HOME alias" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; STUDIO_HOME = "D:\alt" } @("D:\alt\unsloth_studio")) -eq "D:\alt\unsloth_studio")+Check "UNSLOTH_STUDIO_HOME wins" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; UNSLOTH_STUDIO_HOME = "D:\a"; STUDIO_HOME = "D:\b" } @("D:\a\unsloth_studio")) -eq "D:\a\unsloth_studio")+# A literal ~ would leave a cwd-relative path and probe the wrong tree.+Check "tilde expands" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; UNSLOTH_STUDIO_HOME = "~/s" } @("C:\Users\me\s\unsloth_studio")) -eq "C:\Users\me\s\unsloth_studio")+Check "bare tilde expands" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; UNSLOTH_STUDIO_HOME = "~" } @("C:\Users\me\unsloth_studio")) -eq "C:\Users\me\unsloth_studio")+Check "whitespace override ignored" ((Invoke-VenvDir @{ USERPROFILE = "C:\Users\me"; UNSLOTH_STUDIO_HOME = " " } @($DEFAULT)) -eq $DEFAULT)++Write-Host "and reports nothing rather than guessing"+Check "absent venv -> null" ($null -eq (Invoke-VenvDir @{ USERPROFILE = "C:\Users\me" } @()))+Check "no USERPROFILE -> null" ($null -eq (Invoke-VenvDir @{} @($DEFAULT)))+Check "tilde, no USERPROFILE" ($null -eq (Invoke-VenvDir @{ UNSLOTH_STUDIO_HOME = "~/s" } @("C:\Users\me\s\unsloth_studio")))++# --- Test-VenvTorchIsXpu -------------------------------------------------------------------+function Invoke-IsXpu {+ param([string] $VenvPath, [string] $VersionPyBody, [switch] $Missing, [switch] $Throws)+ $sb = [scriptblock]::Create(@"+param(`$Body, `$Missing, `$Throws)+function Join-Path {+ [CmdletBinding()] param([Parameter(Position=0)] [string] `$Path, [Parameter(Position=1)] [string] `$ChildPath)+ # Shadowed: the real cmdlet validates the drive qualifier, so "C:\..." throws on Linux CI.+ # Windows semantics for the only shape used here -- join with a single backslash.+ if (-not `$ChildPath) { return `$Path }+ return (`$Path.TrimEnd('\', '/') + '\' + `$ChildPath.TrimStart('\', '/'))+}+function Test-Path {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ return (-not `$Missing)+}+function Get-Content {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ if (`$Throws) { throw "access denied" }+ return (`$Body -split "``n")+}+$isXpuFn+Test-VenvTorchIsXpu -VenvPath '$VenvPath'+"@)+ return (& $sb $VersionPyBody ([bool]$Missing) ([bool]$Throws))+}++$XPU = "__version__ = '2.9.1+xpu'`ndebug = False`nxpu: Optional[str] = '2025.2'"+$CU = "__version__ = '2.9.1+cu128'`ndebug = False`ncuda: Optional[str] = '12.8'"+$ROC = "__version__ = '2.9.1+rocm6.4'"+$BARE = "__version__ = '2.9.1'"++Write-Host "the wheel flavour is read off disk"+Check "xpu wheel" (Invoke-IsXpu "C:\v" $XPU)+Check "cuda wheel" (-not (Invoke-IsXpu "C:\v" $CU))+Check "rocm wheel" (-not (Invoke-IsXpu "C:\v" $ROC))+Check "untagged wheel" (-not (Invoke-IsXpu "C:\v" $BARE))+# torch.version.xpu is None on some +xpu builds, so the local label is the only reliable signal;+# a line mentioning xpu without the label must not count.+Check "xpu attr but cuda wheel" (-not (Invoke-IsXpu "C:\v" ($CU + "`nxpu: Optional[str] = None")))+Check "no torch installed" (-not (Invoke-IsXpu "C:\v" $XPU -Missing))+Check "unreadable file" (-not (Invoke-IsXpu "C:\v" $XPU -Throws))+Check "no venv path" (-not (Invoke-IsXpu "" $XPU))++# --- Test-VenvTorchIsXpuSupported ------------------------------------------------------------+# The fast path asks this one, and it must answer about the WHEEL only: no dependency pass+# repairs a driver, so keying the escape on readiness re-resolved everything every update.+$isXpuSupFn = Get-FunctionText $setup "Test-VenvTorchIsXpuSupported"+Check "extraction kept the range" ($isXpuSupFn -match '11')+function Invoke-IsXpuSupported {+ param([string] $VenvPath, [string] $VersionPyBody, [switch] $Missing, [switch] $Throws)+ $sb = [scriptblock]::Create(@"+param(`$Body, `$Missing, `$Throws)+function Join-Path {+ [CmdletBinding()] param([Parameter(Position=0)] [string] `$Path, [Parameter(Position=1)] [string] `$ChildPath)+ if (-not `$ChildPath) { return `$Path }+ return (`$Path.TrimEnd('\', '/') + '\' + `$ChildPath.TrimStart('\', '/'))+}+function Test-Path {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ return (-not `$Missing)+}+function Get-Content {+ [CmdletBinding()] param([string] `$LiteralPath, [Parameter(ValueFromRemainingArguments = `$true)] `$Rest)+ if (`$Throws) { throw "access denied" }+ return (`$Body -split "``n")+}+$isXpuSupFn+Test-VenvTorchIsXpuSupported -VenvPath '$VenvPath'+"@)+ return (& $sb $VersionPyBody ([bool]$Missing) ([bool]$Throws))+}++Write-Host "flavour AND range, both off disk"+Check "2.9.1+xpu supported" (Invoke-IsXpuSupported "C:\v" $XPU)+Check "2.6.0+xpu is the floor" (Invoke-IsXpuSupported "C:\v" "__version__ = '2.6.0+xpu'")+Check "2.10.0+xpu supported" (Invoke-IsXpuSupported "C:\v" "__version__ = '2.10.0+xpu'")+# unsloth/models/_utils.py raises at import for an XPU device below 2.6, and 2.11 is the trio's+# ceiling -- both repairable by the dependency pass.+Check "2.5.1+xpu below floor" (-not (Invoke-IsXpuSupported "C:\v" "__version__ = '2.5.1+xpu'"))+Check "2.11.0+xpu at ceiling" (-not (Invoke-IsXpuSupported "C:\v" "__version__ = '2.11.0+xpu'"))+Check "3.0.0+xpu above range" (-not (Invoke-IsXpuSupported "C:\v" "__version__ = '3.0.0+xpu'"))+Check "cuda wheel" (-not (Invoke-IsXpuSupported "C:\v" $CU))+Check "untagged wheel" (-not (Invoke-IsXpuSupported "C:\v" $BARE))+Check "xpu attr but cuda wheel" (-not (Invoke-IsXpuSupported "C:\v" ($CU + "`nxpu: Optional[str] = None")))+# A nightly is judged on its release base, as setup.sh does; an unparseable label is not judged.+Check "dev label reads its base" (Invoke-IsXpuSupported "C:\v" "__version__ = '2.9.0.dev20260101+xpu'")+Check "junk label" (-not (Invoke-IsXpuSupported "C:\v" "__version__ = 'unknown'"))+Check "no version line" (-not (Invoke-IsXpuSupported "C:\v" "debug = False"))+Check "no torch installed" (-not (Invoke-IsXpuSupported "C:\v" $XPU -Missing))+Check "unreadable file" (-not (Invoke-IsXpuSupported "C:\v" $XPU -Throws))+Check "no venv path" (-not (Invoke-IsXpuSupported "" $XPU))++# --- wiring ---------------------------------------------------------------------------------+# Normalised to LF once, rather than per pattern: on a CRLF checkout every \n-anchored pattern+# below matches nothing, and the -not checks over an empty region pass vacuously.+$setupText = (Get-Content -Raw $setup) -replace "`r`n", "`n"+Write-Host "the scan asks before the report, and only when it has to"+# The promotion must sit inside the Intel scan (which the report reads), not after it.+Check "promotion is gated on the scan having failed" ($setupText -match '(?s)if \(-not \$script:IsIntelXpu\) \{\s*try \{\s*\$_probeVenv = Get-ProbableStudioVenvDir')+# Its own try, not the scan's: it must still run when the scan threw, and a junk+# UNSLOTH_STUDIO_HOME makes Join-Path throw, which would otherwise abort setup.+Check "promotion cannot abort setup" ($setupText -match '(?s)\$_probeVenv = Get-ProbableStudioVenvDir.{0,600}?\} catch \{\}')+# The cheap disk read must gate the interpreter launch, or every CPU-only update pays for an+# `import torch`.+Check "disk read gates the probe" ($setupText -match '(?s)if \(Test-VenvTorchIsXpu \$_probeVenv\) \{\s*\$_probePy = .*?Test-TorchXpuAvailable')+$_scanLine = ($setupText -split "`n" | Select-String -Pattern '\$_probeVenv = Get-ProbableStudioVenvDir' | Select-Object -First 1).LineNumber+$_reportLine = ($setupText -split "`n" | Select-String -Pattern 'none \(chat-only / GGUF\)' | Select-Object -First 1).LineNumber+Check "promotion precedes the hardware report" ($_scanLine -and $_reportLine -and $_scanLine -lt $_reportLine)++Write-Host "the fast-path escape judges the wheel, never the driver"+# Anchored on the escape's own if-chain, so an edit inside cannot move the window off the code.+# A driver-only failure must leave the fast path intact: clearing it costs a full resolution+# every update and only reaches the warning Assert-XpuRuntimeReady prints anyway.+$_fastPat = '(?s)(if \(\$script:IsIntelXpu -and \$SkipPythonDeps -and \$_xpuIsReachable\) \{.*?\n \}\n)'+$_fast = if ($setupText -match $_fastPat) { $Matches[1] } else { "" }+Check "the escape was found" ($_fast -ne "")+# The normalisation above, not luck, is what makes this match: without it the region came back+# empty on windows-latest while the -not checks below still reported PASS.+Check "CRLF is normalised, not tolerated" (-not (($setupText -replace "`n", "`r`n") -match $_fastPat))+Check "it reads the installed wheel" ($_fast -match 'Test-VenvTorchIsXpuSupported -VenvPath \$VenvDir')+Check "it clears the fast path" ($_fast -match '\$SkipPythonDeps = \$false')+Check "readiness does not decide it" (-not ($_fast -match 'Test-TorchXpuAvailable'))+# ...and no interpreter is launched: the host most likely to fail this is an Arc box with a+# stalled driver, where `import torch` is exactly what hangs.+Check "it launches no interpreter" (-not ($_fast -match 'Invoke-BoundedPythonProbe|& python'))+# The driver warning still has to exist, on the runtime check, after the install.+Check "the driver warning is elsewhere" ($setupText -match '(?s)function Assert-XpuRuntimeReady \{.*?Test-TorchXpuAvailable')++Write-Host "a timed-out probe must not destroy a working XPU venv"+# Bounding the flavour probe turned a hang into "rebuild", and the host most likely to hang in+# `import torch` is an Arc box with a stalled driver, whose version.py still names a good +xpu+# wheel. Bounded by the surrounding if-chain rather than a line offset.+$_rescue = if ($setupText -match '(?s)(\$_verProbe = Invoke-BoundedPythonProbe.*?# Missing python\.exe means)') { $Matches[1] } else { "" }+Check "the probe chain was found" ($_rescue -ne "")+Check "an unreadable flavour is rescued off disk" ($_rescue -match 'elseif \(Test-VenvTorchIsXpu -VenvPath \$VenvDir\)')+Check "the rescue classifies it as xpu" ($_rescue -match '(?s)elseif \(Test-VenvTorchIsXpu.*?\$installedTorchTag = "xpu"')+# It must NOT set the rebuild flag, or the whole point is lost.+Check "the rescue never sets shouldRebuild" ($_rescue -match '(?s)elseif \(Test-VenvTorchIsXpu.*?\} else \{\s*\$shouldRebuild = \$true' -and+ -not ($_rescue -match '(?s)elseif \(Test-VenvTorchIsXpu[^}]*\$shouldRebuild = \$true'))+# Matched on the substep ARGUMENT, not the region: the comment above the branch says "compute+# driver" too, so a loose match stayed green with the message itself deleted.+Check "the rescue names the driver fix" ($_rescue -match 'substep "[^"]*compute driver')+# Non-Intel families must still rebuild on an unreadable flavour, exactly as before.+Check "other families still rebuild" ($_rescue -match '(?s)\} else \{\s*\$shouldRebuild = \$true')+# The rescue reads the disk, so it must not launch a second interpreter after the first hung.+Check "the rescue launches no interpreter" (-not ($_rescue -match '(?s)elseif \(Test-VenvTorchIsXpu.*?Invoke-BoundedPythonProbe'))++Write-Host "a direct update never deletes an XPU venv"+# The pin is one-shot, and on a hybrid NVIDIA+Arc box the promotion above is gated on+# -not $HasNvidiaSmi, so a later pinless update expects a cu* tag and wipes the working Arc+# venv, then exits, because only install.ps1 makes venvs.+$_keep = if ($setupText -match '(?s)(\$script:PinChangedForceReinstall = \$true.*?if \(\$shouldRebuild\) \{)') { $Matches[1] } else { "" }+Check "the rebuild decision was found" ($_keep -ne "")+Check "an xpu venv is spared the wipe" ($_keep -match '\$installedTorchTag -eq "xpu"')+Check "the escape clears shouldRebuild" ($_keep -match '(?s)\$installedTorchTag -eq "xpu"\) \{.*?\$shouldRebuild = \$false')+# install.ps1 keeps a rollback copy, so that path must still be free to rebuild.+Check "installer-managed runs still rebuild" ($_keep -match '-not \$InstallerManagedSetup')+# Silently keeping a venv the host does not want is its own trap; say how to change it.+Check "the escape says how to replace it" ($_keep -match 'substep "[^"]*install\.ps1')+# Keeping the venv is only half the job: the CUDA arm leaves the +xpu wheel satisfied while+# installing triton-windows over torch's XPU triton, with $XpuIndexUrl null and nothing to swap+# it back. The whole pass has to stay on the xpu index.+Check "the escape steers the install too" ($_keep -match '\$script:PreservedXpuVenv = \$true')+Check "the flag is declared up front" ($setupText -match '(?m)^\$script:PreservedXpuVenv = \$false')+$_tagChain = if ($setupText -match '(?s)(\$PinnedTorchIndexUrl\) \{\s*\$CuTag = Get-TorchIndexLeaf.*?\$CuTag = "cpu")') { $Matches[1] } else { "" }+Check "the index chain was found" ($_tagChain -ne "")+Check "a preserved venv picks the xpu leaf" ($_tagChain -match '(?s)\$script:PreservedXpuVenv\) \{.*?\$CuTag = "xpu"')+# Ahead of the NVIDIA arm, or the hybrid host this exists for never reaches it.+Check "it outranks the NVIDIA arm" (+ $_tagChain.IndexOf('$script:PreservedXpuVenv') -ge 0 -and+ $_tagChain.IndexOf('$script:PreservedXpuVenv') -lt $_tagChain.IndexOf('$HasNvidiaSmi'))+# ...but an explicit pin still wins, as it does everywhere else.+Check "an explicit pin still outranks it" (+ $_tagChain.IndexOf('$PinnedTorchIndexUrl') -lt $_tagChain.IndexOf('$script:PreservedXpuVenv'))+# The hardware report must stay honest: there IS an NVIDIA GPU in this machine.+Check "the report is not forced to Intel" (-not ($_keep -match '\$script:IsIntelXpu = \$true'))++Write-Host "a Triton swap that strands the venv must fail the setup"+# Both installs failing leaves NO importable triton. Printing alone left $stackExit at 0, so+# setup reported success and install.ps1 committed this venv over its rollback copy.+$_bothFailed = if ($setupText -match '(?s)(neither triton would reinstall.*?\n\s*\}\s*\n)') { $Matches[1] } else { "" }+Check "the both-failed branch was found" ($_bothFailed -ne "")+Check "it sets a nonzero stack exit" ($_bothFailed -match '\$stackExit = \$tritonBackExit')+# $tritonBackExit is nonzero by construction -- but only if the assignment reads it rather than+# a literal that could drift to 0.+Check "the exit code is the real failure" (-not ($_bothFailed -match '\$stackExit = 0'))+# And the existing handler must actually act on it.+Check "a nonzero stack exit fails setup" ($setupText -match '(?s)if \(\$stackExit -ne 0\) \{.*?Exit-SetupFailure')++Write-Host ""+if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }+Write-Host "All checks passed" -ForegroundColor Greendiff --git a/tests/studio/test_xpu_arm64_torchaudio.ps1 b/tests/studio/test_xpu_arm64_torchaudio.ps1new file mode 100644index 00000000000..01a8dbc15b5--- /dev/null+++ b/tests/studio/test_xpu_arm64_torchaudio.ps1@@ -0,0 +1,83 @@+#!/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+# Windows on ARM has no torchaudio wheel on ANY index, so every XPU spec list must drop it.+#+# The fresh XPU install already did; the flavor repair did not, and that is the path a MIGRATED+# win-arm64 venv takes -- the repair asks uv for a torchaudio that does not exist for win_arm64+# and fails outright, before setup.ps1 can reach its ARM-aware CPU fallback.+#+# One builder now serves both, since the two copies drifted the moment only one learned about+# ARM. The tests EXECUTE the builder, then assert by AST that the repair site calls it.+# Run: pwsh -NoProfile -File tests/studio/test_xpu_arm64_torchaudio.ps1++$ErrorActionPreference = "Stop"+$repo = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$installPs1 = Join-Path $repo "install.ps1"++$tokens = $null; $errors = $null+$ast = [System.Management.Automation.Language.Parser]::ParseFile($installPs1, [ref]$tokens, [ref]$errors)+if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "install.ps1 has parse errors" }++function Get-FunctionAst {+ param([string] $Name)+ $fn = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name+ }, $true)+ if ($fn.Count -ne 1) { throw "expected exactly one $Name in install.ps1, found $($fn.Count)" }+ return $fn[0]+}++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++# --- Get-XpuTorchSpecs, executed ------------------------------------------------------------+$specsFn = Get-FunctionAst "Get-XpuTorchSpecs"+# An extraction that lost the ARM arm would make every case below pass vacuously.+Check "extraction kept the arm64 branch" ($specsFn.Extent.Text -match 'win-arm64')+. ([scriptblock]::Create($specsFn.Extent.Text))++$arm = Get-XpuTorchSpecs -Platform "win-arm64"+$x64 = Get-XpuTorchSpecs -Platform "win-amd64"+Check "arm64 drops torchaudio" (-not ($arm -match '^torchaudio'))+Check "arm64 keeps torch" (($arm | Where-Object { $_ -eq 'torch>=2.6,<2.11.0' }).Count -eq 1)+Check "arm64 keeps torchvision" (($arm | Where-Object { $_ -eq 'torchvision>=0.21,<0.26.0' }).Count -eq 1)+Check "arm64 asks for exactly two" ($arm.Count -eq 2)+Check "x64 keeps torchaudio" (($x64 | Where-Object { $_ -eq 'torchaudio>=2.6,<2.11.0' }).Count -eq 1)+Check "x64 asks for the full trio" ($x64.Count -eq 3)+# The floor is not cosmetic: unsloth/models/_utils.py raises at import for an XPU device on+# torch < 2.6, so a 2.4 floor installs an environment that cannot run.+Check "floor is 2.6 on both" (($arm[0] -eq 'torch>=2.6,<2.11.0') -and ($x64[0] -eq 'torch>=2.6,<2.11.0'))+# An unaskable interpreter yields "", and a Linux/macOS platform is never win-arm64: both must+# keep torchaudio rather than dropping it everywhere.+foreach ($p in @("", "linux-x86_64", "macosx-14.0-arm64", "win32")) {+ $label = if ($p) { $p } else { "<empty>" }+ Check "platform '$label' keeps torchaudio" ((Get-XpuTorchSpecs -Platform $p).Count -eq 3)+}+# Belt and braces: -eq is case-insensitive here and the probe lowercases too.+Check "an uppercase arm64 is still arm64" ((Get-XpuTorchSpecs -Platform "WIN-ARM64").Count -eq 2)+Check "the probe lowercases its answer" ((Get-FunctionAst "Get-VenvPlatformTag").Extent.Text -match 'ToLowerInvariant')++# --- both call sites go through it -----------------------------------------------------------+# Text, not AST, for the call count: asserting the COUNT catches a copy that quietly+# reintroduces its own literal trio.+$src = Get-Content -Raw -LiteralPath $installPs1+Check "builder is used at 2 sites" (([regex]::Matches($src, 'Get-XpuTorchSpecs -Platform')).Count -eq 2)+# The literal trio must exist in exactly ONE place now (the builder itself), or the drift is back.+Check "one literal torchaudio 2.6 pin" (([regex]::Matches($src, '"torchaudio>=2\.6,<2\.11\.0"')).Count -eq 1)++# The repair site specifically: find the assignment that feeds the reinstall command.+$fixAssign = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and+ $n.Left.Extent.Text -eq '$_fixSpecs'+}, $true)+Check "the repair builds one _fixSpecs" ($fixAssign.Count -eq 1)+Check "the repair calls the builder" ($fixAssign.Count -eq 1 -and $fixAssign[0].Right.Extent.Text -match 'Get-XpuTorchSpecs')+# The non-XPU arm must be untouched -- this PR must not move CUDA/ROCm hosts at all.+Check "the repair keeps the 2.4 CUDA floor" ($fixAssign.Count -eq 1 -and $fixAssign[0].Right.Extent.Text -match 'torch>=2\.4,<2\.11\.0')++if ($failures -gt 0) { Write-Host "FAILED: $failures" -ForegroundColor Red; exit 1 }+Write-Host "All XPU arm64 torchaudio checks passed."diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.pynew file mode 100644index 00000000000..c41ff9788d8--- /dev/null+++ b/tests/studio/test_xpu_triton_swap.py@@ -0,0 +1,610 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""Generic Triton must not shadow torch's XPU Triton.++Both distributions own the top-level ``triton`` package, and resolving unsloth against a+pinned ``+xpu`` torch pulls both (uv reports ``pytorch-triton-xpu 3.5.0`` alongside+``triton 3.7.1``), so the CUDA-oriented build can land last and ``torch.compile`` then loads+the wrong library on an Intel GPU.++The swap lives in ``install_python_stack.py`` rather than ``install.sh`` because install.sh+runs setup.sh, which runs this module: one copy covers the fresh install and+``unsloth studio update``, which never touches install.sh.++Three things here are easy to get wrong and are asserted by execution rather than by reading:++* the ORDER. Fetch, then uninstall, then install. Uninstalling last deletes the shared paths+ the XPU build just wrote, because those paths are in generic triton's own RECORD.+* the venv has no pip. ``uv venv`` is created without ``--seed``, so a fresh venv cannot run+ ``pip download`` at all, and without a bootstrap the swap silently never happens.+* the pin is ONE-SHOT. ``UNSLOTH_TORCH_INDEX_FAMILY=xpu ./install.sh`` leaves nothing behind+ in the environment, so a later plain ``unsloth studio update`` must recognise the installed+ ``+xpu`` wheel instead. See TestTheInstalledWheelIsThePin.+"""++import os+import subprocess+import sys+import types+from pathlib import Path++import pytest+++REPO = Path(__file__).resolve().parents[2]+STACK = REPO / "studio/install_python_stack.py"+++def _load_real_index_env_scrub():+ """The module's OWN _install_env_for_cmd, so the scrub is executed, not re-implemented.++ It is defined below the slice the swap comes from, so it is pulled in separately rather+ than stubbed -- a hand-written copy here would agree with a broken original forever.+ """+ import os as _os++ src = STACK.read_text(encoding = "utf-8")+ ns: dict = {"os": _os}+ for anchor, end, keep in (+ ("_UV_INDEX_ENV_VARS = (", "\n)\n", 2),+ ("def _is_pinned_index_cmd(", "\n\ndef ", 0),+ ("def _install_env_for_cmd(", "\n\ndef ", 0),+ ):+ start = src.index(anchor)+ exec(compile(src[start : src.index(end, start) + keep], str(STACK), "exec"), ns)+ assert "PIP_NO_INDEX" in ns["_UV_INDEX_ENV_VARS"], "extraction lost the pip vars"+ return ns["_install_env_for_cmd"]+++_real_install_env_for_cmd = _load_real_index_env_scrub()+++def _load(+ monkeypatch,+ tmp_path,+ *,+ spec,+ generic,+ has_pip = True,+ ensurepip_works = True,+ download_ok = True,+ drops_wheel = True,+ uninstall_ok = True,+ install_ok = True,+ pinned = True,+ torch_label = "2.9.1+xpu",+):+ """Import the module with the world stubbed, and return (module, action log)."""+ log: list[str] = []++ mod = types.ModuleType("_stack_under_test")+ src = STACK.read_text(encoding = "utf-8")+ # Only these helpers are needed; importing the whole module would run the installer.+ start = src.index("def _installed_torch_version_label() -> str:")+ end = src.index("def _ensure_cpu_torch() -> None:")+ body = src[start:end]+ assert "_ensure_xpu_triton" in body, "extraction lost the swap"+ assert "_ensure_venv_pip" in body, "extraction lost the pip bootstrap"++ import glob as _glob+ import importlib.util as _importlib_util+ import os as _os+ import re as _re+ import shutil as _shutil+ import tempfile as _tempfile++ # A real torch/version.py on disk, so the label read is executed rather than faked. Only the+ # LOCATION step is stubbed, since find_spec would resolve this process's own torch.+ _pkg = tmp_path / "torch"+ _pkg.mkdir()+ (_pkg / "__init__.py").write_text("raise AssertionError('torch must never be imported')\n")+ if torch_label is not None:+ (_pkg / "version.py").write_text(+ f"from typing import Optional\n__version__ = '{torch_label}'\ndebug = False\n"+ )+ monkeypatch.setattr(+ _importlib_util,+ "find_spec",+ lambda name: (+ types.SimpleNamespace(origin = str(_pkg / "__init__.py"))+ if name == "torch" and torch_label is not None+ else None+ ),+ )++ pip_state = {"present": has_pip}+ index_urls: list[str] = []+ download_envs: list = []++ def fake_run(cmd, **kw):+ joined = " ".join(str(c) for c in cmd)+ if "download" in cmd:+ download_envs.append(kw.get("env"))+ if "-m pip --version" in joined or ("pip" in cmd and "--version" in cmd):+ return subprocess.CompletedProcess(cmd, 0 if pip_state["present"] else 1)+ if "ensurepip" in joined:+ log.append("ENSUREPIP")+ if ensurepip_works:+ pip_state["present"] = True+ return subprocess.CompletedProcess(cmd, 0)+ if "importlib.metadata" in joined:+ out = f"SPEC={spec}\nGENERIC={generic}\n".encode()+ return subprocess.CompletedProcess(cmd, 0, stdout = out)+ if "download" in cmd:+ log.append("DOWNLOAD")+ index_urls.append(cmd[cmd.index("--index-url") + 1])+ if download_ok and drops_wheel:+ target = cmd[cmd.index("-d") + 1]+ Path(target, "pytorch_triton_xpu-3.5.0-py3-none-any.whl").write_bytes(b"")+ return subprocess.CompletedProcess(cmd, 0 if download_ok else 1, stdout = b"")+ if "uninstall" in cmd:+ log.append("UNINSTALL")+ return subprocess.CompletedProcess(cmd, 0 if uninstall_ok else 1)+ return subprocess.CompletedProcess(cmd, 0, stdout = b"")++ def fake_pip_install_try(label, *args, **kw):+ if label.startswith("pip"):+ log.append("BOOTSTRAP")+ if ensurepip_works:+ pip_state["present"] = True+ return pip_state["present"]+ log.append("INSTALL")+ return True++ def fake_pip_install(label, *args, **kw):+ # The real one exits the process via run(), which is what keeps the completion manifest+ # unwritten, so the stub raises SystemExit rather than returning.+ log.append("INSTALL")+ if not install_ok:+ raise SystemExit(1)++ ns = {+ "subprocess": types.SimpleNamespace(+ run = fake_run,+ CompletedProcess = subprocess.CompletedProcess,+ TimeoutExpired = subprocess.TimeoutExpired,+ DEVNULL = subprocess.DEVNULL,+ PIPE = subprocess.PIPE,+ STDOUT = subprocess.STDOUT,+ ),+ "sys": sys,+ "glob": _glob,+ "importlib": types.SimpleNamespace(util = _importlib_util, invalidate_caches = lambda: None),+ "os": _os,+ "re": _re,+ "shutil": _shutil,+ "tempfile": _tempfile,+ "Path": Path,+ "NO_TORCH": False,+ "IS_MACOS": False,+ "IS_WINDOWS": False,+ "_PYTORCH_WHL_BASE": "https://download.pytorch.org/whl",+ "_install_env_for_cmd": _real_install_env_for_cmd,+ "_explicit_xpu_torch_index_url": (+ (lambda: "https://download.pytorch.org/whl/xpu") if pinned else (lambda: None)+ ),+ "pip_install_try": fake_pip_install_try,+ "pip_install": fake_pip_install,+ "_red": lambda s: s,+ "print": lambda *a, **k: log.append("WARN") if a and "left in place" in str(a[0]) else None,+ }+ exec(compile(body, str(STACK), "exec"), ns)+ mod.__dict__.update(ns)+ mod.__dict__["_test_index_urls"] = index_urls+ mod.__dict__["_test_download_envs"] = download_envs+ return mod, log+++def _run(monkeypatch, tmp_path, **kw):+ mod, log = _load(monkeypatch, tmp_path, **kw)+ mod.__dict__["_ensure_xpu_triton"]()+ return log+++class TestXpuTritonSwap:+ def test_orders_fetch_uninstall_install(self, monkeypatch, tmp_path):+ # The whole point: the uninstall sits between the fetch and the install.+ log = _run(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]++ def test_handles_the_triton_xpu_rename(self, monkeypatch, tmp_path):+ # torch 2.10 renamed the distribution; the spec is read from torch, never hardcoded.+ log = _run(monkeypatch, tmp_path, spec = "triton-xpu==3.6.0", generic = "3.7.1")+ assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]++ def test_bootstraps_pip_when_the_venv_has_none(self, monkeypatch, tmp_path):+ # uv venv has no --seed, so a fresh venv cannot run pip download at all.+ log = _run(+ monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", has_pip = False+ )+ assert log[0] == "ENSUREPIP"+ assert log[-3:] == ["DOWNLOAD", "UNINSTALL", "INSTALL"]++ def test_falls_back_to_installing_pip(self, monkeypatch, tmp_path):+ log = _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ has_pip = False,+ ensurepip_works = False,+ )+ # ensurepip failed, so it tries a real pip install; that fails too, and the swap must+ # warn rather than uninstall with nothing to install from.+ assert "BOOTSTRAP" in log+ assert "UNINSTALL" not in log++ @pytest.mark.parametrize(+ "spec, generic",+ [+ ("pytorch-triton-xpu==3.5.0", ""), # nothing shadowing it+ ("triton==3.7.1", "3.7.1"), # torch is not the +xpu wheel+ ("", "3.7.1"), # torch declares no triton at all+ ],+ )+ def test_leaves_a_healthy_venv_alone(self, monkeypatch, tmp_path, spec, generic):+ assert _run(monkeypatch, tmp_path, spec = spec, generic = generic) == []++ def test_a_dead_mirror_removes_nothing(self, monkeypatch, tmp_path):+ # Warn and leave the venv working; never uninstall with nothing to install from.+ log = _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ download_ok = False,+ )+ assert "UNINSTALL" not in log and "INSTALL" not in log++ def test_a_successful_exit_with_no_wheel_removes_nothing(self, monkeypatch, tmp_path):+ # The exit code alone is not enough: no wheel on disk means nothing to install from.+ log = _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ drops_wheel = False,+ )+ assert "UNINSTALL" not in log and "INSTALL" not in log+++class TestFailedSwapIsNotSurvivable:+ def test_a_failed_uninstall_changes_nothing(self, monkeypatch, tmp_path):+ # A read-only or locked venv leaves generic triton registered; installing over it would+ # let a later upgrade delete the shared files again and repeat the swap every pass.+ log = _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ uninstall_ok = False,+ )+ assert log == ["DOWNLOAD", "UNINSTALL"]+ assert "INSTALL" not in log++ def test_a_failed_install_propagates(self, monkeypatch, tmp_path):+ # The uninstall already took the shared files, so a warning would commit a venv with a+ # broken torch.compile that the next update fast-paths past (nothing left to trigger on).+ with pytest.raises(SystemExit):+ _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ install_ok = False,+ )+++class TestTheInstalledWheelIsThePin:+ """`UNSLOTH_TORCH_INDEX_FAMILY=xpu ./install.sh` is a ONE-SHOT pin.++ It is gone from the environment by the next plain `unsloth studio update`, yet that+ update's dependency pass can pull generic triton back in (unsloth declares triton as a+ core dep). Gating the swap on the pin alone therefore leaves every already-installed+ XPU venv shadowed forever. The +xpu wheel on disk is the durable signal, and setup.sh+ already raises the bitsandbytes floor off exactly that.+ """++ def test_swaps_with_no_pin_when_torch_is_the_xpu_wheel(self, monkeypatch, tmp_path):+ log = _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ pinned = False,+ )+ assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]++ def test_no_pin_falls_back_to_the_default_xpu_index(self, monkeypatch, tmp_path):+ mod, _ = _load(+ monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", pinned = False+ )+ mod.__dict__["_ensure_xpu_triton"]()+ assert mod.__dict__["_test_index_urls"] == ["https://download.pytorch.org/whl/xpu"]++ @pytest.mark.parametrize("label", ["2.9.1+cu128", "2.9.1+rocm6.4", "2.9.1", "", None])+ def test_no_pin_and_no_xpu_wheel_does_nothing(self, monkeypatch, tmp_path, label):+ # No pin and no +xpu torch is an ordinary CUDA/ROCm/CPU venv, where generic triton is+ # correct and removing it would break torch.compile.+ assert (+ _run(+ monkeypatch,+ tmp_path,+ spec = "pytorch-triton-xpu==3.5.0",+ generic = "3.7.1",+ pinned = False,+ torch_label = label,+ )+ == []+ )++ def test_the_label_is_read_off_disk_not_imported(self, monkeypatch, tmp_path):+ # The fake torch/__init__.py raises, so reaching the swap proves the label came from+ # version.py. `import torch` loads the SYCL runtime and wedges on a stalled Intel driver.+ mod, _ = _load(+ monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1", pinned = False+ )+ assert mod.__dict__["_installed_torch_version_label"]() == "2.9.1+xpu"++ def test_an_explicit_pin_still_wins(self, monkeypatch, tmp_path):+ # A pinned mirror must be used verbatim, not replaced by the default index.+ mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__["_ensure_xpu_triton"]()+ assert mod.__dict__["_test_index_urls"] == ["https://download.pytorch.org/whl/xpu"]+++class TestTheFetchIgnoresTheUsersIndexEnvironment:+ """`pip download` honours PIP_* exactly like `pip install`, and that breaks the pin.++ PIP_NO_INDEX makes pip ignore --index-url outright, and PIP_EXTRA_INDEX_URL /+ PIP_FIND_LINKS are consulted IN ADDITION to it. Either the fetch fails, leaving generic+ triton shadowing the XPU build, or the wheel arrives from an index the pin never named.+ Every other pinned install in this file already routes through _install_env_for_cmd; this+ one is a raw subprocess.run, so it has to ask for the same scrub explicitly.+ """++ @pytest.mark.parametrize(+ "var, value",+ [+ ("PIP_NO_INDEX", "1"),+ ("PIP_INDEX_URL", "https://mirror.internal/simple"),+ ("PIP_EXTRA_INDEX_URL", "https://mirror.internal/simple"),+ ("PIP_FIND_LINKS", "/opt/wheels"),+ ("UV_INDEX_URL", "https://mirror.internal/simple"),+ ],+ )+ def test_the_fetch_drops_index_environment(self, monkeypatch, tmp_path, var, value):+ monkeypatch.setenv(var, value)+ mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__["_ensure_xpu_triton"]()+ env = mod.__dict__["_test_download_envs"][0]+ assert env is not None, "the fetch inherited the ambient environment"+ assert var not in env++ def test_the_fetch_neutralises_the_pip_config_file(self, monkeypatch, tmp_path):+ # A pip.conf index-url outranks nothing on the CLI, but no-index in it does.+ mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__["_ensure_xpu_triton"]()+ env = mod.__dict__["_test_download_envs"][0]+ assert env["PIP_CONFIG_FILE"] == os.devnull+ assert env["UV_NO_CONFIG"] == "1"++ def test_unrelated_environment_survives(self, monkeypatch, tmp_path):+ # Scrub the index vars, not the environment: HTTPS_PROXY and friends are how a corporate+ # host reaches the index at all.+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:8080")+ mod, _ = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__["_ensure_xpu_triton"]()+ env = mod.__dict__["_test_download_envs"][0]+ assert env["HTTPS_PROXY"] == "http://proxy.internal:8080"+++class TestADeadDriverIsNotAFlavourMismatch:+ """A wedged `import torch` under a SUPPORTED +xpu wheel is a driver, not a bad wheel.++ _ensure_xpu_torch used to read every inconclusive probe as "repair", and it runs at two+ repair points: on a stalled Arc host that is two 90-second hangs plus two force-reinstalls+ of the whole multi-gigabyte trio, every single update, fixing nothing. The disk answers+ the question the probe cannot, so an unsupported or missing wheel still repairs while a+ supported one gets the driver warning.+ """++ @pytest.mark.parametrize(+ "label, supported",+ [+ ("2.6.0+xpu", True),+ ("2.9.1+xpu", True),+ ("2.10.0+xpu", True),+ ("2.5.1+xpu", False), # below the floor unsloth raises at+ ("2.11.0+xpu", False), # past the tested ceiling+ ("3.0.0+xpu", False),+ ("2.9.1+cu128", False),+ ("2.9.1+rocm6.4", False),+ ("2.9.1", False),+ ("", False),+ (None, False), # no torch on disk at all+ ],+ )+ def test_the_supported_range_matches_the_probe(self, monkeypatch, tmp_path, label, supported):+ mod, _ = _load(monkeypatch, tmp_path, spec = "", generic = "", torch_label = label)+ assert mod.__dict__["_xpu_wheel_supported_on_disk"]() is supported++ def test_the_disk_check_and_the_probe_agree_on_the_bounds(self):+ # Two copies of the range in different languages; a drifted floor installs an+ # environment that raises at import.+ src = STACK.read_text(encoding = "utf-8")+ assert src.count("(2, 6) <= n < (2, 11)") == 1, "the probe's range moved"+ assert src.count("(2, 6) <= nums < (2, 11)") == 1, "the disk check's range moved"++ def test_a_timeout_on_a_supported_wheel_reinstalls_nothing(self):+ # Asserted on the source because _ensure_xpu_torch sits above the extracted slice: the+ # early return must come BEFORE probe is set to None, or the repair runs anyway.+ src = STACK.read_text(encoding = "utf-8")+ start = src.index("def _ensure_xpu_torch() -> None:")+ body = src[start : src.index("def _installed_torch_version_label", start)]+ guard = body.index("_xpu_wheel_supported_on_disk()")+ assert guard < body.index("probe = None"), "the guard runs after the repair is armed"+ assert "return" in body[guard : guard + 400], "the guard does not return"+++class TestPlatformGuards:+ @pytest.mark.parametrize("flag", ["NO_TORCH", "IS_MACOS", "IS_WINDOWS"])+ def test_skipped_where_it_does_not_apply(self, monkeypatch, tmp_path, flag):+ # Windows is setup.ps1's job; macOS has no XPU; --no-torch touches no wheels.+ mod, log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__[flag] = True+ mod.__dict__["_ensure_xpu_triton"].__globals__[flag] = True+ mod.__dict__["_ensure_xpu_triton"]()+ assert log == []+++def test_the_swap_is_wired_in_at_both_repair_points():+ # The final repair pass would otherwise silently undo the first.+ src = STACK.read_text(encoding = "utf-8")+ assert src.count(" _ensure_xpu_triton()") == 2+++def test_the_swap_runs_after_every_torch_migration():+ """Order, not just presence.++ The swap keys off the INSTALLED +xpu label. Run between two migrations, an explicit CPU pin+ over an XPU venv gets XPU triton installed and then torch replaced with the CPU build under+ it: a CPU environment whose top-level triton package is the XPU implementation, with its+ declared generic triton gone. Asserted on the AST so a reflow cannot fake it.+ """+ import ast as _ast++ blocks = []+ for node in _ast.walk(_ast.parse(STACK.read_text(encoding = "utf-8"))):+ body = getattr(node, "body", None)+ if not isinstance(body, list):+ continue # Lambda / IfExp carry a single expression here, not a statement list+ calls = [+ s.value.func.id+ for s in body+ if isinstance(s, _ast.Expr)+ and isinstance(s.value, _ast.Call)+ and isinstance(s.value.func, _ast.Name)+ and s.value.func.id.startswith("_ensure_")+ ]+ if "_ensure_xpu_triton" in calls:+ blocks.append(calls)+ assert len(blocks) == 2, f"expected 2 repair blocks, found {len(blocks)}: {blocks}"+ for calls in blocks:+ assert calls[-1] == "_ensure_xpu_triton", calls+ for migration in (+ "_ensure_cuda_torch",+ "_ensure_rocm_torch",+ "_ensure_xpu_torch",+ "_ensure_cpu_torch",+ ):+ assert calls.index(migration) < calls.index("_ensure_xpu_triton"), (migration, calls)+++def test_install_sh_does_not_carry_a_second_copy():+ # It used to. install.sh runs setup.sh, which runs this module, so a copy there is redundant+ # and a place for the two to drift apart.+ assert "replace generic Triton" not in (REPO / "install.sh").read_text(encoding = "utf-8")+++class TestCpuRepairSeesAnXpuWheel:+ """An explicit CPU pin must be able to replace a +xpu wheel.++ `_ensure_cpu_torch` classifies the installed build and returns early on "already a CPU+ build". An XPU wheel sets neither `torch.version.cuda` nor `.hip`, so before this it read+ as CPU and the pin was silently ignored. The predicate is executed here, not re-implemented:+ it is pulled out of the module source so a future edit to it is what this test sees.+ """++ @staticmethod+ def _classify(+ ver,+ cuda = "",+ hip = "",+ ):+ src = STACK.read_text(encoding = "utf-8")+ # The probe body is a concatenation of string literals inside the subprocess call.+ start = src.index("def _ensure_cpu_torch() -> None:")+ seg = src[start : src.index("\n\ndef ", start)]+ line = next(l for l in seg.splitlines() if l.strip().startswith('"gpu = '))+ expr = line.strip().removeprefix('"gpu = ').removesuffix('; "')+ import re as _re++ return (+ "gpu"+ if eval(expr, {"re": _re, "hip": hip, "cuda": cuda, "ver": ver.lower()})+ else "cpu"+ )++ def test_xpu_wheel_is_a_gpu_build(self):+ assert self._classify("2.9.1+xpu") == "gpu"++ @pytest.mark.parametrize(+ "ver,cuda,hip,want",+ [+ ("2.9.1+cu128", "12.8", "", "gpu"),+ ("2.9.1+rocm6.4", "", "6.4", "gpu"),+ ("2.9.1+cpu", "", "", "cpu"),+ ("2.9.1", "", "", "cpu"),+ ],+ )+ def test_other_families_are_unchanged(self, ver, cuda, hip, want):+ # The XPU arm must be additive: a CPU build still reads as CPU, or every explicit CPU pin+ # force-reinstalls torch on every update.+ assert self._classify(ver, cuda, hip) == want+++class TestCpuPinSurvivesAWedgedImport:+ """A hung `import torch` must not turn an explicit CPU pin into a no-op.++ The classifier probe has a 90s timeout, and on a wedged Intel driver `import torch` blocks+ in the SYCL runtime until it fires -- which is exactly the host the pin is meant to+ rescue. Returning there meant the one case that needed the repair never got it.+ """++ @staticmethod+ def _fn(name):+ src = STACK.read_text(encoding = "utf-8")+ start = src.index(f"def {name}(")+ body = src[start : src.index("\n\ndef ", start)]+ ns: dict = {+ "re": __import__("re"),+ "importlib": __import__("importlib.util", fromlist = ["util"]),+ "Path": Path,+ }+ exec(compile(body, str(STACK), "exec"), ns)+ return ns[name]++ @pytest.mark.parametrize(+ "label,want",+ [+ ("2.9.1+xpu", True),+ ("2.9.1+cu128", True),+ ("2.9.1+rocm6.4", True),+ ("2.9.1+cpu", False),+ ("2.9.1", False),+ ("", False),+ ],+ )+ def test_gpu_label_classification(self, label, want):+ # The CPU/untagged rows matter most: a slow but healthy CPU-only host must not+ # force-reinstall torch on every update.+ assert self._fn("_is_gpu_torch_label")(label) is want++ def test_timeout_falls_through_to_the_repair(self):+ src = STACK.read_text(encoding = "utf-8")+ start = src.index("def _ensure_cpu_torch() -> None:")+ body = src[start : src.index("\n\ndef ", start)]+ exc = body.index("except (OSError, subprocess.TimeoutExpired):")+ guard = body.index("_is_gpu_torch_label(_installed_torch_label_on_disk())", exc)+ # ...and the repair below must accept the probe-less path, or the fall-through+ # dereferences None instead of reinstalling.+ assert "probe = None" in body[guard : guard + 300]+ assert "if probe is None or probe.returncode != 0:" in body++ def test_the_disk_read_launches_no_interpreter(self):+ # An interpreter here would reintroduce the hang the disk read exists to avoid.+ src = STACK.read_text(encoding = "utf-8")+ start = src.index("def _installed_torch_label_on_disk() -> str:")+ body = src[start : src.index("\n\ndef ", start)]+ assert "subprocess" not in body+ assert "find_spec" in body