Skip to content

fix(amd): gate ROCm GPU selection and crash recovery on the build's arch coverage - #7670

Merged
danielhanchen merged 49 commits into
unslothai:mainfrom
LeoBorcherding:fix-7624-gpu-arch-gate
Aug 13, 2026
Merged

danielhanchen merged 49 commits into
unslothai:mainfrom
LeoBorcherding:fix-7624-gpu-arch-gate

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

On multi-device ROCm hosts, Unsloth Studio picks the GPU with the most free memory. An iGPU reports shared system RAM as free memory, so it can outrank the dGPU. llama-server then gets pinned to a device the build has no kernels for and dies with ROCm error: device kernel image is invalid (exit 3221226505), surfaced as a misleading "check the GGUF / memory" error.

Two confirmed cases: #7624 (R9700 + iGPU, custom-linked official HIP build) and #7669 (RX 7700 XT gfx1101 + Raphael iGPU gfx1036, Studio-installed gfx110X prebuilt). Both fixed by hiding the iGPU manually.

Fix

Layer 1, proactive (prebuilt installs). published_rocm_choice_for_host already matches the host against the manifest's concrete mapped_targets. It now records gfx_target + mapped_targets into UNSLOTH_PREBUILT_INFO.json, and the ROCm path of _get_gpu_memory() drops devices whose gfx arch is not covered before the free-memory rank. Closes #7669.

