Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han8264e80dd952
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 800d7fdd8c8..35ef90ee37a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -549,14 +549,24 @@ class LlamaCppBackend:
@staticmethod
def _get_gpu_free_memory() -> list[tuple[int, int]]:
- """Query free memory per GPU via nvidia-smi.
-
- Returns list of (gpu_index, free_mib) sorted by index.
- Respects CUDA_VISIBLE_DEVICES if set.
- Returns empty list if nvidia-smi is not available.
+ """Query free memory per GPU.
+
+ Order:
+ 1. ``nvidia-smi`` (NVIDIA CUDA hosts) -- respects
+ ``CUDA_VISIBLE_DEVICES``.
+ 2. ``torch.cuda.mem_get_info`` -- universal fallback that
+ works on AMD ROCm too because the HIP runtime
+ reuses the entire ``torch.cuda.*`` namespace. Covers the
+ AMD case for issue #5106 (nvidia-smi-only probe silently
+ returned [] on AMD hosts) and also rescues NVIDIA hosts
+ where ``nvidia-smi`` is missing from PATH.
+
+ Returns list of (gpu_index, free_mib) sorted by index. Empty
+ list if no supported GPU is reachable.
"""
import os
+ # ── NVIDIA via nvidia-smi ────────────────────────────────────
try:
result = subprocess.run(
[
@@ -569,30 +579,95 @@ class LlamaCppBackend:
timeout = 10,
**_windows_hidden_subprocess_kwargs(),
)
- if result.returncode != 0:
- return []
+ if result.returncode == 0:
+ allowed: Optional[set[int]] = None
+ cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
+ if cvd is not None:
+ try:
+ # `if x.strip()` filters trailing-comma masks like
+ # "0,1," which would otherwise raise ValueError on
+ # an empty token. An explicitly empty mask (CVD="")
+ # yields an empty `allowed` set so all GPUs are
+ # filtered out, matching the codebase convention.
+ 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))
+ # Match the docstring's sort-by-id guarantee. nvidia-smi
+ # almost always returns sorted output, but driver order
+ # is not formally guaranteed.
+ gpus.sort(key = lambda g: g[0])
+ if gpus:
+ return gpus
+ except Exception as e:
+ logger.debug(f"nvidia-smi probe failed: {e}")
- # Parse which GPUs are allowed by existing CUDA_VISIBLE_DEVICES
- allowed = None
- cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
- if cvd is not None and cvd.strip():
+ # ── Torch fallback (covers AMD ROCm and missing nvidia-smi) ──
+ try:
+ import torch
+
+ if not hasattr(torch, "cuda") or not torch.cuda.is_available():
+ return []
+ if not hasattr(torch.cuda, "mem_get_info"):
+ return []
+ # torch.cuda enumerates GPUs RELATIVE to the visibility mask.
+ # On NVIDIA builds the mask is CUDA_VISIBLE_DEVICES; on AMD
+ # ROCm builds it is HIP_VISIBLE_DEVICES (or ROCR_VISIBLE_DEVICES
+ # if HIP is unset). Downstream we feed these IDs back into the
+ # llama-server subprocess as CVD, so we must translate visible
+ # ordinals back to physical indices first; otherwise launching
+ # with ``CUDA_VISIBLE_DEVICES=2,3`` would get rewritten to
+ # ``CUDA_VISIBLE_DEVICES=0,1`` and target the wrong GPUs.
+ physical_ids: Optional[list[int]] = None
+ # Match the codebase convention in
+ # ``utils/hardware/hardware.py::_get_parent_visible_gpu_spec``:
+ # treat an explicitly empty mask (``HIP_VISIBLE_DEVICES=""``)
+ # as "set to no GPUs" rather than falling through to the next
+ # var. ``or`` would coerce empty string to falsy and silently
+ # promote the wrong source.
+ if getattr(torch.version, "hip", None) is not None:
+ hip_v = os.environ.get("HIP_VISIBLE_DEVICES")
+ rocr_v = os.environ.get("ROCR_VISIBLE_DEVICES")
+ cvd = (
+ hip_v
+ if hip_v is not None
+ else rocr_v
+ if rocr_v is not None
+ else os.environ.get("CUDA_VISIBLE_DEVICES")
+ )
+ else:
+ cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
+ if cvd is not None:
try:
- allowed = set(int(x.strip()) for x in cvd.split(","))
+ # Empty mask (CVD="") yields an empty list so the
+ # below loop produces no GPUs, consistent with the
+ # nvidia-smi path and utils/hardware/hardware.py.
+ physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
except ValueError:
- pass # Non-numeric (e.g., "GPU-uuid"), ignore filter
-
+ physical_ids = None
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))
- return 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)))
+ # Match the nvidia-smi path's docstring guarantee of sorted-by-id.
+ return sorted(gpus, key = lambda g: g[0])
except Exception as e:
- logger.debug(f"Failed to query GPU free memory via nvidia-smi: {e}")
+ logger.debug(f"torch GPU probe failed: {e}")
return []
@staticmethod
@@ -1756,9 +1831,23 @@ class LlamaCppBackend:
f"{new_ld}:{existing_ld}" if existing_ld else new_ld
)
- # Pin to selected GPU(s) via CUDA_VISIBLE_DEVICES
+ # Pin to selected GPU(s). On ROCm, llama-server (and any torch
+ # in the subprocess) honors HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES;
+ # narrowing only CUDA_VISIBLE_DEVICES leaves an AMD child seeing
+ # the full HIP/ROCR set the parent inherited.
if gpu_indices is not None:
- env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_indices)
+ pinned = ",".join(str(i) for i in gpu_indices)
+ env["CUDA_VISIBLE_DEVICES"] = pinned
+ 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(
+ "Failed to set ROCm visibility env vars for child: %s", e
+ )
# Defensive kill: if a concurrent load slipped past Phase 1
# (because its `self._process` was None at the time) and