Skip to content

fix(amd): read ROCm VRAM through amd-smi so the backend keeps no HIP context - #8669

Merged
danielhanchen merged 8 commits into
mainfrom
studio/hardware-probe-no-cuda-context
Aug 14, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio/hardware-probe-no-cuda-context

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

LlamaCppBackend._get_gpu_memory tries nvidia-smi first and falls back to torch.cuda.mem_get_info. On ROCm the first branch never answers, so every ROCm host takes the torch branch, and mem_get_info creates a HIP primary context in the Studio backend process that nothing can give back.

The models this sizing is for run in a llama-server child process, so the backend is paying a permanent context to answer a question a subprocess could have answered.

Measured

One call per process on a B200, per-PID via nvidia-smi --query-compute-apps:

call context after
import torch only 0 MiB
torch.cuda.is_available() 0 MiB
torch.cuda.device_count() 0 MiB
torch.cuda.get_device_properties(0).total_memory 0 MiB
torch.cuda.get_device_capability(0) 0 MiB
torch.cuda.get_device_name(0) 0 MiB
torch.cuda.mem_get_info(0) 612 MiB

Still 612 MiB after empty_cache() plus gc.collect() and a 5 second wait. Reproduced through the production function rather than a synthetic one, running _get_gpu_memory() in one process and then again with PATH stripped to stand in for a host with no nvidia-smi:

WITH nvidia-smi:    [(5, 179681, 183359)]   context 0 MiB
WITHOUT nvidia-smi: [(5, 179060, 182633)]   context 612 MiB

Note the probe distorts the number it reports: its own context eats ~612 MiB out of the free figure.

The change

The order becomes nvidia-smi, then amd-smi, then torch.

_get_gpu_memory_amd_smi reuses the existing runner in utils/hardware/amd.py (_run_amd_smi, with its Windows UAC guard, shutil.which check, circuit breaker, child_env_without_native_path_secret and windows_hidden_subprocess_kwargs; no shell=True, nothing POSIX-only) and its unit parsing. Rather than duplicate, two helpers were extracted: _vram_used_total_mb out of _extract_gpu_metrics, and _gpu_entries out of get_visible_gpu_utilization.

It honours the visibility mask, since amd-smi enumerates every card, and gives a unified-memory APU the same system RAM cap, host reserve and total = 0 the torch branch does.

Torch stays as the last resort deliberately. Callers read [] as "no GPU": _resolve_auto in core/rag/embeddings.py picks a whole embedding backend from its truthiness, _gpu_available in embed_llama_server.py gates the embedder onto CPU, and the loader fit drops every layer to CPU. Returning unknown there would silently move a ROCm user's inference to the CPU, so on a host with neither smi tool the behaviour is exactly what it is today, context included.

Parity

amd-smi output synthesised from the live nvidia-smi reading of the same card, so free and total are ground truth:

scenario result context
NVIDIA, nvidia-smi present [(5, 178440, 183359)] 0 MiB
NVIDIA, no nvidia-smi (torch fallback) [(5, 177819, 182633)] 612 MiB, unchanged
ROCm plus amd-smi (this change) [(5, 179165, 183359)], ground truth free=179165 total=183359 0 MiB
ROCm, no amd-smi (fallback) [(5, 177819, 182633)] 612 MiB, unchanged

Exact free and total parity. The 0 MiB in row three also shows the shared-pool path is context free: _rocm_unified_memory_gpu_ids ran there and called is_available() and get_device_properties() per device.

Parser parity across every amd-smi shape the repo already handles: mem_usage GiB dicts, old vram MiB strings, fb_memory_usage bare ints, used-above-total clamped to zero, a VRAM-less entry, and a scalar array entry skipped.

What was deliberately left alone

video.py:690 _h3_device_capacity_bytes reads mem_get_info()[1] for a total only, so it looks like an easy substitution. On Windows WDDM that total is the driver-granted budget rather than the card total, which core/training/worker.py documents and tests/test_rocm_oom_guard.py asserts on by source line, so swapping it would loosen a refusal gate on Windows ROCm. It also buys nothing, since it runs inside a video load that puts tensors on the GPU anyway. Same reasoning for the other trusted_mem_get_info callers in diffusion_memory.py, video.py and diffusion_dit_trainer.py: all five genuinely need live free memory rather than total, and all run in processes already holding torch CUDA state.

No xpu-smi, pynvml or amdsmi binding exists anywhere in the backend, and the only XPU VRAM path is in diffusion_memory.py, already inside a torch-holding process. MPS has no mem_get_info at all. CPU-only never reaches the branch.

