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.

fix(amd): report AMD VRAM on Windows by joining the adapter counters on LUID (#8863)

Leo Borcherdinge79354e9ec02
diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.py
index 2d4220ead3d..1bc3ee0b64b 100644
--- a/studio/backend/tests/test_rocm_windows_vram_7072.py
+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py
@@ -19,6 +19,9 @@ The fix reads the per-adapter (LUID-instanced) Dedicated Usage performance
counter -- Task Manager's source -- for per-GPU used, takes per-GPU total from
torch device properties, and guards the free==total mem_get_info quirk. CI has no
AMD GPU/Windows, so torch, the performance counter, and platform are all mocked.
+
+The last section covers the DirectX LUID join layered on top of that counter,
+which resolves the single-GPU host capacity ranking alone can never attribute.
"""
from __future__ import annotations
@@ -44,20 +47,21 @@ def _fake_torch(
free_equals_total = False,
used_per_device = None,
):
- """Build a fake `torch` module. devices: list of (name, total_bytes)."""
+ """Build a fake `torch` module. devices: list of (name, total_bytes[, gfx])."""
dev = list(devices)
class _Props:
- def __init__(self, name, total):
+ def __init__(self, name, total, gfx):
self.name = name
self.total_memory = total
+ self.gcnArchName = gfx
def get_device_properties(i):
- name, total = dev[i]
- return _Props(name, total)
+ name, total, *arch = dev[i]
+ return _Props(name, total, arch[0] if arch else "")
def mem_get_info(i):
- _, total = dev[i]
+ total = dev[i][1]
if free_equals_total:
return (total, total)
used = used_per_device[i] if used_per_device is not None else 0
@@ -106,6 +110,10 @@ def win_rocm(monkeypatch):
monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
monkeypatch.setattr(hw.sys, "platform", "win32")
monkeypatch.setattr(hw, "_smi_query", lambda *a, **k: None) # amd-smi disabled
+ # Capacity-ranking path by default: without this a Windows dev box reads its
+ # own registry here and the LUID join answers instead. The LUID tests below
+ # opt in with their own map.
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: {})
# Visible set via HIP mask so we don't shell out to amd-smi for the count.
monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0,1")
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
@@ -411,6 +419,456 @@ def test_perf_counter_parser_and_sentinel(monkeypatch):
assert hw._rocm_windows_perf_counter_vram_by_adapter() is None
+# ----------------------------------------------------------------------------- #
+# DirectX LUID join
+#
+# Capacity ranking only emits a value a pairing FORCES, and one visible GPU
+# forces nothing -- there is no smaller card for its usage to exceed -- so every
+# single-GPU AMD Windows host read Unknown, the common case. The counters name
+# each instance after the adapter LUID and DirectX records the same LUID with
+# torch's props.name and gcnArchName, so they join on identity instead.
+# ----------------------------------------------------------------------------- #
+SOLO_DEVICE = [("AMD Radeon RX 9060 XT", 16 * GB, "gfx1200")]
+# One dGPU at 3 GiB beside the Basic Render Driver and a second idle placeholder:
+# three counters for one visible card, straight off the reporting host.
+SOLO_ADAPTERS = [
+ ("luid_0x00000000_0x00015369_phys_0", 3 * GB),
+ ("luid_0x00000000_0x000183fe_phys_0", 0.0),
+ ("luid_0x00000000_0x0001842f_phys_0", 0.0),
+]
+SOLO_REGISTRY = {0x15369: {"name": "AMD Radeon RX 9060 XT", "gfx": "gfx1200"}}
+
+
+def win_rocm_solo(win_rocm, monkeypatch):
+ """Windows ROCm host with a single visible GPU and a readable DirectX map."""
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(SOLO_DEVICE, free_equals_total = True))
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(SOLO_ADAPTERS))
+ )
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: dict(SOLO_REGISTRY))
+ return monkeypatch
+
+
+def test_parse_adapter_luid():
+ # DirectX stores one 64-bit AdapterLuid; the counter names it as two halves.
+ assert hw._parse_adapter_luid("luid_0x00000000_0x00015369_phys_0") == 0x15369
+ assert hw._parse_adapter_luid("luid_0x0000000A_0x00015369_phys_0") == (0xA << 32) | 0x15369
+ assert hw._parse_adapter_luid("LUID_0X00000000_0X00015369_PHYS_0") == 0x15369
+ assert hw._parse_adapter_luid("Total") is None
+ assert hw._parse_adapter_luid("luid_zz_0x1_phys_0") is None
+
+
+def test_normalize_adapter_name():
+ # The two sides spell one card differently; only the marks and spacing move.
+ assert hw._normalize_adapter_name("AMD Radeon(TM) 780M Graphics") == hw._normalize_adapter_name(
+ "AMD Radeon 780M Graphics"
+ )
+ assert hw._normalize_adapter_name("AMD Radeon™ RX 9070") == hw._normalize_adapter_name(
+ "amd radeon rx 9070"
+ )
+ # Two models stay two models.
+ assert hw._normalize_adapter_name("AMD Radeon RX 9070") != hw._normalize_adapter_name(
+ "AMD Radeon RX 9070 XT"
+ )
+
+
+def test_parse_adapter_family_gfx():
+ # The driver writes the family, torch the target plus its feature suffixes.
+ assert hw._parse_adapter_family_gfx("AMD_NAVI44:gfx1200") == "gfx1200"
+ assert hw._parse_adapter_family_gfx("gfx1201:sramecc-:xnack-") == "gfx1201"
+ assert hw._parse_adapter_family_gfx("GFX1103") == "gfx1103"
+ assert hw._parse_adapter_family_gfx("AMD_NAVI44") == ""
+ assert hw._parse_adapter_family_gfx("") == ""
+
+
+def test_single_gpu_reports_used_instead_of_unknown(win_rocm_solo):
+ """The regression: one visible GPU plus placeholder counters read Unknown."""
+ result = hw.get_visible_gpu_utilization()
+ (device,) = result["devices"]
+ assert device["vram_used_gb"] == pytest.approx(3.0, abs = 0.01)
+ assert device["vram_total_gb"] == 16.0
+ assert device["vram_utilization_pct"] == pytest.approx(18.8, abs = 0.1)
+ # The System tab tile reads the aggregate, which needed len(counters) == 1.
+ assert result["vram_used_gb_aggregate"] == pytest.approx(3.0, abs = 0.01)
+
+
+def test_single_gpu_train_page_reports_used(win_rocm_solo):
+ """Same figure on get_gpu_utilization, the Train page's GPU Monitor."""
+ (device,) = hw.get_gpu_utilization()["devices"]
+ assert device["vram_used_gb"] == pytest.approx(3.0, abs = 0.01)
+ assert device["gpu_utilization_pct"] == 12.0 # 3D-engine counter, unchanged
+
+
+def test_luid_join_beats_a_busy_foreign_adapter(win_rocm, monkeypatch):
+ """An idle AMD card beside a busy foreign GPU reports the AMD card's own
+ usage. Capacity ranking has no vendor key here and declines outright."""
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(SOLO_DEVICE, free_equals_total = True))
+ adapters = [
+ ("luid_0x00000000_0x00015369_phys_0", 0.4 * GB), # visible AMD card, idle
+ ("luid_0x00000000_0x00099999_phys_0", 9 * GB), # NVIDIA/iGPU, not ours
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: dict(SOLO_REGISTRY))
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["used_gb"] == pytest.approx(0.4, abs = 0.01)
+ assert aggregate == pytest.approx(0.4, abs = 0.01)
+
+
+def test_identical_cards_keep_aggregate_but_not_per_device(win_rocm, monkeypatch):
+ """Two of the same card share one Description AND one arch, so nothing says
+ which counter is which ordinal. The sum does not depend on the pairing."""
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch([("AMD Radeon RX 7900 XTX", 24 * GB, "gfx1100")] * 2, free_equals_total = True),
+ )
+ adapters = [
+ ("luid_0x00000000_0x0000aaaa_phys_0", 10 * GB),
+ ("luid_0x00000000_0x0000bbbb_phys_0", 4 * GB),
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+ record = {"name": "AMD Radeon RX 7900 XTX", "gfx": "gfx1100"}
+ monkeypatch.setattr(
+ hw, "_windows_amd_adapter_records_by_luid", lambda: {0xAAAA: record, 0xBBBB: record}
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["used_gb"] for d in devices] == [None, None]
+ assert aggregate == pytest.approx(14.0, abs = 0.01)
+
+
+# ── The mixed hosts nobody here owns hardware for ────────────────────────────
+IGPU_DGPU_DEVICES = [
+ ("AMD Radeon(TM) 780M Graphics", 2 * GB, "gfx1103"),
+ ("AMD Radeon RX 9070 XT", 16 * GB, "gfx1201"),
+]
+IGPU_DGPU_ADAPTERS = [
+ ("luid_0x00000000_0x0000c001_phys_0", 0.5 * GB), # iGPU, driving the display
+ ("luid_0x00000000_0x0000d002_phys_0", 1.2 * GB), # dGPU, small model loaded
+]
+
+
+def test_igpu_and_dgpu_each_report_their_own(win_rocm, monkeypatch):
+ """Both visible: two different cards, two counters, and identity says which
+ is which. Capacity ranking cannot: the dGPU's 1.2 GiB would also fit the
+ 2 GiB iGPU, so the two are swappable and it reports both unknown."""
+ monkeypatch.setitem(
+ sys.modules, "torch", _fake_torch(IGPU_DGPU_DEVICES, free_equals_total = True)
+ )
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(IGPU_DGPU_ADAPTERS))
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xC001: {"name": "AMD Radeon(TM) 780M Graphics", "gfx": "gfx1103"},
+ 0xD002: {"name": "AMD Radeon RX 9070 XT", "gfx": "gfx1201"},
+ },
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["used_gb"] for d in devices] == [
+ pytest.approx(0.5, abs = 0.01),
+ pytest.approx(1.2, abs = 0.01),
+ ]
+ assert aggregate == pytest.approx(1.7, abs = 0.01)
+
+
+def test_a_name_the_two_sides_spell_differently_still_joins(win_rocm, monkeypatch):
+ """DirectX takes the Description from the driver INF and HIP from the ASIC
+ record, so an iGPU reaches the join under two spellings of one card."""
+ monkeypatch.setitem(
+ sys.modules, "torch", _fake_torch(IGPU_DGPU_DEVICES, free_equals_total = True)
+ )
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(IGPU_DGPU_ADAPTERS))
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xC001: {"name": "AMD Radeon 780M Graphics", "gfx": "gfx1103"}, # no (TM)
+ 0xD002: {"name": "AMD Radeon(R) RX 9070 XT", "gfx": "gfx1201"}, # (R), not (TM)
+ },
+ )
+
+ devices, _ = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["used_gb"] for d in devices] == [
+ pytest.approx(0.5, abs = 0.01),
+ pytest.approx(1.2, abs = 0.01),
+ ]
+
+
+def test_the_arch_answers_when_the_names_do_not(win_rocm, monkeypatch):
+ """A generic iGPU Description that normalizing cannot reconcile. The gfx
+ target both sides carry separates an iGPU from the dGPU beside it."""
+ monkeypatch.setitem(
+ sys.modules, "torch", _fake_torch(IGPU_DGPU_DEVICES, free_equals_total = True)
+ )
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(IGPU_DGPU_ADAPTERS))
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xC001: {"name": "AMD Radeon(TM) Graphics", "gfx": "gfx1103"},
+ 0xD002: {"name": "Radeon RX 9070 XT Series", "gfx": "gfx1201"},
+ },
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["used_gb"] for d in devices] == [
+ pytest.approx(0.5, abs = 0.01),
+ pytest.approx(1.2, abs = 0.01),
+ ]
+ assert aggregate == pytest.approx(1.7, abs = 0.01)
+
+
+def test_a_partial_name_pass_still_lets_the_arch_finish_the_job(win_rocm, monkeypatch):
+ """Three cards, one uniquely named and two sharing a name but not an arch.
+
+ The name pass places the unique card and leaves the pair unknown, which is a
+ real result and used to end the search. It should not: the arch separates
+ all three, and the pass that places more devices is the one to keep.
+ """
+ devices_spec = [
+ ("AMD Radeon PRO W7900", 48 * GB, "gfx1100"),
+ ("AMD Radeon RX 9070", 16 * GB, "gfx1201"),
+ ("AMD Radeon RX 9070", 16 * GB, "gfx1200"), # same name, different arch
+ ]
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(devices_spec, free_equals_total = True))
+ adapters = [
+ ("luid_0x00000000_0x0000a001_phys_0", 30.0 * GB),
+ ("luid_0x00000000_0x0000b002_phys_0", 10.0 * GB),
+ ("luid_0x00000000_0x0000c003_phys_0", 5.0 * GB),
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xA001: {"name": "AMD Radeon PRO W7900", "gfx": "gfx1100"},
+ 0xB002: {"name": "AMD Radeon RX 9070", "gfx": "gfx1201"},
+ 0xC003: {"name": "AMD Radeon RX 9070", "gfx": "gfx1200"},
+ },
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1, 2])
+ assert [d["used_gb"] for d in devices] == [
+ pytest.approx(30.0, abs = 0.01),
+ pytest.approx(10.0, abs = 0.01),
+ pytest.approx(5.0, abs = 0.01),
+ ]
+ assert aggregate == pytest.approx(45.0, abs = 0.01)
+
+
+def test_the_arch_pass_needs_every_record_to_have_one(win_rocm, monkeypatch):
+ """A driver too old to write AdapterFamily leaves a record the arch cannot
+ key. Running the pass on the rest would let the adapters that do carry one
+ stand in for the adapter that does not, so it does not run at all."""
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch([("AMD Radeon RX 9070", 16 * GB, "gfx1201")], free_equals_total = True),
+ )
+ adapters = [
+ ("luid_0x00000000_0x0000c001_phys_0", 6 * GB), # the visible card
+ ("luid_0x00000000_0x0000d002_phys_0", 9 * GB), # its hidden same-arch sibling
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+ # Neither Description matches what torch calls the card, so the name pass
+ # declines and only the arch could answer -- and one record has no arch.
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xC001: {"name": "AMD Radeon RX 9070 Series"},
+ 0xD002: {"name": "AMD Radeon RX 9070 Series", "gfx": "gfx1201"},
+ },
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0])
+ assert devices[0]["used_gb"] is None
+ assert aggregate is None
+
+
+def test_luid_join_declines_and_falls_back(win_rocm, monkeypatch):
+ """Every decline hands the counters back to capacity ranking rather than
+ inventing a figure."""
+ dev_meta = [{"name": "AMD Radeon RX 9060 XT", "gfx": "gfx1200", "total_bytes": 16 * GB}]
+ join = hw._match_adapter_used_by_luid
+
+ # No registry at all (non-Windows, missing key, denied read, partial map).
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: {})
+ assert join(SOLO_ADAPTERS, dev_meta) is None
+
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: dict(SOLO_REGISTRY))
+ # A visible card whose adapter has no record: its counter is unidentified.
+ assert (
+ join(
+ SOLO_ADAPTERS,
+ [{"name": "AMD Radeon RX 7800 XT", "gfx": "gfx1101", "total_bytes": 16 * GB}],
+ )
+ is None
+ )
+ # A same-named, same-arch adapter HIP does not enumerate: two counters, one ordinal.
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {**SOLO_REGISTRY, 0x77777: dict(SOLO_REGISTRY[0x15369])},
+ )
+ assert (
+ join(
+ [*SOLO_ADAPTERS, ("luid_0x00000000_0x00077777_phys_0", 2 * GB)],
+ dev_meta,
+ )
+ is None
+ )
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: dict(SOLO_REGISTRY))
+ # A record outliving its hardware: usage above the card's own capacity.
+ assert join([("luid_0x00000000_0x00015369_phys_0", 20 * GB)], dev_meta) is None
+
+
+# ── Reading the registry itself ──────────────────────────────────────────────
+def _fake_winreg(subkeys):
+ """A `winreg` over ``{subkey: {value: data}}``. An Exception in place of a
+ subkey's dict raises on open; one in place of a value raises on read."""
+
+ class _Key:
+ def __init__(self, name):
+ self.name = name
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ names = list(subkeys)
+ mod = types.ModuleType("winreg")
+ mod.HKEY_LOCAL_MACHINE = object()
+
+ def open_key(root, path):
+ if root is mod.HKEY_LOCAL_MACHINE:
+ return _Key("") # the DirectX key itself
+ entry = subkeys[path]
+ if isinstance(entry, Exception):
+ raise entry
+ return _Key(path)
+
+ def query_value_ex(key, value):
+ values = subkeys[key.name]
+ if value not in values:
+ raise FileNotFoundError(2, "value does not exist")
+ data = values[value]
+ if isinstance(data, Exception):
+ raise data
+ return (data, 0)
+
+ mod.OpenKey = open_key
+ mod.QueryInfoKey = lambda key: (len(names), 0, 0)
+ mod.EnumKey = lambda key, index: names[index]
+ mod.QueryValueEx = query_value_ex
+ return mod
+
+
+AMD_RECORD = {
+ "VendorId": 0x1002,
+ "AdapterLuid": 0x14CF5,
+ "Description": "AMD Radeon RX 9060 XT",
+ "AdapterFamily": "AMD_NAVI44:gfx1200",
+}
+BASIC_RENDER_RECORD = {
+ "VendorId": 0x1414,
+ "AdapterLuid": 0x17DEA,
+ "Description": "Microsoft Basic Render Driver",
+}
+
+
+def on_windows(monkeypatch):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ return monkeypatch
+
+
+def test_registry_reads_the_amd_adapters_and_skips_the_rest(on_windows, monkeypatch):
+ # ShaderCache is a real sibling of the adapter records and holds an
+ # AdapterLuid of 0 -- it is not GUID-named, which is what excludes it.
+ monkeypatch.setitem(
+ sys.modules,
+ "winreg",
+ _fake_winreg(
+ {
+ "ShaderCache": {"AdapterLuid": 0},
+ "{aaaaaaaa-0000-0000-0000-000000000000}": BASIC_RENDER_RECORD,
+ "{bbbbbbbb-0000-0000-0000-000000000000}": AMD_RECORD,
+ }
+ ),
+ )
+ assert hw._windows_amd_adapter_records_by_luid() == {
+ 0x14CF5: {"name": "AMD Radeon RX 9060 XT", "gfx": "gfx1200"}
+ }
+
+
+def test_a_record_that_will_not_read_declines_the_whole_map(on_windows, monkeypatch):
+ """A partial map is indistinguishable from a complete one at the join, which
+ would then hand a visible card its hidden twin's counter."""
+ denied = PermissionError(5, "access is denied")
+ for broken in (
+ denied, # the subkey will not open
+ {**AMD_RECORD, "Description": denied}, # an AMD adapter this cannot name
+ {**AMD_RECORD, "Description": ""}, # ...or that names itself nothing
+ {k: v for k, v in AMD_RECORD.items() if k != "AdapterLuid"},
+ {k: v for k, v in AMD_RECORD.items() if k != "VendorId"}, # vendor unknown
+ ):
+ monkeypatch.setitem(
+ sys.modules,
+ "winreg",
+ _fake_winreg(
+ {
+ "{aaaaaaaa-0000-0000-0000-000000000000}": broken,
+ "{bbbbbbbb-0000-0000-0000-000000000000}": AMD_RECORD,
+ }
+ ),
+ )
+ assert hw._windows_amd_adapter_records_by_luid() == {}, broken
+
+
+def test_a_driver_without_adapter_family_still_gives_the_name(on_windows, monkeypatch):
+ monkeypatch.setitem(
+ sys.modules,
+ "winreg",
+ _fake_winreg(
+ {
+ "{bbbbbbbb-0000-0000-0000-000000000000}": {
+ k: v for k, v in AMD_RECORD.items() if k != "AdapterFamily"
+ }
+ }
+ ),
+ )
+ assert hw._windows_amd_adapter_records_by_luid() == {0x14CF5: {"name": "AMD Radeon RX 9060 XT"}}
+
+
+def test_registry_read_is_windows_only(monkeypatch):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")
+ assert hw._windows_amd_adapter_records_by_luid() == {}
+
+
# ----------------------------------------------------------------------------- #
# Unified-memory (Strix Halo APU) total reconciliation (Codex #7238)
# ----------------------------------------------------------------------------- #
@@ -496,3 +954,212 @@ def test_per_device_vram_uses_the_snapshot_it_is_given(monkeypatch):
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)
+
+
+# ----------------------------------------------------------------------------- #
+# The capacity a counter is bounded by
+#
+# Dedicated Usage measures the dedicated segment, so the carve-out is its
+# ceiling. #9314 widens total_bytes to the whole driver pool on a unified APU
+# for DISPLAY, and every capacity comparison here has to keep using the
+# carve-out: against a pool-sized ceiling a counter no visible card could hold
+# still fits, and the join stops declining where it should.
+# ----------------------------------------------------------------------------- #
+def test_counter_capacity_prefers_the_dedicated_total():
+ """dedicated_bytes wins when present, total_bytes when it is not, so this is
+ right both before and after the widening lands."""
+ assert hw._adapter_counter_capacity({"total_bytes": 8 * GB}) == float(8 * GB)
+ assert hw._adapter_counter_capacity(
+ {"total_bytes": 128 * GB, "dedicated_bytes": 8 * GB}
+ ) == float(8 * GB)
+
+
+def test_the_luid_join_bounds_counters_by_the_carve_out_not_the_pool():
+ """An impossible counter must still be impossible after the total widens.
+ 9 GiB fits no 8 GiB carve-out, so the join has to decline; ranked against a
+ 128 GiB pool it fits and would be published on a card that never held it."""
+ dev_meta = [
+ {
+ "name": "AMD Radeon(TM) 8060S Graphics",
+ "total_bytes": 128 * GB,
+ "dedicated_bytes": 8 * GB,
+ }
+ ]
+ matched = hw._attribute_adapter_useds_by_key({"k": [9.0 * GB]}, {"k": [0]}, dev_meta)
+ assert matched is None
+
+ # Same device, a usage that does fit the carve-out: attributed normally.
+ matched = hw._attribute_adapter_useds_by_key({"k": [2.0 * GB]}, {"k": [0]}, dev_meta)
+ assert matched is not None
+ assigned, aggregate = matched
+ assert assigned[0] == pytest.approx(2.0 * GB)
+ assert aggregate == pytest.approx(2.0 * GB)
+
+
+# ----------------------------------------------------------------------------- #
+# The join must not stop at a pass that answered nothing, or place bytes it
+# cannot account for
+# ----------------------------------------------------------------------------- #
+def test_a_name_collision_falls_through_to_the_gfx_pass(win_rocm, monkeypatch):
+ """Two cards sharing one Description but differing in arch. The name pass
+ succeeds by cardinality yet names neither device, and returning there would
+ keep both unknown when gfx separates them."""
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch(
+ [
+ ("AMD Radeon Graphics", 24 * GB, "gfx1100"),
+ ("AMD Radeon Graphics", 16 * GB, "gfx1200"),
+ ],
+ free_equals_total = True,
+ ),
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xAAAA: {"name": "AMD Radeon Graphics", "gfx": "gfx1100"},
+ 0xBBBB: {"name": "AMD Radeon Graphics", "gfx": "gfx1200"},
+ },
+ )
+ monkeypatch.setattr(
+ hw.subprocess,
+ "run",
+ _subprocess_run(
+ adapter_output = _adapter_output(
+ [
+ ("luid_0x00000000_0x0000aaaa_phys_0", 9.0 * GB),
+ ("luid_0x00000000_0x0000bbbb_phys_0", 3.0 * GB),
+ ]
+ )
+ ),
+ )
+
+ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
+ assert [d["used_gb"] for d in devices] == [9.0, 3.0]
+ assert aggregate == 12.0
+
+
+def test_the_measured_strix_halo_registry(win_rocm, monkeypatch):
+ """The one real Windows AMD reading taken so far, pinned.
+
+ Windows 11 Pro 26200, AMD Radeon(TM) 8060S Graphics, driver 32.0.21041.1000.
+ Two things it establishes that no CI machine could: AdapterLuid comes back as
+ an Int64 rather than the bytes a REG_BINARY would give, so int() is a no-op;
+ and that driver writes no AdapterFamily at all, so the gfx pass is skipped
+ and the NAME pass is what carries the join. DirectX and props.name agreed
+ exactly there, which is why it lands.
+
+ The counter set is also not a subset of the DirectX key: instance 94361 has
+ 1.273 GB shared and no adapter record at all, so anything assuming every
+ instance resolves to a record would be wrong.
+ """
+ records = {86826: {"name": "AMD Radeon(TM) 8060S Graphics"}} # no "gfx" key
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: records)
+ adapters = [
+ ("luid_0x00000000_0x00017099_phys_0", 0.0), # no registry record
+ ("luid_0x00000000_0x0001532a_phys_0", 0.947 * GB), # the AMD adapter
+ ("luid_0x00000000_0x00017034_phys_0", 0.0), # Basic Render Driver
+ ]
+ dev_meta = [
+ {
+ "name": "AMD Radeon(TM) 8060S Graphics",
+ "gfx": "gfx1151",
+ "total_bytes": int(89.465 * GB),
+ "dedicated_bytes": int(89.465 * GB),
+ }
+ ]
+
+ result = hw._match_adapter_used_by_luid(adapters, dev_meta)
+ assert result is not None, "the join declined on the one real reading we have"
+ per_device, aggregate = result
+ assert round(per_device[0] / GB, 3) == 0.947
+ assert round(aggregate / GB, 3) == 0.947
+
+
+def test_the_measured_strix_halo_needs_the_join_for_any_aggregate(win_rocm, monkeypatch):
+ """Measured on the Windows gfx1151 while it held a model: THREE counter
+ instances for ONE visible GPU.
+
+ The AMD adapter plus two placeholders that never go away. So on this host the
+ counter list is never as long as the visible set, the cardinality gate in
+ ``_rocm_windows_aggregate_used_bytes`` fails closed permanently, and capacity
+ ranking can never supply an aggregate no matter what is loaded. The LUID join
+ is not a second opinion here, it is the only path to a figure at all.
+
+ 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.
+ """
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch(
+ [("AMD Radeon(TM) 8060S Graphics", int(89.465 * GB), "gfx1151")],
+ free_equals_total = True,
+ ),
+ )
+ adapters = [
+ ("luid_0x00000000_0x0001532a_phys_0", 31.681 * GB), # the AMD adapter
+ ("luid_0x00000000_0x00017034_phys_0", 0.0), # placeholder, permanent
+ ("luid_0x00000000_0x00017099_phys_0", 0.0), # placeholder, permanent
+ ]
+ monkeypatch.setattr(
+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {86826: {"name": "AMD Radeon(TM) 8060S Graphics"}}, # no AdapterFamily
+ )
+
+ 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)
+
+ # 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])
+ assert (
+ fallback_aggregate is None
+ ), "capacity ranking produced an aggregate the measured host cannot give it"
+
+
+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
+ visible card's own record is spelled differently. The visible device's
+ counter sits under a key no device claims, so pairing the remaining one would
+ report the hidden card's bytes as the visible card's."""
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch([("AMD Radeon RX 7900 XTX", 24 * GB)], free_equals_total = True),
+ )
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0xAAAA: {
+ "name": "AMD Radeon RX 7900 XTX 24GB"
+ }, # the visible card, spelled differently
+ 0xBBBB: {"name": "AMD Radeon RX 7900 XTX"}, # a hidden card wearing the torch name
+ },
+ )
+ monkeypatch.setattr(
+ hw.subprocess,
+ "run",
+ _subprocess_run(
+ adapter_output = _adapter_output(
+ [
+ ("luid_0x00000000_0x0000aaaa_phys_0", 2.0 * GB),
+ ("luid_0x00000000_0x0000bbbb_phys_0", 17.0 * GB),
+ ]
+ )
+ ),
+ )
+
+ 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
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 619efbc927c..288b8a4e263 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -2132,6 +2132,252 @@ def _rocm_windows_perf_counter_vram_by_adapter(
return None
+# DirectX writes one record per adapter here, keyed by a GUID, holding the same
+# AdapterLuid the counter instances are named after alongside the Description
+# string torch reports as props.name and the gfx target it reports as
+# gcnArchName. Those are the join keys capacity ranking lacks.
+_WINDOWS_DIRECTX_KEY = r"SOFTWARE\Microsoft\DirectX"
+
+
+def _parse_adapter_luid(instance_name: str) -> Optional[int]:
+ """The 64-bit LUID in a ``GPU Adapter Memory`` instance name, or None.
+
+ Instances are named ``luid_0x<high>_0x<low>_phys_<n>``; DirectX stores the
+ same value as one 64-bit ``AdapterLuid``, so recombine the halves.
+ """
+ m = re.match(r"luid_0x([0-9a-f]+)_0x([0-9a-f]+)", instance_name.strip(), re.IGNORECASE)
+ if m is None:
+ return None
+ try:
+ return (int(m.group(1), 16) << 32) | int(m.group(2), 16)
+ except ValueError:
+ return None
+
+
+_ADAPTER_NAME_NOISE = re.compile(r"\((?:tm|r)\)|[™®]", re.IGNORECASE)
+
+
+def _normalize_adapter_name(name: str) -> str:
+ """A GPU name in the one spelling both sides of the join can agree on.
+
+ DirectX takes its Description from the driver INF and HIP fills props.name
+ from the ASIC record, so the same card reaches the two sides with the
+ trademark marks and the spacing around them differing -- "AMD Radeon(TM)
+ 780M Graphics" against "AMD Radeon 780M Graphics". Nothing here merges two
+ different models, and a collision between two that did normalize alike is
+ caught by the count check in _attribute_adapter_useds_by_key.
+ """
+ return " ".join(_ADAPTER_NAME_NOISE.sub(" ", name).split()).casefold()
+
+
+def _parse_adapter_family_gfx(family: str) -> str:
+ """The gfx target in a DirectX ``AdapterFamily``, or "" when it holds none.
+
+ The AMD driver writes ``AMD_NAVI44:gfx1200``; torch reports the same target
+ as ``props.gcnArchName``, which on Linux carries feature suffixes
+ (``gfx1201:sramecc-:xnack-``) the comparison has to drop.
+ """
+ for token in str(family).split(":"):
+ token = token.strip().lower()
+ if re.fullmatch(r"gfx[0-9a-f]+", token):
+ return token
+ return ""
+
+
+def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
+ """``{luid: {"name": description, "gfx": arch}}`` for the AMD adapters DirectX records.
+
+ ``gfx`` is absent when the driver wrote no ``AdapterFamily``.
+
+ All or nothing: a record this cannot read makes the map incomplete, and an
+ incomplete map is indistinguishable from a complete one at the join, which
+ would then pair a visible card with a hidden same-named card's counter. So
+ any failure past the point where a subkey is known to be an adapter returns
+ ``{}``, which drops the caller back to capacity ranking. Same for off
+ Windows or without the key.
+ """
+ if platform.system() != "Windows":
+ return {}
+ try:
+ import winreg
+ except ImportError:
+ return {}
+ by_luid: dict[int, Dict[str, str]] = {}
+ try:
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _WINDOWS_DIRECTX_KEY) as dx_key:
+ for index in range(winreg.QueryInfoKey(dx_key)[0]):
+ subkey = winreg.EnumKey(dx_key, index)
+ # Adapter records are GUID-named; ShaderCache and any future
+ # named subkey are not adapters and are not ours to read.
+ if not (subkey.startswith("{") and subkey.endswith("}")):
+ continue
+ with winreg.OpenKey(dx_key, subkey) as adapter_key:
+ vendor_id, _ = winreg.QueryValueEx(adapter_key, "VendorId")
+ if int(vendor_id) != _AMD_PCI_VENDOR_ID:
+ continue
+ luid, _ = winreg.QueryValueEx(adapter_key, "AdapterLuid")
+ description, _ = winreg.QueryValueEx(adapter_key, "Description")
+ try:
+ family, _ = winreg.QueryValueEx(adapter_key, "AdapterFamily")
+ except OSError:
+ family = ""
+ name = str(description).strip()
+ if not name:
+ # An AMD adapter this cannot name: see the all-or-nothing note.
+ return {}
+ record = {"name": name}
+ gfx = _parse_adapter_family_gfx(str(family))
+ if gfx:
+ record["gfx"] = gfx
+ by_luid[int(luid)] = record
+ except Exception as e:
+ logger.debug("DirectX adapter registry read declined: %s", e)
+ return {}
+ return by_luid
+
+
+def _adapter_counter_capacity(meta: Dict[str, Any]) -> float:
+ """The capacity a ``Dedicated Usage`` counter for this device can actually fill.
+
+ That counter measures the dedicated segment, so the carve-out is its ceiling.
+ ``total_bytes`` is what the user is SHOWN, and on a unified APU may be the
+ whole driver pool, against which a counter no visible card could hold still
+ fits. Rank or bound a counter with this, never ``total_bytes``. The fallback
+ keeps it right on a ``dev_meta`` built before ``dedicated_bytes`` existed.
+ """
+ return float(meta.get("dedicated_bytes", meta["total_bytes"]))
+
+
+def _attribute_adapter_useds_by_key(
+ useds_by_key: dict[str, list[float]],
+ positions_by_key: dict[str, list[int]],
+ dev_meta: list[Dict[str, Any]],
+) -> Optional[tuple[list[Optional[float]], float]]:
+ """Pair each key's counters with the devices carrying that key, or decline.
+
+ Returns ``(per_device_used_bytes, aggregate_used_bytes)``, or None when any
+ key's counters are not exactly its devices'. Several devices under one key
+ (two cards of a model, two cards of an arch) leave per-device unknown --
+ nothing says which counter is which ordinal -- while still contributing to
+ the aggregate, which the pairing does not change.
+ """
+ assigned: list[Optional[float]] = [None] * len(dev_meta)
+ total_used = 0.0
+ for key, positions in positions_by_key.items():
+ useds = useds_by_key.get(key, [])
+ # Fewer counters than cards under this key means a visible card has no
+ # reading; more means a same-keyed adapter HIP does not enumerate, or one
+ # adapter emitting several _phys_N instances. Either way this key's
+ # counters are not exactly its devices'.
+ if len(useds) != len(positions):
+ return None
+ # Largest usage against the largest capacity: any other pairing of the
+ # same multiset only makes the check below stricter, never truer.
+ by_capacity = sorted(positions, key = lambda p: -_adapter_counter_capacity(dev_meta[p]))
+ for used, position in zip(sorted(useds, reverse = True), by_capacity):
+ # A usage above its own card's capacity: a record outliving its
+ # hardware, so the key is not identifying what it appears to.
+ if used > _adapter_counter_capacity(dev_meta[position]):
+ return None
+ total_used += used
+ if len(positions) == 1:
+ assigned[positions[0]] = useds[0]
+ return assigned, total_used
+
+
+def _match_adapter_used_by_luid(
+ adapters: list[tuple[str, float]], dev_meta: list[Dict[str, Any]]
+) -> Optional[tuple[list[Optional[float]], float]]:
+ """Attribute per-adapter used bytes to torch devices on the adapter LUID.
+
+ Joins each counter to a DirectX adapter record by the LUID in its instance
+ name, then to a torch device by what the record and the device agree on.
+ Identity, not capacity, so it resolves the single-GPU case that
+ _match_adapter_used_to_devices can never force (nothing smaller exists to
+ exceed) and stays right when a busy foreign adapter outweighs an idle card.
+
+ The model name is tried first, because it separates two cards of one arch
+ (a 9070 beside a 9070 XT) where the arch cannot. DirectX takes it from the
+ driver INF and HIP from the ASIC record, so the two spellings CAN differ by
+ more than normalizing fixes, and a declined name join then falls to the gfx
+ target -- which is also what tells an iGPU from the dGPU beside it. The arch
+ pass runs only when every AMD record has one, so a driver too old to write
+ ``AdapterFamily`` cannot leave a hidden card's counter looking like the
+ visible card's.
+
+ Measured on a Windows gfx1151 (driver 32.0.21041.1000): DirectX said
+ "AMD Radeon(TM) 8060S Graphics" and so did ``props.name``, an exact match, so
+ the name pass carried it. That driver wrote NO ``AdapterFamily`` at all, so
+ the gfx fallback was unavailable on the one machine this has been measured
+ on. The two keys are therefore not the belt and braces this reads as: a
+ driver that both spells the name differently and omits ``AdapterFamily``
+ declines the join outright and drops back to capacity ranking. That is the
+ safe direction, but it means the name pass is load bearing in practice.
+
+ Returns ``(per_device_used_bytes, aggregate_used_bytes)``, or None when
+ neither key establishes the join, so the caller falls back to capacity
+ ranking.
+ """
+ records = _windows_amd_adapter_records_by_luid()
+ if not records:
+ return None
+
+ useds_by_luid: dict[int, list[float]] = {}
+ for instance, used in adapters:
+ luid = _parse_adapter_luid(instance)
+ if luid is not None and luid in records:
+ useds_by_luid.setdefault(luid, []).append(used)
+
+ best: Optional[tuple[list[Optional[float]], float]] = None
+ best_resolved = -1
+
+ for field, record_key, device_key in (
+ (
+ "name",
+ lambda record: _normalize_adapter_name(record["name"]),
+ lambda meta: _normalize_adapter_name(str(meta.get("name", ""))),
+ ),
+ (
+ "gfx",
+ lambda record: record["gfx"],
+ lambda meta: _parse_adapter_family_gfx(str(meta.get("gfx", ""))),
+ ),
+ ):
+ if not all(record.get(field) for record in records.values()):
+ continue
+ useds_by_key: dict[str, list[float]] = {}
+ for luid, useds in useds_by_luid.items():
+ useds_by_key.setdefault(record_key(records[luid]), []).extend(useds)
+ positions_by_key: dict[str, list[int]] = {}
+ for position, meta in enumerate(dev_meta):
+ positions_by_key.setdefault(device_key(meta), []).append(position)
+ if "" in positions_by_key: # a visible device carrying no such key
+ continue
+ # AMD usage this key cannot place, so the key is not identifying
+ # reliably: a card whose Description differs from its props.name leaves
+ # its own counter under one key while a hidden card sits under the
+ # device's, and the pairing would hand over the hidden card's bytes.
+ # Declining drops a masked second AMD card back to capacity ranking,
+ # which is where it already was.
+ if set(useds_by_key) - set(positions_by_key):
+ continue
+ matched = _attribute_adapter_useds_by_key(useds_by_key, positions_by_key, dev_meta)
+ if matched is not None:
+ # Same-keyed cards leave those devices unknown and feed only the
+ # aggregate (#7452). That is a result, not a reason to stop, and it
+ # is not all-or-nothing: a host with one uniquely named card beside
+ # two same-named ones of different arch resolves ONE device by name
+ # and all three by gfx. So rank passes by how many devices they
+ # actually place, keep the first on a tie, and stop early only on a
+ # pass that leaves nothing for a later one to improve.
+ resolved = sum(used is not None for used in matched[0])
+ if resolved == len(dev_meta):
+ return matched
+ if resolved > best_resolved:
+ best, best_resolved = matched, resolved
+ return best
+
+
def _match_adapter_used_to_devices(
adapter_useds: list[float], device_totals: list[float]
) -> list[Optional[float]]:
@@ -2343,6 +2589,8 @@ def _rocm_windows_per_device_vram(
"index": phys_idx,
"visible_ordinal": ordinal,
"name": props.name,
+ # Second join key for _match_adapter_used_by_luid, unused elsewhere.
+ "gfx": str(getattr(props, "gcnArchName", "") or ""),
"total_bytes": int(props.total_memory),
}
)
@@ -2358,10 +2606,17 @@ def _rocm_windows_per_device_vram(
adapters = _rocm_windows_perf_counter_vram_by_adapter()
aggregate_gb: Optional[float] = None
if adapters:
- adapter_useds = [used for _, used in adapters]
- totals = [d["total_bytes"] for d in dev_meta]
- assigned = _match_adapter_used_to_devices(adapter_useds, totals)
- aggregate_bytes = _rocm_windows_aggregate_used_bytes(adapter_useds, totals)
+ # LUID first: it answers by identity, where capacity ranking declines
+ # unless the sizes force a pairing -- which one visible GPU never does.
+ by_luid = _match_adapter_used_by_luid(adapters, dev_meta)
+ if by_luid is not None:
+ assigned, aggregate_bytes = by_luid
+ else:
+ adapter_useds = [used for _, used in adapters]
+ # Capacities the counters can fill, not the displayed totals.
+ totals = [_adapter_counter_capacity(d) for d in dev_meta]
+ assigned = _match_adapter_used_to_devices(adapter_useds, totals)
+ aggregate_bytes = _rocm_windows_aggregate_used_bytes(adapter_useds, totals)
if aggregate_bytes is not None:
aggregate_gb = round(aggregate_bytes / (1024**3), 2)
else: