Skip to content

Studio: probe AMD GPUs in llama-server VRAM detection - #5172

Merged
danielhanchen merged 10 commits into
mainfrom
dh/fix-5106-amd-gpu-probe
Apr 24, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
dh/fix-5106-amd-gpu-probe

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Apr 24, 2026 •

Copy link
Copy Markdown
Member

Addresses #5106.

Problem

_get_gpu_free_memory in studio/backend/core/inference/llama_cpp.py only queries nvidia-smi. On AMD ROCm hosts that returns nothing, so the GPU list is empty, the auto-fit logic falls into the no-gpus branch, and llama-server gets --fit on with no -ngl to anchor it. The model loads on CPU even though Studio's hardware probe (which uses amd-smi) detected the GPU correctly elsewhere.

This is asymmetric with the rest of Studio: install.sh already detects AMD via rocminfo / amd-smi and installs torch with ROCm wheels (rocm6.0 through rocm7.2), and studio/backend/utils/hardware/amd.py has full amd-smi JSON-based monitoring. Only the llama-server VRAM probe was NVIDIA-only.

Fix

Add a torch-based fallback that runs after nvidia-smi fails or returns empty:

import torch
if torch.cuda.is_available() and hasattr(torch.cuda, "mem_get_info"):
    for ordinal in range(torch.cuda.device_count()):
        free, _total = torch.cuda.mem_get_info(ordinal)
        gpus.append((ordinal, free // (1024 * 1024)))

Works on AMD because the ROCm torch wheels Studio installs reuse the entire torch.cuda.* namespace via HIP. Also rescues NVIDIA hosts where nvidia-smi is missing from PATH (a secondary cause of the bug on Windows). Matches the convention studio/backend/utils/hardware/hardware.py:412 already uses for the same fallback purpose.

Verified

  • NVIDIA path returns the expected GPU and free MiB.
  • Torch fallback returns valid VRAM when nvidia-smi is forced to fail.
  • AMD path is the same code; HIP routes through torch.cuda.* so the same query works on ROCm hosts.

Related

#4874 is a draft taking a different approach (parsing vulkaninfo output). Complementary, not conflicting: this PR covers the AMD-with-ROCm-torch and missing-nvidia-smi cases via the existing torch dependency; #4874 covers Intel ARC and other Vulkan-only hardware. Either or both can land.

Test plan

  • On an AMD host, load a GGUF in Studio chat and confirm llama-server is launched with a non-empty -ngl based on the detected VRAM.
  • On an NVIDIA host with nvidia-smi removed from PATH, repeat the above to confirm the torch fallback kicks in.
  • On an NVIDIA host with nvidia-smi present, confirm the existing path still returns the same physical GPU index and free MiB.

_get_gpu_free_memory in studio/backend/core/inference/llama_cpp.py
only queried nvidia-smi. On AMD ROCm hosts that returns nothing, so
the GPU list is empty, the auto-fit logic falls into the no-gpus
branch, and llama-server gets --fit on with no -ngl to anchor it.
The model loads on CPU even though the GPU is detected elsewhere in
Studio. Addresses #5106.

Add a torch-based fallback that runs after nvidia-smi fails or returns
empty:

    import torch
    if torch.cuda.is_available() and hasattr(torch.cuda, "mem_get_info"):
        for ordinal in range(torch.cuda.device_count()):
            free, _total = torch.cuda.mem_get_info(ordinal)
            gpus.append((ordinal, free // (1024 * 1024)))

Works on AMD because the ROCm torch wheels Studio installs reuse the
entire torch.cuda.* namespace via HIP. Also rescues NVIDIA hosts
where nvidia-smi is missing from PATH (a secondary cause of the bug
on Windows). Matches the convention
studio/backend/utils/hardware/hardware.py:412 already uses for the
same fallback purpose.

Verified locally: nvidia-smi path returns the expected GPU and free
MiB; torch fallback returns valid VRAM when nvidia-smi is forced to
fail. Note: PR #4874 is a draft taking a different approach
(parsing vulkaninfo); the two are complementary.

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

ℹ️ 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 +613 to +615
for ordinal in range(torch.cuda.device_count()):
free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
gpus.append((ordinal, int(free_bytes // (1024 * 1024))))

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 CUDA_VISIBLE_DEVICES mapping in torch fallback

When nvidia-smi is unavailable, this fallback records ordinal values from torch.cuda.device_count() as GPU IDs, but those ordinals are relative to the current CUDA_VISIBLE_DEVICES mask, not global device indices. Downstream, these IDs are used to rewrite CUDA_VISIBLE_DEVICES, so a process started with something like CUDA_VISIBLE_DEVICES=2,3 can be remapped to 0,1 and launch on the wrong GPU(s) or violate scheduler pinning. Please translate ordinals back through the existing mask (when present) before returning IDs, or avoid rewriting the mask in this path.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances the _get_gpu_free_memory method by introducing a torch.cuda fallback, ensuring compatibility with AMD ROCm and environments where nvidia-smi is unavailable. Feedback indicates a logic error in the fallback implementation where relative device ordinals are returned instead of physical indices when CUDA_VISIBLE_DEVICES is active, which could cause incorrect GPU selection in child processes. A redundant integer cast was also identified.

Comment on lines +611 to +615
return []
gpus = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
for ordinal in range(torch.cuda.device_count()):
free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
gpus.append((ordinal, int(free_bytes // (1024 * 1024))))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The torch fallback returns relative ordinals (0, 1, ...) which do not match physical indices if CUDA_VISIBLE_DEVICES is set in the environment. This will cause the wrong GPU to be selected for the subprocess. For example, if CUDA_VISIBLE_DEVICES="1", torch.cuda.device_count() is 1, and the loop returns index 0. Setting CUDA_VISIBLE_DEVICES="0" for the child process would then incorrectly target physical GPU 0 instead of physical GPU 1.

Additionally, the int() cast is redundant as floor division (//) between integers already returns an integer.

            gpus = []
            cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
            physical_ids = None
            if cvd and cvd.strip():
                try:
                    physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
                except ValueError:
                    pass

            for ordinal in range(torch.cuda.device_count()):
                free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
                # Map relative ordinal back to physical index if CVD is set
                idx = physical_ids[ordinal] if physical_ids and ordinal < len(physical_ids) else ordinal
                gpus.append((idx, free_bytes // (1024 * 1024)))
            return gpus
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

danielhanchen and others added 2 commits April 24, 2026 14:18
torch.cuda.device_count() enumerates GPUs RELATIVE to the current
CUDA_VISIBLE_DEVICES (or HIP_VISIBLE_DEVICES on ROCm). Returning
those visible ordinals directly lets _select_gpus rewrite
CUDA_VISIBLE_DEVICES with the wrong physical IDs: a process started
with CUDA_VISIBLE_DEVICES=2,3 would get its child llama-server
relaunched with CUDA_VISIBLE_DEVICES=0,1, targeting the wrong GPUs
and violating any scheduler pinning.

Translate visible ordinals back through the active CVD/HIP/ROCR
mask before returning. Falls through to bare ordinal when no mask
is set. Also drop the redundant int() cast on // -- bytes // 2**20
already returns int.

Verified: with CUDA_VISIBLE_DEVICES=6 and nvidia-smi forced to fail,
the torch fallback now returns (6, free_mib) instead of (0, free_mib).

@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: 6e94603754

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

idx = (
physical_ids[ordinal]
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal

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 UUID/MIG masks when torch fallback cannot map IDs

When the visibility mask uses UUID/MIG tokens (for example CUDA_VISIBLE_DEVICES=GPU-...) and the code falls back to torch, physical_ids is unset and this branch returns relative ordinals. Those ordinals are later fed back into CUDA_VISIBLE_DEVICES for the llama-server subprocess, which can remap execution onto the wrong GPUs and break scheduler pinning. Fresh evidence versus the earlier numeric-mask fix: non-numeric masks still fall through to ordinal IDs here.

Useful? React with 👍 / 👎.

Comment on lines +621 to +623
os.environ.get("CUDA_VISIBLE_DEVICES")
or os.environ.get("HIP_VISIBLE_DEVICES")
or os.environ.get("ROCR_VISIBLE_DEVICES")

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 Prefer HIP/ROCR visibility envs before CUDA on ROCm

This fallback resolves device mapping from CUDA_VISIBLE_DEVICES before HIP_VISIBLE_DEVICES/ROCR_VISIBLE_DEVICES, which conflicts with the repo’s own ROCm visibility precedence in utils/hardware/hardware.py (_get_parent_visible_gpu_spec). On AMD systems where both env vars exist but differ, torch enumerates with HIP/ROCR semantics while this code labels ordinals using CUDA values, so returned GPU IDs can be incorrect and downstream pinning may target unintended devices.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 24, 2026 15:50
Two reviewer-flagged correctness bugs in the AMD GPU probe path.

1) ROCm visibility precedence was reversed. torch.cuda enumerates GPUs
   relative to HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES on ROCm builds,
   but the probe's env-var lookup checked CUDA_VISIBLE_DEVICES first. With
   CUDA_VISIBLE_DEVICES=0,1 and HIP_VISIBLE_DEVICES=6,7 the probe returned
   [(0, ...), (1, ...)] when torch's view was actually [(6, ...), (7, ...)].
   The wrong physical IDs flowed downstream into CUDA_VISIBLE_DEVICES for
   the llama-server subprocess, pinning it to GPUs 0,1 instead of 6,7.

   Fix: branch on torch.version.hip. On ROCm, prefer HIP > ROCR > CUDA
   (matches torch's own ordering). On NVIDIA, use CUDA only -- ignoring
   any HIP/ROCR vars the parent happens to have set.

2) Child env narrowing only set CUDA_VISIBLE_DEVICES. On ROCm, llama-server
   honors HIP/ROCR; if the parent shell exported HIP_VISIBLE_DEVICES=4,5
   and the selector picked just GPU 4, the child still saw both because
   we never narrowed HIP/ROCR. Now we set all three on ROCm so the AMD
   subprocess actually sees the planned subset.

Both branches verified via temp/pr_simulation/sim_5172_rocm_precedence.py
(7/7 cases pass), including the reviewer's verbatim R5 case
(CVD=0,1 + HIP/ROCR=6,7).
@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@danielhanchen

Copy link
Copy Markdown
Member Author

Thanks for the careful review. Pushed eff55fb addressing the two highest-impact findings:

Fixed: ROCm visibility precedence reversed (4/5 reviewers)

The probe now branches on torch.version.hip. On ROCm it prefers HIP_VISIBLE_DEVICES > ROCR_VISIBLE_DEVICES > CUDA_VISIBLE_DEVICES (matching what torch.cuda.device_count() actually enumerates). On NVIDIA it uses CUDA_VISIBLE_DEVICES only and ignores any HIP/ROCR vars the parent inherited. The reviewer R5 case (CVD=0,1 + HIP/ROCR=6,7) now correctly returns [(6, 9216), (7, 7168)] instead of [(0, ...), (1, ...)].

Fixed: child env narrowing only set CUDA_VISIBLE_DEVICES (2/5 reviewers)

On ROCm the subprocess now also gets HIP_VISIBLE_DEVICES and ROCR_VISIBLE_DEVICES set to the selected pin. The previous code left an AMD child seeing the wider HIP/ROCR set the parent inherited.

Verified via temp/pr_simulation/sim_5172_rocm_precedence.py (7/7 cases pass), including the verbatim R5 scenario.

Deferred: non-numeric UUID/MIG visibility masks (3/5 reviewers)

I'd like to leave this one for a follow-up. UUID-style masks are almost exclusively a MIG-partitioned A100/H100 datacenter feature; the AMD/consumer audience this PR targets effectively never sees them. The right fix is broader than the probe -- selector and child-env codepaths also need to learn to round-trip UUIDs. Happy to take it as a separate PR if you want.

@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: 56c95c69fb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

Comment on lines +623 to +625
os.environ.get("HIP_VISIBLE_DEVICES")
or os.environ.get("ROCR_VISIBLE_DEVICES")
or os.environ.get("CUDA_VISIBLE_DEVICES")

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 Preserve empty ROCm visibility masks in torch fallback

In _get_gpu_free_memory, the ROCm branch uses os.environ.get("HIP_VISIBLE_DEVICES") or ... to pick a mask, which treats an explicitly empty HIP_VISIBLE_DEVICES/ROCR_VISIBLE_DEVICES as unset and falls through to CUDA_VISIBLE_DEVICES (studio/backend/core/inference/llama_cpp.py lines 623-625). That diverges from the repo’s own ROCm visibility handling (see _get_parent_visible_gpu_spec in studio/backend/utils/hardware/hardware.py) where empty values are meaningful, and it can mislabel ordinals with the wrong physical IDs when env vars differ, leading to incorrect downstream GPU pinning.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances GPU memory detection by adding a torch.cuda fallback to the existing nvidia-smi probe, which enables support for AMD ROCm and environments where nvidia-smi is missing. It also updates the model loading logic to correctly set ROCm-specific environment variables for GPU pinning. A review comment identified that the new fallback path fails to sort the GPU list by index as specified in the docstring, and provided a suggestion to fix this.

Comment on lines 634 to 643
gpus = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
for ordinal in range(torch.cuda.device_count()):
free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
idx = (
physical_ids[ordinal]
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal
)
gpus.append((idx, free_bytes // (1024 * 1024)))
return gpus

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The torch fallback path does not guarantee that the returned list of GPUs is sorted by index, which violates the method's docstring. If CUDA_VISIBLE_DEVICES (or its ROCm equivalents) is set to a non-sequential or reversed list of indices (e.g., "1,0"), the physical_ids mapping will produce a list in that same order. While _select_gpus performs its own sorting by free memory, it is better to maintain consistency with the docstring and the nvidia-smi path by explicitly sorting the result.

Suggested change
gpus = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
for ordinal in range(torch.cuda.device_count()):
free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
idx = (
physical_ids[ordinal]
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal
)
gpus.append((idx, free_bytes // (1024 * 1024)))
return gpus
gpus = []
for ordinal in range(torch.cuda.device_count()):
free_bytes, _total_bytes = torch.cuda.mem_get_info(ordinal)
idx = (
physical_ids[ordinal]
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal
)
gpus.append((idx, free_bytes // (1024 * 1024)))
return sorted(gpus, key = lambda x: x[0])

Two reviewer-flagged correctness nits on top of eff55fb.

1) Gemini medium: the torch fallback returned an unsorted list when the
   visibility mask was non-sequential (e.g. CUDA_VISIBLE_DEVICES=5,2,9),
   diverging from the docstring guarantee and the nvidia-smi path. Now
   sorted by physical id.

2) Codex P2: an explicitly empty HIP_VISIBLE_DEVICES="" should mean
   "no GPUs" per the codebase convention in
   utils/hardware/hardware.py::_get_parent_visible_gpu_spec. The previous
   `or` chain treated empty string as falsy and silently fell through to
   ROCR / CUDA, producing wrong physical IDs. Switch to `is not None`
   checks to match.

Verified via sim_5172_rocm_precedence.py (9/9 cases pass) including the
two new R8 (sort) and R9 (empty-HIP honored) cases.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 6b1cccd addressing the two follow-up correctness nits:

Fixed: torch fallback returned unsorted list (Gemini medium)

The nvidia-smi path returns sorted-by-id; the torch fallback didn't, which violates the docstring and produces a CUDA_VISIBLE_DEVICES=5,2,9 -> [(5,...), (2,...), (9,...)] shape that's confusing to downstream _select_gpus. Now sorted(gpus, key=lambda g: g[0]).

Fixed: empty HIP_VISIBLE_DEVICES="" was falsy-skipped (Codex P2)

The or chain coerced an explicitly empty mask to "fall through to the next env var", which conflicts with the codebase convention in utils/hardware/hardware.py::_get_parent_visible_gpu_spec (lines 603-607) where empty values are honored as "no GPUs". Switched to is not None checks. Now HIP_VISIBLE_DEVICES="" together with CUDA_VISIBLE_DEVICES="3,4" yields ordinal-fallback ids, not the misleading [(3,...), (4,...)].

Verified via the same sim (now 9/9 cases pass with the two new R8 + R9 cases).

Still deferred: UUID/MIG masks (Codex P1, repeated)

This stays in a follow-up. The probe never claimed to handle UUID-format masks, so it's a missing feature rather than a regression. The right fix needs the selector and child-env codepaths to round-trip the UUIDs unchanged, which is broader than this PR. AMD/consumer audience effectively never sees UUID masks (they're a MIG-partitioned datacenter feature). Happy to take it as a separate PR.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances GPU memory detection in llama_cpp.py by implementing a torch fallback mechanism, which provides support for AMD ROCm and environments where nvidia-smi is unavailable. Additionally, it updates the model loading logic to correctly pin GPUs on ROCm systems by setting HIP_VISIBLE_DEVICES and ROCR_VISIBLE_DEVICES. Feedback was provided to improve the robustness of environment variable parsing and ensure consistent sorting in the nvidia-smi path to match the new fallback implementation.

Comment on lines +582 to +600
if result.returncode == 0:
allowed: Optional[set[int]] = None
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None and cvd.strip():
try:
allowed = set(int(x.strip()) for x in cvd.split(","))
except ValueError:
pass
gpus: list[tuple[int, int]] = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
if gpus:
return gpus

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The nvidia-smi path has two issues regarding robustness and consistency with the new torch fallback:

  1. Fragile CVD Parsing: The cvd.split(",") call is susceptible to ValueError if the environment variable contains trailing commas (e.g., "0,1,"), which results in the filter being silently ignored. The torch path at line 641 correctly handles this using if x.strip().
  2. Missing Sort: The docstring at line 564 guarantees a list sorted by index, but this path returns the results in the order provided by nvidia-smi. While usually sorted, an explicit sorted() call (matching line 654) ensures the guarantee is met regardless of driver enumeration order.

I suggest applying the same robust parsing and sorting logic used in the fallback path.

Suggested change
if result.returncode == 0:
allowed: Optional[set[int]] = None
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None and cvd.strip():
try:
allowed = set(int(x.strip()) for x in cvd.split(","))
except ValueError:
pass
gpus: list[tuple[int, int]] = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
if gpus:
return gpus
if result.returncode == 0:
allowed: Optional[set[int]] = None
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None and cvd.strip():
try:
allowed = set(int(x.strip()) for x in cvd.split(",") if x.strip())
except ValueError:
pass
gpus: list[tuple[int, int]] = []
for line in result.stdout.strip().splitlines():
parts = line.split(",")
if len(parts) == 2:
idx = int(parts[0].strip())
free_mib = int(parts[1].strip())
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
if gpus:
return sorted(gpus, key = lambda g: g[0])

Two follow-up Gemini-medium nits on PR #5172.

1) Fragile CVD parsing on the nvidia-smi path: `cvd.split(",")` would
   raise ValueError on a trailing comma like "0,1," because the empty
   trailing token is not skipped. The torch fallback already filters
   empty tokens via `if x.strip()`; mirror that here.

2) Missing sort guarantee on the nvidia-smi path: the docstring promises
   sort-by-id, the torch fallback now sorts, but the nvidia-smi path
   relied on driver enumeration order. Add an explicit sort.

Both changes match what shipped in 6b1cccd for the torch fallback, so
the two probe paths now have identical CVD parsing + ordering semantics.

@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: 95315e5d35

ℹ️ 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 571 to 572
result = subprocess.run(
[

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 Gate nvidia-smi probe behind non-ROCm runtime

In _get_gpu_free_memory, the NVIDIA probe is always attempted first and returned when it succeeds, even on ROCm builds. On mixed AMD+NVIDIA hosts (or any ROCm environment where nvidia-smi is present), this can make GPU selection use NVIDIA VRAM data, but later load_model pins HIP_VISIBLE_DEVICES/ROCR_VISIBLE_DEVICES from those selected IDs, so HIP may be pinned to unintended AMD devices (or to devices with insufficient memory), leading to mis-selection or failed launches. The probe order should be conditioned on runtime/backend (e.g., skip nvidia-smi when torch.version.hip is active).

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 95315e5 aligning the nvidia-smi probe with the torch fallback.

Fixed: fragile CVD parsing on nvidia-smi path (Gemini medium)

cvd.split(",") would raise ValueError on a trailing-comma mask like "0,1,". The torch fallback already filters empty tokens via if x.strip(); mirrored that filter here so both paths handle the same masks.

Fixed: missing sort guarantee on nvidia-smi path (Gemini medium)

The docstring promises sorted-by-id and the torch fallback now sorts (6b1cccd), but the nvidia-smi path was relying on driver enumeration order. Added an explicit gpus.sort(key=lambda g: g[0]) so the two probe paths have identical ordering semantics.

Both changes are tiny and bring the two probe paths to parity.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances GPU memory detection by introducing a torch-based fallback, which extends support to AMD ROCm environments and systems where nvidia-smi is unavailable. It also improves GPU isolation by correctly setting HIP and ROCR environment variables when pinning devices for model loading. Review feedback identified two instances where checking for an empty visibility mask using .strip() would incorrectly default to showing all GPUs instead of none; suggestions were provided to ensure an empty string is correctly interpreted as an empty set of devices.

if result.returncode == 0:
allowed: Optional[set[int]] = None
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None and cvd.strip():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The cvd.strip() check incorrectly treats an explicitly empty CUDA_VISIBLE_DEVICES="" as if the variable were unset, causing the function to return all physical GPUs instead of an empty list. Removing the .strip() check allows the logic to correctly produce an empty allowed set, which filters out all devices. This aligns with the behavior in utils/hardware/hardware.py.

Suggested change
if cvd is not None and cvd.strip():
if cvd is not None:

)
else:
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None and cvd.strip():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Similar to the nvidia-smi path, the .strip() check here prevents an explicitly empty visibility mask (like HIP_VISIBLE_DEVICES="") from being correctly interpreted as "no GPUs". While torch.cuda.is_available() usually guards this, removing the .strip() check ensures that physical_ids is correctly initialized to an empty list, providing a consistent and robust fallback.

Suggested change
if cvd is not None and cvd.strip():
if cvd is not None:

Reviewer-flagged correctness bug. The previous `if cvd is not None and
cvd.strip():` guard treated `CUDA_VISIBLE_DEVICES=""` as if the variable
were unset, leaving `allowed=None` (and `physical_ids=None` on the torch
path). On the nvidia-smi path that mattered: nvidia-smi ignores CVD
entirely, so the probe's `allowed` filter is the only thing that
respects the parent's "no GPUs" intent. Pre-fix the probe returned every
physical GPU when the parent had explicitly hidden them.

Drop the `.strip()` truthiness check on both paths. The downstream
`if x.strip()` token filter still keeps trailing-comma masks like
"0,1," safe, and an empty mask now produces an empty allowed/physical
set as expected (matching utils/hardware/hardware.py convention).

Verified via sim_5172_rocm_precedence.py R10 + R11 (now 11/11 cases
pass): nvidia-smi path with `CUDA_VISIBLE_DEVICES=""` now returns []
instead of leaking the hidden GPUs.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed a6723ec addressing both findings from the latest review.

Fixed: nvidia-smi path leaks hidden GPUs when CUDA_VISIBLE_DEVICES=""

Real bug. nvidia-smi ignores CVD entirely, so the probe's allowed set is the only filter that respects an explicitly empty mask. The previous cvd.strip() truthiness short-circuited that filter, leaving allowed=None and returning every physical GPU when the parent had deliberately hidden them.

Fixed: torch fallback the same way for consistency

torch.cuda.is_available() already returns False for an empty CVD on most builds, but on ROCm builds where HIP/ROCR is the source of truth, the torch path could still reach the parsing branch. Dropped the .strip() truthiness check there too so both paths have identical semantics.

The downstream if x.strip() token filter still keeps trailing-comma masks like "0,1," safe.

Verified via the same sim. New cases:

  • R10: torch fallback with empty CVD - returns ordinal-fallback (torch device_count owns visibility)
  • R11: nvidia-smi path with CUDA_VISIBLE_DEVICES="" - now returns [] instead of leaking 3 GPUs

Sim is now 11/11 pass.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request improves GPU memory detection and environment variable management to support both NVIDIA and AMD ROCm hardware. It updates _get_gpu_free_memory to use torch.cuda.mem_get_info as a fallback when nvidia-smi is unavailable and ensures that HIP_VISIBLE_DEVICES and ROCR_VISIBLE_DEVICES are correctly set when pinning GPUs in ROCm environments. A review comment suggests logging exceptions instead of using a silent pass when setting these environment variables to improve debuggability.

Comment on lines +1831 to +1838
try:
import torch as _torch

if getattr(_torch.version, "hip", None) is not None:
env["HIP_VISIBLE_DEVICES"] = pinned
env["ROCR_VISIBLE_DEVICES"] = pinned
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The exception handler here is broad and silent. While it's appropriate to prevent a crash if torch is missing or if the ROCm check fails, it's a best practice to log the exception at a debug level to aid in troubleshooting hardware-specific issues. This aligns with the general rule to avoid broad, silent exception handlers.

Suggested change
try:
import torch as _torch
if getattr(_torch.version, "hip", None) is not None:
env["HIP_VISIBLE_DEVICES"] = pinned
env["ROCR_VISIBLE_DEVICES"] = pinned
except Exception:
pass
try:
import torch as _torch
if getattr(_torch.version, "hip", None) is not None:
env["HIP_VISIBLE_DEVICES"] = pinned
env["ROCR_VISIBLE_DEVICES"] = pinned
except Exception as e:
logger.debug(f"Failed to set ROCm visibility environment variables: {e}")
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

Reviewer-flagged defensive logging gap. The bare `except Exception: pass`
around the HIP/ROCR env-var assignment would mask anything from a
missing torch import to an unexpected version object shape. Log at
debug so a failed AMD child-env narrowing is at least traceable.
Behavior is unchanged: torch missing or version probe failing still
leaves the child with only CUDA_VISIBLE_DEVICES set.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 4896760. The bare except Exception: pass around the HIP/ROCR env-var assignment now logs at debug, matching the same defensive-logging change just made on PR #5069. Behavior is unchanged: torch missing or the version probe failing still leaves the child with only CUDA_VISIBLE_DEVICES set.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances GPU memory detection and environment variable management to support AMD ROCm and improve robustness on NVIDIA systems. It updates _get_gpu_free_memory to include a torch.cuda fallback when nvidia-smi is unavailable and ensures correct mapping of visible device ordinals to physical indices. Additionally, it now sets HIP_VISIBLE_DEVICES and ROCR_VISIBLE_DEVICES when pinning GPUs for subprocesses on ROCm platforms. I have no feedback to provide.

@danielhanchen
danielhanchen merged commit 8264e80 into main Apr 24, 2026
6 checks passed
@danielhanchen
danielhanchen deleted the dh/fix-5106-amd-gpu-probe branch April 24, 2026 17:00
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