Tests

66 hardware, GPU, VRAM, llama_cpp, inference, embedding and ROCm test files:

  • before: 9 failed, 2597 passed, 13 skipped
  • after: 9 failed, 2607 passed, 13 skipped

The failure set is identical and pre-existing on main (verified by stashing), all in tests/test_amd_apu_unified_memory.py, which mock sys.modules["torch"] partially and lose to the real torch installed on this box.

The 10 new passes are tests/test_rocm_vram_probe_no_hip_context.py. ruff clean on all five files.

The two RAG docstring edits correct claims that the probe was "torch-free (nvidia-smi)" and that "the common path needs no torch", which were false on ROCm and are a large part of why this stayed invisible.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from 9cc50a2 to 01fe57c Compare August 13, 2026 11:33
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto current main as 01fe57cd6, and the rebase was not mechanical.

#7670 landed on the same function, adding for_llama_server and the ROCm arch gate that drops devices whose gfx arch the installed prebuilt has no kernels for (#7624). My amd-smi branch returns before that gate ran, so a straight rebase would have put #7624 straight back for llama-server placement: an iGPU reporting shared RAM outranks the dGPU on free memory, and the child dies with "device kernel image is invalid".

The gate is now a single _rocm_arch_gate_keep helper called from both branches, lifted from #7670 inline block verbatim so the permissive cases match exactly: keeps every device off the llama-server path, off ROCm, on unknown coverage, and for a device with no reported arch. Five tests on the #7624 shape (gfx1101 dGPU plus uncovered gfx1036 iGPU), including one driving the full probe with nvidia-smi absent, which is where the ordering trap actually lives. Removing the gate call from the amd-smi branch alone fails exactly those two tests and leaves the three permissive ones green.

One deliberate choice worth a look: when the gate drops every card, the amd-smi branch returns [], the caller reads that as "amd-smi could not answer" and falls through to torch, where the same gate reaches the same empty list. The answer is identical to main on every input; the cost is one HIP context on that arm alone. I preferred that to giving [] a second meaning, since the two branches enumerate devices from different sources (amd-smi physical ids against torch ordinals) and making the amd-smi branch authoritative would let them disagree.

The gate itself costs nothing: get_device_properties measured 0 MiB against mem_get_info 620 MiB on this box.

Also worth correcting something I said earlier in this PR. The 9 test_amd_apu_unified_memory.py failures I called pre-existing are gone on current main: 794b16e87 fixed exactly that, and the file is green on unmodified main now. Failure sets against main are empty on both sides, before 2114 passed and after 2129, the delta being my 15 tests.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +5734 to +5737
visible = LlamaCppBackend._resolve_visible_physical_ids()
if visible is not None:
allowed = set(visible)
vram = {idx: v for idx, v in vram.items() if idx in allowed}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve UUID-based ROCm visibility masks

When ROCm visibility is expressed with a UUID token, _resolve_visible_physical_ids() returns None just as it does for an unset mask; _visibility_mask_is_unmappable() explicitly recognizes this case. Treating that result as “all GPUs” accepts amd-smi's host-wide physical inventory, and automatic placement can later rewrite the child visibility mask with those numeric IDs, exposing GPUs the inherited UUID mask hid. Fall back to the torch probe when an active mask is unmappable rather than treating every None as unset.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Already addressed in fd0348c, before this review was posted. The UUID mask case now rejects the amd-smi result rather than reading an unresolvable mask as no mask.

Comment on lines +5853 to +5854
if rocm_gpus:
return rocm_gpus

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 Reject partial amd-smi memory results

On a mixed AMD host where one amd-smi entry lacks usable used or total memory, get_gpu_vram_mib() skips that entry but still returns the valid rows. This truthy partial result suppresses the torch fallback, so the affected GPU disappears from fitting and automatic placement even though the previous torch-only path enumerated it. Accept the amd-smi result only when it covers every visible device, or use the fallback to fill incomplete results.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same as above: fd0348c landed before this review. The arch gate is shared through _rocm_arch_gate_keep, so the amd-smi rows go through the same #7624 filter the torch path uses.

danielhanchen added a commit that referenced this pull request Aug 13, 2026
…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}.
@danielhanchen

Copy link
Copy Markdown
Member Author

Two more defects closed in fd0348c9a, both about this branch answering in the wrong index space or for the wrong set of devices.

