Skip to content

Studio: reconcile AMD GPU reporting with installed PyTorch - #8606

Closed
oobabooga wants to merge 35 commits into
unslothai:mainfrom
oobabooga:worktree-amd-torch-probe
Closed

oobabooga wants to merge 35 commits into
unslothai:mainfrom
oobabooga:worktree-amd-torch-probe

Conversation

@oobabooga

@oobabooga oobabooga commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Summary

On Linux AMD systems, Studio could report a healthy ROCm GPU while its venv contained a CPU or CUDA build of PyTorch. The dependency fast path then kept that wheel indefinitely, leaving training unavailable even though setup printed dependencies up to date.

The GPU name could also be wrong because rocminfo lists the CPU first and the installer used the first Marketing Name it found.

Changes

  • Run AMD and NVIDIA detection before the dependency fast path.
  • Reinstall PyTorch through the existing ROCm path when an AMD GPU has a non-ROCm wheel.
  • Warn when the GPU is visible to ROCm but torch.cuda.is_available() is false. The probe is bounded so a broken HIP runtime cannot hang setup.
  • Read the marketing name from a gfx agent, with the existing APU fallback when no gfx agent is present.
  • Respect GGUF-only installs and explicit non-ROCm or custom torch index pins.

Before:

gpu            AMD ROCm (gfx1201)
               GPU: AMD Ryzen 9 9950X 16-Core Processor

After, when PyTorch cannot use the GPU:

gpu            AMD ROCm (gfx1201, PyTorch cannot use it)
               GPU: AMD Radeon AI PRO R9700

Chat and GGUF inference continue to work through llama.cpp. This PR does not change the Live monitor wording or persist the detected gfx architecture.

Testing

  • Added AMD reconciliation coverage for GPU names, wheel families, pins, GPU precedence, and missing torch.
  • Extended the existing fast-path shell suite.
  • 2,706 passed, 121 skipped across tests/studio/install/, tests/python/test_cross_platform_parity.py, tests/python/test_windows_no_torch_setup.py and tests/studio/test_cli_hsa_spoof_launch_7331.py.
  • All 49 suites in tests/sh/ pass.
  • The install suite gives the same result with UNSLOTH_TORCH_BACKEND set to cpu, cuda or xpu and with UNSLOTH_NO_TORCH=1, which is what an installer shell exports.
  • bash -n install.sh
  • bash -n studio/setup.sh
  • git diff --check

Related: #8473, #7307, #7275, #7485.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 0184f2c618

ℹ️ 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.sh
Comment on lines +2015 to +2017
if "$VENV_DIR/bin/python" -c \
'import importlib.util,sys; sys.exit(0 if importlib.util.find_spec("torch") else 1)' \
>/dev/null 2>&1; then

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 Skip the torch health probe in no-torch mode

When an AMD installation is converted to GGUF-only mode but retains a torch package from the prior installation, this existence check still runs the new health diagnostic. A stale CPU wheel then produces the kernel-driver/group-membership warning, while a usable ROCm wheel reports a healthy PyTorch GPU, even though UNSLOTH_NO_TORCH or the persisted manifest intentionally disables the training stack. Fresh evidence here is that the new summary probe ignores the same no-torch state now honored by reconciliation; gate this probe and its messaging on that recorded mode.

Useful? React with 👍 / 👎.

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.

Declining this one. setup.sh has no notion of no-torch mode anywhere today, so this would mean introducing a manifest read into the shell purely to suppress a message, and only on an install that was converted to GGUF-only and still carries a wheel from before. Worth doing as its own change rather than inside this branch.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, and sorry for the long review. The two bugs you are fixing are both real and both worth fixing: the fast path really does keep a CPU or CUDA wheel on an AMD host indefinitely while printing dependencies up to date, and the GPU name really is the CPU's, because rocminfo lists the CPU agent first. #8473 and #7307 are the reports.

I reviewed this on three fronts: the detection rewrite, the reinstall trigger, and the Windows manifest inference. There is no AMD hardware on any runner or on my box, so everything below is fixture-driven or driven against the real code with stubs, and I have said which is which. Nothing here is a claim about observed AMD behaviour.

Ground truth used rather than recollection: rocminfo.cc from ROCm/rocminfo, rocdevice.cpp from ROCm/clr, and the amd-smi CLI formatter executed in process.

Blockers

1. An unimportable torch reads as "not ROCm", so the repair never converges

_probe_rocm_torch returns (False, "") on OSError, TimeoutExpired, or any non-zero exit, and the ROCm marker test requires returncode == 0. So a torch that segfaults or hangs on import is classified as a wrong wheel rather than a broken one, and reinstall = not has_rocm_torch fires.

Driven against the real CLI with a stub torch package, a fake rocminfo on PATH and a fake ROCM_PATH:

stub torch/__init__.py exit
os.abort() 0 (repair)
raise RuntimeError("libamdhip64 missing") 0 (repair)
time.sleep(600), 90s timeout fires 0 (repair)
healthy 2.7.0+rocm6.3 3 (no action)

