Skip to content

fix: prevent ROCm torch from installing on NVIDIA Linux hosts - #6174

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
LeoBorcherding:rocm-torch-installs-on-nvidia
Jun 11, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
LeoBorcherding:rocm-torch-installs-on-nvidia

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #6172: on Linux Mint 22.2 (and similar) with an RTX 4070 Super,
the installer replaced correctly-installed CUDA torch with ROCm wheels,
causing CUBLAS_STATUS_NOT_INITIALIZED at runtime.

Root cause: NVIDIA's open kernel module (driver 560+) registers GPU
topology nodes in the KFD sysfs hierarchy with non-zero gpu_id values.
Both _has_amd_rocm_gpu() (install.sh) and _has_rocm_gpu()
(install_python_stack.py) used gpu_id != 0 as the sole proof of an AMD
GPU. On an NVIDIA-only host with the open driver, this falsely triggered
the ROCm install path.

Changes

  • install.sh _has_amd_rocm_gpu sysfs fallback: awk script now
    also requires vendor_id 4098 (AMD 0x1002) in the node's properties
    file. NVIDIA KFD nodes carry vendor_id 4318 (0x10DE) and are skipped.

  • install_python_stack.py _has_rocm_gpu sysfs fallback: same
    vendor_id guard. Falls back to trusting gpu_id alone on older kernels
    that don't expose a properties file.

  • UNSLOTH_TORCH_BACKEND env var: install.sh now exports
    cuda/rocm/cpu after resolving TORCH_INDEX_URL.
    _ensure_rocm_torch() reads this and exits immediately on cuda/cpu
    hosts — a second layer of defense independent of subprocess GPU detection.

Test plan

  • 9 new tests in test_rocm_support.py covering all three changes
  • Full test_rocm_support.py suite: 289 passed, 2 skipped, 0 failed
  • Verify on an NVIDIA Linux system that unsloth studio update no
    longer installs ROCm torch
  • Verify on an AMD ROCm Linux system that ROCm torch install is
    unaffected (vendor_id 4098 passes the check)

NVIDIA's open kernel module (driver 560+) registers GPU topology nodes in
the KFD sysfs hierarchy with non-zero gpu_id values. The _has_amd_rocm_gpu
(install.sh) and _has_rocm_gpu (install_python_stack.py) sysfs fallbacks
previously treated any non-zero gpu_id as proof of an AMD GPU, so an
NVIDIA-only host with the open kernel driver was misrouted to the ROCm
install path, replacing the correctly-installed CUDA torch with ROCm wheels.

Fixes:

1. install.sh _has_amd_rocm_gpu sysfs fallback: require vendor_id 4098
   (AMD 0x1002) in the KFD node properties file before declaring an AMD
   GPU present. NVIDIA KFD nodes carry vendor_id 4318 (0x10DE) and are
   now skipped.

2. install_python_stack.py _has_rocm_gpu sysfs fallback: same vendor_id
   guard. Also preserves the existing fallback for older kernels that
   don't ship a properties file (trusts gpu_id alone there).

3. install.sh now exports UNSLOTH_TORCH_BACKEND ("cuda"/"rocm"/"cpu")
   immediately after get_torch_index_url() resolves the wheel family.
   install_python_stack.py reads this as _TORCH_BACKEND and short-circuits
   _ensure_rocm_torch() entirely on cuda/cpu hosts, providing a second
   layer of defense that is independent of subprocess GPU detection.

Tests: 9 new cases in TestHasRocmGpuKfdVendorGuard,
TestEnsureRocmTorch, and TestInstallShStructure cover all three changes.
Full test_rocm_support.py suite: 289 passed, 2 skipped, 0 failed.

Closes unslothai#6172
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@LeoBorcherding LeoBorcherding mentioned this pull request Jun 10, 2026
The 'ROCm torch check' and 'ROCm torch (final)' step labels were
hardcoded regardless of whether the installer was targeting CUDA, ROCm,
or CPU. On NVIDIA hosts they showed 'ROCm' even though no ROCm wheels
were being installed, which was misleading.

Add _torch_step_label(suffix) which reads UNSLOTH_TORCH_BACKEND (set by
install.sh) and formats the label as e.g. 'torch check (cuda)' or
'torch final (rocm)'. Falls back to live GPU detection for standalone
studio update runs that bypass install.sh.

@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: 01e3adb836

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread install.sh Outdated
Comment on lines +1729 to +1730
awk '/gpu_id/{ gpu=($2+0>0) } /vendor_id/{ amd=($2==4098) } \
gpu && amd { found=1 } END{ exit !found }' \

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 Reset KFD vendor state per topology node

