Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: count only this adapter's engines in the Windows AMD GPU utilization (#9317)
Leo Borcherding55ba56478a2e
diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.pyindex afd4171f5df..49c97a93b17 100644--- a/studio/backend/tests/test_rocm_windows_vram_7072.py+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py@@ -57,7 +57,10 @@ def _fake_torch(self.gcnArchName = gfxdef get_device_properties(i):- name, total, *arch = dev[i]+ entry = dev[i]+ if isinstance(entry, Exception):+ raise entry+ name, total, *arch = entryreturn _Props(name, total, arch[0] if arch else "")def mem_get_info(i):@@ -88,7 +91,26 @@ def _adapter_output(adapters):return "".join(f"{name}|{int(used)}\n" for name, used in adapters)-def _subprocess_run(*, adapter_output = "__NONE__\n", util_output = "12.0\n"):+def _engine_output(samples):+ """``GPU Engine`` rows in the shape Get-Counter is asked to emit."""+ if not samples:+ return "__NONE__\n"+ return "".join(f"{name}|{value}\n" for name, value in samples)+++# One engine on the solo host's own adapter, so 12.0 narrowed or not.+_DEFAULT_ENGINES = [("pid_1_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 12.0)]+++def _subprocess_run(+ *,+ adapter_output = "__NONE__\n",+ util_output = None,+ engine_samples = None,+):+ if util_output is None:+ util_output = _engine_output(_DEFAULT_ENGINES if engine_samples is None else engine_samples)+def fake_run(cmd, *a, **k):joined = " ".join(cmd) if isinstance(cmd, list) else str(cmd)if "GPU Adapter Memory" in joined and "InstanceName" in joined:@@ -110,10 +132,11 @@ 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.+ # Capacity-ranking path by default: without these a Windows dev box asks its+ # own HIP runtime and reads its own registry, and an identity join answers+ # instead. The identity tests below opt in with their own map.monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", lambda: {})+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", lambda ordinals, names: None)# 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)@@ -881,6 +904,311 @@ def test_registry_read_is_windows_only(monkeypatch):assert hw._windows_amd_adapter_records_by_luid() == {}+# ----------------------------------------------------------------------------- #+# HIP's own LUID (idea and the R0600 route from @pablo86gr in #8793)+#+# The exact key: hipDeviceProp_tR0600 carries the same DXGI LUID the counters+# are named after, so the join needs nothing about the card, only the card.+# Tried before the DirectX record, which falls back to matching on what the two+# sides say about it and so cannot separate two of one model.+# ----------------------------------------------------------------------------- #+TWIN_CARDS = [("AMD Radeon RX 7900 XTX", 24 * GB, "gfx1100")] * 2+TWIN_ADAPTERS = [+ ("luid_0x00000000_0x0000aaaa_phys_0", 10 * GB),+ ("luid_0x00000000_0x0000bbbb_phys_0", 4 * GB),+]+++def _hip_ids(*identities):+ """Stand in for the ctypes probe: (luid, node_mask) per queried ordinal."""++ def probe(ordinals, names):+ probe.asked = list(ordinals)+ return [identities[o] for o in ordinals]++ probe.asked = []+ return probe+++def test_hip_luid_separates_two_of_one_model(win_rocm, monkeypatch):+ """What the DirectX join cannot do: one Description and one arch for both+ cards leaves it the aggregate only, while the LUIDs are still distinct."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(TWIN_CARDS, free_equals_total = True))+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(TWIN_ADAPTERS))+ )+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0xAAAA, 0), (0xBBBB, 0)))++ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])+ assert [d["used_gb"] for d in devices] == [+ pytest.approx(10.0, abs = 0.01),+ pytest.approx(4.0, abs = 0.01),+ ]+ assert aggregate == pytest.approx(14.0, abs = 0.01)+++def test_hip_is_asked_about_the_ordinal_that_answered(win_rocm, monkeypatch):+ """dev_meta is compacted when a device fails to probe, so its positions are+ not HIP ordinals. Asking by position would hand ordinal 0's LUID to the+ card that survived at ordinal 1."""+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ [RuntimeError("ordinal 0 will not probe"), TWIN_CARDS[1]], free_equals_total = True+ ),+ )+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(TWIN_ADAPTERS))+ )+ probe = _hip_ids((0xAAAA, 0), (0xBBBB, 0))+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", probe)++ devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])+ assert probe.asked == [1]+ # Ordinal 1 is the 0xBBBB counter, not the 0xAAAA one its position would name.+ assert devices[0]["used_gb"] == pytest.approx(4.0, abs = 0.01)+ assert aggregate == pytest.approx(4.0, abs = 0.01)+++def test_linked_nodes_keep_the_aggregate_but_not_per_device(win_rocm, monkeypatch):+ """Two ordinals behind one LUID. The counters index the adapter's nodes as+ phys_N and nothing says which ordinal owns which, so the sum survives and+ the pairing does not."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(TWIN_CARDS, free_equals_total = True))+ adapters = [+ ("luid_0x00000000_0x0000aaaa_phys_0", 10 * GB),+ ("luid_0x00000000_0x0000aaaa_phys_1", 4 * GB),+ ]+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))+ )+ monkeypatch.setattr(+ hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0xAAAA, 0b01), (0xAAAA, 0b10))+ )++ 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)+++def test_a_node_the_visible_ordinals_do_not_own_declines(win_rocm, monkeypatch):+ """One ordinal holding one node of a two-node adapter. The second node's+ usage is on hardware HIP is not showing, so it is not this card's to claim,+ and the node mask is what says so."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch([TWIN_CARDS[0]], free_equals_total = True))+ adapters = [+ ("luid_0x00000000_0x0000aaaa_phys_0", 3 * GB),+ ("luid_0x00000000_0x0000aaaa_phys_1", 9 * GB),+ ]+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))+ )+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0xAAAA, 0b01)))++ devices, aggregate = hw._rocm_windows_per_device_vram([0])+ assert devices[0]["used_gb"] is None+ assert aggregate is None+++def test_a_node_count_that_matches_the_wrong_nodes_is_not_ownership(win_rocm, monkeypatch):+ """One ordinal owning node 0 of a linked adapter, whose own sample is missing while+ the node it does NOT own reports: the counts agree, only the identities disagree.+ Taking that as ownership would sum the other node's work as this card's."""+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch([TWIN_CARDS[0]], free_equals_total = True))+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0xAAAA, 0b01)))+ dev_meta = [+ {+ "visible_ordinal": 0,+ "name": TWIN_CARDS[0][0],+ "gfx": "gfx1100",+ "total_bytes": TWIN_CARDS[0][1],+ "dedicated_bytes": TWIN_CARDS[0][1],+ }+ ]++ hidden_only = [("luid_0x00000000_0x0000aaaa_phys_1", 5 * GB)]+ _, _, whole_adapter = hw._match_adapter_used_by_hip_luid(hidden_only, dev_meta)+ assert whole_adapter == [None]++ # The node it does own, reporting: the decline above is the identity check, not+ # the join giving up on linked adapters.+ its_own = [("luid_0x00000000_0x0000aaaa_phys_0", 5 * GB)]+ _, _, whole_adapter = hw._match_adapter_used_by_hip_luid(its_own, dev_meta)+ assert whole_adapter == [0xAAAA]+++def test_hip_luid_join_declines_and_falls_back(win_rocm, monkeypatch):+ dev_meta = [+ {+ "visible_ordinal": 0,+ "name": "AMD Radeon RX 9060 XT",+ "gfx": "gfx1200",+ "total_bytes": 16 * GB,+ }+ ]+ join = hw._match_adapter_used_by_hip_luid++ # The runtime cannot be asked (not Windows, DLL not loaded, symbol absent).+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", lambda ordinals, names: None)+ assert join(SOLO_ADAPTERS, dev_meta) is None++ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0x15369, 0)))+ # One physical node cannot report twice; summing would double-count it.+ assert join([SOLO_ADAPTERS[0], SOLO_ADAPTERS[0]], dev_meta) is None+ # A visible card with no counter of its own.+ assert join([("luid_0x00000000_0x00099999_phys_0", 2 * GB)], dev_meta) is None+ # A usage above the card's own capacity.+ assert join([("luid_0x00000000_0x00015369_phys_0", 20 * GB)], dev_meta) is None+ # And the resolvable case still resolves, so the declines above are the reason.+ assigned, aggregate, whole_adapter = join(SOLO_ADAPTERS, dev_meta)+ assert assigned[0] == pytest.approx(3 * GB)+ assert aggregate == pytest.approx(3 * GB)+ # One ordinal owning every node its LUID names, so the LUID is this device's.+ assert whole_adapter == [0x15369]+++def test_hip_luid_join_bounds_the_counter_by_the_carve_out(win_rocm, monkeypatch):+ """A unified APU is shown the whole driver pool as its total, so bounding+ with that admits any reading at all. The carve-out is what the counter+ fills, and the DirectX join already declines this."""+ apu = [+ {+ "visible_ordinal": 0,+ "name": "AMD Radeon(TM) 8060S Graphics",+ "gfx": "gfx1151",+ "total_bytes": 96 * GB,+ "dedicated_bytes": 0.5 * GB,+ }+ ]+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids((0x15369, 0)))+ over = [("luid_0x00000000_0x00015369_phys_0", 2 * GB)]+ assert hw._match_adapter_used_by_hip_luid(over, apu) is None+ assert hw._attribute_adapter_useds_by_key({"k": [2 * GB]}, {"k": [0]}, apu) is None++ # Inside the carve-out still resolves, so the decline above is the bound.+ under = [("luid_0x00000000_0x00015369_phys_0", 0.25 * GB)]+ assigned, aggregate, _whole = hw._match_adapter_used_by_hip_luid(under, apu)+ assert assigned[0] == pytest.approx(0.25 * GB)+ assert aggregate == pytest.approx(0.25 * GB)+++class _Callable:+ """A ctypes function pointer: callable, and argtypes/restype are settable."""++ def __init__(self, fn):+ self._fn = fn+ self.argtypes = None+ self.restype = None++ def __call__(self, *args):+ return self._fn(*args)+++def _r0600_blob(+ name,+ luid,+ node_mask = 0,+):+ """The documented prefix of hipDeviceProp_tR0600: name[256], uuid[16],+ luid[8], luidDeviceNodeMask[4]."""+ return (+ name.encode("utf-8").ljust(256, b"\x00")+ + bytes(16)+ + luid.to_bytes(8, "little")+ + node_mask.to_bytes(4, "little")+ )+++def _fake_ctypes(+ blobs,+ *,+ loaded = ("amdhip64_7.dll",),+ has_symbol = True,+ rc = 0,+):+ """A `ctypes` whose loaded amdhip64 answers with ``blobs[ordinal]``."""++ class _Buffer:+ def __init__(self, size):+ self.data = bytes(size)++ def __bytes__(self):+ return self.data++ class _Hip:+ def __getattr__(self, symbol):+ if not has_symbol:+ raise AttributeError(symbol)++ def get_properties(buffer, ordinal):+ if rc:+ return rc+ buffer.data = blobs[ordinal].ljust(len(buffer.data), b"\x00")+ return 0++ return _Callable(get_properties)++ kernel32 = types.SimpleNamespace(+ GetModuleHandleW = _Callable(lambda name: 0x1234 if name in loaded else None)+ )+ mod = types.ModuleType("ctypes")+ mod.WinDLL = lambda name, handle = None, use_last_error = False: (+ kernel32 if name == "kernel32" else _Hip()+ )+ mod.create_string_buffer = _Buffer+ mod.byref = lambda buffer: buffer+ mod.c_wchar_p = mod.c_void_p = mod.c_int = object()+ return mod+++def hip_probe_host(monkeypatch):+ """Windows with torch's HIP 7 runtime loaded, so the probe runs for real."""+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(SOLO_DEVICE))+ return monkeypatch+++NINE_SIXTY = "AMD Radeon RX 9060 XT"+++def test_hip_probe_reads_the_luid_and_node_mask(hip_probe_host, monkeypatch):+ monkeypatch.setitem(+ sys.modules, "ctypes", _fake_ctypes([_r0600_blob(NINE_SIXTY, 0x14AD4, node_mask = 0b11)])+ )+ assert hw._rocm_windows_hip_adapter_ids([0], [NINE_SIXTY]) == [(0x14AD4, 0b11)]+++def test_hip_probe_needs_the_name_to_read_back(hip_probe_host, monkeypatch):+ """The R0600 suffix is the ABI version, so the prefix is fixed by the same+ contract that named it, but the offsets here are still hardcoded. Reading+ the name back is what catches a layout that ever moved."""+ monkeypatch.setitem(+ sys.modules, "ctypes", _fake_ctypes([_r0600_blob("Some Other Struct", 0x14AD4)])+ )+ assert hw._rocm_windows_hip_adapter_ids([0], [NINE_SIXTY]) is None+++def test_hip_probe_declines_what_it_cannot_answer(hip_probe_host, monkeypatch):+ blob = [_r0600_blob(NINE_SIXTY, 0x14AD4)]+ for label, fake in (+ ("no LUID for this device", _fake_ctypes([_r0600_blob(NINE_SIXTY, 0)])),+ ("the ordinal will not answer", _fake_ctypes(blob, rc = 1)),+ ("the runtime is not in this process", _fake_ctypes(blob, loaded = ())),+ ("the versioned symbol is absent", _fake_ctypes(blob, has_symbol = False)),+ ):+ monkeypatch.setitem(sys.modules, "ctypes", fake)+ assert hw._rocm_windows_hip_adapter_ids([0], [NINE_SIXTY]) is None, label+++def test_hip_probe_is_windows_only(monkeypatch):+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")+ assert hw._rocm_windows_hip_adapter_ids([0], [NINE_SIXTY]) is None++# ----------------------------------------------------------------------------- ## Unified-memory (Strix Halo APU) total reconciliation (Codex #7238)# ----------------------------------------------------------------------------- #@@ -1896,3 +2224,216 @@ def test_a_discrete_card_on_the_same_runtime_keeps_the_dedicated_counter(win_rocassert devices[0]["total_gb"] == 16.9assert devices[0]["used_gb"] == pytest.approx(7.90, abs = 0.01) # Dedicated aloneassert aggregate == pytest.approx(7.90, abs = 0.01)+++# This card at 17%, other adapters at 61%, so a wrong selection still reads 78.+FOREIGN_ENGINES = [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 12.0),+ ("pid_101_luid_0x00000000_0x00015369_phys_0_eng_1_engtype_3D", 5.0),+ ("pid_200_luid_0x00000000_0x000183fe_phys_0_eng_0_engtype_3D", 44.0),+ ("pid_300_luid_0x00000000_0x0001842f_phys_0_eng_0_engtype_3D", 17.0),+]+++def _engine_query(+ monkeypatch,+ adapters,+ engine_samples = None,+):+ """Run the poll; hand back the devices and the counter path."""+ seen = []+ inner = _subprocess_run(adapter_output = _adapter_output(adapters), engine_samples = engine_samples)++ def fake_run(cmd, *a, **k):+ seen.append(" ".join(cmd) if isinstance(cmd, list) else str(cmd))+ return inner(cmd, *a, **k)++ monkeypatch.setattr(hw.subprocess, "run", fake_run)+ devices = hw.get_gpu_utilization()["devices"]+ (query,) = [c for c in seen if "GPU Engine" in c]+ return devices, query+++def _solo_host(monkeypatch, identity = None):+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(SOLO_DEVICE, free_equals_total = True))+ if identity is not None:+ monkeypatch.setattr(hw, "_rocm_windows_hip_adapter_ids", _hip_ids(identity))+++def test_gpu_utilization_counts_only_this_adapters_engines(win_rocm, monkeypatch):+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(monkeypatch, SOLO_ADAPTERS, FOREIGN_ENGINES)+ assert device["gpu_utilization_pct"] == 17.0 # this card's two engines, not 78+++def test_gpu_utilization_falls_back_to_every_engine(win_rocm, monkeypatch):+ """No HIP identity means no LUID to narrow to, and the host sum beats no reading."""+ _solo_host(monkeypatch)++ (device,), _ = _engine_query(monkeypatch, SOLO_ADAPTERS, FOREIGN_ENGINES)+ assert device["gpu_utilization_pct"] == 78.0+++def test_a_linked_adapters_hidden_nodes_are_not_this_devices_engines(win_rocm, monkeypatch):+ """Narrowing needs the VRAM join to prove the device is the whole adapter."""+ _solo_host(monkeypatch, (0x15369, 0b01))+ linked = [+ ("luid_0x00000000_0x00015369_phys_0", 3 * GB),+ ("luid_0x00000000_0x00015369_phys_1", 5 * GB),+ ]++ (device,), _ = _engine_query(monkeypatch, linked, FOREIGN_ENGINES)+ assert device["vram_used_gb"] is None+ assert device["gpu_utilization_pct"] == 78.0 # the join declined, so the host's sum+++def test_the_adapter_is_matched_here_and_the_engine_type_in_the_path(win_rocm, monkeypatch):+ """A LUID in the path hands adapter selection to PDH, which no test here can run.+ The engine type stays in the path, where it keeps the sample set to one type per+ process."""+ _solo_host(monkeypatch, (0x15369, 0))++ _, query = _engine_query(monkeypatch, SOLO_ADAPTERS, FOREIGN_ENGINES)+ assert "\\GPU Engine(*engtype_3D*)\\Utilization Percentage" in query+ assert "luid_" not in query+ assert "InstanceName" in query+++def test_a_longer_luid_that_starts_the_same_is_not_this_adapter(win_rocm, monkeypatch):+ """0x153690 begins with 0x15369. Matching on a prefix would count it."""+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 12.0),+ ("pid_200_luid_0x00000000_0x00153690_phys_0_eng_0_engtype_3D", 44.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 12.0+++def test_engtype_spelled_in_lower_case_is_still_a_3d_engine(win_rocm, monkeypatch):+ """Hosts emit engtype_3D and engtype_3d both; PDH folded the case for us before."""+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3d", 12.0),+ ("pid_101_LUID_0X00000000_0X00015369_phys_0_eng_1_ENGTYPE_3D", 5.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 17.0+++def test_only_3d_engines_count(win_rocm, monkeypatch):+ """A compute engine is not the 3D reading, and no 3D instance is unknown, not zero."""+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_Compute", 88.0),+ ("pid_101_luid_0x00000000_0x00015369_phys_0_eng_1_engtype_Copy", 3.0),+ ],+ )+ assert device["gpu_utilization_pct"] is None+++def test_an_idle_engine_reads_zero_rather_than_unknown(win_rocm, monkeypatch):+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 0.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 0.0+++def test_unusable_samples_are_dropped_and_the_sum_is_bounded(win_rocm, monkeypatch):+ """The clamp used to live in the PowerShell expression, so it has to live here now."""+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_1_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", "NaN"),+ ("pid_2_luid_0x00000000_0x00015369_phys_0_eng_1_engtype_3D", "Infinity"),+ ("pid_3_luid_0x00000000_0x00015369_phys_0_eng_2_engtype_3D", -5.0),+ ("pid_4_luid_0x00000000_0x00015369_phys_0_eng_3_engtype_3D", "not-a-number"),+ ("pid_5_luid_0x00000000_0x00015369_phys_0_eng_4_engtype_3D", 70.0),+ ("pid_6_luid_0x00000000_0x00015369_phys_0_eng_5_engtype_3D", 70.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 100.0+++def test_an_instance_name_carrying_no_luid_is_not_this_adapters(win_rocm, monkeypatch):+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ SOLO_ADAPTERS,+ [+ ("pid_100_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 12.0),+ ("engtype_3D", 44.0),+ ("pid_200_luid_zz_0x1_phys_0_eng_0_engtype_3D", 44.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 12.0+++def test_no_engine_instances_at_all_reads_unknown(win_rocm, monkeypatch):+ _solo_host(monkeypatch, (0x15369, 0))++ (device,), _ = _engine_query(monkeypatch, SOLO_ADAPTERS, [])+ assert device["gpu_utilization_pct"] is None+++def test_a_high_luid_half_selects_its_own_adapter(win_rocm, monkeypatch):+ """The high half is only ever zero on ordinary hardware, so nothing else covers it."""+ high = (0xA << 32) | 0x15369+ _solo_host(monkeypatch, (high, 0))++ (device,), _ = _engine_query(+ monkeypatch,+ [("luid_0x0000000a_0x00015369_phys_0", 3 * GB)],+ [+ ("pid_1_luid_0x0000000a_0x00015369_phys_0_eng_0_engtype_3D", 12.0),+ ("pid_2_luid_0x00000000_0x00015369_phys_0_eng_0_engtype_3D", 44.0),+ ],+ )+ assert device["gpu_utilization_pct"] == 12.0+++def test_the_luid_is_internal_and_never_reaches_a_payload(win_rocm, monkeypatch):+ """Keeping the internal LUID out of both payloads is a convention, not a mechanism."""+ _solo_host(monkeypatch, (0x15369, 0))+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(SOLO_ADAPTERS))+ )++ def carries_luid(value):+ if isinstance(value, dict):+ return "luid" in value or any(carries_luid(v) for v in value.values())+ if isinstance(value, (list, tuple)):+ return any(carries_luid(v) for v in value)+ return False++ internal, _ = hw._rocm_windows_per_device_vram([0])+ assert internal[0]["luid"] == 0x15369 # the join resolved, so absence below means something+ assert carries_luid(internal[0]) # the control: what a leak would look like++ for payload in (hw.get_gpu_utilization(), hw.get_visible_gpu_utilization()):+ assert not carries_luid(payload)+ assert 0x15369 not in [v for v in payload.values() if isinstance(v, int)]diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 2ff938f3b40..15b93a81b54 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -3384,15 +3384,29 @@ def _rocm_linux_sysfs_power_w() -> Optional[float]:return None-def _rocm_windows_perf_counter_gpu_util_pct() -> Optional[float]:- """Query AMD GPU compute utilization via Windows Performance Counters (3D engine nodes)."""+def _engine_instance_luid(instance_name: str) -> Optional[int]:+ """The LUID ``_parse_adapter_luid`` reads, behind a ``pid_<pid>_`` prefix."""+ head = instance_name.lower().find("luid_0x")+ if head < 0:+ return None+ return _parse_adapter_luid(instance_name[head:])+++def _rocm_windows_perf_counter_gpu_util_pct(luid: Optional[int] = None) -> Optional[float]:+ """Query AMD GPU compute utilization via Windows Performance Counters (3D engine nodes).++ ``luid`` narrows the sum to one adapter's engines, matched here rather than in the+ counter path so tests can reach it. The engine type stays in the path, where it+ keeps the sample set to one type per process.+ """if platform.system() != "Windows":return Nonetry:ps = ("$s=(Get-Counter '\\GPU Engine(*engtype_3D*)\\Utilization Percentage'"" -ErrorAction SilentlyContinue).CounterSamples;"- "if($s){[math]::Min(($s|Measure-Object CookedValue -Sum).Sum,100)}else{-1}"+ "if($s){$s|ForEach-Object{'{0}|{1}' -f $_.InstanceName,$_.CookedValue}}"+ "else{'__NONE__'}")r = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],@@ -3404,8 +3418,31 @@ def _rocm_windows_perf_counter_gpu_util_pct() -> Optional[float]:)if r.returncode != 0 or not r.stdout.strip():return None- val = float(r.stdout.strip())- return round(val, 1) if val >= 0 else None+ total = 0.0+ matched = False+ for line in r.stdout.splitlines():+ line = line.strip()+ if not line or line == "__NONE__" or "|" not in line:+ continue+ instance, _, raw = line.rpartition("|")+ instance = instance.strip()+ # Hosts spell it engtype_3D and engtype_3d both.+ if "engtype_3d" not in instance.lower():+ continue+ if luid is not None and _engine_instance_luid(instance) != luid:+ continue+ try:+ value = float(raw.strip())+ except (ValueError, TypeError):+ continue+ # 0.0 is an idle engine, so a reading; NaN / inf / negative is not.+ if value != value or value in (float("inf"), float("-inf")) or value < 0:+ continue+ total += value+ matched = True+ if not matched:+ return None+ return round(min(total, 100.0), 1)except Exception:return None@@ -3651,6 +3688,168 @@ def _parse_adapter_luid(instance_name: str) -> Optional[int]:return None+# hipDeviceProp_tR0600 opens with name[256], hipUUID[16], luid[8],+# luidDeviceNodeMask[4]. The R0600 suffix IS the ABI version, so that prefix is+# fixed by the same contract that named it; the name is read back and compared+# against the device's own anyway, so a layout that ever moved is caught rather+# than trusted.+_HIP_PROPS_NAME = slice(0, 256)+_HIP_PROPS_LUID = slice(272, 280)+_HIP_PROPS_NODE_MASK = slice(280, 284)+# Oversized on purpose: HIP writes the whole struct, ~2 KiB, and only the prefix+# above is read back.+_HIP_PROPS_BUFFER_BYTES = 64 * 1024+++def _rocm_windows_hip_adapter_ids(+ ordinals: list[int], names: list[str]+) -> Optional[list[tuple[int, int]]]:+ """The ``(luid, node_mask)`` HIP itself reports for each visible ordinal.++ ``hipDeviceProp_tR0600`` carries the same DXGI LUID the ``GPU Adapter+ Memory`` counter instances are named after, so asking HIP joins the two+ sides on the adapter itself rather than on anything about it. Windows+ reassigns LUIDs across a reboot or a driver restart, and all three sources+ move together, so the value is only ever compared within one poll.++ ``node_mask`` is ``luidDeviceNodeMask``: which nodes of a linked adapter+ this ordinal owns, and 0 on the ordinary adapter that is the whole thing.++ Returns one pair per ordinal, or None when the runtime cannot be asked at+ all (off Windows, the DLL not loaded into this process, the symbol absent,+ an ordinal that will not answer, an all-zero LUID, or a name that does not+ read back) so the caller falls back to the DirectX join. All or nothing for+ the same reason that map is: a partially resolved set would let one card's+ counter answer for another.++ Idea and the R0600 route from @pablo86gr in #8793.+ """+ if platform.system() != "Windows" or not ordinals:+ return None+ try:+ import ctypes++ torch = sys.modules.get("torch")+ major = str(getattr(getattr(torch, "version", None), "hip", "")).split(".", 1)[0]+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.GetModuleHandleW.argtypes = [ctypes.c_wchar_p]+ kernel32.GetModuleHandleW.restype = ctypes.c_void_p+ # Only a module already in this process: torch loaded the runtime it is+ # built against, and LoadLibrary could pull in a different one.+ hip = None+ for dll in dict.fromkeys(+ [f"amdhip64_{major}.dll" if major.isdigit() else "", "amdhip64.dll"]+ ):+ handle = kernel32.GetModuleHandleW(dll) if dll else None+ if handle:+ hip = ctypes.WinDLL(dll, handle = handle)+ break+ if hip is None:+ return None+ get_properties = hip.hipGetDevicePropertiesR0600+ get_properties.argtypes = [ctypes.c_void_p, ctypes.c_int]+ get_properties.restype = ctypes.c_int++ identities: list[tuple[int, int]] = []+ for ordinal, name in zip(ordinals, names):+ raw = ctypes.create_string_buffer(_HIP_PROPS_BUFFER_BYTES)+ if get_properties(ctypes.byref(raw), ordinal) != 0:+ return None+ blob = bytes(raw)+ if blob[_HIP_PROPS_NAME].rstrip(b"\x00").decode("utf-8", "replace") != name:+ # Not the struct this reads, so the offsets below mean nothing.+ logger.debug("HIP properties prefix did not read back ordinal %d", ordinal)+ return None+ luid_bytes = blob[_HIP_PROPS_LUID]+ if not any(luid_bytes):+ return None # the runtime has no LUID for this device+ identities.append(+ (+ int.from_bytes(luid_bytes, "little"),+ int.from_bytes(blob[_HIP_PROPS_NODE_MASK], "little"),+ )+ )+ return identities+ except Exception as e:+ logger.debug("HIP adapter identity probe unavailable: %s", e)+ return None+++def _match_adapter_used_by_hip_luid(+ adapters: list[tuple[str, float]], dev_meta: list[Dict[str, Any]]+) -> Optional[tuple[list[Optional[float]], float, list[Optional[int]]]]:+ """Attribute per-adapter used bytes on the LUID HIP reports for each ordinal.++ The exact key, so unlike the DirectX join this separates two cards of one+ model. Ordinals come from ``visible_ordinal``, not from this list's own+ positions, which are compacted when a device fails to probe.++ A linked-node adapter puts several ordinals behind one LUID, and the+ counters index its nodes as ``phys_N`` without saying which ordinal owns+ which. The node mask says how many nodes each ordinal holds, which is+ enough to tell "these counters are exactly these ordinals' nodes" from "one+ of them belongs to a node HIP is not showing us" -- but not enough to pair+ them, so several ordinals under one LUID report unknown per device and+ contribute only to the aggregate, which the pairing does not change.++ The third return is that LUID, only where the device is the whole adapter, which+ is what the engine counters need to filter safely.+ """+ ordinals = [int(meta["visible_ordinal"]) for meta in dev_meta]+ identities = _rocm_windows_hip_adapter_ids(ordinals, [str(meta["name"]) for meta in dev_meta])+ if identities is None:+ return None++ useds_by_luid: dict[int, list[float]] = {}+ physes_by_luid: dict[int, set[int]] = {}+ for instance, used in adapters:+ luid = _parse_adapter_luid(instance)+ phys = re.search(r"_phys_(\d+)", instance, re.IGNORECASE)+ if luid is None or phys is None:+ continue+ index = int(phys.group(1))+ if index in physes_by_luid.setdefault(luid, set()):+ # One physical node cannot report twice; summing would double-count.+ return None+ physes_by_luid[luid].add(index)+ useds_by_luid.setdefault(luid, []).append(used)++ positions_by_luid: dict[int, list[int]] = {}+ nodes_by_luid: dict[int, int] = {}+ for position, (luid, node_mask) in enumerate(identities):+ positions_by_luid.setdefault(luid, []).append(position)+ # A plain adapter reports no mask and is one node.+ nodes_by_luid[luid] = nodes_by_luid.get(luid, 0) + (bin(node_mask).count("1") or 1)++ assigned: list[Optional[float]] = [None] * len(dev_meta)+ whole_adapter: list[Optional[int]] = [None] * len(dev_meta)+ total_used = 0.0+ for luid, positions in positions_by_luid.items():+ useds = useds_by_luid.get(luid, [])+ # Fewer counters than nodes means a visible node has no reading; more+ # means the adapter has a node these ordinals do not own, whose usage is+ # not theirs to claim.+ if len(useds) != nodes_by_luid[luid]:+ return None+ used = float(sum(useds))+ # The carve-out, not the displayed total: on a unified APU the latter is+ # the whole driver pool, against which no reading is out of range.+ capacity = sum(_adapter_counter_capacity(dev_meta[position]) for position in positions)+ if used > capacity:+ return None+ total_used += used+ if len(positions) == 1:+ assigned[positions[0]] = used+ # Counts say how many nodes this ordinal owns, never which. The mask+ # names them (bit i is node i), so the observed phys_N set has to BE+ # those or the LUID covers a node this device does not own; a zero+ # mask names nothing and leaves the count check alone.+ named = {i for i in range(32) if identities[positions[0]][1] >> i & 1}+ if not named or named == physes_by_luid.get(luid, set()):+ whole_adapter[positions[0]] = luid+ return assigned, total_used, whole_adapter++_ADAPTER_NAME_NOISE = re.compile(r"\((?:tm|r)\)|[™®]", re.IGNORECASE)@@ -4353,12 +4552,21 @@ def _rocm_windows_per_device_vram(if adapters is None:adapters = _rocm_windows_perf_counter_vram_by_adapter()aggregate_gb: Optional[float] = None+ whole_adapter: list[Optional[int]] = [None] * len(dev_meta)if adapters:- # 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+ # Identity first, in the order the keys are exact: HIP's own LUID, then+ # the DirectX record reached by name or arch. Either answers where+ # capacity ranking declines unless the sizes force a pairing, which one+ # visible GPU never does.+ by_hip = _match_adapter_used_by_hip_luid(adapters, dev_meta)+ by_identity: Optional[tuple[list[Optional[float]], float]] = None+ if by_hip is not None:+ assigned, aggregate_bytes, whole_adapter = by_hip+ by_identity = (assigned, aggregate_bytes)+ else:+ by_identity = _match_adapter_used_by_luid(adapters, dev_meta)+ if by_identity is not None:+ assigned, aggregate_bytes = by_identityelse:adapter_useds = [used for _, used in adapters]# Capacities the counters can fill, not the displayed totals.@@ -4436,7 +4644,7 @@ def _rocm_windows_per_device_vram()devices: list[Dict[str, Any]] = []- for meta, used_bytes in zip(dev_meta, assigned):+ for meta, used_bytes, luid in zip(dev_meta, assigned, whole_adapter):total_gb = round(meta["total_bytes"] / (1024**3), 2)used_gb = round(used_bytes / (1024**3), 2) if used_bytes is not None else Nonedevices.append(@@ -4446,6 +4654,8 @@ def _rocm_windows_per_device_vram("name": meta["name"],"used_gb": used_gb,"total_gb": total_gb,+ # Internal: filters the engine counters. Never served.+ "luid": luid,})return devices, aggregate_gb@@ -4547,10 +4757,11 @@ def get_gpu_utilization() -> Dict[str, Any]:_win_ids = list(range(_torch_get_physical_gpu_count() or 0))_win_devices, _win_aggregate = _rocm_windows_per_device_vram(_win_ids)if _win_devices:- # A single visible GPU can own the aggregate 3D-engine utilization;- # across several GPUs the sum isn't per-device, so leave it unset.+ # Across several GPUs the engine sum isn't per-device, so leave it unset._win_util = (- _rocm_windows_perf_counter_gpu_util_pct() if len(_win_devices) == 1 else None+ _rocm_windows_perf_counter_gpu_util_pct(_win_devices[0].get("luid"))+ if len(_win_devices) == 1+ else None)return _gpu_utilization_payload(device,