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
Studio Windows XPU Triton: verify the swap and torch's XPU triton payload, repair a broken triton, skip pip backups (#16250)
Daniel Hanc72742fb1ed6
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex bec4fbc9e35..8c60d9cefff 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -77,6 +77,7 @@ on:- 'tests/studio/test_amd_venv_repair_loop.ps1'- 'tests/studio/test_amd_name_arch_r9700.ps1'- 'tests/studio/test_rocm_triton_windows_pairing.ps1'+ - 'tests/studio/test_xpu_triton_windows_swap.ps1'- 'tests/studio/test_nvidia_library_inventory.ps1'- 'tests/studio/test_nvidia_smi_discovery.ps1'- 'tests/studio/test_nvidia_python_probe_parity.ps1'@@ -181,6 +182,7 @@ on:- 'tests/studio/test_amd_venv_repair_loop.ps1'- 'tests/studio/test_amd_name_arch_r9700.ps1'- 'tests/studio/test_rocm_triton_windows_pairing.ps1'+ - 'tests/studio/test_xpu_triton_windows_swap.ps1'- 'tests/studio/test_nvidia_library_inventory.ps1'- 'tests/studio/test_nvidia_smi_discovery.ps1'- 'tests/studio/test_nvidia_python_probe_parity.ps1'@@ -305,6 +307,13 @@ jobs:if: runner.os == 'Windows'shell: powershellrun: powershell -NoProfile -File tests\studio\test_rocm_triton_windows_pairing.ps1+ - name: Intel XPU triton swap tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_xpu_triton_windows_swap.ps1+ - name: Intel XPU triton swap tests (Windows PowerShell 5.1)+ if: runner.os == 'Windows'+ shell: powershell+ run: powershell -NoProfile -File tests\studio\test_xpu_triton_windows_swap.ps1# The 5.1 leg compiles the P/Invoke helper with the .NET Framework compiler setup.ps1 uses.- name: NVIDIA driver-library inventory testsshell: pwshdiff --git a/studio/setup.ps1 b/studio/setup.ps1index cc3ba696691..209428faf0e 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -7558,11 +7558,10 @@ sys.exit(0 if installed is not None and required is not None and installed >= re}# An explicit xpu pin can leave IsIntelXpu false, so check the installed wheel too.if ($SkipPythonDeps -and $_xpuIsReachable -and ($script:IsIntelXpu -or $installedTorchTag -eq "xpu")) {+ # Name lookups exclude pip's interrupted-replacement backups.$_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'), ''))"+ "print('BNB=' + next(((d.version or '') for d in m.distributions(name='bitsandbytes')), '')); " ++ "print('TRITONWIN=' + next(((d.version or '?') for d in m.distributions(name='triton-windows')), ''))"$_xpuDeps = Invoke-BoundedPythonProbe -PythonExe "python" -Code $_xpuDepsCodeif (-not $_xpuDeps.Ok) {substep "Intel XPU dependencies could not be read -- running the dependency pass" "Cyan"@@ -7576,8 +7575,19 @@ sys.exit(0 if installed is not None and required is not None and installed >= retry { $_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"+ $_xpuTritonRepair = $false+ if (-not $_bnbStale -and -not $_tritonWinPresent) {+ $_xpuTritonNow = Get-XpuTritonState+ $_xpuTritonRepair = (-not $_xpuTritonNow.Known) -or ($_xpuTritonNow.XpuSpec -match '(?i)xpu' -and+ (-not $_xpuTritonNow.XpuOk -or -not (Get-TritonRuntimeState).Healthy))+ }+ $_xpuDepsWhy = if ($_bnbStale -or $_tritonWinPresent) { "Intel XPU dependencies are stale" }+ elseif ($_xpuTritonRepair) { "torch's Intel XPU triton is missing, the wrong version or does not import" }+ else { "" }+ if ($_xpuDepsWhy -and -not $_bnbStale -and ($script:OfflineFastPath -or (Test-UvOfflineRequested))) {+ substep "$_xpuDepsWhy but UV_OFFLINE is set -- left for the next online update" "Yellow"+ } elseif ($_xpuDepsWhy) {+ substep "$_xpuDepsWhy -- running the dependency pass" "Cyan"$SkipPythonDeps = $false}}@@ -7656,6 +7666,54 @@ function Test-RocmTritonPairingNeedsPass {substep "triton-windows does not pair with torch $($pair.Torch) -- forcing dependency pass to repair..." "Cyan"return $true}++function Enter-TritonInstallEnv {+ $saved = @{}+ foreach ($n in 'UV_OVERRIDE', 'UV_EXCLUDE', 'UV_CONSTRAINT', 'PIP_CONSTRAINT', 'UV_REQUIRE_HASHES', 'PIP_REQUIRE_HASHES') {+ $saved[$n] = [Environment]::GetEnvironmentVariable($n)+ Remove-Item "Env:$n" -ErrorAction SilentlyContinue+ }+ $env:PIP_REQUIRE_HASHES = "0"+ return $saved+}++function Exit-TritonInstallEnv {+ param([hashtable]$Saved)+ foreach ($n in $Saved.Keys) {+ if ($null -ne $Saved[$n]) { Set-Item "Env:$n" $Saved[$n] }+ else { Remove-Item "Env:$n" -ErrorAction SilentlyContinue }+ }+}++function Get-XpuTritonState {+ # No double quotes: Invoke-BoundedPythonProbe wraps $Code in them.+ $code = "import importlib, importlib.metadata as m, importlib.util as u, re; " ++ "print('TRITONWIN=' + next(((d.version or '?') for d in m.distributions(name='triton-windows')), '')); " ++ "q = next((r.split(';')[0].strip() for r in (m.requires('torch') or []) if 'triton' in r.lower()), ''); " ++ "print('TRITONXPU=' + q); n = re.match(r'[A-Za-z0-9._-]+', q); " ++ "v = next(((d.version or '') for d in m.distributions(name=n.group(0))), None) if n else None; " ++ "print('XPUDIST=' + ('' if v is None else (v or '?'))); " ++ "exec('''def accepted(q, v):\n for p in ('packaging', 'pip._vendor.packaging'):\n try:\n rq = importlib.import_module(p + '.requirements'); vm = importlib.import_module(p + '.version')\n except Exception:\n continue\n try:\n return bool(re.fullmatch(vm.VERSION_PATTERN, v, re.VERBOSE | re.IGNORECASE)) and rq.Requirement(q).specifier.contains(v, prereleases=True)\n except Exception:\n return False\n return q.partition('==')[2].strip().split('+')[0] == v.split('+')[0]'''); " ++ "ok = bool(v) and accepted(q, v); " ++ "print('XPUOK=' + str(int(bool(ok))))"+ $probe = Invoke-BoundedPythonProbe -PythonExe "python" -Code $code+ $win = if ($probe.Output -match '(?m)^TRITONWIN=(\S+)\s*$') { $Matches[1] } else { "" }+ $spec = if ($probe.Output -match '(?m)^TRITONXPU=([^\r\n]+)') { $Matches[1].Trim() } else { "" }+ $dist = if ($probe.Output -match '(?m)^XPUDIST=(\S+)\s*$') { $Matches[1] } else { "" }+ $ok = [bool]($probe.Ok -and $probe.Output -match '(?m)^XPUOK=1\s*$')+ if ($ok) {+ # Generic triton can share Intel's version; verify backend registration without activating a device.+ $base = ($dist -split '\+')[0] -replace '[^0-9A-Za-z._-]', ''+ $rt = Invoke-BoundedPythonProbe -PythonExe "python" -Code ("import importlib; t = importlib.import_module('triton'); " ++ "from triton.backends import backends; from triton.backends.compiler import GPUTarget; " ++ "target = GPUTarget('xpu', {}, 32); " ++ "xpu = any(b.compiler.supports_target(target) and callable(b.driver) for b in backends.values()); " ++ "v = (getattr(t, '__version__', '') or '').split('+')[0]; " ++ "print('XPURT=' + str(int(v == '$base' and xpu)))")+ $ok = [bool]($rt.Ok -and $rt.Output -match '(?m)^XPURT=1\s*$')+ }+ return @{ TritonWin = $win; XpuSpec = $spec; XpuDist = $dist; XpuOk = $ok; Known = [bool]$probe.Ok }+}# End of the AMD ROCm triton-windows pairing helpers.$_PkgName = if ($env:STUDIO_PACKAGE_NAME) { $env:STUDIO_PACKAGE_NAME } else { "unsloth" }@@ -8535,13 +8593,8 @@ if ($stackExit -eq 0 -and -not $NoTorchMode) {substep "[WARN] could not set the install manifest aside; $_rocmTritonFrom left in place -- flex attention decode may run unfused." "Yellow"} else {# Inherited uv / pip inputs that would drop or replace the pin while still reporting success, and- # require-hashes, which the unhashed pin can only fail (the dependency stack relaxes it the same way).- $_rocmSavedEnv = @{}- foreach ($_n in 'UV_OVERRIDE', 'UV_EXCLUDE', 'UV_CONSTRAINT', 'PIP_CONSTRAINT', 'UV_REQUIRE_HASHES', 'PIP_REQUIRE_HASHES') {- $_rocmSavedEnv[$_n] = [Environment]::GetEnvironmentVariable($_n)- Remove-Item "Env:$_n" -ErrorAction SilentlyContinue- }- $env:PIP_REQUIRE_HASHES = "0"+ # require-hashes, which the unhashed pin can only fail.+ $_rocmSavedEnv = Enter-TritonInstallEnv# A broken 3.8, or a record with no version, already satisfies the pin as far as the installer can# tell, so only a forced reinstall restores its files.$_rocmArgs = @($_rocmPair.Spec)@@ -8552,10 +8605,7 @@ if ($stackExit -eq 0 -and -not $NoTorchMode) {$_rocmTritonOut = Fast-Install @_rocmArgs | Out-String$_rocmTritonExit = $LASTEXITCODE} finally {- foreach ($_n in $_rocmSavedEnv.Keys) {- if ($null -ne $_rocmSavedEnv[$_n]) { Set-Item "Env:$_n" $_rocmSavedEnv[$_n] }- else { Remove-Item "Env:$_n" -ErrorAction SilentlyContinue }- }+ Exit-TritonInstallEnv -Saved $_rocmSavedEnv}# Exit 0 is not enough: an override-dependencies entry in a uv config keeps the old version, and a# probe that could not read the venv verifies nothing.@@ -8608,22 +8658,39 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {# Both own the `triton` package. Run after the stack (it reinstalls triton-windows); always# pair the uninstall with a reinstall.if ($stackExit -eq 0 -and $XpuIndexUrl) {- # 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- $_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 { "" }- # Anything but an XPU triton spec means torch is not the +xpu wheel.- if ($_tritonWinVer -and $_tritonXpuSpec -match '(?i)xpu') {- substep "replacing triton-windows $_tritonWinVer with $_tritonXpuSpec (Intel XPU)..." "Cyan"+ $_tritonProbe = Get-XpuTritonState+ $_tritonWinVer = $_tritonProbe.TritonWin+ $_tritonXpuSpec = $_tritonProbe.XpuSpec+ $_tritonImportedBefore = $true+ $_tritonXpuWrong = $false+ if ($_tritonXpuSpec -match '(?i)xpu') {+ $_tritonImportedBefore = (Get-TritonRuntimeState).Healthy+ $_tritonXpuWrong = -not $_tritonProbe.XpuOk+ }+ $_tritonWanted = $_tritonXpuSpec -match '(?i)xpu' -and ($_tritonWinVer -or -not $_tritonImportedBefore -or $_tritonXpuWrong)+ if ($_tritonWanted -and ($script:OfflineFastPath -or (Test-UvOfflineRequested))) {+ substep "torch's Intel XPU triton $_tritonXpuSpec is not in place but UV_OFFLINE is set -- left for the next online update" "Yellow"+ } elseif ($_tritonWanted) {+ if ($_tritonWinVer) {+ substep "replacing triton-windows $_tritonWinVer with $_tritonXpuSpec (Intel XPU)..." "Cyan"+ $_tritonLeft = "triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU."+ } elseif (-not $_tritonImportedBefore) {+ substep "triton does not import -- reinstalling $_tritonXpuSpec (Intel XPU)..." "Cyan"+ $_tritonLeft = "triton still does not import, so torch.compile will not work."+ } else {+ $_tritonXpuHave = if ($_tritonProbe.XpuDist) { "Intel XPU triton $($_tritonProbe.XpuDist)" } else { "no Intel XPU triton" }+ substep "$_tritonXpuHave installed, but torch requires $_tritonXpuSpec -- reinstalling it..." "Cyan"+ $_tritonLeft = "$_tritonXpuHave left in place, and torch requires $_tritonXpuSpec."+ }+ # Redacted: a mirror pin can carry a token.+ $_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl+ $_tritonRepair = "python -m pip install --force-reinstall --no-deps `"$_tritonXpuSpec`" --index-url $_tritonRepairUrl"# test_intel_registry_fallback.ps1 asserts this literal matches MANIFEST_NAME.$_manifestPath = Join-Path $VenvDir "unsloth_install_manifest.json"# Fetch, then uninstall, then install, so a dead mirror cannot strand the venv between steps.$_tritonTmp = Join-Path ([System.IO.Path]::GetTempPath()) "unsloth_triton_xpu_$([guid]::NewGuid().ToString('N').Substring(0,8))"+ # Inherited UV_EXCLUDE can make installation report success without installing the replacement.+ $_tritonSavedEnv = Enter-TritonInstallEnvtry {New-Item -ItemType Directory -Force -Path $_tritonTmp -ErrorAction SilentlyContinue | Out-Null# Advanced function: PowerShell binds `-d` to -Debug, so use `--dest`.@@ -8637,7 +8704,15 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {}$_tritonWheel = @(Get-ChildItem -LiteralPath $_tritonTmp -Filter "*.whl" -ErrorAction SilentlyContinue) | Select-Object -First 1 -ExpandProperty FullNameif ($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"+ if (-not $_tritonImportedBefore -and (Test-Path -LiteralPath $_manifestPath -PathType Leaf)) {+ try {+ Remove-Item -LiteralPath $_manifestPath -Force -ErrorAction Stop+ } catch {+ Write-StudioLine "[ERROR] triton does not import and the install manifest could not be removed: $($_.Exception.Message)" -ForegroundColor Red+ $stackExit = 1+ }+ }+ substep "[WARN] could not fetch $_tritonXpuSpec (exit $tritonDlExit); $_tritonLeft" "Yellow"Write-StudioLine (Redact-InstallOutput $tritonDlOutput) -ForegroundColor Yellow} else {# Move (never rewrite) the manifest aside during the swap: 5.1 encodings would corrupt it.@@ -8659,16 +8734,25 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {}if ($_manifestBlocked) {# An unmovable manifest stays valid through the destructive window, so skip the swap.- substep "[WARN] could not set the install manifest aside; triton-windows $_tritonWinVer left in place -- it still shadows torch XPU triton, so torch.compile will not use the XPU." "Yellow"- } else {+ substep "[WARN] could not set the install manifest aside; $_tritonLeft" "Yellow"+ } elseif ($_tritonWinVer) {Fast-Uninstall "triton-windows" | Out-Null$_uninstallExit = $LASTEXITCODE}- # An uninstall that failed (file held open) leaves the shadowing in place.+ # A failed uninstall can still remove files; recheck imports before restoring the manifest.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 {}+ if ((Get-TritonRuntimeState).Healthy) {+ 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 ($_tritonImportedBefore) {+ Write-StudioLine "[ERROR] removing triton-windows $_tritonWinVer failed part way (exit $_uninstallExit) and triton no longer imports -- torch.compile is broken." -ForegroundColor Red+ Write-StudioLine " Repair with: $_tritonRepair" -ForegroundColor Red+ # Fail, or install.ps1 commits this venv over its rollback copy.+ $stackExit = $_uninstallExit+ } else {+ substep "[WARN] could not remove triton-windows $_tritonWinVer (exit $_uninstallExit); $_tritonLeft" "Yellow"}} elseif (-not $_manifestBlocked) {if ($script:UnslothVerbose) {@@ -8679,22 +8763,33 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {$tritonOutput = Fast-Install --force-reinstall --no-deps $_tritonWheel | Out-String$tritonXpuExit = $LASTEXITCODE}- $_tritonPresent = ($tritonXpuExit -eq 0)- if ($tritonXpuExit -ne 0) {- # Put SOME triton back rather than leave the venv without one.+ $_tritonAfter = Get-XpuTritonState+ $_tritonPresent = ($tritonXpuExit -eq 0 -and $_tritonAfter.Known -and $_tritonAfter.XpuOk -and+ -not $_tritonAfter.TritonWin -and (Get-TritonRuntimeState).Healthy)+ if (-not $_tritonPresent) {+ $_tritonXpuWhy = if ($tritonXpuExit -ne 0) { "exit $tritonXpuExit" } else { "exit 0, but it is not installed or triton does not import" }+ # A stale XPU RECORD can later delete the generic fallback's shared files.+ Fast-Uninstall ($_tritonXpuSpec -replace '^([A-Za-z0-9._-]+).*$', '$1') | Out-NullFast-Install --force-reinstall --no-deps $_tritonSpec | Out-Null$tritonBackExit = $LASTEXITCODE- $_tritonPresent = ($tritonBackExit -eq 0)+ $_tritonBack = Get-XpuTritonState+ $_tritonPresent = ($tritonBackExit -eq 0 -and $_tritonBack.Known -and -not $_tritonBack.XpuDist -and $_tritonBack.TritonWin -and+ (Get-TritonRuntimeState).Healthy)Write-StudioLine (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"+ if ($_tritonPresent -and $InstallerManagedSetup -and -not $_tritonWinVer) {+ Write-StudioLine "[ERROR] could not install $_tritonXpuSpec ($_tritonXpuWhy); the triton-windows fallback would drop the Intel XPU triton -- keeping the installer's rollback copy." -ForegroundColor Red+ Write-StudioLine " Repair with: $_tritonRepair" -ForegroundColor Red+ $stackExit = 1+ } elseif ($_tritonPresent) {+ substep "[WARN] could not install $_tritonXpuSpec ($_tritonXpuWhy); fell back to triton-windows, so triton imports -- but torch.compile will not use the XPU." "Yellow"+ } elseif ($_tritonImportedBefore -or $InstallerManagedSetup) {+ $_tritonBackWhy = if ($_tritonBack.XpuDist) { "the Intel XPU distribution is still recorded over the fallback files" }+ else { "the fallback distribution or runtime could not be verified" }+ Write-StudioLine "[ERROR] could not verify the triton-windows fallback: $_tritonBackWhy." -ForegroundColor Red+ Write-StudioLine " Repair with: $_tritonRepair" -ForegroundColor Red+ $stackExit = if ($tritonBackExit -ne 0) { $tritonBackExit } else { 1 }} else {- # Redacted: a mirror pin can carry a token.- $_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl- Write-StudioLine "[ERROR] triton-windows was removed and neither triton would reinstall -- torch.compile is broken." -ForegroundColor Red- Write-StudioLine " Repair with: python -m pip install --force-reinstall --no-deps $_tritonXpuSpec --index-url $_tritonRepairUrl" -ForegroundColor Red- # Fail, or install.ps1 commits this triton-less venv over its rollback copy.- $stackExit = $tritonBackExit+ substep "[WARN] could not install $_tritonXpuSpec ($_tritonXpuWhy) and the triton-windows fallback could not be verified. Repair with: $_tritonRepair" "Yellow"}}# Restore only once a triton imports; a lost manifest makes the next update repair.@@ -8707,9 +8802,19 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {}}} finally {+ Exit-TritonInstallEnv -Saved $_tritonSavedEnvRemove-Item -Recurse -Force -LiteralPath $_tritonTmp -ErrorAction SilentlyContinue}}+ # Managed setup must preserve rollback even when triton was already broken or its requirement is unreadable.+ if ($stackExit -eq 0 -and $InstallerManagedSetup -and ($_tritonXpuSpec -match '(?i)xpu' -or -not $_tritonProbe.Known) -and+ -not (Get-TritonRuntimeState).Healthy) {+ $_tritonRepairUrl = Redact-InstallOutput $XpuIndexUrl+ $_tritonRepairSpec = if ($_tritonXpuSpec) { $_tritonXpuSpec } else { "pytorch-triton-xpu" }+ Write-StudioLine "[ERROR] triton does not import -- torch.compile is broken; keeping the installer's rollback copy." -ForegroundColor Red+ Write-StudioLine " Repair with: python -m pip install --force-reinstall --no-deps `"$_tritonRepairSpec`" --index-url $_tritonRepairUrl" -ForegroundColor Red+ $stackExit = 1+ }}$ErrorActionPreference = $prevEAPdiff --git a/tests/studio/test_setup_xpu_runtime_prereport.ps1 b/tests/studio/test_setup_xpu_runtime_prereport.ps1index c9bc7885d38..cd0cae93507 100644--- a/tests/studio/test_setup_xpu_runtime_prereport.ps1+++ b/tests/studio/test_setup_xpu_runtime_prereport.ps1@@ -227,10 +227,10 @@ Check "an explicit pin still outranks it" (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 triton installs failing must fail setup, or install.ps1 commits a broken venv.-$_bothFailed = if ($setupText -match '(?s)(neither triton would reinstall.*?\n\s*\}\s*\n)') { $Matches[1] } else { "" }+# Failed fallback verification must not commit a broken installer-managed venv.+$_bothFailed = if ($setupText -match '(?s)(could not verify the triton-windows fallback:.*?\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')+Check "it sets a nonzero stack exit" ($_bothFailed -match '\$stackExit = if \(\$tritonBackExit -ne 0\) \{ \$tritonBackExit \} else \{ 1 \}')Check "the exit code is the real failure" (-not ($_bothFailed -match '\$stackExit = 0'))Check "a nonzero stack exit fails setup" ($setupText -match '(?s)if \(\$stackExit -ne 0\) \{.*?Exit-SetupFailure')diff --git a/tests/studio/test_xpu_triton_windows_swap.ps1 b/tests/studio/test_xpu_triton_windows_swap.ps1new file mode 100644index 00000000000..8aff2264d8a--- /dev/null+++ b/tests/studio/test_xpu_triton_windows_swap.ps1@@ -0,0 +1,549 @@+#!/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+# ASCII only: Windows PowerShell 5.1 reads a BOM-less script in the ANSI code page.++$ErrorActionPreference = "Stop"+$root = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$setupPath = Join-Path (Join-Path $root "studio") "setup.ps1"+$setup = Get-Content -LiteralPath $setupPath -Raw -Encoding UTF8++function Cut([string]$From, [string]$To) {+ $start = $setup.IndexOf($From)+ $end = if ($start -ge 0) { $setup.IndexOf($To, $start) } else { -1 }+ if ($start -lt 0 -or $end -le $start) { throw "setup.ps1 no longer has the block from '$From' to '$To'" }+ return $setup.Substring($start, $end - $start)+}+$helpers = Cut "# AMD ROCm: triton-windows paired with torch." "# End of the AMD ROCm triton-windows pairing helpers."+$fastPath = Cut " # An explicit xpu pin can leave IsIntelXpu false" ' $script:SkipPythonDeps = $SkipPythonDeps'+$swap = Cut '# Both own the `triton` package.' '$ErrorActionPreference = $prevEAP'++$failures = 0+function Check([string]$Name, [bool]$Ok) {+ if ($Ok) { Write-Host " PASS $Name" } else { Write-Host " FAIL $Name" -ForegroundColor Red; $script:failures++ }+}+function Try-Scenario([string]$Name, [scriptblock]$Body) {+ try { & $Body } catch { Check "$Name (threw: $($_.Exception.Message))" $false; return $null }+}++$script:State = @{}+$script:RealProbeDir = $null+$script:Calls = @()+$script:EnvSeen = @()+$script:Lines = @()+$script:InstallExits = @()+$script:InstallLeaves = @()+$script:UninstallExit = 0+$script:UninstallBreaks = $false+$envNames = @('UV_OVERRIDE', 'UV_EXCLUDE', 'UV_CONSTRAINT', 'PIP_CONSTRAINT', 'UV_REQUIRE_HASHES', 'PIP_REQUIRE_HASHES')+function Invoke-BoundedPythonProbe {+ param($PythonExe, $Code, $TimeoutSec)+ if ($script:RealProbeDir) {+ # The real probe code against a site directory of hand-made dist-infos only (-S: no site-packages).+ $py = Get-Command python -ErrorAction SilentlyContinue+ if (-not $py) { $py = Get-Command python3 }+ $savedPath = $env:PYTHONPATH+ $env:PYTHONPATH = $script:RealProbeDir+ $ErrorActionPreference = "Continue"+ try { $out = & $py.Source -S -c $Code 2>&1 | Out-String } finally { $env:PYTHONPATH = $savedPath }+ return @{ Ok = ($LASTEXITCODE -eq 0); Output = $out }+ }+ if ($Code -like "*XPURT=*") {+ if (-not $script:State.Imports) { return @{ Ok = $false; Output = "" } }+ $rt = if ($script:State.ContainsKey('XpuRt')) { [int][bool]$script:State.XpuRt } else { 1 }+ return @{ Ok = $true; Output = "XPURT=$rt" }+ }+ if ($Code -like "*HEALTHY=*") {+ if (-not $script:State.Imports) { return @{ Ok = $false; Output = "" } }+ return @{ Ok = $true; Output = "TRITONVER=`nHEALTHY=1`nPAIRED=0" }+ }+ if ($script:State.PartialSpec) { return @{ Ok = $false; Output = "TRITONWIN=$($script:State.TritonWin)`nTRITONXPU=$($script:State.PartialSpec)`n" } }+ if (-not $script:State.Readable) { return @{ Ok = $false; Output = "" } }+ $ok = if ($script:State.XpuDist -eq "3.5.0") { 1 } else { 0 }+ return @{ Ok = $true; Output = "TRITONWIN=$($script:State.TritonWin)`nTRITONXPU=$($script:State.XpuSpec)`nXPUDIST=$($script:State.XpuDist)`nXPUOK=$ok" }+}+function Save-EnvSeen { $script:EnvSeen += ,(@($envNames | ForEach-Object { [Environment]::GetEnvironmentVariable($_) }) -join "|") }+$script:DownloadExit = 0+function Fast-Download {+ $script:Calls += ,("download " + ($args -join " "))+ Save-EnvSeen+ $dest = $args[[array]::IndexOf($args, '--dest') + 1]+ if ($script:DownloadExit -eq 0) {+ Set-Content -LiteralPath (Join-Path $dest "pytorch_triton_xpu-3.5.0-cp312-cp312-win_amd64.whl") -Value "" -Encoding ascii+ }+ $global:LASTEXITCODE = $script:DownloadExit+ return ""+}+function Fast-Uninstall {+ $script:Calls += ,("uninstall " + ($args -join " "))+ Save-EnvSeen+ if ("$args" -like "*pytorch-triton-xpu*") {+ if (-not $script:XpuUninstallLeaves) { $script:State.XpuDist = ""; $script:State.Imports = $false }+ $global:LASTEXITCODE = $script:XpuUninstallExit+ return ""+ }+ elseif ($script:UninstallExit -eq 0) { $script:State.TritonWin = ""; $script:State.Imports = $false }+ elseif ($script:UninstallBreaks) { $script:State.Imports = $false }+ $global:LASTEXITCODE = $script:UninstallExit+ return ""+}+function Fast-Install {+ $n = @($script:Calls | Where-Object { $_ -like "install *" }).Count+ $script:Calls += ,("install " + ($args -join " "))+ Save-EnvSeen+ if ($n -lt $script:InstallLeaves.Count -and $script:InstallLeaves[$n]) {+ foreach ($k in $script:InstallLeaves[$n].Keys) { $script:State[$k] = $script:InstallLeaves[$n][$k] }+ }+ $global:LASTEXITCODE = if ($n -lt $script:InstallExits.Count) { $script:InstallExits[$n] } else { 0 }+ return ""+}+function substep { param($Text, $Color) $script:Lines += ,"$Text" }+function Write-StudioLine { param($Text, $ForegroundColor) $script:Lines += ,"$Text" }+function Redact-InstallOutput { param($Text) return $Text }+$script:Offline = $false+function Test-UvOfflineRequested { return $script:Offline }+Invoke-Expression $helpers++$venvRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("xpu_triton_venv_" + [guid]::NewGuid().ToString("N"))+New-Item -ItemType Directory -Path $venvRoot -Force | Out-Null+$manifestFile = Join-Path $venvRoot "unsloth_install_manifest.json"+$xpuSpec = "pytorch-triton-xpu==3.5.0"+$generic = "triton-windows<3.7"+$xpuOk = @{ XpuDist = "3.5.0"; Imports = $true; XpuRt = $true }+$backOk = @{ TritonWin = "3.6.0.post25"; Imports = $true; Readable = $true }++function Invoke-Swap($Exits = @(), $Leaves = @($xpuOk), [string]$TritonWin = "3.9.0.post30", [string]$Spec = $xpuSpec,+ [int]$UninstallExit = 0, [bool]$UninstallBreaks = $false, [bool]$Imports = $true,+ [string]$XpuDist = "", [int]$DownloadExit = 0, [bool]$Managed = $false, [bool]$Offline = $false,+ $Extra = $null, [int]$XpuUninstallExit = 0, [bool]$XpuUninstallLeaves = $false) {+ $script:State = @{ TritonWin = $TritonWin; XpuSpec = $Spec; XpuDist = $XpuDist; Imports = $Imports; Readable = $true }+ if ($Extra) { foreach ($k in $Extra.Keys) { $script:State[$k] = $Extra[$k] } }+ $script:DownloadExit = $DownloadExit+ $script:Offline = $Offline+ $InstallerManagedSetup = $Managed+ $script:Calls = @(); $script:EnvSeen = @(); $script:Lines = @()+ $script:InstallExits = $Exits; $script:InstallLeaves = $Leaves; $script:UninstallExit = $UninstallExit+ $script:UninstallBreaks = $UninstallBreaks+ $script:XpuUninstallExit = $XpuUninstallExit; $script:XpuUninstallLeaves = $XpuUninstallLeaves+ Set-Content -LiteralPath $manifestFile -Value '{"complete": true}' -Encoding ascii+ $stackExit = 0+ $XpuIndexUrl = "https://download.pytorch.org/whl/xpu"+ $VenvDir = $venvRoot+ $_tritonSpec = $generic+ Invoke-Expression $swap+ $script:DownloadExit = 0+ $script:Offline = $false+ return @{ Calls = $script:Calls; StackExit = $stackExit; Manifest = (Test-Path -LiteralPath $manifestFile -PathType Leaf);+ Installs = @($script:Calls | Where-Object { $_ -like "install *" }); Lines = $script:Lines }+}+function Has-Error($r) { return @($r.Lines | Where-Object { $_ -like "*[[]ERROR]*" }).Count -gt 0 }++try {+Write-Host "=== swap: verified, not just exit 0 ==="+$r = Try-Scenario "happy path" { Invoke-Swap }+Check "a verified XPU install keeps the manifest and installs once" ($r -and $r.Installs.Count -eq 1 -and $r.Manifest -and $r.StackExit -eq 0)+Check "and runs fetch, uninstall, install in order" ($r -and $r.Calls.Count -eq 3 -and $r.Calls[0] -like "download *" -and $r.Calls[1] -like "uninstall *" -and $r.Calls[2] -like "install *")+$r = Try-Scenario "exit 0, nothing installed" { Invoke-Swap -Leaves @($null, $backOk) }+Check "exit 0 with no XPU dist falls back to triton-windows" ($r -and $r.Installs.Count -eq 2 -and $r.Installs[1] -eq "install --force-reinstall --no-deps $generic")+Check "and the restored triton-windows keeps setup going" ($r -and $r.StackExit -eq 0 -and $r.Manifest -and -not (Has-Error $r))+$r = Try-Scenario "XPU dist recorded, no import" { Invoke-Swap -Leaves @(@{ XpuDist = "3.5.0"; Imports = $false }, $backOk) }+Check "an XPU dist that does not import falls back" ($r -and $r.Installs.Count -eq 2 -and $r.StackExit -eq 0)+$r = Try-Scenario "triton-windows still recorded" { Invoke-Swap -Leaves @(@{ XpuDist = "3.5.0"; Imports = $true; TritonWin = "3.9.0.post30" }, $backOk) }+Check "an install that leaves triton-windows recorded falls back" ($r -and $r.Installs.Count -eq 2)+$r = Try-Scenario "unreadable after install" { Invoke-Swap -Leaves @(@{ XpuDist = "3.5.0"; Imports = $true; Readable = $false }, $backOk) }+Check "a post-install probe that cannot read the venv verifies nothing" ($r -and $r.Installs.Count -eq 2)+$r = Try-Scenario "XPU install fails" { Invoke-Swap -Exits @(1, 0) -Leaves @($null, $backOk) }+Check "a failed XPU install restores triton-windows and the manifest" ($r -and $r.Installs.Count -eq 2 -and $r.StackExit -eq 0 -and $r.Manifest)++Write-Host "=== fallback: verified too ==="+$r = Try-Scenario "fallback exit 0, no import" { Invoke-Swap -Exits @(1, 0) -Leaves @($null, $null) }+Check "a fallback that exits 0 without a working triton fails setup" ($r -and $r.StackExit -ne 0 -and (Has-Error $r))+Check "and the manifest is not restored" ($r -and -not $r.Manifest)+$r = Try-Scenario "fallback fails" { Invoke-Swap -Exits @(1, 7) -Leaves @($null, $null) }+Check "a failed fallback fails setup with its exit code" ($r -and $r.StackExit -eq 7 -and (Has-Error $r) -and -not $r.Manifest)++Write-Host "=== swap: resolver inputs isolated ==="+foreach ($n in $envNames) { Set-Item "Env:$n" "inherited-$n" }+$r = Try-Scenario "env isolation" { Invoke-Swap -Leaves @($null, $backOk) }+$clean = "|||||0"+Check "fetch, uninstalls, install and fallback run with UV_OVERRIDE / UV_EXCLUDE / UV_CONSTRAINT / PIP_CONSTRAINT cleared and hashes relaxed" ($r -and $script:EnvSeen.Count -eq 5 -and @($script:EnvSeen | Where-Object { $_ -ne $clean }).Count -eq 0)+Check "and every inherited value is restored afterwards" (@($envNames | Where-Object { [Environment]::GetEnvironmentVariable($_) -ne "inherited-$_" }).Count -eq 0)+foreach ($n in $envNames) { Remove-Item "Env:$n" -ErrorAction SilentlyContinue }+$r = Try-Scenario "unset env" { Invoke-Swap }+Check "unset ones stay unset after the swap" ($r -and @($envNames | Where-Object { $null -ne [Environment]::GetEnvironmentVariable($_) }).Count -eq 0)++Write-Host "=== swap: when it does not apply ==="+$r = Try-Scenario "no triton-windows" { Invoke-Swap -TritonWin "" -XpuDist "3.5.0" }+Check "no triton-windows, the XPU triton torch requires: nothing is touched" ($r -and $r.Calls.Count -eq 0 -and $r.Manifest)+$r = Try-Scenario "not the xpu wheel" { Invoke-Swap -Spec "triton==3.5.0" }+Check "a torch that does not require an XPU triton: nothing is touched" ($r -and $r.Calls.Count -eq 0 -and $r.Manifest)+$r = Try-Scenario "uninstall fails" { Invoke-Swap -UninstallExit 1 }+Check "a failed uninstall installs nothing and keeps the manifest" ($r -and $r.Installs.Count -eq 0 -and $r.Manifest -and $r.StackExit -eq 0)++Write-Host "=== swap: a failed uninstall that broke triton ==="+$r = Try-Scenario "uninstall fails part way" { Invoke-Swap -UninstallExit 5 -UninstallBreaks $true }+Check "a failed uninstall that leaves triton unimportable fails setup with its exit code" ($r -and $r.StackExit -eq 5 -and (Has-Error $r))+Check "and the manifest is not restored" ($r -and -not $r.Manifest -and $r.Installs.Count -eq 0)+$r = Try-Scenario "uninstall fails, broken before" { Invoke-Swap -UninstallExit 5 -UninstallBreaks $true -Imports $false }+Check "a triton already broken before the swap warns, keeps setup going and withholds the manifest" ($r -and $r.StackExit -eq 0 -and -not (Has-Error $r) -and -not $r.Manifest)++Write-Host "=== swap: a triton that does not import, with no triton-windows record ==="+$r = Try-Scenario "repair, no record" { Invoke-Swap -TritonWin "" -Imports $false }+Check "a damaged triton with no triton-windows record is reinstalled from the XPU wheel" ($r -and $r.Installs.Count -eq 1 -and $r.Calls[0] -like "download *" -and $r.StackExit -eq 0 -and $r.Manifest)+Check "and nothing is uninstalled" ($r -and @($r.Calls | Where-Object { $_ -like "uninstall *" }).Count -eq 0)+$r = Try-Scenario "repair fails" { Invoke-Swap -TritonWin "" -Imports $false -Exits @(1, 1) -Leaves @($null, $null) }+Check "a repair that cannot fix an already broken triton warns, keeps setup going and withholds the manifest" ($r -and $r.Installs.Count -eq 2 -and $r.StackExit -eq 0 -and -not (Has-Error $r) -and -not $r.Manifest)+++Write-Host "=== swap: the XPU triton dist itself ==="+$r = Try-Scenario "no XPU dist, generic files import" { Invoke-Swap -TritonWin "" }+Check "an importable triton with no XPU triton dist recorded is replaced by the XPU wheel" ($r -and $r.Installs.Count -eq 1 -and $r.Calls[0] -like "download *" -and $r.StackExit -eq 0 -and $r.Manifest)+$r = Try-Scenario "wrong XPU version" { Invoke-Swap -TritonWin "" -XpuDist "3.4.0" }+Check "an XPU triton torch does not accept is reinstalled, with nothing to uninstall" ($r -and $r.Installs.Count -eq 1 -and @($r.Calls | Where-Object { $_ -like "uninstall *" }).Count -eq 0 -and $r.StackExit -eq 0)+$r = Try-Scenario "installs the wrong version" { Invoke-Swap -Leaves @(@{ XpuDist = "3.4.0"; Imports = $true }, $backOk) }+Check "an install that leaves a version torch does not accept is not verified and falls back" ($r -and $r.Installs.Count -eq 2 -and $r.Installs[1] -eq "install --force-reinstall --no-deps $generic")++Write-Host "=== swap: a dead mirror for a triton already broken ==="+$r = Try-Scenario "download fails, broken" { Invoke-Swap -TritonWin "" -Imports $false -DownloadExit 1 }+Check "a failed fetch for a triton that does not import withholds the manifest" ($r -and $r.Installs.Count -eq 0 -and -not $r.Manifest -and $r.StackExit -eq 0)+$r = Try-Scenario "download fails, working" { Invoke-Swap -DownloadExit 1 }+Check "a failed fetch for a working triton keeps the manifest" ($r -and $r.Installs.Count -eq 0 -and $r.Manifest -and $r.StackExit -eq 0)++Write-Host "=== swap: installer-managed setup keeps its rollback copy ==="+$r = Try-Scenario "managed, uninstall fails, broken before" { Invoke-Swap -UninstallExit 5 -UninstallBreaks $true -Imports $false -Managed $true }+Check "installer-managed: a failed uninstall leaving triton broken fails setup even when it was broken before" ($r -and $r.StackExit -ne 0 -and (Has-Error $r))+$r = Try-Scenario "managed, both installs fail, broken before" { Invoke-Swap -TritonWin "" -Imports $false -Exits @(1, 1) -Leaves @($null, $null) -Managed $true }+Check "installer-managed: a repair and fallback that both fail an already broken triton fail setup" ($r -and $r.StackExit -ne 0 -and (Has-Error $r))+$r = Try-Scenario "managed, download fails, broken" { Invoke-Swap -TritonWin "" -Imports $false -DownloadExit 1 -Managed $true }+Check "installer-managed: a failed fetch for a broken triton fails setup" ($r -and $r.StackExit -ne 0)+$r = Try-Scenario "managed, happy path" { Invoke-Swap -Managed $true }+Check "installer-managed: a verified swap keeps setup going" ($r -and $r.StackExit -eq 0 -and $r.Manifest)+$r = Try-Scenario "managed, uninstall fails, still imports" { Invoke-Swap -UninstallExit 1 -Managed $true }+Check "installer-managed: a failed uninstall that left triton importing keeps setup going" ($r -and $r.StackExit -eq 0)++Write-Host "=== swap: generic files under the XPU record ==="+$r = Try-Scenario "generic payload, XPU record" {+ Invoke-Swap -TritonWin "" -XpuDist "3.5.0" -Leaves @($xpuOk) -Extra @{ XpuRt = $false }+}+Check "an importable generic triton under the XPU dist's record is reinstalled from the XPU wheel" ($r -and $r.Installs.Count -eq 1 -and $r.Calls[0] -like "download *" -and $r.StackExit -eq 0 -and $r.Manifest)++Write-Host "=== swap: unreadable metadata ==="+$r = Try-Scenario "managed, metadata unreadable, broken" { Invoke-Swap -TritonWin "" -Imports $false -Managed $true -Extra @{ Readable = $false } }+Check "installer-managed: a broken triton fails setup even when the metadata probe could not read torch's requirement" ($r -and $r.StackExit -ne 0 -and (Has-Error $r))+$r = Try-Scenario "metadata fails part way" { Invoke-Swap -TritonWin "" -Extra @{ PartialSpec = $xpuSpec } }+Check "a metadata probe that fails after reading torch's requirement still repairs from the XPU wheel" ($r -and $r.Calls.Count -ge 2 -and $r.Calls[0] -like "download *")++Write-Host "=== swap: the triton-windows fallback ==="+$r = Try-Scenario "fallback after an unverified XPU install" { Invoke-Swap -Leaves @(@{ XpuDist = "3.5.0"; Imports = $true; Readable = $false }, $backOk) }+Check "the XPU dist is uninstalled before the triton-windows fallback, so its record does not stay over generic files" ($r -and @($r.Calls | Where-Object { $_ -like "uninstall *pytorch-triton-xpu*" }).Count -eq 1 -and $r.Calls[-1] -eq "install --force-reinstall --no-deps $generic" -and $r.StackExit -eq 0)+$r = Try-Scenario "fallback installs nothing" { Invoke-Swap -Exits @(1, 0) -Leaves @($null, @{ Imports = $true }) }+Check "a fallback that exits 0 but leaves no triton-windows record is not verified" ($r -and $r.StackExit -ne 0 -and -not $r.Manifest)+$r = Try-Scenario "managed, fallback replaces an XPU triton" { Invoke-Swap -TritonWin "" -XpuDist "3.4.0" -Exits @(1, 0) -Leaves @($null, $backOk) -Managed $true }+Check "installer-managed: falling back to triton-windows over a triton that was not triton-windows fails setup" ($r -and $r.StackExit -ne 0 -and (Has-Error $r))+$r = Try-Scenario "fallback replaces an XPU triton" { Invoke-Swap -TritonWin "" -XpuDist "3.4.0" -Exits @(1, 0) -Leaves @($null, $backOk) }+Check "a direct update that falls back over a non-triton-windows triton warns and keeps going" ($r -and $r.StackExit -eq 0 -and -not (Has-Error $r))++$r = Try-Scenario "XPU cleanup fails, fallback imports" {+ Invoke-Swap -Exits @(1, 0) -Leaves @(@{ XpuDist = "3.5.0"; Imports = $false }, $backOk) -XpuUninstallExit 5 -XpuUninstallLeaves $true+}+Check "a fallback that imports after failed XPU cleanup fails setup and withholds the manifest" ($r -and $r.StackExit -ne 0 -and -not $r.Manifest)+$r = Try-Scenario "XPU cleanup exits zero, XPU record remains" {+ Invoke-Swap -Exits @(1, 0) -Leaves @(@{ XpuDist = "3.5.0"; Imports = $false }, $backOk) -XpuUninstallLeaves $true+}+Check "a fallback with the XPU distribution still recorded is not certified" ($r -and $r.StackExit -ne 0 -and -not $r.Manifest)++$r = Try-Scenario "managed, already broken, XPU record survives fallback" {+ Invoke-Swap -Imports $false -Managed $true -Exits @(1, 0) -Leaves @(@{ XpuDist = "3.5.0"; Imports = $false }, $backOk) -XpuUninstallExit 5 -XpuUninstallLeaves $true+}+Check "installer-managed: an importing fallback with stale XPU ownership fails even when triton was already broken" ($r -and $r.StackExit -ne 0 -and -not $r.Manifest)+$r = Try-Scenario "cleanup reports failure, verified clean fallback" {+ Invoke-Swap -Exits @(1, 0) -Leaves @(@{ XpuDist = "3.5.0"; Imports = $false }, $backOk) -XpuUninstallExit 5+}+Check "a cleanup error with no XPU record and a verified fallback keeps the existing recovery behavior" ($r -and $r.StackExit -eq 0 -and $r.Manifest)++$r = Try-Scenario "spaced requirement repair command" {+ Invoke-Swap -Spec "pytorch-triton-xpu ==3.5.0" -Exits @(1, 1) -Leaves @($null, $null)+}+$repair = @($r.Lines | Where-Object { $_ -match '^\s*Repair with: ' } | ForEach-Object { $_ -replace '^\s*Repair with: ', '' }) | Select-Object -First 1+$repairTokens = $null; $repairErrors = $null+$repairArgs = @()+if ($repair) {+ $repairAst = [System.Management.Automation.Language.Parser]::ParseInput($repair, [ref]$repairTokens, [ref]$repairErrors)+ $repairArgs = @($repairAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.StringConstantExpressionAst] }, $true) | ForEach-Object { $_.Value })+}+Check "the displayed repair passes the spaced requirement as one PowerShell argument" ($repair -and $repairErrors.Count -eq 0 -and $repairArgs -contains "pytorch-triton-xpu ==3.5.0")++Write-Host "=== swap: installer-managed setup, offline ==="+$r = Try-Scenario "managed, offline, broken" { Invoke-Swap -TritonWin "" -Imports $false -Offline $true -Managed $true }+Check "installer-managed, offline: a broken triton left for the next online update still fails setup" ($r -and $r.Calls.Count -eq 0 -and $r.StackExit -ne 0 -and (Has-Error $r))+$r = Try-Scenario "managed, offline, triton-windows importing" { Invoke-Swap -Offline $true -Managed $true }+Check "installer-managed, offline: a triton-windows that imports is left in place and setup keeps going" ($r -and $r.Calls.Count -eq 0 -and $r.StackExit -eq 0 -and $r.Manifest)++Write-Host "=== swap: offline ==="+$r = Try-Scenario "offline, broken" { Invoke-Swap -TritonWin "" -Imports $false -Offline $true }+Check "offline: a broken triton is left for the next online update, nothing fetched" ($r -and $r.Calls.Count -eq 0 -and $r.StackExit -eq 0)+$r = Try-Scenario "offline, triton-windows" { Invoke-Swap -Offline $true }+Check "offline: triton-windows is left for the next online update, nothing fetched" ($r -and $r.Calls.Count -eq 0)++Write-Host "=== probe code (real Python): pip backups are not installed dists ==="+$site = Join-Path ([System.IO.Path]::GetTempPath()) ("xpu_triton_probe_" + [guid]::NewGuid().ToString("N"))+function New-DistInfo([string]$Folder, [string]$Name, [string]$Version, [string]$Requires = "") {+ $dir = Join-Path $site $Folder+ New-Item -ItemType Directory -Path $dir -Force | Out-Null+ $meta = "Metadata-Version: 2.1`nName: $Name`n"+ if ($Version) { $meta += "Version: $Version`n" }+ if ($Requires) { $meta += "Requires-Dist: $Requires`n" }+ Set-Content -LiteralPath (Join-Path $dir "METADATA") -Value $meta -Encoding ascii+}+try {+ New-DistInfo "torch-2.9.0+xpu.dist-info" "torch" "2.9.0+xpu" "$xpuSpec; platform_system == 'Windows'"+ New-DistInfo "pytorch_triton_xpu-3.5.0.dist-info" "pytorch-triton-xpu" "3.5.0"+ New-DistInfo "bitsandbytes-0.50.0.dist-info" "bitsandbytes" "0.50.0"+ New-DistInfo "~riton_windows-3.9.0.post30.dist-info" "triton-windows" "3.9.0.post30"+ $tl = Join-Path (Join-Path $site "triton") "language"+ New-Item -ItemType Directory -Path $tl -Force | Out-Null+ Set-Content -LiteralPath (Join-Path (Join-Path $site "triton") "__init__.py") -Value "__version__ = '3.5.0'`ndef jit(f):`n return f" -Encoding ascii+ Set-Content -LiteralPath (Join-Path $tl "__init__.py") -Value "def program_id(axis):`n return 0" -Encoding ascii+ # Model Triton's entry-point discovery, not just the presence of an Intel directory.+ $intel = Join-Path (Join-Path (Join-Path $site "triton") "backends") "intel"+ New-Item -ItemType Directory -Path $intel -Force | Out-Null+ Set-Content -LiteralPath (Join-Path (Split-Path $intel) "__init__.py") -Value @'+from importlib import import_module+from importlib.metadata import entry_points+from types import SimpleNamespace+backends = {+ ep.name: SimpleNamespace(compiler=import_module(ep.value + '.compiler').XPUBackend,+ driver=import_module(ep.value + '.driver').XPUDriver)+ for ep in entry_points().select(group='triton.backends')+}+'@ -Encoding ascii+ Set-Content -LiteralPath (Join-Path (Split-Path $intel) "compiler.py") -Value @'+from collections import namedtuple+GPUTarget = namedtuple('GPUTarget', 'backend arch warp_size')+'@ -Encoding ascii+ Set-Content -LiteralPath (Join-Path $intel "__init__.py") -Value "" -Encoding ascii+ Set-Content -LiteralPath (Join-Path $intel "compiler.py") -Value @'+class XPUBackend:+ @staticmethod+ def supports_target(target):+ return target.backend == 'xpu'+'@ -Encoding ascii+ Set-Content -LiteralPath (Join-Path $intel "driver.py") -Value @'+class XPUDriver:+ @staticmethod+ def is_active():+ raise AssertionError('payload verification must not require a device')+'@ -Encoding ascii+ $entryPoints = Join-Path (Join-Path $site "pytorch_triton_xpu-3.5.0.dist-info") "entry_points.txt"+ $intelEntryPoint = "[triton.backends]`nintel = triton.backends.intel"+ Set-Content -LiteralPath $entryPoints -Value $intelEntryPoint -Encoding ascii+ $script:RealProbeDir = $site+ $s = Try-Scenario "runtime probe, payload present" { Get-TritonRuntimeState }+ Check "runtime probe: the fixture triton imports" ($s -and $s.Healthy)++ # torch-2.8.0+xpu-cp312-cp312-win_amd64.whl.metadata uses this spaced requirement.+ Remove-Item -Recurse -LiteralPath (Join-Path $site "torch-2.9.0+xpu.dist-info")+ New-DistInfo "torch-2.8.0+xpu.dist-info" "torch" "2.8.0+xpu" "pytorch-triton-xpu ==3.4.0"+ $s = Try-Scenario "swap probe, official Windows torch requirement" { Get-XpuTritonState }+ Check "swap probe: torch 2.8's spaced XPU requirement is preserved" ($s -and $s.Known -and $s.XpuSpec -eq "pytorch-triton-xpu ==3.4.0")+ $r = Try-Scenario "swap, official Windows torch requirement" {+ $script:Calls = @(); $script:InstallExits = @(); $script:InstallLeaves = @()+ Set-Content -LiteralPath $manifestFile -Value '{"complete": true}' -Encoding ascii+ $stackExit = 0; $XpuIndexUrl = "https://download.pytorch.org/whl/xpu"; $VenvDir = $venvRoot; $_tritonSpec = $generic+ Invoke-Expression $swap+ @{ Calls = $script:Calls }+ }+ Check "swap: torch 2.8's spaced requirement starts the wrong-version repair" ($r -and $r.Calls.Count -gt 0 -and $r.Calls[0] -like "download *pytorch-triton-xpu ==3.4.0*")+ Remove-Item -Recurse -LiteralPath (Join-Path $site "torch-2.8.0+xpu.dist-info")+ New-DistInfo "torch-2.9.0+xpu.dist-info" "torch" "2.9.0+xpu" "$xpuSpec; platform_system == 'Windows'"++ $r = Try-Scenario "fast path, backup only" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: a ~riton_windows backup alone does not force the dependency pass" ($r -eq $true)+ $s = Try-Scenario "swap probe, backup only" { Get-XpuTritonState }+ Check "swap probe: a ~riton_windows backup alone is not a triton-windows to replace" ($s -and $s.Known -and $s.TritonWin -eq "" -and $s.XpuSpec -eq $xpuSpec -and $s.XpuDist -eq "3.5.0")+ $r = Try-Scenario "swap, backup only" {+ $script:Calls = @()+ Set-Content -LiteralPath $manifestFile -Value '{"complete": true}' -Encoding ascii+ $stackExit = 0; $XpuIndexUrl = "https://download.pytorch.org/whl/xpu"; $VenvDir = $venvRoot; $_tritonSpec = $generic+ Invoke-Expression $swap+ @{ Calls = $script:Calls.Count; StackExit = $stackExit }+ }+ Check "swap: nothing is fetched or removed for a backup alone" ($r -and $r.Calls -eq 0 -and $r.StackExit -eq 0)++ Rename-Item -LiteralPath (Join-Path $site "triton") -NewName "triton_gone"+ $r = Try-Scenario "fast path, backup only, payload missing" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: a backup with no triton files forces the dependency pass" ($r -eq $false)+ $r = Try-Scenario "swap, backup only, payload missing" {+ $script:Calls = @(); $script:InstallExits = @(); $script:InstallLeaves = @()+ Set-Content -LiteralPath $manifestFile -Value '{"complete": true}' -Encoding ascii+ $stackExit = 0; $XpuIndexUrl = "https://download.pytorch.org/whl/xpu"; $VenvDir = $venvRoot; $_tritonSpec = $generic+ Invoke-Expression $swap+ @{ Calls = $script:Calls }+ }+ Check "swap: a backup with no triton files is repaired from the XPU wheel, with no triton-windows to uninstall" ($r -and $r.Calls.Count -ge 2 -and $r.Calls[0] -like "download *" -and $r.Calls[1] -like "install --force-reinstall --no-deps *pytorch_triton_xpu*" -and @($r.Calls | Where-Object { $_ -like "uninstall triton-windows*" }).Count -eq 0)+ $script:Offline = $true+ $r = Try-Scenario "fast path, payload missing, offline" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ $script:Offline = $false+ Check "fast path, offline: a backup with no triton files is left for the next online update" ($r -eq $true)+ Rename-Item -LiteralPath (Join-Path $site "triton_gone") -NewName "triton"++ $xpuInfo = Join-Path $site "pytorch_triton_xpu-3.5.0.dist-info"+ Rename-Item -LiteralPath $xpuInfo -NewName "parked_xpu"+ $r = Try-Scenario "fast path, no XPU dist" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: an importable triton without torch's XPU triton dist forces the dependency pass" ($r -eq $false)+ $s = Try-Scenario "swap probe, no XPU dist" { Get-XpuTritonState }+ Check "swap probe: no XPU triton dist is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk -and $s.XpuDist -eq "")+ New-DistInfo "pytorch_triton_xpu-3.4.0.dist-info" "pytorch-triton-xpu" "3.4.0"+ $s = Try-Scenario "swap probe, wrong version" { Get-XpuTritonState }+ Check "swap probe: an XPU triton 3.4.0 under a torch that requires 3.5.0 is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk -and $s.XpuDist -eq "3.4.0")+ $r = Try-Scenario "fast path, wrong version" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: an XPU triton torch does not accept forces the dependency pass" ($r -eq $false)+ Remove-Item -LiteralPath (Join-Path $site "pytorch_triton_xpu-3.4.0.dist-info") -Recurse -Force+ New-DistInfo "pytorch_triton_xpu-0.dist-info" "pytorch-triton-xpu" ""+ $s = Try-Scenario "swap probe, versionless XPU dist" { Get-XpuTritonState }+ Check "swap probe: an XPU triton record without Version is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk -and $s.XpuDist -eq "?")+ Remove-Item -LiteralPath (Join-Path $site "pytorch_triton_xpu-0.dist-info") -Recurse -Force+ Rename-Item -LiteralPath (Join-Path $site "parked_xpu") -NewName "pytorch_triton_xpu-3.5.0.dist-info"+ $s = Try-Scenario "swap probe, the XPU dist torch requires" { Get-XpuTritonState }+ Check "swap probe: the XPU triton torch requires is XpuOk" ($s -and $s.Known -and $s.XpuOk)++ $intelGone = Join-Path (Join-Path (Join-Path $site "triton") "backends") "intel_gone"+ Rename-Item -LiteralPath $intel -NewName "intel_gone"+ $s = Try-Scenario "swap probe, no Intel directory" { Get-XpuTritonState }+ Check "swap probe: matching versions without an importable Intel backend are not XpuOk" ($s -and $s.Known -and -not $s.XpuOk)+ $r = Try-Scenario "fast path, missing Intel backend" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: a missing Intel backend forces the dependency pass" ($r -eq $false)+ $r = Try-Scenario "swap, missing Intel backend" {+ $script:Calls = @(); $script:InstallExits = @(); $script:InstallLeaves = @()+ $stackExit = 0; $XpuIndexUrl = "https://download.pytorch.org/whl/xpu"; $VenvDir = $venvRoot; $_tritonSpec = $generic+ Invoke-Expression $swap+ @{ Calls = $script:Calls }+ }+ Check "swap: a missing Intel backend requests an XPU wheel repair" ($r -and $r.Calls.Count -gt 0 -and $r.Calls[0] -like "download *")+ Set-Content -LiteralPath $entryPoints -Value "[triton.backends]`nxpu_plugin = triton.backends.intel_gone" -Encoding ascii+ $s = Try-Scenario "swap probe, relocated Intel backend" { Get-XpuTritonState }+ Check "swap probe: an XPU compiler registered under another name is accepted without an active device" ($s -and $s.Known -and $s.XpuOk)+ Rename-Item -LiteralPath $intelGone -NewName "intel"+ Set-Content -LiteralPath $entryPoints -Value "[triton.backends]" -Encoding ascii+ $s = Try-Scenario "swap probe, unregistered Intel directory" { Get-XpuTritonState }+ Check "swap probe: an Intel directory without backend registration is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk)+ Set-Content -LiteralPath $entryPoints -Value $intelEntryPoint -Encoding ascii+ Rename-Item -LiteralPath (Join-Path $intel "driver.py") -NewName "driver_gone.py"+ $s = Try-Scenario "swap probe, missing Intel driver module" { Get-XpuTritonState }+ Check "swap probe: an Intel backend with an unimportable driver is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk)+ Rename-Item -LiteralPath (Join-Path $intel "driver_gone.py") -NewName "driver.py"+ $compilerPath = Join-Path $intel "compiler.py"+ $compilerCode = Get-Content -LiteralPath $compilerPath -Raw+ Set-Content -LiteralPath $compilerPath -Value ($compilerCode.Replace("== 'xpu'", "== 'cuda'")) -Encoding ascii+ $s = Try-Scenario "swap probe, non-XPU compiler" { Get-XpuTritonState }+ Check "swap probe: a registered backend that does not support XPU is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk)+ Set-Content -LiteralPath $compilerPath -Value $compilerCode -Encoding ascii+ $tinit = Join-Path (Join-Path $site "triton") "__init__.py"+ Set-Content -LiteralPath $tinit -Value "__version__ = '3.4.0'`ndef jit(f):`n return f" -Encoding ascii+ $s = Try-Scenario "swap probe, runtime version" { Get-XpuTritonState }+ Check "swap probe: a triton reporting 3.4.0 under a 3.5.0 XPU record is not XpuOk" ($s -and $s.Known -and -not $s.XpuOk)+ Set-Content -LiteralPath $tinit -Value "__version__ = '3.5.0'`ndef jit(f):`n return f" -Encoding ascii+ # Same size, same second: the cached bytecode would still say 3.4.0.+ Remove-Item -LiteralPath (Join-Path (Join-Path $site "triton") "__pycache__") -Recurse -Force -ErrorAction SilentlyContinue++ # No parser importable (-S: neither packaging nor pip): an exact pin with a local label matches its own wheel.+ $torchInfo = Join-Path $site "torch-2.9.0+xpu.dist-info"+ $xpuInfo = Join-Path $site "pytorch_triton_xpu-3.5.0.dist-info"+ New-DistInfo "torch-2.9.0+xpu.dist-info" "torch" "2.9.0+xpu" "pytorch-triton-xpu==3.5.0+git1b0418a9; platform_system == 'Windows'"+ New-DistInfo "pytorch_triton_xpu-3.5.0.dist-info" "pytorch-triton-xpu" "3.5.0+git1b0418a9"+ $s = Try-Scenario "swap probe, local label" { Get-XpuTritonState }+ Check "swap probe: ==3.5.0+git... matches an installed 3.5.0+git... without a version parser" ($s -and $s.Known -and $s.XpuOk)+ New-DistInfo "torch-2.9.0+xpu.dist-info" "torch" "2.9.0+xpu" "$xpuSpec; platform_system == 'Windows'"+ New-DistInfo "pytorch_triton_xpu-3.5.0.dist-info" "pytorch-triton-xpu" "3.5.0"++ # A packaging that is found but does not import: the next parser decides, the metadata stays readable.+ $pkg = Join-Path $site "packaging"+ New-Item -ItemType Directory -Path $pkg -Force | Out-Null+ Set-Content -LiteralPath (Join-Path $pkg "__init__.py") -Value "" -Encoding ascii+ Set-Content -LiteralPath (Join-Path $pkg "requirements.py") -Value "raise ImportError('damaged')" -Encoding ascii+ $s = Try-Scenario "swap probe, damaged packaging" { Get-XpuTritonState }+ Check "swap probe: a damaged packaging falls back to the next parser" ($s -and $s.Known -and $s.XpuOk -and $s.XpuDist -eq "3.5.0")+ Remove-Item -LiteralPath $pkg -Recurse -Force++ New-DistInfo "triton_windows-3.9.0.post30.dist-info" "triton-windows" "3.9.0.post30"+ $r = Try-Scenario "fast path, active" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: an active triton-windows still forces the dependency pass" ($r -eq $false)+ $script:Offline = $true+ $r = Try-Scenario "fast path, active, offline" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ $script:Offline = $false+ Check "fast path, offline: an active triton-windows is left for the next online update" ($r -eq $true)+ $s = Try-Scenario "swap probe, active" { Get-XpuTritonState }+ Check "swap probe: an active triton-windows is found" ($s -and $s.TritonWin -eq "3.9.0.post30")+ Remove-Item -LiteralPath (Join-Path $site "triton_windows-3.9.0.post30.dist-info") -Recurse -Force+ New-DistInfo "triton_windows-0.dist-info" "triton-windows" ""+ $s = Try-Scenario "swap probe, versionless" { Get-XpuTritonState }+ Check "swap probe: a record without Version still counts as triton-windows" ($s -and $s.Known -and $s.TritonWin -eq "?")+ Remove-Item -LiteralPath (Join-Path $site "triton_windows-0.dist-info") -Recurse -Force++ New-DistInfo "~itsandbytes-0.45.0.dist-info" "bitsandbytes" "0.45.0"+ $r = Try-Scenario "fast path, bnb backup" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: a ~itsandbytes backup does not make bitsandbytes stale" ($r -eq $true)+ Remove-Item -LiteralPath (Join-Path $site "bitsandbytes-0.50.0.dist-info") -Recurse -Force+ $r = Try-Scenario "fast path, bnb backup only" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ Check "fast path: a bitsandbytes backup alone is missing bitsandbytes" ($r -eq $false)+ $script:Offline = $true+ $r = Try-Scenario "fast path, bnb backup only, offline" {+ $SkipPythonDeps = $true; $_xpuIsReachable = $true; $script:IsIntelXpu = $true; $installedTorchTag = "xpu"+ Invoke-Expression $fastPath+ $SkipPythonDeps+ }+ $script:Offline = $false+ Check "fast path, offline: a missing bitsandbytes still runs the dependency pass, as on main" ($r -eq $false)+} finally {+ $script:RealProbeDir = $null+ Remove-Item -LiteralPath $site -Recurse -Force -ErrorAction SilentlyContinue+}+} finally {+ Remove-Item -LiteralPath $venvRoot -Recurse -Force -ErrorAction SilentlyContinue+}++if ($failures -gt 0) {+ Write-Host "$failures check(s) failed" -ForegroundColor Red+ exit 1+}+Write-Host "All checks passed"