Skip to content

Windows installer: fix single-AMD-GPU detection and the unrecoverable "needs repair" loop - #8398

Merged
danielhanchen merged 9 commits into
mainfrom
amd-installer-repair-loop
Aug 11, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
amd-installer-repair-loop

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Two defects that met on the same host and left the Windows installer unable to converge on a single-Radeon machine, plus the hazards that surfaced while closing them. Reported on a Radeon PRO W7900 + W7500 box running Windows 10 and ROCm 7.13.99004.

1. A single AMD GPU read as no AMD GPU

studio/setup.ps1, the WMI fallback that runs when there is no HIP SDK, picked between the healthy adapters and the full adapter list like this:

$wmiGpus = if ($healthyGpus.Count -gt 0) { $healthyGpus } else { $amdGpus }

A one-element array unrolls to a scalar on its way out of an if-expression, and for the type Get-CimInstance returns that scalar's .Count is $null under Windows PowerShell 5.1. So on a host with exactly one AMD GPU the next line, if ($wmiGpus.Count -gt 0), was false: $script:ROCmGpuLabels was never set, no gfx arch was inferred, the hardware report said gpu none, and the installed ROCm environment was then judged stale with torch rocm != required cpu.

The type matters and is worth stating precisely, because checking this the obvious way suggests the bug is imaginary. Measured on a windows-latest runner, 5.1.26100.33158 against pwsh 7.6.4:

value 5.1 .Count 7 .Count
CimInstance, one instance $null 1
PSCustomObject $null 1
String 1 1
plain .NET object 1 1

Fixed by wrapping the whole if in @(), the idiom the Intel scan already uses in the same file and in install.ps1. Verified end to end on that runner by running the pre-fix source from main and the post-fix source side by side: one healthy AMD GPU reports 0 before and 1 after, and two-GPU and zero-GPU cases are identical either way, since a two-element array does not unroll. That is why this only ever hit single-card hosts.

studio/install_python_stack.py's WMI path was checked for the same shape. It does not have it: _names = _healthy or _all_names is correct Python. The comment in setup.ps1 claiming to mirror it is now true.

2. The "needs repair" abort was a fixed point

Independent of what triggered it, the stale-venv abort could not be recovered from. Under $InstallerManagedSetup it printed:

[ERROR] The existing Unsloth environment needs repair.
        Re-run install.ps1 so it can replace the environment safely with rollback.

install.ps1 is the caller on that path. It sets UNSLOTH_INSTALL_ROLLBACK_MANAGED=1 and had already replaced the environment with a rollback copy earlier in the same run, so the advice named the thing that had just happened. Worse, Exit-SetupFailure makes install.ps1 run Restore-StudioVenvRollback, which deletes the new environment and moves the old one back, while Complete-StudioVenvRollback only runs after setup succeeds. Every attempt therefore ended on the byte-identical state it started from, and the next attempt reached the same verdict.

That abort has now been reported from four unrelated triggers (#5942 on CUDA, #7275 on a ROCm clobber, #8335 here, and a driver crash), so this fixes the loop rather than only the trigger. It is replaced by the in-place torch repair that a changed index pin and a changed CUDA family already use: PinChangedForceReinstall makes the dependency pass reinstall the torch trio from the resolved index over the existing environment.

Deleting was never actually available on this path: install.ps1 invokes setup through the environment's own unsloth.exe, so python.exe is held open by the process running the script.

3. What trading the abort for a repair cost, and how each cost is paid

Removing the fixed point opened a second family of failures with one shape: setup exits 0 having done the wrong thing. install.ps1 treats setupExit == 0 as the sole criterion for Complete-StudioVenvRollback, which deletes the backup, so a silent success is permanent, where the abort at least reverted to an identical starting state. Four such paths were found and closed.

The installer's GPU wheel is not force-reinstalled away on the strength of a rescan. Under $InstallerManagedSetup, install.ps1 resolves the index off its own probe and installs the trio before invoking setup, and the environment it hands over carries no family and no index, so setup re-probes from scratch. When those two probes disagree the disagreement is setup's, not the host's: a Get-CimInstance that threw, an nvidia-smi that did not answer, or the single-Radeon unroll above. The repair would then reinstall a different flavour over a working environment and exit 0. The guard keeps the wheel and records the family so it survives index selection, which matters because the AMD arm force-reinstalls unconditionally and the XPU arm force-reinstalls whenever the installed tag is not xpu, so clearing the rebuild flag alone is not enough.

An incomplete environment is refused rather than silently used. Everything after the dot-source reaches the environment through Activate.ps1 and a bare python, Fast-Install resolves its target with (Get-Command python).Source, and install.ps1 deliberately keeps the environment's Scripts directory off PATH. A missing python.exe, a missing Activate.ps1, or an Activate.ps1 that is present but truncated therefore installed the entire stack into whatever interpreter was on PATH and still exited 0. The truncated case is the quiet one: in CPython's Activate.ps1 the PATH assignment is the last statement and $env:VIRTUAL_ENV is set 28 lines earlier, so a torn write produces a file that parses, runs to completion, sets VIRTUAL_ENV and never touches PATH, raising no error at all. Assert-VenvActivated checks the interpreter actually in effect, normalising both sides through Get-Item (the same call Activate.ps1 uses to build its PATH entry) so short paths, substituted drives, junctions and drive-letter case cannot disagree, comparing OrdinalIgnoreCase with an explicit separator so venv2 is not read as a child of venv, and returning rather than refusing when anything is unresolvable.

A driver fault no longer deletes a good ROCm environment. setup.ps1 already guarded this hazard for Intel, reading torch/version.py off disk through Test-VenvTorchIsXpu because "the host most likely to time out inside import torch is an Arc box with a stalled driver". There was no ROCm counterpart, so on AMD a faulted Adrenalin or HIP runtime read as "torch could not be imported" and the working environment was thrown away, which does not fix a driver. Test-VenvTorchIsRocm is the same free disk read and accepts both wheel spellings, 2.8.0+rocm6.4 from download.pytorch.org and the AMD Windows index form. It judges the local label on __version__ only, so a CUDA build carrying hip: Optional[str] = None is not misread as ROCm.

The last unbounded import torch is bounded. Because the rescue above now keeps a venv whose import can hang forever, the AMD fast-path probe became the first import torch such a host reaches, and it had no bound. It goes through Invoke-BoundedPythonProbe like every other probe in the file, with a non-answering probe still reading as CPU so the safe direction is unchanged.

The swallowed error is shown. Invoke-BoundedPythonProbe drained stderr and discarded it, so "the HIP DLLs will not load", "torch is not installed" and "the import never came back" all reached the caller as the same silent .Ok = $false, and the caller deletes environments over that answer. It now carries .Error, in both installers, and the stale-venv message prints the last stderr line, so a WinError 126 reads as a driver problem instead of a broken install. The timeout branch synthesises its message rather than awaiting the reader tasks: awaiting them is exactly the hang the bound exists to prevent.

Tests

tests/studio/test_amd_venv_repair_loop.ps1 follows test_pre_turing_cap.ps1: AST extraction so the top-level installer never runs, a mocked filesystem for the version.py reads, a parity loop over install.ps1 and studio/setup.ps1, and CRLF-normalised source matching with a "was found" guard on every region.

Where behaviour can be driven rather than asserted, it is. The probe checks run a real python -c child on both installer copies. The rebuild decision, the index-selection chain and both install-arm gate conditions are extracted from setup.ps1 and executed against a table of host cases, rather than reimplemented in the test: an earlier hand-copied simulation of that cascade had drifted far enough to assert the wrong outcome. The activation checks build real temporary directories instead of stubbing Get-Item, since a stub would only re-implement the behaviour under test.

cross-platform-parity-ci.yml sets shell: pwsh on every step, so the whole job ran under PowerShell 7, which returns 1 for the scalar 5.1 returns $null for and therefore passes against the unfixed code. This adds a shell: powershell row on the Windows leg, which is the shell the CLI actually launches setup.ps1 with and the only one that can fail on defect 1.

Fixes #8335. Also removes the loop reported in #5942, #7275 and the Discord driver-crash report, which reached the same abort from different triggers.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e556620ce0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/setup.ps1
Comment on lines +3858 to +3867
} elseif (Test-VenvTorchIsRocm -VenvPath $VenvDir) {
# Same rescue on the AMD side, and it is the one that has cost users whole installs.
# A faulted Adrenalin or HIP runtime makes `import torch` raise at the DLL load or
# never return, and the venv then reads as "torch could not be imported" -- so the
# ROCm environment that is actually fine gets thrown away and reinstalled, which
# does not fix a driver. version.py on disk still names the wheel, so trust it and
# point at the driver instead (#8335, #7275).
$installedTorchTag = "rocm"
substep "PyTorch did not respond but this venv holds a ROCm build -- keeping it." "Yellow"
substep "If training fails, reboot and update the AMD Adrenalin / HIP SDK driver." "Yellow"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the fast path after rescuing a ROCm wheel

On a direct update where import torch fails because the AMD driver is faulted but version.py still identifies a ROCm wheel, this branch says it is keeping the environment but does not record that the failure was driver-only. Later, the AMD fast-path check runs another failing import torch, interprets it as CPU-only, sets $SkipPythonDeps = $false, and the ROCm installation arm unconditionally force-reinstalls the entire torch trio. Consequently every update during a driver fault still replaces a healthy multi-gigabyte ROCm installation—the behavior this rescue is intended to prevent—so the disk-based rescue must also suppress that later CPU-wheel escape.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Traced this one and it does not clear the bar. The mechanism is accurate: the second import torch reads a driver fault as CPU-only, clears SkipPythonDeps, and the ROCm arm reinstalls. But the outcome is a correct ROCm install that cost bandwidth, not a wrong result, a crash or data loss. Before this PR that same host had its venv deleted outright, so the rescue is already a strict improvement. The change would also be actively harmful: a half-written wheel produces the identical disk state, and there the dependency pass is the genuine repair, so suppressing the escape would strand that user on a broken torch indefinitely. Slow but correct on a rare degraded host is not worth trading for that. Separately, the probe on this path was the last unbounded import torch in the file, and since the disk-trust rescue now keeps a venv whose import can hang forever, it was the first one such a host would reach. It goes through Invoke-BoundedPythonProbe in 346abff, with a non-answering probe still reading as CPU so the safe direction is unchanged.

…" loop

Two defects that met on the same host and made the installer unable to
converge on a single-Radeon Windows box (#8335).

The WMI fallback picked between the healthy adapters and the full adapter
list with a bare if-expression, which unrolls a one-element array to a
scalar. A scalar's .Count is $null under Windows PowerShell 5.1, so a host
with exactly one AMD GPU read as having none: no $script:ROCmGpuLabels, no
inferred gfx arch, "gpu none" in the hardware report, and the installed
+rocm venv judged stale against a required "cpu". Wrapped in @(), matching
the Intel scan in the same file and in install.ps1.

The stale-venv branch under $InstallerManagedSetup then aborted with
"re-run install.ps1 so it can replace the environment safely with
rollback". install.ps1 is the caller on that path and had already done
exactly that earlier in the same run, and its failure path moves the
previous environment straight back, so every attempt ended on the state it
started from and the next attempt reached the same verdict. That abort has
now been reported from four unrelated triggers. It is replaced by the
in-place torch repair the index-pin and CUDA-family changes already use,
which needs no delete: install.ps1 invokes setup through the venv's own
unsloth.exe, so python.exe is locked by the process running the script.

Also:
- Test-VenvTorchIsRocm, the AMD counterpart of Test-VenvTorchIsXpu. A
  faulted Adrenalin or HIP runtime makes `import torch` raise at the DLL
  load or hang, and the venv then read as "torch could not be imported"
  and got deleted. version.py on disk still names the wheel, so trust it
  and point at the driver.
- Invoke-BoundedPythonProbe keeps the stderr it used to drain and discard,
  in both installers, and the stale-venv message prints it. A dead driver,
  a half-written wheel and a missing torch were previously one sentence.

tests/studio/test_amd_venv_repair_loop.ps1 covers the ROCm disk read, the
probe error plumbing against a real child process in both installers, and
the source shapes. pwsh 7 answers 1 to a scalar .Count, so it cannot
reproduce the 5.1 half of #8335 and does not claim to; that leg is the
windows-latest row of cross-platform-parity-ci.

Closes #8335.
… it, and

close the one path the repair loop fix made worse

Validation follow-up to the previous commit.

The stated root cause was over-general and, as written, wrong. "A scalar's
.Count is $null under Windows PowerShell 5.1" is not true: a String or an
Int32 answers 1 on 5.1, exactly as on 7, so anyone checking the claim that
way concludes there is no bug. $null comes back only for objects whose
PSObject carries no Count of its own -- [pscustomobject], which Microsoft
documents, and CimInstance, which it does not. Get-CimInstance returns the
second kind, which is what the WMI fallback assigns. Measured on
windows-latest, PowerShell 5.1.26100.33158 against a real CIM instance, with
pwsh 7.6.4 on the same runner:

  'a'                         5.1: 1      7: 1
  [pscustomobject]@{...}      5.1: $null  7: 1
  CimInstance (one instance)  5.1: $null  7: 1
  @(if (...) { ... })         5.1: 1      7: 1

The conclusion and the fix are unchanged; the reason is now the right one.

That also means the test could always have been real, rather than a source
shape apologising for pwsh. Win32_OperatingSystem returns exactly one
instance on any Windows host, which reproduces "the machine has exactly one
AMD GPU" with no AMD GPU present. The suite now adapts to its host: under 5.1
it reproduces #8335 and regression-tests the @() wrap for real, under pwsh
the unroll still runs and the consequence is reported as a shape. 93 checks,
green on both, verified on a windows-latest runner under
powershell.exe 5.1.26100.33158 and pwsh 7.6.4.

The claim that the 5.1 leg is covered by cross-platform-parity-ci was wrong:
every step in that workflow is shell: pwsh, which is PowerShell 7. A
shell: powershell step needs adding beside the pwsh one -- 5.1 is the runtime
the CLI actually launches setup with (unsloth_cli/commands/studio.py). Left
out of this commit only because the push token has no workflow scope; the
exact step is on the PR.

The in-place repair had one path it made worse than the abort it replaced. A
venv directory with no Scripts\python.exe is incomplete, not stale, and has
no interpreter to force-reinstall torch through. The abort used to catch it
by catching every stale verdict. Without it the run reaches the activation --
a dot-source, which is NON-terminating at the "Continue" the pip section runs
at -- so setup carried on with the venv unactivated, resolved every later
python and uv pip against PATH, installed the whole stack outside the
environment, and could still exit 0. Narrow to reach, since install.ps1
launches setup through that venv's own unsloth.exe, but silent when reached.
Now refused, before the activation, without deleting anything.

Also:
- The surfaced probe error no longer indexes [0] into a pipeline that a
  whitespace-only stderr empties; fatal under a caller's Set-StrictMode, and
  studio/setup.bat does not pass -NoProfile. Confirmed to throw on 5.1 too.
- $script:PinChangedForceReinstall is hoisted beside $installedTorchTag. Four
  install arms read it to decide --force-reinstall and a fresh install never
  reaches the assignment.
- Test-VenvTorchIsRocm's comment claimed AMD's Windows wheels are labelled
  +gfx1151. They are not. repo.amd.com/rocm/whl/<arch>/torch/ publishes
  torch-2.11.0+rocm7.13.0-cp312-cp312-win_amd64.whl and keeps the arch in the
  URL only -- the same filename is a different binary under gfx1151,
  gfx110X-all and gfx120X-all. download.pytorch.org publishes the
  two-component +rocm6.4, Linux only. +rocm7.13.0 is what the #8335 reporter
  ended up on, and is now a case. The +gfx arm stays as deliberate defence.
@danielhanchen
danielhanchen force-pushed the amd-installer-repair-loop branch from e556620 to ebb9f3e Compare August 11, 2026 10:39
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Validation of this PR, and what it changed

I went back over this one properly. The fix is right and I have now reproduced #8335 on a real
Windows PowerShell 5.1 runner, but the reason I gave for it was wrong, one path was made
worse than the abort it replaced, and the CI coverage I claimed did not exist. All three are
fixed in ebb9f3e4.


1. The stated root cause was over-general, and as written false

I wrote "a scalar's .Count is $null under Windows PowerShell 5.1". That is not true, and it
matters, because the obvious way to check it makes the bug look imaginary:

PS 5.1> $x = 'a'; $x.Count
1

$null comes back only for objects whose PSObject carries no Count of its own:
[pscustomobject], which Microsoft documents, and
Microsoft.Management.Infrastructure.CimInstance, which it does not. Get-CimInstance returns
the second kind, and that is exactly what the WMI fallback assigns.

Measured on windows-latest, powershell.exe 5.1.26100.33158 (Desktop) with pwsh 7.6.4
on the same runner, against a real Get-CimInstance result:

value 5.1 .Count 7 .Count
'a' (String scalar) 1 1
4 (Int32 scalar) 1 1
[pscustomobject]@{...} $null 1
CimInstance, one instance $null 1
@(if (...) { ... }) 1 1

and the guard as the code actually writes it:

OLD  $wmiGpus = if (...)     type=...CimInstance   isArray=False  .Count=$null
NEW  $wmiGpus = @(if (...))  type=System.Object[]  isArray=True   .Count=1
OLD branch taken? ($wmiGpus.Count -gt 0) = False      <-- #8335
NEW branch taken? ($wmiGpus.Count -gt 0) = True

The unroll itself is not version specific and happens on both. Only the consequence differs.
Sources: about_Arrays
and about_Intrinsic_Members
for the scalar rule, about_PSCustomObject
Notes for the documented exception, and the
language spec 8.1.2
plus 7.1.6 / 7.1.7
for why an if expression yields a scalar and @() does not.

Is the defect real? Yes. The reporter of
#8335 independently diagnosed the same line,
patched it, and reported exit 0 with torch 2.11.0+rocm7.13.0 on gfx1151. It is now also
reproduced from the source in CI, not just argued.

2. The test can reproduce it, so it now does

Win32_OperatingSystem returns exactly one instance on any Windows host, which is "the machine
has exactly one AMD GPU" without needing an AMD GPU. That is why this never showed up in CI.
tests/studio/test_amd_venv_repair_loop.ps1 now adapts to its host: under 5.1 it reproduces
#8335 and regression-tests the @() wrap for real, under pwsh the unroll still runs and the
consequence is asserted as a shape, and every check says which it is. 93 checks, green on both.

host: PowerShell 5.1.26100.33158 (Desktop)
  PASS  a String scalar answers 1 on every PowerShell
  PASS  5.1: a Count-less scalar answers $null
  PASS  the @() wrap makes the GPU-label branch fire
  PASS  5.1: the OLD form loses the only adapter (#8335)
All checks passed

3. The CI claim was wrong, and needs one step I cannot push

I said the 5.1 leg was the windows-latest row of cross-platform-parity-ci. Every step in that
workflow is shell: pwsh, which is PowerShell 7. There was no 5.1 coverage anywhere except
studio-windows-update-smoke.yml:91. 5.1 is the shipping runtime: unsloth_cli/commands/studio.py
launches setup with powershell.exe, not pwsh. This needs applying by someone with workflow
scope
(my push token has none), next to the existing pwsh step:

      # And again under Windows PowerShell 5.1, which is the SHIPPING runtime: the CLI launches
      # setup with `powershell.exe` (unsloth_cli/commands/studio.py), not pwsh. This is not a
      # duplicate of the step above. #8335 is a 5.1-only defect -- a one-element array unrolls on
      # every PowerShell, but the resulting scalar's .Count reads $null only on 5.1, and only for
      # a CimInstance, which is exactly what the WMI fallback assigns. Under pwsh the same file
      # reports that half as SKIP/shape; only this leg executes it.
      - name: AMD venv repair loop tests (Windows PowerShell 5.1)
        if: runner.os == 'Windows'
        shell: powershell
        run: powershell -NoProfile -File tests\studio\test_amd_venv_repair_loop.ps1

Before and after, per scenario

studio/setup.ps1 is Windows-only: the single dispatch is
unsloth_cli/commands/studio.py:338, and studio/setup.sh has no stale-venv branch at all
(the whole "venv exists" path is setup.sh:1412-1441, source and continue). So Linux, WSL and
macOS are not reachable by any of this.

Host venv state BEFORE AFTER
any non-Windows any not reachable not reachable
Windows, any GPU fresh install block skipped unchanged
Windows, any GPU healthy venv kept unchanged
Windows, NVIDIA stale (+cpu, host wants cu128) abort, install.ps1 rolls back, loop in-place repair, CUDA arm --force-reinstall
Windows, AMD stale (+cu128, host wants rocm) abort in-place repair, ROCm arm --force-reinstall
Windows, Intel stale (+cu128, host wants xpu) abort in-place repair, XPU arm --force-reinstall
Windows, CPU-only stale (+cu128, no nvidia-smi) abort in-place repair, CPU arm --force-reinstall
Windows, any torch unimportable abort in-place repair, plus the stderr reason printed
Windows, AMD driver crashed, +rocm on disk abort (and on a direct update, venv deleted) kept, driver advice printed, not even judged stale
Windows, Intel driver crashed, +xpu on disk already rescued unchanged
Windows, any venv with no Scripts\python.exe abort (loud) was silent, now refused, see (a)

A direct unsloth studio update ($InstallerManagedSetup false) is byte-identical before and
after on every row except the ROCm disk rescue. Blast radius outside the installer is exactly
that one rescue.

Does it break a previously working path? No. Every changed cell moves from a hard abort to a
repair. The only regression found is the interpreter-less venv, fixed below.


The five risks

(a) Change 2 is not AMD-scoped. Confirmed, and one case was a real regression

Every route to $shouldRebuild under $InstallerManagedSetup, and whether the in-place repair
actually repairs it. --force-reinstall reaches the right arm in every case:
$script:PinChangedForceReinstall clears $SkipPythonDeps at setup.ps1:4346, and the ROCm arm
forces unconditionally while the XPU, CPU and CUDA arms force on that flag.

trigger BEFORE AFTER repaired?
pinned index, flavour mismatch in-place already identical no-op, guard at :3972 fires first
unpinned cu126 vs cu128 drift in-place already identical no-op, guard at :3980 fires first
pinned ROCm family mismatch in-place already identical no-op
custom /simple pin, unknown leaf not stale identical no-op
xpu to cu* (hybrid NVIDIA+Arc) abort in-place yes, CUDA arm
cpu to cu* abort in-place yes, CUDA arm
cu* to cpu abort in-place yes, CPU arm
rocm to cpu (arch not in wheel map) abort in-place yes, CPU arm
cu* to rocm abort in-place yes, ROCm arm
cu* or rocm to xpu abort in-place yes, XPU arm
torch unimportable abort in-place yes
probe hung 30 s, nothing on disk abort in-place yes
driver crash, +rocm on disk abort kept yes, this is #8335
venv exists, no Scripts\python.exe abort (loud) fell through NO

That last row is the regression, and it was silent rather than loud. An interpreter-less venv is
incomplete, not stale, so there is no interpreter to force-reinstall torch through. Execution
reached . $ActivateScript, and a dot-source of a missing path is non-terminating at the
Continue the pip section runs at:

$ pwsh -NoProfile -Command '$ErrorActionPreference="Continue"; . "/nonexistent/Activate.ps1"; Write-Host "REACHED"'
.: The term '/nonexistent/Activate.ps1' is not recognized...
REACHED                      <-- and exit code 0

So setup carried on with the venv unactivated, resolved every later python and uv pip against
PATH, installed the whole stack outside the environment, and could still exit 0. Narrow to reach,
since install.ps1:4599 guards unsloth.exe and launches setup through it, but silent when
reached. Now refused before the activation, without deleting anything, with a message that says
incomplete rather than out of date.

(b) The XPU escape under the installer. Not worse

setup.ps1:3990 is still gated -not $InstallerManagedSetup. Under the installer a stale +xpu
venv used to abort; it now takes the generic in-place repair and is converted to the flavour the
installer already decided for the host. $script:PreservedXpuVenv stays false, which is correct
here, because unlike a direct update we do want the migration. A direct update is unchanged.

(c) Test-VenvTorchIsRocm misclassification. None found, and a wrong comment corrected

Full table, run against a real torch/version.py shape (__all__ line, single quotes,
hip/xpu attrs), 13/13 correct:

torch.__version__ reads as ROCm correct
2.10.0 no yes, untagged
2.10.0+cpu no yes
2.8.0+cu126 (with hip: Optional[str] = None) no yes
2.9.0+cu128 no yes
2.11.0+rocm7.13.0 yes yes, the label #8335 landed on
2.8.0+rocm6.4 yes yes
2.9.0+gfx1151 yes yes
2.7.1+gfx110X.all yes yes
2.11.0+xpu no yes
2.12.0.dev20260801+rocm7.2 yes yes, nightly
2.12.0.dev20260801+cu130 no yes
2.9.0a0+git1a2b3c no yes, source build
2.9.0+cu128 with git_version = 'rocm-branch-gfx1100' no yes

The match is anchored on the __version__ line, so a CUDA build carrying hip: Optional[str] = None
is not a false positive. That is the whole reason it is not a hip grep.

The comment justifying the gfx arm was wrong. I checked the indexes.
repo.amd.com/rocm/whl/<arch>/torch/ is the only place Windows ROCm wheels exist and it publishes
torch-2.11.0+rocm7.13.0-cp312-cp312-win_amd64.whl, keeping the arch in the URL only. The same
filename is a different binary per index (gfx1151 626 MB, gfx110X-all 640 MB, gfx120X-all 267 MB
by content-length), so the arch is genuinely not in the version. download.pytorch.org/whl/rocm6.4
publishes the two-component +rocm6.4 and ships zero win_amd64 wheels. +gfx stays accepted as
deliberate defence, and is now labelled as such rather than as a claim about what AMD ships.

(d) .Error is additive. Proven

Every caller in both installers touches only .Ok and .Output
(install.ps1:3601, 3841, 3855, 3973, 3989; setup.ps1:1063, 3856, 4296, 4762). None splats,
compares or enumerates the object. Set-StrictMode makes a missing property fatal, so adding
one at construction is strictly safer; the PR correctly adds it in the [pscustomobject] literal
rather than assigning a new property later, which would throw.

One real hazard the change did introduce, now fixed: the guard -and $_verProbe.Error passes on a
whitespace-only stderr, Where-Object then drops every line, and @(...)[0] into the empty array
that leaves throws under Set-StrictMode. Reachable, because studio/setup.bat does not pass
-NoProfile. Confirmed to throw on 5.1 as well as 7, and covered by a test with the old form kept
as a negative control.

(e) Force-reinstall over a running interpreter. The claim holds, and this is safe

Verified in the code: install.ps1:4599 resolves $VenvDir\Scripts\unsloth.exe and :4667 runs
setup through it, so the venv's python.exe is executing. Windows will not unlink a running image
(DeleteFileW),
so deleting the venv on this path was never available. The PR body is right about that.

Force-reinstall over it is safe because torch is not loaded in that process. The unsloth CLI
has no module-level import torch anywhere on the studio setup path, so torch's .pyd/.dll
images are not mapped and nothing holds them. Windows locks per loaded image, not per directory.
The failure mode if that ever changed is loud, not silent: NTFS refuses to rename a directory
containing an open file
(MS-FSA 2.1.5.15.12),
and pip surfaces it as [WinError 32] (see pypa/pip#11857,
which is this exact torch case). This is also not a new class of operation: the index-pin and
CUDA-family arms already force-reinstall on this same path in shipped code, and install.ps1:4423
does it too. Not a blocking finding.


What changed in ebb9f3e4

  • studio/setup.ps1: refuse a venv with no Scripts\python.exe before the activation rather than
    half-installing past it; drop the @(...)[0] that a whitespace-only stderr makes fatal under
    strict mode; hoist $script:PinChangedForceReinstall beside $installedTorchTag, since four
    install arms read it and a fresh install never reaches the assignment; correct the
    Test-VenvTorchIsRocm wheel-label comment.
  • tests/studio/test_amd_venv_repair_loop.ps1: reproduce [Bug] AMD Ryzen AI install bug #8335 for real under 5.1 instead of
    apologising for pwsh; add the interpreter-less venv regression with the non-terminating
    dot-source proven first so the guard is not asserted on faith; add the strict-mode case with the
    old form as a negative control; extend the wheel-label table with +rocm7.13.0, nightly, source
    build, +cpu and a git_version decoy.

Test counts

suite before after
tests/studio/*.ps1, pwsh 7.6 on Linux 17 files, 547 checks, 0 fail 18 files, 635 checks, 0 fail
tests/studio/test_amd_venv_repair_loop.ps1, real 5.1 on windows-latest did not exist 93 checks, 0 fail
same file, pwsh 7.6.4 on windows-latest did not exist 93 checks, 0 fail
every python test that scans install.ps1 / setup.ps1 (44 files) 2199 passed, 36 skipped 2199 passed, 36 skipped

The one python failure in that set, test_negative_control_no_tokenizers, fails identically on
origin/main and is an unrelated E2E packaging test.

Honestly labelled

  • Proven by execution on real Windows PowerShell 5.1: the .Count table, the [Bug] AMD Ryzen AI install bug #8335 repro, the
    @() fix, the strict-mode throw, the whole suite passing on both hosts.
  • Proven by reading the source: setup.ps1 being Windows-only, setup.sh having no stale-venv
    branch, the rollback fixed point, the --force-reinstall arm trace, .Error being additive, no
    module-level torch import on the setup path.
  • Simulated by lifting the real decision block out of both trees and driving it with stubbed
    probes: the per-scenario table and the $shouldRebuild enumeration.
  • Not proven, and not claimed: no AMD hardware was involved anywhere. There is still no AMD or
    ROCm CI in this repo, so the ROCm install arms themselves remain mock-covered only.

Every step in cross-platform-parity-ci is shell: pwsh, so the whole job runs
under PowerShell 7. 7 returns .Count = 1 for the single CimInstance that 5.1
returns $null for, which is the entire mechanism of #8335, so the existing pwsh
step passes just as happily against the unfixed code. The suite had no leg on
the shell the CLI actually launches setup.ps1 with.

Adds the same test file under shell: powershell on the Windows row only.
@danielhanchen

Copy link
Copy Markdown
Member Author

Applied the 5.1 leg in dabedd31, so nothing is left outstanding here.

cross-platform-parity-ci.yml sets shell: pwsh on every step, so the whole job ran under
PowerShell 7. Since 7 returns .Count = 1 for the single CimInstance that 5.1 returns $null
for, the existing step passed just as happily against the unfixed code. The new step runs the
same file under shell: powershell on the Windows row only, which is the shell the CLI actually
launches setup.ps1 with.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
… repair, refuse a venv with no activation script, and bound the AMD fast-path torch probe
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Ran the scalar unroll on a real Windows PowerShell 5.1 runner rather than asserting the source
shape, since pwsh 7 cannot reproduce this defect at all. The pre-fix file is fetched from
upstream main, not reconstructed by editing the post-fix one, so the comparison is between the
two real source shapes.

Interpreter: 5.1.26100.33158, PSEdition Desktop, Windows NT 10.0.26100.0.

The crux, scalar .Count per object flavour:

flavour 5.1 7
CimInstance (what Get-CimInstance returns) $null 1
PSCustomObject $null 1
plain .NET object 1 1

So the failure needs a CimInstance or a PSCustomObject. Checking it with a string or an int
shows 1 on both editions and makes the bug look imaginary.

Scenario sweep, ciminstance flavour, GPU count returned by the WMI fallback:

scenario expected pre-fix post-fix
one healthy AMD GPU 1 0 1
two healthy AMD GPUs 2 2 2
one AMD GPU, ConfigManagerErrorCode 45 1 0 1
one healthy + one code 45 1 0 1
AMD GPU with no error code 1 0 1
one healthy AMD + one NVIDIA 1 0 1
no GPUs at all 0 0 0
WMI returned null 0 0 0
NVIDIA only 0 0 0

Every single-AMD-GPU case reports zero before the fix and one after. Two GPUs are unaffected,
because a two-element array does not unroll, which is why this only ever showed up on
single-card hosts. Zero-GPU cases are unchanged in both directions.

cross-platform-parity-ci.yml sets shell: pwsh on every step, so the suite ran entirely under
PowerShell 7 and passed against the unfixed code. The shell: powershell row added here is the
leg that can actually fail on it.

One note on the suite: tests/studio/test_path_probe_access_denied.ps1 fails under both
interpreters, and tests/studio/test_node_probe_guard.ps1 fails under 5.1. A baseline run of
upstream main on the same runners reproduces both, so they are pre-existing and unrelated to
this change.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
…ot just that Activate.ps1 exists

A present Activate.ps1 is not an activated venv. The script prepends the venv to PATH in its
last statement, so a copy truncated by an interrupted or out-of-disk python -m venv runs to its
last complete statement and returns without raising anything at all, and an unparseable one is
a ParserError, which is non-terminating at the Continue the pip section runs at. Either way the
dot-source succeeds with the ambient interpreter still first on PATH, which on a real install
is the system or Microsoft Store python because install.ps1 keeps the venv Scripts directory
off PATH on purpose. Fast-Install hands exactly that to uv pip install --python, every
Exit-SetupFailure after it keys off an exit code from the wrong interpreter, and setup exits 0,
at which point install.ps1 commits over its rollback copy.

Assert the post-condition instead of adding a third existence check: the python now in effect
must live under $VenvDir. VIRTUAL_ENV would not do, since Activate.ps1 sets it before the line
that matters. Both sides are normalised through Get-Item, the same call Activate.ps1 uses to
build the PATH entry, so a short 8.3 path, a substituted drive, a junction or a differently
cased drive letter cannot read as outside, and every branch that cannot prove the interpreter
is wrong returns rather than refusing a working install.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 11, 2026
…elected

The guard that keeps an installer-placed GPU wheel through a rescan treated any
non-cpu wheel under UNSLOTH_INSTALL_ROLLBACK_MANAGED as the installer's own
choice. That is not true on an upgrade: install.ps1's migrated-venv arm installs
unsloth alone and never touches torch, and its flavor repair no-ops whenever its
own expected tag is cpu or unrecognised, so a legacy ~/.unsloth/studio/.venv can
hand setup a +cu118 wheel left by a previous install on different hardware.
Preserving that pinned the whole dependency pass onto a cu118 index, and on a
mapped AMD host the kept cu* tag also blocked the ROCm reroute, which needs
$CuTag -eq "cpu" -- so the Radeon never got a ROCm wheel and setup still exited 0.

install.ps1 now reports the family it settled on in UNSLOTH_INSTALLER_TORCH_TAG
and setup preserves only a wheel that matches it. Absent or blank means the
installer did not say (an older cached install.ps1, or --no-torch) and falls back
to preserving, so an older installer keeps exactly its previous behaviour. A wheel
the installer did not choose repairs in place, as it did before the guard existed;
nothing aborts.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 5819107498

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen and others added 2 commits August 11, 2026 13:47
…oop rounds

Four review rounds each re-explained the same mechanisms, so the exit-0 hazard,
the @() unroll and the preserve guard were each written out in several places.
Keep the full reasoning at one site per mechanism and cut the restatements.
Comments and whitespace only; no executable change.
The Windows PowerShell 5.1 leg of the parity workflow failed at the corrupt
activation script case. Every assertion passed, then the run ended with a
NativeCommandError.

5.1 wraps a native command's stderr in a NativeCommandError and applies
$ErrorActionPreference to it, so the parse error the corrupt script writes to
stderr became terminating under the Stop set at the top of the file. PowerShell
7.1 stopped applying the preference to native stderr, which is why the same
script passes under pwsh and failed only on 5.1.

Set the preference to Continue for the duration of the child invocation. The
exit code is what the case actually judges and it is still read and asserted.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 282b50ae9f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/setup.ps1
# only once $installedTorchTag has answered, which is only true on the path that assigned it.
if ($shouldRebuild -and $InstallerManagedSetup -and
$installedTorchTag -and $installedTorchTag -ne "cpu" -and
((-not $InstallerTorchTag) -or $installedTorchTag -eq $InstallerTorchTag)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Do not preserve GPU wheels when installer provenance is unknown

When the newly installed setup.ps1 is invoked by an older cached install.ps1, this variable is absent, yet the -not $InstallerTorchTag arm treats any installed GPU wheel as if the current installer selected it. In the supported legacy-venv migration path, the installer preserves torch and skips flavor repair when it expects CPU, so a CUDA/ROCm/XPU wheel left from previous hardware reaches this guard, is preserved despite the current CPU verdict, and the installation succeeds with the wrong runtime. An absent or blank report needs to fall back to the repair behavior rather than asserting provenance.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit e696d33 into main Aug 11, 2026
6 of 75 checks passed
@danielhanchen
danielhanchen deleted the amd-installer-repair-loop branch August 11, 2026 19:02
danielhanchen added a commit that referenced this pull request Aug 11, 2026
#8398 landed the same $wmiGpus @() wrap from the same report, so the only
conflict is the comment above an identical line. Took main's, which is the
merged wording and cites #8335.

What is left here on top of main: the second unwrapped if a block down
($gpuNames, still unwrapped on main), the ConfigManagerErrorCode filter in
install.ps1's WMI fallback (still Select-Object -First 1 on main), the private
arch handoff, and the tests.
@aelfwyne

Copy link
Copy Markdown

Does not appear to be fixed, or another similar bug is present. New install on windows 11 machine, R9700 Pro single GPU, not detected.

@danielhanchen

Copy link
Copy Markdown
Member Author

Thanks for reporting this, and you are right that it is not fixed. What you hit is a separate defect from the one this PR closed, which is why the fix did not help you.

The Radeon AI PRO R9700 is Navi 48, gfx1201. The installer infers the gfx arch from the adapter name when no HIP SDK is present, and that table matches RDNA 4 Navi 48 on 9070|9080. "R9700" contains neither, so nothing matches, no arch is inferred, and the install falls back to CPU with the GPU reported as not detected:

AMD Radeon AI PRO R9700  ->  no match
AMD Radeon RX 9070 XT    ->  9070|9080

The same gap is in all six of the name tables (install.ps1, install.sh in two places, studio/setup.ps1, studio/setup.sh, studio/install_python_stack.py). Other R9700 reporters did not hit it because they had a working HIP SDK or amd-smi probe, so the name path never ran.

Fix is on the way and I will link it here. In the meantime this should unblock you, since it skips the inference entirely:

$env:UNSLOTH_ROCM_GFX_ARCH = "gfx1201"

Set that before running the installer. If you would rather it persist, set it as a user environment variable and restart the app.

@danielhanchen

Copy link
Copy Markdown
Member Author

Fix is up as #8573. It adds R9700 to all six name tables (install.ps1, install.sh in two places, studio/setup.ps1, studio/setup.sh, studio/install_python_stack.py), so the card infers gfx1201 without needing the HIP SDK or the env override.

One detail worth recording: the token is R9700 rather than 9700 on purpose. ATI shipped a Radeon 9700 PRO in 2002, and a loose 9700 would hand that card RDNA 4 wheels. "Radeon 9700" does not contain R9700, so the specific token matches the AI PRO and nothing else.

@aelfwyne thanks again for catching this, and for pushing back when I said it was already fixed. It was a separate defect and you were right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] AMD Ryzen AI install bug

4 participants