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: report host VRAM usage when no single GPU's usage can be attributed (#8481)
Daniel Han26ef15b9d335
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex b59aed659af..c5398c7fde7 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1863,6 +1863,15 @@ def _get_cached_system_gpu_info(logger) -> tuple[dict[str, Any], dict[str, Any]])enriched_devices.append(enriched_dev)+ # The tile divides the aggregate by the SUMMED per-device totals, so both must+ # describe the same cards. The two probes enumerate independently: visibility+ # drops a device whose mem_get_info raises, the aggregate side reads torch+ # properties only and keeps it. A device in one and not the other inflates the+ # percentage and floors free at 0, so identical index sets only (#7452).+ aggregate_basis_matches = metrics_match and {+ d.get("index") for d in utilization_info.get("devices", [])+ } == {d.get("index") for d in enriched_devices}+try:from core.inference.llama_cpp import LlamaCppBackendfrom utils.hardware import DeviceType, get_device@@ -1890,6 +1899,11 @@ def _get_cached_system_gpu_info(logger) -> tuple[dict[str, Any], dict[str, Any]]"devices": enriched_devices,"backend": visibility_info.get("backend"),"gguf_gpu_ids_supported": gpu_ids_supported,+ # Host-level used VRAM, for when no counter is attributable to one card+ # (#7452). Only the Windows ROCm path sets it; None everywhere else.+ "vram_used_gb_aggregate": utilization_info.get("vram_used_gb_aggregate")+ if aggregate_basis_matches+ else None,}# Keep inference placement separate on train-capable hosts where a forced Vulkan llama.cppdiff --git a/studio/backend/tests/test_rocm_multi_gpu_vram_system_wide.py b/studio/backend/tests/test_rocm_multi_gpu_vram_system_wide.pyindex db89b02003f..a147062c32b 100644--- a/studio/backend/tests/test_rocm_multi_gpu_vram_system_wide.py+++ b/studio/backend/tests/test_rocm_multi_gpu_vram_system_wide.py@@ -462,7 +462,7 @@ def test_visible_utilization_rocm_fallback_overlays(monkeypatch):# No AMD adapter data on this host. On Windows this branch runs ahead of the torch# fallback under test, and probing it imports torch, which the CI runner does not# install. Off Windows the real function is never reached, so this changes nothing.- monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids: [])+ monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids: ([], None))monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)monkeypatch.setattr(hw, "_smi_query", lambda *a, **k: None) # amd-smi unavailablemonkeypatch.setattr(@@ -494,7 +494,7 @@ def test_visible_utilization_relative_index_skips_overlay(monkeypatch):# No AMD adapter data on this host. On Windows this branch runs ahead of the torch# fallback under test, and probing it imports torch, which the CI runner does not# install. Off Windows the real function is never reached, so this changes nothing.- monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids: [])+ monkeypatch.setattr(hw, "_rocm_windows_per_device_vram", lambda ids: ([], None))monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)monkeypatch.setattr(hw, "_smi_query", lambda *a, **k: None)monkeypatch.setattr(diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.pyindex b4079831b74..02c583b2e1c 100644--- a/studio/backend/tests/test_rocm_windows_vram_7072.py+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py@@ -8,8 +8,9 @@ torch 2.11.0+rocm7.13. On Windows without a HIP SDK, amd-smi is permanentlydisabled (avoids a UAC/DiskPart prompt) and hipMemGetInfo returns free==total(used 0). Two symptoms followed:- * System tab (/api/system -> get_visible_gpu_utilization) showed ~0 VRAM used- on every GPU (torch mem_get_info free==total quirk; ROCm/ROCm#1909).+ * System tab (/api/system -> get_visible_gpu_utilization) showed ~0 VRAM used on+ every GPU (mem_get_info free==total; see rocm_windows_free_is_untrusted for why+ the reading is optimistic).* get_gpu_utilization()'s Windows fallback SUMMED "GPU Adapter Memory\\DedicatedUsage" across all adapters into ONE fake device with only GPU 0's total, sothe second GPU never appeared.diff --git a/studio/backend/tests/test_rocm_windows_vram_7452.py b/studio/backend/tests/test_rocm_windows_vram_7452.pynew file mode 100644index 00000000000..ff15aa238fb--- /dev/null+++ b/studio/backend/tests/test_rocm_windows_vram_7452.py@@ -0,0 +1,280 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for issue #7452 -- "Stops Reading VRAM Total / Usage on RDNA3".++Reporter: the same host as #7072 (AMD Radeon PRO W7900 45 GiB + W7500 7.98 GiB,+Windows 10, ROCm 7.13, torch 2.11.0+rocm7.13), six days after the #7072 fix (#7238)+shipped, so the two are a regression pair rather than duplicates.++#7238 stopped fabricating a per-device usage when the LUID performance counters+cannot be attributed to torch ordinals: Windows shares no key between the two, so+usage is paired by capacity ranking and kept only when capacity FORCES it. Here the+smaller card is 7.98 GiB, so every usage at or below that -- idle, and every small+model -- is swappable between the cards and reports Unknown. Honest per device, but+the System tab's aggregate VRAM tile went Unknown too, and the aggregate does NOT+depend on the pairing: the sum of a permutation is the same whichever way round. His+screenshot shows the per-device totals intact (45.0 / 7.98 GiB) with used, free and+percent all Unknown.++Mocks: torch, the performance counter and the platform are all faked (no AMD GPU and+no Windows or ROCm CI in this repository), imported from test_rocm_windows_vram_7072+so both halves of the pair are driven by one fixture shape.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++from utils.hardware import hardware as hw++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from test_rocm_windows_vram_7072 import ( # noqa: E402, F401 (win_rocm is a fixture)+ GB,+ MiB,+ _adapter_output,+ _fake_torch,+ _subprocess_run,+ win_rocm,+)++# The reporter's cards and his idle used figures from #7072's screenshot (0.22 and+# 0.14 GiB, the 53.0 GiB tile reading 0.36 GiB). One counter instance per visible+# card and no others, the only shape the aggregate is emitted for.+REPORTER_DEVICES = [("AMD Radeon PRO W7900", 45.0 * GB), ("AMD Radeon PRO W7500", 7.98 * GB)]+IDLE_ADAPTERS = [+ ("luid_0x00000000_0x0000d1e2_phys_0", 0.22 * GB), # W7900 idle desktop+ ("luid_0x00000000_0x0000e34a_phys_0", 0.14 * GB), # W7500 idle desktop+]+++# ----------------------------------------------------------------------------- #+# The System tab tile: aggregate usage survives an unattributable pairing+# ----------------------------------------------------------------------------- #+def test_system_tab_reports_aggregate_when_pairing_is_ambiguous(win_rocm, monkeypatch):+ """0.22 + 0.14 GiB across a 45/7.98 GiB pair: neither usage is capacity-forced, so+ per device stays Unknown, but the total is 0.36 GiB either way round. Before the+ fix the whole tile read Unknown (#7452)."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(REPORTER_DEVICES, free_equals_total = True))+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(IDLE_ADAPTERS))+ )++ result = hw.get_visible_gpu_utilization()+ devices = result["devices"]+ assert len(devices) == 2+ assert sorted(d["vram_total_gb"] for d in devices) == [7.98, 45.0]+ # Per device the ranking cannot tell the two apart, so #7238's invariant holds.+ assert all(d["vram_used_gb"] is None for d in devices)+ # But the aggregate is pairing-independent, so the tile has a real number.+ assert result["vram_used_gb_aggregate"] == pytest.approx(0.36, abs = 0.01)+++def test_gpu_utilization_payload_carries_the_aggregate(win_rocm, monkeypatch):+ """The floating monitor reads get_gpu_utilization(), so the figure has to reach+ that payload too, not only the System tab's."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(REPORTER_DEVICES, free_equals_total = True))+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(IDLE_ADAPTERS))+ )++ result = hw.get_gpu_utilization()+ assert result["vram_used_gb_aggregate"] == pytest.approx(0.36, abs = 0.01)+ # The legacy primary mirror must not be overwritten by the aggregate.+ assert result["vram_total_gb"] == 45.0+ assert result["vram_used_gb"] is None+++def test_loaded_card_agrees_with_the_per_device_figures(win_rocm, monkeypatch):+ """#7072's own case: a model resident on the W7900. 40 GiB exceeds the smaller+ card, so the ranking is forced and both rows get a value; the aggregate must equal+ their sum or the tile disagrees with the rows underneath it."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(REPORTER_DEVICES, free_equals_total = True))+ loaded = [+ ("luid_0x00000000_0x0000d1e2_phys_0", 40.0 * GB),+ ("luid_0x00000000_0x0000e34a_phys_0", 0.5 * GB),+ ]+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(loaded))+ )++ result = hw.get_visible_gpu_utilization()+ by_idx = {d["index"]: d for d in result["devices"]}+ assert by_idx[0]["vram_used_gb"] == pytest.approx(40.0, abs = 0.01)+ assert by_idx[1]["vram_used_gb"] == pytest.approx(0.5, abs = 0.01)+ assert result["vram_used_gb_aggregate"] == pytest.approx(40.5, abs = 0.01)+ assert result["vram_used_gb_aggregate"] == pytest.approx(+ sum(d["vram_used_gb"] for d in result["devices"]), abs = 0.01+ )+++def test_no_aggregate_when_the_counter_is_unavailable(win_rocm, monkeypatch):+ """A localized or missing counter set stays Unknown rather than becoming 0: that+ fabricated zero is the #7072 symptom this pair started from."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(REPORTER_DEVICES, free_equals_total = True))+ monkeypatch.setattr(hw.subprocess, "run", _subprocess_run(adapter_output = "__NONE__\n"))++ result = hw.get_visible_gpu_utilization()+ assert len(result["devices"]) == 2+ assert result["vram_used_gb_aggregate"] is None+++# ----------------------------------------------------------------------------- #+# The aggregate rule itself (pure unit)+# ----------------------------------------------------------------------------- #+def test_aggregate_requires_a_counter_per_visible_device():+ agg = hw._rocm_windows_aggregate_used_bytes+ # One counter per visible card: the sum is the visible set's, whatever the pairing.+ assert agg([0.22 * GB, 0.14 * GB], [45 * GB, 8 * GB]) == pytest.approx(0.36 * GB)+ # Two identical cards make the ranking degenerate, and the sum does not care.+ assert agg([10 * GB, 3 * GB], [24 * GB, 24 * GB]) == pytest.approx(13 * GB)+ # Fewer counters than cards: a card has no reading, so the sum is not the total.+ assert agg([5 * GB], [45 * GB, 8 * GB]) is None+ # More counters than visible cards: an adapter in the list is not one of ours.+ assert agg([40 * GB, 7 * GB, 6 * GB], [45 * GB, 8 * GB]) is None+ assert agg([], [45 * GB, 8 * GB]) is None+ assert agg([1 * GB], []) is None+++def test_aggregate_rejects_a_usage_larger_than_any_visible_card():+ """A masked 45 GiB card at 40 GiB beside a visible idle 8 GiB card: the counts can+ match by accident, but 40 GiB cannot be on an 8 GiB card, so the counter set is+ not the visible set and the sum would be a hidden GPU's."""+ agg = hw._rocm_windows_aggregate_used_bytes+ assert agg([40 * GB, 10 * MiB], [8 * GB]) is None+ assert agg([40 * GB, 6 * GB], [45 * GB, 4 * GB]) is None+ # Counter order must not matter.+ assert agg([6 * GB, 40 * GB], [45 * GB, 4 * GB]) is None+++def test_aggregate_never_sums_bytes_that_are_not_on_a_visible_card():+ """The reason an unexplained instance is refused rather than filtered out.++ ``Get-Counter`` lists every WDDM adapter and the instance names carry no vendor,+ LUID or PCI key, so a counter cannot be told apart from a foreign adapter's.+ Dropping the small ones to force a 1:1 count keeps the foreign reading and drops+ the quiet visible card whenever the foreign adapter is the busier of the two, and+ the host total then reports bytes on no visible card. Each case below is one that+ a noise filter would have summed.+ """+ agg = hw._rocm_windows_aggregate_used_bytes+ pair = [45 * GB, 8 * GB]+ # A third AMD card hidden by HIP_VISIBLE_DEVICES, busy at 5 GiB, while the+ # visible 8 GiB card idles below the 64 MiB noise floor. Truth is 30.03 GiB.+ assert agg([30 * GB, 5 * GB, 30 * MiB], pair) is None+ # An NVIDIA card in the same box. Truth is 30.02 GiB.+ assert agg([30 * GB, 6 * GB, 20 * MiB], pair) is None+ # An integrated display GPU holding a 1 GiB carveout. Truth is 30.01 GiB.+ assert agg([30 * GB, 1 * GB, 10 * MiB], pair) is None+ # A Basic Render Driver / Remote Display placeholder ABOVE the cutoff.+ assert agg([30 * GB, 200 * MiB, 20 * MiB], pair) is None+ # One visible card, idle, beside a busy foreign adapter: the worst case, since+ # a single card's capacity admits almost any foreign reading. Truth is 30 MiB.+ assert agg([6 * GB, 30 * MiB], [45 * GB]) is None+ assert agg([6 * GB, 30 * MiB, 3 * MiB], [45 * GB]) is None+++def test_aggregate_is_stable_across_a_changing_instance_list(win_rocm, monkeypatch):+ """Counters come and go between polls (a placeholder adapter appears, a card is+ masked mid-session). Every poll is judged on its own list, so the tile alternates+ between the real figure and Unknown, never between two figures."""+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(REPORTER_DEVICES, free_equals_total = True))+ polls = [+ (IDLE_ADAPTERS, pytest.approx(0.36, abs = 0.01)),+ (IDLE_ADAPTERS + [("luid_0x00000000_0x0000f001_phys_0", 3 * MiB)], None),+ (IDLE_ADAPTERS + [("luid_0x00000000_0x0000f002_phys_0", 2.0 * GB)], None),+ (IDLE_ADAPTERS, pytest.approx(0.36, abs = 0.01)),+ ]+ for adapters, expected in polls:+ monkeypatch.setattr(+ hw.subprocess, "run", _subprocess_run(adapter_output = _adapter_output(adapters))+ )+ result = hw.get_visible_gpu_utilization()+ assert result["vram_used_gb_aggregate"] == expected+++def test_aggregate_tolerates_a_wddm_spill_over_the_smaller_card(win_rocm, monkeypatch):+ """WDDM satisfies an overrun from host RAM, so a usage can exceed the card it sits+ on. That only has to not fabricate a number: a reading above the LARGEST visible+ capacity is refused, one that still fits the ranking is summed as reported."""+ agg = hw._rocm_windows_aggregate_used_bytes+ assert agg([9 * GB, 0.3 * GB], [45 * GB, 8 * GB]) == pytest.approx(9.3 * GB)+ assert agg([46 * GB, 2 * GB], [45 * GB, 8 * GB]) is None+++# ----------------------------------------------------------------------------- #+# The aggregate and the rows have to describe the same cards+# ----------------------------------------------------------------------------- #+++def _merged_gpu_info(monkeypatch, visibility, utilization):+ """Run main's payload merge over two stubbed probes and return the training half.++ Both probes are function-local imports from utils.hardware, so they are patched on+ the package. The module-level cache is cleared first, or a neighbouring test's+ payload comes back instead.+ """+ import main+ import utils.hardware as uh++ monkeypatch.setattr(uh, "get_backend_visible_gpu_info", lambda: visibility)+ monkeypatch.setattr(uh, "get_visible_gpu_utilization", lambda: utilization)+ monkeypatch.setattr(main, "_system_gpu_cache", None, raising = False)+ gpu_info, _ = main._get_cached_system_gpu_info(main.logger)+ return gpu_info+++def _probe_pair(visible_indices, util_indices, aggregate):+ visibility = {+ "available": True,+ "backend": "rocm",+ "devices": [+ {"index": i, "name": f"card{i}", "memory_total_gb": 45.0 if i == 0 else 7.98}+ for i in visible_indices+ ],+ }+ utilization = {+ "backend": "rocm",+ "devices": [{"index": i, "vram_used_gb": None} for i in util_indices],+ "vram_used_gb_aggregate": aggregate,+ }+ return visibility, utilization+++def test_aggregate_is_dropped_when_the_probes_enumerate_different_cards(monkeypatch):+ """The tile divides the aggregate by the SUMMED totals of the rows it shows, so a+ total taken over cards the rows do not list reads above 100 percent and free+ clamps to 0. metrics_match cannot catch it: on the only path that sets an+ aggregate, Windows ROCm, both probes label themselves "rocm", so it is+ unconditionally true and says nothing about which cards were counted. The probes+ really do enumerate independently -- visibility calls mem_get_info per device and+ drops one that raises, the aggregate side reads torch properties only and keeps+ it -- so the sets can differ with both probes reporting success.+ """+ visibility, utilization = _probe_pair([0], [0, 1], 46.0)+ gpu_info = _merged_gpu_info(monkeypatch, visibility, utilization)+ shown_total = sum(d["memory_total_gb"] for d in gpu_info["devices"])+ assert utilization["vram_used_gb_aggregate"] > shown_total # the wrong number+ assert gpu_info["vram_used_gb_aggregate"] is None+++def test_aggregate_survives_when_both_probes_name_the_same_cards(monkeypatch):+ """The reporter's own host, and the case the fix exists for: identical index+ sets, so the aggregate is a total over exactly the rows on screen."""+ visibility, utilization = _probe_pair([0, 1], [0, 1], 0.36)+ gpu_info = _merged_gpu_info(monkeypatch, visibility, utilization)+ assert gpu_info["vram_used_gb_aggregate"] == 0.36+++def test_aggregate_is_dropped_when_the_sets_merely_overlap(monkeypatch):+ """Equal counts are not enough. Two cards each, but index 1 against index 2:+ the aggregate counts a card that has no row, and a row has no counter."""+ visibility, utilization = _probe_pair([0, 1], [0, 2], 46.0)+ gpu_info = _merged_gpu_info(monkeypatch, visibility, utilization)+ assert gpu_info["vram_used_gb_aggregate"] is Nonediff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex f951596aeb9..61497819961 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -1057,11 +1057,35 @@ def _torch_get_physical_gpu_count() -> Optional[int]:return None+def rocm_windows_free_is_untrusted() -> bool:+ """Whether ``mem_get_info``'s FREE half must be treated as an over-report.++ AMD documents this: the hipMemGetInfo reference warns "On Windows, the free+ memory only accounts for memory allocated by this process and may be optimistic."+ WDDM virtualises video memory, so a process is told its own budget rather than+ the card's residency and a fresh process sees free at or near total whatever else+ is resident. An AMD engineer confirms in ROCm/librocdxg#57 that this is the+ intended Windows model rather than a defect, measuring 24410 MiB of 24560+ reported free on a deliberately filled card; ROCm/TheRock#3724 is the same+ symptom, torch OOM while reporting 52.71 GiB of a 53.92 GiB card free.++ Near ``total``, not equal to it, so callers cap instead of testing for a+ sentinel. The TOTAL half is fine. Every other platform is left alone, WSL+ included and deliberately: AMD keeps the WSL2 reading consistent with native+ Linux, where free tracks physical residency, and ``sys.platform`` is "linux"+ there, so this is False and the accurate figure passes through uncapped. One+ predicate for the whole backend (#7452 reporting side, #8403 guard side).+ """+ return sys.platform == "win32" and IS_ROCM++def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]]:"""Query torch for per-GPU name, total VRAM, and used VRAM.- ``used_gb`` is ``None`` on Windows ROCm when ``hipMemGetInfo`` reports- ``free == total`` (ROCm/ROCm#1909): that 0 means unknown, not empty.+ ``used_gb`` is ``None`` on Windows ROCm when the driver reports ``free ==+ total``: that 0 means unknown, not empty. This is the DISPLAY path, so unknown+ rather than a pessimistic ceiling, which is the right answer for a refusal and+ the wrong one for a number shown to the user as measured."""mod, _ = _torch_get_device_module()if mod is None:@@ -1069,7 +1093,7 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]device = get_device()# free==total is a Windows-ROCm-only quirk.- _win_rocm = sys.platform == "win32" and IS_ROCM+ _win_rocm = rocm_windows_free_is_untrusted()devices = []for ordinal, phys_idx in enumerate(device_indices):try:@@ -1567,19 +1591,75 @@ def _match_adapter_used_to_devices(return assigned-def _rocm_windows_per_device_vram(device_indices: list[int]) -> list[Dict[str, Any]]:+def _rocm_windows_aggregate_used_bytes(+ adapter_useds: list[float], device_totals: list[float]+) -> Optional[float]:+ """Total VRAM used across the visible devices, when the counters cover them 1:1.++ Per-device attribution needs capacity to FORCE a pairing, and on an asymmetric+ pair (45 GiB + 8 GiB) nothing at or below 8 GiB is forced, so idle and every+ small model report unknown (#7452). The SUM does not need the pairing -- over a+ bijection it is the same whichever way round the usages go -- so the System tab+ keeps a real figure where per-device honestly cannot. Emitted only when the+ counter list IS the visible set, established by cardinality alone. That rests on+ one ASSUMPTION, stated as such because it is not confirmed against Microsoft's+ counter documentation: that ``Get-Counter`` emits exactly one instance per WDDM+ adapter, so a visible card is always in the list and a list exactly as long as+ 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.++ 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,+ which only ever emits a capacity-FORCED value, but not for a sum, which emits+ every counter it kept. The counters carry no vendor, LUID or PCI key, so a+ retained counter cannot be told apart from a foreign adapter: a card hidden by+ ``HIP_VISIBLE_DEVICES``, an iGPU, an NVIDIA card in the same box or a Basic+ Render Driver placeholder above the cutoff. Whenever such an adapter is busier+ than one visible card is idle, the filter drops the visible card and keeps the+ foreign one, and the sum silently gains bytes on no visible card at all. A host+ total that is confidently wrong is worse than Unknown, so an unexplained instance+ means ``None``. Extra instances are common, so this is narrow on purpose;+ widening it needs the counters joined to devices on LUID or PCI bus id rather+ than on capacity rank, the same key _match_adapter_used_to_devices lacks.+ """+ n = len(device_totals)+ if n == 0 or not adapter_useds:+ return None+ # More counters than devices: one is not ours, and no key says which. Fewer: a+ # visible card has no reading. Either way the sum is not the visible set's.+ if len(adapter_useds) != n:+ return None+ useds = sorted(adapter_useds, reverse = True)+ ranked_totals = sorted(device_totals, reverse = True)+ # A usage above its ranked capacity is on no visible card, so even at matching+ # length the list is not the visible set (a reading was dropped while parsing, or+ # a counter is not a dedicated-VRAM figure).+ for rank in range(n):+ if useds[rank] > ranked_totals[rank]:+ return None+ return float(sum(useds))+++def _rocm_windows_per_device_vram(+ device_indices: list[int],+) -> 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.- Returns ``{index, visible_ordinal, name, used_gb, total_gb}`` per visible GPU- (``used_gb`` may be ``None`` when the counter is unavailable), or ``[]`` when- torch can't enumerate devices so callers fall through to the torch last resort.+ 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."""if platform.system() != "Windows":- return []+ return [], Nonemod, _ = _torch_get_device_module()if mod is None:- return []+ return [], None# Totals/names from torch properties (mem_get_info's free==total quirk zeroes used).dev_meta: list[Dict[str, Any]] = []for ordinal, phys_idx in enumerate(device_indices):@@ -1596,14 +1676,17 @@ def _rocm_windows_per_device_vram(device_indices: list[int]) -> list[Dict[str, Aexcept Exception as e:logger.debug("torch property probe failed for ordinal %d: %s", ordinal, e)if not dev_meta:- return []+ return [], Noneadapters = _rocm_windows_perf_counter_vram_by_adapter()+ aggregate_gb: Optional[float] = Noneif adapters:- assigned = _match_adapter_used_to_devices(- [used for _, used in adapters],- [d["total_bytes"] for d in dev_meta],- )+ 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)+ if aggregate_bytes is not None:+ aggregate_gb = round(aggregate_bytes / (1024**3), 2)else:# Counter unavailable: show every GPU with a correct total, used unknown.assigned = [None] * len(dev_meta)@@ -1621,7 +1704,7 @@ def _rocm_windows_per_device_vram(device_indices: list[int]) -> list[Dict[str, A"total_gb": total_gb,})- return devices+ return devices, aggregate_gbdef _rocm_windows_device_payload_entry(@@ -1718,7 +1801,7 @@ def get_gpu_utilization() -> Dict[str, Any]:_win_ids = _get_parent_visible_gpu_spec().get("numeric_ids")if not _win_ids:_win_ids = list(range(_torch_get_physical_gpu_count() or 0))- _win_devices = _rocm_windows_per_device_vram(_win_ids)+ _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.@@ -1731,6 +1814,7 @@ def get_gpu_utilization() -> Dict[str, Any]:_rocm_windows_device_payload_entry(device, _wd, _win_util)for _wd in _win_devices],+ vram_used_gb_aggregate = _win_aggregate,)# Fallback Linux ROCm@@ -2040,7 +2124,7 @@ def get_visible_gpu_utilization() -> Dict[str, Any]:else:win_ids = list(range(_torch_get_physical_gpu_count() or 0))win_index_kind = "relative"- win_devices = _rocm_windows_per_device_vram(win_ids)+ win_devices, win_aggregate = _rocm_windows_per_device_vram(win_ids)if win_devices:devices = []for wd in win_devices:@@ -2070,6 +2154,9 @@ def get_visible_gpu_utilization() -> Dict[str, Any]:"parent_visible_gpu_ids": win_numeric_ids or [],"devices": devices,"index_kind": win_index_kind,+ # Host total for the System tab tile: known even when no single+ # device's usage is attributable (#7452).+ "vram_used_gb_aggregate": win_aggregate,}# Torch-based fallback for CUDA (nvidia-smi unavailable, AMD ROCm) and XPU (Intel)diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsxindex 74b3696f610..45a0e22a534 100644--- a/studio/frontend/src/components/floating-monitor.tsx+++ b/studio/frontend/src/components/floating-monitor.tsx@@ -7,6 +7,7 @@ import {useMonitorFrameStore,useMonitorOverlayStore,} from "@/features/settings";+import { resolveGpuVramUsedGb } from "@/hooks/gpu-vram";import { aggregateGpuMemoryTotalGb, useSystemInfo } from "@/hooks/use-system";import { useT } from "@/i18n";import {@@ -465,14 +466,11 @@ function FloatingMonitorPanel({: 0;const devices = displayedGpu?.devices ?? [];const vramTotal = aggregateGpuMemoryTotalGb(devices);- // null usage = unknown (e.g. Windows ROCm perf counter): treating it as 0- // fabricates a 0-used readout, so the aggregate is unknown if any device is.- const vramUsageKnown =- devices.length > 0 &&- devices.every((device) => Number.isFinite(device.vram_used_gb));- const vramUsed = vramUsageKnown- ? devices.reduce((sum, device) => sum + (device.vram_used_gb ?? 0), 0)- : 0;+ // null usage = unknown (e.g. Windows ROCm perf counter); 0 would fabricate a+ // readout. The host figure can still be known when no device's is (#7452).+ const resolvedVramUsed = resolveGpuVramUsedGb(displayedGpu);+ const vramUsageKnown = resolvedVramUsed !== null;+ const vramUsed = resolvedVramUsed ?? 0;const vramPercent = clampPercent(vramUsageKnown && vramTotal > 0 ? (vramUsed / vramTotal) * 100 : 0,);diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsxindex a64ab241513..703266bc626 100644--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx@@ -10,6 +10,10 @@ import {openModelsDir,pickHuggingFaceCacheDir,} from "@/features/native-intents";+import {+ gpuVramUsedIsPerDevice,+ resolveGpuVramUsedGb,+} from "@/hooks/gpu-vram";import {aggregateGpuMemoryTotalGb,useSystemInfo,@@ -238,15 +242,13 @@ export function ResourcesTab() {const diskFree = systemInfo.disk?.free_gb ?? 0;const diskUsed = Math.max(0, diskTotal - diskFree);const vramTotal = aggregateGpuMemoryTotalGb(devices);- // null usage = unknown (e.g. Windows ROCm perf counter): treating it as 0- // fabricates a 0-used total, so the aggregate is unknown if any device is.- const vramUsageKnown =- devices.length > 0 &&- devices.every((device) => isFiniteNumber(device.vram_used_gb));- const vramUsed = vramUsageKnown- ? devices.reduce((sum, device) => sum + (device.vram_used_gb ?? 0), 0)- : null;- const vramFree = vramUsageKnown+ // null usage = unknown (e.g. Windows ROCm perf counter); 0 would fabricate a+ // total, so the device's own row stays unknown. The host figure can still be+ // known when no device's is (#7452).+ const perDeviceKnown = gpuVramUsedIsPerDevice(devices);+ const vramUsed = resolveGpuVramUsedGb(displayedGpu);+ const vramUsageKnown = vramUsed !== null;+ const vramFree = perDeviceKnown? devices.reduce((sum, device) =>sum +@@ -257,7 +259,9 @@ export function ResourcesTab() {)),0,)- : null;+ : vramUsed !== null+ ? Math.max(0, vramTotal - vramUsed)+ : null;const vramPercent =vramUsageKnown && isFiniteNumber(vramUsed) && vramTotal > 0? (vramUsed / vramTotal) * 100diff --git a/studio/frontend/src/hooks/gpu-vram.ts b/studio/frontend/src/hooks/gpu-vram.tsnew file mode 100644index 00000000000..137a7d8d4f6--- /dev/null+++ b/studio/frontend/src/hooks/gpu-vram.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Split out of use-system.ts so the VRAM rules can be unit tested without pulling+// the auth and React graph in behind them. Typed structurally, so SystemGpuInfo and+// GpuDevice satisfy these without importing them.++export interface VramReportingDevice {+ vram_used_gb?: number;+}++export interface VramReportingGpu {+ devices?: VramReportingDevice[];+ /** Used VRAM across the visible GPUs when no single device's usage could be+ * attributed. Windows ROCm only; null everywhere else. See #7452. */+ vram_used_gb_aggregate?: number | null;+}++/** Whether every device reports its own usage, so each row and their sum are real. */+export function gpuVramUsedIsPerDevice(+ devices: VramReportingDevice[],+): boolean {+ return (+ devices.length > 0 &&+ devices.every((device) => Number.isFinite(device.vram_used_gb))+ );+}++/** Used VRAM across the GPUs, or null when it is genuinely unknown.+ *+ * Per-device usage is preferred. On Windows ROCm nothing keys the LUID usage+ * counters to torch ordinals, so a usage that fits more than one card cannot be+ * attributed to either and every device reports unknown -- which is idle and every+ * small model on an asymmetric pair. The sum does not depend on that attribution,+ * so the backend still reports it, and rendering Unknown for a figure it already+ * has is what #7452 was.+ *+ * Never falls back to 0: a fabricated 0 used / full free is the #7072 symptom. */+export function resolveGpuVramUsedGb(+ gpu: VramReportingGpu | null | undefined,+): number | null {+ const devices = gpu?.devices ?? [];+ if (gpuVramUsedIsPerDevice(devices)) {+ return devices.reduce((sum, device) => sum + (device.vram_used_gb ?? 0), 0);+ }+ const aggregate = gpu?.vram_used_gb_aggregate;+ return Number.isFinite(aggregate) ? (aggregate as number) : null;+}diff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.tsindex e6a6b756177..97a105d13eb 100644--- a/studio/frontend/src/hooks/use-system.ts+++ b/studio/frontend/src/hooks/use-system.ts@@ -21,6 +21,9 @@ export interface GpuDevice {export interface SystemGpuInfo {available: boolean;backend?: string;+ /** Used VRAM across the visible GPUs when no single device's usage could be+ * attributed. Windows ROCm only; null everywhere else. See #7452. */+ vram_used_gb_aggregate?: number | null;/** Whether GGUF loads accept explicit gpu_ids in the device records'* declared index space. */gguf_gpu_ids_supported?: boolean;diff --git a/studio/frontend/tests/rocm-windows-vram-aggregate.test.ts b/studio/frontend/tests/rocm-windows-vram-aggregate.test.tsnew file mode 100644index 00000000000..e3c8f884b0c--- /dev/null+++ b/studio/frontend/tests/rocm-windows-vram-aggregate.test.ts@@ -0,0 +1,96 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ gpuVramUsedIsPerDevice,+ resolveGpuVramUsedGb,+ type VramReportingDevice,+ type VramReportingGpu,+} from "../src/hooks/gpu-vram.ts";++// The payload as /api/system sends it: the helpers read two fields structurally and+// the rest ride along, which is what the tile gets.+interface SystemGpuPayload extends VramReportingGpu {+ available: boolean;+ backend?: string;+ devices?: (VramReportingDevice & {+ index?: number;+ name?: string;+ memory_total_gb?: number;+ })[];+}++// Issue #7452: a Windows 10 ROCm host, AMD Radeon PRO W7900 (45 GiB) beside a W7500+// (7.98 GiB). Nothing keys the LUID VRAM counters to torch ordinals, so a usage that+// fits both cards reads Unknown on every device -- idle and every small model here.+// The backend still knows the host total; the tile rendered Unknown anyway.+function reporterGpu(+ overrides: Partial<SystemGpuPayload> = {},+): SystemGpuPayload {+ return {+ available: true,+ backend: "rocm",+ devices: [+ { index: 0, name: "AMD Radeon PRO W7900", memory_total_gb: 45.0 },+ { index: 1, name: "AMD Radeon PRO W7500", memory_total_gb: 7.98 },+ ],+ vram_used_gb_aggregate: 0.36,+ ...overrides,+ };+}++test("unattributable per-device usage still reports the host total", () => {+ assert.equal(resolveGpuVramUsedGb(reporterGpu()), 0.36);+ assert.equal(gpuVramUsedIsPerDevice(reporterGpu().devices ?? []), false);+});++test("per-device usage wins over the aggregate when every device reports", () => {+ const gpu: SystemGpuPayload = reporterGpu({+ devices: [+ {+ index: 0,+ memory_total_gb: 45.0,+ vram_used_gb: 40.0,+ },+ { index: 1, memory_total_gb: 7.98, vram_used_gb: 0.5 },+ ],+ // Deliberately NOT 40.5: an aggregate equal to the per-device sum would pass+ // whichever source won, so it would not pin the precedence at all.+ vram_used_gb_aggregate: 99.0,+ });+ assert.equal(gpuVramUsedIsPerDevice(gpu.devices ?? []), true);+ assert.equal(resolveGpuVramUsedGb(gpu), 40.5);+});++test("a partially attributed pair falls back to the aggregate, not a short sum", () => {+ // 40 GiB is capacity-forced onto the W7900, the idle card's 0.5 GiB is not;+ // summing the known half alone would under-report the tile by that card.+ const gpu: SystemGpuPayload = reporterGpu({+ devices: [+ { index: 0, memory_total_gb: 45.0, vram_used_gb: 40.0 },+ { index: 1, memory_total_gb: 7.98 },+ ],+ vram_used_gb_aggregate: 40.5,+ });+ assert.equal(resolveGpuVramUsedGb(gpu), 40.5);+});++test("no aggregate stays unknown rather than becoming zero", () => {+ // A fabricated 0 used / full free is exactly what #7072 reported.+ assert.equal(+ resolveGpuVramUsedGb(reporterGpu({ vram_used_gb_aggregate: null })),+ null,+ );+ assert.equal(+ resolveGpuVramUsedGb(reporterGpu({ vram_used_gb_aggregate: undefined })),+ null,+ );+ assert.equal(resolveGpuVramUsedGb(null), null);+ assert.equal(+ resolveGpuVramUsedGb({ devices: [] }),+ null,+ );+});