Skip to content

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

Studio: take the AMD APU total on Windows from the driver, not the carve-out (#9314)

Leo Borcherdingc82f112ee035
diff --git a/scripts/rocm_windows_apu_probe.py b/scripts/rocm_windows_apu_probe.py
new file mode 100644
index 00000000000..5259d5ebffa
--- /dev/null
+++ b/scripts/rocm_windows_apu_probe.py
@@ -0,0 +1,652 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Diagnostic for Windows ROCm VRAM reporting on a unified-memory APU (#9314).
+
+TEMPORARY. This exists because the change in #9314 rests on one premise that no
+machine in CI can check: that on Windows, `props.total_memory` reports the BIOS
+carve-out while `hipMemGetInfo`'s total spans the whole pool. On Linux the two
+agree exactly, so a Linux APU cannot settle it. Delete this once a Windows APU
+reading is on the PR.
+
+It answers three questions, and needs a Windows AMD APU for any of them:
+
+ 1. Do the two totals actually disagree here? That is the premise. If they
+ agree, #9314 is widening a total that was already correct.
+ 2. Which counter moves when the GPU actually holds memory? `--allocate` takes
+ the reading, allocates, and takes it again. `Dedicated Usage` is what Studio
+ reads today; if the working set lands in `Shared Usage` instead, that is the
+ numerator the PR deferred for want of hardware.
+ 3. What does Studio report end to end, before and after the change?
+
+Run it from a checkout, with the Studio venv's python if you have one:
+
+ python scripts/rocm_windows_apu_probe.py
+ python scripts/rocm_windows_apu_probe.py --allocate 8
+
+`GPU Adapter Memory` lags by tens of seconds, so both readings wait for it to
+stop moving first and the report says whether it did. Without that, a run
+started while an earlier one is still draining reads an inflated baseline and a
+still-climbing "after", and the delta can be wrong by enough to blame the wrong
+counter. `--no-settle` skips the wait and is only for seeing that effect.
+
+Nothing is uploaded. It prints a report to paste into the PR, and `--json`
+writes the same data as JSON.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import platform
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, Optional
+
+GB = 1024**3
+
+
+# --------------------------------------------------------------------------- #
+# Windows performance counters
+# --------------------------------------------------------------------------- #
+def _counter(name: str) -> Optional[list[tuple[str, float]]]:
+ """Read one `GPU Adapter Memory` counter for every adapter instance.
+
+ Returns [(instance, value_bytes)], or None when the counter is unavailable,
+ which is what a localized (non-English) Windows looks like from here.
+ """
+ if platform.system() != "Windows":
+ return None
+ ps = (
+ f"$s=(Get-Counter '\\GPU Adapter Memory(*)\\{name}'"
+ " -ErrorAction SilentlyContinue).CounterSamples;"
+ "if($s){$s|ForEach-Object{'{0}|{1}' -f $_.InstanceName,[int64]$_.CookedValue}}"
+ "else{'__NONE__'}"
+ )
+ try:
+ r = subprocess.run(
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 15,
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if r.returncode != 0 or not r.stdout.strip():
+ return None
+ out: list[tuple[str, float]] = []
+ for line in r.stdout.splitlines():
+ line = line.strip()
+ if not line or line == "__NONE__" or "|" not in line:
+ continue
+ instance, _, raw = line.rpartition("|")
+ try:
+ out.append((instance.strip(), float(raw.strip())))
+ except ValueError:
+ continue
+ return out or None
+
+
+def read_counters() -> dict[str, Any]:
+ """Dedicated and Shared usage side by side, keyed by adapter instance."""
+ dedicated = _counter("Dedicated Usage") or []
+ shared = _counter("Shared Usage") or []
+ # Union, not the dedicated list: the two are separate samples, and an adapter
+ # the dedicated query happened to drop would otherwise vanish from the report
+ # entirely, taking the shared reading that may hold the allocation with it.
+ names = list(dict.fromkeys([n for n, _ in dedicated] + [n for n, _ in shared]))
+ ded, shr = dict(dedicated), dict(shared)
+ return {
+ "available": bool(dedicated or shared),
+ "per_adapter": [
+ {
+ "instance": n,
+ "dedicated_gb": round(ded.get(n, 0.0) / GB, 3) if n in ded else None,
+ "shared_gb": round(shr.get(n, 0.0) / GB, 3) if n in shr else None,
+ }
+ for n in names
+ ],
+ }
+
+
+def _usage_totals_gb(counters: dict[str, Any]) -> tuple[float, float]:
+ """Summed Dedicated and Shared usage across adapters.
+
+ Both, not just Dedicated: past the carve-out Dedicated plateaus while Shared
+ is still climbing, so a dedicated-only test calls that sample settled in the
+ middle of the very overflow this script exists to measure.
+ """
+ per = counters.get("per_adapter", [])
+ return (
+ sum(a["dedicated_gb"] or 0.0 for a in per),
+ sum(a["shared_gb"] or 0.0 for a in per),
+ )
+
+
+def _usage_by_adapter(counters: dict[str, Any]) -> dict[str, tuple[float, float]]:
+ """Per-adapter (dedicated, shared), which is what stability is tested on.
+
+ Not the sums: one adapter rising while another drains leaves the totals flat
+ inside the tolerance while both readings are still moving, and the report is
+ built from per-adapter deltas. An instance appearing or leaving between
+ samples counts as motion too, since a missing row is not a stable one.
+ """
+ return {
+ a["instance"]: (a["dedicated_gb"] or 0.0, a["shared_gb"] or 0.0)
+ for a in counters.get("per_adapter", [])
+ }
+
+
+def _adapters_stable(window: list[dict[str, tuple[float, float]]], tol_gb: float) -> bool:
+ keys = {k for sample in window for k in sample}
+ if any(set(sample) != keys for sample in window):
+ return False # the instance set itself moved
+ for k in keys:
+ for col in range(2):
+ vals = [sample[k][col] for sample in window]
+ if max(vals) - min(vals) > tol_gb:
+ return False
+ return True
+
+
+def read_counters_settled(
+ timeout_s: float = 90.0,
+ tol_gb: float = 0.25,
+ need_stable: int = 3,
+ interval_s: float = 3.0,
+ baseline: Optional[tuple[float, float]] = None,
+ move_gb: float = 0.0,
+ min_wait_s: float = 0.0,
+) -> tuple[dict[str, Any], dict[str, Any]]:
+ """Poll until Dedicated and Shared Usage both stop moving, then take the reading.
+
+ These counters lag badly: a `GPU Process Memory` instance has been observed
+ still reporting 47 GB for a pid that had already exited, and an adapter
+ reading takes tens of seconds to fall back to idle. Reading them cold gives a
+ "before" that is already inflated by whatever ran last and an "after" that is
+ still climbing, and the resulting delta can be wrong by enough to argue for
+ the wrong counter entirely. So the baseline is established rather than
+ assumed, and whether it settled is reported either way: a contaminated run
+ has to be visible as contaminated instead of looking like an answer.
+
+ ``baseline`` is the pre-allocation reading. The same lag that inflates a cold
+ "before" also means the counters can still be sitting at their OLD values for
+ tens of seconds after an allocation lands, and three identical stale samples
+ look exactly like three identical settled ones. So with a baseline the window
+ is only trusted once the reading has actually left it; if it never does,
+ that is reported rather than dressed up as a settled zero delta.
+
+ These totals are host-wide, so a display adapter twitching would otherwise
+ pass for the allocation landing. ``move_gb`` is therefore sized from the
+ amount actually held rather than from the noise tolerance, and ``min_wait_s``
+ holds the window shut for long enough that a lagged counter which happens to
+ be stable at its old value cannot be mistaken for a settled one.
+ """
+ import time
+
+ samples: list[tuple[float, float]] = []
+ keyed: list[dict[str, tuple[float, float]]] = []
+ counters = read_counters()
+ started = time.monotonic()
+ deadline = started + timeout_s
+ settled = False
+ moved = baseline is None
+ threshold = max(move_gb, tol_gb)
+ while True:
+ d, s = _usage_totals_gb(counters)
+ samples.append((round(d, 3), round(s, 3)))
+ keyed.append(_usage_by_adapter(counters))
+ if baseline is not None and not moved:
+ moved = any(abs(now - was) >= threshold for now, was in zip((d, s), baseline))
+ window = keyed[-need_stable:]
+ if (
+ moved
+ and time.monotonic() - started >= min_wait_s
+ and len(window) >= need_stable
+ and _adapters_stable(window, tol_gb)
+ ):
+ settled = True
+ break
+ if time.monotonic() >= deadline:
+ break
+ time.sleep(interval_s)
+ counters = read_counters()
+ return counters, {
+ "settled": settled,
+ "moved_from_baseline": moved,
+ "movement_threshold_gb": round(threshold, 3),
+ "samples_gb": samples,
+ "tolerance_gb": tol_gb,
+ "waited_s": round((len(samples) - 1) * interval_s, 1),
+ }
+
+
+# --------------------------------------------------------------------------- #
+# torch / driver
+# --------------------------------------------------------------------------- #
+def read_torch() -> dict[str, Any]:
+ obs: dict[str, Any] = {}
+ try:
+ import torch
+ except Exception as e: # noqa: BLE001
+ return {"error": f"torch not importable: {type(e).__name__}: {e}"}
+
+ obs["torch_version"] = getattr(torch, "__version__", None)
+ obs["hip"] = getattr(getattr(torch, "version", None), "hip", None)
+ obs["cuda"] = getattr(getattr(torch, "version", None), "cuda", None)
+ try:
+ obs["device_count"] = torch.cuda.device_count()
+ except Exception as e: # noqa: BLE001
+ obs["device_count"] = 0
+ obs["device_count_error"] = f"{type(e).__name__}: {e}"
+
+ devices = []
+ for i in range(obs.get("device_count") or 0):
+ d: dict[str, Any] = {"ordinal": i}
+ try:
+ p = torch.cuda.get_device_properties(i)
+ d["name"] = p.name
+ d["gcn_arch"] = getattr(p, "gcnArchName", None)
+ d["is_integrated"] = getattr(p, "is_integrated", None)
+ # THE PREMISE. On Windows these are expected to disagree on an APU.
+ d["props_total_gb"] = round(p.total_memory / GB, 3)
+ free_b, total_b = torch.cuda.mem_get_info(i)
+ d["driver_total_gb"] = round(total_b / GB, 3)
+ d["driver_free_gb"] = round(free_b / GB, 3)
+ d["driver_exceeds_props"] = bool(total_b > p.total_memory)
+ d["gap_gb"] = round((total_b - p.total_memory) / GB, 3)
+ except Exception as e: # noqa: BLE001
+ d["error"] = f"{type(e).__name__}: {e}"
+ devices.append(d)
+ obs["devices"] = devices
+ return obs
+
+
+def read_studio(repo: Path) -> dict[str, Any]:
+ """What this checkout reports, and what it would have reported before #9314."""
+ backend = repo / "studio" / "backend"
+ if not backend.is_dir():
+ return {"error": f"no Studio backend at {backend}"}
+ sys.path.insert(0, str(backend))
+ obs: dict[str, Any] = {}
+ try:
+ import utils.hardware.hardware as hw
+ except Exception as e: # noqa: BLE001
+ return {"error": f"cannot import hardware module: {type(e).__name__}: {e}"}
+
+ # IS_ROCM is False at module scope until detection runs, and
+ # _rocm_props_total_is_carve_out short-circuits on it, so without this the
+ # probe reports the classifier as not firing and never exercises the changed
+ # path at all -- silently, and worst on exactly the machines that matter.
+ try:
+ obs["detected_device"] = str(hw.ensure_hardware_detected())
+ except Exception as e: # noqa: BLE001
+ obs["detect_error"] = f"{type(e).__name__}: {e}"
+
+ obs["is_rocm"] = bool(getattr(hw, "IS_ROCM", False))
+ try:
+ import torch
+
+ n = torch.cuda.device_count()
+ obs["classifier_says_carve_out"] = [
+ bool(hw._rocm_props_total_is_carve_out(torch.cuda.get_device_properties(i)))
+ for i in range(n)
+ ]
+ indices = list(range(n))
+ except Exception as e: # noqa: BLE001
+ obs["classifier_error"] = f"{type(e).__name__}: {e}"
+ indices = [0]
+
+ try:
+ devices, aggregate = hw._rocm_windows_per_device_vram(indices)
+ obs["per_device_vram"] = devices
+ obs["aggregate_gb"] = aggregate
+ except Exception as e: # noqa: BLE001
+ obs["per_device_vram_error"] = f"{type(e).__name__}: {e}"
+
+ # Why a used_gb came back unknown. On a single-APU box the pairing declines
+ # before the widened-total rule is ever consulted, and without this you have
+ # to reconstruct that by hand to tell the two causes apart.
+ try:
+ adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
+ obs["raw_adapters"] = adapters
+ if adapters:
+ import torch
+
+ totals = [int(torch.cuda.get_device_properties(i).total_memory) for i in indices]
+ useds = [u for _, u in adapters]
+ obs["matcher_result"] = hw._match_adapter_used_to_devices(useds, totals)
+ obs["aggregate_helper"] = hw._rocm_windows_aggregate_used_bytes(useds, totals)
+ except Exception as e: # noqa: BLE001
+ obs["pairing_error"] = f"{type(e).__name__}: {e}"
+ try:
+ obs["inventory"] = hw._torch_get_device_inventory(indices)
+ except Exception as e: # noqa: BLE001
+ obs["inventory_error"] = f"{type(e).__name__}: {e}"
+ try:
+ obs["visible_devices"] = hw.get_visible_gpu_utilization().get("devices")
+ except Exception as e: # noqa: BLE001
+ obs["visible_error"] = f"{type(e).__name__}: {e}"
+ return obs
+
+
+def _unified_ordinal() -> tuple[Optional[int], str]:
+ """The ordinal of a unified part, and why that one.
+
+ ``device="cuda"`` is the DEFAULT device, normally ordinal 0. On a mixed host
+ that is as likely to be a discrete card, and since the counter instances have
+ no mapping back to torch ordinals the report would then be presenting a
+ discrete GPU's behaviour as evidence about unified memory.
+ """
+ import torch
+
+ integrated = []
+ for i in range(torch.cuda.device_count()):
+ props = torch.cuda.get_device_properties(i)
+ if bool(getattr(props, "is_integrated", 0)):
+ integrated.append((i, props.name))
+ if len(integrated) == 1:
+ return integrated[0][0], f"ordinal {integrated[0][0]} ({integrated[0][1]}), is_integrated"
+ if not integrated:
+ return None, "no visible device reports is_integrated; pass --device to override"
+ return None, f"{len(integrated)} integrated devices ({integrated}); pass --device"
+
+
+def allocate(gib: float, ordinal: Optional[int] = None) -> dict[str, Any]:
+ """Hold `gib` on the GPU so the counters can be re-read against it.
+
+ This is the experiment for the open question. Studio reads Dedicated Usage;
+ on a unified APU the working set is expected to land in the shared segment
+ instead, and only a real APU can say which counter actually moves.
+ """
+ import torch
+
+ why = f"ordinal {ordinal} (given with --device)"
+ if ordinal is None:
+ ordinal, why = _unified_ordinal()
+ if ordinal is None:
+ raise RuntimeError(f"refusing to allocate on an unidentified device: {why}")
+ n = int(gib * GB)
+ buf = torch.empty(n, dtype = torch.uint8, device = f"cuda:{ordinal}")
+ buf.fill_(1)
+ torch.cuda.synchronize(ordinal)
+ return {
+ "held_gb": round(n / GB, 3),
+ "device_ordinal": ordinal,
+ "device_choice": why,
+ "device_name": torch.cuda.get_device_properties(ordinal).name,
+ "torch_allocated_gb": round(torch.cuda.memory_allocated(ordinal) / GB, 3),
+ "torch_reserved_gb": round(torch.cuda.memory_reserved(ordinal) / GB, 3),
+ "_buf": buf, # keep alive; stripped before serialising
+ }
+
+
+# --------------------------------------------------------------------------- #
+# Report
+# --------------------------------------------------------------------------- #
+def render(obs: dict[str, Any]) -> str:
+ L: list[str] = []
+ host = obs["host"]
+ L.append("### Host")
+ L.append("")
+ L.append(f"- platform: {host['platform']} {host.get('release', '')}".rstrip())
+ t = obs["torch"]
+ L.append(f"- torch: {t.get('torch_version')} (hip={t.get('hip')}, cuda={t.get('cuda')})")
+ L.append(f"- visible GPUs: {t.get('device_count')}")
+ L.append("")
+
+ L.append("### 1. The premise: do the two totals disagree?")
+ L.append("")
+ L.append("| ordinal | name | arch | integrated | props.total_memory | driver total | gap |")
+ L.append("|---|---|---|---|---|---|---|")
+ for d in t.get("devices", []):
+ if d.get("error"):
+ L.append(f"| {d['ordinal']} | error | | | | | {d['error']} |")
+ continue
+ L.append(
+ f"| {d['ordinal']} | {d.get('name')} | {d.get('gcn_arch')} "
+ f"| {d.get('is_integrated')} | {d.get('props_total_gb')} GB "
+ f"| {d.get('driver_total_gb')} GB | {d.get('gap_gb')} GB |"
+ )
+ L.append("")
+ any_gap = any(d.get("driver_exceeds_props") for d in t.get("devices", []))
+ L.append(
+ f"**driver total exceeds props.total_memory: {any_gap}**"
+ + ("" if any_gap else " <- if this is False on an APU, the premise does not hold here")
+ )
+ L.append("")
+
+ L.append("### 2. Which counter holds the working set?")
+ L.append("")
+ for label in ("counters_before", "counters_after"):
+ c = obs.get(label)
+ if not c:
+ continue
+ when = "before allocation" if label == "counters_before" else "after allocation"
+ if not c.get("available"):
+ why = (
+ "these counters are Windows-only"
+ if host["platform"] != "Windows"
+ else "counter unavailable, which is how a localized Windows reads from here"
+ )
+ L.append(f"- {when}: no reading ({why})")
+ continue
+ s = obs.get("settle_before" if label == "counters_before" else "settle_after")
+ L.append(f"**{when}**")
+ if s:
+ if s["settled"]:
+ L.append(
+ f" (baseline settled after {s['waited_s']}s; "
+ f"(dedicated, shared) totals {s['samples_gb']} GB)"
+ )
+ elif not s.get("moved_from_baseline", True):
+ L.append(
+ f" **WARNING: never moved {s['movement_threshold_gb']} GB off "
+ f"the pre-allocation reading in {s['waited_s']}s** "
+ f"(samples {s['samples_gb']} GB). The "
+ f"allocation is resident but no counter has caught up, so the "
+ f"delta below understates it. Raise --settle-timeout and re-run."
+ )
+ else:
+ L.append(
+ f" **WARNING: still moving after {s['waited_s']}s** "
+ f"(samples {s['samples_gb']} GB). These counters lag, so this "
+ f"reading is contaminated by whatever ran last and the delta "
+ f"below is not trustworthy. Wait for the GPU to go idle and "
+ f"re-run."
+ )
+ L.append("")
+ L.append("| adapter instance | Dedicated Usage | Shared Usage |")
+ L.append("|---|---|---|")
+ for a in c["per_adapter"]:
+ L.append(f"| `{a['instance']}` | {a['dedicated_gb']} GB | {a['shared_gb']} GB |")
+ L.append("")
+ if obs.get("allocation"):
+ a = obs["allocation"]
+ L.append(
+ f"Held {a['held_gb']} GB on the GPU "
+ f"on {a.get('device_name')} [{a.get('device_choice')}] "
+ f"(torch allocated {a['torch_allocated_gb']} GB, "
+ f"reserved {a['torch_reserved_gb']} GB)."
+ )
+ L.append("")
+ before = {
+ x["instance"]: x for x in (obs.get("counters_before") or {}).get("per_adapter", [])
+ }
+ after = {x["instance"]: x for x in (obs.get("counters_after") or {}).get("per_adapter", [])}
+ if before and after:
+ L.append("| adapter instance | Dedicated delta | Shared delta |")
+ L.append("|---|---|---|")
+
+ # A missing side is not zero. The report tells the reader to pick the
+ # numerator by whichever delta matches the amount held, so an absent
+ # baseline coerced to 0.0 would promote an absolute reading to a
+ # delta and hand back a confident wrong answer.
+ def _delta(key: str, b: dict, aft: dict) -> str:
+ x, y = b.get(key), aft.get(key)
+ if x is None or y is None:
+ return "unknown (counter missing on one side)"
+ return f"{round(y - x, 3):+} GB"
+
+ # Union of both snapshots. Dropping out of either one has to show as
+ # a named unknown: an adapter absent from `after` silently vanishing
+ # is how the report ends up claiming nothing moved.
+ for name in dict.fromkeys(list(before) + list(after)):
+ b, aft = before.get(name), after.get(name)
+ if b is None or aft is None:
+ missing = "before" if b is None else "after"
+ cell = f"unknown (absent {missing})"
+ L.append(f"| `{name}` | {cell} | {cell} |")
+ continue
+ L.append(
+ f"| `{name}` | {_delta('dedicated_gb', b, aft)} "
+ f"| {_delta('shared_gb', b, aft)} |"
+ )
+ L.append("")
+ L.append(
+ "Whichever counter moved by roughly the amount held is the one that tracks a "
+ "resident model, and therefore the numerator Studio should be reading. A delta "
+ "materially larger than the amount held means the baseline was not idle; "
+ "re-run rather than believing it."
+ )
+ L.append("")
+
+ L.append("### 3. What Studio reports")
+ L.append("")
+ s = obs.get("studio") or {}
+ if s.get("error"):
+ L.append(f"- not read: {s['error']}")
+ else:
+ L.append(f"- detected device: {s.get('detected_device')}")
+ L.append(f"- IS_ROCM: {s.get('is_rocm')}")
+ L.append(f"- carve-out classifier fires: {s.get('classifier_says_carve_out')}")
+ L.append("")
+ L.append("```json")
+ L.append(
+ json.dumps(
+ {
+ "per_device_vram": s.get("per_device_vram"),
+ "aggregate_gb": s.get("aggregate_gb"),
+ "inventory": s.get("inventory"),
+ "raw_adapters": s.get("raw_adapters"),
+ "matcher_result": s.get("matcher_result"),
+ "aggregate_helper": s.get("aggregate_helper"),
+ "visible_devices": s.get("visible_devices"),
+ },
+ indent = 2,
+ default = str,
+ )
+ )
+ L.append("```")
+ L.append("")
+ L.append("### Before this PR, the same machine would have reported")
+ L.append("")
+ for d in t.get("devices", []):
+ if d.get("error"):
+ continue
+ L.append(
+ f"- ordinal {d['ordinal']}: total **{d.get('props_total_gb')} GB** "
+ f"(props.total_memory verbatim), against **{d.get('driver_total_gb')} GB** now"
+ )
+ return "\n".join(L)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description = __doc__)
+ ap.add_argument(
+ "--allocate",
+ type = float,
+ default = 0.0,
+ help = "GiB to hold on the GPU, to see which counter moves",
+ )
+ ap.add_argument(
+ "--repo",
+ type = Path,
+ default = Path(__file__).resolve().parents[1],
+ help = "checkout to read the Studio hardware module from",
+ )
+ ap.add_argument("--json", type = Path, default = None, help = "also write raw JSON here")
+ ap.add_argument(
+ "--device",
+ type = int,
+ default = None,
+ help = "torch ordinal to allocate on; default is the one reporting is_integrated",
+ )
+ ap.add_argument(
+ "--settle-timeout",
+ type = float,
+ default = 90.0,
+ help = "seconds to wait for the counters to stop moving before reading",
+ )
+ ap.add_argument(
+ "--no-settle",
+ action = "store_true",
+ help = "read the counters cold; the reading may be contaminated by whatever ran last",
+ )
+ args = ap.parse_args()
+
+ obs: dict[str, Any] = {
+ "host": {
+ "platform": platform.system(),
+ "release": platform.release(),
+ "machine": platform.machine(),
+ "python": platform.python_version(),
+ },
+ "torch": read_torch(),
+ }
+ if obs["host"]["platform"] != "Windows":
+ print(
+ "NOTE: this is a Windows diagnostic. On any other platform the "
+ "counters are unavailable and the Windows code path is inert, "
+ "which is exactly why it cannot be validated off Windows.\n"
+ )
+
+ if args.no_settle:
+ obs["counters_before"] = read_counters()
+ else:
+ obs["counters_before"], obs["settle_before"] = read_counters_settled(
+ timeout_s = args.settle_timeout,
+ # There is no baseline to leave here, so stability is the only test,
+ # and a counter still draining from whatever ran last can be flat for
+ # a few intervals before it starts falling. Hold the window shut long
+ # enough that a stale plateau cannot pass for an idle one.
+ min_wait_s = 15.0,
+ )
+
+ held = None
+ if args.allocate > 0:
+ try:
+ held = allocate(args.allocate, args.device)
+ obs["allocation"] = {k: v for k, v in held.items() if k != "_buf"}
+ # The reading climbs for a while after the allocation lands, so the
+ # "after" needs settling every bit as much as the "before".
+ if args.no_settle:
+ obs["counters_after"] = read_counters()
+ else:
+ obs["counters_after"], obs["settle_after"] = read_counters_settled(
+ timeout_s = args.settle_timeout,
+ baseline = _usage_totals_gb(obs["counters_before"]),
+ # Half the held amount: enough that a display adapter's blip
+ # cannot pass for the allocation, loose enough that a counter
+ # which only ever accounts for part of it still qualifies.
+ move_gb = 0.5 * held["held_gb"],
+ min_wait_s = 15.0,
+ )
+ except Exception as e: # noqa: BLE001
+ obs["allocation_error"] = f"{type(e).__name__}: {e}"
+
+ obs["studio"] = read_studio(args.repo)
+
+ report = render(obs)
+ print(report)
+ if args.json:
+ args.json.write_text(json.dumps(obs, indent = 2, default = str))
+ print(f"\nraw JSON written to {args.json}")
+ del held
+ 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.py
index 1bc3ee0b64b..d2366791ba2 100644
--- a/studio/backend/tests/test_rocm_windows_vram_7072.py
+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py
@@ -1090,6 +1090,13 @@ def test_the_measured_strix_halo_needs_the_join_for_any_aggregate(win_rocm, monk
This is the shape a single-GPU Windows AMD host actually has, which is why
#7072's reporter saw Unknown where the hardware was plainly busy.
+
+ The figure itself moved when the APU pairing landed on top of the join. The
+ join reads Dedicated Usage, which pins at the carve-out, and this part is a
+ confirmed APU whose retained total spans the pool, so the published number is
+ now Dedicated+Shared (31.681 + 17.820, the counters measured together on the
+ same host). What the join still supplies, and nothing below it can, is the
+ aggregate: that is the claim this test exists for and it is unchanged.
"""
monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
monkeypatch.setitem(
@@ -1113,18 +1120,37 @@ def test_the_measured_strix_halo_needs_the_join_for_any_aggregate(win_rocm, monk
"_windows_amd_adapter_records_by_luid",
lambda: {86826: {"name": "AMD Radeon(TM) 8060S Graphics"}}, # no AdapterFamily
)
+ # The counter fake answers every "GPU Adapter Memory" query with the same
+ # rows, so Shared would come back as a second copy of Dedicated. Patch the
+ # sum directly, as the other APU tests here do, and give it the two figures
+ # actually measured together on this host.
+ monkeypatch.setattr(
+ hw, "_rocm_windows_unified_used_bytes", lambda dedicated = None: (31.681 + 17.820) * GB
+ )
devices, aggregate = hw._rocm_windows_per_device_vram([0])
- assert devices[0]["used_gb"] == pytest.approx(31.68, abs = 0.01)
- assert aggregate == pytest.approx(31.68, abs = 0.01)
+ assert devices[0]["used_gb"] == pytest.approx(49.5, abs = 0.01)
+ assert aggregate == pytest.approx(49.5, abs = 0.01)
- # The same host with the registry unreadable: everything below the join.
- monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: {})
- _, fallback_aggregate = hw._rocm_windows_per_device_vram([0])
+ # The claim itself, put to the helper rather than inferred from the caller:
+ # capacity ranking cannot produce an aggregate on this host at any load,
+ # because three counter instances are not the one-device visible set.
assert (
- fallback_aggregate is None
+ hw._rocm_windows_aggregate_used_bytes(
+ [used for _, used in adapters], [float(int(89.465 * GB))]
+ )
+ is None
), "capacity ranking produced an aggregate the measured host cannot give it"
+ # With the registry unreadable the join is gone, and on THIS part the APU
+ # pairing still supplies a figure, because a confirmed unified device takes
+ # the Dedicated+Shared sum whether or not identity resolved. So the host is
+ # no longer one-path; the two agree, and the fallback is the pairing rather
+ # than capacity ranking, which is still declining underneath.
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: {})
+ _, fallback_aggregate = hw._rocm_windows_per_device_vram([0])
+ assert fallback_aggregate == pytest.approx(49.5, abs = 0.01)
+
def test_the_join_declines_usage_it_cannot_place(win_rocm, monkeypatch):
"""A hidden AMD card carrying the visible device's torch name, while the
@@ -1163,3 +1189,701 @@ def test_the_join_declines_usage_it_cannot_place(win_rocm, monkeypatch):
devices, _ = hw._rocm_windows_per_device_vram([0])
# 17 GiB is the hidden card's. Unknown is the only honest answer here.
assert devices[0]["used_gb"] is None
+
+
+# ----------------------------------------------------------------------------- #
+# The per-device total on a unified-memory APU
+#
+# _rocm_windows_per_device_vram took props.total_memory verbatim, which on an APU
+# is the dedicated carve-out rather than what torch can use, so a 128 GiB Strix
+# Halo budgeted as roughly 8. Every other path already corrects this through
+# _rocm_props_total_is_carve_out; this one did not.
+# ----------------------------------------------------------------------------- #
+APU = ("AMD Radeon(TM) 8060S Graphics", 8 * GB)
+
+APU_ADAPTERS = [("luid_0x00000000_0x0000c001_phys_0", 2 * GB)]
+
+
+def test_windows_apu_total_is_the_driver_pool_not_the_carve_out(win_rocm, monkeypatch):
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ torch = _fake_torch([APU])
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (96 * GB, 128 * GB))
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(APU_ADAPTERS))
+ )
+
+ monkeypatch.setattr(hw, "_rocm_props_are_positively_unified", lambda props: True)
+ monkeypatch.setattr(hw, "_rocm_windows_unified_used_bytes", lambda d = None: 12.0 * GB)
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 128.0
+ # Dedicated Usage alone saturates at the carve-out, so a widened total takes
+ # the Dedicated+Shared sum instead. Pairing the carve-out reading with a pool
+ # total would hand back the shared pool as free while a model sits in it.
+ assert devices[0]["used_gb"] == 12.0
+ assert aggregate == 12.0
+
+
+def test_an_unsettled_classifier_does_not_cost_a_card_its_occupancy(win_rocm, monkeypatch):
+ """The classifier answers "carve-out" for a discrete card too whenever the
+ runtime leaves it unsettled (no integrated flag, HIP below 6.2). The driver
+ total comes back equal there, so nothing widened and nothing is unknown."""
+ torch = _fake_torch(DEVICES, free_equals_total = True)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(REPORTER_ADAPTERS))
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0]
+ assert devices[0]["used_gb"] == pytest.approx(40.0, abs = 0.01)
+
+
+def test_a_discrete_card_must_not_pay_a_context_for_its_total(win_rocm, monkeypatch):
+ """Only an APU pays mem_get_info for its total; a poll that attaches a
+ context on a discrete card never gives the memory back."""
+ torch = _fake_torch(DEVICES, free_equals_total = True)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(
+ torch.cuda, "mem_get_info", lambda i: pytest.fail("a discrete card must not be asked")
+ )
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: False)
+ monkeypatch.setattr(hw.subprocess, "run", _subprocess_run(adapter_output = "__NONE__\n"))
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0]
+
+
+# ----------------------------------------------------------------------------- #
+# A widened APU total must not follow the APU into the capacity matching
+#
+# _match_adapter_used_to_devices ranks the Dedicated Usage counters against
+# device capacity, and that counter measures the DEDICATED segment, whose ceiling
+# is the carve-out and never the pool. Ranked against a widened total the APU
+# outranks every discrete card, the threshold that forces a pairing rises, and so
+# does the ceiling of the impossible-counter check. The total_is_pool guard runs
+# after the matching and nulls only the widened device, so it cannot reach that.
+# ----------------------------------------------------------------------------- #
+MIXED = [("AMD Radeon(TM) 8060S Graphics", 8 * GB), ("AMD Radeon RX 7900 XTX", 24 * GB)]
+
+MIXED_ADAPTERS = [
+ ("luid_0x00000000_0x0000c001_phys_0", 2.0 * GB), # APU carve-out
+ ("luid_0x00000000_0x0000d1e2_phys_0", 10.0 * GB), # 7900 XTX, model loaded
+ ("luid_0x00000000_0x0000f001_phys_0", 3 * MiB), # Basic Render Driver
+]
+
+
+def _mixed_host(monkeypatch):
+ """APU (8 GiB carve-out, 128 GiB pool) at ordinal 0, discrete 24 GiB at 1."""
+ torch = _fake_torch(MIXED, free_equals_total = True)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ # _Props carries no is_integrated, so the classifier stays patched; keying it
+ # on the total is what lets one fake host hold an APU and a discrete card.
+ monkeypatch.setattr(
+ hw, "_rocm_props_total_is_carve_out", lambda props: props.total_memory == 8 * GB
+ )
+ monkeypatch.setattr(
+ torch.cuda,
+ "mem_get_info",
+ lambda i: (96 * GB, 128 * GB)
+ if i == 0
+ else pytest.fail("a discrete card must not be asked"),
+ )
+ return torch
+
+
+def test_widened_apu_total_does_not_cost_the_discrete_card_its_usage(win_rocm, monkeypatch):
+ """Hidden-adapter branch. Against carve-out totals [8, 24] the 10 GiB counter
+ exceeds 8 GiB, so capacity forces it onto the 24 GiB card. Against a 128 GiB
+ pool the APU takes rank 0, 10 GiB no longer exceeds the next capacity, and
+ the discrete card reads Unknown."""
+ _mixed_host(monkeypatch)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(MIXED_ADAPTERS))
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["total_gb"] for d in devices] == [128.0, 24.0] # displayed total still widened
+ assert devices[0]["used_gb"] is None # Dedicated Usage is not the pool's numerator
+ assert devices[1]["used_gb"] == pytest.approx(10.0, abs = 0.01)
+ assert aggregate is None # one member of the visible set is unknown
+
+
+def test_widened_apu_total_does_not_make_every_pairing_ambiguous(win_rocm, monkeypatch):
+ """Equal-length branch, no placeholder counter. The ambiguity check asks
+ whether the two usages could be swapped without breaking capacity: 10 GiB
+ does not fit the 8 GiB carve-out, so they could not, but it fits a 128 GiB
+ slot, so every ranking on a mixed host becomes swappable."""
+ _mixed_host(monkeypatch)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(MIXED_ADAPTERS[:2]))
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert devices[1]["used_gb"] == pytest.approx(10.0, abs = 0.01)
+ assert devices[0]["used_gb"] is None
+
+
+def test_widened_apu_total_does_not_admit_an_impossible_counter(win_rocm, monkeypatch):
+ """A 50 GiB counter fits no visible card, so the list is not the visible set
+ and every device must read Unknown. Against a 128 GiB slot it fits, shifts
+ the others down a rank and fabricates 30 GiB on the 48 GiB card: a wrong
+ reading rather than an unknown one, which the guard does not cover."""
+ torch = _fake_torch(
+ [
+ ("AMD Radeon(TM) 8060S Graphics", 8 * GB),
+ ("AMD Radeon PRO W7900", 48 * GB),
+ ("AMD Radeon PRO W7800", 24 * GB),
+ ],
+ free_equals_total = True,
+ )
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,1,2")
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(
+ hw, "_rocm_props_total_is_carve_out", lambda props: props.total_memory == 8 * GB
+ )
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (96 * GB, 128 * GB))
+ adapters = [
+ ("luid_0x00000000_0x0000a001_phys_0", 50.0 * GB), # hidden card, no visible home
+ ("luid_0x00000000_0x0000d1e2_phys_0", 30.0 * GB),
+ ("luid_0x00000000_0x0000e34a_phys_0", 1.0 * GB),
+ ("luid_0x00000000_0x0000f001_phys_0", 3 * MiB),
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1, 2])
+ assert [d["used_gb"] for d in devices] == [None, None, None]
+ assert [d["total_gb"] for d in devices] == [128.0, 48.0, 24.0]
+ assert aggregate is None
+
+
+def test_a_driver_total_below_the_carve_out_is_not_adopted(win_rocm, monkeypatch):
+ """The classifier says carve-out for a discrete card on an unsettled runtime
+ too, and this path carries a used alongside the total. A driver total below
+ props.total_memory there reports past 100% utilization and, through
+ free = max(total - used, 0), zero free on a card that is mostly empty."""
+ torch = _fake_torch(DEVICES, free_equals_total = True)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True)
+ # Driver under-reports the 48 GiB card.
+ monkeypatch.setattr(
+ torch.cuda, "mem_get_info", lambda i: (0, 36 * GB) if i == 0 else (0, 8 * GB)
+ )
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(REPORTER_ADAPTERS))
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0]
+ assert devices[0]["used_gb"] == pytest.approx(40.0, abs = 0.01)
+ assert all(d["used_gb"] <= d["total_gb"] for d in devices if d["used_gb"] is not None)
+
+
+def test_a_failing_carve_out_probe_keeps_the_device(win_rocm, monkeypatch):
+ """The correction is a probe, and it is the first thing this path asks the
+ classifier. A probe that throws must cost the device its correction, not its
+ place in the visible set: dropping it shows the System tab no GPU at all."""
+ torch = _fake_torch(DEVICES, free_equals_total = True)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+
+ def _boom(props):
+ raise RuntimeError("classifier unavailable")
+
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", _boom)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(REPORTER_ADAPTERS))
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0]
+ assert devices[0]["used_gb"] == pytest.approx(40.0, abs = 0.01)
+
+
+def test_the_inventory_path_also_refuses_to_shrink_a_total(monkeypatch):
+ """The sibling correction this one is modelled on. It publishes no used, so a
+ shrink cannot break the used <= total invariant there, but an understated
+ total still hides models the device can hold, which is the failure the
+ classifier exists to prevent."""
+ # Not on win_rocm (this path is platform-independent), so it has to pin
+ # get_device itself. _torch_get_device_module resolves through it, and on a
+ # runner with no GPU the cached detection answers CPU, which returns
+ # (None, None) and makes the inventory come back empty. Leaving it ambient
+ # made this test pass locally and fail on CI.
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ torch = _fake_torch(DEVICES)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True)
+ # Under-reports the 48 GiB card, agrees on the 8 GiB one.
+ monkeypatch.setattr(
+ torch.cuda, "mem_get_info", lambda i: (0, 36 * GB) if i == 0 else (0, 8 * GB)
+ )
+
+ devices = hw._torch_get_device_inventory([0, 1])
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0]
+ assert all(d["used_gb"] is None for d in devices)
+
+
+def _apu_host(monkeypatch, unified_used = 12.0 * GB):
+ """A lone 8 GiB carve-out / 128 GiB pool APU.
+
+ ``unified_used`` stands in for _rocm_windows_unified_used_bytes, which sums
+ Dedicated and Shared. Patched rather than driven through the counters because
+ what is under test here is that a widened device takes that figure, not the
+ counter plumbing, which #9362's own tests already cover. ``None`` simulates it
+ declining.
+ """
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ torch = _fake_torch([APU])
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (96 * GB, 128 * GB))
+ 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, "_rocm_windows_unified_used_bytes", lambda d = None: unified_used)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(APU_ADAPTERS))
+ )
+
+
+def test_widened_total_survives_get_gpu_utilization(win_rocm, monkeypatch):
+ """The helper is not what the user sees. The corrected total has to reach the
+ payload, and the unknown occupancy has to stay unknown through the legacy
+ primary-device mirror rather than being filled in with a zero."""
+ _apu_host(monkeypatch)
+
+ result = hw.get_gpu_utilization()
+ assert result["devices"][0]["vram_total_gb"] == 128.0
+ assert result["devices"][0]["vram_used_gb"] == 12.0
+ assert result["devices"][0]["vram_utilization_pct"] == pytest.approx(9.4, abs = 0.1)
+ assert result["vram_total_gb"] == 128.0 # legacy mirror carries it too
+ assert result["vram_used_gb"] == 12.0
+
+
+def test_the_system_tab_does_not_invent_free_vram_on_an_apu(win_rocm, monkeypatch):
+ """The failure this guards is a 128 GiB card reporting 128 GiB free while a
+ model sits in the shared pool: free is total minus used, and used is unknown,
+ so free must stay unknown rather than defaulting used to zero."""
+ _apu_host(monkeypatch)
+
+ devices = hw.get_visible_gpu_utilization()["devices"]
+ assert devices[0]["vram_total_gb"] == 128.0
+ assert devices[0]["vram_used_gb"] == 12.0
+ assert devices[0]["vram_utilization_pct"] == pytest.approx(9.4, abs = 0.1)
+
+
+def test_a_declining_unified_read_leaves_the_apu_unknown(win_rocm, monkeypatch):
+ """When the sum cannot be established the carve-out reading must not be left
+ standing under a pool-sized total: that is the reading that reports a loaded
+ 128 GiB card as almost entirely free."""
+ _apu_host(monkeypatch, unified_used = None)
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 128.0
+ assert devices[0]["used_gb"] is None
+ assert aggregate is None
+
+
+def test_shared_usage_needs_a_positively_unified_part(win_rocm, monkeypatch):
+ """_rocm_props_total_is_carve_out fails open, so a discrete card on an
+ unsettled runtime can widen. Shared Usage is host memory that its
+ props.total_memory never counted, so the sum must not become its numerator:
+ the stricter classifier has to gate it, exactly as get_gpu_memory_info does."""
+ _apu_host(monkeypatch, unified_used = 90.0 * GB)
+ monkeypatch.setattr(hw, "_rocm_props_are_positively_unified", lambda props: False)
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ # Not merely "the sum is not used": without positive UMA the driver total is
+ # never asked for, so there is no widening to pair a numerator with either.
+ assert devices[0]["total_gb"] == 8.0
+ assert devices[0]["used_gb"] == 2.0 # the Dedicated counter, not the sum
+ assert aggregate == 2.0
+
+
+def test_a_nonzero_sub_threshold_row_declines_the_unified_sum(win_rocm, monkeypatch):
+ """The helper picks the lone counter above the noise floor. With only the APU
+ visible but a hidden GPU active, that counter is the hidden one and the APU is
+ the small row, so its usage would be published as the APU's. The matcher
+ declines this shape by requiring every dropped counter to be an exact zero."""
+ _apu_host(monkeypatch, unified_used = 30.0 * GB)
+ monkeypatch.setattr(
+ hw.subprocess,
+ "run",
+ _subprocess_run(
+ adapter_output = _adapter_output(
+ [
+ ("luid_0x00000000_0x0000c001_phys_0", 10 * MiB), # the visible APU, idle
+ ("luid_0x00000000_0x0000d1e2_phys_0", 30.0 * GB), # a hidden GPU, loaded
+ ]
+ )
+ ),
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["used_gb"] is None
+ assert aggregate is None
+
+
+def test_a_negative_counter_never_publishes_negative_usage(win_rocm, monkeypatch):
+ """The helper declines a negative reading at source; this is the consumer end
+ of the same guarantee, driven with the helper stubbed so the clamp that
+ publishes the number is what gets tested rather than the decline above it."""
+ _apu_host(monkeypatch, unified_used = -5.0 * GB)
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["used_gb"] == 0.0
+ assert aggregate == 0.0
+
+
+def test_an_apu_beside_a_discrete_card_probes_only_the_apu(win_rocm, monkeypatch):
+ """The mixed host, which is the one configuration nobody has hardware for.
+
+ An APU whose props.total_memory IS the 32 GiB carve-out, beside a 48 GiB
+ discrete card holding 40 GiB. Three things have to hold at once, and only
+ the middle one is covered elsewhere:
+
+ * the APU's total widens to the pool, 32 -> 89.46
+ * the discrete card KEEPS its capacity-forced 40 GiB; widening one device
+ must not rerank the others out of a reading
+ * exactly one mem_get_info call, on the APU. The discrete card must not be
+ asked, because that call attaches a permanent ~612 MiB context.
+ """
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,1")
+ torch = _fake_torch(
+ [
+ ("AMD Radeon(TM) 8060S Graphics", 32 * GB), # carve-out, not the pool
+ ("AMD Radeon PRO W7900", 48 * GB),
+ ]
+ )
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ probed = []
+ monkeypatch.setattr(
+ torch.cuda,
+ "mem_get_info",
+ lambda i: (probed.append(i), (0, int(89.465 * GB) if i == 0 else 48 * GB))[1],
+ )
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True)
+ monkeypatch.setattr(
+ hw,
+ "_rocm_props_are_positively_unified",
+ lambda props: props.total_memory == 32 * GB,
+ )
+ monkeypatch.setattr(
+ hw.subprocess,
+ "run",
+ _subprocess_run(
+ adapter_output = _adapter_output(
+ [
+ ("luid_0x00000000_0x0001532a_phys_0", 31.58 * GB), # APU, saturated
+ ("luid_0x00000000_0x0000d1e2_phys_0", 40.0 * GB), # the discrete card
+ ("luid_0x00000000_0x00017034_phys_0", 0.0), # placeholder
+ ]
+ )
+ ),
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert devices[0]["total_gb"] == 89.46 # widened
+ assert devices[1]["used_gb"] == 40.0 # and the discrete card kept its reading
+ assert probed == [0], f"expected only the APU to be probed, got {probed}"
+
+
+def test_the_poll_does_not_probe_an_unclassified_discrete_card(win_rocm, monkeypatch):
+ """mem_get_info attaches a primary HIP context worth ~612 MiB that is never
+ released, and main reaches this function without ever calling it. The
+ carve-out classifier fails open for an unclassified discrete card, so gating
+ the probe on it would take that off every discrete GPU on the host on every
+ telemetry poll, for a total the device then does not use."""
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,1")
+ torch = _fake_torch(DEVICES)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ probed = []
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (probed.append(i), (0, 99 * GB))[1])
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda props: True) # fails open
+ monkeypatch.setattr(hw, "_rocm_props_are_positively_unified", lambda props: False)
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(REPORTER_ADAPTERS))
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert probed == [], "a discrete card was asked for a context it does not need"
+ assert [d["total_gb"] for d in devices] == [48.0, 8.0] # props totals, unwidened
+
+
+def test_a_failed_driver_probe_keeps_the_apu_on_the_dedicated_counter(win_rocm, monkeypatch):
+ """Being a UMA part says what the device is, not what scope its total has. A
+ confirmed APU whose mem_get_info probe fails keeps a carve-out-sized total,
+ and Dedicated Usage is the correct numerator for that one. Summing Shared
+ into it would clamp to a fabricated 100%."""
+ _apu_host(monkeypatch, unified_used = 40.0 * GB)
+ torch = sys.modules["torch"]
+ monkeypatch.setattr(
+ torch.cuda,
+ "mem_get_info",
+ lambda i: (_ for _ in ()).throw(RuntimeError("hipMemGetInfo failed")),
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 8.0 # the carve-out, unwidened
+ assert devices[0]["used_gb"] == 2.0 # the Dedicated counter, not the sum
+ assert devices[0]["used_gb"] <= devices[0]["total_gb"]
+
+
+def test_the_measured_strix_halo_at_64_gib_held(win_rocm, monkeypatch):
+ """Real numbers off a Windows gfx1151, driver 32.0.21041.1000, 32 GiB carve-out.
+
+ Holding 64 GiB, Dedicated Usage reads 31.637 GB and Shared 33.887: Dedicated
+ tracks the allocation one for one until it pins at the carve-out, then stays
+ flat while Shared absorbs every further GiB. props.total_memory is already
+ 89.465 GB, so nothing widens and total_is_pool never fires.
+
+ Pre-PR this reported 31.64 used against an 89.46 total, i.e. 57.82 GB free
+ with 64 GiB resident. Overstating free by 33.88 GB is the direction that
+ OOMs, and it is the case this pairing exists to fix.
+ """
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ torch = _fake_torch([("AMD Radeon(TM) 8060S Graphics", int(89.465 * GB))])
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (0, int(89.465 * GB)))
+ 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,
+ "_rocm_windows_unified_used_bytes",
+ lambda dedicated = None: (31.637 + 33.887) * GB,
+ )
+ monkeypatch.setattr(
+ hw.subprocess,
+ "run",
+ _subprocess_run(
+ adapter_output = _adapter_output(
+ [
+ (
+ "luid_0x00000000_0x0001532a_phys_0",
+ 31.637 * GB,
+ ), # saturated at the carve-out
+ ("luid_0x00000000_0x00017034_phys_0", 0.0),
+ ("luid_0x00000000_0x00017099_phys_0", 0.0),
+ ]
+ )
+ ),
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 89.46
+ assert devices[0]["used_gb"] == 65.52 # not the 31.64 Dedicated alone reports
+ assert devices[0]["total_gb"] - devices[0]["used_gb"] < 24.0
+
+
+def test_a_confirmed_apu_takes_the_unified_sum_even_unwidened(win_rocm, monkeypatch):
+ """The measured gfx1151 has props.total_memory already spanning the pool, so
+ nothing widens and total_is_pool stays false. The total is pool-scoped all
+ the same, and Dedicated alone plateaus at the carve-out under it, which is
+ the reading that reports a loaded APU as mostly free."""
+ _apu_host(monkeypatch, unified_used = 4.0 * GB)
+ torch = sys.modules["torch"]
+ # Both totals agree: the driver has nothing wider to offer.
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (0, APU[1]))
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == round(APU[1] / GB, 2)
+ # 4.0, not the 2.0 the Dedicated counter alone reports for this adapter.
+ assert devices[0]["used_gb"] == 4.0
+ assert aggregate == 4.0
+
+
+def test_the_unified_sum_is_clamped_to_the_widened_total(win_rocm, monkeypatch):
+ """Dedicated plus Shared counts driver and desktop allocations too, so it can
+ exceed torch's pool. Every other reading is clamped on its way through the
+ matcher; this one bypasses it and the payload derives free as total minus
+ used, so an unclamped sum publishes negative free."""
+ _apu_host(monkeypatch, unified_used = 140.0 * GB)
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["used_gb"] == 128.0
+ assert aggregate == 128.0
+
+
+def test_the_dedicated_snapshot_is_not_sampled_twice(win_rocm, monkeypatch):
+ """Each counter query is an out-of-process PowerShell call, and re-sampling
+ would also answer from a different instant than the attribution above it."""
+ _apu_host(monkeypatch)
+ seen = []
+ monkeypatch.setattr(
+ hw,
+ "_rocm_windows_unified_used_bytes",
+ lambda dedicated = None: (seen.append(dedicated), 12.0 * GB)[1],
+ )
+
+ hw._rocm_windows_per_device_vram([0])
+ assert seen and seen[0], "the caller's snapshot was not handed over"
+
+
+def test_an_unavailable_dedicated_snapshot_is_not_requeried(win_rocm, monkeypatch):
+ """When the caller's own Dedicated query came back unavailable, handing None
+ to the helper reads as "not supplied" and runs the query a second time, on the
+ polled telemetry path, to arrive at the same None."""
+ _apu_host(monkeypatch)
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", lambda *a, **k: None)
+ seen = []
+ monkeypatch.setattr(
+ hw,
+ "_rocm_windows_unified_used_bytes",
+ lambda dedicated = None: (seen.append(dedicated), None)[1],
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert seen == [], "an unavailable snapshot was handed over and re-queried"
+ assert devices[0]["used_gb"] is None
+ assert aggregate is None
+
+
+def test_a_negative_counter_reading_is_declined(win_rocm, monkeypatch):
+ """A negative cooked counter is a broken reading, not low usage. The caller
+ clamps the upper bound only and the payload derives free as total minus used,
+ so a negative sum would publish a negative used and a free above the total."""
+
+ def counters(counter = "Dedicated Usage"):
+ if counter == "Dedicated Usage":
+ return [("luid_0x00000000_0x0000abcd_phys_0", 2.0 * GB)]
+ return [("luid_0x00000000_0x0000abcd_phys_0", -1.0 * GB)]
+
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", counters)
+ assert hw._rocm_windows_unified_used_bytes() is None
+
+
[email protected]("system", ["Linux", "Darwin"])
+def test_the_windows_path_is_inert_off_windows(win_rocm, monkeypatch, system):
+ """Linux, macOS and WSL (which reports Linux) never reach this path, so no
+ change to it can reach them."""
+ monkeypatch.setattr(hw.platform, "system", lambda: system)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(DEVICES))
+ monkeypatch.setattr(
+ hw, "_rocm_props_total_is_carve_out", lambda props: pytest.fail("not on this platform")
+ )
+
+ assert hw._rocm_windows_per_device_vram([0, 1]) == ([], None)
+
+
+# ----------------------------------------------------------------------------- #
+# An APU the shared classifier cannot name
+#
+# _rocm_classify_unified_memory names an APU from hipDeviceProp_t::integrated or
+# from the shared-pool arch set that drives the memory-fraction cap. A gfx1103
+# Phoenix iGPU on a runtime that leaves the flag at 0 is in neither, so
+# _rocm_props_are_positively_unified said no -- while on Windows PAL had already
+# added the WDDM shared heap to globalMemSize_ for it, because that inflation
+# keys off Pal::GpuType::Integrated and not off what the props struct reports.
+#
+# A pool-scoped total paired with the Dedicated-only numerator is the exact
+# failure this PR exists to fix, on a device the classifier misses.
+# ----------------------------------------------------------------------------- #
+# Reported on a Windows Radeon 780M with 24295 MiB of RAM
+# (patientx/ComfyUI-Zluda#387): mem_get_info's total reads 17303 MiB. That is
+# paldevice.cpp's formula to the MiB -- an 8 GiB BIOS carve-out plus 75% of the
+# ~12147 MiB WDDM shared heap (8192 + 9110 = 17302). The same divergence is
+# described from the other side in likelovewant/ROCmLibs-for-gfx1103#67: ADLX
+# reports only the BIOS carve-out while hipMemGetInfo reports the shared pool.
+PHOENIX_CARVE_OUT = 8.0 * GB
+PHOENIX_POOL = 17303 * MiB # 16.90 GiB
+PHOENIX_RESIDENT = 12.0 * GB # a model that does not fit the carve-out
+PHOENIX_DEDICATED = 7.90 * GB # plateaued just under the carve-out
+PHOENIX_SHARED = 4.10 * GB # the overflow
+
+
+def _phoenix_host(
+ monkeypatch,
+ gfx = "gfx1103",
+ name = "AMD Radeon(TM) 780M Graphics",
+):
+ """A lone Windows APU on a pre-6.2 HIP runtime, driven through the counters.
+
+ ``_rocm_props_are_positively_unified`` is deliberately NOT patched: what is
+ under test is the classification itself, so the real helper has to run.
+ """
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ torch = _fake_torch([(name, int(PHOENIX_POOL), gfx)])
+ torch.__version__ = "2.9.0+rocm6.1"
+ torch.version = types.SimpleNamespace(hip = "6.1", cuda = None)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ # The same variable read twice in clr, so the driver has nothing wider.
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda i: (0, int(PHOENIX_POOL)))
+ monkeypatch.setattr(
+ hw,
+ "_rocm_windows_perf_counter_vram_by_adapter",
+ lambda counter = "Dedicated Usage": [
+ (
+ "luid_0x00000000_0x0000c001_phys_0",
+ PHOENIX_DEDICATED if counter == "Dedicated Usage" else PHOENIX_SHARED,
+ )
+ ],
+ )
+ return torch
+
+
+def test_a_phoenix_apu_the_classifier_misses_reads_as_an_unnamed_apu(win_rocm):
+ """gfx1103 is an integrated part and never shipped as a discrete board, so
+ naming it cannot upgrade anything whose total is really carve-out scoped."""
+
+ class _P:
+ name = "AMD Radeon(TM) 780M Graphics"
+ gcnArchName = "gfx1103"
+ total_memory = int(PHOENIX_POOL)
+ is_integrated = 0 # pre-6.2 HIP leaves it 0 on Windows
+
+ assert hw._rocm_props_are_positively_unified(_P()) is False # unchanged
+ assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+ _P.gcnArchName = "gfx1103:xnack-" # suffixes and case must not hide it
+ assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+ _P.gcnArchName = "GFX1103"
+ assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+
+
+def test_a_discrete_card_is_neither_positively_unified_nor_an_unnamed_apu(win_rocm):
+ """The guarantee the numerator rests on: shared bytes are host memory a
+ discrete card's props.total_memory never counted."""
+
+ class _P:
+ name = "AMD Radeon RX 7900 XTX"
+ gcnArchName = "gfx1100"
+ total_memory = 24 * GB
+ is_integrated = 0
+
+ assert hw._rocm_props_are_positively_unified(_P()) is False
+ assert hw._rocm_props_are_an_unnamed_apu(_P()) is False
+ _P.gcnArchName, _P.name = "gfx1201", "AMD Radeon RX 9070 XT"
+ assert hw._rocm_props_are_positively_unified(_P()) is False
+ assert hw._rocm_props_are_an_unnamed_apu(_P()) is False
+
+
+def test_a_phoenix_pool_total_takes_the_shared_sum_not_the_plateau(win_rocm, monkeypatch):
+ """16.90 GiB pool under an 8 GiB carve-out with 12 GiB resident.
+
+ Pre-fix: 7.90 used, i.e. 9.00 free with 12 GiB in the pool. Overstating free
+ by 4.10 GB is the direction that OOMs, and it is the same reading the
+ measured gfx1151 gets when Dedicated alone is paired with a pool total."""
+ _phoenix_host(monkeypatch)
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 16.9
+ assert devices[0]["used_gb"] == pytest.approx(12.0, abs = 0.01) # not the 7.90 plateau
+ assert aggregate == pytest.approx(12.0, abs = 0.01)
+ assert devices[0]["total_gb"] - devices[0]["used_gb"] == pytest.approx(4.9, abs = 0.01)
+
+
+def test_a_discrete_card_on_the_same_runtime_keeps_the_dedicated_counter(win_rocm, monkeypatch):
+ """The other half of the guarantee, through the same fixture: an unsettled
+ runtime does not let Shared Usage into a discrete card's numerator, and its
+ total is never probed for a pool it does not have."""
+ torch = _phoenix_host(monkeypatch, gfx = "gfx1100", name = "AMD Radeon RX 7900 XTX")
+ monkeypatch.setattr(
+ torch.cuda, "mem_get_info", lambda i: pytest.fail("a discrete card must not be asked")
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["total_gb"] == 16.9
+ assert devices[0]["used_gb"] == pytest.approx(7.90, abs = 0.01) # Dedicated alone
+ assert aggregate == pytest.approx(7.90, abs = 0.01)
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 288b8a4e263..1eaf4f42da4 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -1447,6 +1447,25 @@ def _hip_runtime_version() -> Optional[tuple[int, int]]:
return None
+# APU architectures that are unified memory but sit outside the shared
+# classifier's positive set. That set is the list of parts whose SHARED POOL SIZE
+# drives a lower set_per_process_memory_fraction cap, and it names anything else
+# from hipDeviceProp_t::integrated; a Phoenix / Hawk Point iGPU on a runtime that
+# leaves that flag at 0 is therefore in neither, and reads as "not unified".
+#
+# Harmless for the cap and for the total, and wrong for a NUMERATOR: clr never
+# assigned deviceProps.integrated before tag rocm-6.2.0 (so HIP SDK for Windows
+# 5.5.1 / 5.7.1 / 6.1.2 leave it 0 in a zero-initialised struct, which is what
+# _HIP_INTEGRATED_FLAG_MIN above already encodes), and the legacy R0000 property
+# ABI still does not assign it on any version -- while paldevice.cpp inflates
+# globalMemSize_ off settings().apuSystem_ in both cases.
+#
+# gfx1103 Phoenix / Hawk Point is an integrated part and never shipped as a
+# discrete board, so naming it here can only ever upgrade a part whose
+# props.total_memory really does span host memory.
+_ROCM_UNNAMED_APU_ARCHES = frozenset({"gfx1103"})
+
+
def _rocm_props_are_positively_unified(props: Any) -> bool:
"""Whether this part is KNOWN to be unified memory, not merely unclassified.
@@ -1454,6 +1473,17 @@ def _rocm_props_are_positively_unified(props: Any) -> bool:
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``.
+
+ "Uncertain" is what this must not accept. A part the classifier can NAME as
+ an APU is not uncertain, whichever way the classifier's own answer went: on
+ Windows the backend is PAL, and paldevice.cpp adds the WDDM shared heap to
+ globalMemSize_ for any ``Pal::GpuType::Integrated`` part, which is a property
+ of the DEVICE and not of whether HIP filled in the props struct's integrated
+ field. So a gfx1103 Phoenix on a pre-6.2 runtime already carries a
+ pool-scoped total, and answering False here pairs that pool with Dedicated
+ Usage alone, which plateaus at the BIOS carve-out. Measured shape: 17.0 GB
+ total, 8 GiB resident, published as 1.90 used and 15.10 free.
+
"""
if not IS_ROCM:
return False
@@ -1465,18 +1495,53 @@ def _rocm_props_are_positively_unified(props: Any) -> bool:
return False
+def _rocm_props_are_an_unnamed_apu(props: Any) -> bool:
+ """True for an APU arch the shared classifier's positive set omits.
+
+ Only ever asked of a LONE visible device, and only to settle the numerator.
+ Beside a discrete card the same chip's props.total_memory is the one number
+ this module cannot scope -- #9198 keeps a hybrid iGPU on its carve-out for
+ exactly that reason, and the Dedicated+Shared sum needs a single adapter
+ above the noise floor to be attributable in the first place, so upgrading
+ there could only take a reading away. On a lone APU neither applies.
+
+ Indexed rather than unpacked so a classifier that grows its tuple (#9198)
+ keeps working.
+ """
+ if not IS_ROCM:
+ return False
+ try:
+ from core.training.worker import _rocm_classify_unified_memory
+ arch = str(_rocm_classify_unified_memory(props)[0] or "")
+ except Exception as e:
+ logger.debug("ROCm unified-memory classification failed: %s", e)
+ return False
+ return arch.split(":")[0].strip().lower() in _ROCM_UNNAMED_APU_ARCHES
+
+
def _rocm_props_total_is_carve_out(props: Any) -> bool:
"""True when ``props.total_memory`` may understate what torch can actually use.
- On a unified-memory ROCm APU the two totals are NOT the same number:
- ``props.total_memory`` is the dedicated carve-out while ``hipMemGetInfo``'s
- total spans the GTT pool, which is the figure the rest of this module treats
- as authoritative (_apply_unified_memory_correction adopts it over amd-smi's
- for exactly this reason). Reporting the carve-out would undo that correction
- and budget a 128 GiB Strix Halo as ~8 GiB. There is no context-free source for
- the GTT total, so only APUs pay mem_get_info; every discrete device keeps the
- free inventory. Same classifier the training worker and the llama.cpp backend
- use, so all three agree on what an APU is.
+ On some stacks ``props.total_memory`` is the dedicated carve-out while
+ ``hipMemGetInfo``'s total spans the GTT pool. MAY, not does: measured on a
+ Windows gfx1151 (driver 32.0.21041.1000, torch 2.11.0+rocm7.13.0) the two
+ agree at 89.47 GB against a 32 GB BIOS carve-out, and on a Linux gfx1151 they
+ agree at 64 GB, so on both APUs tested props.total_memory already spans the
+ pool and this returning True buys nothing. Callers must therefore compare the
+ two and adopt only a larger driver total, never adopt it outright.
+
+ The gap this module DOES have provenance for is a different pair:
+ _apply_unified_memory_correction adopts torch's total over amd-smi's, because
+ amd-smi reports the carve-out. That is torch against amd-smi, not
+ props.total_memory against hipMemGetInfo, and it is not evidence for this one.
+ A stack where these two disagree is inferred from reports of an understated
+ total, not yet reproduced; #8862 and #7449 are about used VRAM reading
+ Unknown, which is a different fault.
+
+ There is no context-free source for the GTT total, so only APUs pay
+ mem_get_info; every discrete device keeps the free inventory. Same classifier
+ the training worker and the llama.cpp backend use, so all three agree on what
+ an APU is.
"Not unified" is not the same answer as "discrete". That classifier knows an APU
by the driver's integrated flag or by a hardcoded arch set, so a gfx1103 Phoenix
@@ -1527,13 +1592,17 @@ def _torch_get_device_inventory(device_indices: list[int]) -> list[Dict[str, Any
# torch ordinals are 0-based relative to CUDA_VISIBLE_DEVICES.
props = mod.get_device_properties(ordinal)
total_bytes = props.total_memory
- if _rocm_props_total_is_carve_out(props) and hasattr(mod, "mem_get_info"):
- try:
- total_bytes = mod.mem_get_info(ordinal)[1]
- except Exception as e:
- # Keep the carve-out rather than dropping the device: an
- # understated total still beats no device at all.
- logger.debug("ROCm APU driver total failed for ordinal %d: %s", ordinal, e)
+ try:
+ if _rocm_props_total_is_carve_out(props) and hasattr(mod, "mem_get_info"):
+ # Only a WIDER total, same as _rocm_windows_per_device_vram.
+ # The classifier fails open, so a discrete card reaches here
+ # too, and a total below props.total_memory would hide models
+ # this device can hold.
+ total_bytes = max(int(mod.mem_get_info(ordinal)[1]), int(total_bytes))
+ except Exception as e:
+ # Keep the carve-out rather than dropping the device: an
+ # understated total still beats no device at all.
+ logger.debug("ROCm APU driver total failed for ordinal %d: %s", ordinal, e)
devices.append(
{
"index": phys_idx,
@@ -2393,6 +2462,12 @@ def _match_adapter_used_to_devices(
counters number EXACTLY the visible devices AND capacity forces the mapping;
otherwise every device is unknown. Best-effort but correct for the common
loaded-card case (#7072). Returns a list aligned to ``device_totals``.
+
+ ``device_totals`` must be the DEDICATED capacity each counter can fill, never a
+ unified-memory total. A widened total reranks its device, raises the threshold
+ that forces a pairing, and lifts the ceiling below which a usage is judged
+ impossible, which costs other devices their readings and admits counters that
+ belong to no visible card.
"""
n = len(device_totals)
if n == 0:
@@ -2477,7 +2552,9 @@ def _rocm_windows_aggregate_used_bytes(
the visible set therefore holds those cards and nothing else. It fails closed if
that is wrong: a second instance for one adapter makes the list longer than the
visible set, which returns None rather than a total. Verify it before widening
- this, not before trusting it.
+ this, not before trusting it. ``device_totals`` carries the same requirement as
+ _match_adapter_used_to_devices: dedicated capacity, never a unified total, or
+ the check above stops rejecting usages no visible card could hold.
Deliberately NOT the noise filter _match_adapter_used_to_devices uses. Dropping
sub-threshold counters and summing the rest is safe for per-device attribution,
@@ -2511,7 +2588,9 @@ def _rocm_windows_aggregate_used_bytes(
return float(sum(useds))
-def _rocm_windows_unified_used_bytes() -> Optional[float]:
+def _rocm_windows_unified_used_bytes(
+ dedicated: Optional[list[tuple[str, float]]] = None,
+) -> 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
@@ -2536,8 +2615,13 @@ def _rocm_windows_unified_used_bytes() -> Optional[float]:
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`` lets a caller that already holds a Dedicated Usage snapshot
+ hand it over: each query is an out-of-process PowerShell call, and re-sampling
+ would also answer from a different instant than the caller's own attribution.
"""
- dedicated = _rocm_windows_perf_counter_vram_by_adapter()
+ if dedicated is None:
+ dedicated = _rocm_windows_perf_counter_vram_by_adapter()
if not dedicated:
return None
candidates = [
@@ -2558,21 +2642,34 @@ def _rocm_windows_unified_used_bytes() -> Optional[float]:
if shared is None:
return None
shared_used = next((used for name, used in shared if name == instance), 0.0)
+ # A negative cooked counter is a broken reading, not low usage. The caller
+ # clamps the upper bound only, and the payload derives free as total minus
+ # used, so a negative sum publishes negative used and a free above total.
+ # Decline for the same reason a failed Shared query declines: nothing here
+ # can tell how much of the reading is wrong.
+ if dedicated_used < 0.0 or shared_used < 0.0:
+ return None
return dedicated_used + shared_used
def _rocm_windows_per_device_vram(
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.
+ """Per-GPU VRAM on Windows AMD/ROCm: total from torch properties, widened to
+ the driver pool on a unified APU, used from the per-adapter Dedicated Usage
+ counter.
Returns ``([{index, visible_ordinal, name, used_gb, total_gb}], aggregate_gb)``
- per visible GPU (``used_gb`` is ``None`` when the counter is unavailable or the
- pairing is not capacity-forced), or ``([], None)`` when torch can't enumerate
- devices so callers fall through to the torch last resort. ``aggregate_gb`` is the
- visible set's total used VRAM, which survives a pairing no single device can
- claim (#7452), and ``None`` when even that is not established.
+ per visible GPU, or ``([], None)`` when torch can't enumerate devices so callers
+ fall through to the torch last resort. ``aggregate_gb`` is the visible set's
+ total used VRAM, which survives a pairing no single device can claim (#7452),
+ and ``None`` when even that is not established.
+
+ ``used_gb`` is ``None`` when the counter is unavailable, when the pairing is not
+ capacity-forced, or when this device's total was widened to the unified pool --
+ that counter measures the dedicated segment, so it is not a numerator for a
+ total spanning the shared one. The two totals are kept apart internally for the
+ same reason: the counters are ranked against the carve-out, never the pool.
"""
if platform.system() != "Windows":
return [], None
@@ -2584,14 +2681,124 @@ def _rocm_windows_per_device_vram(
for ordinal, phys_idx in enumerate(device_indices):
try:
props = mod.get_device_properties(ordinal)
+ total_bytes = int(props.total_memory)
+ # What the Dedicated Usage counters are RANKED against, which is not
+ # what is shown to the user: that counter measures the dedicated
+ # segment, so the carve-out is its ceiling and the pool is not.
+ # Ranking against a widened total puts a 2 GiB APU reading above a
+ # 10 GiB discrete one and admits a counter no visible card can hold.
+ dedicated_bytes = total_bytes
+ # On a unified-memory APU props.total_memory CAN be the dedicated
+ # carve-out rather than what torch can use; same correction, and the
+ # same APU-only price for a context, as _torch_get_device_inventory.
+ # Measured on a Windows gfx1151, driver 32.0.21041.1000 with torch
+ # 2.11.0+rocm7.13.0, props.total_memory already spans the GTT pool
+ # (89.47 GB against a 32 GB BIOS carve-out), so the split is a
+ # property of some stacks and not of Windows. Hence the comparison
+ # below rather than an unconditional adopt: this has to be inert
+ # where the two agree. The free half of the reading is the untrusted
+ # one either way, the total is fine.
+ total_is_pool = False
+ # Whether the driver CONFIRMED this total reaches the pool, as opposed
+ # to it merely not having been widened. A probe that fails leaves a
+ # carve-out-sized total standing, and a unified part is exactly where
+ # that is possible, so the two are not the same question.
+ pool_confirmed = False
+ # POSITIVELY unified, not _rocm_props_total_is_carve_out, and this is
+ # the gate on the probe rather than only on what the probe's answer is
+ # used for. mem_get_info attaches a primary HIP context worth ~612 MiB
+ # that is never released, main reaches this function without ever
+ # calling it, and the carve-out classifier deliberately fails open for
+ # an unclassified DISCRETE card. Gating on it would therefore have made
+ # a telemetry poll take 612 MiB off every discrete GPU on the host, to
+ # obtain a total that is then not used for anything: only a positively
+ # unified part takes the widened total or the unified numerator.
+ unified = False
+ try:
+ # Inside the try with the probe it gates: both are probes, and a
+ # probe that throws must cost this device its correction, not its
+ # place in the list.
+ unified = _rocm_props_are_positively_unified(props)
+ if not unified and len(device_indices) == 1:
+ # The classifier names an APU from hipDeviceProp_t::integrated
+ # or from the shared-pool arch set that sizes the memory-fraction
+ # cap. A gfx1103 Phoenix on a pre-6.2 runtime is in neither, and
+ # PAL does not consult either: it adds the WDDM shared heap to
+ # globalMemSize_ for any Pal::GpuType::Integrated part, which is
+ # a fact about the DEVICE. So that part reaches here with a
+ # pool-scoped total and, unpatched, the Dedicated-only numerator
+ # that plateaus at the BIOS carve-out -- the same overstated-free
+ # reading on a device the classifier misses. Reported shape: a
+ # Windows 780M on 24295 MiB of RAM reads a 17303 MiB total
+ # (ComfyUI-Zluda#387), which is an 8 GiB carve-out plus 75% of
+ # the WDDM shared heap. Hold 12 GiB there and Dedicated is 7.90,
+ # so free publishes as 9.00 with 12 GiB resident.
+ unified = _rocm_props_are_an_unnamed_apu(props)
+ if unified and hasattr(mod, "mem_get_info"):
+ pool_bytes = int(mod.mem_get_info(ordinal)[1])
+ # >= not >, and the equal case is the ONLY one that occurs.
+ # hipMemGetInfo's total and hipDeviceProp_t::totalGlobalMem
+ # are both device->info().globalMemSize_ in clr (hip_memory.cpp,
+ # hip_device.cpp); only `free` is sourced separately. So these
+ # two numbers are the same variable read twice and can never
+ # differ on an AMD backend.
+ #
+ # That makes this look like a tautology, and taken alone it is.
+ # What carries it is the conjunction at pool_scoped below:
+ # on Windows the backend is PAL, and paldevice.cpp adds 50-75%
+ # of the WDDM shared heap to globalMemSize_ whenever
+ # settings().apuSystem_, which is Pal::GpuType::Integrated --
+ # the same flag that fills hipDeviceProp_t::integrated and so
+ # the same one _rocm_classify_unified_memory gates on. A part
+ # this classifier calls unified therefore HAS a pool-scoped
+ # total by construction, which is the proof the equality alone
+ # does not supply. Measured twice: 89.465 GB under a 32 GB
+ # carve-out here, and 107.87 GB under a 96 GB VGM in
+ # ROCm/TheRock#3032, matching the PAL formula exactly.
+ #
+ # Linux is the opposite regime -- globalMemSize_ is the KFD
+ # framebuffer heap and CAN be carve-out sized -- but this
+ # function returns ([], None) off Windows, so it never applies.
+ pool_confirmed = pool_bytes >= total_bytes
+ # Kept for the shrink guard, not because widening is reachable:
+ # per the above, pool_bytes > total_bytes cannot hold on AMD.
+ # The classifier says carve-out for a discrete card on an
+ # unsettled runtime too, and unlike the inventory this path
+ # carries a used: a shrunk total reports past 100% utilization
+ # and zero free.
+ if pool_bytes > total_bytes:
+ logger.debug(
+ "ROCm unified memory: ordinal %d total %.2f -> %.2f GB (driver pool)",
+ ordinal,
+ total_bytes / (1024**3),
+ pool_bytes / (1024**3),
+ )
+ total_bytes = pool_bytes
+ total_is_pool = True
+ except Exception as e:
+ logger.debug("ROCm APU driver total failed for ordinal %d: %s", ordinal, e)
dev_meta.append(
{
"index": phys_idx,
"visible_ordinal": ordinal,
"name": props.name,
- # Second join key for _match_adapter_used_by_luid, unused elsewhere.
+ "total_bytes": total_bytes,
+ "dedicated_bytes": dedicated_bytes,
+ # Second join key for _match_adapter_used_by_luid (#8863).
"gfx": str(getattr(props, "gcnArchName", "") or ""),
- "total_bytes": int(props.total_memory),
+ "total_is_pool": total_is_pool,
+ # Whether Shared Usage belongs in this device's numerator is
+ # a question about the PART, not about whether this call
+ # happened to widen anything. On the measured gfx1151 the two
+ # totals already agree, so total_is_pool stays false while the
+ # total is pool-scoped all the same, and Dedicated alone would
+ # be paired with it. It is also the stricter question:
+ # _rocm_props_total_is_carve_out fails open, so a discrete
+ # card can widen, and shared bytes are host memory its
+ # props.total_memory never counted. Same test
+ # get_gpu_memory_info applies before summing the two counters.
+ "positively_unified": unified,
+ "pool_confirmed": pool_confirmed,
}
)
except Exception as e:
@@ -2623,6 +2830,70 @@ def _rocm_windows_per_device_vram(
# Counter unavailable: show every GPU with a correct total, used unknown.
assigned = [None] * len(dev_meta)
+ # A pool-scoped total needs a numerator that spans the same ground. Dedicated
+ # Usage does not: it saturates at the carve-out and is wrong past it, so
+ # pairing it with the pool total would report a loaded card as mostly free,
+ # and the caller derives free as total minus used.
+ # _rocm_windows_unified_used_bytes sums Dedicated and Shared for exactly this
+ # (#9362 measured the plateau at ~30.5 GiB on a gfx1151 and the overflow
+ # landing in Shared). A decline still has to null the reading rather than
+ # leave the carve-out figure standing under a pool-sized total.
+ #
+ # Pool-scoped covers both ways to get there: a total this call widened, and a
+ # confirmed APU whose props.total_memory already spanned the pool, which is
+ # what the measured gfx1151 does. Keying on the widening alone would leave
+ # that host, the one this PR is about, on the plateaued counter. Being a UMA
+ # part is not enough by itself though: it says what the device is, not what
+ # scope the retained total has, and an APU whose driver probe failed still
+ # carries a carve-out-sized one that Dedicated Usage is the right numerator
+ # for. Hence pool_confirmed.
+ pool_scoped = [
+ m["total_is_pool"] or (m["positively_unified"] and m["pool_confirmed"]) for m in dev_meta
+ ]
+ if any(pool_scoped):
+ only = dev_meta[0] if len(dev_meta) == 1 else None
+ # Two conditions beyond "this device wants the sum", both of which the
+ # matcher applies to its own readings and the unified helper does not:
+ #
+ # adapters falsy the Dedicated query already failed. Passing None
+ # reads as "no snapshot supplied" and pays for the
+ # same failing PowerShell call a second time, on a
+ # path that polls, only to return unknown anyway.
+ # a NON-ZERO sub-threshold row
+ # the helper picks the lone counter above the noise
+ # floor, which on a masked host can be a hidden GPU
+ # while the visible APU is the small one; its usage
+ # would then be published as the APU's. The matcher
+ # declines exactly this shape, requiring every dropped
+ # counter to be an EXACT zero, so the same rule holds
+ # here. An adapter at zero has nothing committed and
+ # cannot be the holder of the survivor's bytes.
+ wants_sum = only is not None and pool_scoped[0] and only["positively_unified"]
+ placeholders_only = bool(adapters) and all(
+ used == 0 for _, used in adapters if used < _ROCM_WIN_ADAPTER_MIN_BYTES
+ )
+ unified_used = (
+ _rocm_windows_unified_used_bytes(adapters) if wants_sum and placeholders_only else None
+ )
+ if unified_used is not None:
+ # Every other reading is clamped on its way through the matcher.
+ # This one bypasses it, and the payload derives free as total minus
+ # used, so an unclamped sum publishes negative free. The lower bound
+ # is belt and braces: the helper already declines a negative reading
+ # at source, and this keeps the guarantee local to the consumer that
+ # publishes the number.
+ unified_used = max(0.0, min(unified_used, float(only["total_bytes"])))
+ assigned = [
+ (unified_used if scoped else used) for scoped, used in zip(pool_scoped, assigned)
+ ]
+ # The aggregate is the visible set's exact total, so it survives only
+ # when every pool-scoped member got a figure.
+ aggregate_gb = (
+ round(unified_used / (1024**3), 2)
+ if unified_used is not None and len(dev_meta) == 1
+ else None
+ )
+
devices: list[Dict[str, Any]] = []
for meta, used_bytes in zip(dev_meta, assigned):
total_gb = round(meta["total_bytes"] / (1024**3), 2)