Skip to content

fix(amd): ask HIP for the adapter LUID before inferring it from the DirectX record - #9316

Closed
LeoBorcherding wants to merge 8 commits into
unslothai:mainfrom
LeoBorcherding:pr-a-hip-luid-probe
Closed

LeoBorcherding wants to merge 8 commits into
unslothai:mainfrom
LeoBorcherding:pr-a-hip-luid-probe

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Stacks on #8863. GitHub can only base this on main, so the diff below also carries that PR's commit. This one is the top commit alone: fix-amd-windows-vram-monitor...pr-a-hip-luid-probe

#8863 reaches a device through what the two sides say about it: the DirectX Description, or the gfx target when the names disagree. Neither can separate two cards of one model, since both report one string and one arch, so both get the aggregate and neither a figure of its own.

HIP already knows. hipDeviceProp_tR0600 carries the same DXGI LUID the GPU Adapter Memory counter instances are named after, so asking the runtime joins on the adapter rather than on anything about it. The DirectX join stays underneath for when the runtime cannot be asked, and capacity ranking below that.

Idea and the R0600 route from @pablo86gr in #8793, closed as a duplicate, with both of its review findings addressed:

  • Ordinals come from the recorded visible_ordinal, not from dev_meta positions, which compact when get_device_properties fails for an earlier ordinal and would otherwise hand ordinal 0's LUID to the card that survived at ordinal 1.
  • luidDeviceNodeMask is read and used. A linked-node adapter puts several ordinals behind one LUID while the counters index its nodes as phys_N, and nothing pairs the two, so those ordinals report unknown per device and contribute only to the aggregate, which the pairing does not change. The mask decides the thing it can decide: whether those counters are all of that adapter's nodes, or whether one belongs to a node HIP is not showing.

The offsets are hardcoded, so the name is read back from the head of the struct and compared against the device's own; a layout that ever moved is caught rather than trusted. The probe declines as a whole and falls back to the DirectX map: off Windows, runtime not loaded in this process, symbol absent, an ordinal that will not answer, an all-zero LUID.

Verification

Windows 11, RX 9060 XT, ROCm 7.13, torch 2.11.0+rocm7.13.0, runtime loaded:

HIP identity : luid 0x14ad4, node mask 0
counter      : luid_0x00000000_0x00014ad4_phys_0
hip join     : 1.65 GiB     directx join : 1.65 GiB

The two paths agree independently. The probe also resolves the LUID with torch.cuda.is_initialized() still False, so a telemetry poll does not buy a HIP context to ask, which matters on a path this module deliberately keeps context-free.

Tests

Nine cases added: the HIP join separating two of one model, ordinals queried by visible_ordinal against a compacted list, linked nodes keeping the aggregate but not per device, a node the visible ordinals do not own declining, each probe decline falling back to the DirectX join, and the ctypes layer itself over a fake winreg-style module (LUID and node mask read back, the name guard, an absent symbol, an unloaded runtime, an all-zero LUID). 40 in the file, 113 across the ROCm/VRAM/context suites.

Split out of #8863 at review request.

… LUID

Windows ROCm has no amd-smi and hipMemGetInfo does not see other processes, so
used VRAM comes from the per-adapter "GPU Adapter Memory\Dedicated Usage"
counter. Nothing keyed that counter to a torch device, so it was attributed by
ranking usages against device capacities, and a value was emitted only when
capacity FORCED the pairing. One visible GPU forces nothing -- there is no
smaller card for its usage to exceed -- so the single-GPU host, the common AMD
Windows case, always read Unknown. The host aggregate needed the counters to
number the visible devices exactly, which the Basic Render Driver and an idle
iGPU break, so it was unknown too.

Windows names each counter instance after the adapter LUID, and DirectX keeps a
record per LUID under HKLM\SOFTWARE\Microsoft\DirectX carrying the same
Description string torch reports as props.name. Join on that instead: identity
needs no disambiguation, so a lone card resolves exactly, and a busy foreign
adapter beside an idle Radeon no longer blocks the read. Every case the join
cannot establish falls back to the capacity ranking unchanged.
Reading an adapter subkey could fail and leave the rest of the map
standing. A partial map is indistinguishable from a complete one at the
join, so a visible card whose own record was unreadable could be handed a
hidden same-named card's counter. Adapter records are GUID-named, which
tells them from ShaderCache without inferring it from a missing VendorId,
and any read failure past that point now empties the map, which falls
back to capacity ranking.

The join itself now tries two keys. DirectX takes the Description from
the driver INF and HIP fills props.name from the ASIC record, so one card
can reach the two sides spelled differently: the trademark marks and the
spacing around them are normalized away, and when the names still
disagree the gfx target both sides also carry settles it
(AdapterFamily=AMD_NAVI44:gfx1200 against gcnArchName=gfx1200). That is
what an iGPU beside a dGPU needs, where the archs differ but the
marketing names may not resolve. Name first, because it separates a 9070
from a 9070 XT where the shared arch cannot. The arch pass runs only when
every AMD record has a family, so a driver too old to write one cannot
let the records that have it answer for the adapter that does not.

Verified live on Windows 11 / RX 9060 XT: the walk skips ShaderCache and
the Basic Render Driver and resolves the card's own counter.
…ectX record

Stacks on unslothai#8863. That PR reaches a device through what the two sides say
about it, the DirectX Description or the gfx target, which cannot separate
two cards of one model: both report one string and one arch, so both get the
aggregate and neither a figure of its own. HIP already knows the answer.
hipDeviceProp_tR0600 carries the same DXGI LUID the GPU Adapter Memory
counter instances are named after, so asking the runtime joins on the adapter
rather than on anything about it, and identical cards resolve.

Idea and the R0600 route from @pablo86gr in unslothai#8793, with its two review
findings addressed. Ordinals come from visible_ordinal, not from dev_meta
positions, which are compacted when a device fails to probe and would
otherwise hand ordinal 0's LUID to the card that survived at ordinal 1.
luidDeviceNodeMask is read and used: a linked-node adapter puts several
ordinals behind one LUID while the counters index its nodes as phys_N, and
nothing pairs the two, so those ordinals report unknown per device and the
mask is what says whether their counters are all of that adapter's nodes or
whether one belongs to a node HIP is not showing.

The offsets are hardcoded, so the name is read back from the head of the
struct and compared against the device's own; a layout that ever moved is
caught rather than trusted. The probe declines as a whole, like the DirectX
map, and falls back to it: off Windows, runtime not loaded in this process,
symbol absent, an ordinal that will not answer, an all-zero LUID.

Verified on Windows 11 / RX 9060 XT with the runtime loaded: HIP reports
luid 0x14ad4 node mask 0, the live counter instance is
luid_0x00000000_0x00014ad4_phys_0, and the HIP join and the DirectX join
independently agree on the same figure. The probe resolves it with
torch.cuda.is_initialized() still False, so a telemetry poll does not buy a
context to ask.

Split out of unslothai#8863 at review request.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the HIP hipGetDevicePropertiesR0600 probe in studio/backend/utils/hardware/hardware.py resolves the per-adapter LUID that the DirectX Description join cannot separate for two cards of one model, with the DirectX path kept as fallback. Since this sits on top of #8863, I will review that one first and then take this.

LeoBorcherding added a commit to LeoBorcherding/unsloth that referenced this pull request Aug 24, 2026
…apshot

Two of the three Codex P2s on unslothai#9314.

A negative cooked `Shared Usage` sample is a broken reading, not low usage.
The caller clamps the upper bound only and the payload derives free as total
minus used, so a negative sum publishes a negative used_gb and a free above
total. It now declines for the same reason a failed Shared query declines:
nothing available here can tell how much of the reading is wrong.

Passing `adapters=None` into `_rocm_windows_unified_used_bytes` reads as "not
supplied", so the helper re-ran the ~1.3 s PowerShell query on the polled
telemetry path only to arrive at the same None. Guarded at the call site.

The third P2 is not fixable here. Declining whenever a visibility mask is set
would disable the unified path on nearly every host: `win_rocm` itself sets
HIP_VISIBLE_DEVICES="0,1" because a mask is how this codebase expresses the
visible set, not an anomaly. That guard broke 6 tests, including
test_the_dedicated_snapshot_is_not_sampled_twice, and was reverted. Proving a
counter belongs to the visible device needs a counter-instance to torch-device
key, which is the LUID join in unslothai#8863 and unslothai#9316.

Both fixes are mutation-checked, each caught by its own test.
danielhanchen added a commit that referenced this pull request Aug 25, 2026
…rve-out (#9314)

* Studio: take the AMD APU total on Windows from the driver, not the carve-out

_rocm_windows_per_device_vram read props.total_memory verbatim. On a
unified-memory APU that is the dedicated carve-out rather than what torch can
use, so a 128 GiB Strix Halo was budgeted as roughly 8. Every other path
already corrects this through _rocm_props_total_is_carve_out, the classifier
the training worker and the llama.cpp backend also use;
_torch_get_device_inventory pays mem_get_info for exactly this and only on an
APU. This path did not.

The occupancy that goes with the widened total is left unknown. Used comes
from the GPU Adapter Memory\Dedicated Usage counter, which counts the
carve-out, while the working set on an APU lives in the shared segment the
widened total now spans, and /api/system reports free as total minus used. A
model resident in shared memory would otherwise read as almost none of a very
large card and hand the whole pool back as free. Completing it means reading
Shared Usage as the matching numerator, which needs an APU to validate
against rather than a guess.

The guard keys on the total having actually widened, not on the classifier's
answer, which reports carve-out for a discrete card too whenever the runtime
leaves it unsettled (no integrated flag, HIP below 6.2). The driver total
comes back equal there, so nothing widens and no discrete card loses its
reading or pays a context for it.

Split out of #8863 at review request.

* Rank the Windows ROCm adapter counters against the carve-out, not the widened APU total (#9314)

The pool-widened total was passed into _match_adapter_used_to_devices and
_rocm_windows_aggregate_used_bytes, which rank the Dedicated Usage counters
against device capacity. That counter measures the dedicated segment, so its
ceiling is the carve-out and never the pool. Widening one slot from 8 GiB to
128 GiB reranked the APU above every discrete card, raised the threshold that
forces a pairing, and raised the ceiling of the impossible-counter check. The
total_is_pool guard runs after the matching and nulls only the widened device,
so it could not reach the damage: on an APU plus discrete host the discrete
card lost a capacity-forced reading, and a counter that fits no visible card
shifted the others down a rank and landed on one as a fabricated value.

Keep props.total_memory as the capacity the counters are ranked against and use
the widened total only for the displayed total_gb.

Also adopt the driver total only when it is strictly larger. It was assigned
unconditionally, so a driver total below props.total_memory shrank the total
while total_is_pool stayed false and the used was kept, reporting past 100%
utilization and zero free through free = max(total - used, 0). The classifier
answers carve-out for a discrete card on an unsettled runtime too, so this is
reachable outside an APU.

Four tests added: both matcher branches on a mixed APU plus discrete host, the
impossible counter, and a driver total below the carve-out. 22 pass in that
file, 252 across the ROCm/VRAM/system-poll tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep a device when the carve-out probe throws, and cover the platform matrix (#9314)

Simulation across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD discrete, AMD
APU, CPU-only] turned up one regression this branch introduced. The carve-out
correction put a new call to _rocm_props_total_is_carve_out inside the
per-device try, and that classifier is the first thing the path now asks. If it
throws, the except drops the device, so a single failing probe emptied the
whole visible set and the System tab showed no GPU at all. Before this branch
the function never called the classifier, so it could not happen.

The probe now sits in its own try and a failure costs the device its
correction, not its place in the list, which is the rule
_torch_get_device_inventory already states for the same probe.

Two tests added: a throwing classifier keeps both cards on their carve-out
totals, and the path stays inert off Windows, which is what keeps Linux, WSL
and macOS out of reach of any of this.

Recorded while simulating, and deliberately not changed here because it is
older than this branch and identical before and after it: when the counters
number no more than the visible devices, _match_adapter_used_to_devices clamps
a usage onto the card it ranked it against, so a hidden adapter busier than any
visible card reads as that card being exactly full.

* Pin the widened total at the caller, and stop the inventory shrinking too (#9314)

Docstring first: _rocm_windows_per_device_vram still said the total came from
torch properties, which this branch made untrue, and still listed only two
reasons for an unknown used. Both now describe what the function does.

Both matcher helpers now state the requirement their callers have to meet, that
device_totals is the DEDICATED capacity a counter can fill and never a unified
total. The ranking bug this branch already fixed was easy to introduce because
nothing said so.

_torch_get_device_inventory is the correction this path is modelled on and it
still adopted the driver total unconditionally, so it could shrink for the same
reason this one could. It publishes no used, so a shrink cannot invert used and
total there, but an understated total hides models the device can hold, which
is the failure the classifier exists to prevent. It now takes the wider of the
two, and its probe moved inside the try for the same reason as the other path.

Two caller-level tests, which is the gap that mattered most: every test here
called the helper directly, so nothing pinned what the user actually sees. The
corrected total now has to survive get_gpu_utilization, including the legacy
primary-device mirror, and the System tab has to leave free unknown rather than
reporting a 128 GiB card as 128 GiB free while a model sits in the shared pool.

Also a debug line when a total widens, so a report from an affected machine
shows whether the correction fired.

28 pass in this file, 1763 across the backend gpu, hardware, vram, rocm, amd,
system and cuda tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add a temporary Windows AMD APU diagnostic for #9314

Nothing in CI can check the premise this change rests on: that on Windows
props.total_memory is the BIOS carve-out while hipMemGetInfo's total spans the
whole pool. The Linux gfx1151 runner measured the two as identical at 64 GiB,
which is consistent with it being a WDDM phenomenon but does not establish it,
and a Linux APU cannot be used as a stand-in.

scripts/rocm_windows_apu_probe.py answers three things on a Windows AMD APU:

  1. Whether the two totals actually disagree there. If they do not, this PR is
     widening a total that was already right.
  2. Which performance counter moves when the GPU really holds memory.
     --allocate takes a reading, holds N GiB, and takes it again. Studio reads
     Dedicated Usage; if a resident model lands in Shared Usage instead, that is
     the numerator this PR deferred for want of hardware, and the reading
     settles the open question in the description.
  3. What Studio reports end to end, alongside what it would have reported
     before this change.

Reads only, uploads nothing, and prints a report to paste into the PR. Degrades
rather than failing off Windows, where the counters do not exist and the code
path is inert.

Temporary: delete it once a Windows APU reading is on the PR.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe: run detection before reading the classifier, and show the pairing (#9314)

From the Windows gfx1151 reading on the PR. read_studio() imported the hardware
module but never called ensure_hardware_detected(), so IS_ROCM was still False
at module scope and _rocm_props_total_is_carve_out short-circuited on its first
line. The probe reported the classifier as not firing without ever exercising
the path this PR changes, and it would have done that most misleadingly on the
machines the reading was asked for. Detection now runs first.

Also prints the raw adapter counters, the matcher result and the aggregate
helper. On a single-APU box the pairing declines before the widened-total rule
is consulted, so a used_gb of null there is the counter-to-device matching
saying it cannot attribute, not the APU suppression. Reading the probe should
not require reconstructing that by hand.

And the carve-out comment now records what was measured. On that machine
props.total_memory already spans the GTT pool, 89.47 GB against a 32 GB BIOS
carve-out, so props.total_memory being the carve-out is a property of some
stacks rather than of Windows. The strictly-greater comparison is what keeps the
correction inert where the two agree, which is what that reading exercised.

116 pass across the ROCm/VRAM/APU files, 786 in the platform simulation.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe: settle the counters before reading them (#9314)

From the second Windows gfx1151 reading. GPU Adapter Memory lags by tens of
seconds: an adapter was observed reporting 30.6 GB and taking well over a minute
to fall back to a ~1.4 GB idle, and a GPU Process Memory instance still reported
47 GB for a pid that had already exited. Read cold, a run started while an
earlier one is still draining takes a before that is already inflated and an
after that is still climbing.

That is not a cosmetic error. The contaminated run reported +13.88 Dedicated
against +1.57 Shared for an 8 GiB allocation, where two clean runs both give
+8.07 against +0.02. Pasted in good faith it would have argued that Shared Usage
moves materially with a resident model, which is the opposite of the answer, and
the whole point of this script is that a stranger runs it once and pastes what
it prints.

Both readings now poll Dedicated Usage until it stops moving, within 0.25 GB
across three samples, up to --settle-timeout. The report says whether it settled
and prints the samples, so a run that never settled is visible as contaminated
rather than looking like a result. The after reading settles too: it climbs for
a while after the allocation lands.

Also prints the per-adapter delta directly, since that is where the conclusion
lives and subtracting two tables by hand is how the wrong one gets quoted.

--no-settle keeps the old cold read for anyone wanting to see the effect.

The settle loop is checked against a simulated draining counter, a never-settling
one, an already-idle one and one drifting just past tolerance.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record what the carve-out premise actually rests on (#9314)

Two APUs have now been measured and neither shows the gap this classifier is
named for. Windows gfx1151, driver 32.0.21041.1000, torch 2.11.0+rocm7.13.0:
props.total_memory and hipMemGetInfo agree at 89.47 GB against a 32 GB BIOS
carve-out. Linux gfx1151: both 64 GB. On both, props.total_memory already spans
the pool.

The docstring cited _apply_unified_memory_correction as the reason to believe
otherwise. That function adopts torch's total over amd-smi's, because amd-smi
reports the carve-out. torch against amd-smi is a real and provenanced gap; it
is not this one, which is props.total_memory against hipMemGetInfo inside torch,
and the citation does not support it.

Nor do the issues. #8862 and #7449 both report used VRAM reading Unknown, not an
understated total. So a stack where these two totals disagree is inferred rather
than observed, and the docstring now says so and tells callers to compare and
adopt only a larger driver total instead of adopting outright.

No behaviour change. The comparison this describes is already what the code
does, which is why both measured machines see it correctly do nothing.

* Gate the unified numerator on positive UMA, clamp it, and reuse the counter snapshot (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Select the unified numerator by the part, not by whether this call widened (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require the counters to leave the baseline, and union both snapshots (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require a confirmed driver total before the unified numerator (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hold the pre-allocation settle window shut for a stale plateau (#9314)

* Do not attach a HIP context on a card that is not positively unified (#9314)

* Settle per adapter, and allocate on the identified APU (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Decline a negative counter reading, and stop re-querying an absent snapshot

Two of the three Codex P2s on #9314.

A negative cooked `Shared Usage` sample is a broken reading, not low usage.
The caller clamps the upper bound only and the payload derives free as total
minus used, so a negative sum publishes a negative used_gb and a free above
total. It now declines for the same reason a failed Shared query declines:
nothing available here can tell how much of the reading is wrong.

Passing `adapters=None` into `_rocm_windows_unified_used_bytes` reads as "not
supplied", so the helper re-ran the ~1.3 s PowerShell query on the polled
telemetry path only to arrive at the same None. Guarded at the call site.

The third P2 is not fixable here. Declining whenever a visibility mask is set
would disable the unified path on nearly every host: `win_rocm` itself sets
HIP_VISIBLE_DEVICES="0,1" because a mask is how this codebase expresses the
visible set, not an anomaly. That guard broke 6 tests, including
test_the_dedicated_snapshot_is_not_sampled_twice, and was reverted. Proving a
counter belongs to the visible device needs a counter-instance to torch-device
key, which is the LUID join in #8863 and #9316.

Both fixes are mutation-checked, each caught by its own test.

* Apply the matcher's placeholder rule, skip a failed query, clamp below zero (#9314)

* Apply the matcher placeholder rule, and drop a test the branch already had

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the measured Strix Halo saturation case (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the mixed APU-plus-discrete host: widen, keep the neighbour, probe once (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin get_device in the inventory test so a GPU-less runner cannot empty it (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record why equal totals are pool-scoped on Windows, and that widening cannot fire (#9314)

* Give a lone gfx1103 the unified numerator its pool-scoped total needs (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 25, 2026
…rve-out (#9314)

* Studio: take the AMD APU total on Windows from the driver, not the carve-out

_rocm_windows_per_device_vram read props.total_memory verbatim. On a
unified-memory APU that is the dedicated carve-out rather than what torch can
use, so a 128 GiB Strix Halo was budgeted as roughly 8. Every other path
already corrects this through _rocm_props_total_is_carve_out, the classifier
the training worker and the llama.cpp backend also use;
_torch_get_device_inventory pays mem_get_info for exactly this and only on an
APU. This path did not.

The occupancy that goes with the widened total is left unknown. Used comes
from the GPU Adapter Memory\Dedicated Usage counter, which counts the
carve-out, while the working set on an APU lives in the shared segment the
widened total now spans, and /api/system reports free as total minus used. A
model resident in shared memory would otherwise read as almost none of a very
large card and hand the whole pool back as free. Completing it means reading
Shared Usage as the matching numerator, which needs an APU to validate
against rather than a guess.

The guard keys on the total having actually widened, not on the classifier's
answer, which reports carve-out for a discrete card too whenever the runtime
leaves it unsettled (no integrated flag, HIP below 6.2). The driver total
comes back equal there, so nothing widens and no discrete card loses its
reading or pays a context for it.

Split out of #8863 at review request.

* Rank the Windows ROCm adapter counters against the carve-out, not the widened APU total (#9314)

The pool-widened total was passed into _match_adapter_used_to_devices and
_rocm_windows_aggregate_used_bytes, which rank the Dedicated Usage counters
against device capacity. That counter measures the dedicated segment, so its
ceiling is the carve-out and never the pool. Widening one slot from 8 GiB to
128 GiB reranked the APU above every discrete card, raised the threshold that
forces a pairing, and raised the ceiling of the impossible-counter check. The
total_is_pool guard runs after the matching and nulls only the widened device,
so it could not reach the damage: on an APU plus discrete host the discrete
card lost a capacity-forced reading, and a counter that fits no visible card
shifted the others down a rank and landed on one as a fabricated value.

Keep props.total_memory as the capacity the counters are ranked against and use
the widened total only for the displayed total_gb.

Also adopt the driver total only when it is strictly larger. It was assigned
unconditionally, so a driver total below props.total_memory shrank the total
while total_is_pool stayed false and the used was kept, reporting past 100%
utilization and zero free through free = max(total - used, 0). The classifier
answers carve-out for a discrete card on an unsettled runtime too, so this is
reachable outside an APU.

Four tests added: both matcher branches on a mixed APU plus discrete host, the
impossible counter, and a driver total below the carve-out. 22 pass in that
file, 252 across the ROCm/VRAM/system-poll tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep a device when the carve-out probe throws, and cover the platform matrix (#9314)

Simulation across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD discrete, AMD
APU, CPU-only] turned up one regression this branch introduced. The carve-out
correction put a new call to _rocm_props_total_is_carve_out inside the
per-device try, and that classifier is the first thing the path now asks. If it
throws, the except drops the device, so a single failing probe emptied the
whole visible set and the System tab showed no GPU at all. Before this branch
the function never called the classifier, so it could not happen.

The probe now sits in its own try and a failure costs the device its
correction, not its place in the list, which is the rule
_torch_get_device_inventory already states for the same probe.

Two tests added: a throwing classifier keeps both cards on their carve-out
totals, and the path stays inert off Windows, which is what keeps Linux, WSL
and macOS out of reach of any of this.

Recorded while simulating, and deliberately not changed here because it is
older than this branch and identical before and after it: when the counters
number no more than the visible devices, _match_adapter_used_to_devices clamps
a usage onto the card it ranked it against, so a hidden adapter busier than any
visible card reads as that card being exactly full.

* Pin the widened total at the caller, and stop the inventory shrinking too (#9314)

Docstring first: _rocm_windows_per_device_vram still said the total came from
torch properties, which this branch made untrue, and still listed only two
reasons for an unknown used. Both now describe what the function does.

Both matcher helpers now state the requirement their callers have to meet, that
device_totals is the DEDICATED capacity a counter can fill and never a unified
total. The ranking bug this branch already fixed was easy to introduce because
nothing said so.

_torch_get_device_inventory is the correction this path is modelled on and it
still adopted the driver total unconditionally, so it could shrink for the same
reason this one could. It publishes no used, so a shrink cannot invert used and
total there, but an understated total hides models the device can hold, which
is the failure the classifier exists to prevent. It now takes the wider of the
two, and its probe moved inside the try for the same reason as the other path.

Two caller-level tests, which is the gap that mattered most: every test here
called the helper directly, so nothing pinned what the user actually sees. The
corrected total now has to survive get_gpu_utilization, including the legacy
primary-device mirror, and the System tab has to leave free unknown rather than
reporting a 128 GiB card as 128 GiB free while a model sits in the shared pool.

Also a debug line when a total widens, so a report from an affected machine
shows whether the correction fired.

28 pass in this file, 1763 across the backend gpu, hardware, vram, rocm, amd,
system and cuda tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add a temporary Windows AMD APU diagnostic for #9314

Nothing in CI can check the premise this change rests on: that on Windows
props.total_memory is the BIOS carve-out while hipMemGetInfo's total spans the
whole pool. The Linux gfx1151 runner measured the two as identical at 64 GiB,
which is consistent with it being a WDDM phenomenon but does not establish it,
and a Linux APU cannot be used as a stand-in.

scripts/rocm_windows_apu_probe.py answers three things on a Windows AMD APU:

  1. Whether the two totals actually disagree there. If they do not, this PR is
     widening a total that was already right.
  2. Which performance counter moves when the GPU really holds memory.
     --allocate takes a reading, holds N GiB, and takes it again. Studio reads
     Dedicated Usage; if a resident model lands in Shared Usage instead, that is
     the numerator this PR deferred for want of hardware, and the reading
     settles the open question in the description.
  3. What Studio reports end to end, alongside what it would have reported
     before this change.

Reads only, uploads nothing, and prints a report to paste into the PR. Degrades
rather than failing off Windows, where the counters do not exist and the code
path is inert.

Temporary: delete it once a Windows APU reading is on the PR.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe: run detection before reading the classifier, and show the pairing (#9314)

From the Windows gfx1151 reading on the PR. read_studio() imported the hardware
module but never called ensure_hardware_detected(), so IS_ROCM was still False
at module scope and _rocm_props_total_is_carve_out short-circuited on its first
line. The probe reported the classifier as not firing without ever exercising
the path this PR changes, and it would have done that most misleadingly on the
machines the reading was asked for. Detection now runs first.

Also prints the raw adapter counters, the matcher result and the aggregate
helper. On a single-APU box the pairing declines before the widened-total rule
is consulted, so a used_gb of null there is the counter-to-device matching
saying it cannot attribute, not the APU suppression. Reading the probe should
not require reconstructing that by hand.

And the carve-out comment now records what was measured. On that machine
props.total_memory already spans the GTT pool, 89.47 GB against a 32 GB BIOS
carve-out, so props.total_memory being the carve-out is a property of some
stacks rather than of Windows. The strictly-greater comparison is what keeps the
correction inert where the two agree, which is what that reading exercised.

116 pass across the ROCm/VRAM/APU files, 786 in the platform simulation.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe: settle the counters before reading them (#9314)

From the second Windows gfx1151 reading. GPU Adapter Memory lags by tens of
seconds: an adapter was observed reporting 30.6 GB and taking well over a minute
to fall back to a ~1.4 GB idle, and a GPU Process Memory instance still reported
47 GB for a pid that had already exited. Read cold, a run started while an
earlier one is still draining takes a before that is already inflated and an
after that is still climbing.

That is not a cosmetic error. The contaminated run reported +13.88 Dedicated
against +1.57 Shared for an 8 GiB allocation, where two clean runs both give
+8.07 against +0.02. Pasted in good faith it would have argued that Shared Usage
moves materially with a resident model, which is the opposite of the answer, and
the whole point of this script is that a stranger runs it once and pastes what
it prints.

Both readings now poll Dedicated Usage until it stops moving, within 0.25 GB
across three samples, up to --settle-timeout. The report says whether it settled
and prints the samples, so a run that never settled is visible as contaminated
rather than looking like a result. The after reading settles too: it climbs for
a while after the allocation lands.

Also prints the per-adapter delta directly, since that is where the conclusion
lives and subtracting two tables by hand is how the wrong one gets quoted.

--no-settle keeps the old cold read for anyone wanting to see the effect.

The settle loop is checked against a simulated draining counter, a never-settling
one, an already-idle one and one drifting just past tolerance.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record what the carve-out premise actually rests on (#9314)

Two APUs have now been measured and neither shows the gap this classifier is
named for. Windows gfx1151, driver 32.0.21041.1000, torch 2.11.0+rocm7.13.0:
props.total_memory and hipMemGetInfo agree at 89.47 GB against a 32 GB BIOS
carve-out. Linux gfx1151: both 64 GB. On both, props.total_memory already spans
the pool.

The docstring cited _apply_unified_memory_correction as the reason to believe
otherwise. That function adopts torch's total over amd-smi's, because amd-smi
reports the carve-out. torch against amd-smi is a real and provenanced gap; it
is not this one, which is props.total_memory against hipMemGetInfo inside torch,
and the citation does not support it.

Nor do the issues. #8862 and #7449 both report used VRAM reading Unknown, not an
understated total. So a stack where these two totals disagree is inferred rather
than observed, and the docstring now says so and tells callers to compare and
adopt only a larger driver total instead of adopting outright.

No behaviour change. The comparison this describes is already what the code
does, which is why both measured machines see it correctly do nothing.

* Gate the unified numerator on positive UMA, clamp it, and reuse the counter snapshot (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Select the unified numerator by the part, not by whether this call widened (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require the counters to leave the baseline, and union both snapshots (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require a confirmed driver total before the unified numerator (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hold the pre-allocation settle window shut for a stale plateau (#9314)

* Do not attach a HIP context on a card that is not positively unified (#9314)

* Settle per adapter, and allocate on the identified APU (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Decline a negative counter reading, and stop re-querying an absent snapshot

Two of the three Codex P2s on #9314.

A negative cooked `Shared Usage` sample is a broken reading, not low usage.
The caller clamps the upper bound only and the payload derives free as total
minus used, so a negative sum publishes a negative used_gb and a free above
total. It now declines for the same reason a failed Shared query declines:
nothing available here can tell how much of the reading is wrong.

Passing `adapters=None` into `_rocm_windows_unified_used_bytes` reads as "not
supplied", so the helper re-ran the ~1.3 s PowerShell query on the polled
telemetry path only to arrive at the same None. Guarded at the call site.

The third P2 is not fixable here. Declining whenever a visibility mask is set
would disable the unified path on nearly every host: `win_rocm` itself sets
HIP_VISIBLE_DEVICES="0,1" because a mask is how this codebase expresses the
visible set, not an anomaly. That guard broke 6 tests, including
test_the_dedicated_snapshot_is_not_sampled_twice, and was reverted. Proving a
counter belongs to the visible device needs a counter-instance to torch-device
key, which is the LUID join in #8863 and #9316.

Both fixes are mutation-checked, each caught by its own test.

* Apply the matcher's placeholder rule, skip a failed query, clamp below zero (#9314)

* Apply the matcher placeholder rule, and drop a test the branch already had

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the measured Strix Halo saturation case (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the mixed APU-plus-discrete host: widen, keep the neighbour, probe once (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin get_device in the inventory test so a GPU-less runner cannot empty it (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record why equal totals are pool-scoped on Windows, and that widening cannot fire (#9314)

* Give a lone gfx1103 the unified numerator its pool-scoped total needs (#9314)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
# Conflicts:
#	studio/backend/tests/test_rocm_windows_vram_7072.py
#	studio/backend/utils/hardware/hardware.py
_adapter_counter_capacity arrived with unslothai#8863's merged form, after this
branch was cut, so the HIP join is the one caller still bounding with
total_bytes. On a unified APU that total is the whole driver pool, which
no counter reading can exceed, and the join runs ahead of the DirectX one
that would have declined.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed cdb2a844b6. Main merged in, plus one fix.

The capacity guard in the HIP join bounded the counter with total_bytes, where every other caller uses _adapter_counter_capacity. That helper landed with #8863's merged form, after this branch was cut, so the HIP path was the only caller left on the old bound. On a unified APU total_bytes can be the whole driver pool, which no counter reading can exceed, so the guard admitted readings the DirectX join declines, and the HIP path runs first. It now bounds by the carve-out. Test added: the same 2 GiB reading against a 512 MiB carve-out is declined by both paths, and a reading inside the carve-out still resolves.

Verified on a second card since the description was written. Windows 11, Radeon AI PRO R9700, ROCm 7.13, torch 2.11.0+rocm7.13.0, measured at cdb2a844b6:

HIP identity : luid 0x142b9, node mask 0
counter      : luid_0x00000000_0x000142b9_phys_0
hip join     : 3.9318 GiB    directx join : 3.9318 GiB

Both paths agree to the byte, as they did on the 9060 XT. In a fresh process the probe resolves the LUID with torch.cuda.is_initialized() still False both before and after, so a telemetry poll still buys no HIP context. Two foreign adapters on the same box report 0.0 and are correctly left out, since HIP does not enumerate them.

87 tests in the file, 234 across the ROCm and VRAM suites, measured at cdb2a844b6. Two failures in test_system_poll_no_cuda_context.py (test_rocm_apu_keeps_the_carve_out_when_the_driver_total_fails and test_linux_rocm_shared_pool_declines_ambiguous_masks[ROCR_VISIBLE_DEVICES]) reproduce on upstream/main's own hardware.py against the identical test file, so they are not this PR's.

@LeoBorcherding LeoBorcherding self-assigned this Sep 2, 2026
@LeoBorcherding LeoBorcherding changed the title Studio: ask HIP for the adapter LUID before inferring it from the DirectX record fix(amd): ask HIP for the adapter LUID before inferring it from the DirectX record Sep 2, 2026
@danielhanchen

Copy link
Copy Markdown
Member

main now has the HIP hipGetDevicePropertiesR0600 probe and the LUID join in studio/backend/utils/hardware/hardware.py, tried ahead of the DirectX record, so I do not think this branch is needed any more. Sorry for the slow review, and thanks for putting it together.

@danielhanchen

Copy link
Copy Markdown
Member

main already asks HIP for the adapter LUID in studio/backend/utils/hardware/hardware.py, via the work that landed with #9317, so I do not think this branch is needed any more. Sorry for the slow review, and thanks for putting it together.

@danielhanchen

Copy link
Copy Markdown
Member

I went through all seven of the open AMD PRs together, on real gfx1151 Strix Halo hardware for the parts that hardware can answer and on a simulated OS x accelerator matrix for the rest. This one I am recommending we close, and I want to lay out exactly why so it is reviewable rather than just a decision.

Before and after

Before this PR was written: on Windows with an AMD card, Studio joined the GPU Adapter Memory performance counters to torch's devices by name. Names are not unique, so on a machine with two identical adapters the join was ambiguous and Settings > System could attribute memory to the wrong card.

What this PR does: reads the LUID out of hipDeviceProp_tR0600 (fixed offsets 272 and 280) and joins on that instead, which is unique per adapter.

That is a real problem and the approach is the right one.

The issue is that main already does this

_rocm_windows_hip_adapter_ids and _match_adapter_used_by_hip_luid landed on main in 55ba564 on 2026-09-03, via your own #9317. They are at studio/backend/utils/hardware/hardware.py:2887 and :2941 today.

Main's version is a strict superset of this one, in two ways:

  1. It returns a 3-tuple, not a 2-tuple. The third element, whole_adapter, is what drives the per-adapter utilization fix. It is unpacked at hardware.py:3418 and consumed at :3464. This PR's 2-tuple version would delete that, so merging it would revert Studio: count only this adapter's engines in the Windows AMD GPU utilization #9317's actual behaviour change.
  2. It has the luidDeviceNodeMask naming check that this version does not.

I verified the offsets independently and they are right: name[256], hipUUID[16], then luid[8] at 272 and luidDeviceNodeMask[4] at 280. That part of the work is sound, it just already shipped.

Recommendation

Close as superseded by #9317. Nothing here is wrong, it is the earlier draft of a change that is already in main and has since grown a feature this version does not carry. If there is a specific piece you think main is still missing, point me at it and I will look again rather than close on my reading alone.

@danielhanchen

Copy link
Copy Markdown
Member

Closing as superseded by #9317, which landed on main in 55ba564 on 2026-09-03.

Main's studio/backend/utils/hardware/hardware.py already asks HIP for the adapter LUID through hipGetDevicePropertiesR0600 (_rocm_windows_hip_adapter_ids) and joins the performance counters on it ahead of the DirectX Description record (_match_adapter_used_by_hip_luid). Main's version is a strict superset of this branch: it returns the 3-tuple whose third element drives the per-adapter utilisation fix, and it carries the luidDeviceNodeMask naming check. Merging this branch over it would revert both.

The offsets this branch reads (name[256], hipUUID[16], luid[8] at 272, luidDeviceNodeMask[4] at 280) are correct; that work shipped through #9317. If you see a case main still gets wrong on two identical adapters, open an issue with the counter names and I will look at it against main rather than this branch.

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.

2 participants