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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(amd): read ROCm VRAM through amd-smi so the backend keeps no HIP context (#8669)
Daniel Han300292b2f0b1
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 1c1d08b3828..6f3b337465e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -1945,6 +1945,12 @@ _CTX_FIT_VRAM_FRACTION = 0.97# 0.85 MLX uses in mlx_inference.py (_configure_memory_limits); not kept in sync._APPLE_UNIFIED_MEMORY_FRACTION = 0.85+# How far amd-smi's total VRAM may sit from HIP's before the two are reporting+# different memory scopes rather than one pool (an APU carve-out against the GTT+# pool, a partition against the whole card). Same 10% margin+# utils/hardware/hardware.py::_rocm_system_wide_vram_by_index gates its overlay on.+_AMD_SMI_TOTAL_TOLERANCE = 0.10+# Flat MTP reserve, used only when GGUF dims are too sparse for the byte-accurate# reserve (_estimate_mtp_overhead_bytes). Applied to both the fit budget and pin._MTP_VRAM_RESERVE_FRAC = 0.05@@ -6006,6 +6012,368 @@ class LlamaCppBackend:rec_bytes = min(rec_bytes, available)return int(rec_bytes * _APPLE_UNIFIED_MEMORY_FRACTION)+ @staticmethod+ def _rocm_arch_gate_keep(+ binary: Optional[str], torch_mod, for_llama_server: bool+ ) -> Callable[[int], bool]:+ """Predicate over PHYSICAL ids: False for a device the installed ROCm+ prebuilt has no kernels for.++ llama-server placement only, so the free-memory rank cannot pick a GPU that+ binary cannot run (#7624: an iGPU reporting shared RAM outranks the dGPU and+ the child dies with "device kernel image is invalid"). Keeps every device off+ that path, off ROCm, on unknown coverage, and for a device with no reported+ arch. Shared by both branches of ``_get_gpu_memory`` so the amd-smi and torch+ paths cannot gate differently.+ """+ if not for_llama_server or not LlamaCppBackend._torch_is_rocm(torch_mod):+ return lambda _idx: True+ supported_archs = LlamaCppBackend._installed_llama_gfx_archs(binary)+ if supported_archs is None:+ return lambda _idx: True+ arch_by_id = LlamaCppBackend._rocm_arch_by_physical_id()++ def _keep(idx: int) -> bool:+ _base = arch_by_id.get(idx, "")+ if _base and _base not in supported_archs:+ logger.warning(+ f"Skipping GPU {idx} ({_base}): installed llama.cpp "+ f"prebuilt only covers {sorted(supported_archs)}"+ )+ return False+ return True++ return _keep++ @staticmethod+ def _rocm_hip_is_reachable() -> bool:+ """Whether HIP can actually open a device on this ROCm host.++ amd-smi reads the driver over sysfs and libdrm, HIP needs ``/dev/kfd`` and a+ matching HSA runtime, so the two disagree on a container given only+ ``/dev/dri`` and on a torch built against another ROCm: amd-smi lists the+ card and ``hipGetDeviceCount`` returns 0. The llama-server child is a HIP+ process too, so answering there places a model on a device nothing can open.++ ``is_available()`` is that ``hipGetDeviceCount``, not ``_lazy_init``, so it+ creates no primary context; ``_rocm_unified_memory_gpu_ids`` already calls it+ further down the same probe. False when torch is missing or unreadable.+ """+ try:+ import torch+ return bool(hasattr(torch, "cuda") and torch.cuda.is_available())+ except Exception:+ return False++ @staticmethod+ def _rocm_hip_device_count() -> int:+ """How many devices HIP can open here, or 0 when torch cannot say.++ ``hipGetDeviceCount``, the same call ``_rocm_hip_is_reachable`` asks for a+ yes/no, so it costs no primary context either. This is the size of the+ inventory the llama-server child will see; amd-smi reads sysfs and answers+ for the whole host regardless, so the two disagree wherever something+ outside the visibility variables filters the device set (a device-cgroup+ container given one ``/dev/dri/renderD*`` node, ``GPU_DEVICE_ORDINAL``, a+ card amd-smi could not size).+ """+ try:+ import torch+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):+ return 0+ return int(torch.cuda.device_count())+ except Exception:+ return 0++ @staticmethod+ def _gpu_device_ordinal_active() -> bool:+ """Whether ``GPU_DEVICE_ORDINAL`` is filtering this process's devices.++ ROCm's fourth visibility variable, and the one nothing here reads:+ ``_active_gpu_visibility_mask`` knows the HIP, ROCR and CUDA names only, so+ ``_resolve_visible_physical_ids`` answers None ("no mask") under it. AMD+ documents it at the ROCclr layer as "devices indices exposed to OpenCL and+ HIP applications", while clr itself reads it only on the non-HIP branch+ (``rocclr/device/rocm/rocdevice.cpp`` picks HIP_VISIBLE_DEVICES /+ CUDA_VISIBLE_DEVICES when ``amd::IS_HIP``), so the two disagree on whether+ HIP honours it. Treat it as a mask either way: being wrong here costs the+ host nothing but this branch's context saving, and being wrong the other way+ offers a hidden card for placement. ``utils/hardware/hardware.py::+ _rocm_visibility_mask_active`` gates the system-wide VRAM overlay on the same+ four names. Whitespace is not a filter, matching that helper."""+ return bool(os.environ.get("GPU_DEVICE_ORDINAL", "").strip())++ @staticmethod+ def _rocm_visibility_masks_are_stacked() -> bool:+ """Whether a ROCr mask AND a HIP-layer mask are both filtering this process.++ The two sit at different layers and therefore COMPOSE: ROCR_VISIBLE_DEVICES+ filters and renumbers the agent list inside the ROCr runtime+ (``ROCR-Runtime/core/inc/amd_filter_device.h::RvdFilter``), and clr's+ ``Device::init`` then indexes ``HIP_VISIBLE_DEVICES`` (or its+ ``CUDA_VISIBLE_DEVICES`` twin) into ``gpu_agents_``, the vector+ ``hsa_iterate_agents`` just returned -- so the HIP ordinals count positions in+ what ROCr left, not physical devices. ``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 is the right answer for one layer and cannot express two: it reads+ ``[0]`` for that example, and on a host whose cards have the same total the+ inventory and total-memory cross-checks agree with it. Callers that would map+ those ids onto amd-smi's host-wide device list must decline instead. Composing+ the masks here is not an option: the physical->ROCr mapping is exactly what+ ROCr renumbered away, and guessing it wrong offers a hidden card.++ HIP and CUDA together are ONE layer, not two -- clr reads whichever is set+ first and never both -- so they do not stack. Windows has no ROCr layer at+ all, so a stray ROCR variable filters nothing there, matching+ ``_active_gpu_visibility_mask`` and ``_emit_child_gpu_visibility``. Set is+ set: an empty ROCr mask hides every agent rather than nothing."""+ if sys.platform == "win32":+ return False+ if os.environ.get("ROCR_VISIBLE_DEVICES") is None:+ return False+ return (+ os.environ.get("HIP_VISIBLE_DEVICES") is not None+ or os.environ.get("CUDA_VISIBLE_DEVICES") is not None+ )++ @staticmethod+ def _rocm_total_memory_mib_by_physical_id() -> dict[int, int]:+ """Total memory HIP reports per PHYSICAL device id, honoring the active ROCm+ mask, for cross-checking amd-smi's totals.++ Read through ``get_device_properties`` like ``_rocm_arch_by_physical_id``, so+ it costs no primary context (``mem_get_info`` is the call that does).+ Devices torch cannot describe are omitted and callers fail open on them;+ empty off ROCm and on any error."""+ totals: dict[int, int] = {}+ try:+ import torch++ if not LlamaCppBackend._torch_is_rocm(torch):+ return totals+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):+ return totals+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()+ for ordinal in range(torch.cuda.device_count()):+ try:+ total_bytes = int(+ getattr(torch.cuda.get_device_properties(ordinal), "total_memory", 0) or 0+ )+ except Exception:+ continue+ if total_bytes <= 0:+ continue+ pid = (+ physical_ids[ordinal]+ if physical_ids is not None and ordinal < len(physical_ids)+ else ordinal+ )+ totals[pid] = total_bytes // (1024 * 1024)+ except Exception:+ return totals+ return totals++ @staticmethod+ def _amd_smi_hip_id_map(+ enumerated: list[int], mask: Optional[list[int]]+ ) -> Optional[dict[int, int]]:+ """{amd-smi gpu id: HIP id} for every enumerated device, else None.++ amd-smi numbers its devices in discovery order and HIP numbers them by KFD+ node id, so the two agree on most hosts and not on all of them (MI350X in+ SPX/NPS1 among others). Every id this probe returns is fed back as a HIP+ ordinal -- matched against the visibility mask, then written into the child's+ HIP_VISIBLE_DEVICES -- so an untranslated amd-smi id pins the wrong card.++ 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]):+ # One card on the host, so HIP can only be looking at that card and its+ # id can only be 0. Keeps the single-GPU ROCm desktop, which is most of+ # them, on amd-smi even where the CLI predates the mapping below.+ return {enumerated[0]: 0}+ from utils.hardware.amd import get_hip_id_by_gpu_index++ mapping = get_hip_id_by_gpu_index()+ if mapping is None or not all(_g in mapping for _g in enumerated):+ logger.debug(+ "amd-smi VRAM probe deferring to torch: no amd-smi to HIP id mapping "+ "for this host (amd-smi list -e needs ROCm 6.4.0+)"+ )+ return None+ return mapping++ @staticmethod+ def _get_gpu_memory_amd_smi(+ binary: Optional[str] = None, *, for_llama_server: bool = False+ ) -> list[tuple[int, int, int]]:+ """ROCm free/total VRAM per PHYSICAL (HIP) gpu id via amd-smi, else ``[]``.++ Same index space and arch gate as the torch branch of ``_get_gpu_memory``,+ read from a child process instead. Reading VRAM through+ ``torch.cuda.mem_get_info`` creates a HIP primary context that the backend+ never gives back (~700 MiB measured), and the GGUF models this sizes run in a+ llama-server CHILD, so that VRAM is lost for the life of the process to+ answer a question a subprocess can answer.++ ``[]`` off ROCm and whenever amd-smi cannot answer, so the caller falls+ through to torch exactly as before. A gate that drops every card answers+ ``[]`` too, and torch then gates identically to the same empty list, so the+ one context this still costs is on the arm already headed for the CPU.+ A visible unified-memory APU answers ``[]`` as well: amd-smi sees only its+ dedicated VRAM carve-out, not the GTT pool the torch branch measures. So does+ anything it can only half answer: a subset is a non-empty list the caller+ takes as the whole host, which would drop a device from the count tensor+ parallelism is decided on.++ The inventory has to be HIP's, since the child is a HIP process: the answer+ is declined when the device set is filtered by something the mask cannot see+ (``GPU_DEVICE_ORDINAL``, a device-cgroup container), when amd-smi and HIP+ count different numbers of devices, and when they report totals far enough+ apart to be describing different memory scopes.+ """+ try:+ import torch+ if not LlamaCppBackend._torch_is_rocm(torch):+ return []+ except Exception:+ return []+ if not LlamaCppBackend._rocm_hip_is_reachable():+ # amd-smi would still list the hardware, but HIP cannot open it and+ # neither can the llama-server child. Torch answers [] here, as it did+ # before this branch existed, and the load goes to CPU.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: this ROCm torch cannot open "+ "a device, so amd-smi's inventory is not usable by llama-server"+ )+ return []+ try:+ from utils.hardware.amd import get_gpu_vram_report++ if LlamaCppBackend._visibility_mask_is_unmappable():+ # A mask IS set but names devices by UUID, so it cannot be applied+ # here. amd-smi ignores the mask itself (it reads KFD directly), so+ # answering would offer cards the parent deliberately hid. Torch sees+ # only the masked set, so let it answer.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: the GPU visibility mask "+ "is not index based, so amd-smi's device list cannot be filtered"+ )+ return []+ if LlamaCppBackend._gpu_device_ordinal_active():+ # _resolve_visible_physical_ids does not read this one, so "no mask"+ # below would be a lie wherever it does filter, and every hidden card+ # would be offered for ranking.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: GPU_DEVICE_ORDINAL is "+ "set, so amd-smi's device list cannot be filtered"+ )+ return []+ if LlamaCppBackend._rocm_visibility_masks_are_stacked():+ # A ROCr mask under a HIP mask re-indexes it, and the resolved value+ # is the HIP one alone -- ordinals into the set ROCr left, not the+ # physical ids amd-smi answers for. Every later check agrees with the+ # wrong ids on a host whose cards match, so this is the only place it+ # can be caught.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: ROCR_VISIBLE_DEVICES is "+ "stacked under a HIP-layer mask, so the visible ids are positions "+ "in the ROCr-filtered set rather than physical devices"+ )+ return []+ mask = LlamaCppBackend._resolve_visible_physical_ids()+ if mask is not None and not mask:+ return [] # every device hidden+ vram, enumerated = get_gpu_vram_report()+ if not enumerated:+ return []+ # amd-smi ids are not HIP ids; translate before anything compares them+ # against the mask or hands them to the child.+ hip_by_gpu = LlamaCppBackend._amd_smi_hip_id_map(enumerated, mask)+ if hip_by_gpu is None:+ return []+ 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())+ if not visible.issubset(vram):+ # A device that is visible and unmeasured: all or nothing.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: no usable VRAM reading "+ f"for visible GPU(s) {sorted(visible - set(vram))}"+ )+ return []+ hip_count = LlamaCppBackend._rocm_hip_device_count()+ if len(visible) != hip_count:+ # This inventory has to BE the child's. amd-smi answers for the whole+ # host off sysfs, so anything filtering devices outside the+ # visibility variables leaves it larger than HIP's: a device-cgroup+ # container given one /dev/dri/renderD* node and no env var (see+ # test_overlay_skips_device_cgroup_filtered_container) is the usual+ # one. Smaller means amd-smi omitted a card HIP can open, which the+ # single-GPU shortcut in _amd_smi_hip_id_map would otherwise read as+ # a one-card host. Either way the numbers are not comparable.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: amd-smi reports "+ f"{len(visible)} visible GPU(s) and HIP opens {hip_count}"+ )+ return []+ hip_totals = LlamaCppBackend._rocm_total_memory_mib_by_physical_id()+ disagreeing = sorted(+ _idx+ for _idx in visible+ if _idx in hip_totals+ and abs(vram[_idx][1] - hip_totals[_idx])+ > _AMD_SMI_TOTAL_TOLERANCE * hip_totals[_idx]+ )+ if disagreeing:+ # Two memory scopes, not two readings of one pool. The case that+ # matters is an APU _rocm_classify_unified_memory does not name (a+ # gfx1103 Phoenix wheel with no is_integrated flag): amd-smi sees the+ # BIOS carve-out and HIP the GTT pool, so accepting amd-smi's figure+ # would cut context or push the model to CPU. A partitioned MI300+ # reads the other way round. hardware.py::+ # _rocm_system_wide_vram_by_index gates its own overlay on the same+ # comparison. Devices torch cannot describe are absent from+ # hip_totals and fail open, so an unreadable properties call cannot+ # disable this branch wholesale.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: amd-smi and HIP report "+ f"different total memory for GPU(s) {disagreeing}"+ )+ return []+ unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids()+ if unified_ids:+ # 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 amd-smi says 8GiB and torch says ~100GiB. Handing the+ # GGUF fitter the slice would cut context or push the model to CPU.+ # utils/hardware/hardware.py::_apply_unified_memory_correction+ # adopts torch's total over amd-smi's for the System tab for the+ # same reason. Defer the WHOLE host rather than mix two memory+ # scopes: dropping only the APU would remove it from placement, and+ # the two branches of _get_gpu_memory must not disagree.+ logger.debug(+ "amd-smi VRAM probe deferring to torch: unified-memory APU(s) "+ f"{sorted(unified_ids)} report only their dedicated VRAM slice"+ )+ return []+ arch_keeps = LlamaCppBackend._rocm_arch_gate_keep(binary, torch, for_llama_server)+ gpus: list[tuple[int, int, int]] = []+ for idx in sorted(visible):+ if not arch_keeps(idx):+ continue+ free_mib, total_mib = vram[idx]+ gpus.append((idx, free_mib, total_mib))+ return gpus+ except Exception as e:+ logger.debug(f"amd-smi GPU probe failed: {e}")+ return []+@staticmethoddef _get_gpu_memory(binary: Optional[str] = None, *, for_llama_server: bool = False@@ -6013,9 +6381,12 @@ class LlamaCppBackend:"""Query free AND total memory per GPU.Order: ``nvidia-smi`` (NVIDIA, respects ``CUDA_VISIBLE_DEVICES``), then+ ``amd-smi`` (ROCm, the same answer without a HIP context), then``torch.cuda.mem_get_info``, a universal fallback that works on ROCm too(HIP reuses the ``torch.cuda.*`` namespace). The fallback covers #5106- (nvidia-smi returned [] on AMD) and NVIDIA hosts without nvidia-smi on PATH.+ (nvidia-smi returned [] on AMD) and hosts with no smi tool on PATH; it is+ last because it costs this process a permanent CUDA/HIP context, and kept+ because callers read ``[]`` as "no GPU" and would silently drop to CPU.On a Vulkan build the ggml Vulkan probe is authoritative, so the indices areggml's compact Vulkan ordinals (what ``--device Vulkan<i>`` selects). It@@ -6085,6 +6456,13 @@ class LlamaCppBackend:except Exception as e:logger.debug(f"nvidia-smi probe failed: {e}")+ # ── AMD ROCm via amd-smi ─────────────────────────────────────+ rocm_gpus = LlamaCppBackend._get_gpu_memory_amd_smi(+ binary, for_llama_server = for_llama_server+ )+ if rocm_gpus:+ return rocm_gpus+# ── Torch fallback (covers AMD ROCm and missing nvidia-smi) ──try:import torch@@ -6106,17 +6484,8 @@ class LlamaCppBackend:# Shared-pool APU: same as the Vulkan iGPU path. Hold back the host# margin, and report total 0 since that "total" is system RAM.unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids()- # llama-server placement only: gate on the prebuilt's built-arch list so- # the free-memory rank cannot pick a GPU the binary has no kernels for- # (#7624: an iGPU reporting shared RAM outranks the dGPU and the child- # dies with "device kernel image is invalid"). Unknown coverage, or a- # device with no reported arch, keeps every device.- supported_archs = None- arch_by_id: dict[int, str] = {}- if for_llama_server and LlamaCppBackend._torch_is_rocm(torch):- supported_archs = LlamaCppBackend._installed_llama_gfx_archs(binary)- if supported_archs is not None:- arch_by_id = LlamaCppBackend._rocm_arch_by_physical_id()+ # Same #7624 arch gate the amd-smi branch applies, from the one helper.+ arch_keeps = LlamaCppBackend._rocm_arch_gate_keep(binary, torch, for_llama_server)gpus = []# Windows ROCm's free reading is an over-report on discrete cards too,# not only on the shared pool handled below (#8403). It is capped@@ -6131,14 +6500,8 @@ class LlamaCppBackend:if physical_ids is not None and ordinal < len(physical_ids)else ordinal)- if supported_archs is not None:- _base = arch_by_id.get(idx, "")- if _base and _base not in supported_archs:- logger.warning(- f"Skipping GPU {idx} ({_base}): installed llama.cpp "- f"prebuilt only covers {sorted(supported_archs)}"- )- continue+ if not arch_keeps(idx):+ continueshared = idx in unified_idsraw_mib = free_bytes // (1024 * 1024)if shared:diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex dc06ac15472..9acdbbcb8e1 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -285,10 +285,10 @@ class LlamaServerBackend:@staticmethoddef _gpu_available() -> bool:"""Apple Metal, or an NVIDIA/ROCm GPU with enough free VRAM. Reuses- llama_cpp's static probe (nvidia-smi first, so the common path needs no- torch). This backend IS llama-server, so it opts into the ROCm arch gate: an- uncovered device crashes the embedding server as it does a chat load- (#7624)."""+ llama_cpp's static probe, which asks an smi tool before torch, so the+ common path leaves no CUDA/HIP context behind. This backend IS+ llama-server, so it opts into the ROCm arch gate: an uncovered device+ crashes the embedding server as it does a chat load (#7624)."""from utils.hardware import is_apple_siliconif is_apple_silicon():diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.pyindex 25a65d79eaf..767b542e201 100644--- a/studio/backend/core/rag/embeddings.py+++ b/studio/backend/core/rag/embeddings.py@@ -572,7 +572,9 @@ _AUTO_ALIASES = frozenset({"auto", ""})def _resolve_auto() -> str:"""Pick a backend for ``auto``: sentence-transformers when a CUDA/ROCm GPU ispresent (torch fp16 wins bulk indexing), else the torch-free GGUF llama-server- -- or ST if its binary is missing. GPU check is torch-free (nvidia-smi)."""+ -- or ST if its binary is missing. The GPU check goes through an smi tool+ (nvidia-smi, then amd-smi), so it costs no CUDA/HIP context unless neither+ is installed."""from core.inference.llama_cpp import LlamaCppBackend# Unfiltered probe on purpose: the winner here runs under PyTorch, so thediff --git a/studio/backend/tests/test_amd_smi_hip_index_and_coverage.py b/studio/backend/tests/test_amd_smi_hip_index_and_coverage.pynew file mode 100644index 00000000000..3ce56f6c5fb--- /dev/null+++ b/studio/backend/tests/test_amd_smi_hip_index_and_coverage.py@@ -0,0 +1,248 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The amd-smi VRAM branch must answer in HIP's index space, for every visible device.++Two index spaces exist on an AMD host and they are not the same number. amd-smi's+``gpu`` id is "an enumeration index assigned in discovery order" over the KFD/sysfs+view; HIP's id is what ``HIP_VISIBLE_DEVICES`` names, what torch reports as+``cuda:N``, and what ``_get_gpu_memory``'s callers feed back to the llama-server+child. AMD ships the mapping between them as ``amd-smi list -e`` (``hip_id``, ROCm+6.4.0+, ``amdsmi_get_gpu_enumeration_info``), whose whole documented purpose is+"mapping physical-to-logical GPU IDs"; the library derives it from the KFD node id,+not from the discovery order, and the two disagree on real hardware (MI350X in+SPX/NPS1). Answering with the wrong one associates a card's VRAM with another+card's id, so the planner pins the wrong GPU.++amd-smi also enumerates every card regardless of ``ROCR_VISIBLE_DEVICES`` /+``HIP_VISIBLE_DEVICES`` (it reads KFD directly), so the branch has to apply the mask+itself, and a mask it cannot read is not the same thing as no mask at all.++Third: the branch either answers for every visible device or declines. A subset is+indistinguishable from a complete answer to the caller, which reads a non-empty list+as the final word and never asks torch.++torch, ROCm detection and amd-smi are all mocked; this repository has no AMD GPU.+"""++from __future__ import annotations++import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils import hardware+from utils.hardware import amd+++def _hip_sees(+ monkeypatch,+ count,+ totals = None,+):+ """Declare HIP's own inventory: how many devices it opens, and the total memory+ it reports per physical id. Empty totals mean torch could not describe the+ devices, which the probe fails open on."""+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_device_count", staticmethod(lambda: count))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_total_memory_mib_by_physical_id",+ staticmethod(lambda: dict(totals or {})),+ )+++def rocm(monkeypatch):+ """A ROCm host whose nvidia-smi probe finds nothing, with no APUs and no mask.++ HIP reachability and its device count are declared, not inherited: unpatched+ they read this host's own GPU, and CI has none."""+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: True))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_is_reachable", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_var, raising = False)+ monkeypatch.delenv("GPU_DEVICE_ORDINAL", raising = False)+ _hip_sees(monkeypatch, 1)+++def _payload(*gpus: tuple[int, int, int]):+ """amd-smi ``metric`` output for (amd-smi gpu id, used MiB, total MiB) triples."""+ return [+ {+ "gpu": idx,+ "mem_usage": {+ "used_vram": {"value": used, "unit": "MB"},+ "total_vram": {"value": total, "unit": "MB"},+ },+ }+ for idx, used, total in gpus+ ]+++def _enumeration(hip_by_gpu: dict):+ """``amd-smi list -e`` output: the amd-smi gpu id -> HIP id mapping."""+ return [{"gpu": gpu, "hip_id": hip} for gpu, hip in hip_by_gpu.items()]+++def _fake_amd_smi(metric, enumeration = None):+ """Stub amd-smi: ``metric`` returns the VRAM rows, ``list`` the id mapping."""++ def _run(*args, **kwargs):+ if args and args[0] == "list":+ return enumeration+ return metric++ return _run+++class TestTheAmdSmiIdIsTranslatedToHip:+ """Defect A: the branch keyed rows by amd-smi's gpu id and compared that number+ against HIP visibility tokens."""++ def test_a_reordered_host_reports_each_cards_memory_under_its_hip_id(self, rocm, monkeypatch):+ """amd-smi gpu 1 is HIP 0 here. Keyed by amd-smi's number, the 96 GiB card's+ memory lands on HIP id 1 and the planner pins the 16 GiB card for a model+ only the big one fits."""+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 1024, 16384), (1, 2048, 98304)),+ _enumeration({0: 1, 1: 0}),+ ),+ )+ _hip_sees(monkeypatch, 2)+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [+ (0, 96256, 98304),+ (1, 15360, 16384),+ ]++ def test_the_mask_is_matched_in_hip_space(self, rocm, monkeypatch):+ """HIP_VISIBLE_DEVICES=0 names the 96 GiB card, which amd-smi calls gpu 1."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 1024, 16384), (1, 2048, 98304)),+ _enumeration({0: 1, 1: 0}),+ ),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 96256, 98304)]++ def test_a_multi_gpu_host_declines_when_the_mapping_is_unavailable(self, rocm, monkeypatch):+ """amd-smi before ROCm 6.4.0 has no ``list -e``. Identity is an assumption+ there, not a fact, so hand the host to torch."""+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 1024, 16384), (1, 2048, 98304)), None),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_a_partial_mapping_declines(self, rocm, monkeypatch):+ """``hip_id`` is "N/A" when the library cannot read the device's KFD node."""+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 1024, 16384), (1, 2048, 98304)),+ [{"gpu": 0, "hip_id": 0}, {"gpu": 1, "hip_id": "N/A"}],+ ),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_a_single_gpu_host_needs_no_mapping(self, rocm, monkeypatch):+ """One card on both sides forces the mapping, so the common ROCm desktop+ keeps the context saving on any amd-smi version."""+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 4096, 24576)), None))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]+++class TestAnUnreadableMaskDeclines:+ """Defect A, second half: ``_resolve_visible_physical_ids`` returns None both for+ "no mask" and for a mask it cannot parse. ROCr accepts UUID tokens, so reading+ the second as the first offers a deliberately hidden card for ranking."""++ def test_a_uuid_rocr_mask_is_not_read_as_no_mask(self, rocm, monkeypatch):+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "GPU-a1b2c3d4e5f60718")+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 1024, 16384), (1, 2048, 98304)),+ _enumeration({0: 0, 1: 1}),+ ),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_an_empty_mask_still_means_no_gpus(self, rocm, monkeypatch):+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "")+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 1024, 16384)), None))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []+++class TestAPartialAnswerDefersToTorch:+ """Defect B: a row amd-smi cannot size is dropped, and what is left is a+ non-empty list the caller takes as the whole host.++ The field shape: an APU beside a dGPU, where the shared pool reports total 0.+ ``_get_gpu_memory`` returns one device, so the "fewer than 2 usable GPUs" arm+ disables tensor parallelism on a host the torch branch reports as two.+ """++ @pytest.fixture+ def apu_plus_dgpu(self, rocm, monkeypatch):+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 512, 0), (1, 1024, 8192)),+ _enumeration({0: 0, 1: 1}),+ ),+ )+ _hip_sees(monkeypatch, 2)++ def test_the_branch_declines_rather_than_answering_for_one_card(self, apu_plus_dgpu):+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_probe_still_sees_both_devices(self, apu_plus_dgpu, monkeypatch):+ """End to end: the torch branch answers, and both GPUs survive, so the+ tensor-parallel decision is the one main makes."""+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ torch_mod = types.ModuleType("torch")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 2,+ mem_get_info = lambda *a: (0, 0),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ monkeypatch.setattr(+ hardware,+ "trusted_mem_get_info",+ lambda ordinal, *a, **k: (+ (16 * 1024**3, 32 * 1024**3) if ordinal == 0 else (7 * 1024**3, 8 * 1024**3)+ ),+ )+ assert LlamaCppBackend._get_gpu_memory() == [(0, 16384, 32768), (1, 7168, 8192)]++ def test_a_visible_device_amd_smi_never_enumerated_declines(self, rocm, monkeypatch):+ """The mask names two cards and amd-smi answered for one; the other is not+ "absent", it is unmeasured."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,1")+ _hip_sees(monkeypatch, 2)+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 1024, 16384)), None))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []diff --git a/studio/backend/tests/test_amd_smi_inventory_matches_hip.py b/studio/backend/tests/test_amd_smi_inventory_matches_hip.pynew file mode 100644index 00000000000..d6ad7fc4227--- /dev/null+++ b/studio/backend/tests/test_amd_smi_inventory_matches_hip.py@@ -0,0 +1,274 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The amd-smi VRAM branch must answer for HIP's inventory, or not at all.++amd-smi reads the driver's own view over sysfs and libdrm, so it answers for every+card the host has. The llama-server child is a HIP process and sees whatever HIP+sees, and three things move those two apart without any of the visibility variables+``_resolve_visible_physical_ids`` reads being set:++* ``GPU_DEVICE_ORDINAL``. ROCm's fourth visibility variable, which+ ``_active_gpu_visibility_mask`` does not read, so the branch would take "no mask"+ from a process that has been masked. ``utils/hardware/hardware.py::+ _rocm_visibility_mask_active`` already counts it as one of the four, and+ ``test_overlay_skips_under_gpu_device_ordinal`` pins the behaviour it forces+ there: ``GPU_DEVICE_ORDINAL=1`` surfaces physical GPU 1 as torch ordinal 0.+* A device-cgroup container. Given one ``/dev/dri/renderD*`` node and no env var at+ all, HIP opens one device while amd-smi still enumerates the host+ (``test_overlay_skips_device_cgroup_filtered_container`` is the same topology).+ The two read different sources: libhsakmt drops a topology node whose render node+ it cannot open (the cgroup denies it with EPERM) and ROCr then renumbers what is+ left from zero, while amd-smi walks /sys/class/drm and /sys/class/kfd, which the+ cgroup does not touch, and keeps the device with its host numbering.+* ``amd-smi metric`` omitting a device it cannot read. What is left is a shorter+ list, and on a two-card host the remaining single row would take the single-GPU+ shortcut in ``_amd_smi_hip_id_map`` and pass for a one-card host.++Fourth, the two can enumerate the same devices and still be measuring different+pools. ``_rocm_classify_unified_memory`` names an APU from ``is_integrated``, then+from ``gfx1150``/``gfx1151``/``gfx1152``, then from the Radeon name table; a wheel+that exposes a Phoenix iGPU as ``gfx1103`` with no ``is_integrated`` flag hits none+of them, and the branch's APU deferral never fires. amd-smi then reports the BIOS+carve-out where HIP reports the GTT pool, and the fit loses most of the memory the+model can actually use. Comparing the totals catches it without the branch having to+recognise the device: ``hardware.py::_rocm_system_wide_vram_by_index`` gates its own+overlay on the same 10% comparison, for the same two scopes.++torch, ROCm detection and amd-smi are all mocked; this repository has no AMD GPU.+"""++from __future__ import annotations++import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils import hardware+from utils.hardware import amd+++def _payload(*gpus: tuple[int, int, int]):+ """amd-smi ``metric`` output for (amd-smi gpu id, used MiB, total MiB) triples."""+ return [+ {+ "gpu": idx,+ "mem_usage": {+ "used_vram": {"value": used, "unit": "MB"},+ "total_vram": {"value": total, "unit": "MB"},+ },+ }+ for idx, used, total in gpus+ ]+++def _fake_amd_smi(metric, hip_by_gpu = None):+ """Stub amd-smi: ``metric`` returns the VRAM rows, ``list -e`` the id mapping."""++ def _run(*args, **kwargs):+ if args and args[0] == "list":+ if hip_by_gpu is None:+ return None+ return [{"gpu": gpu, "hip_id": hip} for gpu, hip in hip_by_gpu.items()]+ return metric++ return _run+++def _hip_sees(+ monkeypatch,+ count,+ totals = None,+):+ """Declare HIP's own inventory: how many devices it opens, and the total memory+ it reports per physical id. Empty totals mean torch could not describe the+ devices, which the probe fails open on."""+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_device_count", staticmethod(lambda: count))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_total_memory_mib_by_physical_id",+ staticmethod(lambda: dict(totals or {})),+ )+++def rocm(monkeypatch):+ """A ROCm host with no APU the classifier can name and no visibility mask.++ Every variable is cleared as well as patched: the probe asks whether a mask is+ SET before asking what it resolves to, so the shell's own CUDA_VISIBLE_DEVICES+ would read as a mask that resolves to nothing (#8662). HIP's inventory is+ declared for the same reason: unpatched it reads this host's own GPU."""+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: True))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_is_reachable", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ for _var in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ ):+ monkeypatch.delenv(_var, raising = False)+ _hip_sees(monkeypatch, 2)+++def two_cards(rocm, monkeypatch):+ """A plain two-card host: amd-smi and HIP agree on both devices."""+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 4096, 24576), (1, 8192, 16384)), {0: 0, 1: 1}),+ )+++class TestGpuDeviceOrdinalIsHonoured:+ """``GPU_DEVICE_ORDINAL`` is a ROCm visibility variable and+ ``_resolve_visible_physical_ids`` does not read it, so an unfiltered amd-smi+ inventory would be offered as the whole visible set.++ AMD documents it as masking "OpenCL and HIP applications" while clr reads it+ only when ``amd::IS_HIP`` is false, so the two disagree on whether HIP obeys it.+ The branch declines under either reading: deferring on a host where HIP ignores+ it costs only the context saving, offering a hidden card where HIP obeys it+ costs a load."""++ def test_a_masked_process_is_not_offered_the_hidden_card(self, two_cards, monkeypatch):+ """GPU_DEVICE_ORDINAL=1 is the mask this repository already models, in+ ``test_overlay_skips_under_gpu_device_ordinal``: physical GPU 1 as torch+ ordinal 0. The branch must not rank GPU 0 behind it."""+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", "1")+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_a_full_ordinal_list_defers_too(self, two_cards, monkeypatch):+ """Every card is still visible, but the variable also REORDERS them, so the+ ids this branch would hand the child are not the ones it named."""+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", "1,0")+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_an_unset_or_blank_variable_is_not_a_mask(self, two_cards, monkeypatch):+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576), (1, 8192, 16384)]+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", " ")+ assert LlamaCppBackend._gpu_device_ordinal_active() is False+ assert LlamaCppBackend._get_gpu_memory_amd_smi() != []+++class TestTheInventoryMustBeTheOneHipOpens:+ """A count HIP does not agree with means something outside the visibility+ variables filtered the device set."""++ def test_a_device_cgroup_container_defers_to_torch(self, two_cards, monkeypatch):+ """One renderD node, no env var: amd-smi lists both host cards, HIP opens+ one. Answering would let the fit pin a GPU the container cannot access."""+ _hip_sees(monkeypatch, 1)+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_container_still_gets_torchs_single_device(self, two_cards, monkeypatch):+ """End to end: the torch branch answers for the one device HIP opened."""+ _hip_sees(monkeypatch, 1)+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ torch_mod = types.ModuleType("torch")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ mem_get_info = lambda *a: (0, 0),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (20 * 1024**3, 24 * 1024**3)+ )+ assert LlamaCppBackend._get_gpu_memory() == [(0, 20480, 24576)]++ def test_a_row_amd_smi_omitted_does_not_pass_for_a_one_card_host(self, rocm, monkeypatch):+ """``amd-smi metric`` skipped the device it could not read. One row and no+ mask is exactly the shape ``_amd_smi_hip_id_map``'s single-GPU shortcut+ accepts without consulting ``list -e``, so the omitted card would simply+ cease to exist for tensor-parallel placement."""+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 4096, 24576)), None))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_a_masked_subset_is_measured_against_the_mask(self, rocm, monkeypatch):+ """HIP_VISIBLE_DEVICES=1 hides a card from HIP, not from amd-smi, so one+ device each is agreement rather than a filtered inventory."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "1")+ _hip_sees(monkeypatch, 1)+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 4096, 24576), (1, 8192, 16384)), {0: 0, 1: 1}),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(1, 8192, 16384)]+++class TestAnApuTheClassifierMisses:+ """The field shape: a Phoenix iGPU a wheel reports as ``gfx1103`` with no+ ``is_integrated``. ``_rocm_classify_unified_memory`` calls it discrete, so the+ APU deferral never fires and amd-smi's 512 MiB carve-out would replace the+ 16 GiB pool torch reports."""++ @pytest.fixture+ def phoenix(self, rocm, monkeypatch):+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 128, 512)), None))+ _hip_sees(monkeypatch, 1, {0: 16384})++ def test_the_branch_declines_rather_than_reporting_the_carve_out(self, phoenix):+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_probe_still_reports_the_pool_the_model_runs_in(self, phoenix, monkeypatch):+ """End to end: _get_gpu_memory keeps the torch branch's figures, which is+ what it returned before this branch existed."""+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ torch_mod = types.ModuleType("torch")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ mem_get_info = lambda *a: (0, 0),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (12 * 1024**3, 16 * 1024**3)+ )+ assert LlamaCppBackend._get_gpu_memory() == [(0, 12288, 16384)]++ def test_a_partitioned_card_defers_the_other_way_round(self, rocm, monkeypatch):+ """The mismatch is symmetric: an MI300 partition reports a slice to HIP+ while amd-smi reports the whole card."""+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 4096, 196608)), None))+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_two_readings_of_one_pool_are_accepted(self, rocm, monkeypatch):+ """amd-smi and HIP do not report a card's total to the byte (reserved pages,+ MB against MiB), so the comparison has the same 10% margin the System tab's+ overlay uses."""+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 4096, 24576)), None))+ _hip_sees(monkeypatch, 1, {0: 24400})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]++ def test_a_device_torch_cannot_describe_fails_open(self, rocm, monkeypatch):+ """``_rocm_total_memory_mib_by_physical_id`` omits a device whose properties+ it cannot read, exactly like ``_rocm_arch_by_physical_id``. No evidence is+ not evidence against, or an unreadable properties call would disable this+ branch on every host."""+ monkeypatch.setattr(amd, "_run_amd_smi", _fake_amd_smi(_payload((0, 4096, 24576)), None))+ _hip_sees(monkeypatch, 1, {})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]diff --git a/studio/backend/tests/test_rocm_hip_unreachable_defers_to_torch.py b/studio/backend/tests/test_rocm_hip_unreachable_defers_to_torch.pynew file mode 100644index 00000000000..22a653fe1f0--- /dev/null+++ b/studio/backend/tests/test_rocm_hip_unreachable_defers_to_torch.py@@ -0,0 +1,118 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The amd-smi VRAM branch must not answer for a host where HIP cannot open a device.++amd-smi and HIP do not read the same thing. amd-smi reports the driver's inventory+over sysfs and libdrm's ``/dev/dri/renderD*``; HIP needs ``/dev/kfd`` and a matching+HSA runtime. The two come apart on real hosts: a container started with+``--device=/dev/dri`` but no ``--device=/dev/kfd`` (AMD's own container docs require+BOTH), and a torch wheel built against a ROCm the installed runtime does not match.+There 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, which is the right answer; the amd-smi branch returns first and+hands placement a device nothing can open.++Neither existing guard catches it, because both are themselves torch readers that+fail open: ``_rocm_unified_memory_gpu_ids`` returns ``set()`` and+``_rocm_arch_by_physical_id`` returns ``{}`` the moment ``is_available()`` is False.+So an APU on such a host is not even recognised as one, and amd-smi's dedicated+carve-out is accepted as the whole pool.++Gating 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``+and not ``_lazy_init``.++torch, ROCm detection and amd-smi are all mocked; this repository has no AMD GPU.+"""++from __future__ import annotations++import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils.hardware import amd+++def _payload(*gpus: tuple[int, int, int]):+ """amd-smi ``metric`` output for (amd-smi gpu id, used MiB, total MiB) triples."""+ return [+ {+ "gpu": idx,+ "mem_usage": {+ "used_vram": {"value": used, "unit": "MB"},+ "total_vram": {"value": total, "unit": "MB"},+ },+ }+ for idx, used, total in gpus+ ]+++def rocm(monkeypatch):+ """A ROCm host with one card, no mask, and an amd-smi that answers.++ The three mask vars are cleared from the environment as well as patched: the+ probe asks whether a mask is SET before asking what it resolves to, so the+ shell's own CUDA_VISIBLE_DEVICES would otherwise read as a mask that resolves to+ nothing (#8662 for the same trap in the APU tests)."""+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: True))+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_var, raising = False)+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: _payload((0, 4096, 24576)))+++def _fake_torch(monkeypatch, *, hip_up: bool):+ """A ROCm torch whose HIP either can or cannot open the card amd-smi just listed."""+ torch_mod = types.ModuleType("torch")+ torch_mod.version = types.SimpleNamespace(hip = "6.2.41134")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: hip_up,+ device_count = lambda: 1 if hip_up else 0,+ get_device_properties = lambda _o: types.SimpleNamespace(+ name = "Radeon RX 7900 XTX", gcnArchName = "gfx1100"+ ),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ return torch_mod+++class TestHipCannotOpenTheDevice:+ @pytest.fixture+ def hip_is_down(self, rocm, monkeypatch):+ return _fake_torch(monkeypatch, hip_up = False)++ def test_the_amd_smi_branch_declines(self, hip_is_down):+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_and_the_whole_probe_reports_no_gpu(self, hip_is_down, monkeypatch):+ """End to end: the pre-branch answer for this host, which is CPU."""+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ assert LlamaCppBackend._get_gpu_memory() == []++ def test_no_existing_guard_would_have_caught_it(self, hip_is_down):+ """Both are torch readers that fail open, which is why the gate is explicit."""+ assert LlamaCppBackend._rocm_unified_memory_gpu_ids() == set()+ assert LlamaCppBackend._rocm_arch_by_physical_id() == {}+++def test_a_reachable_hip_still_answers_from_amd_smi(rocm, monkeypatch):+ """The gate must not cost the saving on a working host: no mem_get_info here."""+ _fake_torch(monkeypatch, hip_up = True)+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]diff --git a/studio/backend/tests/test_rocm_stacked_visibility_masks.py b/studio/backend/tests/test_rocm_stacked_visibility_masks.pynew file mode 100644index 00000000000..40b6f5bf517--- /dev/null+++ b/studio/backend/tests/test_rocm_stacked_visibility_masks.py@@ -0,0 +1,217 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Stacked ROCm visibility masks re-index each other, so only one of them can be read.++``ROCR_VISIBLE_DEVICES`` filters at the ROCr/HSA layer and ``HIP_VISIBLE_DEVICES``+(and its ``CUDA_VISIBLE_DEVICES`` twin) filters at the HIP layer ABOVE it, so the two+compose: ROCr hands clr an already filtered, already renumbered agent list, and the+HIP ordinals index into what survived. ``clr/rocclr/device/rocm/rocdevice.cpp::+Device::init`` splits the HIP list and looks each entry up in ``gpu_agents_``, the+vector ``hsa_iterate_agents`` just filled, which ROCR-Runtime's ``RvdFilter``+(``core/inc/amd_filter_device.h``) has already filtered and reordered. AMD documents+the same layering under "GPU isolation techniques".++``_active_gpu_visibility_mask`` returns ONE value, the highest-precedence one, so+``ROCR_VISIBLE_DEVICES=1,2`` with ``HIP_VISIBLE_DEVICES=0`` resolves to ``[0]`` when+the device HIP actually opens is physical GPU 1. Every guard on the amd-smi branch+passes on a homogeneous host: HIP opens one device and the mask names one, and the+two cards have the same total, so the branch reports the free VRAM of physical GPU 0,+a card the ROCr mask hid, under the id the picker then places on.++Nothing here composes the masks: doing that needs a physical->ROCr id map this+process cannot build without opening the runtime, and guessing wrong hands the child+a hidden card. The branch declines instead, which costs only its context saving.++torch, ROCm detection and amd-smi are all mocked; this repository has no AMD GPU.+"""++from __future__ import annotations++import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils import hardware+from utils.hardware import amd+++def _payload(*gpus: tuple[int, int, int]):+ """amd-smi ``metric`` output for (amd-smi gpu id, used MiB, total MiB) triples."""+ return [+ {+ "gpu": idx,+ "mem_usage": {+ "used_vram": {"value": used, "unit": "MB"},+ "total_vram": {"value": total, "unit": "MB"},+ },+ }+ for idx, used, total in gpus+ ]+++def _fake_amd_smi(metric, hip_by_gpu = None):+ """Stub amd-smi: ``metric`` returns the VRAM rows, ``list -e`` the id mapping."""++ def _run(*args, **kwargs):+ if args and args[0] == "list":+ if hip_by_gpu is None:+ return None+ return [{"gpu": gpu, "hip_id": hip} for gpu, hip in hip_by_gpu.items()]+ return metric++ return _run+++def _hip_sees(+ monkeypatch,+ count,+ totals = None,+):+ """Declare HIP's own inventory, which is not this host's: how many devices it+ opens, and the total memory it reports per physical id."""+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_device_count", staticmethod(lambda: count))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_total_memory_mib_by_physical_id",+ staticmethod(lambda: dict(totals or {})),+ )+++def three_identical_cards(monkeypatch):+ """A ROCm Linux host with three same-model cards and no mask set.++ Same model on purpose: the branch's total-memory cross-check cannot tell the+ wrong card from the right one when both report 24 GiB, which is what a multi-GPU+ ROCm box usually is. amd-smi says GPU 0 is nearly idle and GPUs 1 and 2 are+ nearly full -- the reason someone masks GPU 0 off in the first place.++ Every variable is cleared as well as patched: the probe asks whether a mask is+ SET before asking what it resolves to, so this host's own CUDA_VISIBLE_DEVICES+ would read as a mask (#8662)."""+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: True))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_is_reachable", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ for _var in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ ):+ monkeypatch.delenv(_var, raising = False)+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(+ _payload((0, 4096, 24576), (1, 23552, 24576), (2, 23552, 24576)),+ {0: 0, 1: 1, 2: 2},+ ),+ )+ _hip_sees(monkeypatch, 3, {0: 24576, 1: 24576, 2: 24576})+++class TestStackedMasksAreNotResolvable:+ """Both layers filtering means the resolved ids are not the ids HIP opened."""++ def test_a_rocr_mask_under_a_hip_mask_defers_to_torch(self, three_identical_cards, monkeypatch):+ """ROCR keeps physical 1 and 2 and renumbers them 0 and 1; HIP then keeps+ the first of THOSE, so HIP device 0 is physical GPU 1.+ ``_resolve_visible_physical_ids`` reads the HIP mask alone and answers [0],+ and every later guard agrees with it: HIP opens one device, the mask names+ one, and the totals match because the cards are the same model. Answering+ would report idle physical GPU 0's 20 GiB for a process that can only reach+ a nearly full GPU 1."""+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_cuda_twin_stacks_the_same_way(self, three_identical_cards, monkeypatch):+ """AMD documents CUDA_VISIBLE_DEVICES as having "the same effect as+ HIP_VISIBLE_DEVICES on the AMD platform", and clr reads it from the same+ line: ``HIP_VISIBLE_DEVICES[0] != '\\0' ? HIP_VISIBLE_DEVICES :+ CUDA_VISIBLE_DEVICES``. It indexes the post-ROCr list too."""+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_an_empty_rocr_mask_under_a_hip_mask_defers(self, three_identical_cards, monkeypatch):+ """``ROCR_VISIBLE_DEVICES=""`` hides every agent (case A1 in ROCR-Runtime's+ ``amd_filter_device.h``), so the HIP mask indexes an empty list. Set is set:+ the value is not what makes the two stack."""+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "")+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 0, {})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_load_still_gets_torchs_figures(self, three_identical_cards, monkeypatch):+ """End to end: deferring is not dropping the GPU. The torch branch answers+ for the one device HIP opened, in HIP's own index space, which is what+ _get_gpu_memory returned before the amd-smi branch existed."""+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 1, {0: 24576})+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ torch_mod = types.ModuleType("torch")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ mem_get_info = lambda *a: (0, 0),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (1024**3, 24 * 1024**3)+ )+ assert LlamaCppBackend._get_gpu_memory() == [(0, 1024, 24576)]+++class TestOneMaskIsStillAnswerable:+ """The guard is about two layers filtering at once, not about the variables+ existing. A single mask maps to physical ids exactly as before."""++ def test_a_lone_rocr_mask_still_answers(self, three_identical_cards, monkeypatch):+ """No HIP layer above it, so the ROCR ids ARE the physical ids+ ``_resolve_visible_physical_ids`` reads."""+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ _hip_sees(monkeypatch, 2, {1: 24576, 2: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(1, 1024, 24576), (2, 1024, 24576)]++ def test_a_lone_hip_mask_still_answers(self, three_identical_cards, monkeypatch):+ """Nothing filtered below it, so its ordinals are physical ids too."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]++ def test_hip_and_cuda_together_are_one_layer(self, three_identical_cards, monkeypatch):+ """Both name the HIP layer and clr reads whichever of them is set FIRST,+ never both, so they do not compose and the HIP value is the whole mask."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2")+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]++ def test_windows_has_no_rocr_layer_to_stack(self, three_identical_cards, monkeypatch):+ """Windows HIP has no ROCr layer, so a stray ROCR variable filters nothing+ and cannot re-index the HIP mask. ``_active_gpu_visibility_mask`` already+ ignores it there, and this guard has to agree with it or the branch would+ be dead on every Windows host that inherited one."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ _hip_sees(monkeypatch, 1, {0: 24576})+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]diff --git a/studio/backend/tests/test_rocm_vram_probe_no_hip_context.py b/studio/backend/tests/test_rocm_vram_probe_no_hip_context.pynew file mode 100644index 00000000000..6fdcb1a513a--- /dev/null+++ b/studio/backend/tests/test_rocm_vram_probe_no_hip_context.py@@ -0,0 +1,305 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""``_get_gpu_memory`` must not open a HIP context to read VRAM on ROCm.++``torch.cuda.mem_get_info`` creates a primary context the process never releases:+measured at 612 MiB on a B200 with CUDA 13, and reported in the 692-712 MiB range+elsewhere. ``get_device_properties`` and ``get_device_capability`` do not, which is+why the System tab already reads totals through properties.++NVIDIA hosts were already safe because the probe asks nvidia-smi first. ROCm hosts+were not: they fell straight through to torch, so a Studio backend serving GGUF+models paid a permanent ~700 MiB for a number it only reads, on a card whose models+run in a llama-server CHILD that then cannot use it. amd-smi answers the same+question from a subprocess.++The torch fallback stays for hosts with no smi tool at all. Callers read ``[]`` as+"no GPU" -- ``_resolve_auto`` picks a backend from it, ``_gpu_available`` gates the+embedder, and the loader's fit drops to CPU -- so returning "unknown" there would+silently move inference off the GPU. Accepting the context is the lesser cost.++torch, ROCm detection and amd-smi are all mocked: this repository has no AMD GPU+and no ROCm CI, so none of this is a hardware validation.+"""++from __future__ import annotations++import json+import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils import hardware+from utils.hardware import amd+++def _hip_sees(+ monkeypatch,+ count,+ totals = None,+):+ """Declare HIP's own inventory: how many devices it opens, and the total memory+ it reports per physical id. Empty totals mean torch could not describe the+ devices, which the probe fails open on."""+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_device_count", staticmethod(lambda: count))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_total_memory_mib_by_physical_id",+ staticmethod(lambda: dict(totals or {})),+ )+++def rocm(monkeypatch):+ """A ROCm host whose nvidia-smi probe finds nothing, with no APUs.++ The mask is cleared from the environment as well as patched: the probe asks+ whether a mask is SET before asking what it resolves to, so the shell's own+ CUDA_VISIBLE_DEVICES would otherwise read as a mask that resolves to nothing+ (#8662 for the same trap in the APU tests). HIP reachability and its device+ count are declared for the same reason: unpatched they read this host's own+ GPU, and CI has none."""+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: True))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_hip_is_reachable", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_var, raising = False)+ monkeypatch.delenv("GPU_DEVICE_ORDINAL", raising = False)+ monkeypatch.setattr(+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: None)+ )+ _hip_sees(monkeypatch, 1)+++def _payload(*gpus: tuple[int, int, int]):+ """amd-smi ``metric`` output for (id, used MiB, total MiB) triples."""+ return [+ {+ "gpu": idx,+ "mem_usage": {+ "used_vram": {"value": used, "unit": "MB"},+ "total_vram": {"value": total, "unit": "MB"},+ },+ }+ for idx, used, total in gpus+ ]+++def _fake_amd_smi(metric, hip_by_gpu = None):+ """Stub amd-smi: ``metric`` returns the VRAM rows, ``list -e`` the amd-smi gpu id+ to HIP id mapping a host with more than one card needs before its ids can be+ used as HIP ordinals (see test_amd_smi_hip_index_and_coverage.py)."""++ def _run(*args, **kwargs):+ if args and args[0] == "list":+ return [{"gpu": gpu, "hip_id": hip} for gpu, hip in (hip_by_gpu or {}).items()]+ return metric++ return _run+++def test_amd_smi_supplies_free_and_total_without_torch(rocm, monkeypatch):+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: _payload((0, 4096, 24576)))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]+++def test_the_visibility_mask_is_honoured(rocm, monkeypatch):+ """amd-smi enumerates every card; a masked-out GPU must not be offered."""+ monkeypatch.setattr(LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: [1]))+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 0, 24576), (1, 8192, 16384)), {0: 0, 1: 1}),+ )+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(1, 8192, 16384)]+++class TestAUnifiedMemoryApuDefersToTorch:+ """amd-smi reports only the dedicated VRAM carve-out on a unified-memory APU;+ HIP reports the GTT pool the models actually run in. ``hardware.py::+ _apply_unified_memory_correction`` already adopts torch's larger total over+ amd-smi's for the System tab for exactly this reason.++ The field shape: a 128 GiB Strix Halo (gfx1151) whose BIOS carves out 8 GiB of+ "VRAM". Sizing the GGUF fit off that slice cuts context or drops the model to+ CPU, so this branch must hand the whole host back to the torch one rather than+ answer from a different memory scope than the branch it replaces.+ """++ @pytest.fixture+ def strix_halo(self, rocm, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 98304)+ )+ # amd-smi: 1 GiB used of the 8 GiB dedicated slice.+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: _payload((0, 1024, 8192)))++ def test_the_amd_smi_branch_declines(self, strix_halo):+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []++ def test_the_probe_still_reports_the_gtt_pool(self, strix_halo, monkeypatch):+ """End to end: _get_gpu_memory must return the torch branch's figure, not+ the carve-out. 100 GiB free GTT, capped at 96 GiB system RAM, less the+ 1 GiB host reserve, and total 0 because that "total" is system RAM."""+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ torch_mod = types.ModuleType("torch")+ torch_mod.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ mem_get_info = lambda *a: (100 * 1024**3, 128 * 1024**3),+ )+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (100 * 1024**3, 128 * 1024**3)+ )+ assert LlamaCppBackend._get_gpu_memory() == [(0, 98304 - 1024, 0)]+++ "envelope",+ [+ lambda rows: rows, # a bare JSON array+ lambda rows: {"gpu_data": rows}, # newer versions+ lambda rows: {"gpus": rows},+ lambda rows: {"gpu": rows},+ lambda rows: rows[0], # the single-GPU dict get_primary_gpu_utilization takes+ ],+)+def test_every_amd_smi_envelope_shape_is_read(rocm, monkeypatch, envelope):+ """The single-GPU dict carries its own numeric "gpu" id, so reading that key as+ the device list yields the id itself and enumerating an int raises TypeError.+ ``_get_gpu_memory_amd_smi`` swallows that and falls back to+ ``torch.cuda.mem_get_info``, recreating the very HIP context this branch exists+ to avoid."""+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: envelope(_payload((0, 4096, 24576))))+ assert amd.get_gpu_vram_mib() == {0: (20480, 24576)}+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 20480, 24576)]+++ "payload",+ [None, [], [{"gpu": 0, "power": {}}], [{"gpu": 0, "vram": {"used": 1, "total": 0}}]],+)+def test_an_unusable_amd_smi_falls_through(rocm, monkeypatch, payload):+ """Absent, empty, VRAM-less and zero-total answers all defer to the caller."""+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: payload)+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []+++def test_the_branch_is_inert_off_rocm(monkeypatch):+ """An NVIDIA host must not spawn amd-smi; its numbers stay exactly as they were."""+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda torch: False))++ def _boom(*a, **k):+ raise AssertionError("amd-smi must not run off ROCm")++ monkeypatch.setattr(amd, "_run_amd_smi", _boom)+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == []+++def test_used_above_total_cannot_become_negative_free(rocm, monkeypatch):+ """A stale reading mid-reset clamps to 0 rather than offering negative VRAM."""+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: _payload((0, 9000, 8192)))+ assert LlamaCppBackend._get_gpu_memory_amd_smi() == [(0, 0, 8192)]+++def test_free_is_derived_the_way_nvidia_smi_reports_it(rocm, monkeypatch):+ """Parity with the nvidia-smi branch: free == total - used, in MiB."""+ monkeypatch.setattr(amd, "_run_amd_smi", lambda *a, **k: _payload((0, 5000, 16384)))+ assert amd.get_gpu_vram_mib() == {0: (16384 - 5000, 16384)}+++class TestTheArchGateAppliesToThisBranchToo:+ """#7624's gate lives in ``_get_gpu_memory``, and this branch returns before the+ torch one that carries it. An llama-server placement must lose a device the+ installed prebuilt has no kernels for here as well, or reading VRAM through+ amd-smi reintroduces the "device kernel image is invalid" crash.++ The #7624 shape: a gfx1101 dGPU beside a gfx1036 iGPU the build does not cover.+ """++ @pytest.fixture+ def mixed_host(self, rocm, tmp_path, monkeypatch):+ """Both cards visible to amd-smi; only the dGPU's arch is in the marker."""+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"mapped_targets": ["gfx1100", "gfx1101"]}), encoding = "utf-8"+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_arch_by_physical_id",+ staticmethod(lambda: {0: "gfx1101", 1: "gfx1036"}),+ )+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 4096, 24576), (1, 1024, 16384)), {0: 0, 1: 1}),+ )+ _hip_sees(monkeypatch, 2)+ return str(tmp_path / "build" / "bin" / "llama-server")++ def test_an_uncovered_device_is_dropped(self, mixed_host):+ assert LlamaCppBackend._get_gpu_memory_amd_smi(mixed_host, for_llama_server = True) == [+ (0, 20480, 24576)+ ]++ def test_and_kept_for_every_other_caller(self, mixed_host):+ # _resolve_auto's winner runs under PyTorch, which covers the card fine.+ assert LlamaCppBackend._get_gpu_memory_amd_smi(mixed_host) == [+ (0, 20480, 24576),+ (1, 15360, 16384),+ ]++ def test_the_gate_survives_the_full_probe(self, mixed_host, monkeypatch):+ """End to end through _get_gpu_memory, which is where the ordering trap is:+ a truthy amd-smi answer returns before the torch branch can gate it."""+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary: False)+ )++ def _no_nvidia_smi(*args, **kwargs):+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ assert LlamaCppBackend._get_gpu_memory(mixed_host, for_llama_server = True) == [+ (0, 20480, 24576)+ ]++ def test_unknown_coverage_keeps_every_device(self, rocm, tmp_path, monkeypatch):+ """No install marker (source build, pre-#7624 install): fail open, the same+ way the torch branch does."""+ monkeypatch.setattr(+ LlamaCppBackend,+ "_rocm_arch_by_physical_id",+ staticmethod(lambda: {0: "gfx1101", 1: "gfx1036"}),+ )+ monkeypatch.setattr(+ amd,+ "_run_amd_smi",+ _fake_amd_smi(_payload((0, 4096, 24576), (1, 1024, 16384)), {0: 0, 1: 1}),+ )+ _hip_sees(monkeypatch, 2)+ binary = str(tmp_path / "build" / "bin" / "llama-server")+ assert len(LlamaCppBackend._get_gpu_memory_amd_smi(binary, for_llama_server = True)) == 2++ def test_a_device_with_no_reported_arch_is_kept(self, mixed_host, monkeypatch):+ """Torch could not describe it, so there is no evidence against it."""+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_arch_by_physical_id", staticmethod(lambda: {0: "gfx1101"})+ )+ assert len(LlamaCppBackend._get_gpu_memory_amd_smi(mixed_host, for_llama_server = True)) == 2diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.pyindex 318759f67d9..bba420b944a 100644--- a/studio/backend/utils/hardware/amd.py+++ b/studio/backend/utils/hardware/amd.py@@ -103,8 +103,18 @@ def _amd_smi_allowed() -> bool:return _hip_sdk_present()-def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optional[Any]:- """Run amd-smi with the given args and return parsed JSON, or None."""+def _run_amd_smi(+ *args: str,+ timeout: int = _AMD_SMI_DEFAULT_TIMEOUT,+ count_failures: bool = True,+) -> Optional[Any]:+ """Run amd-smi with the given args and return parsed JSON, or None.++ ``count_failures = False`` keeps a failure out of the circuit breaker, for a+ subcommand an older amd-smi rejects outright: that exit code says the CLI is old,+ not that the tool is broken, and three of them must not disable VRAM and+ utilization polling for the life of the process.+ """global _amd_smi_consecutive_failures, _amd_smi_disabledif _amd_smi_disabled:return None@@ -157,6 +167,8 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optionalogger.debug("amd-smi not found (not in PATH): %s", e)else:logger.warning("amd-smi query failed: %s", e)+ if not count_failures:+ return None_amd_smi_consecutive_failures += 1if _amd_smi_consecutive_failures >= _AMD_SMI_FAILURE_LIMIT:logger.info(@@ -167,6 +179,8 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optionareturn Noneif result.returncode != 0:logger.warning("amd-smi returned code %d", result.returncode)+ if not count_failures:+ return None_amd_smi_consecutive_failures += 1if _amd_smi_consecutive_failures >= _AMD_SMI_FAILURE_LIMIT:logger.info(@@ -251,6 +265,28 @@ def _parse_memory_mb(value: Any) -> Optional[float]:return num+def _vram_used_total_mb(gpu_data: dict) -> tuple[Optional[float], Optional[float]]:+ """(used, total) VRAM in MB, unit-aware across amd-smi formats.++ Newer versions use "mem_usage" with "total_vram"/"used_vram"; older use+ "vram" or "fb_memory_usage" with "used"/"total". Shared with the VRAM probe+ so both read the same keys.+ """+ vram_data = gpu_data.get(+ "mem_usage",+ gpu_data.get("vram", gpu_data.get("fb_memory_usage", {})),+ )+ if not isinstance(vram_data, dict):+ return None, None+ used = _parse_memory_mb(+ vram_data.get("used_vram", vram_data.get("vram_used", vram_data.get("used")))+ )+ total = _parse_memory_mb(+ vram_data.get("total_vram", vram_data.get("vram_total", vram_data.get("total")))+ )+ return used, total++def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:"""Extract standardized metrics from a single GPU's amd-smi data."""# Output structure varies by version; try common paths@@ -286,23 +322,7 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:power_draw = Nonepower_limit = None- # VRAM: unit-aware parsing across amd-smi formats. Newer versions use- # "mem_usage" with "total_vram"/"used_vram"; older use "vram" or- # "fb_memory_usage" with "used"/"total".- vram_data = gpu_data.get(- "mem_usage",- gpu_data.get("vram", gpu_data.get("fb_memory_usage", {})),- )- if isinstance(vram_data, dict):- vram_used_mb = _parse_memory_mb(- vram_data.get("used_vram", vram_data.get("vram_used", vram_data.get("used")))- )- vram_total_mb = _parse_memory_mb(- vram_data.get("total_vram", vram_data.get("vram_total", vram_data.get("total")))- )- else:- vram_used_mb = None- vram_total_mb = None+ vram_used_mb, vram_total_mb = _vram_used_total_mb(gpu_data)# Build the standardized dict (same shape as nvidia._build_gpu_metrics)vram_used_gb = round(vram_used_mb / 1024, 2) if vram_used_mb is not None else None@@ -357,6 +377,134 @@ def get_physical_gpu_count() -> Optional[int]:return None+def _gpu_entries(data: Any) -> list[tuple[int, dict]]:+ """(physical gpu id, gpu dict) pairs from any amd-smi envelope shape.++ A JSON array, a dict under "gpu_data"/"gpus"/"gpu", or a guarded+ scalar/string fallback. The id is amd-smi's own, falling back to the+ enumeration index when it is missing or unparseable.++ An envelope key only counts when its value is really a list. A single-GPU+ response is a bare dict carrying its own numeric ``"gpu"`` id (the shape+ ``get_primary_gpu_utilization`` also handles); reading that key as the+ envelope yields the id itself, and enumerating an int raises TypeError+ instead of falling back to treating the dict as the one entry.+ """+ if isinstance(data, dict):+ gpu_list: Any = [data]+ for _key in ("gpu_data", "gpus", "gpu"):+ _value = data.get(_key)+ if isinstance(_value, list):+ gpu_list = _value+ break+ elif isinstance(data, list):+ gpu_list = data+ else:+ gpu_list = [data]++ entries: list[tuple[int, dict]] = []+ for fallback_idx, gpu_data in enumerate(gpu_list):+ # Skip non-dict entries (a scalar in the array would raise AttributeError).+ if not isinstance(gpu_data, dict):+ continue+ # Use the AMD-reported GPU ID, else the enumeration index. _parse_numeric+ # handles bare ints/floats/strings and the {"value", "unit"} dict shape.+ raw_id = gpu_data.get("gpu", gpu_data.get("gpu_id", gpu_data.get("id", fallback_idx)))+ parsed_id = _parse_numeric(raw_id)+ if parsed_id is None:+ logger.warning(+ "amd-smi GPU id %r could not be parsed; falling back to enumeration index %d",+ raw_id,+ fallback_idx,+ )+ idx = fallback_idx+ else:+ rounded = round(parsed_id)+ if rounded != parsed_id:+ logger.warning(+ "amd-smi GPU id %r parsed as non-integer %r; truncating to %d",+ raw_id,+ parsed_id,+ rounded,+ )+ idx = int(rounded)+ entries.append((idx, gpu_data))+ return entries+++def get_gpu_vram_report() -> tuple[dict[int, tuple[int, int]], list[int]]:+ """(``get_gpu_vram_mib()``, every amd-smi gpu id the same call enumerated).++ The ids are amd-smi's own, which are NOT HIP's (see+ ``get_hip_id_by_gpu_index``). The second element is what tells a partial answer+ from a complete one: a device whose VRAM does not parse (a shared pool reporting+ total 0) is missing from the dict but present here, and a caller that ranks GPUs+ has to see the whole set or none of it -- what is left of a dropped row is a+ non-empty dict, indistinguishable from a host that really has one card.+ """+ data = _run_amd_smi("metric")+ if data is None:+ return {}, []+ out: dict[int, tuple[int, int]] = {}+ enumerated: list[int] = []+ for idx, gpu_data in _gpu_entries(data):+ enumerated.append(idx)+ used_mb, total_mb = _vram_used_total_mb(gpu_data)+ if used_mb is None or total_mb is None or total_mb <= 0:+ continue+ # Clamp: a used reading above total (seen when a card reports a stale+ # figure mid-reset) must not become negative free.+ out[idx] = (int(max(0.0, total_mb - used_mb)), int(total_mb))+ return out, enumerated+++def get_gpu_vram_mib() -> dict[int, tuple[int, int]]:+ """{amd-smi gpu id: (free MiB, total MiB)} for every AMD GPU amd-smi sees.++ The out-of-process answer to the question ``torch.cuda.mem_get_info`` answers+ in-process. That call creates a HIP primary context the process never gives+ back (~700 MiB measured), which is pure loss in a backend whose GGUF models+ run in a llama-server child. amd-smi reports used rather than free, so free is+ derived; MiB and MB agree here because ``_parse_memory_mb`` normalises the+ binary units amd-smi reports.++ Empty when amd-smi is missing, disabled, or reports no usable VRAM, so callers+ keep whatever fallback they had.+ """+ return get_gpu_vram_report()[0]+++def get_hip_id_by_gpu_index() -> Optional[dict[int, int]]:+ """{amd-smi gpu id: HIP device id}, or None when the mapping is not readable.++ Two index spaces, one number. amd-smi's gpu id is an enumeration index in+ discovery order over its KFD/sysfs view; HIP's is what ``HIP_VISIBLE_DEVICES``+ names and what torch reports as ``cuda:N``, and the library derives it from the+ KFD node id instead (``hip_id = node_id - smallest_node_id``). They coincide on+ most hosts and not on all of them, so the number cannot be carried from one+ space to the other without this call.++ ``amd-smi list -e`` is the mapping AMD publishes for exactly this ("mapping+ physical-to-logical GPU IDs"), added in ROCm 6.4.0. None when any device lacks a+ usable id -- an older CLI rejects ``-e`` outright, and ``hip_id`` reads "N/A"+ when the library cannot reach the device's KFD node -- so callers decline rather+ than assume the identity mapping.+ """+ data = _run_amd_smi("list", "-e", count_failures = False)+ if data is None:+ return None+ mapping: dict[int, int] = {}+ for idx, gpu_data in _gpu_entries(data):+ hip_id = _parse_numeric(gpu_data.get("hip_id"))+ if hip_id is None or hip_id < 0 or hip_id != int(hip_id):+ return None+ mapping[idx] = int(hip_id)+ # A collision means the ids describe something other than a 1:1 device mapping.+ if not mapping or len(set(mapping.values())) != len(mapping):+ return None+ return mapping++def _first_visible_amd_gpu_id() -> Optional[str]:"""Return the physical AMD GPU id treated as 'primary'.@@ -438,43 +586,11 @@ def get_visible_gpu_utilization("index_kind": "physical",}- # Extract a device list across envelope shapes: a JSON array, a dict under- # "gpu_data"/"gpus"/"gpu", or a guarded scalar/string fallback.- if isinstance(data, list):- gpu_list = data- elif isinstance(data, dict):- gpu_list = data.get("gpu_data", data.get("gpus", data.get("gpu", [data])))- else:- gpu_list = [data]visible_set = set(parent_visible_ids)ordinal_map = {gpu_id: ordinal for ordinal, gpu_id in enumerate(parent_visible_ids)}devices = []- for fallback_idx, gpu_data in enumerate(gpu_list):- # Skip non-dict entries (a scalar in the array would raise AttributeError).- if not isinstance(gpu_data, dict):- continue- # Use the AMD-reported GPU ID, else the enumeration index. _parse_numeric- # handles bare ints/floats/strings and the {"value", "unit"} dict shape.- raw_id = gpu_data.get("gpu", gpu_data.get("gpu_id", gpu_data.get("id", fallback_idx)))- parsed_id = _parse_numeric(raw_id)- if parsed_id is None:- logger.warning(- "amd-smi GPU id %r could not be parsed; falling back to enumeration index %d",- raw_id,- fallback_idx,- )- idx = fallback_idx- else:- rounded = round(parsed_id)- if rounded != parsed_id:- logger.warning(- "amd-smi GPU id %r parsed as non-integer %r; truncating to %d",- raw_id,- parsed_id,- rounded,- )- idx = int(rounded)+ for idx, gpu_data in _gpu_entries(data):if idx not in visible_set:continuemetrics = _extract_gpu_metrics(gpu_data)