Layer 2, reactive (any build). Custom-linked builds (UNSLOTH_LOCAL_LLAMA_CPP_DIR, #7624's setup) have no manifest, so layer 1 fails open there. New rung in the load ladder: when llama-server dies with a HIP kernel-image error on an auto-placed launch, respawn once on a narrowed device set. Both spellings count, case-folded: hipErrorInvalidImage ("device kernel image is invalid", what both field logs show) and hipErrorNoBinaryForGpu, whose own documented cause is code compiled for a different GPU arch. _arch_crash_retry_gpu_ids prefers the enumerated devices the crashed launch never touched; when the launch already used all of them, it drops the unified-memory devices instead, which is where this mismatch keeps landing. Runs before the flash-attn retry: the crash is deterministic, and FA/fit retries cannot help (both field logs show four identical crashes). Closes #7624.

Knowing a supported device exists is not enough on a mixed host. The child enumerates every ROCm agent, and that HSA enumeration is what dies, so wherever nothing else pins the child the gate's survivors are masked in (_arch_gate_survivors):

  • --fit on and manual full-GPU tensor-split launches, which leave gpu_indices unset and so sit outside layer 2's reach.
  • The RAG embedding llama-server: same binary, same devices, same crash.
  • Every card uncovered: the child is masked onto the CPU instead of being left to enumerate and abort.

Placement changes carry their launch state with them. Narrowing off an APU withdraws GGML_CUDA_ENABLE_UNIFIED_MEMORY, but only when this launch set it. Narrowing to one card drops --split-mode tensor and clears tensor_parallel, which the UI reports and the MTP watchdog arms. A --tensor-split sized for the old device count is dropped, since the shares are positional over the visible set. The APU RAM preflight is re-asked for the set the child will actually see, so a surviving discrete card is not refused a model that fits it.

Everything unknown fails open: source builds, pre-existing installs (no mapped_targets recorded, deliberately kept out of the install fingerprint so existing installs stay valid), non-ROCm bundles, non-concrete mapped_targets (a generic code object or family label matches no device and would otherwise drop every GPU), unreadable device arch, a UUID/MIG visibility mask whose ids cannot be named back to the child, and Vulkan (pins via --device). The sentence-transformers embedding picker keeps the unfiltered probe: a device this llama.cpp build lacks kernels for is usually still a fine PyTorch device. An explicit pick in Studio's GPU picker is left alone and keeps its own clear error.

Tests

254 tests across three new files, passing locally and in Backend CI:

  • test_gpu_arch_gate_7624.py (78): marker parsing, the gate inside _get_gpu_memory, the crash markers, the retry's device choice, the fail-open paths.
  • test_gpu_arch_gate_consumers_7624.py (73): which callers opt in, the embed server's pin and its CPU path, _resolve_auto staying unfiltered.
  • test_gpu_arch_gate_os_matrix_7624.py (103): OS x GPU-vendor matrix, mask composition, forced-CPU, survivor pinning, env handoff.

Plus six in existing suites: install-fingerprint stability, arch fields surviving a marker rewrite, non-ROCm bundles recording nothing, and ROCR mask retention on the CPU pin.

No hardware validation is claimed. There is no ROCm CI in the repo, so all of this is mock-based. Both reporters confirmed the equivalent manual mask fixes the crash; layer 1 automates that selection and layer 2 recovers when the mask cannot be predicted.

Also covered

The iGPU/HIP half of #7307. Layer 1 drops the Ryzen iGPU on the Studio-installed rocm-gfx120X bundle, which records ["gfx1200", "gfx1201"]; the marker-less source-build path in that report reaches layer 2's unified-memory narrowing wherever the driver reports the iGPU as integrated. The RDNA4 prebuilt segfault in the same issue is a separate problem.

Out of scope

Note

@danielhanchen carried the review items and the follow-on hardening on this branch; the original commits and authorship are intact.

LeoBorcherding and others added 6 commits July 30, 2026 18:57
… built archs (unslothai#7624)

The free-memory rank could pick a device the installed llama.cpp binary has
no kernels for (e.g. an iGPU reporting shared system RAM outranking the
dGPU), crashing llama-server with 'device kernel image is invalid'.

- install_llama_prebuilt: record gfx_target + mapped_targets in
  UNSLOTH_PREBUILT_INFO.json for published ROCm bundles
- llama_cpp: drop devices whose gcnArchName is not in the recorded list
  before ranking; unknown coverage or unknown device arch fails open
…nel image is invalid' crash (unslothai#7624)

Custom-linked llama.cpp builds have no mapped_targets manifest, so the
proactive arch gate cannot see them. Catch ROCm's arch-mismatch crash on
an auto-pinned device and respawn once with that device excluded, letting
an arch-compatible sibling (e.g. the dGPU next to an unsupported iGPU)
take the load. Explicit user device picks keep their error.
- _installed_llama_gfx_archs now reads the install marker via
  llama_cpp_freshness.read_install_marker (walks up from the resolved
  binary), replacing a hand-rolled root list that missed custom studio
  homes and duplicated the freshness util
- extract _rocm_arch_by_physical_id from _amd_apu_wants_unified_memory
  and share it with the enumeration gate instead of a second inline
  gcnArchName loop
@LeoBorcherding LeoBorcherding self-assigned this Jul 31, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

🌊 Poseidon Review 🐚

Reviewed 843d913.

Six issues are open against the current head: three P2 (the crash-marker misses hipErrorNoBinaryForGpu, the proactive gate skips AMD SDK wheels, and the reactive respawn has no test) and three P3 (multi-GPU retry geometry, a noisy per-poll warning, and a stale docstring). Nothing has been fixed since the last comprehensive pass because head has not moved: all 22 earlier runs ran against this same commit 843d913. Fix the P2 cluster first, because two of them silently defeat the fix on real ROCm hosts and the third is the only untested piece of the change that closes #7624.

P2 - Match hipErrorNoBinaryForGpu too, and lowercase the compare
studio/backend/core/inference/llama_cpp.py:7771

_KERNEL_IMAGE_INVALID_MARKER matches only "device kernel image is invalid", which docs/hip-error-codes.md line 665 documents as hipErrorInvalidImage ("the device code image is corrupted or in an unsupported format"). The canonical arch-mismatch code is hipErrorNoBinaryForGpu (docs/hip-error-codes.md line 646), whose message is "No kernel image is available for execution on the device" and whose listed cause is exactly this bug: code compiled for a different GPU architecture. Both #7624 and #7669 field logs happened to surface the InvalidImage wording, so observed cases are covered, but a different ROCm or ggml build can raise NoBinaryForGpu for the same iGPU pick, and then the reactive retry at line 10538 never fires and the user lands back on the misleading GGUF/memory error. The NoBinaryForGpu text is capitalised in HIP, and the match at line 7775 is case-sensitive (in (output or "")), so lower-case the input too. Raised by essentially every earlier run.

_KERNEL_IMAGE_INVALID_MARKERS = (
    "device kernel image is invalid",              # hipErrorInvalidImage
    "no kernel image is available for execution",  # hipErrorNoBinaryForGpu
)

@classmethod
def _kernel_image_invalid(cls, output: str) -> bool:
    text = (output or "").lower()
    return any(m in text for m in cls._KERNEL_IMAGE_INVALID_MARKERS)

Add a NoBinaryForGpu case to TestKernelImageInvalidMarker alongside the existing InvalidImage one.

P2 - Gate the proactive arch check on the file's own is_rocm test, not just torch.version.hip
studio/backend/core/inference/llama_cpp.py:4633

In _get_gpu_memory's torch fallback the arch gate computes supported_archs/arch_by_id only when getattr(torch.version, "hip", None) is not None. This same file treats a host as ROCm with the broader hip is not None or "rocm" in torch.__version__.lower() at _resolve_visible_physical_ids (lines 4141-4144) and _emit_child_gpu_visibility (lines 4200-4203), with a comment explaining that AMD SDK wheels leave version.hip unset and encode rocm in __version__. On that class of host _rocm_arch_by_physical_id still resolves arches (it reads gcnArchName, no hip check), but the gate here is skipped, so supported_archs stays None, the unsupported iGPU survives enumeration, and the #7669 mis-pick is only recoverable through the layer-2 crash-and-retry, lost entirely if that build raises NoBinaryForGpu. The regression test sets torch.version.hip = "7.1.0", so this path is untested. Raised by both logic and standards runs.

is_rocm = (
    getattr(torch.version, "hip", None) is not None
    or "rocm" in getattr(torch, "__version__", "").lower()
)
if is_rocm:
    supported_archs = LlamaCppBackend._installed_llama_gfx_archs(binary)
    if supported_archs is not None:
        arch_by_id = LlamaCppBackend._rocm_arch_by_physical_id()

Better, factor the is_rocm expression into one helper so all three sites agree.

P2 - Add a test around the reactive respawn's device selection
studio/backend/core/inference/llama_cpp.py:10541

test_gpu_arch_gate_7624.py covers _installed_llama_gfx_archs, the _kernel_image_invalid string match, and the proactive gate in _get_gpu_memory, but nothing exercises the reactive respawn, which is the part that actually closes #7624 for custom-linked builds with no install manifest. The branch predicate (not gpu_ids and not is_vulkan_backend and gpu_indices and _kernel_image_invalid(...) at lines 10532-10539) and the pick (_remaining = sorted(i for i, _free in gpus if i not in set(gpu_indices)) at line 10541) are inline in load_model, unreachable from a test without a live spawn. On a repo where no reviewer can run the hardware, an untested selection path is exactly what slips. Raised by both comprehensive and standards runs.

Extract the complement into a static helper such as _devices_excluding(gpus, gpu_indices) -> list[int] and unit-test it: the (0=iGPU, 1=dGPU) shape from #7624 leaves the dGPU, an explicit gpu_ids pick is skipped, and an empty complement returns nothing.

P3 - Rebuild launch geometry before the arch-fallback respawn, or restrict it to single-device picks
studio/backend/core/inference/llama_cpp.py:10554

The reactive retry recomputes visibility and replays the original cmd unchanged (line 10554), which mishandles two multi-GPU auto shapes. First, _remaining is every enumerated GPU not in gpu_indices, so when auto-fit tensor-splits across a supported dGPU plus an unsupported iGPU (both inside gpu_indices), the crash leaves _remaining empty and the load falls through to the FA/MTP retries this block already notes cannot help. Second, when _remaining is non-empty but smaller than the original count, cmd still carries the --tensor-split/--split-mode tensor and fit budget sized for the old device count, so llama-server gets a split list longer than the visible GPUs. Both need a marker-less build where the proactive gate cannot prune, so they are narrow, but they hand llama-server inconsistent geometry rather than a clean fallback. Raised across the logic and standards runs; the comprehensive run filed both modes as one.

Restrict the reactive retry to the single-device case (skip when len(set(gpu_indices)) > 1), or rebuild the split/fit args for _remaining before respawning instead of replaying the original multi-GPU cmd. Either satisfies both failure modes.

P3 - Emit the arch-skip warning once per load, not on every VRAM-settle poll
studio/backend/core/inference/llama_cpp.py:4648

The per-device logger.warning("Skipping GPU {idx} ...") lives inside _get_gpu_memory, which is not called once per load. _get_gpu_free_memory (line 4503) is a thin wrapper over it, and _wait_for_vram_settle polls _get_gpu_free_memory() every 0.25s for up to 2.0s on each reload (line 4857), with the fit path probing again at load. On the exact mixed iGPU+dGPU host this PR targets (#7669), one Apply-reload emits the same Skipping GPU 1 (gfx1036)... WARNING roughly eight times for a permanently-present iGPU, burying any genuine warning raised in that window. It is not wrong, just noisy on the hot probe path. Raised by three logic and standards runs.

Drop the skip to logger.debug inside _get_gpu_memory, or dedupe it by caching the already-warned (idx, arch) set on the class, keeping a single WARNING at the actual placement decision.

P3 - Document the arch filter in the _get_gpu_memory docstring
studio/backend/core/inference/llama_cpp.py:4552

On a ROCm prebuilt host _get_gpu_memory now silently drops any enumerated device whose gcnArchName is absent from the bundle's mapped_targets (line 4645-4652), but the return contract at line 4552 still only promises (gpu_index, free_mib, total_mib) sorted by index; empty if no supported GPU is reachable. A maintainer chasing why a healthy, reachable GPU vanished from the fit would not learn from the signature that it was filtered by arch; only the runtime logger.warning explains it. Raised by one standards run.

Add a sentence to the return contract, e.g. On a ROCm prebuilt host a device whose gfx arch is absent from the install marker's mapped_targets is omitted (the binary has no kernels for it).

1 similar comment
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

🌊 Poseidon Review 🐚

Reviewed 843d913.

Six issues are open against the current head: three P2 (the crash-marker misses hipErrorNoBinaryForGpu, the proactive gate skips AMD SDK wheels, and the reactive respawn has no test) and three P3 (multi-GPU retry geometry, a noisy per-poll warning, and a stale docstring). Nothing has been fixed since the last comprehensive pass because head has not moved: all 22 earlier runs ran against this same commit 843d913. Fix the P2 cluster first, because two of them silently defeat the fix on real ROCm hosts and the third is the only untested piece of the change that closes #7624.

P2 - Match hipErrorNoBinaryForGpu too, and lowercase the compare
studio/backend/core/inference/llama_cpp.py:7771

_KERNEL_IMAGE_INVALID_MARKER matches only "device kernel image is invalid", which docs/hip-error-codes.md line 665 documents as hipErrorInvalidImage ("the device code image is corrupted or in an unsupported format"). The canonical arch-mismatch code is hipErrorNoBinaryForGpu (docs/hip-error-codes.md line 646), whose message is "No kernel image is available for execution on the device" and whose listed cause is exactly this bug: code compiled for a different GPU architecture. Both #7624 and #7669 field logs happened to surface the InvalidImage wording, so observed cases are covered, but a different ROCm or ggml build can raise NoBinaryForGpu for the same iGPU pick, and then the reactive retry at line 10538 never fires and the user lands back on the misleading GGUF/memory error. The NoBinaryForGpu text is capitalised in HIP, and the match at line 7775 is case-sensitive (in (output or "")), so lower-case the input too. Raised by essentially every earlier run.

_KERNEL_IMAGE_INVALID_MARKERS = (
    "device kernel image is invalid",              # hipErrorInvalidImage
    "no kernel image is available for execution",  # hipErrorNoBinaryForGpu
)

@classmethod
def _kernel_image_invalid(cls, output: str) -> bool:
    text = (output or "").lower()
    return any(m in text for m in cls._KERNEL_IMAGE_INVALID_MARKERS)

Add a NoBinaryForGpu case to TestKernelImageInvalidMarker alongside the existing InvalidImage one.

P2 - Gate the proactive arch check on the file's own is_rocm test, not just torch.version.hip
studio/backend/core/inference/llama_cpp.py:4633

In _get_gpu_memory's torch fallback the arch gate computes supported_archs/arch_by_id only when getattr(torch.version, "hip", None) is not None. This same file treats a host as ROCm with the broader hip is not None or "rocm" in torch.__version__.lower() at _resolve_visible_physical_ids (lines 4141-4144) and _emit_child_gpu_visibility (lines 4200-4203), with a comment explaining that AMD SDK wheels leave version.hip unset and encode rocm in __version__. On that class of host _rocm_arch_by_physical_id still resolves arches (it reads gcnArchName, no hip check), but the gate here is skipped, so supported_archs stays None, the unsupported iGPU survives enumeration, and the #7669 mis-pick is only recoverable through the layer-2 crash-and-retry, lost entirely if that build raises NoBinaryForGpu. The regression test sets torch.version.hip = "7.1.0", so this path is untested. Raised by both logic and standards runs.

is_rocm = (
    getattr(torch.version, "hip", None) is not None
    or "rocm" in getattr(torch, "__version__", "").lower()
)
if is_rocm:
    supported_archs = LlamaCppBackend._installed_llama_gfx_archs(binary)
    if supported_archs is not None:
        arch_by_id = LlamaCppBackend._rocm_arch_by_physical_id()

Better, factor the is_rocm expression into one helper so all three sites agree.

P2 - Add a test around the reactive respawn's device selection
studio/backend/core/inference/llama_cpp.py:10541

test_gpu_arch_gate_7624.py covers _installed_llama_gfx_archs, the _kernel_image_invalid string match, and the proactive gate in _get_gpu_memory, but nothing exercises the reactive respawn, which is the part that actually closes #7624 for custom-linked builds with no install manifest. The branch predicate (not gpu_ids and not is_vulkan_backend and gpu_indices and _kernel_image_invalid(...) at lines 10532-10539) and the pick (_remaining = sorted(i for i, _free in gpus if i not in set(gpu_indices)) at line 10541) are inline in load_model, unreachable from a test without a live spawn. On a repo where no reviewer can run the hardware, an untested selection path is exactly what slips. Raised by both comprehensive and standards runs.

Extract the complement into a static helper such as _devices_excluding(gpus, gpu_indices) -> list[int] and unit-test it: the (0=iGPU, 1=dGPU) shape from #7624 leaves the dGPU, an explicit gpu_ids pick is skipped, and an empty complement returns nothing.

P3 - Rebuild launch geometry before the arch-fallback respawn, or restrict it to single-device picks
studio/backend/core/inference/llama_cpp.py:10554

The reactive retry recomputes visibility and replays the original cmd unchanged (line 10554), which mishandles two multi-GPU auto shapes. First, _remaining is every enumerated GPU not in gpu_indices, so when auto-fit tensor-splits across a supported dGPU plus an unsupported iGPU (both inside gpu_indices), the crash leaves _remaining empty and the load falls through to the FA/MTP retries this block already notes cannot help. Second, when _remaining is non-empty but smaller than the original count, cmd still carries the --tensor-split/--split-mode tensor and fit budget sized for the old device count, so llama-server gets a split list longer than the visible GPUs. Both need a marker-less build where the proactive gate cannot prune, so they are narrow, but they hand llama-server inconsistent geometry rather than a clean fallback. Raised across the logic and standards runs; the comprehensive run filed both modes as one.

Restrict the reactive retry to the single-device case (skip when len(set(gpu_indices)) > 1), or rebuild the split/fit args for _remaining before respawning instead of replaying the original multi-GPU cmd. Either satisfies both failure modes.

P3 - Emit the arch-skip warning once per load, not on every VRAM-settle poll
studio/backend/core/inference/llama_cpp.py:4648

The per-device logger.warning("Skipping GPU {idx} ...") lives inside _get_gpu_memory, which is not called once per load. _get_gpu_free_memory (line 4503) is a thin wrapper over it, and _wait_for_vram_settle polls _get_gpu_free_memory() every 0.25s for up to 2.0s on each reload (line 4857), with the fit path probing again at load. On the exact mixed iGPU+dGPU host this PR targets (#7669), one Apply-reload emits the same Skipping GPU 1 (gfx1036)... WARNING roughly eight times for a permanently-present iGPU, burying any genuine warning raised in that window. It is not wrong, just noisy on the hot probe path. Raised by three logic and standards runs.

Drop the skip to logger.debug inside _get_gpu_memory, or dedupe it by caching the already-warned (idx, arch) set on the class, keeping a single WARNING at the actual placement decision.

P3 - Document the arch filter in the _get_gpu_memory docstring
studio/backend/core/inference/llama_cpp.py:4552

On a ROCm prebuilt host _get_gpu_memory now silently drops any enumerated device whose gcnArchName is absent from the bundle's mapped_targets (line 4645-4652), but the return contract at line 4552 still only promises (gpu_index, free_mib, total_mib) sorted by index; empty if no supported GPU is reachable. A maintainer chasing why a healthy, reachable GPU vanished from the fit would not learn from the signature that it was filtered by arch; only the runtime logger.warning explains it. Raised by one standards run.

Add a sentence to the return contract, e.g. On a ROCm prebuilt host a device whose gfx arch is absent from the install marker's mapped_targets is omitted (the binary has no kernels for it).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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.

This is the right shape and the highest-value unmerged fix in this area, so I want to land it. Two layers, both failing open, with the proactive one keyed on data we already have at install time, is exactly how I would have written it. Your own review comment on 843d913 is accurate and I would treat all three P2 items as blocking. Four things beyond that list.

1. The rebase is not mechanical, and it hands you the fix for your own second P2. main has since rewritten the torch fallback in _get_gpu_memory: it now computes unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids() (llama_cpp.py:5209, helper at :4864) and applies a system-RAM cap plus _apply_igpu_host_reserve_mib, and _amd_apu_wants_unified_memory (:4905) is a thin wrapper over it. Your _rocm_arch_by_physical_id extraction is against the old body.

That refactor already carries the arch reader you want. core/training/worker.py:_rocm_classify_unified_memory (:1487) returns (gcn_arch, is_unified) and tries gcnArchName, gcn_arch_name, arch_name, gfx_arch_name in order, with a comment at :1502-1503 recording that AMD SDK and Radeon wheels populate none of them. Your helper reads gcnArchName only, so on that wheel class every arch is "", every device fails open, and layer 1 is a no-op on exactly the Windows AMD hosts in #7624 and #7669. Please source the arch map from that classifier on rebase instead of adding a third reader.

2. Fail open when the filter would drop everything. mapped_targets is concrete in the published manifest today (gfx110X -> [gfx1100, gfx1101, gfx1102, gfx1103]), so the gate is sound. But if a bundle ever records a generic target such as gfx10-3-generic, or the arch spelling drifts, no device matches and _get_gpu_memory returns [], which silently drops a healthy machine to CPU with only a per-device warning. If the filter would empty the list, keep every device. That keeps the whole feature strictly additive.

3. _remaining reads the wrong list.

_remaining = sorted(i for i, _free in gpus if i not in set(gpu_indices))

gpus is set to [] in both Manual memory modes so the planner is bypassed, while _detected_gpus keeps the full probe. There is a comment in that region saying to use _detected_gpus "not gpus" for precisely this reason. As written, the reactive retry never fires in Manual mode even though gpu_indices was populated from _detected_gpus. Switch to _detected_gpus.

4. The respawn inherits env decided for the crashed device. GGML_CUDA_ENABLE_UNIFIED_MEMORY is set from _amd_apu_wants_unified_memory(gpu_indices) before the first spawn, and _apply_datacenter_env right after. In the canonical case the crashed device is the APU and the retry lands on a discrete GPU, so the child keeps the unified-memory env that the helper's own docstring says hurts discrete GPUs. The retry only rewrites visibility. Recompute both for _remaining, or drop them for the fallback spawn.

On #7307. Layer 1 covers it: the Studio-installed rocm-gfx120X bundle records ["gfx1200", "gfx1201"], so the Ryzen iGPU is dropped before the rank, which matches that reporter's corrected diagnosis. Layer 2 does not. They ran a source build with no marker, and _remaining is the complement of the entire selection, so with two R9700s plus an iGPU the complement is either empty (no retry) or excludes a healthy dGPU alongside the bad one. Excluding only the offending device rather than the whole selection would cover #7307's source-build path and would also dissolve your own P3 geometry item, since the surviving set then keeps the original device count in the common single-bad-device case.

Once the P2 cluster plus the four above are in and it is rebased, I am happy to take it. Please also drop the draft flag when it is ready.

@danielhanchen

Copy link
Copy Markdown
Member

@LeoBorcherding no pressure on timing, but flagging that this one is worth landing: it closes #7624 and #7669, which are the same defect through the two install paths, and both are hard crashes that surface as a GGUF or memory error rather than as the device problem they are. #7307 is partly covered too.

The branch is conflicting now. main has since rewritten the torch fallback in _get_gpu_memory, which is what my review comment above is mostly about, and that rewrite happens to hand you the fix for your own second P2: core/training/worker.py:_rocm_classify_unified_memory at :1487 already tries gcnArchName, gcn_arch_name, arch_name and gfx_arch_name in order, with a comment recording that AMD SDK and Radeon wheels populate none of them. Sourcing the arch map from there instead of adding a third reader removes the case where layer 1 silently no-ops on exactly the hosts in #7624 and #7669.

If you have time to rebase and pick up the P2 cluster plus the four items above, that is the outcome I would prefer, since the design here is yours and it is the right one. If you would rather hand it off, say so and I will carry it forward with you credited as the author of the approach, either as commits on this branch or as a follow-up that keeps your history.

Either way it should not sit, given what it fixes.

Merge conflict was in studio/backend/core/inference/llama_cpp.py, where main
has since grown unified-memory APU accounting in the same torch fallback loop
this PR filters in. Both behaviours are kept: a shared-pool device still gets
its host-RAM reserve and reports total 0, and an unsupported device is still
dropped.

Review items addressed:

- The arch gate is now opt-in (_get_gpu_memory / _get_gpu_free_memory take
  for_llama_server). It answers "what can llama-server run on", not "what GPUs
  exist", and the same probe backs core/rag/embeddings.py::_resolve_auto, which
  picks sentence-transformers (PyTorch). A device the installed llama.cpp
  prebuilt lacks kernels for is usually still a fine torch device, so gating
  that probe would have pushed RAG embeddings onto the CPU. The llama-server
  call sites opt in: automatic placement in load_model, and the GGUF embedding
  backend's own GPU check.
- _rocm_arch_by_physical_id reads the arch through the training worker's
  classifier, so the alternate spellings AMD SDK / Radeon wheels use
  (gcn_arch_name, arch_name, gfx_arch_name) are covered as well as the
  canonical gcnArchName. Reading only the canonical name left the map empty on
  those wheels and failed the gate open.
- The ROCm check uses the shared _torch_is_rocm predicate instead of a bare
  torch.version.hip test, so AMD SDK wheels that leave version.hip unset are
  gated too.
- The kernel-image-invalid recovery set moved into _arch_crash_retry_gpu_ids.
  It still prefers never-selected devices, and when the failed launch used
  every enumerated GPU it narrows the selection by dropping the unified-memory
  devices instead of giving up.
- _installed_llama_gfx_archs no longer lets a marker read raise: it runs inside
  the GPU probe, where an exception would have dropped every device.

tests/test_gpu_arch_gate_7624.py grew coverage for the torch-caller path, the
arch attribute fallback, the broader ROCm wheel predicate, the APU reserve and
the gate coexisting, and the retry set.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this @LeoBorcherding, and sorry for the slow turnaround. The design here is right: recording the prebuilt's mapped_targets at install time, refusing to rank a GPU the binary has no kernels for, and failing open when coverage is unknown is the correct shape for #7624. Keeping mapped_targets out of the install fingerprint was also the right call, so existing installs stay valid and nobody gets a surprise reinstall.

I pushed to your branch rather than opening a competing PR, so your commits and authorship stay intact. What changed is scope, not direction.

Merged main in. While this sat, main grew unified-memory APU accounting in the exact loop you were filtering in (_rocm_unified_memory_gpu_ids, the system-RAM cap, _apply_igpu_host_reserve_mib, and reporting total 0 for a shared pool). I merged rather than rebased so your five commits stay verbatim and there is no force-push onto your fork. Both behaviours now coexist in that loop, in this order per device: arch gate first (continue on unsupported), then the APU accounting. Order matters, since a dropped device must never reach the shared-pool math.

The gate had to become opt-in. This is the one blocking item. _get_gpu_free_memory has two consumers outside placement:

caller picks gate?
rag/embed_llama_server.py::_gpu_available llama-server embeddings yes
rag/embeddings.py::_resolve_auto sentence-transformers, i.e. PyTorch no

On a host where the iGPU runs fine under PyTorch but the llama.cpp prebuilt has no kernels for it, the unconditional gate silently downgraded RAG embeddings off a perfectly usable GPU. _resolve_auto's own docstring says its GPU check is meant to be torch-free. So both probes now take a keyword-only for_llama_server, defaulting to unfiltered, and only the two llama-server paths opt in. At the placement site it is auto-only (for_llama_server = not gpu_ids), because an explicit user pin that got filtered would hit the fail-open and quietly land on a different card, which contradicts your own intent that an explicit pick keeps its error.

Two helpers already existed in the tree, so they now delegate instead of re-implementing:

  • arch property spellings: core/training/worker.py already loops gcnArchName / gcn_arch_name / arch_name / gfx_arch_name, and tests/test_rocm_oom_guard.py parametrises them. _rocm_arch_by_physical_id reads the arch through _rocm_classify_unified_memory so the two paths cannot drift.
  • ROCm detection: _torch_is_rocm handles AMD SDK wheels, which leave torch.version.hip unset but encode rocm in __version__. A bare version.hip test would have left those users ungated.

Your _kernel_image_invalid recovery was kept and extended, not replaced. It only retried on never-selected devices, so on a 2 GPU host where the planner took both cards it was dead code for exactly the markerless and custom-build case it exists to cover. It now falls back to dropping the unified-memory devices and retrying on the discrete remainder, which is the reported host shape, and bails out when narrowing changes nothing.

One extra fix not from review: _installed_llama_gfx_archs ran unguarded inside _get_gpu_memory's outer try, so a raising marker read would have returned zero GPUs instead of falling back to unknown.

Tests are at 28 for test_gpu_arch_gate_7624.py, and I checked each new assertion by reverting the behaviour it claims and confirming it fails. No hardware validation is claimed here, there is no ROCm CI in the repo, so all of this is mock-based.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
danielhanchen and others added 5 commits August 12, 2026 12:35
…nslothai#7624)

mapped_targets is remote data: it comes from llama-prebuilt-manifest.json,
which the release pipeline versions independently of this code. The gate is
exact-set membership against the arch a device reports, so a token no device
can ever report matches nothing and drops EVERY GPU, silently forcing CPU.
That is worse than not gating at all, and it is reachable today from a
malformed marker ([null] and [123] both produce such a set) as well as from a
future publish recording a ROCm generic code object (gfx11-generic) or an
umbrella family label (gfx110X).

Treat an arch list that is not entirely concrete gfx tokens as unknown and
keep every device. All-or-nothing on purpose: dropping just the odd token out
of [gfx1100, gfx11-generic] would under-report what the build covers.

Also pin the compatibility contract that had no coverage: a marker corpus
(absent, empty, invalid, truncated, list-not-dict, null/string/dict/int
targets, unreadable, directory-in-place-of-file, huge list) that must resolve
to a sane arch set or None and never raise; that the new keys leave the
install fingerprint byte-identical, so existing installs do not refresh on
upgrade; that non-ROCm bundles record no archs; that the marker rewrite path
preserves the fields; and that the family-label match still records the
concrete list.
…ai#7624)

The gate returning an empty pool left gpu_indices None, so the launch took
the --fit on arm, the pin block never ran, and no HIP/ROCR/CUDA mask was
written. The child still enumerated every unsupported card and died exactly
as unslothai#7624 reports, and the reactive arch-crash retry could not help because
its guard needs a truthy gpu_indices. Mask the child onto the CPU instead
and say why, on auto placement on a ROCm host only.

Also:
- the arch-crash retry enumerates _detected_gpus, not gpus, matching what
  the region's own comments say to use;
- the retry withdraws GGML_CUDA_ENABLE_UNIFIED_MEMORY when it moves to a
  discrete card, but only when this launch set it, so a user value stands;
- test_single_gpu_host_has_no_retry counts probe calls instead of raising:
  the narrowing branch runs under except Exception, which swallowed the
  raising spy and left the test green with the guard removed;
- correct the justification for gating automatic placement only.
@danielhanchen
danielhanchen dismissed their stale review August 12, 2026 15:44

All four items are addressed on the current head: the probe is opt-in so the PyTorch RAG picker stays unfiltered, the retry enumerates _detected_gpus, the respawn no longer inherits unified-memory env decided for the crashed device, and the all-uncovered case now masks the child off the GPU instead of handing it cards the build has no kernels for.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…retry (unslothai#7624)

Two ways the gate stopped short of the process it was protecting.

The embedding llama-server probe reduced the gated device list to a bool, so
on a mixed host (unsupported iGPU plus supported dGPU) the gate passed on the
dGPU and the child still enumerated every ROCm agent -- and that HSA
enumeration is what dies on an arch the prebuilt has no kernels for. Pin the
survivors with the ROCr-layer mask instead. Inert unless the install marker
reports concrete mapped_targets AND the gate actually narrows the set, so
NVIDIA, CPU-only, Vulkan and macOS write no mask and skip the probe entirely.

The arch-crash retry masked devices out but respawned the planned argv
verbatim. --tensor-split shares are positional over the child's visible
devices (llama.cpp parses them by index, then copies the first n_devices), so
the narrowed set re-indexes the survivors and hands them the crashed set's
weights, which can overcommit a card. Drop the flag for the respawn and fall
back to llama.cpp's free-VRAM split, which is correct for any device set.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@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: b4447cfca2

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

if (
not healthy
and not self._cancel_event.is_set()
and not gpu_ids

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 Honor explicit device flags before retrying

On a custom/no-marker ROCm build, a user can explicitly choose a device through extra_args (--device/-dev) or inherited LLAMA_ARG_DEVICE without populating gpu_ids; this guard therefore treats that launch as automatic. If the chosen GPU produces the kernel-image error, the retry changes the visibility mask to another physical GPU while retaining the explicit device flag, so a relative name such as HIP0 can silently target a different card after reindexing instead of preserving the requested failure. Include the existing argv/env device-selection predicates in the explicit-placement guard.

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.

Not taking this one.

The premise about extras surviving is right: _strip_device_extra_args and _clear_device_placement_env are both conditional on gpu_ids, so an auto launch keeps a user --device. But the reindexing is not introduced by the retry. The FIRST launch already writes the mask on the gpu_indices is not None arm without consulting any argv device pin, and llama.cpp enumerates ROCm<i>/CUDA<i> over the visible set, so ROCm0 was already bound to whatever card the auto mask put first. The retry rebinds it no more than the launch it is retrying did.

The retry's "an explicit user pick keeps its error" refers to Studio's picker (gpu_ids), which the guard does check; nothing here promises anything about argv --device.

And the outcome runs the wrong way. The only way to reach the retry with a user --device is that the name resolved onto the uncovered card and crashed. Today the retry re-resolves it onto a covered card and the load succeeds; adding the argv predicate would replace a working server with a preserved crash.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 13, 2026
unslothai#8520 consolidated the per-field sync_marker_* helpers into one
sync_marker_selection driven by _marker_selection_patch, which conflicted with
the sync_marker_arch_coverage this branch added.

Took main's consolidation and folded the built-arch coverage into
_marker_selection_patch instead of keeping a separate helper. It already
receives the AssetChoice, so the coverage now rides the single write every
reuse path already makes, and the tests move to that writer.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 2712d8d18f

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

pre-commit-ci Bot and others added 3 commits August 13, 2026 10:08
)

Comment-only pass over the files this PR touches: the multi-line blocks and
docstrings say the same things in fewer lines, with the reasoning that records a
review finding kept intact.

Preserved verbatim in shorter form: why _CONCRETE_GFX_ARCH fails open on
non-concrete tokens and why its trailing hex is load-bearing (a digits-only
pattern would reject gfx90a / gfx90c); why the crash markers cover both
hipErrorInvalidImage and hipErrorNoBinaryForGpu and why the match is case-folded;
why the -archfallback respawn restores the memory-policy snapshot; and why an
unmappable visibility mask is left alone.

Two comments were also corrected where they had drifted from the code: the
marker block still said "two spellings" after the set grew to four, and the
regex comment did not say that the trailing hex is what admits gfx90a / gfx90c.

No code changed, verified with comment_tools.py check --strip-docstrings.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: b0cafea08a

ℹ️ 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
danielhanchen merged commit 5a3e9fc into unslothai:main Aug 13, 2026
74 of 78 checks passed
danielhanchen added a commit that referenced this pull request Aug 13, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 13, 2026
…#8667)

* Keep the drafterless retry intact when the arch gate narrows the argv

_spec_start is a positional index captured just before the speculative flags
are appended. #7670's arch gate rebinds cmd with tokens REMOVED from the
prefix (--split-mode / --tensor-split), which slides the spec block left and
leaves the index pointing past it.

The fallback then kept spec_flags[:N], re-running the drafter that had just
failed (llama.cpp accumulates spec types, so --spec-default cannot undo it),
and sliced N tokens out of the middle of the tail. With the four-token
narrowing that included --api-key, so the retry launched llama-server with no
key at all.

Re-locate the block instead of trusting the index, searching back from the
hint first since narrowing can only move it left. A future narrowing site is
then safe by construction rather than by remembering to adjust the index.

* Point the startup-retry guard test at the relocated spec slice

* Tighten the moved-right assertion to the full token invariant

---------

Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit that referenced this pull request Aug 13, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 13, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 13, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 14, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 14, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 14, 2026
torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.
danielhanchen added a commit that referenced this pull request Aug 14, 2026
…context (#8669)

* Read ROCm VRAM through amd-smi so the backend keeps no HIP context

torch.cuda.mem_get_info creates a CUDA/HIP primary context that the process
never releases: 612 MiB measured on a B200 with CUDA 13, 692-712 MiB reported
elsewhere. get_device_properties and get_device_capability do not, and agree
with mem_get_info on total memory exactly.

LlamaCppBackend._get_gpu_memory asks nvidia-smi first, so NVIDIA hosts were
already clean. ROCm hosts, and NVIDIA hosts without nvidia-smi on PATH, fell
straight through to torch, so a backend serving GGUF models held ~700 MiB for
a number it only reads, on a card whose models run in a llama-server child
that then cannot use it. Two docstrings promised the probe was torch-free.

amd-smi answers the same question from a subprocess. The new branch sits
between nvidia-smi and torch, reuses utils/hardware/amd.py's runner, unit
parsing and circuit breaker, honours the visibility mask, and gives a
unified-memory APU the same host reserve and total 0 as the torch branch.

The torch fallback stays for hosts with no smi tool. Callers read an empty
result as no GPU (_resolve_auto picks a backend from it, _gpu_available gates
the embedder, the loader fit drops to CPU), so an unknown there would silently
move inference off the GPU; the context is the lesser cost.

Parity on GPU 5, amd-smi output synthesised from the live nvidia-smi reading
of the same card: free 179165 MiB and total 183359 MiB both branches, 0 MiB
context on the new path against 612 MiB on the torch path. NVIDIA numbers are
untouched, and the branch is inert off ROCm.

Rebased over #7670, which added for_llama_server and the ROCm arch gate to the
same function. The new branch returns before the gate ran, so it would have put
#7624 back for llama-server placement. _rocm_arch_gate_keep now holds the gate,
and both branches call it, so the two cannot drift. It costs no context of its
own: get_device_properties measured 0MiB against mem_get_info's 620MiB on GPU 5.

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

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

* Defer to torch on unified-memory APUs, and read a single-GPU amd-smi dict for PR #8669

amd-smi reports only the dedicated VRAM carve-out on a unified-memory APU,
while HIP reports the far larger GTT pool the models actually run in. On a
128GiB Strix Halo with an 8GiB BIOS carve-out that is 8GiB against ~100GiB, so
the new branch would have handed the GGUF fitter the slice and refused models
that fit today. The branch now declines the whole host when any visible device
is a unified-memory APU: discrete ROCm cards keep the context saving, APU hosts
keep byte-identical pre-PR numbers, and the two branches cannot disagree because
only one ever answers.

Reconstructing the pool from total_gtt was the other option and was rejected:
HIP's mem_get_info on an APU is not documented as equal to GTT alone, and the
older vram / fb_memory_usage shapes carry no GTT fields, so the two branches
would drift, which is what _rocm_arch_gate_keep was unified to prevent.

Separately, _gpu_entries' documented bare single-GPU dict fallback was dead:
data.get("gpu", [data]) returns the numeric id for that shape and enumerate(int)
raises. An envelope key now only counts when its value is really a list, which
also closes enumerate(None) on {"gpus": null}.

* Translate amd-smi gpu ids into HIP ids, and answer for every visible device

amd-smi numbers its devices in discovery order over its own KFD view; HIP numbers
them by KFD node id (amdsmi computes hip_id as node_id - smallest_node_id). The two
agree on most hosts and not on all of them, and the branch was keying VRAM rows by
amd-smi's number, comparing it against HIP/ROCR/CUDA visibility tokens and then
pinning the child with it. On a host where they differ, the larger card's memory
lands on the smaller card's HIP id and a load that fit before this PR can OOM.

amd-smi list -e (ROCm 6.4.0+, amdsmi_get_gpu_enumeration_info) is the mapping AMD
publishes for exactly this. Read it and re-key, and decline when it is not readable:
an older CLI rejects -e, hip_id reads N/A when the library cannot reach the device's
KFD node, and identity is then an assumption rather than a fact. A single-GPU host
skips the call, since one card on the host forces the mapping, so the ROCm desktops
this branch mostly runs on keep the context saving on any amd-smi version. That -e
failure is kept out of the circuit breaker: an old CLI is not an amd-smi outage, and
three of them would disable the utilization poller too.

_resolve_visible_physical_ids returns None both for "no mask" and for a mask it
cannot parse, and the branch read the second as the first. ROCr accepts UUID tokens
(ROCR_VISIBLE_DEVICES=GPU-<uuid>), and amd-smi ignores the mask entirely, so a
deliberately hidden card was being offered for automatic ranking. Use the existing
_visibility_mask_is_unmappable and defer to torch, which enumerates the masked set.

Separately, get_gpu_vram_mib drops a row whose total reads 0, and what was left was
a non-empty list the caller takes as the whole host. On an APU beside a dGPU that
turned two devices into one, so the "fewer than 2 usable GPUs" arm switched off
tensor parallelism on a host main reports as two. get_gpu_vram_report now also
returns every id amd-smi enumerated, and the branch answers for every visible device
or declines entirely.

The existing rocm fixture only patched _resolve_visible_physical_ids and left the
shell's own CUDA_VISIBLE_DEVICES in the environment, which now reads as a mask set
but unresolvable; clear it there too, the same trap as #8662.

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

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

* Decline the amd-smi VRAM branch when HIP cannot open a device

amd-smi reads the driver over sysfs and libdrm, HIP needs /dev/kfd and a
matching HSA runtime. They come apart on a container started with
--device=/dev/dri but no --device=/dev/kfd, and on a torch wheel built
against a ROCm the installed runtime does not match: amd-smi lists the card
and hipGetDeviceCount returns 0, so torch.cuda.is_available() is False while
_torch_is_rocm() stays True.

The llama-server child is a HIP process too, so it dies exactly where torch
did. Before this branch existed the torch fallback returned [] for such a
host and the load went to CPU. The amd-smi branch returns first and hands
placement a device nothing can open.

Neither existing guard catches it, since both are torch readers that fail
open: _rocm_unified_memory_gpu_ids answers set() and _rocm_arch_by_physical_id
answers {} the moment is_available() is False, so a unified-memory APU is not
even recognised as one and its dedicated carve-out is taken for the whole
pool.

The gate costs nothing this path was not already paying:
_rocm_unified_memory_gpu_ids calls is_available() and get_device_properties()
further down the same function. Neither creates a primary context (measured:
no compute-apps entry, against 612 MiB for mem_get_info), because
is_available() is hipGetDeviceCount rather than _lazy_init.

Both rocm fixtures now declare HIP reachability instead of inheriting the
host's, the same trap as #8662: unpatched they read the test machine's own
GPU and 16 of them fail on a CPU-only runner.

* Answer the amd-smi VRAM branch only for HIP's own inventory for PR #8669

GPU_DEVICE_ORDINAL is a ROCm visibility variable that
_resolve_visible_physical_ids does not read, so the branch took no mask
from a process that had one. Defer to torch while it is set, the way
hardware.py::_rocm_visibility_mask_active gates the system-wide overlay.

Compare the visible device count against hipGetDeviceCount as well: a
device-cgroup container given one /dev/dri/renderD* node and no env var
leaves amd-smi enumerating the whole host, and a row amd-smi omitted
leaves a single-GPU shape the id-mapping shortcut accepts as a one-card
host.

Compare the totals too, with the same 10% margin the System tab's
overlay uses. An APU _rocm_classify_unified_memory cannot name (a
gfx1103 Phoenix wheel with no is_integrated flag) has amd-smi reporting
the BIOS carve-out where HIP reports the GTT pool, and a partition reads
the other way round. Devices torch cannot describe fail open.

* Decline the amd-smi VRAM branch when ROCm visibility masks are stacked

ROCR_VISIBLE_DEVICES filters and renumbers agents inside the ROCr runtime, and
clr's Device::init then indexes HIP_VISIBLE_DEVICES (or its CUDA_VISIBLE_DEVICES
twin) into the agent vector ROCr left behind, so the two compose:
ROCR_VISIBLE_DEVICES=1,2 with HIP_VISIBLE_DEVICES=0 opens physical GPU 1.

_active_gpu_visibility_mask returns the single highest-precedence value, which
reads [0] there, and on a host whose cards share a model every later check on the
amd-smi branch agrees with it: HIP opens one device, the mask names one, and the
totals match. The branch then reported physical GPU 0's free VRAM for a process
that can only reach GPU 1. Defer to torch instead, which enumerates in HIP's own
space; composing the masks would need the physical to ROCr mapping ROCr just
renumbered away.

HIP and CUDA together are one layer, not two, and Windows has no ROCr layer, so
neither defers.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 1, 2026
…arch coverage (#8791)

* Studio: keep training off GPUs the installed torch build has no kernels for

#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 #7669 machine, which
still fails there after #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 #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.

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

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

* Studio: fail the training arch gate open on a mixed arch list, and ignore 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.

* Pin the ROCr-relative ordinal, not the physical id, when HIP stacks on 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.

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

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

* Refuse the arch gate behind renumbered ordinals, and settle ROCm from 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.

* Stop the arch-gate tests leaking IS_ROCM into the rest of the session

The new test file installs a fake AMD torch and then calls the gate, which
reaches _get_parent_visible_gpu_spec() -> get_device() -> detect_hardware().
Nothing pins the detection globals, so that assignment latches IS_ROCM = True
and DEVICE = CUDA as module globals for the remainder of the pytest process,
and monkeypatch never restores them because nothing patched them.

Three tests in test_gpu_selection.py then fail, on any host: _backend_label()
returns 'rocm', and both get_backend_visible_gpu_info() and
get_visible_gpu_utilization() take the amd branch and bypass the mocked
nvidia-smi. It stayed hidden only because test_gpu_selection.py sorts before
test_training_gpu_arch_gate.py, so the victim normally runs first. Reordering
the two files reproduces it on a plain NVIDIA box, and it showed up on a real
gfx1151 runner where the files ran the other way round.

Two of this file's own tests also read whatever mask variables the shell
exported: with ROCR_VISIBLE_DEVICES set at all, _rocm_visibility_masks_are_stacked()
is true and the gate fails open before reaching what they assert. They take the
no_mask fixture the file already defines for exactly this reason.

No product code changes. 118 pass with the two files in either order.

* Trim comments on the ROCm training arch gate

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.

* Keep the arch gate from dropping a card the wheel does cover

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.

* Keep gating when amd-smi undercounts the GPUs

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. #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.

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

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

* Keep the arch gate filtering when a device arch never read

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.

* Trim the comments added since the last pass on the ROCm arch gate

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
…e cards the build has kernels for (unslothai#16513)

Reported by a Discord user in the help thread: Windows 11, RX 7900 XTX +
Radeon AI PRO R9700 + Ryzen iGPU, a manual GPU split. Every load died
with "llama-server crashed at startup ... hide it with
ROCR_VISIBLE_DEVICES". The log shows `ROCm error: invalid kernel file` /
`current device: 2`, and device 2 is the R9700. The installed prebuilt
was `gfx110X`, which has no `gfx1201` kernels.

**Why nothing caught it**

unslothai#7670 added two guards for this, and both were skipped:
- The proactive gate pins llama-server to the covered cards, but only
when it can read the build's coverage list (`mapped_targets` in
`UNSLOTH_PREBUILT_INFO.json`). The log has no `Skipping GPU` line, so it
couldn't.
- The reactive arch-crash retry runs only when Unsloth pinned the launch
(`gpu_indices` truthy). A manual split with no GPU picked is never
pinned.

So all four retries (flash-attn off, no MTP, CPU projector, text-only)
crashed the same way. Then the hint pointed at `ROCR_VISIBLE_DEVICES`,
which masks nothing on Windows.

**What changes**
- For an unpinned launch, the arch-crash retry now names the crashed
card from llama-server's own `current device: N`, mapped through any
inherited mask. It drops that card, and a shared-memory iGPU when a
discrete card remains, then respawns with the positional
`--tensor-split` removed. This is the respawn unslothai#7670 already uses for
pinned launches, unchanged. ROCm only: an unmasked CUDA child orders
devices by speed, so its ordinal isn't our id.
- The dropped split is recorded in `_arch_gate_dropped_tensor_split`, as
the proactive gate does, so the next Apply doesn't reload.
- The Windows HIP crash hint names `HIP_VISIBLE_DEVICES`.

**Tests**

The new tests are red on base and green on head: 11 failed / 10 passed
vs 21 passed. They're `TestUnpinnedArchCrashRetry`, the Windows hint
case, and a call-site pin that an unpinned launch reaches the retry and
records the drop. Across the related suites (arch gate, crash message,
companion widening, placement, load-mode matrix, sidecar reserve, auto
tensor split), 2600 pass. Four fail on a macOS box and fail identically
on base: `test_spec_sidecar_fit_reserve_multi_gpu` x3 and
`test_the_launch_env_masks_the_child_to_them`.

**Hardware**

No hosted runner has an AMD GPU. The Strix Halo runner on oobabooga's
fork is one gfx1151 APU on Linux, so it can't put a covered and an
uncovered discrete card in one Windows box. This table is the test
report. Rows A to E: Windows 11, 2x Radeon AI PRO R9700 (gfx1201) +
Radeon iGPU (gfx1036), ROCm `b11985` prebuilts, Qwen3-0.6B Q4_K_M,
`gpu_layers=999`, `tensor_split=1,1,1`. Rows F and G: Windows 11, RX
5700 XT (gfx1010, uncovered) + RX 6500 XT (gfx1034, covered), the
`b11985-mix-c116c32` gfx103X build through `LLAMA_SERVER_PATH` (no
coverage file, so the gate can't read it), SmolLM2-135M Q4_K_M,
`gpu_layers=999`, `tensor_split=1,1`, same env for both with only
`llama_cpp.py` swapped.

| run | code | llama.cpp build | coverage list | result | verified |
|---|---|---|---|---|---|
| A | base `073f6e0` | gfx120X | readable | gate skips GPU 2, pins `[0,
1]`, loads and chats | measured |
| A2 | base | gfx120X | emptied | loads; llama.cpp itself leaves the
iGPU out when a dGPU is present | measured |
| B | base | gfx110X | emptied | `device kernel image is invalid` on
device 0, no arch retry, load fails (the reported crash) | measured |
| C | head `31d4231` | gfx110X | emptied | "kernel-image error on GPU(s)
[0] ... Retrying on GPU(s) [1]", split dropped, iGPU excluded; GPU 1 is
also uncovered, so the load still fails | measured |
| D | head | gfx120X | readable | same as A, no regression | measured |
| E | head | gfx120X | emptied | same as A2, no regression | measured |
| F | base `073f6e0` | gfx103X | unreadable | `invalid kernel file` on
device 0 (5700 XT), only the no-flash retry, same crash, load fails
(HTTP 500) | measured |
| G | head `186046e` | gfx103X | unreadable | same crash, then the
arch-crash retry on the 6500 XT alone: loads and chats. The reporter's
shape, one covered + one uncovered card | measured |

Server log, run B (base):
```
GPUs free: [] (manual mode), selected: None, --fit: off
[llama-server] E ROCm error: device kernel image is invalid
[llama-server] E   current device: 0, in function ggml_cuda_kernel_launch at ggml-cuda\common.cuh:1740
llama-server exited with code 3221226505.
llama-server hard-crashed at startup (exit 3221226505) with flash attention on; retrying once with --flash-attn off
[llama-server] E ROCm error: device kernel image is invalid
llama-server exited with code 3221226505.
Error loading model: llama-server failed to start.
```

Server log, run C (head):
```
GPUs free: [] (manual mode), selected: None, --fit: off
[llama-server] E ROCm error: device kernel image is invalid
[llama-server] E   current device: 0, in function ggml_cuda_kernel_launch at ggml-cuda\common.cuh:1740
llama-server exited with code 3221226505.
llama-server crashed with a HIP kernel-image error on GPU(s) [0] -- the llama.cpp build has no kernels for that arch. Retrying on GPU(s) [1].
Dropped --tensor-split for the arch-crash retry: its shares are positional over the visible devices and the narrowed set re-indexes them.
[llama-server] E ROCm error: device kernel image is invalid
```

**Bottom line:** on real hardware, the crash reproduces on base, and on
head the retry drops the uncovered card and the load recovers on the
covered one (run G). Not run: Linux ROCm with a mixed pair, where the
retry masks through `ROCR_VISIBLE_DEVICES` and reads `current device`
through that re-indexing.

**Still unknown:** whether the reporter's gate failed because the
install file predates `mapped_targets` or because the per-card arch
lookup came back empty on Windows. The retry covers both.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants