Repository navigation
Studio: probe AMD GPUs in llama-server VRAM detection - #5172
Conversation
_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.
There was a problem hiding this comment.
💡 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".
| 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)))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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)))) |
There was a problem hiding this comment.
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 gpusReferences
- To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.
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).
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| os.environ.get("CUDA_VISIBLE_DEVICES") | ||
| or os.environ.get("HIP_VISIBLE_DEVICES") | ||
| or os.environ.get("ROCR_VISIBLE_DEVICES") |
There was a problem hiding this comment.
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 👍 / 👎.
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).
|
/gemini review |
|
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 Fixed: child env narrowing only set CUDA_VISIBLE_DEVICES (2/5 reviewers) On ROCm the subprocess now also gets Verified via 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. |
There was a problem hiding this comment.
💡 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".
| os.environ.get("HIP_VISIBLE_DEVICES") | ||
| or os.environ.get("ROCR_VISIBLE_DEVICES") | ||
| or os.environ.get("CUDA_VISIBLE_DEVICES") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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.
|
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 Fixed: empty The 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. |
|
/gemini review |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
The nvidia-smi path has two issues regarding robustness and consistency with the new torch fallback:
- Fragile CVD Parsing: The
cvd.split(",")call is susceptible toValueErrorif the environment variable contains trailing commas (e.g.,"0,1,"), which results in the filter being silently ignored. Thetorchpath at line 641 correctly handles this usingif x.strip(). - 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 explicitsorted()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.
| 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.
There was a problem hiding this comment.
💡 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".
| result = subprocess.run( | ||
| [ |
There was a problem hiding this comment.
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 👍 / 👎.
|
Pushed 95315e5 aligning the nvidia-smi probe with the torch fallback. Fixed: fragile CVD parsing on nvidia-smi path (Gemini medium)
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 Both changes are tiny and bring the two probe paths to parity. |
|
/gemini review |
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
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.
| 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(): |
There was a problem hiding this comment.
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.
| 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.
|
Pushed a6723ec addressing both findings from the latest review. Fixed: nvidia-smi path leaks hidden GPUs when Real bug. nvidia-smi ignores CVD entirely, so the probe's Fixed: torch fallback the same way for consistency
The downstream Verified via the same sim. New cases:
Sim is now 11/11 pass. |
|
/gemini review |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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
- 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.
|
/gemini review |
There was a problem hiding this comment.
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.
Addresses #5106.
Problem
_get_gpu_free_memoryinstudio/backend/core/inference/llama_cpp.pyonly queriesnvidia-smi. On AMD ROCm hosts that returns nothing, so the GPU list is empty, the auto-fit logic falls into the no-gpus branch, andllama-servergets--fit onwith no-nglto anchor it. The model loads on CPU even though Studio's hardware probe (which usesamd-smi) detected the GPU correctly elsewhere.This is asymmetric with the rest of Studio:
install.shalready detects AMD viarocminfo/amd-smiand installs torch with ROCm wheels (rocm6.0throughrocm7.2), andstudio/backend/utils/hardware/amd.pyhas fullamd-smiJSON-based monitoring. Only the llama-server VRAM probe was NVIDIA-only.Fix
Add a torch-based fallback that runs after
nvidia-smifails or returns empty:Works on AMD because the ROCm torch wheels Studio installs reuse the entire
torch.cuda.*namespace via HIP. Also rescues NVIDIA hosts wherenvidia-smiis missing from PATH (a secondary cause of the bug on Windows). Matches the conventionstudio/backend/utils/hardware/hardware.py:412already uses for the same fallback purpose.Verified
nvidia-smiis forced to fail.torch.cuda.*so the same query works on ROCm hosts.Related
#4874 is a draft taking a different approach (parsing
vulkaninfooutput). 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
llama-serveris launched with a non-empty-nglbased on the detected VRAM.nvidia-smiremoved from PATH, repeat the above to confirm the torch fallback kicks in.nvidia-smipresent, confirm the existing path still returns the same physical GPU index and free MiB.