Exit 0 sets _SKIP_PYTHON_DEPS=false, which reaches _ensure_rocm_torch and a --force-reinstall --no-cache-dir pass. Nothing is persisted about the attempt, so if the reinstalled wheel still fails to import, the next studio update downloads it again, and the next. gfx1151 (#7331) is exactly that shape.

The failure mode I care about more: run() does sys.exit(result.returncode) and setup.sh runs under set -euo pipefail. If the reinstall itself fails, and the interesting case is a proxy that allows PyPI but blocks download.pytorch.org or repo.amd.com, then unsloth studio update goes from succeeding to aborting on every invocation. That is the "needs repair" fixed point from #5942, #7275 and #8335 re-entering through a new door, and #8398 only just closed the last one.

test_missing_or_corrupt_torch_import_forces_the_pass asserts this as intended, so it will not be caught by reading the tests.

Suggestion: record the attempted plan (index, wheel state, timestamp) in the manifest and refuse to repeat an identical plan that did not help.

2. A deliberate CPU or CUDA wheel is overwritten, because the pin guards read environment variables that are gone by update time

The only "the user chose otherwise" guards are _TORCH_BACKEND in {"cuda", "cpu", "xpu"} and _explicit_unknown_family_torch_index_url(), and both read the environment. write_manifest() persists schema, completed_at_ms, requirement_files and no_torch, and no index URL or backend field, and this PR does not add one.

Measured on a fake AMD host with a stub torch 2.9.0+cpu:

CPU torch on AMD host, no env                       rc=0   repair
  + UNSLOTH_TORCH_BACKEND=cpu                       rc=3
  + UNSLOTH_TORCH_INDEX_URL=.../whl/cpu             rc=3
  + UNSLOTH_NO_TORCH=1                              rc=3
CUDA torch 2.9.0+cu128 on AMD host, no env          rc=0   repair

So the GGUF-only half of the PR description holds and is durable, because no_torch is in the manifest. The pin half does not: it holds only if the user re-exports the variable on every update. Someone who ran UNSLOTH_TORCH_INDEX_URL=.../whl/cpu ./install.sh on a Radeon box for llama.cpp work, then later runs plain unsloth studio update, gets several GB of ROCm torch installed over a deliberate choice.

Suggestion: persist the resolved index URL and backend at install time and consult those here, the way no_torch already is.

3. CUDA_VISIBLE_DEVICES="" or -1 collapses NVIDIA precedence

The ordering is right: _has_usable_nvidia_gpu() runs before _has_rocm_gpu(), and _has_rocm_gpu short circuits on NVIDIA again. But _has_usable_nvidia_gpu returns False early on "" and -1, before the /proc/driver/nvidia/gpus fallback runs.

Reproduced on a real multi-GPU NVIDIA host, with a fake rocminfo on PATH and a stub CPU torch:

CUDA_VISIBLE_DEVICES unset -> rc=3
CUDA_VISIBLE_DEVICES=""    -> rc=0
CUDA_VISIBLE_DEVICES=-1    -> rc=0

-1 is the common "run this on CPU" idiom. On an AMD-CPU-with-iGPU plus NVIDIA dGPU box, which is a very ordinary machine, one stray environment variable turns studio update into "replace my working CUDA torch with ROCm torch".

4. The marketing-name fallback still returns the CPU's name

This is the one I would most want fixed, because it is the PR's own headline case. In _setup_rocminfo_gpu_records, if (mkt != "" && first == "") first = mkt latches the first Marketing Name in the stream, and the PR's premise is that the CPU agent comes first. So when a GPU agent carries no gfx token, the |name fallback can only ever emit the processor string.

Running your helper verbatim against an APU fixture whose GPU agent is Name: AMD Radeon Graphics / Marketing Name: AMD Radeon 780M Graphics:

|AMD Ryzen 9 9950X 16-Core Processor

On a host where ROCm is installed but the GPU is not enumerated, which is the ordinary missing-render-group state, install.sh then infers an arch from that CPU string and advises a UNSLOTH_ROCM_GFX_ARCH based on it:

STEP[gpu] AMD ROCm (gfx1103)
  sub: GPU: AMD Ryzen 9 7940HS w/ Radeon 780M Graphics

test_apu_without_a_gfx_agent_keeps_the_processor_name covers a fixture with no GPU agent at all, so it does not exercise this, and its CPU string is one where inferring an iGPU arch happens to be right.

Suggestion: only latch first from an agent that is not the CPU agent, since rocminfo prints Vendor Name: CPU, or drop the fallback.

Worth fixing before merge

Empty mask semantics are inverted. setup.sh treats HIP_VISIBLE_DEVICES="" as hiding every device and tells the user so. In clr Device::init() the filter is skipped entirely when the mask is empty, and an empty HIP_VISIBLE_DEVICES falls through to CUDA_VISIBLE_DEVICES, while the shell precedence chain stops at the first variable that is set. -1 is classified correctly. The message only fires when torch.cuda.is_available() is already False, so the cost is a misdiagnosis that sends the user after the wrong thing instead of the driver and render-group advice on the next branch.

A UUID token selects device 0. case "$_setup_first" in ''|*[!0-9]*) leaves the index at 0 for any non-integer, and the ROCR escape hatch does not cover the HIP or CUDA masks. clr does resolve GPU- prefixed tokens for those masks too, not only for ROCR_VISIBLE_DEVICES. Failing open would be safer than defaulting to 0.

The probe runs before the ROCm probe environment is seeded. The probe is invoked around line 1660, but export HSA_ENABLE_DXG_DETECTION and the /opt/rocm/bin PATH append are about 120 lines later. On WSL2 ROCDXG the probe therefore sees no AMD GPU and declines to repair, and the summary immediately after, with the variable set, prints that PyTorch cannot use the GPU. The two halves disagree about the same machine. Hoisting the export and the PATH append above the probe fixes it.

Unsupported iGPUs are repaired into a wheel that cannot run. _has_rocm_gpu matches any gfx[1-9]... with no allowlist. Measured with a CPU torch: gfx1103, gfx90c, gfx1036 and gfx803 all return rc=0. The first three are already in this file's own _SHADOWING_INTEGRATED_GFX set. HIP has no family fallback, so an exact-arch gate here would demote nothing that currently works. A host with no readable ROCm version does bail correctly, so this is the iGPU laptop with distro ROCm packages installed, not the bare one.

awk -F': ' truncates on an embedded ": ". Marketing Name: AMD Instinct MI300X OAM: 750W SKU yields gfx942|AMD Instinct MI300X OAM. Your sibling helper _setup_amd_smi_marketing_records already uses sub(/^[^:]*:[[:space:]]*/, "", value) and survives it. Worth making the two consistent. I could not find a shipping name that contains ": ", so this is robustness rather than a live failure.

The amd-smi path indexes two lists that can differ in length. The gfx source there is still a bare grep -oE while the names come from the ordinal-safe emitter, so a GPU missing TARGET_GRAPHICS_VERSION skews one list and not the other, pairing GPU1's arch with GPU0's name. Narrow trigger, since a whole-GPU ASIC failure blanks the name too. Separately, amd-smi list emits only BDF, UUID and KFD ids and no gfx token, so that first gfx probe looks dead.

"Keep in sync" has drifted. The three awk bodies are byte identical, but the callers are not: install.sh has none of the _setup_amd_hidden logic, sets _gpu_probe_kind=rocminfo on a different condition, gates the amd-smi name records differently, and calls rocminfo unbounded where setup.sh wraps it in a timeout.

On the Windows manifest inference

I want to flag that the population this protects is very small. The new branch only fires on a manifest with no no_torch key, and write_manifest omits that key only when the caller passes None, which production never does. The key landed 3 hours 57 minutes after the manifest itself, on main only. The first wheel that ships install_manifest.py at all already has the key, and installers take studio/ from the wheel. So this is developers or CI who ran a local install inside a four-hour window.

Against that, the misfire states are the ordinary shapes of a broken torch install: pip uninstall torch, which is the most common advice given to AMD users fighting a bad ROCm wheel and so is this PR's own audience; an upgrade that dies after pip removed the old distribution; AV deleting files under site-packages\torch; a hand rmdir before a clean reinstall.

Two structural points:

The inference is a one way latch. Once it returns true, Set-PersistedNoTorch writes the marker and UNSLOTH_NO_TORCH=true is exported, so the next write_manifest burns "no_torch": true in. The evidence is replaced by an explicit record and no update recovers it. The escape is a reinstall, and this is wired into _fail_if_install_damaged, which is the "some installed files are damaged, reinstall over the top" path, and which prepends UNSLOTH_NO_TORCH=1 to the command it prints when recorded_no_torch() is true. So the remedy for a torch whose files went missing becomes a reinstall without torch.

The two implementations disagree on the same manifest. Driving both over identical fixtures, 4 of 7 cases differ. PowerShell tests only for non-null where Python requires isinstance(..., int) and isinstance(..., dict), $payload.schema -eq 1 coerces so the string "1" passes on Windows only, and PowerShell has no counterpart to Python's "no_torch" not in manifest guard, so an explicit "no_torch": null reads as GGUF-only on Windows and unknown on POSIX. Both are live on Windows: setup.ps1 decides for the setup run and install_manifest.py decides for the damaged-install hint.

There is also no announcement on POSIX. setup.sh has no occurrence of no_torch, so Linux and macOS get the same mode switch through _infer_no_torch() without the yellow line Windows users at least see.

If you keep it: make it non latching, so a run that reached no-torch by inference does not write "no_torch": true; exclude the damaged-install call site so it honours only an explicit record; and align the two predicates.

What I checked that came back clean

  • The gfx regex change. Tested both forms over 42 tokens. Old and new agree on every real ISA name including gfx90a, gfx90c, gfx803 and the four digit forms, and both reject the generic targets. The only divergence is qualifier suffixed gfx90a:sramecc+:xnack-, and rejecting it is correct, because rocminfo's ISA line prints exactly that and the old unanchored grep counted it as a second device. This is a real improvement.
  • Ordinal alignment for rocminfo. Held under a CPU agent first, two GPUs, two identical GPUs, an empty Marketing Name, a missing Marketing Name line, and ENABLE_CACHE_DUMP builds that emit extra Name: lines for caches.
  • NVIDIA precedence ordering itself, aside from the CUDA_VISIBLE_DEVICES hole above. A fake nvidia-smi exiting 6 with "No devices were found" still yields rc=3, because the /proc fallback holds.
  • The HSA_OVERRIDE_GFX_VERSION clearing. I tried hard to break this and could not. The spoofable set is Strix only and it requires independent KFD gfx_target_version corroboration, so the classic gfx1030 override on an unsupported card, which is how a lot of people get ROCm working at all, is structurally unreachable from the clear path. Good.
  • Manifest write order. The manifest is written last, strictly after torch, and any existing one is dropped up front, so there is no window where a complete manifest coexists with a not yet installed torch. A run whose torch install failed writes "no_torch": false, which the new branch ignores.
  • Schema compatibility. write_manifest is unchanged and no new fields are emitted, so an older Studio reading a new manifest sees what it already understood.
  • Offline. The probe cannot fire with no network, because it sits inside the branch where the PyPI version matched, so an offline run takes the existing "could not reach PyPI" path exactly as before.
  • The probe has no install side effects, never returns 0 on an internal error, and a missing sibling module yields rc=1, which keeps the fast path.
  • No --system-site-packages anywhere in the installers, so torch cannot legitimately live outside the venv.

