Skip to content

fix(hardware): report driver-level free VRAM in the GPU summary - #9362

Merged
danielhanchen merged 26 commits into
unslothai:mainfrom
yzxcj797:fix/gpu-summary-driver-free-vram
Aug 24, 2026
Merged

danielhanchen merged 26 commits into
unslothai:mainfrom
yzxcj797:fix/gpu-summary-driver-free-vram

Conversation

@yzxcj797

@yzxcj797 yzxcj797 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

get_gpu_memory_info computed free_gb as total - 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_gb now comes from system-wide driver telemetry. The probe order is:

  1. Context-free vendor telemetry first (nvidia-smi, amd-smi, or Linux DRM sysfs). These run out of process, so an idle backend does not pay for them.
  2. trusted_mem_get_info when 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.
  3. total - reserved only 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, never driver_total - driver_used. NVIDIA reports a reserved framebuffer separately from used, and props.total_memory already excludes it, so subtracting from torch's total is exactly the driver's free figure without querying an extra field. memory.reserved is 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_ORDINAL is 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_ORDER is not PCI_BUS_ID on 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_caps in the llama.cpp backend already applies.
  • The driver total does not match torch's, which is a MIG instance or an MI300 partition being handed its parent's whole-GPU figures.
  • The amd-smi to HIP mapping is unproven, or ROCr and HIP masks are stacked.

A full-GPU UUID mask is exempt from the order gate: CUDA enumerates the entries of CUDA_VISIBLE_DEVICES in the order listed and a UUID names its device absolutely, so there is no ordinal space to share. ROCR_VISIBLE_DEVICES is ignored on Windows, which has no ROCr layer, matching what the llama.cpp backend already does.

allocated_gb / reserved_gb / utilization_pct keep their existing semantics, no returned key is added or removed, and the MLX path is untouched.

Consumer chain. get_gpu_memory_info feeds get_gpu_summary, which is served by GET /api/system/hardware and read by the frontend as vram_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 that auto_select_gpu_ids does not read it; that path computes free per device from get_visible_gpu_utilization. The frequently polled /api/system route 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.

host held by another process before after driver truth
gfx1151 ROCm, 64 GiB 4 GiB 64.00 59.70 59.70
B200, 178 GiB 8 GiB 178.35 170.45 170.45

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 - used gives 176.450 GiB against a driver figure of 175.745, and makes free_gb + allocated_gb exceed total_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, cuDevicePrimaryCtxGetState as the oracle: get_gpu_summary() and _context_free_cuda_memory_info() both leave the context inactive at 0 MiB, while trusted_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 no free_gb that is negative, above total_gb, or inconsistent with allocated_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() is sys.platform == "win32" and IS_ROCM, so on Linux trusted_mem_get_info is a passthrough. The XPU path is covered by mocks only, and MLX is unchanged.

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.
@danielhanchen

Copy link
Copy Markdown
Member

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.

@Imagineer99 Imagineer99 self-assigned this Aug 20, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e14aa0dcd5

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: c5f08b284f

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

Windows + AMD ROCm run: the Windows leg does not work

Ran it. The headline is the one you were worried about: hipMemGetInfo is process-local on Windows WDDM, so free_gb is blind to other processes and this fix is a no-op here. Everything else came out in the PR's favour.

The box is an APU rather than a discrete card, so it takes the _rocm_props_total_is_carve_out() path you flagged as deliberately different.

Windows-11-10.0.26200-SP0
AMD Radeon(TM) 8060S Graphics  gfx1151  Strix Halo APU  is_integrated = 1
props_total_gb  89.4654541015625
torch 2.11.0+rocm7.13.0   HIP 7.13.99004   python 3.13.13

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 see another process? No.

holder held                  4.00 GiB (plus its own context)
accepted band                3.60 to 6.00 GiB
free_gb dropped by           +0.00 GiB   (want >= 3.60)
old formula dropped by       +0.00 GiB   (want ~0.00, the defect)
torch.mem_get_info dropped   +0.00 GiB   (attribution only)
observer stayed a bystander  0.00 GiB allocated

free_gb reads 89.30902099609375 before, during and after — bit-identical across all three, with a 4.00 GiB holder confirmed READY at allocated_gib: 4.0.

This is your first branch, not your second: mem_get_info did not move either, so the driver is reporting process-local free and the logic in this PR is not at fault.