amd-smi ids are not HIP ids. I had been keying rows by amd-smi "gpu", which AMD documents as an enumeration index in discovery order over amd-smi own KFD view, and then comparing that number directly against HIP_VISIBLE_DEVICES tokens and using it to pin the child. In amdsmi own source (src/amd_smi/amd_smi.cc:753) the HIP id is derived differently: info->hip_id = kfd_info.node_id - smallest_node_id. Agreement is a coincidence, not a guarantee, which is why AMD ships amd-smi list -e whose stated purpose is mapping physical to logical GPU ids, and why AMD documents MI350X in SPX/NPS1 as a host where HIP order is not discovery order. Concretely: two cards of different capacity, the planner associates the larger card memory with the wrong HIP index, pins the smaller card, and can OOM a load that fit before this branch.

A UUID mask read as no mask. _resolve_visible_physical_ids() returns None on ValueError, and the branch tested if visible is not None, so ROCR_VISIBLE_DEVICES=GPU-<uuid> was indistinguishable from an unset mask and a deliberately hidden GPU could enter ranking and win it. The class already had _visibility_mask_is_unmappable() for exactly this distinction; this one call site was not using it.

On correlate versus decline I did both, split by whether the mapping is provable. Blanket declining would gut the branch on every multi-GPU ROCm host; blanket correlation is not available, since amd-smi list -e and amdsmi_get_gpu_enumeration_info only landed in ROCm 6.4.0 and hip_id reads N/A when the library cannot reach a device KFD node. So the branch reads AMD published mapping when it exists, treats a single enumerated card with no mask (or mask [0]) as forced identity since HIP can only be looking at that card, and declines otherwise. A single-GPU ROCm desktop keeps the context saving at any CLI version; a multi-GPU host either gets the published mapping or gets torch.

One side effect handled: an old CLI rejecting -e exits non-zero, and three of those would trip _AMD_SMI_FAILURE_LIMIT and disable amd-smi process-wide including the utilization poller, so _run_amd_smi grew count_failures = False for that probe alone.

A partial result suppressed the fallback. get_gpu_vram_mib() drops rows with total <= 0, so a host where one row cannot be sized returned only the others, and a non-empty result meant torch was never asked. With both GPUs explicitly selected and tensor parallelism on, main sees two devices and this branch saw one, so the fewer-than-2 branch silently disabled tensor parallelism. The branch now declines unless it can answer for every visible device. Worth noting the existing APU deferral does not cover this: it keys off a torch-property classification, which is orthogonal to a row amd-smi cannot size.

10 tests in test_amd_smi_hip_index_and_coverage.py, with the zero-total case built as a genuinely partial payload rather than post-processed. 8 fail before, all pass after. Across 34 ROCm and placement test files: 8 failed before (all the new ones), 3561 passed and zero failures after.

One trap worth recording for anyone else testing this area, same shape as #8662: the probe asks whether a mask is set before asking what it resolves to, so a shell CUDA_VISIBLE_DEVICES made the whole file decline. The rocm fixture now clears the three visibility vars.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit that referenced this pull request Aug 13, 2026
…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}.
@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from 593a940 to 77f1e64 Compare August 13, 2026 13:40
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto main now that #8677 has landed. Both touch ROCm APU capacity from opposite directions, so re-verified against the merged tree rather than the old base:

  • test_rocm_hip_unreachable_defers_to_torch.py, test_rocm_vram_probe_no_hip_context.py, test_amd_smi_hip_index_and_coverage.py, test_amd_apu_unified_memory.py: 101 passed.
  • Studio: stop the /api/system poll from pinning a CUDA/HIP primary context #8677's own suites on this branch (test_system_poll_no_cuda_context.py, test_amd_apu_unified_memory.py): 97 passed.
  • Simulated CPU-only CI (CUDA_VISIBLE_DEVICES=-1): 91 passed.

The two APU paths do not overlap: #8677's _rocm_props_total_is_carve_out corrects the torch properties total in utils/hardware/hardware.py, while this PR keeps the amd-smi branch from answering at all on a unified-memory APU and defers to torch there.

@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: 77f1e64ac3

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

vram = {hip_by_gpu[_g]: _v for _g, _v in vram.items()}
# amd-smi enumerates every card regardless of the mask, so drop the ones
# this process cannot see. No mask means all of them.
visible = set(mask) if mask is not None else set(hip_by_gpu.values())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep ROCR masks in ROCr index space

When ROCR_VISIBLE_DEVICES is the active numeric mask on a host where amd-smi list -e reports a non-identity amd-smi-to-HIP mapping, mask contains ROCr agent IDs but this line compares them with the HIP IDs produced above. For example, with mapping {gpu 0: HIP 1, gpu 1: HIP 0} and ROCR_VISIBLE_DEVICES=0, the torch path measures agent 0, while this branch selects the VRAM row for HIP 0 (gpu 1), so fitting can use the wrong card's capacity and subsequently pin the wrong device. Preserve the mask's source/index space, translate ROCr IDs separately, or defer this branch when a ROCR mask is active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The premise that ROCr agent index differs from HIP device index does not hold. clr/hipamd/src/hip_context.cpp builds g_devices by straight iteration over amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false) with i as the HIP ordinal, and there is no PCI-bus sort in rocdevice.cpp (unlike CUDA's default), so HIP device i is ROCr GPU agent i. ROCr's agent order is the rank of KFD topology nodes with NumFComputeCores != 0 in ascending node id (amd_topology.cpp BuildTopology), which is the same ranking amdsmi's hip_id = node_id - smallest_node_id computes. It is also unreachable as a stacked mask here: _active_gpu_visibility_mask reads ROCR only when HIP_VISIBLE_DEVICES is unset. And it is not PR-specific: _resolve_visible_physical_ids has treated ROCR entries as physical ids since before this PR, and the torch branch and _emit_child_gpu_visibility use it identically, so changing only this branch would make the two disagree. On the 96 GiB versus 16 GiB example given, the totals check added above now declines rather than misreporting.

@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from 84f0b0c to 584f92f Compare August 13, 2026 14:13
danielhanchen added a commit that referenced this pull request Aug 13, 2026
…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}.
danielhanchen added a commit that referenced this pull request Aug 13, 2026


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.
@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from 584f92f to 5f4f53a Compare August 13, 2026 14:15
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

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

Reviewed commit: 7e3080e309

ℹ️ 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 added a commit that referenced this pull request Aug 13, 2026
…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}.
@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from 7e3080e to 44609bc Compare August 13, 2026 15:43
danielhanchen added a commit that referenced this pull request Aug 13, 2026


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.
@LeoBorcherding LeoBorcherding changed the title Studio: read ROCm VRAM through amd-smi so the backend keeps no HIP context fix(amd): read ROCm VRAM through amd-smi so the backend keeps no HIP context Aug 14, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto current main (eee14f2). The branch had picked up two Merge branch 'main' commits; every commit they brought in was already in main, so the rebase drops the merge noise without losing anything. Confirmed the PR's own content is byte identical across the rewrite: all 9 changed files hash the same before and after, and the branch is now 0 behind main with the diff being exactly those 9 files.

Backend suite on the rebased head: 121 passed, and 121 passed again under CUDA_VISIBLE_DEVICES=-1, so the fixtures declare HIP's inventory rather than inheriting the host's.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: eee14f2b3e

ℹ️ 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 added a commit that referenced this pull request Aug 14, 2026
…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}.
danielhanchen added a commit that referenced this pull request Aug 14, 2026


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.
@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from eee14f2 to d421f29 Compare August 14, 2026 07:24
danielhanchen added a commit that referenced this pull request Aug 14, 2026
…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}.
danielhanchen added a commit that referenced this pull request Aug 14, 2026


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.
@danielhanchen
danielhanchen force-pushed the studio/hardware-probe-no-cuda-context branch from d421f29 to 304a0ea Compare August 14, 2026 12:31

@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: 304a0eacda

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

None means "not provable", and the branch then defers to torch, which
enumerates in HIP's space by construction.
"""
if len(enumerated) == 1 and mask in (None, [0]):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Verify the inventory before assuming HIP device 0

When amd-smi metric skips all but one row on a multi-GPU host and the active mask is unset or [0], this shortcut treats the surviving row as proof that the host has one card and remaps it to HIP 0 without consulting list -e. If the surviving row is actually another card, the later coverage and HIP-count checks can still pass—especially with equal-total cards—so fitting uses the wrong GPU's free memory and may overcommit the selected device. Fresh evidence beyond the earlier partial-result report is this current singleton shortcut, which bypasses the newly added completeness mapping precisely when a partial response has one row.

Useful? React with 👍 / 👎.

danielhanchen and others added 8 commits August 14, 2026 12:40
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.
…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}.
…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.
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.


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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e6806cc921

ℹ️ 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 added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 14, 2026
@danielhanchen
danielhanchen merged commit 300292b into main Aug 14, 2026
12 of 55 checks passed
@danielhanchen
danielhanchen deleted the studio/hardware-probe-no-cuda-context branch August 14, 2026 12:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant