Repository navigation
Installer: repair stale/CPU-only PyTorch and warn on silent CPU fallback (NVIDIA + AMD, Win/Linux/Mac/WSL) - #5942
Conversation
A Windows machine with an NVIDIA CUDA 13 driver (e.g. RTX 6000 Pro on enterprise
drivers) could get permanently stuck at:
Stale venv detected (torch cpu != required cu130).
[ERROR] The existing Studio environment needs repair.
Re-run install.ps1 so it can replace the environment safely with rollback.
Re-running install.ps1 did not help. install.ps1 installs torch with
"torch>=2.4,<2.11.0" --index-url .../cu130 but no --force-reinstall, so when a
torch==X+cpu is already present uv treats it as satisfying the range (PEP 440
ignores the +cpu/+cuXXX local label) and makes no change -- the CPU wheel is
never replaced. setup.ps1 then rejects the venv as cpu != cu130 and exits, but it
cannot create a venv or install torch, so the loop never resolves. The migrated-
venv branch also preserves existing torch and never reinstalls it.
After the install step, detect the installed torch flavor (cuXXX/cpu/rocm) and,
when it does not match the tag implied by the selected index, force-reinstall the
torch/torchvision/torchaudio triplet from the correct index via three
--reinstall-package flags. No-op on a healthy matching venv; skipped for
--no-torch, ROCm (already --force-reinstalls), and CPU-only machines.
Adds two pure helpers (ConvertTo-TorchFlavorTag, Get-ExpectedTorchFlavorTag), a
PowerShell unit test (tests/studio/test_torch_flavor.ps1), and a CI parse gate for
install.ps1 (previously unparsed).
There was a problem hiding this comment.
Code Review
This pull request introduces helper functions in install.ps1 to detect and enforce that the installed PyTorch flavor matches the expected CUDA build, preventing issues where a stale CPU wheel survives installation. It also adds a unit test suite to verify these helpers. Feedback on the changes highlights a potential hang risk when reading the process's standard output before waiting for its exit, and suggests a safer execution order to ensure the 30-second timeout is respected.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| $proc = [System.Diagnostics.Process]::Start($psi) | ||
| $torchVer = $proc.StandardOutput.ReadToEnd().Trim() | ||
| $finished = $proc.WaitForExit(30000) | ||
| if (-not $finished) { try { $proc.Kill() } catch {} } | ||
| elseif ($proc.ExitCode -eq 0 -and $torchVer) { | ||
| $installedTorchTag = ConvertTo-TorchFlavorTag $torchVer | ||
| } |
There was a problem hiding this comment.
Calling $proc.StandardOutput.ReadToEnd() before $proc.WaitForExit(30000) can cause the installer to hang indefinitely if the Python process hangs (e.g., during import torch due to driver or CUDA lockups). This completely bypasses the 30-second timeout.
Since the output of print(torch.__version__) is extremely small, there is no risk of the process deadlocking due to a full stdout pipe buffer. Therefore, it is much safer to call WaitForExit(30000) first, and only read the output if the process successfully finished within the timeout.
$proc = [System.Diagnostics.Process]::Start($psi)
$finished = $proc.WaitForExit(30000)
if (-not $finished) {
try { $proc.Kill() } catch {}
} else {
$torchVer = $proc.StandardOutput.ReadToEnd().Trim()
if ($proc.ExitCode -eq 0 -and $torchVer) {
$installedTorchTag = ConvertTo-TorchFlavorTag $torchVer
}
}
…all.ps1) install.sh has the same latent bug as the Windows installer: the CUDA torch install uses "torch>=2.4,<2.11.0" --index-url .../cuXXX with no --force-reinstall, so an already-present torch==X+cpu satisfies the version range (PEP 440 ignores the +cpu/+cuXXX local label) and uv leaves it in place. The migrated-venv branch also preserves existing torch. Unlike Windows there is no stale-venv check in setup.sh, so on Linux the symptom is silent CPU training rather than a hard loop -- same root cause. Mirror the install.ps1 fix: after the install block, detect the installed torch flavor (_torch_flavor_tag) and, when it does not match the index tag (_expected_torch_flavor_tag), force-reinstall the torch/torchvision/torchaudio triplet from the selected index via --reinstall-package. No-op on a healthy matching venv; skipped for --no-torch, ROCm (its own repair force-reinstalls), and CPU-only / macOS hosts. Adds tests/sh/test_torch_flavor.sh (run in studio-backend-ci and run_all.sh).
…unfixable) Extend the torch-flavor safety net beyond NVIDIA: - install.sh now auto-repairs a stale CPU torch on standard pytorch.org ROCm indexes too (the rocm-index install path lacked --force-reinstall, unlike the Windows ROCm install). Reuses the rocm-adjusted $TORCH_CONSTRAINT + rocm index, so it pulls the correct ROCm wheels. - Both installers gain a universal post-install warning: when a GPU build was expected (cuXXX / rocm, including the repo.amd.com gfx* arch indexes) but torch is still CPU-only, warn loudly instead of silently training on CPU. This catches the cases auto-repair cannot safely fix (AMD gfx arch indexes that need --find-links, a migrated AMD venv on Windows where the ROCm install was skipped). - Mac / Intel / CPU-only hosts resolve to the cpu index -> expected == installed -> no-op, no false warning. WSL uses install.sh, so the NVIDIA repair + warning apply there. Adds Get-InstalledTorchTag (ps1) and _torch_index_repairable (sh) helpers and extends both unit tests. gfx*/AMD indexes now map to the 'rocm' expected flavor.
Condense the rationale comments added for the stale/CPU PyTorch repair in install.ps1, install.sh and the two helper unit tests; same intent, fewer lines. Comment-only: AST parse of install.ps1/setup.ps1 clean, helper unit tests (15 ps1, 24 sh under bash and dash) and the integration sims (24 ps1, 28 sh) still pass, banner markers the sims slice on are unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9f6a586fb
ℹ️ 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".
| substep "[WARN] PyTorch is CPU-only but a $_expected_torch_tag GPU build was expected for this machine." "$C_WARN" | ||
| substep "[WARN] Training and GPU inference will run on CPU until this is fixed." "$C_WARN" | ||
| substep "[WARN] Re-run this installer, or reinstall the GPU build manually:" "$C_WARN" | ||
| substep "[WARN] uv pip install --python \"$_VENV_PY\" \"$TORCH_CONSTRAINT\" torchvision torchaudio --index-url $TORCH_INDEX_URL --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio" "$C_WARN" |
There was a problem hiding this comment.
Fix the gfx manual reinstall command
When a Linux AMD gfx* index is selected and the venv still contains CPU torch, _torch_index_repairable intentionally skips auto-repair for gfx*, so this warning is the user's recovery path. However, the printed command still uses --index-url $TORCH_INDEX_URL, even though the helper comment says these repo.amd.com gfx* indexes are not plain---index-url reinstallable and need --find-links; following the suggested command leaves the affected AMD/Strix stale-CPU install unrepaired.
Useful? React with 👍 / 👎.
install.ps1: in Get-InstalledTorchTag, call WaitForExit(30000) and drain stdout and stderr asynchronously instead of reading stdout synchronously first, so a hung or noisy "import torch" (a wedged CUDA/driver, the exact failure this PR targets) can no longer block the probe past the timeout. install.sh and install.ps1: treat the repo.amd.com gfx* indexes as plain --index-url reinstallable. They are PEP 503 simple indexes uv resolves in full (torch plus every transitive dep) via --index-url, the same URLs the fresh ROCm install paths already use, so a stale CPU torch on AMD Strix now auto-repairs to the correct ROCm build instead of only warning. install.sh: include */gfx* alongside */rocm* in the bitsandbytes install and ROCm torch repair gates, so a custom UNSLOTH_AMD_ROCM_MIRROR whose path lacks /rocm/ still installs the AMD bitsandbytes build and repairs ROCm torch. tests/sh/test_torch_flavor.sh: gfx indexes now assert repairable, plus a gfx1151 case and an unknown-mirror not-repairable case.
|
@codex review |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces helper functions and logic in both install.ps1 and install.sh to detect and repair mismatched PyTorch installations (such as stale CPU or incorrect CUDA/ROCm builds) relative to the detected GPU environment, accompanied by new unit tests. Feedback is provided for install.ps1 to defensively guard against null or empty values for $PythonExe before calling Test-Path -LiteralPath to prevent potential terminating errors.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| # ProcessStartInfo (not &) so stderr doesn't trip $ErrorActionPreference. | ||
| function Get-InstalledTorchTag { | ||
| param([string]$PythonExe) | ||
| if (-not (Test-Path -LiteralPath $PythonExe)) { return $null } |
There was a problem hiding this comment.
To prevent potential terminating errors under $ErrorActionPreference = 'Stop', defensively guard against null or empty values for $PythonExe before calling Test-Path -LiteralPath. In PowerShell, passing an empty string or null to -LiteralPath throws a binder exception.
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
Make the early return explicit for an empty $PythonExe instead of relying on Test-Path -LiteralPath '' returning false, so the probe stays safe under Set-StrictMode or a future refactor that drops the [string] annotation.
|
@codex review |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces helpers and logic to both the PowerShell (install.ps1) and Bash (install.sh) installers to ensure that the installed PyTorch flavor matches the detected GPU build (CUDA, ROCm, or CPU), preventing silent fallbacks to CPU training. It also adds comprehensive unit tests for these new helper functions. The review feedback suggests improving resource management in PowerShell by properly disposing of the System.Diagnostics.Process object, and enhancing URL parsing robustness in Bash by handling multiple trailing slashes when extracting the index leaf.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
I am having trouble creating individual review comments. Click here to see my feedback.
install.ps1 (1487-1514)
The System.Diagnostics.Process object allocated by [System.Diagnostics.Process]::Start($psi) implements IDisposable and holds system handles. To prevent resource leaks, wrap the process execution in a try/finally block to ensure .Dispose() is called on the process object.
function Get-InstalledTorchTag {
param([string]$PythonExe)
if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
try {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PythonExe
$psi.Arguments = '-c "import torch; print(torch.__version__)"'
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$proc = $null
try {
$proc = [System.Diagnostics.Process]::Start($psi)
# Drain BOTH streams async, then WaitForExit. A synchronous ReadToEnd()
# before the wait would block forever if a wedged "import torch" never
# closes stdout; leaving the redirected stderr undrained would deadlock a
# child that floods it past the pipe buffer. Async reads let a noisy-but-
# exiting probe finish, while a truly hung one still hits the 30s timeout
# and is killed -- bounded either way.
$outTask = $proc.StandardOutput.ReadToEndAsync()
$errTask = $proc.StandardError.ReadToEndAsync()
$finished = $proc.WaitForExit(30000)
if (-not $finished) { try { $proc.Kill() } catch {}; return $null }
$torchVer = $outTask.GetAwaiter().GetResult().Trim()
[void]$errTask.GetAwaiter().GetResult()
if ($proc.ExitCode -ne 0 -or -not $torchVer) { return $null }
return ConvertTo-TorchFlavorTag $torchVer
} finally {
if ($proc) { $proc.Dispose() }
}
} catch { return $null }
}
References
- When a function is designed to return null on failure and the caller handles the null case, an empty catch block is acceptable to prevent graceful fallbacks from turning into terminating errors, especially when ErrorActionPreference is set to Stop.
install.sh (1783-1792)
The current implementation of _expected_torch_flavor_tag uses _u="${1%/}" which only strips a single trailing slash. If the URL contains multiple trailing slashes (e.g., from custom mirrors or proxies), it can fail to parse the leaf correctly. Using a loop to strip all trailing slashes (consistent with how trailing slashes are handled elsewhere in this script) makes the URL parsing robust.
_expected_torch_flavor_tag() {
_u="$1"
while [ "${_u%/}" != "$_u" ]; do
_u="${_u%/}"
done
_leaf="${_u##*/}"
case "$_leaf" in
cu[0-9]*) echo "$_leaf" ;;
cpu) echo "cpu" ;;
rocm*|gfx*) echo "rocm" ;;
*) echo "" ;;
esac
}
install.sh (1799-1806)
Similar to _expected_torch_flavor_tag, _torch_index_repairable only strips a single trailing slash. If the URL contains multiple trailing slashes, it can fail to match the expected leaf. Using a loop to strip all trailing slashes ensures robust parsing.
_torch_index_repairable() {
_u="$1"
while [ "${_u%/}" != "$_u" ]; do
_u="${_u%/}"
done
_leaf="${_u##*/}"
case "$_leaf" in
cu[0-9]*|rocm[0-9]*|gfx*) echo "yes" ;;
*) echo "no" ;;
esac
}
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2550566859
ℹ️ 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".
| run_install_cmd "reinstall PyTorch ($_expected_torch_tag)" uv pip install --python "$_VENV_PY" \ | ||
| "$TORCH_CONSTRAINT" torchvision torchaudio \ | ||
| --index-url "$TORCH_INDEX_URL" \ | ||
| --reinstall-package torch --reinstall-package torchvision --reinstall-package torchaudio |
There was a problem hiding this comment.
Preserve the CPU warning when reinstall fails
On Linux GPU installs with a stale CPU torch, this reinstall is the first command that may actually fetch the GPU wheel; if uv returns non-zero here (for example a transient network/index failure or an unsupported mirror), install.sh is running under set -e and run_install_cmd returns that non-zero status, so the script exits before the safety-net warning below can run. That turns the intended “warn loudly if it can't be reinstalled” path into a hard install failure for the affected venv; capture/retry this command's failure and then re-check/warn instead of letting set -e abort here.
Useful? React with 👍 / 👎.
Summary
On a machine with an NVIDIA CUDA 13 driver (reported on an RTX 6000 Pro with NVIDIA RTX enterprise drivers), Studio install could get permanently stuck:
Re-running
install.ps1as instructed did not help — it looped. This is distinct from the already-fixedcu130 != cu126UMD-regex bug (#5827, #5861): heresetup.ps1correctly computesrequired cu130, but the venv holds a stale CPU torch that the installer never replaces.Root cause
The installer installs torch with no
--force-reinstall:Per PEP 440, a public version range ignores a candidate's local label, so an already-installed
torch==2.10.0+cpusatisfiestorch>=2.4,<2.11.0. uv therefore reportsWould make no changes/Checked N packageseven with--index-url .../cu130, and the CPU wheel is never replaced. The migrated-venv branch also preserves existing torch and never reinstalls it.setup.ps1detectstorch cpu != required cu130and exits, but it cannot create a venv or install torch, so its "re-run install.ps1" advice hits the same no-op → an unrecoverable loop.install.shhas the identical torch command and migrated-branch behavior, butsetup.shhas no stale-venv check, so the symptom is silent CPU training rather than a hard loop. Same root cause.The ROCm path already uses
--force-reinstall; CPU-only / macOS /--no-torchare unaffected; a fresh install is already correct. Only a pre-existing CPU torch traps the machine.What this changes
Both installers gain a torch-flavor invariant. After the install step, detect the installed torch flavor and, when it does not match the tag implied by the selected index, force-reinstall the
torch/torchvision/torchaudiotriplet from the correct index via--reinstall-package.install.ps1: adds pure helpersConvertTo-TorchFlavorTag(parsestorch.__version__→cuXXX/rocm/cpu; untagged →cpu) andGet-ExpectedTorchFlavorTag(index-URL leaf → tag;$nullfor an unrecognized leaf so it safely no-ops on oddUNSLOTH_PYTORCH_MIRROR), plus the repair block (reads the version with the sameProcessStartInfoprobesetup.ps1uses).install.sh: mirrors it with_torch_flavor_tag/_expected_torch_flavor_tagand the same repair, for Linux/Mac parity.import torch, no reinstall, no download) and on--no-torch/ CPU-only / macOS hosts (expected == installed).Cross-platform coverage (AMD / Intel / WSL / Mac)
The safety net is now universal — every GPU host either gets the right build or a loud warning, and non-GPU hosts are untouched:
cputorch → correctcuXXXbuildpytorch.org/whl/rocmX.Yinstall lacked--force-reinstall; the Windows ROCm install already had it)gfx*index--index-url-reinstallable (needs--find-links); a stalecpuis warned loudlycputorch is warnedinstall.sh→ same NVIDIA repair + warningcpu== installedcpu→ no-op, no false warningThe universal warning fires only when a GPU build was expected (
cuXXX/rocm) but torch is stillcpuafter install/repair, so Mac/Intel/CPU (expectedcpu) and--no-torchnever trigger it. New helpers:Get-InstalledTorchTag(ps1),_torch_index_repairable(sh);gfx*/AMD indexes map to therocmexpected flavor.Tests / CI:
tests/studio/test_torch_flavor.ps1andtests/sh/test_torch_flavor.sh: unit tests for the helpers (AST/extraction; no GPU/venv).studio-windows-inference-smoke.ymlnow also parse-checksinstall.ps1(previously unparsed) and runs the ps1 test;studio-backend-ci.yml+run_all.shrun the sh test.Validation (this PR was simulated extensively on Linux)
torch==2.9.0+cpuvenv + the OLD command → no-op (Checked 3 packages, torch stays+cpu); + the NEW--reinstall-packagecommand →torch 2.10.0+cu130,torchvision 0.25.0+cu130,torchaudio 2.11.0+cu130,torch.version.cuda == 13.0. cu128→cu130 swap and healthy-cu130 no-op also confirmed.install.ps1/install.shand drive every scenario with a stubbed venv-python (that updates after a mocked reinstall) and a call-recordinguv: 24/24 (ps1) and 28/28 (sh) — covering CPU, CUDA, cu128→cu130, AMD standard-ROCm auto-repair, AMDgfx-index warning, ROCm-migrated warning, "no warning after a successful repair",--no-torch, custom mirror, unrecognized-leaf skip, nightly/untagged wheels, trailing slash, broken/empty torch, and the failure path.pwshparse ofinstall.ps1/setup.ps1andbash -n install.shclean.test_cross_platform_parity.py+test_tokenizers_and_torch_constraint.pygreen (noTORCH_CONSTRAINTvar added;Get-TorchIndexUrl/get_torch_index_urlthresholds and--torch-backend=auto-only-in-fallback untouched).Not a browser change (the installer scripts are unaffected by the Studio web UI), so no cross-browser surface here.
Behavior before vs after
PyTorch flavor mismatch (installed cpu, need cu130) -- reinstalling...), then setup proceeds. Healthy installs, CPU/macOS, ROCm, and--no-torchare unchanged (no-op).Note (separate, pre-existing)
The installer's existing torch command resolves
torch 2.10.0+cu130withtorchaudio 2.11.0+cu130(torchaudio is unconstrained while torch is capped<2.11). A fresh run of the original command resolves identically, so this version skew predates and is independent of this change — flagged here as a possible separate follow-up (constrain torchaudio/torchvision), not addressed in this PR.Workaround for affected users (until this ships)
then re-run the installer.