Control you didn't have. "Free never moves" and "free is process-local" produce the same output in your script, and they are very different problems, so I added a leg where the observer itself allocates. Also sampled the WDDM perf counters (\GPU Process Memory(*)) at each point to see whether anything on Windows can see across the boundary:

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_gb is process-local via hipMemGetInfo on WDDM, exactly as you predicted, and nothing in the suite catches it.
  • A working Windows source exists: the WDDM \GPU Process Memory perf 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.

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up on the same box: amd-smi is worse than described, and a working no-UAC source is already in this PR

Same machine as my previous comment — gfx1151 Strix Halo APU, Windows 11, torch 2.11.0+rocm7.13.0, amd-smi on PATH at C:\windows\system32\amd-smi.EXE, no HIP SDK.

Nothing below retracts anything in that comment. Two additions.


1. The UAC prompt is 5 for 5, and amd-smi cannot do anything anyway

I invoked amd-smi four more times by hand, deliberately bypassing _amd_smi_allowed(), with the four subcommands the PR's new call sites actually use. All four failed:

amd-smi list      EXIT=1   Error LoadLibraryA
amd-smi list -e   EXIT=1   Access is denied. / Error LoadLibraryA
amd-smi metric    EXIT=1   Error LoadLibraryA
amd-smi version   EXIT=1   Error LoadLibraryA

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 Get-Process consent after each command returned. That is unreliable — it only catches a dialog that happens to be open at the instant of the poll, and it read 0 for all four of these. I briefly concluded from that null result that the prompt was not reproducible. It was; the detector was wrong. The only reliable oracle here is a person watching the screen, exactly as you said.

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. _amd_smi_allowed() is not trading a prompt for telemetry — it is declining a prompt that buys zero. That is a stronger justification than the PR currently claims for itself.

Worth noting where the exposure actually is: this box is an APU, so _rocm_props_total_is_carve_out() short-circuits before the guard is ever consulted, and the guard result and the APU bypass independently produce the same zero spawns. On a discrete Windows AMD card with a driver and no SDK, step 1 of the ladder would call get_visible_gpu_utilization -> amd-smi metric on every Resources-tab poll, and _amd_smi_allowed() would be the only thing standing between that user and a repeating dialog that yields nothing. That is the configuration to keep the guard for.

2. \GPU Adapter Memory does see across processes here, with no UAC

The source you want is already wired into this PR via _rocm_windows_per_device_vram, and it works on this box. Raw counters, 4 GiB holder in another process, real adapter luid_0x00000000_0x0001544a_phys_0:

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 — 0x171ac reports 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/system poll 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.

@danielhanchen

Copy link
Copy Markdown
Member

Consolidated Windows + AMD ROCm report, and a UAC-free path that works

Everything 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:

Windows-11-10.0.26200-SP0
AMD Radeon(TM) 8060S Graphics  gfx1151  Strix Halo APU  is_integrated = 1
props_total_gb 89.4654541015625   torch 2.11.0+rocm7.13.0   HIP 7.13.99004
amd-smi present at C:\windows\system32\amd-smi.EXE, no HIP SDK

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

holder held                  4.00 GiB (plus its own context)
free_gb dropped by           +0.00 GiB   (want >= 3.60)
old formula dropped by       +0.00 GiB   (want ~0.00, the defect)
torch.mem_get_info dropped   +0.00 GiB

free_gb reads 89.30902099609375 before, during and after, bit-identical, against a holder confirmed at allocated_gib: 4.0. Reproduced across two independent runs.

This is your first branch, not your second: mem_get_info did not move either, so the driver is reporting process-local free and the logic in this PR is not at fault.

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:

free_gb mem_get_info
idle 89.31 89.31
self holds 4 GiB 85.29 85.29
other holds 4 GiB 89.04 89.04

free_gb tracks this process at -4.02 GiB and another at exactly 0.00. hipMemGetInfo works; it is scoped to the calling process on WDDM.

2. amd-smi: 5 UAC prompts for 5 invocations, and zero useful output

_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 vacuous — amd-smi is on PATH, so the guard refused on its merits.

I then invoked amd-smi by hand five times total, bypassing the guard, using the subcommands this PR's new call sites actually reach:

amd-smi list      EXIT=1   Error LoadLibraryA
amd-smi list -e   EXIT=1   Access is denied. / Error LoadLibraryA
amd-smi metric    EXIT=1   Error LoadLibraryA
amd-smi version   EXIT=1   Error LoadLibraryA

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 Get-Process consent after each command returned. That only catches a dialog open at the instant of the poll, and it read 0 for four of these. I briefly concluded the prompt was not reproducible; it was, and the detector was wrong. The reliable oracle is a person watching the screen, exactly as you wrote.

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. _amd_smi_allowed() is not trading a prompt for telemetry, it is declining a prompt that buys zero.

Where the real exposure is: this box is an APU, so _rocm_props_total_is_carve_out() short-circuits before the guard is consulted, and the two independently produce the same zero. On a discrete Windows AMD card with a driver and no SDK, step 1 of the ladder calls get_visible_gpu_utilization -> amd-smi metric on every Resources-tab poll, and the guard is the only thing between that user and a repeating dialog that yields nothing. Keep the guard.

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: free_gb equals mem_get_info free exactly.

4. Bug in the check script

windows_rocm_vram_check.py never calls detect_hardware(), so hw.IS_ROCM is the module 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 dead, the non-ROCm path measured and presented as a Windows ROCm reading. It prints the same PASS/FAIL either way.

Re-running with hw.detect_hardware() first gave the gates in section 3 and identical VRAM numbers, so nothing above is affected. But as written it will collect gate dumps from other people describing a branch their machine never took.


5. How to get this without UAC

The source is already wired into this PR through _rocm_windows_per_device_vram, backed by \GPU Adapter Memory performance counters. It works here. Real adapter luid_0x00000000_0x0001544a_phys_0, 4 GiB holder in another process:

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 when another process allocates, reversing on release — the cross-process visibility this PR exists to get. Zero consent.exe across every run.

Skip PowerShell: read PDH directly

Get-Counter costs about 1.3 s per sample because it spawns powershell, which is fine for the Resources tab and too slow for the 3 s/5 s /api/system poll. The same counters are available from pdh.dll via ctypes, no subprocess:

PdhOpenQueryW -> PdhAddEnglishCounterW(r"\GPU Adapter Memory(*)\Dedicated Usage")
             -> PdhCollectQueryData -> PdhGetFormattedCounterArrayW(PDH_FMT_LARGE)

Measured here:

  • 178-231 ms first call in a process (DLL load), then 0.0-0.1 ms per read.
  • Tracks another process: 1.324 -> 5.469 GiB with the holder up, +4.15 GiB.
  • Live inside a long-lived process, which is how the backend would use it. Sampling every 2 s in one process while the holder was killed mid-loop: 5.481, 5.481, 5.481, [holder killed], 1.294, 1.294, .... It reflected the change on the very next sample. No staleness, no per-handle caching.
  • No elevation. PdhAddEnglishCounterW also sidesteps the localization problem your Get-Counter docstring worries about, since it resolves English counter names on a localized Windows.

That makes this cheap enough to sit on the fast poll, which Get-Counter never could.

Two blockers, both of which 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 is sound for the total — 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 the two lights 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 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 capacity, and that case falls through. This host emits 3 instances, two 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 returns None too, for a different reason: it requires len(adapter_useds) == n before any noise filter, and 3 != 1.

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

  • 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 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.
  • Whether dedicated alone or dedicated+shared is correct on unified memory I have not established. Both track the holder, +4.32 and +4.39. Summing across adapters is definitely wrong: 0x171ac shows 1.30 GiB shared, 0 dedicated, and is not the compute device.
  • The PDH timings are from this one box. The API is documented as non-privileged for these counters, but I have only measured it here.
  • rocm_windows_free_is_untrusted, _amd_smi_allowed on Windows, and the ROCR/GPU_DEVICE_ORDINAL handling are now exercised on real hardware. The XPU path and MLX remain untested by me.

7. Suggested shape

  1. Keep _amd_smi_allowed() exactly as it is. Section 2 is the evidence for it, and it is stronger than the PR currently argues.
  2. Split the APU gate so telemetry supplies used while torch supplies total.
  3. Let _match_adapter_used_to_devices return the forced value when n == 1 and exactly one counter survives the threshold.
  4. Prefer PDH over Get-Counter for the counter read, so it is affordable on the fast poll.
  5. Add detect_hardware() to the check script before anyone else runs it.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

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 mine

Correct and my fault. IS_ROCM is False at import (hardware.py:87) and is only assigned inside detect_hardware() (hardware.py:592), so reading the gates without calling it describes the non-ROCm path on a ROCm box. Worse, it fails silently: the PASS/FAIL line is unchanged, so a stale dump looks like a clean result.