One process note: the added tests are shallow on the structural half of the predicate. Mutating each of the three completeness guards individually, on both the PowerShell and Python sides, leaves every test passing, because no fixture holds two of the three fields. Deleting the two Windows patterns from _has_torch_install_artifact also leaves everything green, and that branch is what governs the damaged-install hint on Windows. The happy path and the artifact discriminators are genuinely covered.

Also worth running tests/python/test_windows_no_torch_setup.py under Windows PowerShell 5.1 before merge. The $null -ne (Get-ChildItem ... | Select-Object -First 1) shape is exactly the kind that has behaved differently on 5.1 in this repo before, and pwsh 7 on Linux cannot reproduce it.

Overlap with #8620

Heads up that #8620 adds the same "PyTorch cannot see the announced GPU" diagnostic. The two branches merge with no textual conflict, which is the awkward case, because the merged setup.sh then emits the warning twice for one condition, and mine would fire right after yours had already triggered a repair.

Your Linux side is the better answer, since repairing beats reporting and the GPU name fix is a bug I had not addressed. I will cut #8620 down to its Windows half, which this PR does not cover, plus the XPU suppression that keeps a working Intel host from being falsely accused. No action needed on your side.

@danielhanchen

Copy link
Copy Markdown
Member

Two corrections to my review above, both mine, and one of them is unfair to you.

1. The Windows manifest section describes code you had already removed. I fetched the diff while d881c6300 was head, posted at 01:07 UTC, and did not re-fetch. 0184f2c61 landed at 00:55, eleven minutes before I posted, and it reverted that block: Get-PersistedNoTorch at your current head is byte-identical to the merge base, and the comment you left there now says the opposite of what I argued against, that missing package contents cannot establish the previous mode because they also describe a damaged install. Same for install_manifest.recorded_no_torch, which is a docstring change only.

Measured at 0184f2c61:

manifest state recorded_no_torch
legacy, structurally complete, no no_torch key None
{"no_torch": true} True
{"no_torch": false} False
no manifest None
.unsloth-no-torch marker only True

No latch, nothing written back, nothing wired into the damaged-install hint. Please disregard that whole section. You had already reached the right answer on your own.

2. "studio update goes from succeeding to aborting every time" is wrong at this head. Your rc gate at setup.sh:1676-1697 maps the probe status explicitly, and it holds under set -euo pipefail. Driven across eight statuses:

probe exit 0 1 2 3 4 5 124 137
deps forced yes no no no no yes no no
shell survives yes yes yes yes yes yes yes yes

Separating the HSA clear (4) from the install (0), with 5 for both, is also exactly right, and it answers the coupling concern I raised.

The abort risk did not vanish, it moved: once a repair is triggered, pip_install reaches run(), which does sys.exit(result.returncode) at install_python_stack.py:3581. On a host where PyPI is reachable through a proxy but download.pytorch.org is not, the newly reachable repair makes studio update fail every time. That is a consequence of the false positives below rather than of the gate.

What I still think is live, all re-derived at 0184f2c61 by driving the real CLI in a scratch venv with a stub torch and fake rocminfo / nvidia-smi on PATH, exit codes as observed (0 repair, 3 no action, 4 clear override):

Masked NVIDIA, install_python_stack.py:1441-1443:

CUDA_VISIBLE_DEVICES unset  -> 3
CUDA_VISIBLE_DEVICES=""     -> 0   plan: whl/rocm6.4, install_torch=true
CUDA_VISIBLE_DEVICES=-1     -> 0
no nvidia-smi, no /proc/driver/nvidia (container, trimmed unit) -> 0

That last one needs no env var at all, and it is the ordinary shape of a container. The early return concedes the host before the /proc/driver/nvidia/gpus fallback runs, so a working CUDA install is force-reinstalled with ROCm and the machine ends up with neither.

Torch that does not answer, _probe_rocm_torch at :2839-2858:

import raises OSError -> 0      import calls os.abort() -> 0
import hangs          -> 0 after 90.2s      healthy +rocm6.4 -> 3

"Did not answer" is being read as "is not ROCm". Nothing records that a repair was attempted, so where the reinstall does not take, this recurs on every update. The 90 second cell is its own cost on the path that exists to be fast.

Unsupported arches, where the repair installs a wheel that cannot run:

gfx803 (RX 580) -> 0        gfx1103 (780M) -> 0

_has_rocm_gpu()'s gfx[1-9][0-9a-z]{2,3} accepts both. PYTORCH_ROCM_ARCH for stable wheels through 2.10 has no gfx1103 (it is nightly-only) and no gfx803, and rocBLAS 4.0.0 for ROCm 6.0 removed gfx803 device code outright. Three of gfx90c / gfx1035 / gfx1036 / gfx1103 are already in this file's own _SHADOWING_INTEGRATED_GFX. Note the repair is idempotent here but permanently wrong: the reinstalled wheel is +rocm, so the probe reports the machine healthy forever.

Deliberate non-ROCm wheels. Worth narrowing what I said before: a ROCm pin is durable, because the installed wheel carries +rocm and short-circuits the reinstall, and an unknown-family verbatim pin is respected. The non-durable set is exactly the cpu / cuda / xpu intents, whose only record is an env var that is gone by studio update time. A +cpu or +cu128 local label is sitting in site-packages/torch/version.py, and setup.sh already parses that file for the XPU escape; consulting it would veto these without an import.

One new finding. setup.sh exports HSA_ENABLE_DXG_DETECTION=1 and appends /opt/rocm/bin to PATH at line 1782, but the probe runs at line 1664. On a WSL2 ROCDXG host the probe therefore runs before the runtime has what it needs to enumerate, and I observed it resolve https://repo.amd.com/rocm/whl/gfx1151/ with the reason "gfx1151 inferred while the ROCm runtime is not visible", i.e. a per-arch wheel chosen from a /proc/cpuinfo product string the runtime never corroborated. Hoisting those two lines above the probe block fixes it.

The marketing-name fallback, which I can now give you the exact reachability path for rather than just the symptom. The rocminfo branch is skipped when _setup_gfx_all is empty, the amd-smi branch does reset _setup_amd_records="", but the /dev/kfd branch at setup.sh:1900-1904 sets only _setup_amd_detected and _setup_amd_probe_kind and leaves the stale CPU record in place. The selection block at :1918 then reads the CPU name out of it:

records: [|AMD Ryzen 9 9950X 16-Core Processor]
_setup_gfx = []
_setup_mkt = [AMD Ryzen 9 9950X 16-Core Processor]

install.sh:4348-4368 carries the identical awk. Gating the fallback on the agent's Vendor Name: not being CPU fixes both.

Also worth a line in the PR description, not a defect: _is_pip_rocm_family_leaf moved from ^gfx\d to a closed allowlist, and repo.amd.com/rocm/whl/ also publishes gfx110X-dgpu, gfx90X-dcgpu, gfx94X-dcgpu, gfx950-dcgpu, gfx103X-dgpu and gfx1153. Anyone pinned to one of those is reclassified from "ROCm family" to "custom verbatim pin". Their install still works, but the reclassification is invisible otherwise.

And the part I would sign off on as-is: the HSA_OVERRIDE_GFX_VERSION clear. I tried hard to break it. It only fires when a Strix arch is inferred from the product name and KFD sysfs or an override-free re-probe corroborates, so the load-bearing gfx1030 override on RDNA2 and the 11.0.0 override on a 780M both correctly return 3, not 4. That is the case that makes a lot of people's ROCm work at all, and you guarded it.

Both bugs you set out to fix are real, and the name bug in particular was one nobody else had pinned down. I am taking the remaining items on directly rather than leaving them with you.

The fast-path probe classifies a torch that segfaults, raises or hangs on import
as a wrong wheel rather than a broken one, so the repair re-arms on every
`studio update` and force-reinstalls several GB that cannot help. Under
setup.sh's `set -euo pipefail` a repair that cannot reach download.pytorch.org
turns a succeeding update into a guaranteed abort.

- _probe_rocm_torch reports importability separately from the ROCm marker.
- Record the attempted repair (index plus observed torch state, hashed) beside
  the no-torch marker, before running it, and refuse to repeat an identical one.
  The key covers the observed state, so a repair that changed anything is never
  blocked, and convergence clears the record.
- Persist an explicit UNSLOTH_TORCH_INDEX_URL / _FAMILY pin in the install
  manifest and consult it, so a deliberate CPU or CUDA index on an AMD host
  survives an update that does not re-export the variable. The autodetected
  UNSLOTH_TORCH_BACKEND is deliberately not persisted.
- Split NVIDIA presence from NVIDIA visibility: a CUDA_VISIBLE_DEVICES mask no
  longer authorises replacing a working CUDA torch on a host that owns an NVIDIA
  card. The mask's routing role from unslothai#6183 is unchanged.
- rocminfo lists the CPU agent first, so the marketing-name fallback preferred
  the processor even when a GPU agent was present (unslothai#7307). Classify the agent
  before latching, and read field values past the first colon so a name
  containing ": " is not truncated. Both copies stay byte identical.
- Seed HSA_ENABLE_DXG_DETECTION and the /opt/rocm/bin PATH append above the
  probe, so the repairing half and the reporting half judge the same hardware.
@danielhanchen

Copy link
Copy Markdown
Member

I pushed the fixes for the four blockers directly to your branch rather than leaving you a list to work through, since maintainer_can_modify was on. New head is 40d27cb8d. Everything below is fixture-driven or driven against the real code with stubs, same as the review: there is still no AMD hardware on any runner or on my box.

Your two diagnoses were both right and both worth the PR. The fast path really does keep a CPU or CUDA wheel on an AMD host indefinitely while printing dependencies up to date, and the GPU line really was the processor, because rocminfo lists the CPU agent first. Those are #8473 and #7307 and they are fixed here. What follows is repair work on top of your design, not a rewrite of it.

Corrections to my own review first

Blocker 3 was not your bug and I should not have filed it against this PR. The CUDA_VISIBLE_DEVICES early return in _has_usable_nvidia_gpu landed in #6183 (2026-06-11), long before your branch, and it is deliberate: on a mixed AMD plus NVIDIA host steered to the AMD card with CUDA_VISIBLE_DEVICES=-1, the installer is supposed to pick ROCm wheels. It is pinned in both directions by TestHiddenCvdNotUsable, test_hidden_nvidia_restores_rocm_detection, and cases 34 to 38 in tests/sh/test_get_torch_index_url.sh. Ripping it out would have reversed a tested policy inside someone else's PR, so I did not.

What your PR does change is the blast radius: detection now runs before the fast path, so that policy can force-reinstall on every update instead of only during a dependency pass. So I fixed the destructive half only. NVIDIA presence and NVIDIA visibility are now separate probes, and a mask no longer authorises replacing a working CUDA torch on a host that owns an NVIDIA card. The routing behaviour from #6183 is untouched: a CPU wheel, a ROCm wheel or a broken torch on that same host is still repaired exactly as before.

Blocker 2, I persisted less than I proposed. I suggested recording the resolved index URL and the backend. Recording the backend turns out to be unsafe: install.sh:4054-4056 invents UNSLOTH_TORCH_BACKEND from GPU autodetection, so a cpu verdict from a GPU-less install would be frozen into the manifest and would outlive the user adding a GPU. Only UNSLOTH_TORCH_INDEX_URL / _FAMILY is unambiguously the user's, so only that is recorded, and only when explicitly set. install.sh:2071-2072 forwards those two and never invents them, which is what makes them safe to trust.

What changed

1. An unimportable torch no longer re-arms the repair forever. _probe_rocm_torch now reports importability separately from the ROCm marker, so a torch that aborts, raises or times out is classified as broken rather than as the wrong wheel. The attempted repair is fingerprinted (index URL plus the observed torch state, hashed because a pinned index can carry credentials) and recorded next to the no-torch marker, written before the install runs so an attempt that dies mid-pip is still remembered. An identical plan against an identical state is refused with a diagnostic instead of repeated. The key includes the observed state, so any repair that actually changed something is never blocked, and convergence clears the record. The ledger sits outside the manifest for the same reason .unsloth-no-torch does: the manifest is dropped before the very pass that performs the repair.

This also closes the set -euo pipefail case, which was the part I cared about most: a proxy that reaches PyPI but not download.pytorch.org previously turned unsloth studio update from succeeding into aborting on every invocation, permanently.

2. A deliberate CPU or CUDA pin survives an update. write_manifest gains an additive torch_index_url key, read back the way no_torch already is. Absent still means unknown, never "no choice". An env pin on the current run always wins over the recorded one.

3. The marketing-name fallback can no longer name the CPU. This was your headline bug and the fix still contained it. Marketing Name is now held until the agent is classified, and a non-CPU agent's name is preferred; the CPU's name is used only when no other agent offered one, which keeps test_apu_without_a_gfx_agent_keeps_the_processor_name and the arch inference that depends on it working. Classification accepts either Vendor Name or Device Type, whichever lands first, since both follow Marketing Name in the stream. Verified against ROCr rather than recollection: amd_cpu_agent.cpp:218 hardcodes Vendor Name: CPU and amd_gpu_agent.cpp:1337 hardcodes AMD, and rocminfo.cc:604-607 fixes the field order.

While in there I also took the awk -F': ' truncation you and I both flagged: field values are now read past the first colon only, so AMD Instinct MI300X OAM: 750W SKU survives. Both copies stay byte identical and there is now a test asserting that, since previously only behaviour kept them honest.

4. The repair half and the reporting half now see the same machine. HSA_ENABLE_DXG_DETECTION and the /opt/rocm/bin PATH append moved above the reconciliation probe. On WSL2 ROCDXG the probe previously ran about 120 lines before that export and declined to repair, while the summary immediately after, with the variable set, reported that PyTorch could not use the GPU.

Verification

23 new tests, all in your test_amd_gpu_torch_reconciliation.py, plus an autouse fixture in tests/studio/install/conftest.py that keeps the new repair ledger out of sys.prefix. That fixture is not cosmetic: without it _ensure_rocm_torch writes into the interpreter prefix during a test run and the next run of unrelated tests sees a repair as already attempted, which is exactly how it bit me first time.

Counts, run serially:

  • tests/studio/install/: 1966 passed, 2 skipped
  • tests/studio/install/ plus tests/python/: 3032 passed, 91 skipped, 1 failed
  • tests/sh/: all pass
  • The one failure is test_tokenizers_and_torch_constraint.py::TestE2ETokenizersFix::test_negative_control_no_tokenizers, which I confirmed fails identically on a clean checkout of 0184f2c61. Pre-existing and unrelated.

Because a test that cannot fail is not coverage, I mutated the source to revert each claimed behaviour and confirmed the tests caught it, both directions on every guard. 24 mutations, 24 killed, 0 survivors. Two survived the first pass and both were informative: one showed an importability term in the CUDA guard was redundant, since a CUDA local tag is only readable from a torch that imported, so I removed it rather than keep an untestable condition; the other was a malformed mutation of mine, not a weak test.

The awk helper was also run under gawk, mawk and busybox awk, since arm order and function support are the kind of thing that only breaks on the shell nobody develops on.

Left alone deliberately

The unsupported-iGPU allowlist (gfx1103, gfx90c, gfx1036, gfx803 all still return rc=0), the amd-smi ordinal mismatch, and the Windows manifest inference. The first two want their own change with their own tests, and the third protects a population small enough that I would rather discuss it than quietly rewrite it in your branch. None of them are regressions from this PR.

Everything I listed as clean in the review is still clean and I did not touch any of it: the anchored gfx regex, rocminfo ordinal alignment, the HSA_OVERRIDE_GFX_VERSION clearing, manifest write order, and the offline path.

Please do look over the diff, especially the repair-ledger semantics, since that is the piece that decides when Studio stops trying. If you would rather own any of it differently, say so and I will back it out. As I mentioned, I will cut #8620 down to its Windows half so the two do not both emit the same warning.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A suppressed repeat repair was reported as a satisfied wheel, so _ensure_rocm_torch
cleared the repair ledger and the next update re-armed the same multi-gigabyte
reinstall, and a confirmed HSA override was removed even though the per-architecture
wheel it stands in for was never installed. Both now travel as an explicit blocked
plan.

Also carry the recorded torch index pin across the dependency pass that drops the
manifest, store it without index credentials, and apply the confirmed HSA override
clear in the setup shell after a forced pass, not only on the fast path.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
main gained the shared torch classification (unslothai#8779). It rewrote the same
Linux ROCm block this branch moved into _linux_rocm_torch_plan(), so the
two conflict textually while wanting the same thing.

Kept this branch's plan structure and carried unslothai#8779 into it rather than
either side wholesale:

- _probe_rocm_torch() reads _probe_torch_runtime() instead of spawning
  its own interpreter. Its four values are a subset of the shared five,
  and a private probe would restore both the extra "import torch" and
  the extra independent 90s timeout on exactly the wedged-driver host
  this path exists to rescue.
- The classification parity guard from unslothai#8779 fired on the move, which is
  what it is for. Re-checked the equivalence against the same reference
  implementation and retargeted it at _probe_rocm_torch, where the
  derivation now lives, rather than assuming it across the rename.
- The fast-path source guard now asserts the bounded import where it
  moved to, and additionally fails if the fast path ever spawns its own
  subprocess again.
- Probe mocks feed the shared marked line and drop the memo first.

tests/studio/install: 2687 passed, 2 skipped. Both retargeted guards were
mutation-tested: breaking the marker derivation fails 4 parity cases, and
reintroducing a private subprocess fails 3 reconciliation cases.
@danielhanchen

Copy link
Copy Markdown
Member

Merged main and resolved the conflict, pushed as b3142a91a.

The conflict is with #8779, which landed the shared torch classification. It rewrote the same Linux ROCm block this branch moved into _linux_rocm_torch_plan(), so the two collide textually while wanting the same thing.

I kept this branch's plan structure and carried #8779 into it, rather than taking either side wholesale. The part worth flagging: _probe_rocm_torch() now reads _probe_torch_runtime() instead of spawning its own interpreter. Its four values are a subset of the shared five, and keeping the private probe would have restored both the extra import torch and a second independent 90s timeout, on exactly the stalled-driver host this path exists to rescue.

#8779's classification parity guard fired on the move, which is what it is for. I re-checked the equivalence against the same reference implementation it cites and retargeted it at _probe_rocm_torch, rather than assuming it across the rename. The fast-path source guard now also fails if that path ever spawns its own subprocess again.

tests/studio/install: 2687 passed, 2 skipped. Both retargeted guards were mutation-tested: breaking the marker derivation fails 4 parity cases, and reintroducing a private subprocess fails 3 reconciliation cases.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

ℹ️ 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 on lines +3530 to 3533
_repaired_is_rocm, _, _, _ = _probe_rocm_torch()
if _repaired_is_rocm:
install_manifest.clear_rocm_repair_attempt()
rocm_torch_ready = True

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 a non-ROCm repair result marked unready

When pip_install exits successfully but the selected index or mirror supplies a non-HIP torch wheel, the new re-probe correctly leaves the repair ledger in place, but this assignment still marks the environment ROCm-ready. The branches below then install AMD bitsandbytes—or perform the gfx906 bitsandbytes cleanup—against the CPU/CUDA wheel that the probe just rejected. Set readiness from _repaired_is_rocm so a semantically failed repair does not trigger ROCm-only package changes.

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.

Not taking this one.

That assignment is main's behavior, not something this branch introduces. On origin/main (cb8e206) install_python_stack.py sets rocm_torch_ready = True unconditionally at the end of the generic install (line 3245), and the gfx906 bitsandbytes cleanup (:3251) and the AMD bitsandbytes install (:3273) read that same flag. What this PR adds after pip_install is the re-probe, and only to settle the repair ledger.

The change would also lose a case the repair exists for. _probe_rocm_torch reports has_rocm False both for a wrong wheel and for a torch that cannot be imported at all, and a wedged HIP runtime is the host this path was written to rescue. Reading readiness off _repaired_is_rocm there would skip the AMD bitsandbytes install on a venv that just received the correct ROCm wheels.

That leaves the case you name: a leaf _is_pip_rocm_family_leaf accepts, served by a mirror that publishes non-HIP wheels. Pairing the AMD bitsandbytes wheel with an already-wrong torch there is not worth a branch that breaks the unimportable-torch host.

Comment on lines +36 to +38
@pytest.fixture(autouse = True)
def _isolate_torch_routing_env(monkeypatch):
"""Run every install test against an unset routing environment.

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 Clear no-torch mode before test-module import

When the test runner exports UNSLOTH_NO_TORCH=1, install_python_stack.py computes its module-level NO_TORCH while test modules are collected, before this autouse fixture can sanitize the environment. The new _linux_rocm_torch_plan then returns immediately in existing direct _ensure_rocm_torch tests; in this environment the targeted install suite regresses from passing at the parent commit to 26 failures. Clear this variable before test-module imports or explicitly reset the imported modules' NO_TORCH state in the fixture.

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.

Fixed in a43dda9. tests/studio/install/conftest.py now pops UNSLOTH_NO_TORCH at module scope and recomputes install_python_stack.NO_TORCH, since a whole-tree run can already have imported the module from another directory before this conftest loads. The per-test fixture cannot reach it, exactly as you describe: NO_TORCH is read once during collection.

install_python_stack reads the variable once at module scope into NO_TORCH, so for a
test module the value is frozen during collection, before any fixture can run. A shell
that exports it (install.sh does) then returns every routing plan early and the suite
fails on the environment rather than on the code: 45 failures against 3 on Ubuntu 24.04.

Popped in the conftest rather than added to _ROUTING_ENV_VARS, because a per-test
fixture cannot undo an import-time read. The constant is recomputed as well, since a
whole-tree run collects other directories first and may already have imported it.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Merged main, and took the conftest finding.

UNSLOTH_NO_TORCH can't be handled by the per-test fixture. install_python_stack reads it into NO_TORCH at module scope, which for a test module is collection time, before any fixture runs, so a shell that exports it (install.sh does) returns every routing plan early and the suite fails on the environment instead of the code. It also wasn't in _ROUTING_ENV_VARS. Now popped in the conftest, with the constant recomputed in case a whole-tree run imported the module first.

Measured on Ubuntu 24.04, tests/studio/install:

UNSLOTH_NO_TORCH=1, before:  45 failed, 2522 passed
UNSLOTH_NO_TORCH=1, after:    3 failed, 2564 passed
clean env, before and after:  3 failed, 2564 passed

Diffing the failure sets rather than the counts: 42 eliminated, 0 introduced. The 3 survivors are test_managed_node_runtime and they fail on main too. tests/sh is 43 of 48 here against 42 of 48 on main, same 6 failures on both.

I did not take the rocm_torch_ready one. I tried it, and setting readiness from _repaired_is_rocm breaks 5 existing tests. test_probe_timeout_triggers_reinstall is the one that convinced me: a probe that times out returns False for the ROCm marker, so that version reads "did not answer" as "is not ROCm" and skips bitsandbytes on a host whose repair actually worked. That's the distinction you added importability to make, and I'd rather not guess at what readiness means on a broken-probe host inside your ledger. Codex's underlying point still stands, it just needs both flags.

Main merge is 181 commits, 737 files, no conflicts.

Also worth knowing for merge order: this branch and the Windows one don't conflict, so a merge won't flag anything, but the merged setup.sh warns twice for the same condition, at line 2453 and again at 2759. Cleanest fix is landing this one first and trimming the other to its Windows and XPU half.

@oobabooga @danielhanchen probably best if you both review the findings above before this goes anywhere, particularly the one I declined.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 2106bae141

ℹ️ 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

Copy link
Copy Markdown
Member

Confirmed the first Marketing Name from rocminfo is still the CPU agent in install.sh, and nothing on the update path checks the venv torch against the GPU it just announced, so this is worth fixing. The direction is right, but the branch also narrows the ROCm index leaf test to a fixed family allowlist and adds the reinstall fingerprint, so could you split those out?

@LeoBorcherding could you take a look at this one?

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@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: 2106bae141

ℹ️ 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 on lines +35 to +45
_ROUTING_ENV_VARS = (
"UNSLOTH_ROCM_GFX_ARCH",
"HSA_OVERRIDE_GFX_VERSION",
"HIP_VISIBLE_DEVICES",
"CUDA_VISIBLE_DEVICES",
"UNSLOTH_ROCM_TORCH_INSTALLED",
"ROCM_PATH",
# install.sh exports this, so a suite run from an installer shell would assert the
# fresh-install branch of the recorded-pin guards instead of the update one.
"UNSLOTH_INSTALLER_RESOLVED_TORCH_INDEX",
)

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 Clear the module-level torch backend before collection

When UNSLOTH_TORCH_BACKEND=cpu, cuda, or xpu is exported in the test environment, install_python_stack.py captures it in _TORCH_BACKEND during collection, before this autouse fixture runs, and this routing-variable list neither clears the environment value nor recomputes the module constant. I verified that UNSLOTH_TORCH_BACKEND=cpu python -m pytest -q tests/studio/install/test_rocm_support.py tests/studio/install/test_cuda_repair.py tests/studio/install/test_gpu_detection_followups.py produces 28 routing failures because the ROCm helpers return early. Sanitize this module-level variable before test imports and reset _TORCH_BACKEND, as is already done for NO_TORCH above.

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.

Reproduced. Before the fix, UNSLOTH_TORCH_BACKEND=cpu took tests/studio/install/test_rocm_support.py, test_cuda_repair.py and test_gpu_detection_followups.py from 617 passed to 28 failed. The sensitivity is not introduced here (the merge base fdf83cb fails 27 of them the same way), but the isolation fixture this branch adds is what is meant to cover this class, and install.sh exports the variable next to UNSLOTH_NO_TORCH.

Fixed in b324496. The derivation moved into _infer_torch_backend() so the conftest can recompute the constant the way it already does for NO_TORCH, rather than forcing it to "": UNSLOTH_TORCH_INDEX_URL and UNSLOTH_TORCH_INDEX_FAMILY still feed it and those are deliberately left set. Those three files now give 618 passed, 16 skipped under cpu, cuda and xpu alike, and a regression test asserts both module constants match a recompute from the sanitized environment.

The same commit points TestTorchBackendDerivationFromPin at _infer_torch_backend() instead of its own copy of the derivation, which had already drifted: the copy was missing the xpu arm.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 21, 2026
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: b93d5849b4

ℹ️ 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".

@oobabooga

Copy link
Copy Markdown
Member Author

I'm closing this PR in favor of the following two, which fix the same issues with less code and more robustly:

#9498
#9499

@oobabooga oobabooga closed this Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants