Repository navigation
fix(amd): gate training GPU selection on the installed torch build's arch coverage - #8791
Conversation
…ls for unslothai#7670 gated llama-server placement on the llama.cpp bundle's built-arch list. Training never sees that gate: prepare_gpu_selection -> auto_select_gpu_ids ranks by free VRAM alone, so on a mixed ROCm host the iGPU stays in the selection, device_map="balanced" shards layers onto it, and the load dies with hipErrorInvalidKernelFile ("CUDA error: invalid kernel file") before the first step. Reported on the unslothai#7669 machine, which still fails there after unslothai#7670 merged. The wheel's own answer is torch.cuda.get_arch_list(), which was not wired into product code anywhere. Compare it against what each device PRESENTS, not its silicon, so HSA_OVERRIDE_GFX_VERSION keeps working: that override exists to make an unsupported card present a supported arch, and it is the standard workaround for this class of problem. Applied once, before the rank and before every fallback: three of the four exits return the whole visible set, which is how both cards reached the child on the reported host. Explicit picks are untouched, matching unslothai#7670. Fails open on a non-ROCm host, an unreadable or non-concrete arch list, a UUID/MIG mask whose ordinals cannot be named back to physical ids, an unreadable device arch, and a filter that would drop every device it could read, since sending a working machine to CPU is worse than the bug. 27 tests, mock-based (no ROCm CI, no AMD hardware here). Each wiring assertion mutation-checked: unfiltering the device list fails the ranked test, unfiltering the fallbacks fails the other two.
…nore ROCR on Windows torch.cuda.get_arch_list() can carry a generic code object (gfx11-generic) next to concrete targets on ROCm 6.4+ wheels. Filtering the generic token out and treating the concrete remainder as the build's whole coverage marks a card the wheel does run as uncovered, so a gfx1100/gfx1101 host loses the gfx1101 to automatic selection. Reject the list whole when any token is non-concrete, the same all-or-nothing rule the llama.cpp gate applies to mapped_targets. _get_parent_visible_gpu_spec also read ROCR_VISIBLE_DEVICES on every ROCm host, but ROCr is Linux-only: a stray value on Windows masks nothing, so taking it as the ordinal->physical map renames one card by another card's id and the gate drops the wrong GPU. Ignore it there, matching the llama.cpp visibility resolver, which never writes ROCR on Windows either.
|
Both P2s were real; fixed in 0a4f2ec, plus main merged in. Non-concrete tokens in ROCR on Windows — also right, and it is |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…n ROCr apply_gpu_ids writes HIP_VISIBLE_DEVICES and deliberately leaves an inherited ROCR_VISIBLE_DEVICES alone, but HIP indexes the agents ROCr already filtered, not the host. So the physical id it writes means a different device: with ROCR_VISIBLE_DEVICES=1,0 and the gate excluding physical GPU 0, auto-selection keeps [1], apply_gpu_ids writes HIP=1, and HIP index 1 of the ROCr list IS physical 0 -- the card just excluded. With ROCR_VISIBLE_DEVICES=2,3 the id is past the agent count and the worker sees no GPU at all, which is the torch.cuda.is_available() failure the old comment here described. Translates the pin to post-ROCr ordinals instead of dropping the ROCr mask. Dropping it would re-expose every agent it hides, including the unsupported one the arch gate exists to keep away from HSA enumeration -- the same reason llama.cpp's _emit_child_gpu_visibility emits post-ROCr ordinals on its prefer_rocr path. Inert unless ROCR_VISIBLE_DEVICES is set, and an identity mask translates to itself, so any host that never set ROCR by hand is byte-identical. Windows is excluded (no ROCr layer, mirroring the mask reads elsewhere), an inherited HIP mask is already ROCr-relative and left alone, and a UUID mask or an id from another space leaves the value untouched. Tests: seven cases on the pin the gate's ids produce, two of which fail without the translation.
…ch-gate # Conflicts: # studio/backend/utils/hardware/hardware.py
… fix-training-gpu-arch-gate
|
Merged main, now up to date. The only conflict was a comment in The open P2 is addressed, on a different line than it is anchored to. Of the two remedies offered I took the second, translate rather than avoid stacking. Driving the exact case from the finding, An identity mask is a no-op, so a host that never set ROCR by hand is unaffected. CI. The three Still unverified on hardware, unchanged from the matrix in the body: the defect needs two AMD GPUs on one board and no runner has that. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e713575328
ℹ️ 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".
… the build Two of the three review findings were real, on the ordinal-to-physical map and on the ROCr translation. The gate paired a torch ordinal with _get_parent_visible_gpu_spec()'s numeric ids, which no longer describe each other once something renumbers them. GPU_DEVICE_ORDINAL reorders at the ROCclr layer and the spec never reads it; a ROCr mask under a HIP/CUDA one leaves the spec naming ROCr's agents while torch counts what survived both. Under ROCR="2,0,1" + CUDA="1,2" that excludes the covered card and keeps the uncovered one, the exact inversion of the fix. Both states already have predicates here, the ones the amd-smi VRAM translation declines on, so the gate now declines on them too. apply_gpu_ids translated a pin to ROCr-relative ordinals on the strength of ROCR_VISIBLE_DEVICES being set. Schedulers export both families of visibility variable, so a Linux NVIDIA node can inherit a ROCR mask that means nothing there, and translating against it moved the CUDA pin to another card. ROCm is now settled from the build (IS_ROCM, else torch.version.hip / __version__) before anything is written, the same stale-mask caution _get_parent_visible_gpu_spec applies to HIP_VISIBLE_DEVICES. The HIP mirror keeps its wider env-var test: writing HIP on a host that turns out to be NVIDIA is inert, where a missed mirror strands a ROCm worker. The third finding, failing the whole probe on any unreadable device arch, is not taken. Skipping one unreadable device leaves that card exactly as eligible as it was before this gate existed; discarding the answer puts the known-uncovered cards back with it and re-breaks the reported host. The docstring did promise the stronger behaviour, so it now says what the code does, and a parametrised test pins the boundary in both spellings. Tests: 45 pass. Each new assertion mutation-checked -- dropping the renumbering guard fails both renumber tests, ungating the translation fails the NVIDIA test, and applying the whole-probe remedy fails both unreadable-device cases.
The review fixes were written on e713575 at 03:04, ten minutes after the branch picked up a main merge on origin at 02:54, so the two diverged. Merging base in rather than rebasing, because a rebase here means a force-push and this PR already has a review thread and a pinned CI history on it. Clean auto-merge. Only hardware.py overlapped and the edits are in different functions.
|
Two of the three are real and fixed in P2 renumbered ordinal mappings: taken. You're right that Both states already had predicates in this module, the ones the amd-smi index translation declines on, so the gate now declines on the same two at P2 gate ROCr translation on a confirmed ROCm backend: taken. Schedulers export both families of visibility variable, so a Linux NVIDIA node can inherit a ROCR mask that means nothing there, and translating against it moved the CUDA pin to a different card. ROCm is now settled from the build at The HIP mirror below it keeps the wider env-var test on purpose. Writing P2 fail open when any device architecture is unreadable: not taken. The remedy costs more than the case it fixes. On your three-GPU host, skipping the unreadable device leaves that card exactly as eligible as it was before this gate existed. Returning an empty set instead puts the known-uncovered card back alongside it, so the reported failure comes back on a host we can positively identify, in order to maybe help one we can't read at all. That trades a certain regression for a speculative fix. Also merged main. The branch had drifted from |
The branch was behind main, so the Python 3.13 red was staleness rather than content: the failures named the OpenAI responses adapter, async singleton access and parallel slot routing, none of which this PR touches. Merging main so the checks mean something. No conflicts.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Comment-only pass over the two files this PR adds to. Comment lines among the PR's added lines go from 211 to 63, a 70 percent reduction. Deleted rather than reworded: docstrings that restated a helper signature or a test name, pointers to other code, development narrative, and measured detail belonging in the PR description. Long narrative docstrings collapse to the constraint they carry. Survivors are correctness constraints the code does not state, issue citations, and the wrong-alternative cases the gate exists to avoid: the ROCr translation example and why clearing the mask is the wrong fix, the build-not-env-var predicate in apply_gpu_ids, the stacked ROCR and CUDA ordinal arithmetic, and the detection fixture that prevents a cross-test IS_ROCM leak. comment_tools.py check --changed --strip-docstrings verifies no code changed. tests/test_training_gpu_arch_gate.py passes, 45 tests.
|
Consolidating my earlier comments on this PR into one summary, and deleting the rest to keep the thread reviewable. Validated on real AMD hardware (gfx1151 Strix Halo)
The selection leg ran against two devices torch genuinely enumerates: Not shown, and it needs hardware: a model actually sharding across two physical AMD GPUs of different architectures. The second device here is the real GPU wearing another number, so memory and compute are shared. Two things I changed on the branch
One open question for you, not more testing
Separately: this PR also rewrites |
torch.cuda.device_count() is frozen at the first torch.cuda call, but
_get_parent_visible_gpu_spec() re-reads the visibility vars on every call. Once
apply_gpu_ids() narrows the mask in a process that has already touched
torch.cuda, the gate sees more ordinals than the mask has ids, and
physical_ids[ordinal] if ordinal < len(physical_ids) else ordinal quietly
switches namespace for the overflow.
With HIP_VISIBLE_DEVICES=2,0 and three live ordinals that names ordinal 2 as
physical 2, which is the covered card sitting at ordinal 0. The gate then
returns {0, 2}, _covered() removes every visible id, and auto_select_gpu_ids
returns [] in fallback_all. An empty list is not "inherit parent visibility",
it is "no GPU", so a working two-card host trains on CPU. Verified on a real
NVIDIA box that device_count() does not follow a later CUDA_VISIBLE_DEVICES
change, so the precondition is reachable rather than theoretical.
Bail out instead when the ordinals outnumber the ids: without a total
ordinal -> id map the probe cannot name anything back, and failing open is what
the rest of this function already does.
Also count the all-uncovered guard in ordinals. It compared len(unsupported),
a set of ids, against a count of devices, so a mask naming one id twice ("0,0")
read two rejected devices as one and let the drop-everything case through.
48 pass, and the three new tests fail with either hunk reverted.
The previous commit bailed out whenever torch reported more ordinals than the visible spec had ids. That is right when a mask is in play, but with no mask at all the ids come from get_physical_gpu_count(), which on ROCm is amd-smi, and amd-smi routinely does not enumerate the integrated GPU. unslothai#8792 is a 7800 XT next to a 7600X iGPU, so the reported host is exactly the one where amd-smi returns 1 while torch sees 2, and bailing there would disable the fix on it. Unmasked there is no renumbering, so ordinal is the physical id by construction and the list can simply be extended. Keep the bail-out for the masked case, where the two really are different namespaces.
An unreadable device is still selectable, so it is not part of "every device is uncovered": bailing out then handed the known-uncovered card back to the picker even though another GPU remained and nothing would have forced CPU. Stop re-translating ids that already went through an inherited CUDA mask. rocclr reads CUDA_VISIBLE_DEVICES as the HIP-layer mask when HIP_VISIBLE_DEVICES is empty (rocclr/device/rocm/rocdevice.cpp:391), so with ROCR_VISIBLE_DEVICES=1,0 and CUDA_VISIBLE_DEVICES=1 the parent had already indexed the ROCr agents once. Translating again resolved to ROCr agent 0, which is the physical GPU the parent hid.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |

Closes #8792.
Problem
PR #7670 gated llama-server placement on the llama.cpp bundle's built-arch list. Training never sees that gate:
prepare_gpu_selection->auto_select_gpu_idsranks by free VRAM alone, so an uncovered iGPU stays in the selection,device_map="balanced"shards layers onto it, and the load dies withhipErrorInvalidKernelFile. Full repro, logs and environment in #8792.mapped_targetscannot answer for torch: it describes a different binary, and the two can cover different archs on the same host. The wheel's own answer istorch.cuda.get_arch_list(), which was not wired into product code anywhere.Fix
New
rocm_gpu_ids_without_torch_kernels()returns the physical ids whose reported arch is outside that list, andauto_select_gpu_idsdrops them before the rank.Applied once, before every exit. Three of the four exits return the whole visible set, so filtering only the ranked path would have left the reported host broken.
Compares what the device presents, not its silicon. Under
HSA_OVERRIDE_GFX_VERSIONan unsupported card presents a supported arch, and that override is the standard workaround for this class of problem, so it has to keep working. Same direction #7670 chose, and pinned by a test here.Explicit picks are untouched, matching #7670: a user pin keeps its own error rather than being quietly relocated.
Fails open on a non-ROCm host, an unreadable or non-concrete arch list, a UUID/MIG mask whose ordinals cannot be named back to physical ids, an unreadable device arch, and a filter that would drop every device it could read. Sending a working machine to CPU is worse than the bug.
Two fixes from review
Non-concrete tokens in
get_arch_list(). Worse on ROCm 6.4+, where a generic code object next to concrete targets is normal, and the case where this PR would otherwise be a silent no-op on exactly the hosts that need it. The list is now rejected whole when any token is non-concrete, the same all-or-nothing rule as_installed_llama_gfx_archs. Three parametrised cases cover generic-first, generic-last and a family label between concrete tokens; without the fix each one drops a gfx1101 the wheel does run.ROCR on Windows.
_get_parent_visible_gpu_specpreferred ROCR on every ROCm host, whilellama_cpp.py:5195and_emit_child_gpu_visibilityboth treat ROCr as Linux-only. Fixed there rather than in this caller, so the gate and the telemetry/pin paths share one answer instead of gaining a third mask reader. It only changes behaviour on Windows with HIP unset and ROCR set.Two more fixed after simulation
Ordinal-to-physical overflow silently changed namespace.
physical_ids[ordinal] if ordinal < len(physical_ids) else ordinalminted overflow ordinals as physical ids that already belong to other devices.torch.cuda.device_count()and_get_parent_visible_gpu_spec()can legitimately disagree: the count is frozen at context init while the spec re-reads the environment live, and before initdevice_count()goes through_device_count_amdsmi(), which does not see the HIP layer at all (withROCR=0,1,2,3andCUDA=0, PyTorch reports 4 where the runtime gives 1).Measured end to end through the real
auto_select_gpu_ids: three torch ordinals,HIP_VISIBLE_DEVICES=2,0, dGPU covered at physical 2. Base selects[2], correctly. This branch returnedids=[] mode=fallback_all, and an empty list is not "inherit", it is "no GPU", so a working two-card host would have trained on CPU. Fixed. The first fix over-corrected by bailing whenever ordinals outnumbered ids, which would have disabled the gate on the reported host, because unmasked the ids come from amd-smi and amd-smi routinely misses the iGPU. The unmasked case now extends the list, where the ordinal is the physical id; only the masked case bails.The all-uncovered guard compared a set against a count.
len(unsupported), a set of ids, was compared withreadable, a count of ordinals, so a mask naming one id twice collapsed the set and let the drop-everything case through.On the
apply_gpu_ids()changeIt is beyond the title, and it is necessary: the gate emits physical ids that flow into
apply_gpu_ids, and under a non-identity ROCr mask the old code wrote a physical id into HIP's ROCr-relative index space. The premise matches rocclr and PyTorch's own comment that ROCR is processed first and reduces the set HIP can select from; Windows and PAL neither reorder nor observe ROCR, hence thewin32guard.Blast radius measured exhaustively: 1152 rows, [Windows, Linux, WSL, Mac] x [NVIDIA, AMD, CPU, no torch] x 12 masks x 4 pins. 81 rows change, all of them ROCm, non-Windows, with a non-identity
ROCR_VISIBLE_DEVICES. Zero change on NVIDIA including stale-ROCR-on-NVIDIA, CPU, Windows, no mask, identity ROCR, HIP set, stacked, UUID, empty and trailing comma.One case is deliberately not byte-identical: single-GPU AMD with
ROCR_VISIBLE_DEVICES=1. Base wroteHIP=1, out of range in a one-agent list, so torch saw no GPU. Head writesHIP=0. The old behaviour was broken and the change fixes it.Open question: the duplicated arch reader
This reads the four
gcnArchNamespellings inline rather than reusingcore/training/worker.py::_rocm_classify_unified_memory, which is the opposite of what I was asked to do in #7670.Correcting my own earlier reasoning here: there are four arch readers, not three (
worker.py:1858, the newhardware.py:4353, plushardware.py:1601andhardware.py:2887), and the import-direction argument does not support keeping them.worker.py:55importsutils.hardwareat module level, so hardware importing worker at module level would be circular, but the refactor moves the function down intohardware.py, which is the acyclic direction.hardware.py:1471already does a deferredfrom core.training.worker import _rocm_classify_unified_memoryon the GPU-inventory path, so the lazy-import cost is already being paid and the move would remove that edge.Consolidating all four is not behaviour-preserving:
hardware.py:2887is a deliberately raw join key for_match_adapter_used_by_luid(#8863) against a Windows driver string, and normalising it changes what joins against what. The right end state is to consolidate the two four-spelling readers and leave the two raw ones with a comment saying why.I still think that belongs in a follow-up rather than here, since this PR already runs 688 insertions into code that just stabilised. Say if you would rather have it in one go.
Note for anyone touching this: only
gcnArchNameexists in upstream PyTorch.gcn_arch_name,arch_nameandgfx_arch_namehave zero hits. On CUDA buildsgcnArchNamealiasesprop.nameand returns something likeNVIDIA B200, so the ROCm-build early return is load-bearing rather than decorative.Tests
49 in
test_training_gpu_arch_gate.py, all mock-based: torch, the arch attributes,get_arch_listand the visibility masks are faked. Covers the reported host shape,HSA_OVERRIDEsurvival, all four arch spellings, the xnack suffix, ordinal-to-physical mapping under a mask, the fail-open corpus, and all four selector exits including a control asserting a fully covered host selects exactly as before. Each wiring assertion is mutation-checked: unfiltering the device list fails the ranked test, unfiltering the fallbacks fails the other two.Hardware coverage
Needs:
rocm,gpu,integrated_gpu,discrete_gpu,multi_gpu_amd,windowshipErrorInvalidKernelFilereproAbout the gfx1151 run
This host has one GPU. Rather than mock
device_count(), the run interposes the HIP runtime withLD_PRELOADsohipGetDeviceCountreports two and phantom ordinals fold onto the real device. torch then enumerates two devices because the C++ runtime does (torch._C._cuda_getDeviceCount() == 2), and the probe allocates a tensor and runs a matmul on both before the gate is asked anything, so a shim that silently failed makes the run inconclusive rather than a pass. A control leg without the shim records that the unshimmed host really has one device.One Python patch remains: the arch string of device 1. The gate compares a device's arch against
get_arch_list(), so with both devices reporting the real gfx1151 neither is uncovered and there is nothing to find. The amd-smi binary is additionally stubbed on the selection leg only, becausehardware.pyenumerates through amd-smi rather than torch; the stub wraps the real amd-smi and duplicates its entry, shaping the copy to win a free-VRAM-only ranking so the base cannot pick the good card by tie-break. The gate leg needs neither.Base has no gate and hands the uncovered device over; head names device 1 uncovered and keeps device 0.
Not covered
windows_get_parent_visible_gpu_specfix only changes behaviour on Windows with HIP unset and ROCR set, and is exercised against mocks onlyHSA_OVERRIDE_GFX_VERSIONon real siliconThe reporter has the affected machine and has tested every previous round.