Fixed in c549f94b4. It now calls detect_hardware() before reading anything and records what it returned, plus a self-check that fails outright when torch is a ROCm build and IS_ROCM still reads False, so the same mistake cannot pass quietly again.

Your correction of your own detector is the more useful half of that. Polling Get-Process consent after the command returns only catches a dialog that happens to be open at the sampling instant, and it gave four false negatives. Worth stating plainly for anyone reading later: a null result from that method is not evidence of no prompt.

Windows: accepted, and it does not block this PR

free_gb moving 4.02 GiB for this process and exactly 0.00 for another is conclusive, and the observer-allocates leg is the control that makes it conclusive. I did not have that, and without it "never moves" and "process-local" are indistinguishable. Good catch.

To be clear about what it costs though, the Windows path is not made worse by this PR. Before, free was total - torch.allocated, blind to other processes AND to this process's own allocator cache. After, it is hipMemGetInfo, still blind to other processes but now correct about this one, including the cache. Strictly better, just not the fix that was advertised. So this is a gap to close, not a regression to revert.

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 argument

Five 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 _amd_smi_allowed()'s docstring, since the current wording undersells it.

Your point about where the exposure actually lives is the one I would have missed. This box is an APU, so _rocm_props_total_is_carve_out() short-circuits before the guard is consulted and the two independently produce the same zero. The configuration that matters is a discrete Windows AMD card with a driver and no SDK, where get_visible_gpu_utilization would reach amd-smi metric on every Resources-tab poll and the guard is the only thing between that user and a repeating dialog that yields nothing.

The two changes: yes to both

(a) Split the APU total from the APU used

Agreed, 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 _free_in_torch_scope(total_bytes, used_gb). Skipping the probe to protect the total discards the used figure along with it, which is a wider gate than the reason justifies. Split them.

(b) n = 1, with a correction that shrinks the fix

Your diagnosis is right and I reproduced it, but the boundary is not where the comment puts it. n = 1 is not rejected in general. With exactly one counter it already works:

n=1, 1 counter  -> [1292292096.0]
n=1, 3 counters -> [None]
aggregate       -> None

The failure is specific to the len(useds) > n branch, the hidden-adapter case, which is what your host hits with its two placeholder instances. That branch filters to exactly n supra-threshold counters, confirms none exceeds its ranked capacity, and then asks capacity to force the pairing via rank + 1 < n -- which at n = 1 is never true, so the single surviving counter is discarded after it has already passed every check that matters.

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:

  • Keep the clamp (min(used, device_total)), so a hidden larger adapter cannot report a fully-used card.
  • A regression test at exactly your host's shape: three instances, two at zero, one visible device.

_rocm_windows_aggregate_used_bytes returning None at 3 != 1 I would leave alone. Its docstring is explicit that cardinality is the only thing establishing that the counter list is the visible set, and relaxing that is how a foreign adapter's bytes get silently added to a host total.

The one thing I do not want decided by measurement alone

Dedicated 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, 0x171ac is not the compute device, and 1.3 s per sample means this belongs on the Resources tab only. The /api/system poll at 3 s and 5 s must not reach it, cached or otherwise, and I will add a test pinning that rather than rely on it staying true.

No need for the forced UNSLOTH_ENABLE_AMD_SMI=1 leg. You have already shown the prompt is real and that the guard holds; making Studio pop one deliberately proves nothing further and costs you a dialog.

@danielhanchen

Copy link
Copy Markdown
Member

Patch for (a) and (b), plus the carve-out measurement you asked for

Ran 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+shared

You were right that 4 GiB could not separate them, and right about the mechanism. Deltas over baseline, PDH, holder in another process:

held dedicated shared sum
4 GiB +4.14 +0.04 +4.18
8 GiB +8.24 +0.04 +8.28
12 GiB +12.24 +0.04 +12.29
16 GiB +16.60 +0.08 +16.68
24 GiB +24.58 +0.04 +24.62
40 GiB +29.07 +11.29 +40.36
48 GiB +29.19 +19.02 +48.21

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 so

I implemented this, but not where you put the line, because your existing test at test_rocm_windows_vram_7072.py:341 is a counterexample to it:

# 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 [1.2 GiB, 0, 0] / [89 GiB] attributes; [6 GiB, 10 MiB] / [8 GiB] and [1.2 GiB, 10 MiB, 0] / [89 GiB] both stay unknown. Your test passes unmodified.

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 split