On NVIDIA-open systems with multiple KFD nodes, this awk keeps gpu and amd set across every */properties file in the glob. If node 0 is a CPU/AMD node with gpu_id 0 and vendor_id 4098, then a later NVIDIA node can set gpu on its gpu_id line while amd is still true from the previous file, so _has_amd_rocm_gpu returns success before it ever sees that node's vendor_id 4318. That preserves the original misrouting on common Ryzen+NVIDIA hosts; reset state on FNR==1 or check each properties file independently.

Useful? React with 👍 / 👎.

LeoBorcherding and others added 3 commits June 10, 2026 18:43
…s file

The previous implementation fell through to `return True` when the KFD
node's properties file was missing (OSError), intending to support older
kernels. But NVIDIA open driver KFD nodes can also lack a properties file
on some kernel versions, so the fallback still produced a false positive.

Change the `except OSError: pass` to `continue` so any node without a
readable properties file is skipped rather than trusted. KFD properties
files exist on every kernel version that actually exposes /sys/class/kfd,
so this does not regress real AMD GPU detection -- if the directory exists
at all, properties files will be present for genuine GPU nodes.
Four changes that together ensure ROCm torch can never be installed on an
NVIDIA host regardless of which detection path fires:

1. _has_rocm_gpu() (Python): NVIDIA guard at the top -- returns False
   immediately when _has_usable_nvidia_gpu() is True, blocking rocminfo,
   amd-smi, and KFD sysfs from producing a false positive even when ROCm
   tools are co-installed alongside the NVIDIA driver.

2. _has_amd_rocm_gpu() (install.sh): same NVIDIA guard -- calls
   _has_usable_nvidia_gpu first and returns 1 if it succeeds.

3. _has_usable_nvidia_gpu() (Python): adds /proc/driver/nvidia/gpus/
   sysfs fallback. The NVIDIA driver populates this directory on Linux
   regardless of nvidia-smi state, so a subprocess PATH gap, timeout, or
   driver initialisation race can no longer silence NVIDIA detection.

4. _has_usable_nvidia_gpu() (install.sh): same /proc/driver/nvidia/gpus
   fallback, tried after nvidia-smi -L rather than instead of it.

Together: NVIDIA wins at every decision point. If nvidia-smi works, it
confirms NVIDIA. If it fails, /proc/driver/nvidia confirms NVIDIA. If
somehow both fail, _has_rocm_gpu still checks NVIDIA first before any AMD
path runs.

@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: fcd95c93e8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread install.sh
Comment on lines +1767 to +1769
if [ -d /proc/driver/nvidia/gpus ] && \
[ -n "$(ls -A /proc/driver/nvidia/gpus 2>/dev/null)" ]; then
return 0

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 Handle proc-only NVIDIA before selecting CPU wheels

When nvidia-smi is not on PATH (and not /usr/bin) but the driver exposes /proc/driver/nvidia/gpus, this fallback makes _has_usable_nvidia_gpu return success. In get_torch_index_url, however, _smi is still empty because it is populated only from nvidia-smi, so the code enters the “No NVIDIA GPU” branch; the new NVIDIA guard in _has_amd_rocm_gpu then returns false and the installer selects the CPU index. This silently downgrades proc-detected NVIDIA hosts instead of installing CUDA wheels, so either the CUDA-selection path needs to handle the proc-only case or this fallback should not be treated as a usable NVIDIA GPU there.

Useful? React with 👍 / 👎.

@Erland366

Erland366 commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

I did test the changes and it is working properly.

I able to reproduce the problem before which looks like this :
image

Then it's fixed but there's a bug on the UI (it shows ROCm even though it's CUDA) Which confirmed if we see the .venv directly
image

Then finally the last commit fix that :
image

LeoBorcherding and others added 2 commits June 10, 2026 21:14
1. KFD awk state not reset per node file (Ryzen+NVIDIA false positive):
   The awk glob processes all topology node properties files in one pass.
   Without FNR==1 reset, a Ryzen+NVIDIA host where an AMD CPU-agent node
   sets amd=1 (vendor_id 4098, gpu_id 0) can combine with a later NVIDIA
   node setting gpu=1 (gpu_id > 0), triggering found=1 before vendor_id
   4318 is seen. Added FNR==1{ gpu=0; amd=0 } to reset per file.

2. proc-only NVIDIA not reaching CUDA wheel selection:
   _has_usable_nvidia_gpu returning true via /proc/driver/nvidia fallback
   left _smi empty, so get_torch_index_url entered the AMD/CPU branch and
   selected CPU wheels despite NVIDIA being confirmed. Introduced
   _nvidia_detected flag (separate from _smi) so the AMD branch is skipped
   whenever NVIDIA is confirmed by any path, while _cuda_ver reads from
   _smi when available (with the existing cu126 fallback when _smi is absent).

@danielhanchen danielhanchen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified the fix end to end: reproduced the KFD gpu_id false positive from #6172 against main with synthetic sysfs fixtures (bash and Python paths), confirmed the vendor_id 4098 guard, the /proc/driver/nvidia/gpus fallback, and the UNSLOTH_TORCH_BACKEND handoff each independently block the misroute. Full OS x GPU matrix simulations (Linux, WSL, macOS, Windows x NVIDIA, AMD, CPU, mixed) show identical behavior to main on all previously working pathways. Chat UI Test failures are pre-existing on main and unrelated to this installer change.

@danielhanchen
danielhanchen merged commit bf2cd74 into unslothai:main Jun 11, 2026
31 of 35 checks passed
danielhanchen added a commit that referenced this pull request Jun 11, 2026
…, llama.cpp routing, probe bounds) (#6183)

* Installer: harden GPU detection follow-ups after #6174

Ports the NVIDIA-priority and /proc/driver/nvidia/gpus hardening from #6174
to the remaining pathways and adds recovery for already-poisoned venvs:

- install_python_stack.py: add _ensure_cuda_torch so 'unsloth studio update'
  force-reinstalls CUDA torch when the venv carries a ROCm build on an NVIDIA
  Linux host (the pre-#6174 poisoning signature). Honors UNSLOTH_TORCH_BACKEND,
  UNSLOTH_ROCM_TORCH_INSTALLED, and CUDA_VISIBLE_DEVICES=-1/'' opt-outs; never
  touches healthy CUDA, deliberate CPU wheels, macOS, or Windows.
- install_llama_prebuilt.py: detect_host gains the /proc NVIDIA fallback and
  skips ROCm probes when NVIDIA is usable; forwarded --rocm-gfx/--has-rocm
  overrides still win.
- setup.sh: GPU summary classifies NVIDIA first through a timeout-bounded
  probe with the /proc fallback; AMD probes are bounded and gain a KFD
  vendor_id 4098 fallback; the llama.cpp source build only selects
  GGML_CUDA/GGML_HIP when the matching GPU is actually detected.
- install.sh: bound both nvidia-smi calls with a 10s timeout (no behavior
  change when healthy or when the timeout binary is absent); classify the
  exported UNSLOTH_TORCH_BACKEND on the final index path segment so custom
  mirrors containing 'rocm'/'gfx' in their base path are not mislabeled.
- install.ps1 + setup.ps1: NVIDIA probes now require a real 'GPU N:' row from
  nvidia-smi -L under a 10s bound instead of bare exit code 0; later CUDA
  version and compute_cap queries are bounded too.

Tests: 3 new test files (50+ tests), suite at 788 passed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix Resolve-CudaToolkit driver probe for extracted-function unit test

tests/studio/test_resolve_cuda_toolkit.ps1 extracts Resolve-CudaToolkit alone
into a child pwsh and stubs nvidia-smi with a .ps1 script. The bounded runner
is not in scope there (and ProcessStartInfo cannot dispatch .ps1 stubs), so
the DriverMaxCuda parse silently returned nothing and the major-mismatch
scenarios failed. Fall back to direct invocation when Invoke-NvidiaSmiBounded
is unavailable; production setup.ps1 always has it defined and keeps the
10s bound.

* Treat CUDA_VISIBLE_DEVICES empty or -1 as hidden in NVIDIA-first guards

The NVIDIA-first guards added in this branch only special-cased
CUDA_VISIBLE_DEVICES=-1 at two setup.sh gates and ignored the empty-string
form entirely, while the Python detector (install_llama_prebuilt.py)
already treats both as hidden. On a mixed AMD+NVIDIA host steered to the
AMD card via CUDA_VISIBLE_DEVICES, the guards suppressed the AMD probes,
so setup.sh fell to a CPU llama.cpp build and install.sh picked CUDA
wheels instead of ROCm.

Move the policy into the helpers so every consumer agrees:

- install.sh: new _cvd_hides_nvidia checked first in _has_usable_nvidia_gpu
- studio/setup.sh: same via _setup_cvd_hides_nvidia; the two ad-hoc
  CUDA_VISIBLE_DEVICES=-1 gate conditions are now redundant and removed
- studio/install_python_stack.py: _has_usable_nvidia_gpu returns False
  when CUDA_VISIBLE_DEVICES is set to  or -1 (whitespace tolerated)

Tests: 5 new sh scenarios (hidden via , -1, padded -1, visible device,
and mixed host with hidden NVIDIA restoring the ROCm route) plus a pytest
class covering all three implementations behaviourally.

Addresses the review comment on the NVIDIA-first setup.sh block.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Retrigger CI after PyPI 503 outage during the previous run

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

Broken installer

3 participants