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(hardware): report driver-level free VRAM in the GPU summary (#9362)
yzxcj7979e11d53a3081
diff --git a/studio/backend/tests/manual/windows_rocm_vram_check.py b/studio/backend/tests/manual/windows_rocm_vram_check.pynew file mode 100644index 00000000000..20e52c0a5eb--- /dev/null+++ b/studio/backend/tests/manual/windows_rocm_vram_check.py@@ -0,0 +1,428 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""TEMPORARY hardware check for Windows + AMD ROCm. Delete before merge.++CI cannot reach these paths. The AMD runner is Linux, so+``rocm_windows_free_is_untrusted()`` is False there and the WDDM cap never+executes; ``_amd_smi_allowed()`` never takes its Windows branch either. Both+are currently argued from code and simulation, not measured.++This answers three questions on a real Windows ROCm box:++ 1. Does ``free_gb`` move when ANOTHER process holds VRAM? That is the PR's+ entire claim, and it is the one that could silently be a no-op here:+ hipMemGetInfo is system-wide on Linux but process-local on Windows WDDM.+ 2. Does reading the summary ever spawn amd-smi? On Windows without a HIP SDK+ it elevates a child and pops a UAC/DiskPart prompt, so the answer must be+ no spawns.+ 3. What do the Windows-only gates actually evaluate to?++Run from ``studio/backend`` with the Studio venv's python::++ python tests/manual/windows_rocm_vram_check.py --gib 4++Add ``--json out.json`` to save the raw readings. Holding 4 GiB needs a card+with at least ~6 GiB free; lower it with ``--gib`` on a smaller GPU.+"""++from __future__ import annotations++import argparse+import json+import os+import platform+import queue+import subprocess+import sys+import threading+import time+from pathlib import Path++GIB = 1024**3++# Run from studio/backend, or from anywhere: resolve the backend root either way.+BACKEND = Path(__file__).resolve().parents[2]+if str(BACKEND) not in sys.path:+ sys.path.insert(0, str(BACKEND))+++# ========== holder ==========+++def run_holder(gib: float, max_seconds: int) -> int:+ """Hold VRAM in this process and announce readiness on stdout."""+ import torch++ if not torch.cuda.is_available():+ print(json.dumps({"status": "ERROR", "error": "no cuda/hip device"}), flush = True)+ return 2++ # TOUCHED, not merely allocated: an uncommitted allocation is not what a+ # resident model is, and on WDDM it may not be committed to VRAM at all.+ chunks, held, step = [], 0, 256 * 1024 * 1024+ want = int(gib * GIB)+ while held < want:+ t = torch.empty(step, dtype = torch.uint8, device = "cuda")+ t.fill_(1)+ chunks.append(t)+ held += step+ torch.cuda.synchronize()+ print(+ json.dumps(+ {+ "status": "READY",+ "pid": os.getpid(),+ "held_gib": held / GIB,+ "allocated_gib": torch.cuda.memory_allocated() / GIB,+ }+ ),+ flush = True,+ )++ deadline = time.time() + max_seconds+ while time.time() < deadline:+ time.sleep(1)+ return 0+++# ========== observer ==========+++def _count_amd_smi_spawns(fn):+ """Run fn() with every subprocess spawn recorded, and return the amd-smi ones.++ Patches both entry points: amd.py uses subprocess.run, but a UAC prompt from+ a Popen would be just as visible to a user.+ """+ seen: list[list[str]] = []+ real_run, real_popen = subprocess.run, subprocess.Popen++ def record(args):+ try:+ argv = [str(a) for a in (args if isinstance(args, (list, tuple)) else [args])]+ except Exception: # noqa: BLE001+ return+ if argv and "amd-smi" in os.path.basename(argv[0]).lower():+ seen.append(argv)++ def fake_run(*a, **kw):+ if a:+ record(a[0])+ return real_run(*a, **kw)++ def fake_popen(*a, **kw):+ if a:+ record(a[0])+ return real_popen(*a, **kw)++ subprocess.run, subprocess.Popen = fake_run, fake_popen+ try:+ result = fn()+ finally:+ subprocess.run, subprocess.Popen = real_run, real_popen+ return result, seen+++def _reading(hw, torch) -> dict:+ """One observation. The observer must stay a bystander or this is self-measurement."""+ props = torch.cuda.get_device_properties(torch.cuda.current_device())+ allocated = torch.cuda.memory_allocated()+ mem = hw.get_gpu_memory_info()+ out = {+ "free_gb": mem.get("free_gb"),+ "total_gb": mem.get("total_gb"),+ "allocated_gb": mem.get("allocated_gb"),+ "reserved_gb": mem.get("reserved_gb"),+ # The pre-PR expression, evaluated here so the base leg is present+ # without needing a second checkout. It is blind to other processes by+ # construction, and that is the point.+ "old_formula_free_gb": (props.total_memory - allocated) / GIB,+ "observer_allocated_gb": allocated / GIB,+ }+ try:+ free_b, _total_b = torch.cuda.mem_get_info()+ out["torch_mem_get_info_free_gb"] = free_b / GIB+ except Exception as e: # noqa: BLE001+ out["torch_mem_get_info_error"] = f"{type(e).__name__}: {e}"+ return out+++def _wait_for_ready(proc, timeout: float) -> dict | None:+ """Poll for the holder's READY line. Never sleep a fixed interval instead."""+ q: queue.Queue = queue.Queue()++ def pump():+ for line in proc.stdout:+ q.put(line)+ q.put(None)++ threading.Thread(target = pump, daemon = True).start()+ deadline = time.time() + timeout+ while time.time() < deadline:+ try:+ line = q.get(timeout = 1.0)+ except queue.Empty:+ if proc.poll() is not None:+ return None+ continue+ if line is None:+ return None+ line = line.strip()+ if not line.startswith("{"):+ continue+ try:+ msg = json.loads(line)+ except ValueError:+ continue+ if msg.get("status") == "READY":+ return msg+ if msg.get("status") == "ERROR":+ return None+ return None+++def main() -> int:+ ap = argparse.ArgumentParser(description = __doc__)+ ap.add_argument("--holder", action = "store_true", help = argparse.SUPPRESS)+ ap.add_argument("--gib", type = float, default = 4.0)+ ap.add_argument("--max-seconds", type = int, default = 300)+ ap.add_argument("--json", type = Path, default = None)+ args = ap.parse_args()++ if args.holder:+ return run_holder(args.gib, args.max_seconds)++ import torch++ from utils.hardware import hardware as hw++ # IS_ROCM is False at import and is only set by detect_hardware(). Reading+ # the gates without this reports every ROCm branch as inactive on a ROCm+ # box, and the run then describes a path the machine never took.+ try:+ detected = str(hw.detect_hardware())+ except Exception as e: # noqa: BLE001+ detected = f"error: {type(e).__name__}: {e}"++ report: dict = {+ "platform": platform.platform(),+ "python": sys.version.split()[0],+ "torch": torch.__version__,+ "hip": getattr(torch.version, "hip", None),+ "cuda": getattr(torch.version, "cuda", None),+ "hardware_module": hw.__file__,+ "detect_hardware": detected,+ }++ if not torch.cuda.is_available():+ report["fatal"] = "no cuda/hip device visible to torch"+ print(json.dumps(report, indent = 2))+ return 2++ props = torch.cuda.get_device_properties(torch.cuda.current_device())+ report["gpu"] = {+ "name": props.name,+ "arch": getattr(props, "gcnArchName", None),+ "props_total_gb": props.total_memory / GIB,+ "is_integrated": getattr(props, "is_integrated", None),+ }++ # --- gates: what the Windows-only branches actually decide here ---+ def _safe(fn, *a):+ try:+ return fn(*a)+ except Exception as e: # noqa: BLE001+ return f"error: {type(e).__name__}: {e}"++ gates = {+ "IS_ROCM": getattr(hw, "IS_ROCM", None),+ "rocm_windows_free_is_untrusted": _safe(hw.rocm_windows_free_is_untrusted),+ "rocm_props_total_is_carve_out": _safe(hw._rocm_props_total_is_carve_out, props),+ "rocm_device_ordinal_active": _safe(hw._rocm_device_ordinal_active),+ }+ try:+ from utils.hardware import amd as _amd+ gates["amd_smi_allowed"] = _safe(_amd._amd_smi_allowed)+ except Exception as e: # noqa: BLE001+ gates["amd_smi_allowed"] = f"error: {type(e).__name__}: {e}"+ gates["env"] = {+ k: os.environ.get(k)+ for k in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ "CUDA_VISIBLE_DEVICES",+ "UNSLOTH_ENABLE_AMD_SMI",+ )+ }+ report["gates"] = gates++ # --- question 2: does reading the summary spawn amd-smi at all? ---+ # Asked BEFORE anything below pins a context, since that is the state a real+ # idle backend is in.+ #+ # Two calls, because "0 spawns" means different things on different boxes.+ # With a HIP SDK present amd-smi is ALLOWED and a spawn is correct, so the+ # as-configured run cannot by itself exercise the guard. The forced run+ # drives _amd_smi_allowed() to False explicitly, which every new call site+ # must honour whatever the host looks like.+ import shutil++ _summary, spawns = _count_amd_smi_spawns(hw.get_gpu_summary)+ report["amd_smi_spawns_during_summary"] = spawns+ report["amd_smi_on_path"] = shutil.which("amd-smi") or shutil.which("amd-smi.exe")++ prior = os.environ.get("UNSLOTH_ENABLE_AMD_SMI")+ os.environ["UNSLOTH_ENABLE_AMD_SMI"] = "0"+ try:+ _s2, spawns_refused = _count_amd_smi_spawns(hw.get_gpu_summary)+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_ENABLE_AMD_SMI", None)+ else:+ os.environ["UNSLOTH_ENABLE_AMD_SMI"] = prior+ report["amd_smi_spawns_when_refused"] = spawns_refused++ # --- questions 1: does free move when someone ELSE holds memory? ---+ # Warm the primary context FIRST. _reading calls mem_get_info, which pins+ # roughly 600 MiB on first use; without this the observer's own context+ # lands between the two readings and is charged to the holder.+ try:+ torch.cuda.mem_get_info()+ except Exception as e: # noqa: BLE001+ report["context_warmup_error"] = f"{type(e).__name__}: {e}"+ report["before"] = _reading(hw, torch)++ proc = subprocess.Popen(+ [+ sys.executable,+ str(Path(__file__).resolve()),+ "--holder",+ "--gib",+ str(args.gib),+ "--max-seconds",+ str(args.max_seconds),+ ],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ )+ ready = _wait_for_ready(proc, timeout = 180)+ report["holder"] = ready+ if ready:+ report["with_holder"] = _reading(hw, torch)+ # Stop by PID. Never pkill by pattern: it matches the shell running it.+ proc.terminate()+ try:+ proc.wait(timeout = 30)+ except subprocess.TimeoutExpired:+ proc.kill()+ time.sleep(3)+ report["after"] = _reading(hw, torch)++ print(json.dumps(report, indent = 2))+ if args.json:+ args.json.write_text(json.dumps(report, indent = 2))++ # --- verdict ---+ print("\n" + "=" * 62)+ if not ready:+ print("INCONCLUSIVE: the holder never became ready, so nothing was")+ print("measured against it. A differential against a condition that was")+ print("never established is no result, not a failing one.")+ return 3++ held = float(ready.get("allocated_gib") or 0.0)+ before, during = report["before"], report["with_holder"]+ # The holder costs its tensor PLUS its own primary context, so the driver's+ # free legitimately drops by more than `held`. The question is binary --+ # did free track another process at all, or not move -- so this is a band,+ # not a point. Anything under `floor` means the other process was invisible.+ floor, ceiling = 0.9 * held, held + 2.0++ new_drop = (before["free_gb"] or 0) - (during["free_gb"] or 0)+ old_drop = before["old_formula_free_gb"] - during["old_formula_free_gb"]+ mgi_drop = None+ if "torch_mem_get_info_free_gb" in before and "torch_mem_get_info_free_gb" in during:+ mgi_drop = before["torch_mem_get_info_free_gb"] - during["torch_mem_get_info_free_gb"]++ print(f"holder held {held:.2f} GiB (plus its own context)")+ print(f"accepted band {floor:.2f} to {ceiling:.2f} GiB")+ print(f"free_gb dropped by {new_drop:+.2f} GiB (want >= {floor:.2f})")+ print(f"old formula dropped by {old_drop:+.2f} GiB (want ~0.00, the defect)")+ if mgi_drop is not None:+ print(f"torch.mem_get_info dropped {mgi_drop:+.2f} GiB (attribution only)")+ print(f"observer stayed a bystander {during['observer_allocated_gb']:.2f} GiB allocated")+ allowed = gates.get("amd_smi_allowed")+ print(f"amd-smi on PATH {report['amd_smi_on_path'] or 'no'}")+ print(f"amd-smi allowed here {allowed}")+ print(+ f"amd-smi spawns, as configured {len(spawns)}"+ f"{' (allowed, so not a fault)' if allowed is True else ''}"+ )+ print(f"amd-smi spawns, when refused {len(spawns_refused)} (want 0)")++ problems = []+ # A ROCm build whose ROCm gates read False means detection did not take, and+ # every gate below describes a branch this machine never executed.+ if getattr(torch.version, "hip", None) and not gates.get("IS_ROCM"):+ problems.append(+ "torch is a ROCm build but hw.IS_ROCM is False, so the gate dump "+ "describes the non-ROCm path: do not trust it"+ )+ if during["observer_allocated_gb"] >= 0.5:+ problems.append("observer allocated memory itself, so this measures the wrong thing")+ if abs(old_drop) > 0.5:+ problems.append("the OLD formula moved, so the base does not show the defect here: VOID")+ if new_drop < floor:+ problems.append(+ f"free_gb moved only {new_drop:.2f} GiB against {held:.2f} GiB held: "+ f"the other process is largely invisible here"+ )+ elif new_drop > ceiling:+ problems.append(+ f"free_gb moved {new_drop:.2f} GiB, more than {held:.2f} GiB held plus "+ f"2.00 GiB of process overhead: free is being under-reported"+ )+ # A spawn is only a fault where the guard said no. With a HIP SDK present+ # amd-smi is allowed and calling it is the intended behaviour.+ if allowed is False and spawns:+ problems.append(+ f"amd-smi was spawned {len(spawns)}x despite _amd_smi_allowed() being "+ f"False, which is the UAC/DiskPart prompt path: {spawns}"+ )+ if spawns_refused:+ problems.append(+ f"amd-smi was spawned {len(spawns_refused)}x with UNSLOTH_ENABLE_AMD_SMI=0, "+ f"so a call site bypasses the guard: {spawns_refused}"+ )++ print("=" * 62)+ if problems:+ print("PROBLEMS FOUND")+ for p in problems:+ print(" - " + p)+ if mgi_drop is not None and abs(mgi_drop) < 0.5 and new_drop < floor:+ print("\n Note: torch.cuda.mem_get_info did not move either, so the")+ print(" driver itself is reporting process-local free here (WDDM),")+ print(" rather than this being a bug in the PR's own logic.")+ return 1+ print(f"PASS: free_gb tracked another process's {held:.2f} GiB, the old formula")+ print("did not, and no call site spawned amd-smi once the guard refused.")+ # State the reach of the amd-smi result rather than letting PASS imply more.+ if platform.system() != "Windows":+ print("\n Note: not Windows, so _amd_smi_allowed() returned True by")+ print(" platform and the elevation guard was never under test.")+ elif not report["amd_smi_on_path"]:+ print("\n Note: amd-smi is not on PATH, so zero spawns is trivially true.")+ print(" The refusal path is confirmed, the real no-SDK case is not.")+ elif allowed is True:+ print("\n Note: a HIP SDK is present, so amd-smi is legitimately allowed")+ print(" here. The forced-refusal leg passed, but the genuine")+ print(" Windows-without-a-HIP-SDK case needs a box without one.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.pyindex 02c583b2e1c..2d4220ead3d 100644--- a/studio/backend/tests/test_rocm_windows_vram_7072.py+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py@@ -206,12 +206,94 @@ def test_match_adapter_pairs_and_clamps():assert hw._match_adapter_used_to_devices([40 * GB], [48 * GB, 8 * GB]) == [40 * GB, None]+def test_match_adapter_pairs_single_device_past_placeholder_adapters():+ # Exactly the shape a gfx1151 Strix Halo host emits: three counter instances,+ # two of them placeholders at EXACTLY 0, one visible device. An adapter at zero+ # has nothing committed and so cannot hold the survivor's bytes, which is what+ # makes this attributable. Before this, the capacity test needed a next-smaller+ # device to compare against and discarded the survivor as unknown.+ assert hw._match_adapter_used_to_devices([1.2 * GB, 0.0, 0.0], [89 * GB]) == [1.2 * GB]+ # Order of the counters must not matter.+ assert hw._match_adapter_used_to_devices([0.0, 1.2 * GB, 0.0], [89 * GB]) == [1.2 * GB]+ # Still clamped: a hidden larger adapter must not report a fully-used card.+ assert hw._match_adapter_used_to_devices([100 * GB, 0.0, 0.0], [48 * GB]) == [None]+ assert hw._match_adapter_used_to_devices([40 * GB, 0.0], [48 * GB]) == [40 * GB]+ # Zero is what makes it attributable, not the cardinality. A merely sub-floor+ # counter can be the visible card idle, making the survivor a hidden GPU's --+ # that shape must stay unknown (see the [6 GiB, 10 MiB] case below).+ assert hw._match_adapter_used_to_devices([1.2 * GB, 10 * MiB, 0.0], [89 * GB]) == [None]++def test_match_adapter_reports_unknown_when_more_active_than_visible():# More adapters actively using VRAM than are visible (a GPU outside the mask):# attribution would fabricate a value, so report unknown for every device.assert hw._match_adapter_used_to_devices([40 * GB, 0.5 * GB], [8 * GB]) == [None]+def test_unified_used_sums_dedicated_and_shared_for_the_compute_adapter(monkeypatch):+ # On an APU, Dedicated saturates at the carve-out and the overflow lands in+ # Shared, so only the sum tracks the allocation (measured: 48 GiB held reports+ # +29.19 dedicated, +19.02 shared on a gfx1151 host).+ def fake(counter = "Dedicated Usage"):+ if counter == "Dedicated Usage":+ return [("luid_compute", 30.5 * GB), ("luid_placeholder", 0.0)]+ return [("luid_compute", 19.0 * GB), ("luid_placeholder", 1.3 * GB)]++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)+ assert hw._rocm_windows_unified_used_bytes() == 30.5 * GB + 19.0 * GB+++def test_unified_used_selects_on_dedicated_not_the_sum(monkeypatch):+ # A display adapter reports 0 dedicated while holding gigabytes of shared.+ # Selecting on the sum would see two candidates and either bail or add a+ # foreign adapter's bytes; selecting on dedicated isolates the compute device.+ def fake(counter = "Dedicated Usage"):+ if counter == "Dedicated Usage":+ return [("luid_compute", 1.2 * GB), ("luid_display", 0.0)]+ return [("luid_compute", 0.15 * GB), ("luid_display", 1.3 * GB)]++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)+ assert hw._rocm_windows_unified_used_bytes() == 1.2 * GB + 0.15 * GB+++def test_unified_used_declines_when_the_compute_adapter_is_ambiguous(monkeypatch):+ # Two adapters above the floor: no key says which is visible, so report None+ # rather than pick one, matching _rocm_windows_aggregate_used_bytes.+ def two(counter = "Dedicated Usage"):+ return [("luid_a", 1.2 * GB), ("luid_b", 2.4 * GB)]++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", two)+ assert hw._rocm_windows_unified_used_bytes() is None++ # Every adapter below the floor: nothing to stand on.+ monkeypatch.setattr(+ hw,+ "_rocm_windows_perf_counter_vram_by_adapter",+ lambda counter = "Dedicated Usage": [("luid_a", 10 * MiB)],+ )+ assert hw._rocm_windows_unified_used_bytes() is None++ # Counter unavailable entirely.+ monkeypatch.setattr(+ hw,+ "_rocm_windows_perf_counter_vram_by_adapter",+ lambda counter = "Dedicated Usage": None,+ )+ assert hw._rocm_windows_unified_used_bytes() is None+++def test_unified_used_declines_rather_than_falling_back_to_dedicated_only(monkeypatch):+ # Dedicated-only is correct BELOW the carve-out and wrong above it, and nothing+ # here knows which side a reading is on: on the measured host 30.5 GiB is both a+ # legitimate below-carve-out figure and a saturated one. So a failed Shared query+ # declines instead of degrading to dedicated, which would overstate free.+ def fake(counter = "Dedicated Usage"):+ return [("luid_compute", 1.2 * GB)] if counter == "Dedicated Usage" else None++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)+ assert hw._rocm_windows_unified_used_bytes() is None++def test_match_adapter_reports_unknown_when_hidden_high_use_adapter_survives_filter():# Idle 8 GiB card (10 MiB noise) beside a hidden 48 GiB card at 40 GiB: the# 40 GiB can't fit the 8 GiB device, so clamping there would fabricate. Unknown.@@ -360,3 +442,57 @@ def test_unified_memory_no_op_when_torch_total_not_larger():assert metrics["vram_total_gb"] == 48.0assert metrics["vram_used_gb"] == 10.0assert metrics["vram_utilization_pct"] == 20.8+++def test_unified_used_declines_when_the_shared_query_fails(monkeypatch):+ # Past the carve-out the overflow lives entirely in Shared, so treating a+ # FAILED shared query as zero reports the measured 48 GiB case as 30.5 and+ # overstates free by 19 GiB. Nothing here knows where the carve-out sits, so+ # a failed query has to decline rather than guess.+ def fake(counter = "Dedicated Usage"):+ return [("luid_compute", 30.5 * GB)] if counter == "Dedicated Usage" else None++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)+ assert hw._rocm_windows_unified_used_bytes() is None+++def test_unified_used_keeps_a_successful_query_that_omits_the_luid(monkeypatch):+ # A query that SUCCEEDS but has no row for this adapter is a real zero, not a+ # failure, and must stay usable.+ def fake(counter = "Dedicated Usage"):+ if counter == "Dedicated Usage":+ return [("luid_compute", 1.2 * GB)]+ return [("luid_other", 3.0 * GB)]++ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)+ assert hw._rocm_windows_unified_used_bytes() == 1.2 * GB+++def test_per_device_vram_uses_the_snapshot_it_is_given(monkeypatch):+ # The caller validates a snapshot's cardinality before trusting the mapping.+ # Re-sampling here would apply that check to a different sample than+ # attribution runs on, and costs a second ~1.3 s PowerShell call.+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setattr(+ hw,+ "_rocm_windows_perf_counter_vram_by_adapter",+ lambda counter = "Dedicated Usage": (_ for _ in ()).throw(+ AssertionError("must not re-sample when a snapshot was passed in")+ ),+ )+ monkeypatch.setattr(+ hw,+ "_torch_get_device_module",+ lambda: (+ types.SimpleNamespace(+ get_device_properties = lambda _o: types.SimpleNamespace(+ name = "APU", total_memory = 89 * GB+ )+ ),+ None,+ ),+ )++ devices, _agg = hw._rocm_windows_per_device_vram([0], [("a", 1.2 * GB)])++ assert devices[0]["used_gb"] == round(1.2 * GB / (1024**3), 2)diff --git a/studio/backend/tests/test_system_poll_no_cuda_context.py b/studio/backend/tests/test_system_poll_no_cuda_context.pyindex 47ea26d7ca0..a6e7aee1d2b 100644--- a/studio/backend/tests/test_system_poll_no_cuda_context.py+++ b/studio/backend/tests/test_system_poll_no_cuda_context.py@@ -21,6 +21,7 @@ would mask the regression.from __future__ import annotationsimport importlib+import osimport subprocessimport sysimport textwrap@@ -166,6 +167,652 @@ def test_the_probe_would_catch_a_regression():assert mib > 0, "mem_get_info created no context here, so the assertions above prove nothing"+def _summary_torch(*, properties_total, driver_free, driver_total):+ props = types.SimpleNamespace(total_memory = properties_total, name = "Test GPU")++ def _mem_get_info(_ordinal):+ if driver_free is None:+ raise AssertionError("the native probe answered; mem_get_info would pin a context")+ return driver_free, driver_total++ cuda = types.SimpleNamespace(+ current_device = lambda: 0,+ get_device_properties = lambda _ordinal: props,+ memory_allocated = lambda _ordinal: 1 << 30,+ memory_reserved = lambda _ordinal: 2 << 30,+ mem_get_info = _mem_get_info,+ )+ return types.SimpleNamespace(cuda = cuda), props+++def test_gpu_summary_prefers_context_free_driver_memory(monkeypatch):+ gib = 1 << 30+ torch_stub, _props = _summary_torch(+ properties_total = 16 * gib,+ driver_free = None,+ driver_total = 16 * gib,+ )+ monkeypatch.setitem(sys.modules, "torch", torch_stub)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: {+ "available": True,+ "devices": [{"visible_ordinal": 0, "vram_used_gb": 7.0, "vram_total_gb": 16.0}],+ },+ )++ summary = hw.get_gpu_summary()++ assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 16.0, "vram_free_gb": 9.0}+++def test_gpu_summary_pairs_rocm_apu_free_with_driver_total(monkeypatch):+ gib = 1 << 30+ torch_stub, _props = _summary_torch(+ properties_total = 8 * gib,+ driver_free = 98 * gib,+ driver_total = 100 * gib,+ )+ monkeypatch.setitem(sys.modules, "torch", torch_stub)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda _props: True)+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("an APU needs hipMemGetInfo's matching GTT total"),+ )+ # No WDDM counter reading available: free falls back to hipMemGetInfo's.+ monkeypatch.setattr(hw, "_rocm_windows_unified_used_bytes", lambda: None)++ summary = hw.get_gpu_summary()++ assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 100.0, "vram_free_gb": 98.0}+++def test_gpu_summary_apu_prefers_wddm_counters_over_process_local_hip(monkeypatch):+ # hipMemGetInfo is process-local on Windows WDDM, so an APU takes its GTT+ # *total* from HIP but its *used* from the counters. Driver says 98 free of+ # 100; the counters say 40 GiB is in use across all processes -> 60 free.+ gib = 1 << 30+ torch_stub, _props = _summary_torch(+ properties_total = 8 * gib,+ driver_free = 98 * gib,+ driver_total = 100 * gib,+ )+ monkeypatch.setitem(sys.modules, "torch", torch_stub)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda _props: True)+ monkeypatch.setattr(hw, "_rocm_props_are_positively_unified", lambda _props: True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("an APU must not take its total from the vendor CLI"),+ )+ monkeypatch.setattr(hw, "_rocm_windows_unified_used_bytes", lambda: 40.0 * gib)++ summary = hw.get_gpu_summary()++ # Total still HIP's, free now derived from the counters against that total.+ assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 100.0, "vram_free_gb": 60.0}+++def test_context_free_rocm_smi_translates_hip_ordinals(monkeypatch):+ from utils.hardware import amd++ gib = 1 << 30+ monkeypatch.setattr(hw, "IS_ROCM", True)+ # The visibility vars are read from the real environment on the way through,+ # so a runner that exports one (a CI job pinning a GPU beside this test) can+ # change the outcome. Its siblings already isolate; this one did not.+ for name in (+ "GPU_DEVICE_ORDINAL",+ "ROCR_VISIBLE_DEVICES",+ "HIP_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ ):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(amd, "get_hip_id_by_gpu_index", lambda: {0: 1, 1: 0})+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: 2)++ # amd-smi GPU 1 is HIP 0 and owns the 96 GiB pool. Passing HIP ids through+ # unchanged would instead publish GPU 0's 1 GiB free for torch device 0.+ readings = {0: (15.0, 16.0), 1: (2.0, 96.0)}++ def _smi(_name, visible_ids, **_kwargs):+ return {+ "available": True,+ "devices": [+ {+ "index": smi_id,+ "visible_ordinal": ordinal,+ "vram_used_gb": readings[smi_id][0],+ "vram_total_gb": readings[smi_id][1],+ }+ for ordinal, smi_id in enumerate(visible_ids)+ ],+ }++ monkeypatch.setattr(hw, "_smi_query", _smi)++ assert hw._context_free_cuda_memory_info(0, 96 * gib) == 94 * gib+++def test_context_free_rocm_smi_declines_without_an_id_mapping(monkeypatch):+ from utils.hardware import amd++ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Darwin")+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(amd, "get_hip_id_by_gpu_index", lambda: None)+ monkeypatch.setattr(amd, "get_physical_gpu_count", lambda: 2)+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("an unproven amd-smi/HIP mapping must be declined"),+ )++ assert hw._context_free_cuda_memory_info(0, 16 << 30) is None+++def test_context_free_rocm_smi_declines_stacked_visibility_masks(monkeypatch):+ from utils.hardware import amd++ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.sys, "platform", "linux")+ monkeypatch.setattr(hw.platform, "system", lambda: "Darwin")+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,2")+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": "0", "numeric_ids": [0], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ amd,+ "get_hip_id_by_gpu_index",+ lambda: pytest.fail("stacked masks have no global HIP mapping"),+ )+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("stacked masks must decline amd-smi telemetry"),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) is None+++def test_context_free_rocm_smi_declines_gpu_device_ordinal(monkeypatch):+ from utils.hardware import amd++ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Darwin")+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", "1")+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ amd,+ "get_hip_id_by_gpu_index",+ lambda: pytest.fail("GPU_DEVICE_ORDINAL makes the global mapping unusable"),+ )+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("an external GPU ordinal filter must decline amd-smi"),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) is None+++def test_context_free_rocm_smi_declines_inventory_count_mismatch(monkeypatch):+ from utils.hardware import amd++ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Darwin")+ for name in (+ "GPU_DEVICE_ORDINAL",+ "ROCR_VISIBLE_DEVICES",+ "HIP_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ ):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(amd, "get_hip_id_by_gpu_index", lambda: {0: 0, 1: 1})+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: 1)+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("amd-smi and HIP inventory counts must agree"),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) is None+++def test_context_free_nvidia_smi_resolves_a_uuid_mask(monkeypatch):+ from utils.hardware import nvidia++ gib = 1 << 30+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {+ "raw": "GPU-bbbbbbbb",+ "numeric_ids": None,+ "supports_explicit_gpu_ids": False,+ },+ )++ def _run(command, **_kwargs):+ assert "--query-gpu=index,uuid,utilization.gpu,temperature.gpu," in command[1]+ return types.SimpleNamespace(+ returncode = 0,+ stdout = "\n".join(+ [+ "0, GPU-aaaaaaaa-1111-2222-3333-444444444444, 5, 30, 15360, 16384, 100, 300",+ "1, GPU-bbbbbbbb-1111-2222-3333-444444444444, 7, 31, 2048, 98304, 120, 350",+ ]+ ),+ )++ monkeypatch.setattr(nvidia.subprocess, "run", _run)++ assert hw._context_free_cuda_memory_info(0, 96 * gib) == 94 * gib+++def test_nvidia_uuid_mask_keeps_public_indices_relative(monkeypatch):+ from utils.hardware import nvidia++ def _run(_command, **_kwargs):+ return types.SimpleNamespace(+ returncode = 0,+ stdout = "\n".join(+ [+ "0, GPU-aaaaaaaa-1111-2222-3333-444444444444, 5, 30, 15360, 16384, 100, 300",+ "1, GPU-bbbbbbbb-1111-2222-3333-444444444444, 7, 31, 2048, 98304, 120, 350",+ ]+ ),+ )++ monkeypatch.setattr(nvidia.subprocess, "run", _run)++ result = nvidia.get_visible_gpu_utilization(+ None,+ "GPU-bbbbbbbb,GPU-aaaaaaaa",+ )++ assert result["index_kind"] == "relative"+ assert result["parent_visible_gpu_ids"] == []+ assert {device["visible_ordinal"]: device["index"] for device in result["devices"]} == {+ 0: 0,+ 1: 1,+ }+ # The mask asks for the b-card first, so ordinal 0 must carry the b-card's+ # 2048 MiB, not the a-card's 15360. List position has to agree with it too:+ # nvidia-smi emitted these rows the other way round.+ assert [device["vram_used_gb"] for device in result["devices"]] == [2.0, 15.0]+ assert [device["visible_ordinal"] for device in result["devices"]] == [0, 1]+++def _nvidia_smi_reading(monkeypatch, used_gb, driver_total_gb):+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: {+ "available": True,+ "devices": [+ {"visible_ordinal": 0, "vram_used_gb": used_gb, "vram_total_gb": driver_total_gb}+ ],+ },+ )+++def test_context_free_free_excludes_the_reserved_framebuffer(monkeypatch):+ # nvidia-smi reports reserved separately from used, and torch's total already+ # excludes it. Subtracting used from the DRIVER total would hand back that+ # reservation as free: 100 - 2 = 98 where only 97.5 is allocatable.+ gib = 1 << 30+ _nvidia_smi_reading(monkeypatch, used_gb = 2.0, driver_total_gb = 100.0)+ assert hw._context_free_cuda_memory_info(0, round(99.5 * gib)) == round(97.5 * gib)+++def test_context_free_free_is_zero_on_a_full_card(monkeypatch):+ # The reservation is the whole margin here: a card with every allocatable byte+ # taken must not be advertised as having the reserved 0.5 GiB free.+ gib = 1 << 30+ _nvidia_smi_reading(monkeypatch, used_gb = 99.5, driver_total_gb = 100.0)+ assert hw._context_free_cuda_memory_info(0, round(99.5 * gib)) == 0+++def test_context_free_free_never_goes_negative(monkeypatch):+ # A stale or over-subscribed reading can exceed torch's total.+ gib = 1 << 30+ _nvidia_smi_reading(monkeypatch, used_gb = 120.0, driver_total_gb = 100.0)+ assert hw._context_free_cuda_memory_info(0, round(99.5 * gib)) == 0+++def test_context_free_declines_when_cuda_order_is_not_pci_bus_id(monkeypatch):+ # CUDA enumerates FASTEST_FIRST while nvidia-smi reports PCI order, so torch+ # ordinal 0 need not be row 0. Two equal-sized cards (a 3090 beside a 4090)+ # slip past the total-scope check, so only the order gate catches it.+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ _nvidia_smi_reading(monkeypatch, used_gb = 2.0, driver_total_gb = 24.0)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 2)+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: pytest.fail("an unshared index space must decline SMI telemetry"),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) is None+++def test_context_free_keeps_smi_on_a_single_gpu_under_fastest_first(monkeypatch):+ # One card makes every ordering the identity, so the gate must not cost this+ # host a permanent primary context.+ gib = 1 << 30+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ _nvidia_smi_reading(monkeypatch, used_gb = 2.0, driver_total_gb = 24.0)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 1)+ monkeypatch.setattr(hw, "_physical_gpu_count_from_smi", True)++ assert hw._context_free_cuda_memory_info(0, 24 * gib) == 22 * gib+++def test_context_free_declines_when_the_gpu_count_is_not_smi_confirmed(monkeypatch):+ # `nvidia-smi -L` failing falls back to torch, which counts VISIBLE devices,+ # so a one-device mask on a multi-GPU host reads as single-GPU. Granting the+ # exemption there reads the mask in nvidia-smi's index space, which under+ # FASTEST_FIRST can be a different card. The count is cached, so one+ # transient timeout would disable the gate for the life of the process.+ gib = 1 << 30+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ _nvidia_smi_reading(monkeypatch, used_gb = 2.0, driver_total_gb = 24.0)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 1)+ monkeypatch.setattr(hw, "_physical_gpu_count_from_smi", False)++ assert hw._context_free_cuda_memory_info(0, 24 * gib) is None+++def test_physical_gpu_count_records_whether_the_smi_answered(monkeypatch):+ from utils.hardware import nvidia++ # The flag is what the order gate reads, so it must track the SOURCE of the+ # count, not merely that one was produced.+ monkeypatch.setattr(hw, "_physical_gpu_count", None)+ monkeypatch.setattr(hw, "_physical_gpu_count_from_smi", False)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(nvidia, "get_physical_gpu_count", lambda: 4)+ assert hw.get_physical_gpu_count() == 4+ assert hw._physical_gpu_count_from_smi is True++ monkeypatch.setattr(hw, "_physical_gpu_count", None)+ monkeypatch.setattr(hw, "_physical_gpu_count_from_smi", False)+ monkeypatch.setattr(nvidia, "get_physical_gpu_count", lambda: None)+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: 1)+ assert hw.get_physical_gpu_count() == 1+ assert hw._physical_gpu_count_from_smi is False+++def test_free_in_torch_scope_never_exceeds_the_total(monkeypatch):+ # Both SMI parsers accept signed values, so a transient negative used counter+ # would otherwise advertise more free than the card holds. utilization_pct+ # and the training-method policy both read this.+ gib = 1 << 30+ assert hw._free_in_torch_scope(24 * gib, -1.0) == 24 * gib+ assert hw._free_in_torch_scope(24 * gib, 0.0) == 24 * gib+ assert hw._free_in_torch_scope(24 * gib, 2.0) == 22 * gib+ assert hw._free_in_torch_scope(24 * gib, 99.0) == 0+++def test_context_free_uuid_mask_skips_the_cuda_order_gate(monkeypatch):+ from utils.hardware import nvidia++ # A UUID mask names its devices absolutely and CUDA enumerates them in the+ # order listed, so FASTEST_FIRST changes nothing. Declining here would spend+ # the ~612 MiB primary context this whole path exists to avoid.+ gib = 1 << 30+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 2)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {+ "raw": "GPU-bbbbbbbb",+ "numeric_ids": None,+ "supports_explicit_gpu_ids": False,+ },+ )++ def _run(_command, **_kwargs):+ return types.SimpleNamespace(+ returncode = 0,+ stdout = "\n".join(+ [+ "0, GPU-aaaaaaaa-1111-2222-3333-444444444444, 5, 30, 15360, 16384, 100, 300",+ "1, GPU-bbbbbbbb-1111-2222-3333-444444444444, 7, 31, 2048, 98304, 120, 350",+ ]+ ),+ )++ monkeypatch.setattr(nvidia.subprocess, "run", _run)++ assert hw._context_free_cuda_memory_info(0, 96 * gib) == 94 * gib+++def test_parent_visible_spec_ignores_a_rocr_mask_on_windows(monkeypatch):+ # Windows HIP has no ROCr layer, so a stray ROCR var masks nothing there and+ # must not be read as the ordinal to physical mapping.+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 2)+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "1,0")++ monkeypatch.setattr(hw.sys, "platform", "win32")+ assert hw._get_parent_visible_gpu_spec()["numeric_ids"] == [0, 1]++ # Linux does honour it, so the reordering must survive there.+ monkeypatch.setattr(hw.sys, "platform", "linux")+ assert hw._get_parent_visible_gpu_spec()["numeric_ids"] == [1, 0]+++def test_context_free_rocm_windows_declines_gpu_device_ordinal(monkeypatch):+ # GPU_DEVICE_ORDINAL=1 makes physical GPU 1 torch ordinal 0, but it is a+ # ROCclr-layer variable that _get_parent_visible_gpu_spec never reads, so the+ # adapter list is still [0, 1] and ordinal 0 would publish GPU 0's VRAM.+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", "1")+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ hw,+ "_rocm_windows_per_device_vram",+ lambda ids, adapters = None: pytest.fail(+ "an external GPU ordinal filter must decline the adapter path"+ ),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) is None+++def test_context_free_nvidia_smi_declines_whole_gpu_metrics_for_mig(monkeypatch):+ gib = 1 << 30+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: {+ "available": True,+ "devices": [{"visible_ordinal": 0, "vram_used_gb": 70.0, "vram_total_gb": 80.0}],+ },+ )++ # torch reports the 10 GiB MIG allocation, while --query-gpu reports its+ # 80 GiB parent. Capping the parent's 10 GiB free would falsely report the+ # instance as completely empty even when its own allocation is full.+ assert hw._context_free_cuda_memory_info(0, 10 * gib) is None+++def test_context_free_never_spawns_amd_smi_on_windows_without_a_hip_sdk(monkeypatch):+ """The probe must stay behind amd.py's elevation guard.++ amd-smi elevates a child on Windows without a HIP runtime, and the resulting+ UAC/DiskPart prompt cannot be suppressed. This path reaches amd-smi through a+ helper, so a later refactor calling it directly would reintroduce the prompt+ with nothing failing. Assert on the spawn itself, not on the return value.+ """+ from utils.hardware import amd++ spawned = []++ def _spy(command, *args, **kwargs):+ spawned.append(command)+ raise FileNotFoundError("no amd-smi should be spawned here")++ monkeypatch.setattr(amd, "platform", types.SimpleNamespace(system = lambda: "Windows"))+ monkeypatch.setattr(amd, "_hip_sdk_present", lambda: False)+ monkeypatch.setattr(amd.shutil, "which", lambda _n: r"C:\rocm\bin\amd-smi.exe")+ monkeypatch.setattr(amd.subprocess, "run", _spy)+ monkeypatch.delenv("UNSLOTH_ENABLE_AMD_SMI", raising = False)+ monkeypatch.setattr(amd, "_amd_smi_disabled", False)+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ # Windows reads per-adapter counters, so declining amd-smi still answers.+ # One instance per visible device, so the identity check upstream holds.+ monkeypatch.setattr(+ hw,+ "_rocm_windows_perf_counter_vram_by_adapter",+ lambda counter = "Dedicated Usage": [("a", 8.0 * (1 << 30)), ("b", 0.0)],+ )+ monkeypatch.setattr(+ hw,+ "_rocm_windows_per_device_vram",+ lambda ids, adapters = None: (+ [{"index": 0, "visible_ordinal": 0, "name": "RX", "used_gb": 8.0, "total_gb": 24.0}],+ 8.0,+ ),+ )++ assert hw._context_free_cuda_memory_info(0, 24 << 30) == 16 << 30+ assert spawned == []++[email protected](sys.platform != "win32", reason = "the guard is Windows-only")+def test_amd_smi_is_refused_on_a_real_windows_host_without_a_hip_sdk():+ # The test above fakes the platform. This one runs the same predicate against+ # the real OS, PATH and environment, so the guard is pinned where it applies.+ from utils.hardware import amd+ if amd._hip_sdk_present() or os.environ.get("UNSLOTH_ENABLE_AMD_SMI"):+ pytest.skip("this host may legitimately run amd-smi un-elevated")+ assert amd._amd_smi_allowed() is False+++def test_context_free_rocm_smi_declines_whole_gpu_metrics_for_a_partition(monkeypatch):+ from utils.hardware import amd++ gib = 1 << 30+ monkeypatch.setattr(hw, "IS_ROCM", True)+ for name in (+ "GPU_DEVICE_ORDINAL",+ "ROCR_VISIBLE_DEVICES",+ "HIP_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ ):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": [0], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(amd, "get_hip_id_by_gpu_index", lambda: {0: 0})+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: 1)+ monkeypatch.setattr(+ hw,+ "_smi_query",+ lambda *a, **k: {+ "available": True,+ "devices": [{"visible_ordinal": 0, "vram_used_gb": 70.0, "vram_total_gb": 80.0}],+ },+ )+ # amd-smi is only the first probe. Leaving the Linux sysfs branch to the real+ # host made this vacuous exactly where it matters: where sysfs is unreachable+ # the branch never runs, and where it IS reachable the inventory was built+ # from the host's own card rather than the partition, so the totals matched+ # and a figure came back. Pin the whole path, sysfs included.+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")+ monkeypatch.setattr(+ hw,+ "_torch_get_device_module",+ lambda: (+ types.SimpleNamespace(+ get_device_properties = lambda _o: _FakeProps("MI300X partition", 10 * gib)+ ),+ "cuda",+ ),+ )+ monkeypatch.setattr(hw, "_rocm_kfd_gpu_pci_ids", lambda: {0: "0000:03:00.0"})+ monkeypatch.setattr(hw, "_rocm_visibility_mask_active", lambda: False)+ # sysfs speaks for the whole 80 GiB card, which is not this partition's pool.+ monkeypatch.setattr(+ hw, "_rocm_linux_sysfs_vram_by_pci_gb", lambda: {"0000:03:00.0": (70.0, 80.0)}+ )++ assert hw._context_free_cuda_memory_info(0, 10 * gib) is None++# ========== Inventory parity ==========@@ -246,12 +893,14 @@ def test_visibility_endpoint_uses_inventory_not_occupancy(monkeypatch):monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: pytest.fail("the visibility poll must not ask torch for occupancy"),+ lambda ids, adapters = None: pytest.fail(+ "the visibility poll must not ask torch for occupancy"+ ),)monkeypatch.setattr(hw,"_torch_get_device_inventory",- lambda ids: [+ lambda ids, adapters = None: [{"index": 0,"visible_ordinal": 0,@@ -530,7 +1179,7 @@ def _rocm_linux(monkeypatch, resolved):monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)monkeypatch.setattr(hw, "_smi_query", lambda *a, **k: None) # amd-smi unavailablemonkeypatch.setattr(hw.platform, "system", lambda: "Linux")- monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids: ([], None))+ monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids, adapters = None: ([], None))monkeypatch.setattr(hw,"_get_parent_visible_gpu_spec",@@ -540,7 +1189,7 @@ def _rocm_linux(monkeypatch, resolved):monkeypatch.setattr(hw,"_torch_get_device_inventory",- lambda ids: [+ lambda ids, adapters = None: [{"index": i, "visible_ordinal": i, "name": "MI210", "total_gb": 64.0, "used_gb": None}for i in ids],@@ -553,7 +1202,9 @@ def test_rocm_linux_reads_sysfs_without_asking_torch_for_occupancy(monkeypatch):monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: pytest.fail("sysfs answered in full; torch occupancy is dead weight"),+ lambda ids, adapters = None: pytest.fail(+ "sysfs answered in full; torch occupancy is dead weight"+ ),)result = hw.get_visible_gpu_utilization()assert result["available"] is True@@ -573,7 +1224,7 @@ def test_rocm_linux_sysfs_first_matches_the_old_torch_then_overlay_result(monkeymonkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: [+ lambda ids, adapters = None: [{"index": i, "visible_ordinal": i, "name": "MI210", "total_gb": 64.0, "used_gb": 0.02}for i in ids],@@ -609,11 +1260,19 @@ def test_rocm_linux_falls_back_to_torch_when_sysfs_covers_only_some(monkeypatch)monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: used.append(ids)- or [- {"index": i, "visible_ordinal": i, "name": "MI210", "total_gb": 64.0, "used_gb": 1.0}- for i in ids- ],+ lambda ids, adapters = None: (+ used.append(ids)+ or [+ {+ "index": i,+ "visible_ordinal": i,+ "name": "MI210",+ "total_gb": 64.0,+ "used_gb": 1.0,+ }+ for i in ids+ ]+ ),)result = hw.get_visible_gpu_utilization()assert used == [[0, 1]]@@ -628,11 +1287,19 @@ def test_rocm_linux_falls_back_when_sysfs_knows_nothing(monkeypatch):monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: used.append(ids)- or [- {"index": i, "visible_ordinal": i, "name": "MI210", "total_gb": 64.0, "used_gb": 1.0}- for i in ids- ],+ lambda ids, adapters = None: (+ used.append(ids)+ or [+ {+ "index": i,+ "visible_ordinal": i,+ "name": "MI210",+ "total_gb": 64.0,+ "used_gb": 1.0,+ }+ for i in ids+ ]+ ),)result = hw.get_visible_gpu_utilization()assert used == [[0, 1]]@@ -654,7 +1321,7 @@ def test_nvidia_torch_fallback_keeps_using_occupancy(monkeypatch):monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: [+ lambda ids, adapters = None: [{"index": 0, "visible_ordinal": 0, "name": "L40S", "total_gb": 44.0, "used_gb": 4.0}],)@@ -672,11 +1339,19 @@ def test_rocm_relative_index_skips_the_sysfs_shortcut(monkeypatch):monkeypatch.setattr(hw,"_torch_get_per_device_info",- lambda ids: seen.append(ids)- or [- {"index": i, "visible_ordinal": i, "name": "MI210", "total_gb": 64.0, "used_gb": 1.0}- for i in ids- ],+ lambda ids, adapters = None: (+ seen.append(ids)+ or [+ {+ "index": i,+ "visible_ordinal": i,+ "name": "MI210",+ "total_gb": 64.0,+ "used_gb": 1.0,+ }+ for i in ids+ ]+ ),)result = hw.get_visible_gpu_utilization()assert result["index_kind"] == "relative"@@ -689,7 +1364,7 @@ def test_rocm_windows_does_not_take_the_linux_sysfs_path(monkeypatch):monkeypatch.setattr(hw,"_rocm_windows_per_device_vram",- lambda ids: (+ lambda ids, adapters = None: ([{"index": i, "visible_ordinal": i, "name": "RX", "used_gb": 2.0, "total_gb": 24.0}for i in ids@@ -730,3 +1405,66 @@ def test_decision_helper_does_not_mutate(monkeypatch):snapshot = dict(devices[0])assert hw._rocm_system_wide_vram_by_index(devices) == {0: (32.0, 64.0)}assert devices[0] == snapshot+++def test_context_free_windows_rocm_declines_when_counters_outnumber_devices(monkeypatch):+ # A hidden adapter makes the counter set larger than the visible set. The+ # capacity ranking can then hand its reading to a visible card: over 89/89/8+ # GiB a card really holding 86 GiB reports 10, overstating free by 76 GiB.+ # The System tab tolerates that mapping; free_gb feeds training-method+ # selection, where overstating free is what OOMs. So decline instead.+ gib = 1 << 30+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "_rocm_device_ordinal_active", lambda: False)+ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": "0,1", "numeric_ids": [0, 1], "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(hw, "_smi_query", lambda *a, **k: {"available": False, "devices": []})+ monkeypatch.setattr(+ hw,+ "_rocm_windows_per_device_vram",+ lambda _ids: (_ for _ in ()).throw(+ AssertionError("must decline before consulting the capacity mapping")+ ),+ )+ # Three instances, two visible devices: not an identity mapping.+ monkeypatch.setattr(+ hw,+ "_rocm_windows_perf_counter_vram_by_adapter",+ lambda counter = "Dedicated Usage": [("a", 0.0), ("b", 1.0 * gib), ("hidden", 20.0 * gib)],+ )++ assert hw._context_free_cuda_memory_info(0, 48 * gib) is None+++def test_gpu_summary_apu_counters_need_positively_identified_uma(monkeypatch):+ # _rocm_props_total_is_carve_out answers True for an UNCERTAIN device too (old+ # HIP, unreadable integrated flag), because a too-small total hides models.+ # That justifies the driver total, not adding Shared Usage: shared bytes are+ # not part of a discrete card's props.total_memory, so a discrete GPU misread+ # as uncertain would have its free understated.+ gib = 1 << 30+ torch_stub, _props = _summary_torch(+ properties_total = 8 * gib,+ driver_free = 98 * gib,+ driver_total = 100 * gib,+ )+ monkeypatch.setitem(sys.modules, "torch", torch_stub)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda _props: True)+ monkeypatch.setattr(hw, "_rocm_props_are_positively_unified", lambda _props: False)+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setattr(+ hw,+ "_rocm_windows_unified_used_bytes",+ lambda: (_ for _ in ()).throw(AssertionError("uncertain is not positively unified")),+ )++ summary = hw.get_gpu_summary()++ # Driver total kept, free still hipMemGetInfo's.+ assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 100.0, "vram_free_gb": 98.0}diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.pyindex 632c8011f42..8551a458668 100644--- a/studio/backend/tests/test_utils.py+++ b/studio/backend/tests/test_utils.py@@ -8,6 +8,8 @@ is imported at top level; tests needing torch/mlx internals skip when unavailabl"""import platform+import sys+import typesfrom unittest.mock import patch, MagicMockimport pytest@@ -247,6 +249,16 @@ class TestGetGpuMemoryInfo:patch("torch.cuda.get_device_properties", return_value = mock_props),patch("torch.cuda.memory_allocated", return_value = 4 * (1024**3)),patch("torch.cuda.memory_reserved", return_value = 6 * (1024**3)),+ # Driver truth from a context-free SMI/sysfs probe: another process+ # and torch's cache leave only 9 of 16 GiB free.+ patch(+ "utils.hardware.hardware._context_free_cuda_memory_info",+ return_value = 9 * (1024**3),+ ),+ patch(+ "utils.hardware.hardware.trusted_mem_get_info",+ side_effect = AssertionError("native telemetry must avoid mem_get_info"),+ ),):result = get_gpu_memory_info()@@ -255,9 +267,102 @@ class TestGetGpuMemoryInfo:assert result["device_name"] == "NVIDIA Test GPU"assert abs(result["total_gb"] - 16.0) < 0.01assert abs(result["allocated_gb"] - 4.0) < 0.01- assert abs(result["free_gb"] - 12.0) < 0.01+ assert abs(result["free_gb"] - 9.0) < 0.01assert abs(result["utilization_pct"] - 25.0) < 0.1+ @needs_torch+ def test_cuda_free_falls_back_to_reserved_when_probe_fails(self):+ mock_props = MagicMock()+ mock_props.total_memory = 16 * (1024**3)+ mock_props.name = "NVIDIA Test GPU"++ def _boom():+ raise RuntimeError("driver unavailable")++ with (+ patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA),+ patch("torch.cuda.current_device", return_value = 0),+ patch("torch.cuda.get_device_properties", return_value = mock_props),+ patch("torch.cuda.memory_allocated", return_value = 4 * (1024**3)),+ patch("torch.cuda.memory_reserved", return_value = 6 * (1024**3)),+ patch("utils.hardware.hardware._context_free_cuda_memory_info", return_value = None),+ patch("utils.hardware.hardware.trusted_mem_get_info", side_effect = _boom),+ ):+ result = get_gpu_memory_info()++ # Reserved includes allocated, so the fallback bound is 16 - 6, not+ # the old allocated-only 12.+ assert abs(result["free_gb"] - 10.0) < 0.01++ @needs_torch+ def test_rocm_apu_free_uses_the_matching_driver_total(self):+ mock_props = MagicMock()+ mock_props.total_memory = 8 * (1024**3)+ mock_props.name = "AMD Radeon 8060S Graphics"++ with (+ patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA),+ patch("utils.hardware.hardware.IS_ROCM", True),+ patch("torch.cuda.current_device", return_value = 0),+ patch("torch.cuda.get_device_properties", return_value = mock_props),+ patch("torch.cuda.memory_allocated", return_value = 1 * (1024**3)),+ patch("torch.cuda.memory_reserved", return_value = 2 * (1024**3)),+ patch("utils.hardware.hardware._rocm_props_total_is_carve_out", return_value = True),+ patch(+ "utils.hardware.hardware._context_free_cuda_memory_info",+ side_effect = AssertionError("an APU needs hipMemGetInfo's GTT total"),+ ),+ patch(+ "utils.hardware.hardware.trusted_mem_get_info",+ return_value = (98 * (1024**3), 100 * (1024**3)),+ ),+ ):+ result = get_gpu_memory_info()++ assert abs(result["total_gb"] - 100.0) < 0.01+ assert abs(result["free_gb"] - 98.0) < 0.01++ # --- XPU (Intel GPU) ---++ def _xpu_torch(self, mem_get_info):+ """A torch stub exposing only what the XPU branch touches."""+ props = types.SimpleNamespace(total_memory = 16 * (1024**3), name = "Intel Arc A770")+ xpu = types.SimpleNamespace(+ current_device = lambda: 0,+ get_device_properties = lambda _o: props,+ memory_allocated = lambda _o: 2 * (1024**3),+ memory_reserved = lambda _o: 3 * (1024**3),+ )+ if mem_get_info is not None:+ xpu.mem_get_info = mem_get_info+ return types.SimpleNamespace(xpu = xpu)++ def _xpu_result(self, monkeypatch, mem_get_info):+ monkeypatch.setitem(sys.modules, "torch", self._xpu_torch(mem_get_info))+ monkeypatch.setattr(_hw_module, "get_device", lambda: DeviceType.XPU)+ monkeypatch.setattr(_hw_module, "rocm_windows_free_is_untrusted", lambda: False)+ return get_gpu_memory_info()++ def test_xpu_free_comes_from_the_driver(self, monkeypatch):+ # 12 of 16 GiB free system-wide, against 2 GiB allocated by this process:+ # the old total - allocated would have claimed 14.+ result = self._xpu_result(monkeypatch, lambda _o: (12 * (1024**3), 16 * (1024**3)))+ assert abs(result["free_gb"] - 12.0) < 0.01+ assert abs(result["total_gb"] - 16.0) < 0.01++ def test_xpu_falls_back_to_reserved_when_the_probe_fails(self, monkeypatch):+ def _boom(_o):+ raise RuntimeError("level zero unavailable")++ result = self._xpu_result(monkeypatch, _boom)+ assert abs(result["free_gb"] - 13.0) < 0.01++ def test_xpu_falls_back_on_a_torch_without_mem_get_info(self, monkeypatch):+ # torch.xpu.mem_get_info is newer than the floor this backend supports,+ # so its absence must degrade, not raise.+ result = self._xpu_result(monkeypatch, None)+ assert abs(result["free_gb"] - 13.0) < 0.01+# --- MLX-specific mocked test ---@needs_mlxdiff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 3e95eae8793..619efbc927c 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -876,6 +876,222 @@ def _clear_mps_cache() -> None:logger.debug("Failed to clear MPS cache: %s", e)+def _rocm_visibility_masks_are_stacked() -> bool:+ """Whether a ROCr mask is composed with a higher HIP-layer mask."""+ if sys.platform == "win32" or 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+ )+++def _rocm_device_ordinal_active() -> bool:+ """Whether GPU_DEVICE_ORDINAL renumbers HIP devices.++ ROCclr-layer, so it applies on Windows too, and no visibility spec here reads+ it: a torch ordinal cannot be paired with a physical id while it is set.+ """+ return bool(os.environ.get("GPU_DEVICE_ORDINAL", "").strip())+++def _cuda_order_matches_smi() -> bool:+ """Whether torch ordinals and nvidia-smi rows share one index space.++ CUDA enumerates FASTEST_FIRST by default and nvidia-smi reports PCI order;+ PCI_BUS_ID is only a setdefault here, so an explicit override survives and+ the two disagree. Equal-sized cards defeat the total-scope check, so nothing+ else catches it. Same gate the llama.cpp SM probe applies. One GPU is exempt:+ every ordering is the identity there.+ """+ if IS_ROCM or os.environ.get("CUDA_DEVICE_ORDER") == "PCI_BUS_ID":+ return True+ # The count must be the SMI's. The torch fallback counts VISIBLE devices, so+ # a mask of one on a multi-GPU host reads as single-GPU and would grant the+ # exemption the mask is exactly the reason to withhold. It is cached, so one+ # transient `nvidia-smi -L` timeout would otherwise disable this for the+ # life of the process.+ count = get_physical_gpu_count()+ if _physical_gpu_count_from_smi and count <= 1:+ return True+ if not _physical_gpu_count_from_smi:+ logger.debug("Skipping SMI VRAM query: physical GPU count is not SMI-confirmed")+ return False+ logger.debug("Skipping SMI VRAM query: CUDA_DEVICE_ORDER is not PCI_BUS_ID")+ return False+++def _amd_smi_ids_for_hip_ids(hip_ids: Optional[list[int]]) -> Optional[list[int]]:+ """Translate visible HIP ordinals to amd-smi physical GPU IDs."""+ if hip_ids is None or not hip_ids:+ return hip_ids+ if _rocm_device_ordinal_active():+ logger.debug("Skipping amd-smi VRAM query: GPU_DEVICE_ORDINAL filters HIP devices")+ return None+ if _rocm_visibility_masks_are_stacked():+ logger.debug("Skipping amd-smi VRAM query: ROCr and HIP visibility masks are stacked")+ return None++ from . import amd++ smi_to_hip = amd.get_hip_id_by_gpu_index()+ if smi_to_hip is None:+ # Identity is still provable on a host with exactly one physical GPU.+ if hip_ids == [0] and amd.get_physical_gpu_count() == 1:+ return [0]+ logger.debug("Skipping amd-smi VRAM query: HIP GPU mapping is unavailable")+ return None++ torch_visible_count = _torch_get_physical_gpu_count()+ if torch_visible_count is None or torch_visible_count != len(hip_ids):+ logger.debug("Skipping amd-smi VRAM query: amd-smi and HIP visible counts differ")+ return None+ has_standard_mask = any(+ os.environ.get(name) is not None+ for name in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")+ )+ if not has_standard_mask and len(smi_to_hip) != torch_visible_count:+ logger.debug("Skipping amd-smi VRAM query: amd-smi and HIP inventories differ")+ return None++ hip_to_smi = {hip_id: smi_id for smi_id, hip_id in smi_to_hip.items()}+ if any(hip_id not in hip_to_smi for hip_id in hip_ids):+ logger.debug("Skipping amd-smi VRAM query: HIP GPU mapping is incomplete")+ return None+ return [hip_to_smi[hip_id] for hip_id in hip_ids]+++def _free_in_torch_scope(total_bytes: int, used_gb: float) -> int:+ """Driver used-memory turned into free bytes, in torch's allocatable scope.++ Subtract from torch's total, never the driver's: NVIDIA's total also spans a+ reserved framebuffer that ``used`` excludes and torch can never hand out+ (726 MiB on a B200), so ``driver_total - used`` reports a full card as free.++ Clamped both ends: the parsers accept signed values, and a negative used+ would otherwise advertise more free than the card has, which utilization_pct+ and the training-method policy both read.+ """+ return min(total_bytes, max(0, total_bytes - round(used_gb * (1024**3))))+++def _context_free_cuda_memory_info(+ idx: int,+ total_bytes: int,+ unified: bool = False,+) -> Optional[int]:+ """System-wide free bytes without attaching a CUDA/HIP primary context.++ ``unified`` marks a ROCm APU, whose *total* must still come from HIP but whose+ *used* is available here; see ``_rocm_windows_unified_used_bytes``.+ """+ parent_visible_spec = _get_parent_visible_gpu_spec()++ # A unified part goes straight to the WDDM counters. The vendor CLI and DRM+ # sysfs both report the dedicated carve-out for it, which the total-tolerance+ # check below would reject anyway, and Linux hipMemGetInfo is already+ # system-wide there -- so this exists for Windows, where it is not.+ if unified:+ if platform.system() != "Windows" or _rocm_device_ordinal_active():+ return None+ used_bytes = _rocm_windows_unified_used_bytes()+ if used_bytes is None:+ return None+ return _free_in_torch_scope(total_bytes, used_bytes / (1024**3))++ # Prefer the vendor CLI. Both nvidia-smi and amd-smi run out of process, so+ # querying an idle backend does not leave a context resident in this process.+ visible_ids = parent_visible_spec["numeric_ids"]+ if IS_ROCM:+ visible_ids = _amd_smi_ids_for_hip_ids(visible_ids)+ # Without numeric ids ROCm cannot map at all, while an NVIDIA UUID mask names+ # its devices absolutely: CUDA enumerates them in the order listed, so there+ # is no ordinal space to share and the order gate does not apply.+ may_query = not IS_ROCM if visible_ids is None else _cuda_order_matches_smi()+ result = None+ if may_query:+ result = _smi_query(+ "get_visible_gpu_utilization",+ visible_ids,+ parent_cuda_visible_devices = parent_visible_spec["raw"],+ )+ if result is not None:+ for device in result.get("devices", []):+ if device.get("visible_ordinal") != idx:+ continue+ used_gb = device.get("vram_used_gb")+ driver_total_gb = device.get("vram_total_gb")+ if used_gb is None or driver_total_gb is None:+ break+ driver_total_bytes = round(driver_total_gb * (1024**3))+ total_tolerance = max(total_bytes // 100, 16 * 1024**2)+ if abs(driver_total_bytes - total_bytes) > total_tolerance:+ logger.debug("Skipping whole-GPU VRAM telemetry for a partitioned GPU device")+ break+ return _free_in_torch_scope(total_bytes, used_gb)++ if not IS_ROCM:+ return None++ # Linux DRM sysfs is system-wide and context-free. Build the complete+ # physical inventory because the resolver intentionally rejects partial or+ # visibility-masked sets whose ordinals cannot be matched safely.+ if platform.system() == "Linux":+ numeric_ids = parent_visible_spec.get("numeric_ids")+ if numeric_ids is not None and 0 <= idx < len(numeric_ids):+ mod, _ = _torch_get_device_module()+ probe = []+ if mod is not None:+ try:+ for ordinal, physical_idx in enumerate(numeric_ids):+ props = mod.get_device_properties(ordinal)+ probe.append(+ {+ "index": physical_idx,+ "vram_total_gb": props.total_memory / (1024**3),+ }+ )+ except Exception as e:+ logger.debug("ROCm context-free inventory failed: %s", e)+ probe = []+ resolved = _rocm_system_wide_vram_by_index(probe)+ entry = resolved.get(numeric_ids[idx])+ if entry is not None:+ used_gb, _sysfs_total_gb = entry+ return _free_in_torch_scope(total_bytes, used_gb)++ # Native Windows ROCm exposes per-adapter dedicated usage without entering+ # HIP. Reuse the same conservative mapping as the System telemetry route.+ # GPU_DEVICE_ORDINAL renumbers torch ordinals but not the visible spec, so+ # device_ids[idx] would be a different card; the Linux path declines already.+ if platform.system() == "Windows" and not _rocm_device_ordinal_active():+ numeric_ids = parent_visible_spec.get("numeric_ids")+ device_ids = (+ numeric_ids if numeric_ids else list(range(_torch_get_physical_gpu_count() or 0))+ )+ # Only when the counter instances ARE the visible set. With extras present+ # the capacity ranking may hand a hidden adapter's smaller reading to a+ # busier visible card: simulated over 89/89/8 GiB, a card really holding+ # 86 GiB reports 10, overstating free by 76 GiB. The System tab can carry+ # that best-effort mapping, but free_gb feeds training-method selection,+ # where overstating free is what OOMs. Same cardinality assumption+ # _rocm_windows_aggregate_used_bytes already rests on.+ adapters = _rocm_windows_perf_counter_vram_by_adapter()+ if adapters is None or len(adapters) != len(device_ids):+ return None+ devices, _aggregate = _rocm_windows_per_device_vram(device_ids, adapters)+ for device in devices:+ if device.get("visible_ordinal") != idx:+ continue+ used_gb = device.get("used_gb")+ driver_total_gb = device.get("total_gb")+ if used_gb is None or driver_total_gb is None:+ break+ return _free_in_torch_scope(total_bytes, used_gb)++ return None++def get_gpu_memory_info() -> Dict[str, Any]:"""Get GPU memory info.@@ -895,6 +1111,55 @@ def get_gpu_memory_info() -> Dict[str, Any]:allocated = torch.cuda.memory_allocated(idx)reserved = torch.cuda.memory_reserved(idx)+ # Driver-level free includes torch's cache and other processes. Try+ # context-free telemetry first: mem_get_info pins a primary context+ # for the life of this backend.+ #+ # A ROCm APU needs its GTT *total* from HIP, which the context-free+ # probes cannot supply, so it pays for the context regardless. That is+ # a reason to take the total from HIP, not a reason to take the free+ # figure from it too: hipMemGetInfo is process-local on Windows WDDM+ # and blind to other processes there. So resolve the total first, then+ # still prefer telemetry for used.+ driver_total_needed = _rocm_props_total_is_carve_out(props)+ free = None+ if driver_total_needed:+ try:+ free, driver_total = trusted_mem_get_info(idx)+ # Only adopt a driver total that is usable: utilization_pct+ # divides by it, so a zero would lose the whole report.+ if driver_total:+ total = driver_total+ except Exception as e:+ logger.debug("mem_get_info probe failed; free VRAM from reserved: %s", e)+ free = max(0, total - reserved)+ # The counters only apply where UMA is POSITIVELY identified.+ # _rocm_props_total_is_carve_out also answers True for an+ # uncertain device (old HIP, unreadable flag), on the principle+ # that a too-small total hides models. That justifies the driver+ # total, not summing Shared Usage: shared system memory is not+ # part of a discrete card's props.total_memory, so on a discrete+ # GPU misread as uncertain it would understate free.+ telemetry_free = None+ if _rocm_props_are_positively_unified(props):+ try:+ telemetry_free = _context_free_cuda_memory_info(idx, total, unified = True)+ except Exception as e:+ logger.debug("context-free free-VRAM probe failed: %s", e)+ if telemetry_free is not None:+ free = telemetry_free+ else:+ try:+ free = _context_free_cuda_memory_info(idx, total)+ except Exception as e:+ logger.debug("context-free free-VRAM probe failed: %s", e)+ try:+ if free is None:+ free, _driver_total = trusted_mem_get_info(idx)+ except Exception as e:+ logger.debug("mem_get_info probe failed; free VRAM from reserved: %s", e)+ free = max(0, total - reserved)+return {"available": True,"backend": _backend_label(device),@@ -903,7 +1168,7 @@ def get_gpu_memory_info() -> Dict[str, Any]:"total_gb": total / (1024**3),"allocated_gb": allocated / (1024**3),"reserved_gb": reserved / (1024**3),- "free_gb": (total - allocated) / (1024**3),+ "free_gb": free / (1024**3),"utilization_pct": (allocated / total) * 100,}except Exception as e:@@ -926,6 +1191,14 @@ def get_gpu_memory_info() -> Dict[str, Any]:allocated = torch.xpu.memory_allocated(idx)reserved = torch.xpu.memory_reserved(idx)+ # Same rationale as the CUDA path: driver free, reserved as the+ # fallback bound (see above).+ try:+ free, _driver_total = trusted_mem_get_info(idx, module = torch.xpu)+ except Exception as e:+ logger.debug("xpu mem_get_info probe failed; free VRAM from reserved: %s", e)+ free = max(0, total - reserved)+return {"available": True,"backend": _backend_label(device),@@ -934,7 +1207,7 @@ def get_gpu_memory_info() -> Dict[str, Any]:"total_gb": total / (1024**3),"allocated_gb": allocated / (1024**3),"reserved_gb": reserved / (1024**3),- "free_gb": (total - allocated) / (1024**3),+ "free_gb": free / (1024**3),"utilization_pct": (allocated / total) * 100,}except Exception as e:@@ -1174,6 +1447,24 @@ def _hip_runtime_version() -> Optional[tuple[int, int]]:return None+def _rocm_props_are_positively_unified(props: Any) -> bool:+ """Whether this part is KNOWN to be unified memory, not merely unclassified.++ ``_rocm_props_total_is_carve_out`` folds "uncertain" in with "unified" on+ purpose, because a total that is too small hides models. Anything that adds+ host-shared memory to a used figure needs the stricter question: on a+ discrete card, shared bytes are not part of ``props.total_memory``.+ """+ if not IS_ROCM:+ return False+ try:+ from core.training.worker import _rocm_classify_unified_memory+ return bool(_rocm_classify_unified_memory(props)[1])+ except Exception as e:+ logger.debug("ROCm unified-memory classification failed: %s", e)+ return False++def _rocm_props_total_is_carve_out(props: Any) -> bool:"""True when ``props.total_memory`` may understate what torch can actually use.@@ -1790,8 +2081,15 @@ def _rocm_linux_sysfs_vram_by_pci_gb() -> dict[str, tuple[float, float]]:_ROCM_WIN_ADAPTER_MIN_BYTES = 64 * 1024 * 1024 # 64 MiB-def _rocm_windows_perf_counter_vram_by_adapter() -> Optional[list[tuple[str, float]]]:- """Per-adapter dedicated VRAM usage on Windows via Performance Counters.+def _rocm_windows_perf_counter_vram_by_adapter(+ counter: str = "Dedicated Usage",+) -> Optional[list[tuple[str, float]]]:+ """Per-adapter VRAM usage on Windows via Performance Counters.++ ``counter`` selects the ``GPU Adapter Memory`` field. Dedicated Usage is the+ default and the only one safe to select adapters on; see+ ``_rocm_windows_unified_used_bytes`` for why Shared Usage is read separately+ rather than folded in here.Returns ``[(instance_name, used_bytes)]`` (one per LUID-named adapter), or``None`` when the counter is unavailable/localized/empty so callers fall back.@@ -1801,7 +2099,7 @@ def _rocm_windows_perf_counter_vram_by_adapter() -> Optional[list[tuple[str, flotry:# Emit "<InstanceName>|<CookedValue>" per sample, or a __NONE__ sentinel.ps = (- "$s=(Get-Counter '\\GPU Adapter Memory(*)\\Dedicated Usage'"+ f"$s=(Get-Counter '\\GPU Adapter Memory(*)\\{counter}'"" -ErrorAction SilentlyContinue).CounterSamples;""if($s){$s|ForEach-Object{'{0}|{1}' -f $_.InstanceName,[int64]$_.CookedValue}}""else{'__NONE__'}"@@ -1866,6 +2164,7 @@ def _match_adapter_used_to_devices(return [None] * n# Exactly n supra-threshold counters: extras were placeholders, so a# capacity-ranked bijection is plausible.+ dropped = [u for u in useds if u < _ROCM_WIN_ADAPTER_MIN_BYTES]useds = non_trivialranked_useds = [useds[rank] for rank in range(n)]# A usage above its ranked capacity is a hidden larger GPU; clamping onto the@@ -1873,6 +2172,25 @@ def _match_adapter_used_to_devices(for rank in range(n):if ranked_useds[rank] > ranked_totals[rank]:return [None] * n+ # One visible device, one supra-threshold counter, and every other counter+ # at EXACTLY zero: attribute it. A Strix Halo host emits three instances,+ # two of them at 0 dedicated, and the capacity test below cannot decide+ # this shape because it needs a next-smaller device to compare against.+ #+ # Zero is the load-bearing part, not the cardinality. A merely sub-floor+ # counter (10 MiB) can be the visible card sitting idle, which would make+ # the survivor a hidden GPU's -- see the [6 GiB, 10 MiB] / [8 GiB] case,+ # which must stay unknown. An adapter at exactly zero has nothing+ # committed and cannot be the holder of the survivor's bytes.+ #+ # Residual risk, stated rather than hidden: the visible card could itself+ # be the zero while a hidden adapter holds the survivor, and then this+ # over-reports used. That errs toward understating free, which is the safe+ # direction here -- the consumer is training-method selection, where an+ # overstated free picks a method that OOMs. Clamped like every other+ # branch, so a hidden larger adapter cannot report a fully-used card.+ if n == 1 and all(u == 0 for u in dropped):+ return [min(ranked_useds[0], device_totals[0])]# Capacity forces the mapping only when the usage exceeds the next-smaller# capacity; the smallest card and merely-fitting usages stay unknown.# Keeps 40 GiB over 48/8 GiB -> [40, None].@@ -1947,8 +2265,58 @@ def _rocm_windows_aggregate_used_bytes(return float(sum(useds))+def _rocm_windows_unified_used_bytes() -> Optional[float]:+ """Used VRAM for a unified-memory ROCm APU on Windows, from the WDDM counters.++ Dedicated Usage alone saturates at the carve-out on an APU and is wrong past+ it. Measured on a gfx1151 Strix Halo host (89.47 GiB torch total), holding N+ GiB in another process, deltas over baseline:++ held dedicated shared sum+ 4 + 4.14 + 0.04 + 4.18+ 16 +16.60 + 0.08 +16.68+ 24 +24.58 + 0.04 +24.62+ 40 +29.07 +11.29 +40.36+ 48 +29.19 +19.02 +48.21++ Dedicated plateaus around 30.5 GiB and the overflow lands in Shared, so only+ the sum tracks the allocation. Discrete cards are unaffected: this is reached+ only when ``_rocm_props_total_is_carve_out`` says the part is unified.++ Adapter SELECTION still keys off Dedicated Usage alone, deliberately. Display+ and placeholder adapters report 0 dedicated while carrying gigabytes of shared+ (a Basic Render Driver instance on the same host holds 1.30 GiB shared), so+ filtering on the sum would stop telling them apart from the compute device and+ would silently add a foreign adapter's bytes. Returns ``None`` unless exactly+ one adapter clears the noise floor, matching the caution in+ ``_rocm_windows_aggregate_used_bytes``.+ """+ dedicated = _rocm_windows_perf_counter_vram_by_adapter()+ if not dedicated:+ return None+ candidates = [+ (instance, used) for instance, used in dedicated if used >= _ROCM_WIN_ADAPTER_MIN_BYTES+ ]+ # Two compute adapters means no key says which is the visible one, and zero+ # means the card is idle below the floor: neither is a figure we can stand on.+ if len(candidates) != 1:+ return None+ instance, dedicated_used = candidates[0]+ shared = _rocm_windows_perf_counter_vram_by_adapter("Shared Usage")+ # A failed Shared query is not zero shared usage. Past the carve-out the+ # overflow lives entirely in Shared, so defaulting to zero there reports the+ # measured 48 GiB case as 30.5 and overstates free by 19 GiB, which is the+ # direction that OOMs. Nothing here knows where the carve-out sits, so decline+ # rather than guess whether this reading was saturated. A query that SUCCEEDS+ # but omits the LUID is a real zero, and is kept.+ if shared is None:+ return None+ shared_used = next((used for name, used in shared if name == instance), 0.0)+ return dedicated_used + shared_used++def _rocm_windows_per_device_vram(- device_indices: list[int],+ device_indices: list[int], adapters: Optional[list[tuple[str, float]]] = None) -> tuple[list[Dict[str, Any]], Optional[float]]:"""Per-GPU VRAM on Windows AMD/ROCm: total from torch properties (reliable),used from the per-adapter Dedicated Usage counter.@@ -1983,7 +2351,11 @@ def _rocm_windows_per_device_vram(if not dev_meta:return [], None- adapters = _rocm_windows_perf_counter_vram_by_adapter()+ # Re-sampling here would leave a caller's cardinality check applied to a+ # DIFFERENT sample than the one attribution runs on, and costs a second+ # ~1.3 s PowerShell call. A validated snapshot is passed in instead.+ if adapters is None:+ adapters = _rocm_windows_perf_counter_vram_by_adapter()aggregate_gb: Optional[float] = Noneif adapters:adapter_useds = [used for _, used in adapters]@@ -2626,6 +2998,9 @@ def get_visible_gpu_utilization() -> Dict[str, Any]:# ========== Multi-GPU Detection & Safe num_proc ==========_physical_gpu_count: Optional[int] = None+# Whether the cached count came from the SMI (physical) or the torch fallback+# (visibility-filtered). Only the former can answer "is this host single-GPU".+_physical_gpu_count_from_smi: bool = False_visible_gpu_count: Optional[int] = None@@ -2717,7 +3092,10 @@ def _get_parent_visible_gpu_spec() -> Dict[str, Any]:)if _is_rocm_spec:hip_vis = os.environ.get("HIP_VISIBLE_DEVICES")- rocr_vis = os.environ.get("ROCR_VISIBLE_DEVICES")+ # ROCR_VISIBLE_DEVICES is Linux-only: Windows HIP has no ROCr layer, so a+ # stray ROCR var there masks nothing and must not be read as the+ # ordinal->physical mapping (mirrors the llama.cpp backend).+ rocr_vis = None if sys.platform == "win32" else os.environ.get("ROCR_VISIBLE_DEVICES")if hip_vis is not None:cuda_visible = hip_viselif rocr_vis is not None:@@ -3442,7 +3820,7 @@ def get_physical_gpu_count() -> int:Uses ``nvidia-smi -L`` on NVIDIA (unaffected by CUDA_VISIBLE_DEVICES),with a torch fallback for AMD ROCm and Intel XPU. Cached after first call."""- global _physical_gpu_count+ global _physical_gpu_count, _physical_gpu_count_from_smiif _physical_gpu_count is not None:return _physical_gpu_count@@ -3457,6 +3835,7 @@ def get_physical_gpu_count() -> int:count = _smi_mod.get_physical_gpu_count()if count is not None:_physical_gpu_count = count+ _physical_gpu_count_from_smi = Truereturn _physical_gpu_countexcept Exception:passdiff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.pyindex 39e36529211..adefc121e37 100644--- a/studio/backend/utils/hardware/nvidia.py+++ b/studio/backend/utils/hardware/nvidia.py@@ -48,6 +48,27 @@ def _visible_ordinal_map(parent_visible_ids: Optional[list[int]]) -> Optional[direturn {gpu_id: ordinal for ordinal, gpu_id in enumerate(parent_visible_ids)}+def _uuid_visible_ordinal_map(+ parent_cuda_visible_devices: Optional[str], gpu_rows: list[tuple[int, str]]+) -> Optional[dict[int, int]]:+ """Resolve an ordered full-GPU UUID mask against nvidia-smi rows."""+ tokens = [+ token.strip().lower()+ for token in (parent_cuda_visible_devices or "").split(",")+ if token.strip()+ ]+ if not tokens or any(not token.startswith("gpu-") for token in tokens):+ return None++ visible_ordinals: dict[int, int] = {}+ for ordinal, token in enumerate(tokens):+ matches = [idx for idx, gpu_uuid in gpu_rows if gpu_uuid.lower().startswith(token)]+ if len(matches) != 1 or matches[0] in visible_ordinals:+ return None+ visible_ordinals[matches[0]] = ordinal+ return visible_ordinals++def get_physical_gpu_count() -> Optional[int]:"""Return physical GPU count via nvidia-smi, or None on failure."""try:@@ -114,23 +135,19 @@ def get_primary_gpu_utilization() -> dict[str, Any]:def get_visible_gpu_utilization(parent_visible_ids: Optional[list[int]], parent_cuda_visible_devices: Optional[str] = None) -> dict[str, Any]:- # parent_visible_ids None (UUID/MIG mask): can't map nvidia-smi rows to- # visible devices, so return empty rather than exposing all physical GPUs.- if parent_visible_ids is None:- return {- "available": False,- "backend_cuda_visible_devices": parent_cuda_visible_devices,- "parent_visible_gpu_ids": [],- "devices": [],- "index_kind": "unresolved",- }visible_ordinals = _visible_ordinal_map(parent_visible_ids)+ includes_uuid = parent_visible_ids is None+ query_fields = "index,"+ if includes_uuid:+ query_fields += "uuid,"+ query_fields += (+ "utilization.gpu,temperature.gpu,memory.used,memory.total,power.draw,power.limit"+ )try:result = subprocess.run(["nvidia-smi",- "--query-gpu=index,utilization.gpu,temperature.gpu,"- "memory.used,memory.total,power.draw,power.limit",+ f"--query-gpu={query_fields}","--format=csv,noheader,nounits",],capture_output = True,@@ -148,7 +165,7 @@ def get_visible_gpu_utilization("backend_cuda_visible_devices": parent_cuda_visible_devices,"parent_visible_gpu_ids": parent_visible_ids or [],"devices": [],- "index_kind": "physical",+ "index_kind": "physical" if parent_visible_ids is not None else "unresolved",}if result.returncode != 0 or not result.stdout.strip():return {@@ -156,45 +173,66 @@ def get_visible_gpu_utilization("backend_cuda_visible_devices": parent_cuda_visible_devices,"parent_visible_gpu_ids": parent_visible_ids or [],"devices": [],- "index_kind": "physical",+ "index_kind": "physical" if parent_visible_ids is not None else "unresolved",}- devices = []+ gpu_rows: list[tuple[int, list[str]]] = []for line in result.stdout.strip().splitlines():parts = [p.strip() for p in line.split(",")]- if len(parts) < 7:+ if len(parts) < (8 if includes_uuid else 7):continuetry:idx = int(parts[0])except (ValueError, TypeError):continue+ gpu_rows.append((idx, parts))+ if parent_visible_ids is None:+ visible_ordinals = _uuid_visible_ordinal_map(+ parent_cuda_visible_devices,+ [(idx, parts[1]) for idx, parts in gpu_rows],+ )+ if visible_ordinals is None:+ return {+ "available": False,+ "backend_cuda_visible_devices": parent_cuda_visible_devices,+ "parent_visible_gpu_ids": [],+ "devices": [],+ "index_kind": "unresolved",+ }++ devices = []+ field_offset = 1 if includes_uuid else 0+ for idx, parts in gpu_rows:if visible_ordinals is not None and idx not in visible_ordinals:continue+ visible_ordinal = visible_ordinals[idx] if visible_ordinals is not None else len(devices)devices.append(_build_gpu_metrics(- vram_used_mb = _parse_smi_value(parts[3]),- vram_total_mb = _parse_smi_value(parts[4]),- power_draw = _parse_smi_value(parts[5]),- power_limit = _parse_smi_value(parts[6]),- index = idx,- index_kind = "physical",- visible_ordinal = (- visible_ordinals[idx] if visible_ordinals is not None else len(devices)- ),- gpu_utilization_pct = _parse_smi_value(parts[1]),- temperature_c = _parse_smi_value(parts[2]),+ vram_used_mb = _parse_smi_value(parts[3 + field_offset]),+ vram_total_mb = _parse_smi_value(parts[4 + field_offset]),+ power_draw = _parse_smi_value(parts[5 + field_offset]),+ power_limit = _parse_smi_value(parts[6 + field_offset]),+ index = visible_ordinal if includes_uuid else idx,+ index_kind = "relative" if includes_uuid else "physical",+ visible_ordinal = visible_ordinal,+ gpu_utilization_pct = _parse_smi_value(parts[1 + field_offset]),+ temperature_c = _parse_smi_value(parts[2 + field_offset]),))+ # nvidia-smi emits physical row order, so a reordering mask would hand back+ # devices whose position contradicts their own visible_ordinal.+ devices.sort(key = lambda d: d["visible_ordinal"])+return {"available": len(devices) > 0,"backend_cuda_visible_devices": parent_cuda_visible_devices,"parent_visible_gpu_ids": parent_visible_ids or [],"devices": devices,- "index_kind": "physical",+ "index_kind": "relative" if includes_uuid else "physical",}