Repository navigation
fix(hardware): report driver-level free VRAM in the GPU summary - #9362
Conversation
get_gpu_memory_info computed free as total - torch-allocated, which sees neither this process's reserved cache nor any other process's allocations: the summary could report a card as free while a model was resident. The summary feeds /system-info, whose consumers include training-method auto-selection — an overstated free picks a method that OOMs on launch. The CUDA and XPU paths now take free from trusted_mem_get_info (the driver figure, with the platform's free over-report caps already applied by that helper — Windows ROCm WDDM), falling back to total - reserved when the probe fails; reserved includes allocated, so the fallback bound is tighter than the old allocated-only figure. allocated/reserved/ utilization semantics are unchanged, and the MLX path (AGX usage against unified memory) keeps its existing shape.
|
Confirmed this hits studio/backend/utils/hardware/hardware.py where free_gb is still total minus allocated at all three sites, so a card with a model resident reports as free to /system-info and its consumers. Will get this reviewed. |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Windows + AMD ROCm run: the Windows leg does not workRan it. The headline is the one you were worried about: The box is an APU rather than a discrete card, so it takes the I ran everything twice on separate invocations. Both runs agree to the last digit, so none of this is a single-sample artifact. 1. Does
|
free_gb |
mem_get_info |
perf dedicated | |
|---|---|---|---|
| idle | 89.31 | 89.31 | 1.96 |
| self holds 4 GiB | 85.29 | 85.29 | 5.99 |
| self released | 89.04 | 89.04 | 6.00 |
| other holds 4 GiB | 89.04 | 89.04 | 10.20 |
| other released | 89.04 | 89.04 | 5.98 |
free_gb tracks this process at −4.02 GiB and another at exactly 0.00. So hipMemGetInfo is working, it is simply scoped to the calling process on WDDM.
The useful part: the perf counters did see it, +4.22 GiB, reversing cleanly on release. Windows needs a different source, not no source.
2. amd-smi: zero spawns, and the elevation premise is real
_amd_smi_allowed() returns False here, and get_gpu_summary() spawned amd-smi 0 times as configured and 0 times with UNSLOTH_ENABLE_AMD_SMI=0.
Not a vacuous zero. This box is the configuration you said the script cannot manufacture: amd-smi is on PATH at C:\windows\system32\amd-smi.EXE, and no HIP SDK is present, so the guard refused on its own merits rather than for lack of a binary.
On the observation you said the script can't make for you — I invoked amd-smi directly from a shell, deliberately bypassing the guard. It hung with no output, and consent.exe appeared with the window title:
DiskPart is requesting your permission
That is #5940 and #6296, reproduced on real hardware. __COMPAT_LAYER=RunAsInvoker did not suppress it, which confirms your reading of the asInvoker manifest.
Be clear about the direction of that result, because it is easy to misread: Studio did not pop that prompt, I did. It establishes that there is something real behind the guard, not that anything reaches around it. I re-ran both scripts afterwards from a clean baseline of zero consent.exe, watching the screen, and neither produced a single dialog or a single amd-smi process.
3. Gate values
IS_ROCM true
rocm_windows_free_is_untrusted true
rocm_props_total_is_carve_out true
rocm_device_ordinal_active false
amd_smi_allowed false
HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / GPU_DEVICE_ORDINAL
/ CUDA_VISIBLE_DEVICES / UNSLOTH_ENABLE_AMD_SMI all unset
rocm_windows_free_is_untrusted is True, so the WDDM cap did execute — and was a no-op, since free_gb equals mem_get_info free exactly.
A bug in the check script itself
Worth fixing before anyone else runs it. windows_rocm_vram_check.py never calls detect_hardware(), so hw.IS_ROCM is still the module-level default. My first run reported:
IS_ROCM false
rocm_windows_free_is_untrusted false
rocm_props_total_is_carve_out false
on a machine where all three are True. Every ROCm gate was dead, and the script measured the non-ROCm path while presenting the result as a Windows ROCm reading. It prints the same PASS/FAIL either way, so there is nothing in the output to catch it.
I re-ran with hw.detect_hardware() called first. The gates then read as in section 3, and the VRAM numbers were identical, so the conclusion above stands. But as it is, this script will collect gate dumps from other people that describe a branch their machine never executed.
Summary
- The core claim does not hold on Windows.
free_gbis process-local viahipMemGetInfoon WDDM, exactly as you predicted, and nothing in the suite catches it. - A working Windows source exists: the WDDM
\GPU Process Memoryperf counters tracked another process's 4 GiB accurately and reversibly. - The amd-smi guard is correct and its premise is real. Zero spawns on the genuine no-SDK box; the DiskPart prompt is reproducible when the guard is bypassed by hand.
- Add
detect_hardware()to the check script.
Happy to run anything else on this box, including a forced UNSLOTH_ENABLE_AMD_SMI=1 leg if you want the prompt observed coming from Studio's own call path rather than from a manual invocation.
Follow-up on the same box: amd-smi is worse than described, and a working no-UAC source is already in this PRSame machine as my previous comment — gfx1151 Strix Halo APU, Windows 11, torch 2.11.0+rocm7.13.0, Nothing below retracts anything in that comment. Two additions. 1. The UAC prompt is 5 for 5, and amd-smi cannot do anything anywayI invoked amd-smi four more times by hand, deliberately bypassing And all four popped a DiskPart UAC prompt, confirmed by the human at the keyboard. With the one from my earlier comment that is 5 invocations, 5 prompts. Correction to my own method, since it affects how much weight to put on this: I had been checking for the prompt by polling The new part is the pairing of those two facts. amd-smi elevates first and fails to load its library second, so on this configuration it costs a UAC dialog and returns nothing whatsoever. Worth noting where the exposure actually is: this box is an APU, so 2.
|
| dedicated | +shared | derived free | hip_free |
PR's used_gb |
|
|---|---|---|---|---|---|
| idle | 1.22 | 1.38 | 88.09 | 89.31 | None |
| other holds 4 GiB | 5.54 | 5.77 | 83.70 | 89.31 | None |
| released | 1.36 | 1.54 | 87.93 | 89.31 | None |
+4.32 GiB dedicated when another process allocates, reversing cleanly on release. That is precisely the cross-process visibility this PR exists to get, and hip_free sits at 89.31 through all three, blind as ever. Cost is about 1.3 s per Get-Counter sample, zero consent.exe, zero amd-smi spawns, across three separate runs.
get_gpu_memory_info still returns None for it, for two independent reasons that both have to go.
a. The APU gate skips the probe entirely. _rocm_props_total_is_carve_out(props) is True, so _context_free_cuda_memory_info is never called. Your reasoning for that is sound as far as the total goes — dedicated usage is the carve-out and a driver total would budget this 89 GiB part as about 8 GiB. But the ladder only needs used from telemetry; the total already comes from torch inside _free_in_torch_scope(total_bytes, used_gb). Skipping the probe to protect the total discards the used figure with it. Splitting those two would light this path up on every unified-memory ROCm part.
b. The matcher cannot attribute on a single-GPU host. In _match_adapter_used_to_devices, with n = 1:
for rank, pos in enumerate(ranked_positions):
if rank + 1 < n and ranked_useds[rank] > ranked_totals[rank + 1]:
assigned[pos] = min(ranked_useds[rank], device_totals[pos])rank + 1 < 1 is never true, so assigned stays [None]. The docstring explains that the smallest card stays unknown because capacity cannot force it — but with one visible device and exactly one supra-threshold counter there is nowhere else the usage can go. It is forced by cardinality rather than by capacity, and that case currently falls through. This host emits 3 counter instances, two of them at 0.00 dedicated, which the 64 MiB threshold filters to exactly 1:
luid_0x00000000_0x0001544a_phys_0|1292292096
luid_0x00000000_0x0001715a_phys_0|0
luid_0x00000000_0x000171ac_phys_0|0
_rocm_windows_aggregate_used_bytes also returns None, for a different reason: it requires len(adapter_useds) == n before any noise filter, and 3 != 1.
Net effect is that single-GPU Windows — the common case — cannot get a per-device used figure from this path at all.
Scope of the claim
- The LUID-to-torch-ordinal join is genuinely unsolved for multi-GPU and I am not suggesting otherwise. The counters carry no vendor, LUID or PCI key to match on, and your docstring is right about that. My claim is narrow: n = 1 is trivially safe and is currently rejected along with the hard cases.
- Which figure is correct on a unified-memory APU, dedicated alone or dedicated+shared for that one LUID, I have not established. Both track the holder (+4.32 and +4.39 respectively). Summing across adapters is definitely wrong —
0x171acreports 1.30 GiB shared and 0 dedicated and is not the compute device. - 1.3 s per sample is fine for the Resources tab and too slow for the 3 s/5 s
/api/systempoll without caching.
Happy to put up a patch for (a) and (b) and test it against a holder here, but the APU total/used split looks like your design call rather than mine, so I would rather you say which way you want it first.
Consolidated Windows + AMD ROCm report, and a UAC-free path that worksEverything from my two earlier comments in one place, plus a new result: a system-wide VRAM source on Windows that needs no elevation, no amd-smi, and costs under a millisecond per read. That last part is new and is the actionable half. Machine, throughout: That last line matters: this is the driver-but-no-SDK configuration you said the script could not manufacture. 1. The core claim does not hold on Windows
This is your first branch, not your second: Control the script lacks. "Free never moves" and "free is process-local" look identical in your output, so I added a leg where the observer itself allocates:
2. amd-smi: 5 UAC prompts for 5 invocations, and zero useful output
I then invoked amd-smi by hand five times total, bypassing the guard, using the subcommands this PR's new call sites actually reach: Every one popped a DiskPart UAC prompt, confirmed by the human at the keyboard: 5 invocations, 5 prompts. Correction to my own method, since it bears on how much to trust the above. I had been detecting the prompt by polling The load-bearing new fact is the pairing: amd-smi elevates first and fails to load its library second. On this configuration it costs a UAC dialog and returns nothing at all. Where the real exposure is: this box is an APU, so 3. Gate values
4. Bug in the check script
Re-running with 5. How to get this without UACThe source is already wired into this PR through
+4.32 GiB when another process allocates, reversing on release — the cross-process visibility this PR exists to get. Zero Skip PowerShell: read PDH directly
Measured here:
That makes this cheap enough to sit on the fast poll, which Two blockers, both of which have to goa. The APU gate skips the probe entirely. b. The matcher cannot attribute on a single-GPU host. In for rank, pos in enumerate(ranked_positions):
if rank + 1 < n and ranked_useds[rank] > ranked_totals[rank + 1]:
assigned[pos] = min(ranked_useds[rank], device_totals[pos])
Net effect: single-GPU Windows, the common case, cannot get a per-device used figure from this path at all. 6. Scope of what I am claiming
7. Suggested shape
Happy to put up a patch for 2-4 and test it against a holder on this box. The APU total/used split reads like your design call rather than mine, so say which way you want it and I will follow. |
IS_ROCM is False at import and only set by detect_hardware(), so the gate dump reported every ROCm branch as inactive on a ROCm box. Adds the call and a self-check that fails when a ROCm torch build still reads IS_ROCM False, so a stale dump cannot pass silently.
|
This is the run the PR needed, and both findings hold up. I reproduced the two code claims locally rather than take them on trust, and one of them is narrower than stated in a way that makes the fix smaller. The script bug was mineCorrect and my fault. Fixed in Your correction of your own detector is the more useful half of that. Polling Windows: accepted, and it does not block this PR
To be clear about what it costs though, the Windows path is not made worse by this PR. Before, free was What does need to change is the PR description, which currently implies cross-process visibility everywhere. I will scope that to Linux explicitly. amd-smi: the LoadLibraryA pairing changes the argumentFive for five with a human watching, on a box that genuinely has amd-smi on PATH and no SDK, is much better evidence than my simulation. And you are right that the pairing is the interesting part: every one of those invocations elevated and then failed to load its library. So the guard is not trading a prompt for telemetry, it is refusing a prompt that returns nothing at all. I will move that into Your point about where the exposure actually lives is the one I would have missed. This box is an APU, so The two changes: yes to both(a) Split the APU total from the APU usedAgreed, and this is my design call to make so I will state it rather than leave it open. The gate exists to protect the total: dedicated usage is the carve-out, and adopting a driver total would budget this 89 GiB part at about 8 GiB. But the ladder only ever needs used from telemetry, because the total already comes from torch inside (b) n = 1, with a correction that shrinks the fixYour diagnosis is right and I reproduced it, but the boundary is not where the comment puts it. The failure is specific to the So the fix is confined to that branch, not to the matcher generally: once the filter has left exactly one supra-threshold counter and exactly one visible device, cardinality forces it and there is nowhere else the usage can go. The multi-GPU LUID join stays unsolved and I am not asking you to touch it. Please do put up the patch. Two things I would like in it:
The one thing I do not want decided by measurement aloneDedicated versus dedicated+shared on a unified-memory part. Both tracked your holder (+4.32 and +4.39), which is exactly why 4 GiB cannot separate them: it fits inside the dedicated carve-out, so both are still linear there. The discriminating test is an allocation comfortably larger than the carve-out, say 16 GiB on this 89 GiB box. If dedicated saturates near the carve-out while shared keeps climbing, dedicated alone is wrong for an APU and the answer is dedicated+shared for the compute LUID. If dedicated keeps tracking, it is the safer figure. Could you run that one? It is the only remaining input I need, and I would rather not guess it. Agreed on the rest: summing across adapters is wrong, No need for the forced |
Patch for (a) and (b), plus the carve-out measurement you asked forRan the discriminating test first, since it changed the shape of the patch. Then implemented both changes and verified them against a holder on the same gfx1151 Strix Halo host. The Windows check script now PASSes. The carve-out measurement: it is dedicated+sharedYou were right that 4 GiB could not separate them, and right about the mechanism. Deltas over baseline, PDH, holder in another process:
Dedicated plateaus around 30.5 GiB absolute and the overflow lands in Shared. Only the sum tracks the allocation, across the whole range. So dedicated alone is wrong for an APU, and at 48 GiB held it under-reports by 19 GiB. One correction to an assumption in the thread: the carve-out here is about 30.5 GiB, not "about 8 GiB". The gate is still right to refuse the driver total — 30.5 is not 89.47 — but it is a much larger carve-out than the reasoning assumed. This forced a design point I did not expect. Adapter selection must still key off Dedicated Usage alone. Display and placeholder adapters report 0 dedicated while carrying gigabytes of shared — a Basic Render Driver instance on this host sits at 1.30 GiB shared — so filtering on the sum stops telling them apart from the compute device and would silently add a foreign adapter's bytes. Selection on dedicated, value as the sum. (b) Your stated boundary is not safe, and your own test says soI implemented this, but not where you put the line, because your existing test at # A single visible card with a hidden adapter is never attributable: a fitting
# survivor could be the hidden GPU's while the visible card is idle.
assert hw._match_adapter_used_to_devices([6 * GB, 10 * MiB], [8 * GB]) == [None]"Exactly one supra-threshold counter and exactly one visible device" is precisely that shape, so implementing your rule as stated turns this test red. Cardinality does not force the pairing: the 10 MiB counter can be the visible card sitting idle, which makes the 6 GiB survivor a hidden GPU's. What is safe is narrower — every other counter at exactly zero: if n == 1 and all(u == 0 for u in dropped):
return [min(ranked_useds[0], device_totals[0])]An adapter at exactly zero has nothing committed and cannot be holding the survivor's bytes. A merely sub-floor adapter can. Your host-shape case Residual risk I did not design away, stated rather than buried: the visible card could itself be the zero while a hidden adapter holds the survivor, and then used is over-reported. That errs toward understating free, which is the safe direction given the consumer is training-method selection, where an overstated free picks a method that OOMs. If you would rather have unknown than a conservative figure, say so and I will drop this half. Clamp kept, as requested. (a) The APU splitTotal still from One test of yours changed
Verification on hardwareYour check script, unmodified, on the patched tree: And past the carve-out, which is what the shared handling exists for: Dedicated alone would have reported about +29 there. Suites: 135 passed, 14 skipped across Two notes
You closed with "1.3 s per sample means this belongs on the Resources tab only" — that is the Patch below, against diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.py
index 02c583b2..1defdd76 100644
--- a/studio/backend/tests/test_rocm_windows_vram_7072.py
+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py
@@ -206,12 +206,90 @@ def test_match_adapter_pairs_and_clamps():
assert hw._match_adapter_used_to_devices([40 * GB], [48 * GB, 8 * GB]) == [40 * GB, None]
+def test_match_adapter_pairs_single_device_past_placeholder_adapters():
+ # Exactly the shape a gfx1151 Strix Halo host emits: three counter instances,
+ # two of them placeholders at EXACTLY 0, one visible device. An adapter at zero
+ # has nothing committed and so cannot hold the survivor's bytes, which is what
+ # makes this attributable. Before this, the capacity test needed a next-smaller
+ # device to compare against and discarded the survivor as unknown.
+ assert hw._match_adapter_used_to_devices([1.2 * GB, 0.0, 0.0], [89 * GB]) == [1.2 * GB]
+ # Order of the counters must not matter.
+ assert hw._match_adapter_used_to_devices([0.0, 1.2 * GB, 0.0], [89 * GB]) == [1.2 * GB]
+ # Still clamped: a hidden larger adapter must not report a fully-used card.
+ assert hw._match_adapter_used_to_devices([100 * GB, 0.0, 0.0], [48 * GB]) == [None]
+ assert hw._match_adapter_used_to_devices([40 * GB, 0.0], [48 * GB]) == [40 * GB]
+ # Zero is what makes it attributable, not the cardinality. A merely sub-floor
+ # counter can be the visible card idle, making the survivor a hidden GPU's --
+ # that shape must stay unknown (see the [6 GiB, 10 MiB] case below).
+ assert hw._match_adapter_used_to_devices([1.2 * GB, 10 * MiB, 0.0], [89 * GB]) == [None]
+
+
def test_match_adapter_reports_unknown_when_more_active_than_visible():
# More adapters actively using VRAM than are visible (a GPU outside the mask):
# attribution would fabricate a value, so report unknown for every device.
assert hw._match_adapter_used_to_devices([40 * GB, 0.5 * GB], [8 * GB]) == [None]
+def test_unified_used_sums_dedicated_and_shared_for_the_compute_adapter(monkeypatch):
+ # On an APU, Dedicated saturates at the carve-out and the overflow lands in
+ # Shared, so only the sum tracks the allocation (measured: 48 GiB held reports
+ # +29.19 dedicated, +19.02 shared on a gfx1151 host).
+ def fake(counter = "Dedicated Usage"):
+ if counter == "Dedicated Usage":
+ return [("luid_compute", 30.5 * GB), ("luid_placeholder", 0.0)]
+ return [("luid_compute", 19.0 * GB), ("luid_placeholder", 1.3 * GB)]
+
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)
+ assert hw._rocm_windows_unified_used_bytes() == 30.5 * GB + 19.0 * GB
+
+
+def test_unified_used_selects_on_dedicated_not_the_sum(monkeypatch):
+ # A display adapter reports 0 dedicated while holding gigabytes of shared.
+ # Selecting on the sum would see two candidates and either bail or add a
+ # foreign adapter's bytes; selecting on dedicated isolates the compute device.
+ def fake(counter = "Dedicated Usage"):
+ if counter == "Dedicated Usage":
+ return [("luid_compute", 1.2 * GB), ("luid_display", 0.0)]
+ return [("luid_compute", 0.15 * GB), ("luid_display", 1.3 * GB)]
+
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)
+ assert hw._rocm_windows_unified_used_bytes() == 1.2 * GB + 0.15 * GB
+
+
+def test_unified_used_declines_when_the_compute_adapter_is_ambiguous(monkeypatch):
+ # Two adapters above the floor: no key says which is visible, so report None
+ # rather than pick one, matching _rocm_windows_aggregate_used_bytes.
+ def two(counter = "Dedicated Usage"):
+ return [("luid_a", 1.2 * GB), ("luid_b", 2.4 * GB)]
+
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", two)
+ assert hw._rocm_windows_unified_used_bytes() is None
+
+ # Every adapter below the floor: nothing to stand on.
+ monkeypatch.setattr(
+ hw, "_rocm_windows_perf_counter_vram_by_adapter",
+ lambda counter = "Dedicated Usage": [("luid_a", 10 * MiB)],
+ )
+ assert hw._rocm_windows_unified_used_bytes() is None
+
+ # Counter unavailable entirely.
+ monkeypatch.setattr(
+ hw, "_rocm_windows_perf_counter_vram_by_adapter",
+ lambda counter = "Dedicated Usage": None,
+ )
+ assert hw._rocm_windows_unified_used_bytes() is None
+
+
+def test_unified_used_tolerates_a_missing_shared_counter(monkeypatch):
+ # Shared unavailable must degrade to dedicated-only, not to None: an APU below
+ # its carve-out is still correct on dedicated alone.
+ def fake(counter = "Dedicated Usage"):
+ return [("luid_compute", 1.2 * GB)] if counter == "Dedicated Usage" else None
+
+ monkeypatch.setattr(hw, "_rocm_windows_perf_counter_vram_by_adapter", fake)
+ assert hw._rocm_windows_unified_used_bytes() == 1.2 * GB
+
+
def test_match_adapter_reports_unknown_when_hidden_high_use_adapter_survives_filter():
# Idle 8 GiB card (10 MiB noise) beside a hidden 48 GiB card at 40 GiB: the
# 40 GiB can't fit the 8 GiB device, so clamping there would fabricate. Unknown.
diff --git a/studio/backend/tests/test_system_poll_no_cuda_context.py b/studio/backend/tests/test_system_poll_no_cuda_context.py
index d09ce166..a3febfab 100644
--- a/studio/backend/tests/test_system_poll_no_cuda_context.py
+++ b/studio/backend/tests/test_system_poll_no_cuda_context.py
@@ -230,12 +230,42 @@ def test_gpu_summary_pairs_rocm_apu_free_with_driver_total(monkeypatch):
"_smi_query",
lambda *a, **k: pytest.fail("an APU needs hipMemGetInfo's matching GTT total"),
)
+ # No WDDM counter reading available: free falls back to hipMemGetInfo's.
+ monkeypatch.setattr(hw, "_rocm_windows_unified_used_bytes", lambda: None)
summary = hw.get_gpu_summary()
assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 100.0, "vram_free_gb": 98.0}
+def test_gpu_summary_apu_prefers_wddm_counters_over_process_local_hip(monkeypatch):
+ # hipMemGetInfo is process-local on Windows WDDM, so an APU takes its GTT
+ # *total* from HIP but its *used* from the counters. Driver says 98 free of
+ # 100; the counters say 40 GiB is in use across all processes -> 60 free.
+ gib = 1 << 30
+ torch_stub, _props = _summary_torch(
+ properties_total = 8 * gib,
+ driver_free = 98 * gib,
+ driver_total = 100 * gib,
+ )
+ monkeypatch.setitem(sys.modules, "torch", torch_stub)
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw, "_rocm_props_total_is_carve_out", lambda _props: True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(
+ hw,
+ "_smi_query",
+ lambda *a, **k: pytest.fail("an APU must not take its total from the vendor CLI"),
+ )
+ monkeypatch.setattr(hw, "_rocm_windows_unified_used_bytes", lambda: 40.0 * gib)
+
+ summary = hw.get_gpu_summary()
+
+ # Total still HIP's, free now derived from the counters against that total.
+ assert summary == {"gpu_name": "Test GPU", "vram_total_gb": 100.0, "vram_free_gb": 60.0}
+
+
def test_context_free_rocm_smi_translates_hip_ordinals(monkeypatch):
from utils.hardware import amd
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 54d31ca0..2e0cc83a 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -939,10 +939,28 @@ def _free_in_torch_scope(total_bytes: int, used_gb: float) -> int:
return max(0, total_bytes - round(used_gb * (1024**3)))
-def _context_free_cuda_memory_info(idx: int, total_bytes: int) -> Optional[int]:
- """System-wide free bytes without attaching a CUDA/HIP primary context."""
+def _context_free_cuda_memory_info(
+ idx: int, total_bytes: int, unified: bool = False
+) -> Optional[int]:
+ """System-wide free bytes without attaching a CUDA/HIP primary context.
+
+ ``unified`` marks a ROCm APU, whose *total* must still come from HIP but whose
+ *used* is available here; see ``_rocm_windows_unified_used_bytes``.
+ """
parent_visible_spec = _get_parent_visible_gpu_spec()
+ # A unified part goes straight to the WDDM counters. The vendor CLI and DRM
+ # sysfs both report the dedicated carve-out for it, which the total-tolerance
+ # check below would reject anyway, and Linux hipMemGetInfo is already
+ # system-wide there -- so this exists for Windows, where it is not.
+ if unified:
+ if platform.system() != "Windows" or _rocm_device_ordinal_active():
+ return None
+ used_bytes = _rocm_windows_unified_used_bytes()
+ if used_bytes is None:
+ return None
+ return _free_in_torch_scope(total_bytes, used_bytes / (1024**3))
+
# Prefer the vendor CLI. Both nvidia-smi and amd-smi run out of process, so
# querying an idle backend does not leave a context resident in this process.
visible_ids = parent_visible_spec["numeric_ids"]
@@ -1047,25 +1065,44 @@ def get_gpu_memory_info() -> Dict[str, Any]:
# Driver-level free includes torch's cache and other processes. Try
# context-free telemetry first: mem_get_info pins a primary context
- # for the life of this backend. A ROCm APU is the exception, its GTT
- # total is unavailable from the context-free probes.
+ # for the life of this backend.
+ #
+ # A ROCm APU needs its GTT *total* from HIP, which the context-free
+ # probes cannot supply, so it pays for the context regardless. That is
+ # a reason to take the total from HIP, not a reason to take the free
+ # figure from it too: hipMemGetInfo is process-local on Windows WDDM
+ # and blind to other processes there. So resolve the total first, then
+ # still prefer telemetry for used.
driver_total_needed = _rocm_props_total_is_carve_out(props)
free = None
- if not driver_total_needed:
+ if driver_total_needed:
try:
- free = _context_free_cuda_memory_info(idx, total)
- except Exception as e:
- logger.debug("context-free free-VRAM probe failed: %s", e)
- try:
- if free is None:
free, driver_total = trusted_mem_get_info(idx)
# Only adopt a driver total that is usable: utilization_pct
# divides by it, so a zero would lose the whole report.
- if driver_total_needed and driver_total:
+ if driver_total:
total = driver_total
- except Exception as e:
- logger.debug("mem_get_info probe failed; free VRAM from reserved: %s", e)
- free = max(0, total - reserved)
+ except Exception as e:
+ logger.debug("mem_get_info probe failed; free VRAM from reserved: %s", e)
+ free = max(0, total - reserved)
+ try:
+ telemetry_free = _context_free_cuda_memory_info(idx, total, unified = True)
+ except Exception as e:
+ logger.debug("context-free free-VRAM probe failed: %s", e)
+ telemetry_free = None
+ if telemetry_free is not None:
+ free = telemetry_free
+ else:
+ try:
+ free = _context_free_cuda_memory_info(idx, total)
+ except Exception as e:
+ logger.debug("context-free free-VRAM probe failed: %s", e)
+ try:
+ if free is None:
+ free, _driver_total = trusted_mem_get_info(idx)
+ except Exception as e:
+ logger.debug("mem_get_info probe failed; free VRAM from reserved: %s", e)
+ free = max(0, total - reserved)
return {
"available": True,
@@ -1970,8 +2007,15 @@ def _rocm_linux_sysfs_vram_by_pci_gb() -> dict[str, tuple[float, float]]:
_ROCM_WIN_ADAPTER_MIN_BYTES = 64 * 1024 * 1024 # 64 MiB
-def _rocm_windows_perf_counter_vram_by_adapter() -> Optional[list[tuple[str, float]]]:
- """Per-adapter dedicated VRAM usage on Windows via Performance Counters.
+def _rocm_windows_perf_counter_vram_by_adapter(
+ counter: str = "Dedicated Usage",
+) -> Optional[list[tuple[str, float]]]:
+ """Per-adapter VRAM usage on Windows via Performance Counters.
+
+ ``counter`` selects the ``GPU Adapter Memory`` field. Dedicated Usage is the
+ default and the only one safe to select adapters on; see
+ ``_rocm_windows_unified_used_bytes`` for why Shared Usage is read separately
+ rather than folded in here.
Returns ``[(instance_name, used_bytes)]`` (one per LUID-named adapter), or
``None`` when the counter is unavailable/localized/empty so callers fall back.
@@ -1981,7 +2025,7 @@ def _rocm_windows_perf_counter_vram_by_adapter() -> Optional[list[tuple[str, flo
try:
# Emit "<InstanceName>|<CookedValue>" per sample, or a __NONE__ sentinel.
ps = (
- "$s=(Get-Counter '\\GPU Adapter Memory(*)\\Dedicated Usage'"
+ f"$s=(Get-Counter '\\GPU Adapter Memory(*)\\{counter}'"
" -ErrorAction SilentlyContinue).CounterSamples;"
"if($s){$s|ForEach-Object{'{0}|{1}' -f $_.InstanceName,[int64]$_.CookedValue}}"
"else{'__NONE__'}"
@@ -2046,6 +2090,7 @@ def _match_adapter_used_to_devices(
return [None] * n
# Exactly n supra-threshold counters: extras were placeholders, so a
# capacity-ranked bijection is plausible.
+ dropped = [u for u in useds if u < _ROCM_WIN_ADAPTER_MIN_BYTES]
useds = non_trivial
ranked_useds = [useds[rank] for rank in range(n)]
# A usage above its ranked capacity is a hidden larger GPU; clamping onto the
@@ -2053,6 +2098,25 @@ def _match_adapter_used_to_devices(
for rank in range(n):
if ranked_useds[rank] > ranked_totals[rank]:
return [None] * n
+ # One visible device, one supra-threshold counter, and every other counter
+ # at EXACTLY zero: attribute it. A Strix Halo host emits three instances,
+ # two of them at 0 dedicated, and the capacity test below cannot decide
+ # this shape because it needs a next-smaller device to compare against.
+ #
+ # Zero is the load-bearing part, not the cardinality. A merely sub-floor
+ # counter (10 MiB) can be the visible card sitting idle, which would make
+ # the survivor a hidden GPU's -- see the [6 GiB, 10 MiB] / [8 GiB] case,
+ # which must stay unknown. An adapter at exactly zero has nothing
+ # committed and cannot be the holder of the survivor's bytes.
+ #
+ # Residual risk, stated rather than hidden: the visible card could itself
+ # be the zero while a hidden adapter holds the survivor, and then this
+ # over-reports used. That errs toward understating free, which is the safe
+ # direction here -- the consumer is training-method selection, where an
+ # overstated free picks a method that OOMs. Clamped like every other
+ # branch, so a hidden larger adapter cannot report a fully-used card.
+ if n == 1 and all(u == 0 for u in dropped):
+ return [min(ranked_useds[0], device_totals[0])]
# Capacity forces the mapping only when the usage exceeds the next-smaller
# capacity; the smallest card and merely-fitting usages stay unknown.
# Keeps 40 GiB over 48/8 GiB -> [40, None].
@@ -2127,6 +2191,50 @@ def _rocm_windows_aggregate_used_bytes(
return float(sum(useds))
+def _rocm_windows_unified_used_bytes() -> Optional[float]:
+ """Used VRAM for a unified-memory ROCm APU on Windows, from the WDDM counters.
+
+ Dedicated Usage alone saturates at the carve-out on an APU and is wrong past
+ it. Measured on a gfx1151 Strix Halo host (89.47 GiB torch total), holding N
+ GiB in another process, deltas over baseline:
+
+ held dedicated shared sum
+ 4 + 4.14 + 0.04 + 4.18
+ 16 +16.60 + 0.08 +16.68
+ 24 +24.58 + 0.04 +24.62
+ 40 +29.07 +11.29 +40.36
+ 48 +29.19 +19.02 +48.21
+
+ Dedicated plateaus around 30.5 GiB and the overflow lands in Shared, so only
+ the sum tracks the allocation. Discrete cards are unaffected: this is reached
+ only when ``_rocm_props_total_is_carve_out`` says the part is unified.
+
+ Adapter SELECTION still keys off Dedicated Usage alone, deliberately. Display
+ and placeholder adapters report 0 dedicated while carrying gigabytes of shared
+ (a Basic Render Driver instance on the same host holds 1.30 GiB shared), so
+ filtering on the sum would stop telling them apart from the compute device and
+ would silently add a foreign adapter's bytes. Returns ``None`` unless exactly
+ one adapter clears the noise floor, matching the caution in
+ ``_rocm_windows_aggregate_used_bytes``.
+ """
+ dedicated = _rocm_windows_perf_counter_vram_by_adapter()
+ if not dedicated:
+ return None
+ candidates = [
+ (instance, used)
+ for instance, used in dedicated
+ if used >= _ROCM_WIN_ADAPTER_MIN_BYTES
+ ]
+ # Two compute adapters means no key says which is the visible one, and zero
+ # means the card is idle below the floor: neither is a figure we can stand on.
+ if len(candidates) != 1:
+ return None
+ instance, dedicated_used = candidates[0]
+ shared = _rocm_windows_perf_counter_vram_by_adapter("Shared Usage") or []
+ shared_used = next((used for name, used in shared if name == instance), 0.0)
+ return dedicated_used + shared_used
+
+
def _rocm_windows_per_device_vram(
device_indices: list[int],
) -> tuple[list[Dict[str, Any]], Optional[float]]: |
… free at the total get_physical_gpu_count falls back to torch on an nvidia-smi -L failure, which counts VISIBLE devices, so a one-device mask on a multi-GPU host read as single-GPU and granted the CUDA_DEVICE_ORDER exemption that the mask is precisely the reason to withhold. The count is cached, so one transient timeout disabled the gate for the process lifetime. Track whether the count came from the SMI and require that. _free_in_torch_scope also lost its upper clamp when it replaced the three min(total_bytes, free_bytes) call sites; both SMI parsers accept signed values, so a negative used counter advertised more free than the card has.
…adapter past placeholders hipMemGetInfo is process-local on Windows WDDM, so an APU took its total AND its free from a source blind to other processes. The total must still come from HIP (the GTT pool), but used is available from the GPU Adapter Memory counters, so resolve the total first and still prefer telemetry for used. Dedicated Usage saturates at the carve-out on a unified part (measured: 48 GiB held reports +29.19 dedicated, +19.02 shared), so the value is dedicated plus shared for the compute adapter. Selection still keys off dedicated alone: display and placeholder adapters report 0 dedicated while holding gigabytes of shared. _match_adapter_used_to_devices now attributes a single visible device when the one supra-threshold counter is accompanied only by counters at exactly zero. Zero is what makes it safe, not the cardinality: a sub-floor counter can be the visible card idle, which keeps [6 GiB, 10 MiB] over [8 GiB] unknown.
|
Applied in You are right that my boundary was unsafeI stated "exactly one supra-threshold counter and exactly one visible device is forced by cardinality". It is not, and the counterexample is in the file I was editing ( assert hw._match_adapter_used_to_devices([6 * GB, 10 * MiB], [8 * GB]) == [None]Implementing my rule as written turns that red. Your narrower version, every other counter at exactly zero, is the correct line: a sub-floor counter can be the visible card sitting idle, which makes the survivor a hidden GPU's, while an adapter at exactly zero has nothing committed and cannot be. Verified at head: Keeping your half. The residual risk you named, the visible card being the zero while a hidden adapter holds the survivor, is real, but it errs toward understating free and the consumer is training-method selection, where the expensive direction is overstating. I would rather have the conservative figure than Unknown here. It is documented in the code, which is the part that matters. The carve-out measurement settles itDedicated plateauing near 30.5 GiB with the overflow landing in Shared is exactly the discriminator, and 4 GiB could not have shown it. Dedicated alone under-reporting by 19 GiB at 48 GiB held is decisive. Two things I would have got wrong without the measurement. I assumed the carve-out was around 8 GiB; 30.5 is a different animal. And selection on dedicated with the value as the sum is a distinction I did not anticipate, but the Basic Render Driver at 1.30 GiB shared and 0 dedicated makes the reason concrete: fold shared into selection and a display adapter stops being distinguishable from the compute device. The test change is cleanI checked it specifically because you flagged it. My assertions in Rebase noteThe patch was against That commit also fixed the order-gate exemption: Suites on the merged tree: 147 passed, 5 skipped across the four files, ruff clean. On PDHGood to know, and the 178-231 ms first call versus 0.0-0.1 ms thereafter is the number that changes the picture. Agreed it is a separate change; Nothing further needed on your side unless the next Codex round turns something up. Thanks for running the discriminating case first rather than patching to the assumption. |
…es are the visible set _match_adapter_used_to_devices ranks by capacity, and once the noise filter has dropped counters the ranking can hand a hidden adapter's smaller reading to a busier visible card. Randomised over the mapping, a card holding 86 GiB of 89 reports 10, overstating free by 76 GiB. The System tab has carried that best-effort mapping since unslothai#7072 and still does; free_gb is a new consumer and feeds training-method selection, where overstating free is what OOMs. Require one counter instance per visible device before using it here, the same cardinality assumption _rocm_windows_aggregate_used_bytes rests on, and fall through to mem_get_info otherwise.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 938cfbb617
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| candidates = [ | ||
| (instance, used) for instance, used in dedicated if used >= _ROCM_WIN_ADAPTER_MIN_BYTES | ||
| ] | ||
| # Two compute adapters means no key says which is the visible one, and zero | ||
| # means the card is idle below the floor: neither is a figure we can stand on. | ||
| if len(candidates) != 1: |
There was a problem hiding this comment.
Require the unified-memory candidate to be the visible APU
On a Windows ROCm APU host with another WDDM adapter, this filter treats whichever single adapter exceeds 64 MiB as the compute device without tying its LUID to the torch-visible APU. For example, if the selected APU is idle while a hidden discrete GPU is using VRAM, that hidden GPU's dedicated and shared counters are subtracted from the APU's GTT total, understating free_gb and potentially forcing an unnecessarily constrained training method. Decline the reading unless the candidate can be identified as the visible APU.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the reason is consistency rather than disagreement with the mechanism.
The scenario is real: with the APU idle below the 64 MiB floor and a hidden discrete adapter busy, the single candidate is the discrete GPU and its bytes are subtracted from the APU's GTT total. But that is the same trade _match_adapter_used_to_devices already makes deliberately for a single visible device, documented in its comment as a stated residual risk, and I accepted it earlier in this PR on the grounds that it errs toward UNDERSTATING free.
It cannot go the other way here. Overstating free would need the candidate to be smaller than the APU's true usage, and if the APU were using more than the floor it would be a second candidate and len(candidates) != 1 would already decline. So the only reachable error is a conservative one, and the consumer is training-method selection, where overstating is what OOMs and understating merely picks QLoRA.
Tying the LUID to the torch-visible device is the right long-term answer, and it is the same missing key that keeps multi-GPU attribution unsolved in _rocm_windows_aggregate_used_bytes. It is not something this PR can add for free. If you would rather have Unknown than a conservative figure, that is a coherent position, but it should change BOTH sites together rather than just this one, and I would want it as a separate change with its own evidence.
Three separate holes in the counter route for free_gb: Uncertain is not unified. _rocm_props_total_is_carve_out answers True for an unclassifiable device as well, because a too-small total hides models. That justifies the driver total, not adding Shared Usage, which is not part of a discrete card's props.total_memory. Adds a stricter positive check for the used figure and leaves the total rule alone. A failed Shared query is not zero shared usage. Past the carve-out the overflow lives entirely in Shared, so defaulting to zero reports the measured 48 GiB case as 30.5 and overstates free by 19 GiB. Nothing here knows where the carve-out sits, so decline. A query that succeeds but omits the LUID is a real zero and is still kept. The cardinality check ran against a different PowerShell sample than attribution did, since the mapper re-queried the counters. The validated snapshot is now passed through, which also drops a second ~1.3 s call.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
get_gpu_memory_infocomputedfree_gbastotal - torch.allocated, which sees neither this process's reserved cache nor any other process's VRAM, so the summary reported a card as free while a model was resident.free_gbnow comes from system-wide driver telemetry. The probe order is:nvidia-smi,amd-smi, or Linux DRM sysfs). These run out of process, so an idle backend does not pay for them.trusted_mem_get_infowhen that is unavailable. Correct, but it attaches a CUDA/HIP primary context worth roughly 612 MiB for the life of the process, which is why it is not first.total - reservedonly when both fail. Process-local, so it is a bound rather than a measurement.A unified-memory ROCm APU skips step 1 deliberately: its allocatable GTT total is only available from
hipMemGetInfo, and reporting the dedicated carve-out instead would budget a 128 GiB Strix Halo as about 8 GiB.Free is derived as
torch_total - driver_used, neverdriver_total - driver_used. NVIDIA reports a reserved framebuffer separately from used, andprops.total_memoryalready excludes it, so subtracting from torch's total is exactly the driver's free figure without querying an extra field.memory.reservedis R510+ and an unknown field name aborts the whole CSV query rather than returning[N/A], so deriving beats asking.Because the probe now keys telemetry rows to a torch ordinal, it declines wherever that mapping is not provable rather than guessing:
GPU_DEVICE_ORDINALis set. It is a ROCclr-layer variable, so it renumbers HIP devices on Windows as well as Linux, and no visibility spec here reads it.CUDA_DEVICE_ORDERis notPCI_BUS_IDon a multi-GPU host. CUDA enumerates FASTEST_FIRST by default while nvidia-smi reports PCI order. A single GPU is exempt, since every ordering is the identity there. This is the gate_cuda_compute_capsin the llama.cpp backend already applies.A full-GPU UUID mask is exempt from the order gate: CUDA enumerates the entries of
CUDA_VISIBLE_DEVICESin the order listed and a UUID names its device absolutely, so there is no ordinal space to share.ROCR_VISIBLE_DEVICESis ignored on Windows, which has no ROCr layer, matching what the llama.cpp backend already does.allocated_gb/reserved_gb/utilization_pctkeep their existing semantics, no returned key is added or removed, and the MLX path is untouched.Consumer chain.
get_gpu_memory_infofeedsget_gpu_summary, which is served byGET /api/system/hardwareand read by the frontend asvram_free_gb. Its one behaviour-changing consumer is training-method auto-selection (training-method-hardware-policy.ts:18), which picks LoRA or QLoRA by comparing an estimate against free VRAM, so an overstated figure picks a method that OOMs on launch. It is also displayed on the Resources tab. Note thatauto_select_gpu_idsdoes not read it; that path computes free per device fromget_visible_gpu_utilization. The frequently polled/api/systemroute does not reach this function on CUDA or XPU either, so the 3s/5s poll is unaffected.Verification
Real hardware, cross-process. A holder process allocates and touches memory while an otherwise idle observer reads the summary.
The pre-fix figure is blind by exactly the amount held. Controls on the ROCm run: idle baseline spread 0.000 GiB over three samples, observer's own allocated and reserved 0.00 in every reading, and free returned to the idle median after the holder exited.
Reserved framebuffer. On a B200 with a 2 GiB tensor resident,
driver_total - usedgives 176.450 GiB against a driver figure of 175.745, and makesfree_gb + allocated_gbexceedtotal_gb. Normalising to torch's total gives 175.743. On a completely full card the same error reported 0.71 GB free.No context pinned. Fresh process,
cuDevicePrimaryCtxGetStateas the oracle:get_gpu_summary()and_context_free_cuda_memory_info()both leave the context inactive at 0 MiB, whiletrusted_mem_get_info()leaves it active at 612 MiB.Platform matrix. 61 simulated scenarios over [Linux, Windows, WSL, macOS] x [NVIDIA, AMD discrete, AMD APU, Intel XPU, CPU-only, MLX], faking only the driver boundary so the real branch logic runs. Covers nvidia-smi missing, non-zero exit, empty, malformed, truncated rows,
[N/A]values and timeout; MIG and MI300 partitions; stacked ROCm masks;GPU_DEVICE_ORDINAL; ambiguous, duplicate, unknown, mixed and uppercase UUID masks; a full card; and a driver reporting more used than torch's total. Across every scenario: no exception, no key added or removed from any returned dict, and nofree_gbthat is negative, abovetotal_gb, or inconsistent withallocated_gb. The normalisation is a no-op wherever reserved is 0, which is every AMD path and any NVIDIA GPU reporting none.Suites. 343 pass across the GPU-related backend tests. Every fix carries a regression test that fails on the preceding commit.
Not covered
The Windows ROCm WDDM free cap is untested;
rocm_windows_free_is_untrusted()issys.platform == "win32" and IS_ROCM, so on Linuxtrusted_mem_get_infois a passthrough. The XPU path is covered by mocks only, and MLX is unchanged.