Total still from hipMemGetInfo, used now from the counters. The unified path goes straight to the WDDM counters rather than through step 1, so your _smi_query guard in test_gpu_summary_pairs_rocm_apu_free_with_driver_total stays meaningful — the vendor CLI and DRM sysfs both report the carve-out for a unified part anyway, and Linux hipMemGetInfo is already system-wide.

One test of yours changed

test_gpu_summary_pairs_rocm_apu_free_with_driver_total asserted vram_free_gb == 98.0, i.e. that an APU's free comes from hipMemGetInfo. Change (a) supersedes that by design. I kept your assertion as the fallback case by pinning _rocm_windows_unified_used_bytes to None, and added test_gpu_summary_apu_prefers_wddm_counters_over_process_local_hip for the new contract. Flagging it because silently rewriting a test to match new behaviour is how a regression gets shipped — check I did not weaken your intent.

Verification on hardware

Your check script, unmodified, on the patched tree:

holder held                  4.00 GiB (plus its own context)
free_gb dropped by           +4.23 GiB   (want >= 3.60)
old formula dropped by       +0.00 GiB   (want ~0.00, the defect)
torch.mem_get_info dropped   +0.00 GiB   (attribution only)
amd-smi spawns, as configured 0
amd-smi spawns, when refused  0   (want 0)
PASS

And past the carve-out, which is what the shared handling exists for:

holder held                  40.00 GiB
free_gb dropped by           +40.37 GiB   (want >= 36.00)
old formula dropped by       +0.00 GiB
PASS

Dedicated alone would have reported about +29 there.

Suites: 135 passed, 14 skipped across test_system_poll_no_cuda_context.py, test_rocm_windows_vram_7072.py, test_rocm_multi_gpu_vram_system_wide.py, test_utils.py. Zero consent.exe throughout.

Two notes

_rocm_windows_aggregate_used_bytes untouched, per your call.

You closed with "1.3 s per sample means this belongs on the Resources tab only" — that is the Get-Counter figure. PDH via ctypes is 0.0-0.1 ms after a 178-231 ms first call, verified live in a long-lived process (sampled every 2 s while the holder was killed mid-loop: 5.481, 5.481, 5.481, [killed], 1.294, 1.294..., correct on the very next sample). PdhAddEnglishCounterW also sidesteps the localization worry in your Get-Counter docstring. I have not put PDH in this patch — it is a separate change and yours to want — but the cost argument for keeping this off the fast poll no longer holds. Your test pinning /api/system away from it is still worth having for the other reasons.

Patch below, against c549f94b4.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@danielhanchen

Copy link
Copy Markdown
Member

Applied in 4b021ec84, unchanged apart from a rebase onto 843bc21bf and the repo's kwarg-spacing formatter. Both corrections to me are right and I checked each one rather than taking it.

You are right that my boundary was unsafe

I 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 (test_rocm_windows_vram_7072.py:267, not 341):

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:

host shape [1.2G,0,0]/[89G]                    -> [1.2]
my wrong rule counterexample [6G,10M]/[8G]     -> [None]
sub-floor present [1.2G,10M,0]/[89G]           -> [None]
hidden larger [100G,0,0]/[48G]                 -> [None]
two active [40G,0.5G]/[8G]                     -> [None]

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 it

Dedicated 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 clean

I checked it specifically because you flagged it. My assertions in test_gpu_summary_pairs_rocm_apu_free_with_driver_total are byte-identical; the only addition is pinning _rocm_windows_unified_used_bytes to None so it covers the fallback, and the new contract went into a separate test. That is the right way to do it, and flagging it was the right call.

Rebase note

The patch was against c549f94b4 and head had moved to 843bc21bf, which touched _free_in_torch_scope. The three-way merge kept both changes, so the clamp you preserved is now min(total_bytes, max(0, ...)) rather than the max(0, ...) in your diff context. Worth knowing if you re-apply locally.

That commit also fixed the order-gate exemption: get_physical_gpu_count() falls back to a visibility-filtered torch count on an nvidia-smi -L failure, so a one-device mask on a multi-GPU host read as single-GPU and granted the exemption the mask is the reason to withhold. It is cached, so one transient timeout disabled it for the process lifetime.

Suites on the merged tree: 147 passed, 5 skipped across the four files, ruff clean.

On PDH

Good 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; PdhAddEnglishCounterW sidestepping the localization caveat is a second reason to want it. I will still add the test pinning /api/system away from this path, since the argument for that was never only cost: the fast poll should not depend on a Windows-only counter surface at all.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +2248 to +2253
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: af5a27e012

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants