Skip to content

fix(amd): report AMD VRAM on Windows by joining the adapter counters on LUID - #8863

Merged
danielhanchen merged 19 commits into
unslothai:mainfrom
LeoBorcherding:fix-amd-windows-vram-monitor
Aug 25, 2026
Merged

danielhanchen merged 19 commits into
unslothai:mainfrom
LeoBorcherding:fix-amd-windows-vram-monitor

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #8862. Should also cover the "does not recognize the VRAM free or used" half of #7449; see the limitation below for why I'm not claiming the whole of it.

Windows ROCm reads used VRAM from the per-adapter GPU Adapter Memory\Dedicated Usage counter, because amd-smi is unavailable and hipMemGetInfo is process-local. Nothing keyed a counter to a torch device, so _match_adapter_used_to_devices attributed by ranking usages against device capacities and emitted a value only where capacity forced the pairing. A single visible GPU forces nothing -- no smaller card exists for its usage to exceed -- so it always reported Unknown as soon as any extra adapter instance was present, which on Windows is always. The host aggregate declined on the same host because it requires the counter list to match the visible set exactly.

Windows names each counter instance after the adapter LUID, and DirectX keeps a record per LUID under HKLM\SOFTWARE\Microsoft\DirectX carrying VendorId and the same Description string torch reports as props.name. _match_adapter_used_by_luid joins on that. Identity needs no disambiguation, so a lone card resolves exactly, and a busy foreign adapter beside an idle Radeon no longer blocks the read.

The name is tried first, since it separates two cards of one arch where the arch cannot. DirectX takes it from the driver INF and HIP from the ASIC record, so a declined name join falls to the gfx target both sides also carry, which is what tells an iGPU from the dGPU beside it. The arch pass runs only when every AMD record has one, so a driver too old to write AdapterFamily cannot let a hidden card stand in for the visible one.

The join declines -- and hands back to the existing capacity ranking unchanged -- when the registry is unreadable, a visible device has no AMD record holding a counter, a same-named adapter HIP doesn't enumerate, or a usage exceeds its own card's capacity. Two identical cards share one Description, so per-device stays unknown while the aggregate, which the pairing doesn't change, stays exact.

Counters are bounded by _adapter_counter_capacity, not the displayed total. Dedicated Usage measures the dedicated segment, so the carve-out is its ceiling; ranking against a pool-sized total would let a counter no visible card could hold pass the sanity check. That matters once #9314 widens the displayed total on a unified APU, and is a no-op here.

Scope

This branch is the LUID join only. The rest of the original diff went out separately:

Known limitation

The counter this joins is Dedicated Usage. On a discrete card that is the whole story. On a unified-memory APU the working set spills into the shared pool, so the per-device figure here reads real but low. #9362 has since landed _rocm_windows_unified_used_bytes, which reads Shared Usage with measurements from a gfx1151 host, but on the context-free free-memory path rather than this one. Reconciling the two is a follow-up.

Temperature and power remain unavailable on Windows ROCm and still read --.

Verification

Live /api/system on Windows 11, RX 9060 XT, ROCm 7.13, torch 2.11.0+rocm7.13.0:

before   vram_used_gb: null   vram_free_gb: null    vram_utilization_pct: null   aggregate: null
after    vram_used_gb: 3.75   vram_free_gb: 12.17   vram_utilization_pct: 23.6   aggregate: 3.75

Measured on 54cec09, before this branch was reduced to the join. The join is the component those numbers came from and is unchanged in behaviour since, but I'm labelling them rather than reprinting them as current.

Current head additionally carries @danielhanchen's windows-latest run (43 pass on ubuntu, macos and windows) and a gfx1151 Strix Halo run through the amd_ci harness (NO_REGRESSION, 144 passed).

Tests

43 in test_rocm_windows_vram_7072.py: LUID parsing, name normalization and AdapterFamily parsing; the single-GPU regression on both endpoints; an idle Radeon beside a busy foreign adapter; identical cards keeping the aggregate but not per-device; iGPU and dGPU each reporting their own, including under two spellings and via arch when names cannot reconcile; the arch pass declining on a record with no family; each decline falling back; the registry read being Windows-only and declining a partial map; the carve-out bound; a name collision falling through to gfx; and usage the join cannot place.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author
image

LeoBorcherding added a commit to LeoBorcherding/unsloth that referenced this pull request Aug 14, 2026
Codex P2 on unslothai#8863: the loaded flag only ever flipped on success, so a single
failed /api/system with polling off left the System tab saying "Checking for
GPUs..." forever, with nothing retrying it. shouldRetrySystemDiscovery bails at
retrySubscribers <= 0 and useSystemInfo's finally returns early without pollMs,
so no request was coming.

Replace the flag with a three-state status. A settled failure moves the
placeholder to unavailable and the tab says it could not read the hardware,
which is true and does not promise a check that is not running. Data already on
screen survives a later failed poll rather than being blanked.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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. Breezy!

Reviewed commit: e810ff5891

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

@LeoBorcherding LeoBorcherding changed the title Studio: report AMD VRAM on Windows by joining the adapter counters on LUID fix(amd): report AMD VRAM on Windows by joining the adapter counters on LUID Aug 17, 2026

@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: 14d890aebe

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@codex review

Since the last review this takes the better half of #8793 (@pablo86gr), which I'm closing as a duplicate, plus two fixes to readings the counters were getting wrong on a mixed host.

Identity now comes from HIP first. hipDeviceProp_tR0600 carries the same DXGI LUID the GPU Adapter Memory instances are named after, so the join lands on the adapter rather than on the Description or gfx target that describe it. That separates two cards of one model, which the DirectX join structurally cannot: both report one string and one arch, so both got the aggregate and neither a figure of its own. The DirectX join stays as the fallback for when the runtime cannot be asked, and capacity ranking stays below that.

Three guards on the probe, since it reads a C struct at fixed offsets:

  • 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.
  • 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. 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 keep the aggregate. The mask decides whether their counters are all of that adapter's nodes or whether one belongs to a node HIP is not showing.

It declines as a whole and falls through, the same way the DirectX map does, on any of: not Windows, runtime not loaded in this process, symbol absent, an ordinal that will not answer, an all-zero LUID.

Two more readings, both wrong on a host with more than one adapter:

  • props.total_memory on a unified-memory APU is the dedicated carve-out, which budgets a 128 GiB Strix Halo as roughly 8. Corrected through _rocm_props_total_is_carve_out, the classifier _torch_get_device_inventory already uses, so only an APU pays a context for it and the untrusted free half is not involved.
  • The GPU Engine instances are named after the adapter too, and the 3D utilization summed every one of them. On a laptop that is the display iGPU's work reported as the dGPU being busy; on my own host it was summing the Basic Render Driver in. Narrowed to the card's own LUID when HIP will say what it is, and unchanged when it will not.

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 the poll does not attach a context to ask.

44 tests in test_rocm_windows_vram_7072.py, up from 31: 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, the APU total, a discrete card still not paying a context for its total, and the utilization query carrying the LUID. 147 passed across the ROCm/VRAM/context suites.

Backend CI is still running on this head. If Repo tests (CPU) comes back red it is test_backend_ci_parallel_isolation::test_an_isolated_file_never_shadows_an_installed_library_with_a_stub, which fails on every recent main run and is unrelated to this branch: test_llama_cpp_wait_for_vram_settle.py installs its loggers stub with sys.modules.setdefault where that rule wants a try: import guard. Happy to send that as its own PR.

@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: 14d890aebe

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

@LeoBorcherding LeoBorcherding self-assigned this Aug 18, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@codex review

P2 confirmed and fixed in d0f74b9. You're right, and the path is concrete: main.py computes vram_free_gb as total - used, so widening the APU total while the numerator stayed Dedicated Usage reported a model resident in the shared segment as almost none of a very large card and handed the whole pool back as free. That was a regression my own previous commit introduced, not a pre-existing gap.

I took the second of the two remedies you offered. A device whose total was widened now reports unknown occupancy, and the host aggregate goes with it because one member of the visible set is unknown; a discrete card beside it keeps its own reading. Reading Shared Usage as the matching numerator is the right end state, and the counter does exist and is populated, but whether dedicated + shared is correct on an APU or double-counts a carve-out that is itself system RAM is not something I can settle without one to measure against. That is the same reason the shared read was left out to begin with, so I would rather report the corrected total and an honest unknown than a number I cannot check.

The guard keys on the total having actually widened, not on the classifier's answer. _rocm_props_total_is_carve_out reports carve-out for a discrete card too whenever the runtime leaves it unsettled (no integrated flag, HIP below 6.2), and there the driver total comes back equal, so nothing widens and no discrete card loses its occupancy. There is a test on that case specifically.

Also merged main, which this branch was behind. Worth flagging for anyone reading the checks: Backend CI is currently failing on main itself with 74 distinct tests, the same set across its last three runs, so this branch now inherits that. The suites this PR touches pass locally: 46 in test_rocm_windows_vram_7072.py, 149 across the ROCm/VRAM/context tests.

@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: d0f74b9785

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Both review findings from the last two rounds are addressed and pushed.

a2c3166 — the engine counters are now filtered on a LUID the device is established to own. The mask alone could not settle it: one bit set reads identically whether the ordinal owns the only node or one of two, so filtering to "the mask's physical-node indices" would infer a mask-bit to phys_N correspondence I declined to infer for the memory counters. What does settle it is the node count the VRAM join already checks, the number of counter instances that LUID has. The join hands the LUID back only for a device it established is the whole of what that LUID names, and the engine query filters on that. Where it did not, the LUID is absent and the sum stays the host's, which is what it has always been. That also drops a second identity probe per poll.

d0f74b9 — a device whose total was widened to the unified pool reports unknown occupancy rather than counting a shared-segment working set against a dedicated-segment numerator.

Also merged main, and picked up one unrelated line while doing it. Frontend CI has been red on main since #9173: studio/frontend/src/features/chat/utils/image-input-support.ts imports "./mmproj-fallback" without an extension. Vite and tsc resolve that, the node test runner's ESM resolver does not, and queued-model-capabilities.test.ts reaches the module transitively, so the file failed to load:

ERR_MODULE_NOT_FOUND: Cannot find module '...chat/utils/mmproj-fallback'
  imported from ...chat/utils/image-input-support.ts

Adding the extension fixes it. Not this branch's bug, taken here only because it is one line and this PR changes frontend files, so its frontend checks could not go green without it. Happy to split it out if you would rather it went in on its own.

Local state: 3797 frontend unit tests, build and typecheck clean, 150 across the ROCm/VRAM/context suites, 47 in test_rocm_windows_vram_7072.py. The remaining red checks are main's own, the same sets failing on its recent runs.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 54cec0919f

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

ci failures are unrelated to this pr
image

@danielhanchen

danielhanchen commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Confirmed the single-device case in hardware.py where the capacity guard never fires, so the counter is dropped and used VRAM reads Unknown; the LUID join is the right direction, but this branch also carries the HIP probe, the APU total change, the engine utilization rework and the Settings placeholder fix, so could you split those out and keep this to the LUID join?

… 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.
@LeoBorcherding
LeoBorcherding force-pushed the fix-amd-windows-vram-monitor branch from 54cec09 to f3d2ed2 Compare August 19, 2026 18:36
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 564933801b

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

Re-running this on the Windows AMD machine, start to finish

Consolidating what is worth running here, since several earlier comments on this PR have been superseded. Everything is inline; nothing needs fetching from a branch.

Setup, once

git fetch https://github.com/LeoBorcherding/unsloth fix-amd-windows-vram-monitor
git worktree add ..\pr8863 FETCH_HEAD

Only one checkout this time. The LUID join is new in this PR, so there is nothing on main to compare against; the scripts print the capacity-ranking answer beside the join's, which is what main would have done.

Activate the venv with the ROCm torch build. Steps 1 and 2 need no admin; step 3 does.

1. The module's reader against the real registry (about 10 seconds, no admin)

real_registry.py, below:

python real_registry.py ..\pr8863\studio\backend

This is the one check nothing else substitutes for. It runs the module's own registry walk against HKLM\SOFTWARE\Microsoft\DirectX on this machine and prints what it found. Everything else assumes that reader works.

  • records: {} is the result that matters. Empty means the join declines on this hardware and every device falls back to capacity ranking, which is where they already were, so it is safe but it also means this PR does nothing here. If that is what prints, the reason is worth knowing before merging.
  • LUIDs present on both sides should not be NONE. The join is an identity match between the DirectX AdapterLuid and the LUID embedded in the performance counter instance name, and it only works if the two agree. This is the line that proves they do.
  • gfx will likely print as absent. Driver 32.0.21041.1000 writes no AdapterFamily, so the arch fallback is unavailable and the name pass is load bearing on this machine. That is expected, and it is why the code declines rather than guesses when the names do not reconcile.

2. The join with two devices, spoofed (about 20 seconds, no admin)

spoof_two_gpus_windows.py, below:

python spoof_two_gpus_windows.py ..\pr8863\studio\backend --split 2 --clone-adapter

It spoofs the device COUNT and nothing else. --clone-adapter additionally clones this machine's real DirectX record and its real counter row under LUIDs that do not exist, dividing the real bytes between them, so the join sees two records for two devices instead of declining on cardinality. The identity is synthetic; the bytes and the reader are real.

Read the per-device lines and aggregate. Without --clone-adapter the join should decline (one record, two devices) and fall back, which is itself the behaviour worth confirming: a decline must not lose the aggregate.

Note that totals here will not widen to the driver pool. That correction is #9314, not this PR, so on this branch the totals stay at the props total. The two PRs answer different questions and their evidence should not be read across.

It is read-only and in process. Nothing is installed, no registry value is written, no file is touched, and there is nothing to undo.

3. The two-card host this machine does not have (about 30 seconds, needs admin)

sim_two_amd.py, below, from an elevated PowerShell:

python sim_two_amd.py ..\pr8863\studio\backend

This is the #7072 reporter's actual shape: a W7900 holding 40 GiB beside an idle W7500, plus the Basic Render Driver placeholder that made capacity ranking give up. It does NOT touch HKLM\SOFTWARE\Microsoft\DirectX. It creates its own scratch key under HKLM\SOFTWARE\UnslothProbeDirectX, writes two AMD adapter records there, points the module at that path, and deletes the key in a finally block. AdapterFamily is deliberately omitted so it mirrors this machine's driver and leaves the name pass load bearing.

The real winreg, the real HKLM hive and the module's real reader are all in play; only the path is scratch. Expected:

  LUID join     : [40.0, 0.5]
  capacity rank : [40.0, None]
  truth         : [40.0, 0.5]

That None in the middle row is the reporter's screenshot. The join recovering the idle card is the whole point of this PR.

If it exits without printing scratch key removed, the key is still there; delete HKLM\SOFTWARE\UnslothProbeDirectX by hand.

What still will not be covered

Two real AMD cards in one machine. Step 3 writes real registry records but there is still one adapter, one driver and one counter instance behind them, so nothing here catches a defect that needs a second physical card to appear: a second real counter instance, a real AdapterLuid written by a second driver, or the two spelling one card's name differently in a way normalizing does not fix. That is the case the join exists for, and it needs the hardware.

real_registry.py
import sys
sys.path.insert(0, sys.argv[1])
import utils.hardware.hardware as hw
print("detected:", hw.ensure_hardware_detected(), " IS_ROCM:", hw.IS_ROCM)
records = hw._windows_amd_adapter_records_by_luid()
print("key:", hw._WINDOWS_DIRECTX_KEY)
print("records:", records or "{}  <-- EMPTY: the join would decline and fall back")
for luid, rec in sorted((records or {}).items()):
    print(f"  luid={luid} ({hex(luid)})  name={rec.get('name')!r}  gfx={rec.get('gfx', '(none)')!r}")
adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
print("counter instances:", [i for i, _ in (adapters or [])] or "none")
for inst, used in (adapters or []):
    print(f"  {inst}  luid={hw._parse_adapter_luid(inst)}  {used / 1024**3:.3f} GiB")
matched = {hw._parse_adapter_luid(i) for i, _ in (adapters or [])} & set(records or {})
print("LUIDs present on both sides:", sorted(matched) or "NONE")
spoof_two_gpus_windows.py
r"""Present the ONE real AMD GPU on this Windows box as two, read-only.

Unlike the off-Windows harness, nothing here is faked except the device COUNT.
The registry read, the Dedicated/Shared performance counters, the classifier and
the driver pool total are all the real ones on this machine.

Nothing is installed, written or patched on disk. `_torch_get_device_module` is a
module-level function in hardware.py, so it is swapped in process for a proxy.
The process exits and the spoof is gone. Every call this makes is a read; it
touches no registry value, no file and no driver state.

  --split N        show the one GPU as N devices, each carrying 1/N of its
                   props.total_memory. The driver pool total stays whole, so on
                   a Strix Halo this is exactly the carve-out shape the PR
                   corrects, at N times the margin. Note that every device the
                   classifier calls unified widens to the WHOLE pool, so with
                   --second apu the reported totals sum to more than the machine
                   holds. That is the harness splitting one pool N ways, not the
                   PR over-reporting.
  --second         what ordinal 1 pretends to be: `discrete` (default) gives it
                   a discrete card's name, arch and is_integrated=0, so the real
                   classifier has to decline it; `apu` leaves it a copy of the
                   real device.
  --clone-adapter  additionally clone this machine's real DirectX record and its
                   real counter row under synthetic LUIDs, so the LUID join sees
                   N records for N devices instead of declining on cardinality.

The single most useful run on a Strix Halo is the default:

    python spoof_two_gpus_windows.py ...\studio\backend --split 2

ordinal 0 is the real APU and ordinal 1 a discrete card that does not exist. The
APU's total should widen to the driver pool, the discrete card's should stay at
its own props total, and `mem_get_info called for ordinals` should read `[0]`.
That last line is the one this box can prove and CI cannot: probing a device
attaches a HIP primary context worth roughly 612 MiB for the life of the
process, so a probe of the discrete card would be a permanent cost on hardware
that never needed the correction.

Run it in a checkout of the PR and again in a checkout of main, and compare.

    python spoof_two_gpus_windows.py C:\path\to\studio\backend --split 2
"""
import argparse
import copy
import sys
import types

GB = 1024**3


class _Props:
    """A real props object with total_memory overridden. Attributes are copied,
    never mutated on the original, so torch's own record is untouched."""

    _COPY = ("name", "gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name",
             "is_integrated", "integrated", "major", "minor", "multi_processor_count")

    def __init__(self, real, total_memory, discrete = False):
        for attr in self._COPY:
            if hasattr(real, attr):
                setattr(self, attr, getattr(real, attr))
        self.total_memory = int(total_memory)
        if discrete:
            # A card the classifier must decline: no unified arch, no integrated
            # flag, and a name carrying none of the shared-pool markers.
            self.name = "AMD Radeon PRO W7900"
            for attr in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):
                if hasattr(self, attr):
                    setattr(self, attr, "gfx1100")
            for attr in ("is_integrated", "integrated"):
                if hasattr(self, attr):
                    setattr(self, attr, 0)


class SplitDeviceModule:
    """One physical device presented as N. Records every probe."""

    def __init__(self, real, props, pool_bytes):
        self._real = real
        self._props = props
        self._pool = pool_bytes
        self.mem_get_info_calls = []

    def device_count(self):
        return len(self._props)

    def is_available(self):
        return True

    def current_device(self):
        return 0

    def get_device_properties(self, i):
        return self._props[i]

    def mem_get_info(self, i):
        # A call here attaches a HIP primary context worth roughly 612 MiB,
        # permanently. Recording it is the only way to check that a device the
        # classifier did not call unified is never probed.
        self.mem_get_info_calls.append(i)
        return self._pool

    def __getattr__(self, name):
        return getattr(self._real, name)


def _clone_adapters(real_adapters, records, n):
    """Give each spoofed device its own LUID, carrying real bytes.

    The real counter row and the real registry record are duplicated under LUIDs
    that do not exist, and the bytes are divided so the machine's real total is
    preserved. Only the identity is synthetic.
    """
    if not real_adapters or not records:
        return real_adapters, records
    base_luid = next(iter(records))
    base_record = records[base_luid]
    biggest = max(real_adapters, key = lambda pair: pair[1])
    instance, used = biggest
    out = [pair for pair in real_adapters if pair is not biggest]
    new_records = dict(records)
    for k in range(n):
        luid = base_luid + 0x100000 * (k + 1)
        out.append((f"luid_0x00000000_0x{luid:08x}_phys_0", used / n))
        new_records[luid] = copy.deepcopy(base_record)
    new_records.pop(base_luid, None)
    return out, new_records


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("backend", help = r"path to <checkout>\studio\backend")
    ap.add_argument("--split", type = int, default = 2)
    ap.add_argument("--second", choices = ("discrete", "apu"), default = "discrete",
                    help = "what ordinals past 0 pretend to be (default discrete)")
    ap.add_argument("--clone-adapter", action = "store_true")
    args = ap.parse_args()

    sys.path.insert(0, args.backend)
    import utils.hardware.hardware as hw

    if hw.platform.system() != "Windows":
        print("This harness is for the Windows AMD box. Off Windows the counters and")
        print("the registry do not exist, and _rocm_windows_per_device_vram returns ([], None).")
        print("Use spoof_two_gpus.py for the off-Windows version.")
        return 2

    import torch

    if not torch.cuda.is_available() or torch.cuda.device_count() < 1:
        print("No ROCm device visible to torch.")
        return 2

    real_props = torch.cuda.get_device_properties(0)
    pool = torch.cuda.mem_get_info(0)          # the real driver numbers
    print(f"real device : {real_props.name}")
    print(f"  props.total_memory : {real_props.total_memory / GB:.2f} GiB")
    print(f"  driver total       : {pool[1] / GB:.2f} GiB   (free {pool[0] / GB:.2f})")
    print(f"  gcnArchName        : {getattr(real_props, 'gcnArchName', '')!r}")
    print(f"  is_integrated      : {getattr(real_props, 'is_integrated', 'absent')!r}")
    print(f"  classifier says positively unified: "
          f"{hw._rocm_props_are_positively_unified(real_props)}")

    real_adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
    print(f"\nreal counters ({len(real_adapters or [])}):")
    for instance, used in (real_adapters or []):
        print(f"  {instance:44s} {used / GB:8.2f} GiB")

    # The DirectX LUID join lives on #8863's branch, not on this one or on main,
    # so read it through getattr: on a branch without it there is no registry
    # half to report and the join simply does not participate.
    read_records = getattr(hw, "_windows_amd_adapter_records_by_luid", None)
    real_records = read_records() if read_records else {}
    if read_records is None:
        print("real DirectX AMD records: n/a on this branch (the LUID join is #8863)")
    else:
        print(f"real DirectX AMD records ({len(real_records)}):")
        for luid, record in real_records.items():
            print(f"  0x{luid:x}  {record}")

    n = max(1, args.split)
    props = [
        _Props(real_props, real_props.total_memory // n,
               discrete = i > 0 and args.second == "discrete")
        for i in range(n)
    ]
    print("\nclassifier verdict per spoofed ordinal, from the real classifier:")
    for i, p in enumerate(props):
        print(f"  ordinal {i}: {p.name:34s} positively_unified="
              f"{hw._rocm_props_are_positively_unified(p)}")
    spoof = SplitDeviceModule(torch.cuda, props, pool)

    adapters = real_adapters
    if args.clone_adapter:
        if read_records is None:
            print("\n--clone-adapter needs the LUID join, which is #8863's branch. Ignored.")
        else:
            adapters, cloned = _clone_adapters(real_adapters, real_records, n)
            hw._windows_amd_adapter_records_by_luid = lambda: cloned
            print(f"\ncloned {n} records/counters from the real one "
                  f"(bytes divided, identity synthetic)")

    hw._torch_get_device_module = lambda: (spoof, "cuda")

    print(f"\n=== presented as {n} device(s), each with "
          f"{props[0].total_memory / GB:.2f} GiB of props total ===")
    devices, aggregate = hw._rocm_windows_per_device_vram(
        list(range(n)), adapters = adapters
    )
    for d in devices:
        print(f"  ordinal {d['index']}  {d['name']:34s} "
              f"used={d['used_gb']} total={d['total_gb']}")
    print(f"  aggregate: {aggregate}")
    print(f"  mem_get_info called for ordinals: {spoof.mem_get_info_calls}")

    print("\nWhat to compare against main:")
    print("  total_gb  should be the DRIVER pool on this PR and the carve-out on main")
    print("  used_gb   should not appear on a device whose total was widened")
    print("  the probe list should hold only devices the classifier called unified")
    return 0


if __name__ == "__main__":
    sys.exit(main())
sim_two_amd.py
r"""Simulate a two-AMD-card Windows host, with the REGISTRY half real.

Needs an elevated PowerShell (writes under HKLM\SOFTWARE). It does NOT touch
HKLM\SOFTWARE\Microsoft\DirectX: it creates its own scratch key, points the
module at it, and deletes it in a finally block.
"""
import sys, winreg

SCRATCH = r"SOFTWARE\UnslothProbeDirectX"
GB = 1024**3
AMD = 4098

# The #7072 host: W7900 48 GB loaded, W7500 8 GB idle, plus a placeholder.
CARDS = [
    ("{11111111-0000-0000-0000-000000000001}", 0xd1e2, "AMD Radeon PRO W7900"),
    ("{22222222-0000-0000-0000-000000000002}", 0xe34a, "AMD Radeon PRO W7500"),
]

def make():
    for guid, luid, name in CARDS:
        with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, SCRATCH + "\\" + guid,
                                0, winreg.KEY_ALL_ACCESS) as k:
            winreg.SetValueEx(k, "VendorId", 0, winreg.REG_DWORD, AMD)
            winreg.SetValueEx(k, "AdapterLuid", 0, winreg.REG_QWORD, luid)
            winreg.SetValueEx(k, "Description", 0, winreg.REG_SZ, name)
            # AdapterFamily deliberately omitted: driver 32.0.21041.1000 omits it,
            # so this mirrors the real machine and leaves the name pass load bearing.

def destroy():
    for guid, _, _ in CARDS:
        try:
            winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, SCRATCH + "\\" + guid)
        except OSError:
            pass
    try:
        winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, SCRATCH)
    except OSError:
        pass

def main(backend):
    sys.path.insert(0, backend)
    import utils.hardware.hardware as hw
    hw._WINDOWS_DIRECTX_KEY = SCRATCH          # real winreg, real HKLM, scratch path

    records = hw._windows_amd_adapter_records_by_luid()
    print("records read back through the REAL winreg path:")
    for luid, rec in sorted(records.items()):
        print(f"  luid={luid} ({hex(luid)})  {rec}")
    assert len(records) == 2, f"expected 2 AMD records, got {len(records)}"

    adapters = [
        ("luid_0x00000000_0x0000d1e2_phys_0", 40.0 * GB),
        ("luid_0x00000000_0x0000e34a_phys_0", 0.5 * GB),
        ("luid_0x00000000_0x0000f001_phys_0", 3 * 1024**2),
    ]
    dev_meta = [
        {"name": "AMD Radeon PRO W7900", "gfx": "gfx1100",
         "total_bytes": 48*GB, "dedicated_bytes": 48*GB},
        {"name": "AMD Radeon PRO W7500", "gfx": "gfx1102",
         "total_bytes": 8*GB, "dedicated_bytes": 8*GB},
    ]
    joined = hw._match_adapter_used_by_luid(adapters, dev_meta)
    ranked = hw._match_adapter_used_to_devices([u for _, u in adapters],
                                               [d["dedicated_bytes"] for d in dev_meta])
    g = lambda xs: [None if u is None else round(u/GB, 2) for u in xs]
    print()
    print("  LUID join     :", g(joined[0]) if joined else "DECLINED")
    print("  capacity rank :", g(ranked))
    print("  truth         : [40.0, 0.5]")

if __name__ == "__main__":
    try:
        make()
        main(sys.argv[1])
    finally:
        destroy()
        print("\nscratch key removed")

@danielhanchen

Copy link
Copy Markdown
Member

Windows AMD machine: the exact items to test, for both #8863 and #9314

One list covering both PRs, since they touch the same file and the same machine is the only one that can settle either. This comment is posted identically on #8863 and #9314; the scripts are at the bottom, so nothing needs fetching from a branch.

Both PRs are Windows-only in effect. windows-latest CI has no AMD GPU and the gfx1151 Linux runner reports multi_gpu: needs at least two GPUs, so neither can reach any of the five items below.

Setup, once

git fetch https://github.com/LeoBorcherding/unsloth fix-amd-windows-vram-monitor
git worktree add ..\pr8863 FETCH_HEAD
git fetch https://github.com/LeoBorcherding/unsloth pr-b-apu-carve-out-total
git worktree add ..\pr9314 FETCH_HEAD
git worktree add ..\mainline origin/main

Save the four scripts from the bottom of this comment anywhere. Activate the venv with the ROCm torch build. Items 1 to 4 need no admin; item 5 does.

Do not read results across the two PRs. #9314 widens the total to the driver pool and #8863 does not; #8863 adds the LUID join and #9314 does not. Each item below says which branch it belongs to.


Item 1 (#9314) The reported bug, under real load

python e2e_9314.py ..\pr9314\studio\backend --hold 48
python e2e_9314.py ..\mainline\studio\backend --hold 48

Everything runs through the module's own code: its PowerShell invocation, its parser, its noise floor, its classifier, its pairing. Every earlier reading on this machine came from a reimplementation of that reader pasted into a comment, which is not the same code.

Look at: the holding 48 GiB block in both runs.

Expected: total_gb is the driver pool on pr9314 and the carve-out on mainline. The two >> lines show what Studio displays against what Dedicated alone would have said; the gap between them is the free VRAM that was being overstated.

A failure looks like: the same total_gb in both runs (the correction is not firing on this hardware), or used_gb exceeding total_gb.

Lower --hold if 48 GiB is more than the machine can spare. Anything comfortably above the carve-out works.

Item 2 (#9314) The mixed host, and the probe that must not happen

python spoof_two_gpus_windows.py ..\pr9314\studio\backend --split 2
python spoof_two_gpus_windows.py ..\mainline\studio\backend --split 2

Ordinal 0 is the real APU, ordinal 1 a discrete card that does not exist, given a discrete name, arch and is_integrated=0 so the real classifier has to decline it.

Look at: mem_get_info called for ordinals.

Expected: [0]. Probing a device attaches a HIP primary context worth roughly 612 MiB for the life of the process, so probing the discrete card would be a permanent cost on hardware that never needed the correction.

Also expected: ordinal 0's total_gb widens on pr9314 and not on mainline; ordinal 1 keeps its own props total and its used_gb is untouched by ordinal 0 widening.

A failure looks like: [0, 1], or ordinal 1's numbers moving between the two runs.

Item 3 (#8863) The module's reader against the real registry

python real_registry.py ..\pr8863\studio\backend

The one check nothing else substitutes for. Every other item involving the join assumes this reader works.

Look at: records: and LUIDs present on both sides.

Expected: records is not empty, and the LUID line is not NONE. The join is an identity match between the DirectX AdapterLuid and the LUID embedded in the counter instance name; that line is what proves the two agree.

A failure looks like: records: {}. That is safe (every device falls back to capacity ranking, where it already was) but it means #8863 does nothing on this hardware, which is worth knowing before merging.

Expected but not a failure: gfx absent. Driver 32.0.21041.1000 writes no AdapterFamily, so the arch fallback is unavailable here and the name pass is load bearing.

Item 4 (#8863) The join with two devices

python spoof_two_gpus_windows.py ..\pr8863\studio\backend --split 2
python spoof_two_gpus_windows.py ..\pr8863\studio\backend --split 2 --clone-adapter

--clone-adapter clones the real DirectX record and the real counter row under LUIDs that do not exist, dividing the real bytes between them, so the join sees two records for two devices instead of declining on cardinality. The identity is synthetic; the bytes and the reader are real.

Look at: the per-device lines and aggregate, in both runs.

Expected: without --clone-adapter the join declines on cardinality and falls back, and aggregate survives that decline. With it, the join attributes.

A failure looks like: aggregate: None in the first run (a decline that loses the aggregate), or a device given bytes larger than its own capacity.

Item 5 (#8863) The two-card host this machine does not have

From an elevated PowerShell:

python sim_two_amd.py ..\pr8863\studio\backend

The #7072 reporter's actual shape: a W7900 holding 40 GiB beside an idle W7500, plus the Basic Render Driver placeholder that made capacity ranking give up. It does NOT touch HKLM\SOFTWARE\Microsoft\DirectX. It creates a scratch key under HKLM\SOFTWARE\UnslothProbeDirectX, writes two AMD records there, points the module at that path, and deletes the key in a finally. AdapterFamily is omitted on purpose so it mirrors this machine's driver.

Expected:

  LUID join     : [40.0, 0.5]
  capacity rank : [40.0, None]
  truth         : [40.0, 0.5]

That None in the middle row is the reporter's screenshot. The join recovering the idle card is the point of #8863.

A failure looks like: the join row not matching the truth row, or the run ending without printing scratch key removed. If that last line is missing the scratch key is still there; delete HKLM\SOFTWARE\UnslothProbeDirectX by hand.


Safety

Items 1 to 4 are read-only and in process. _torch_get_device_module is a module-level function, so it is swapped for a proxy for the life of the process; nothing is installed, no registry value is written, no file is touched, and there is nothing to undo. Item 5 is the only one that writes, and only to a scratch key of its own making.

What none of this covers

Two real AMD cards in one machine. Items 2 and 4 spoof the second device and item 5 writes real registry records, but there is still one adapter, one driver and one counter instance behind all of them. Nothing here catches a defect that needs a second physical card to appear: a second real counter instance, an AdapterLuid written by a second driver, or the two sides spelling one card's name differently in a way normalizing does not fix. That is the case the join exists for, and it needs the hardware.

Reporting back

Console output of each item is enough. If something disagrees with the expected line, the raw block matters more than a summary of it, particularly for items 1 and 3 where the numbers are the evidence.

e2e_9314.py
r"""Run 9314's OWN code end to end on a real Windows AMD APU. No second GPU needed.

Everything here is real: the module's PowerShell invocation, its parser, its
noise floor, the classifier against real props, and the pairing that decides
what the System tab shows. Up to now the module's own counter path has never
executed on Windows -- earlier readings came from a hand-written reimplementation
of it in a PR comment, which is not the same code.

    python e2e_9314.py <path-to>\studio\backend [--hold 48]

Use the venv that has the ROCm torch build in it.
"""
import argparse, sys, time


def snapshot(hw, label):
    print(f"\n----- {label}")
    try:
        raw = hw._rocm_windows_perf_counter_vram_by_adapter()
        print("  Dedicated counters (module's own reader):")
        for inst, used in (raw or []):
            print(f"    {inst}  {used / 1024**3:.3f} GiB")
        dedicated_only = max((u for _, u in (raw or [])), default = 0.0)
    except Exception as e:
        print(f"  counter read FAILED: {type(e).__name__}: {e}")
        dedicated_only = 0.0
    try:
        unified = hw._rocm_windows_unified_used_bytes()
        print(f"  unified sum (Dedicated+Shared): "
              f"{'None' if unified is None else f'{unified / 1024**3:.3f} GiB'}")
    except Exception as e:
        print(f"  unified sum FAILED: {type(e).__name__}: {e}")
    try:
        devices, aggregate = hw._rocm_windows_per_device_vram([0])
        print(f"  per-device: {devices}")
        print(f"  aggregate : {aggregate}")
        if devices and devices[0].get("used_gb") is not None:
            d = devices[0]
            print(f"  >> Studio shows used {d['used_gb']} / {d['total_gb']} GiB, "
                  f"free {round(d['total_gb'] - d['used_gb'], 2)} GiB")
            print(f"  >> Dedicated alone would have said "
                  f"{round(dedicated_only / 1024**3, 2)} GiB used, free "
                  f"{round(d['total_gb'] - dedicated_only / 1024**3, 2)} GiB")
    except Exception as e:
        print(f"  per-device FAILED: {type(e).__name__}: {e}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("backend")
    ap.add_argument("--hold", type = float, default = 48.0, help = "GiB to hold")
    ap.add_argument("--settle", type = float, default = 25.0, help = "seconds to let counters catch up")
    args = ap.parse_args()

    sys.path.insert(0, args.backend)
    import utils.hardware.hardware as hw
    # Without this IS_ROCM stays False and every path below short-circuits.
    print("detected:", hw.ensure_hardware_detected(), " IS_ROCM:", hw.IS_ROCM)

    snapshot(hw, "idle")

    import torch
    buf = torch.empty(int(args.hold * 1024**3), dtype = torch.uint8, device = "cuda:0")
    buf.fill_(1)
    torch.cuda.synchronize(0)
    print(f"\nholding {args.hold} GiB; waiting {args.settle}s for the counters to catch up")
    time.sleep(args.settle)
    snapshot(hw, f"holding {args.hold} GiB")
    del buf


if __name__ == "__main__":
    main()
spoof_two_gpus_windows.py
r"""Present the ONE real AMD GPU on this Windows box as two, read-only.

Unlike the off-Windows harness, nothing here is faked except the device COUNT.
The registry read, the Dedicated/Shared performance counters, the classifier and
the driver pool total are all the real ones on this machine.

Nothing is installed, written or patched on disk. `_torch_get_device_module` is a
module-level function in hardware.py, so it is swapped in process for a proxy.
The process exits and the spoof is gone. Every call this makes is a read; it
touches no registry value, no file and no driver state.

  --split N        show the one GPU as N devices, each carrying 1/N of its
                   props.total_memory. The driver pool total stays whole, so on
                   a Strix Halo this is exactly the carve-out shape the PR
                   corrects, at N times the margin. Note that every device the
                   classifier calls unified widens to the WHOLE pool, so with
                   --second apu the reported totals sum to more than the machine
                   holds. That is the harness splitting one pool N ways, not the
                   PR over-reporting.
  --second         what ordinal 1 pretends to be: `discrete` (default) gives it
                   a discrete card's name, arch and is_integrated=0, so the real
                   classifier has to decline it; `apu` leaves it a copy of the
                   real device.
  --clone-adapter  additionally clone this machine's real DirectX record and its
                   real counter row under synthetic LUIDs, so the LUID join sees
                   N records for N devices instead of declining on cardinality.

The single most useful run on a Strix Halo is the default:

    python spoof_two_gpus_windows.py ...\studio\backend --split 2

ordinal 0 is the real APU and ordinal 1 a discrete card that does not exist. The
APU's total should widen to the driver pool, the discrete card's should stay at
its own props total, and `mem_get_info called for ordinals` should read `[0]`.
That last line is the one this box can prove and CI cannot: probing a device
attaches a HIP primary context worth roughly 612 MiB for the life of the
process, so a probe of the discrete card would be a permanent cost on hardware
that never needed the correction.

Run it in a checkout of the PR and again in a checkout of main, and compare.

    python spoof_two_gpus_windows.py C:\path\to\studio\backend --split 2
"""
import argparse
import copy
import sys
import types

GB = 1024**3


class _Props:
    """A real props object with total_memory overridden. Attributes are copied,
    never mutated on the original, so torch's own record is untouched."""

    _COPY = ("name", "gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name",
             "is_integrated", "integrated", "major", "minor", "multi_processor_count")

    def __init__(self, real, total_memory, discrete = False):
        for attr in self._COPY:
            if hasattr(real, attr):
                setattr(self, attr, getattr(real, attr))
        self.total_memory = int(total_memory)
        if discrete:
            # A card the classifier must decline: no unified arch, no integrated
            # flag, and a name carrying none of the shared-pool markers.
            self.name = "AMD Radeon PRO W7900"
            for attr in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):
                if hasattr(self, attr):
                    setattr(self, attr, "gfx1100")
            for attr in ("is_integrated", "integrated"):
                if hasattr(self, attr):
                    setattr(self, attr, 0)


class SplitDeviceModule:
    """One physical device presented as N. Records every probe."""

    def __init__(self, real, props, pool_bytes):
        self._real = real
        self._props = props
        self._pool = pool_bytes
        self.mem_get_info_calls = []

    def device_count(self):
        return len(self._props)

    def is_available(self):
        return True

    def current_device(self):
        return 0

    def get_device_properties(self, i):
        return self._props[i]

    def mem_get_info(self, i):
        # A call here attaches a HIP primary context worth roughly 612 MiB,
        # permanently. Recording it is the only way to check that a device the
        # classifier did not call unified is never probed.
        self.mem_get_info_calls.append(i)
        return self._pool

    def __getattr__(self, name):
        return getattr(self._real, name)


def _clone_adapters(real_adapters, records, n):
    """Give each spoofed device its own LUID, carrying real bytes.

    The real counter row and the real registry record are duplicated under LUIDs
    that do not exist, and the bytes are divided so the machine's real total is
    preserved. Only the identity is synthetic.
    """
    if not real_adapters or not records:
        return real_adapters, records
    base_luid = next(iter(records))
    base_record = records[base_luid]
    biggest = max(real_adapters, key = lambda pair: pair[1])
    instance, used = biggest
    out = [pair for pair in real_adapters if pair is not biggest]
    new_records = dict(records)
    for k in range(n):
        luid = base_luid + 0x100000 * (k + 1)
        out.append((f"luid_0x00000000_0x{luid:08x}_phys_0", used / n))
        new_records[luid] = copy.deepcopy(base_record)
    new_records.pop(base_luid, None)
    return out, new_records


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("backend", help = r"path to <checkout>\studio\backend")
    ap.add_argument("--split", type = int, default = 2)
    ap.add_argument("--second", choices = ("discrete", "apu"), default = "discrete",
                    help = "what ordinals past 0 pretend to be (default discrete)")
    ap.add_argument("--clone-adapter", action = "store_true")
    args = ap.parse_args()

    sys.path.insert(0, args.backend)
    import utils.hardware.hardware as hw

    if hw.platform.system() != "Windows":
        print("This harness is for the Windows AMD box. Off Windows the counters and")
        print("the registry do not exist, and _rocm_windows_per_device_vram returns ([], None).")
        print("Use spoof_two_gpus.py for the off-Windows version.")
        return 2

    import torch

    if not torch.cuda.is_available() or torch.cuda.device_count() < 1:
        print("No ROCm device visible to torch.")
        return 2

    real_props = torch.cuda.get_device_properties(0)
    pool = torch.cuda.mem_get_info(0)          # the real driver numbers
    print(f"real device : {real_props.name}")
    print(f"  props.total_memory : {real_props.total_memory / GB:.2f} GiB")
    print(f"  driver total       : {pool[1] / GB:.2f} GiB   (free {pool[0] / GB:.2f})")
    print(f"  gcnArchName        : {getattr(real_props, 'gcnArchName', '')!r}")
    print(f"  is_integrated      : {getattr(real_props, 'is_integrated', 'absent')!r}")
    print(f"  classifier says positively unified: "
          f"{hw._rocm_props_are_positively_unified(real_props)}")

    real_adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
    print(f"\nreal counters ({len(real_adapters or [])}):")
    for instance, used in (real_adapters or []):
        print(f"  {instance:44s} {used / GB:8.2f} GiB")

    # The DirectX LUID join lives on #8863's branch, not on this one or on main,
    # so read it through getattr: on a branch without it there is no registry
    # half to report and the join simply does not participate.
    read_records = getattr(hw, "_windows_amd_adapter_records_by_luid", None)
    real_records = read_records() if read_records else {}
    if read_records is None:
        print("real DirectX AMD records: n/a on this branch (the LUID join is #8863)")
    else:
        print(f"real DirectX AMD records ({len(real_records)}):")
        for luid, record in real_records.items():
            print(f"  0x{luid:x}  {record}")

    n = max(1, args.split)
    props = [
        _Props(real_props, real_props.total_memory // n,
               discrete = i > 0 and args.second == "discrete")
        for i in range(n)
    ]
    print("\nclassifier verdict per spoofed ordinal, from the real classifier:")
    for i, p in enumerate(props):
        print(f"  ordinal {i}: {p.name:34s} positively_unified="
              f"{hw._rocm_props_are_positively_unified(p)}")
    spoof = SplitDeviceModule(torch.cuda, props, pool)

    adapters = real_adapters
    if args.clone_adapter:
        if read_records is None:
            print("\n--clone-adapter needs the LUID join, which is #8863's branch. Ignored.")
        else:
            adapters, cloned = _clone_adapters(real_adapters, real_records, n)
            hw._windows_amd_adapter_records_by_luid = lambda: cloned
            print(f"\ncloned {n} records/counters from the real one "
                  f"(bytes divided, identity synthetic)")

    hw._torch_get_device_module = lambda: (spoof, "cuda")

    print(f"\n=== presented as {n} device(s), each with "
          f"{props[0].total_memory / GB:.2f} GiB of props total ===")
    devices, aggregate = hw._rocm_windows_per_device_vram(
        list(range(n)), adapters = adapters
    )
    for d in devices:
        print(f"  ordinal {d['index']}  {d['name']:34s} "
              f"used={d['used_gb']} total={d['total_gb']}")
    print(f"  aggregate: {aggregate}")
    print(f"  mem_get_info called for ordinals: {spoof.mem_get_info_calls}")

    print("\nWhat to compare against main:")
    print("  total_gb  should be the DRIVER pool on this PR and the carve-out on main")
    print("  used_gb   should not appear on a device whose total was widened")
    print("  the probe list should hold only devices the classifier called unified")
    return 0


if __name__ == "__main__":
    sys.exit(main())
real_registry.py
import sys
sys.path.insert(0, sys.argv[1])
import utils.hardware.hardware as hw
print("detected:", hw.ensure_hardware_detected(), " IS_ROCM:", hw.IS_ROCM)
records = hw._windows_amd_adapter_records_by_luid()
print("key:", hw._WINDOWS_DIRECTX_KEY)
print("records:", records or "{}  <-- EMPTY: the join would decline and fall back")
for luid, rec in sorted((records or {}).items()):
    print(f"  luid={luid} ({hex(luid)})  name={rec.get('name')!r}  gfx={rec.get('gfx', '(none)')!r}")
adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
print("counter instances:", [i for i, _ in (adapters or [])] or "none")
for inst, used in (adapters or []):
    print(f"  {inst}  luid={hw._parse_adapter_luid(inst)}  {used / 1024**3:.3f} GiB")
matched = {hw._parse_adapter_luid(i) for i, _ in (adapters or [])} & set(records or {})
print("LUIDs present on both sides:", sorted(matched) or "NONE")
sim_two_amd.py
r"""Simulate a two-AMD-card Windows host, with the REGISTRY half real.

Needs an elevated PowerShell (writes under HKLM\SOFTWARE). It does NOT touch
HKLM\SOFTWARE\Microsoft\DirectX: it creates its own scratch key, points the
module at it, and deletes it in a finally block.
"""
import sys, winreg

SCRATCH = r"SOFTWARE\UnslothProbeDirectX"
GB = 1024**3
AMD = 4098

# The #7072 host: W7900 48 GB loaded, W7500 8 GB idle, plus a placeholder.
CARDS = [
    ("{11111111-0000-0000-0000-000000000001}", 0xd1e2, "AMD Radeon PRO W7900"),
    ("{22222222-0000-0000-0000-000000000002}", 0xe34a, "AMD Radeon PRO W7500"),
]

def make():
    for guid, luid, name in CARDS:
        with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, SCRATCH + "\\" + guid,
                                0, winreg.KEY_ALL_ACCESS) as k:
            winreg.SetValueEx(k, "VendorId", 0, winreg.REG_DWORD, AMD)
            winreg.SetValueEx(k, "AdapterLuid", 0, winreg.REG_QWORD, luid)
            winreg.SetValueEx(k, "Description", 0, winreg.REG_SZ, name)
            # AdapterFamily deliberately omitted: driver 32.0.21041.1000 omits it,
            # so this mirrors the real machine and leaves the name pass load bearing.

def destroy():
    for guid, _, _ in CARDS:
        try:
            winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, SCRATCH + "\\" + guid)
        except OSError:
            pass
    try:
        winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, SCRATCH)
    except OSError:
        pass

def main(backend):
    sys.path.insert(0, backend)
    import utils.hardware.hardware as hw
    hw._WINDOWS_DIRECTX_KEY = SCRATCH          # real winreg, real HKLM, scratch path

    records = hw._windows_amd_adapter_records_by_luid()
    print("records read back through the REAL winreg path:")
    for luid, rec in sorted(records.items()):
        print(f"  luid={luid} ({hex(luid)})  {rec}")
    assert len(records) == 2, f"expected 2 AMD records, got {len(records)}"

    adapters = [
        ("luid_0x00000000_0x0000d1e2_phys_0", 40.0 * GB),
        ("luid_0x00000000_0x0000e34a_phys_0", 0.5 * GB),
        ("luid_0x00000000_0x0000f001_phys_0", 3 * 1024**2),
    ]
    dev_meta = [
        {"name": "AMD Radeon PRO W7900", "gfx": "gfx1100",
         "total_bytes": 48*GB, "dedicated_bytes": 48*GB},
        {"name": "AMD Radeon PRO W7500", "gfx": "gfx1102",
         "total_bytes": 8*GB, "dedicated_bytes": 8*GB},
    ]
    joined = hw._match_adapter_used_by_luid(adapters, dev_meta)
    ranked = hw._match_adapter_used_to_devices([u for _, u in adapters],
                                               [d["dedicated_bytes"] for d in dev_meta])
    g = lambda xs: [None if u is None else round(u/GB, 2) for u in xs]
    print()
    print("  LUID join     :", g(joined[0]) if joined else "DECLINED")
    print("  capacity rank :", g(ranked))
    print("  truth         : [40.0, 0.5]")

if __name__ == "__main__":
    try:
        make()
        main(sys.argv[1])
    finally:
        destroy()
        print("\nscratch key removed")

@danielhanchen

Copy link
Copy Markdown
Member

Results from the Windows AMD machine: all five items

Ran the whole list. Machine: Windows 11 Pro build 26200, en-US, AMD Radeon(TM) 8060S Graphics (Strix Halo, gfx1151), driver 32.0.21041.1000, torch 2.11.0+rocm7.13.0 (HIP 7.13.99004), props.total_memory 89.47 GiB, driver total 89.47 GiB, is_integrated=1. One AMD adapter, three counter instances.

Item PR Verdict
1 #9314 pass, decisively
2 #9314 pass, after fixing a bug in spoof_two_gpus_windows.py
3 #8863 pass
4 #8863 fails as written, both sub-runs, both harness artifacts
5 #8863 pass, via an HKCU substitute (no admin available here)

Two things need correcting in the instructions themselves, and one of the scripts has a real bug that silently invalidates two items. Details under each.


Item 1 (#9314): the reported bug reproduces, and the margin is 17.78 GiB

pr9314, holding 48 GiB:

----- holding 48.0 GiB
  Dedicated counters (module's own reader):
    luid_0x00000000_0x0001532a_phys_0  31.624 GiB
    luid_0x00000000_0x00017034_phys_0  0.000 GiB
    luid_0x00000000_0x00017099_phys_0  0.000 GiB
  unified sum (Dedicated+Shared): 49.565 GiB
  per-device: [{'index': 0, 'visible_ordinal': 0, 'name': 'AMD Radeon(TM) 8060S Graphics', 'used_gb': 49.42, 'total_gb': 89.47}]
  aggregate : 49.42
  >> Studio shows used 49.42 / 89.47 GiB, free 40.05 GiB
  >> Dedicated alone would have said 31.62 GiB used, free 57.85 GiB

mainline, same load:

----- holding 48.0 GiB
  Dedicated counters (module's own reader):
    luid_0x00000000_0x0001532a_phys_0  31.638 GiB
    luid_0x00000000_0x00017034_phys_0  0.000 GiB
    luid_0x00000000_0x00017099_phys_0  0.000 GiB
  unified sum (Dedicated+Shared): 49.487 GiB
  per-device: [{'index': 0, 'visible_ordinal': 0, 'name': 'AMD Radeon(TM) 8060S Graphics', 'used_gb': 31.64, 'total_gb': 89.47}]
  aggregate : None
  >> Studio shows used 31.64 / 89.47 GiB, free 57.83 GiB
  >> Dedicated alone would have said 31.64 GiB used, free 57.83 GiB

Mainline overstates free VRAM by 17.78 GiB under a 48 GiB load. The mechanism is visible in the counters: Dedicated saturates at 31.6 GiB, which is the 32 GB BIOS carve-out, and the remaining ~18 GiB spills into Shared, which mainline never adds. Idle is 1.25 against 0.96, so the correction is not a constant offset either.

The "Expected" line for this item is wrong, though, and the code already knew it. total_gb is 89.47 on both branches, not the driver pool on one and the carve-out on the other. props.total_memory on this part already spans the pool, which is exactly what _rocm_props_total_is_carve_out's docstring records for a Windows gfx1151 on this driver: the two agree at 89.47 GB against a 32 GB BIOS carve-out. The instruction and the docstring contradict each other, and the docstring is the correct one. What the PR changes here is used_gb, not total_gb. Anyone testing against the stated expectation would file a false negative.

Also worth noting: aggregate is None on mainline and a real figure on pr9314, in both the idle and the loaded snapshot.

Item 2 (#9314): passes, but only after fixing the harness

As written, every device is declined on both branches, with mem_get_info called for ordinals: [] and the real 8060S reported as classifier says positively unified: False.

That is not either branch's behaviour. spoof_two_gpus_windows.py never calls ensure_hardware_detected(), so module-level IS_ROCM is still False when _rocm_props_are_positively_unified runs, and it short-circuits on its first line:

if not IS_ROCM:
    return False

Confirmed directly: IS_ROCM False at import, then after ensure_hardware_detected(), _rocm_classify_unified_memory(props) returns ('gfx1151', True) and positively_unified is True. real_registry.py and e2e_9314.py both call it; this one does not. The fix is one line after the import, matching what the other two scripts already do:

print("detected:", hw.ensure_hardware_detected(), " IS_ROCM:", hw.IS_ROCM)

With that, Item 2 passes on every point. pr9314:

  classifier says positively unified: True
  ordinal 0: AMD Radeon(TM) 8060S Graphics      positively_unified=True
  ordinal 1: AMD Radeon PRO W7900               positively_unified=False

[debug] ROCm unified memory: ordinal 0 total 44.73 -> 89.47 GB (driver pool)
  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=None total=89.47
  ordinal 1  AMD Radeon PRO W7900               used=None total=44.73
  mem_get_info called for ordinals: [0]

mainline, same run: ordinal 0 stays at total=44.73, and mem_get_info called for ordinals: [].

So the probe list is [0] and never [0, 1]: the discrete card that does not exist is never probed, and the ~612 MiB primary context is never attached. Ordinal 0 widens only on the PR. Ordinal 1 keeps its own props total and its used_gb is untouched by ordinal 0 widening. The real classifier declines the spoofed discrete card on its own.

Item 3 (#8863): the reader works against the real registry

detected: DeviceType.CUDA  IS_ROCM: True
key: SOFTWARE\Microsoft\DirectX
records: {86826: {'name': 'AMD Radeon(TM) 8060S Graphics'}}
  luid=86826 (0x1532a)  name='AMD Radeon(TM) 8060S Graphics'  gfx='(none)'
counter instances: ['luid_0x00000000_0x0001532a_phys_0', 'luid_0x00000000_0x00017034_phys_0', 'luid_0x00000000_0x00017099_phys_0']
  luid_0x00000000_0x0001532a_phys_0  luid=86826  1.129 GiB
  luid_0x00000000_0x00017034_phys_0  luid=94260  0.000 GiB
  luid_0x00000000_0x00017099_phys_0  luid=94361  0.000 GiB
LUIDs present on both sides: [86826]

records is not empty and the LUID line is not NONE. gfx is absent, as predicted for this driver, so the name pass is carrying the join by itself here.

And the case the PR exists to fix, the real single device end to end on pr8863:

luid join -> ([31.681], 31.681)
capacity rank -> [31.681]
aggregate (capacity path) -> None
per_device_vram([0]) -> ([{'index': 0, 'visible_ordinal': 0, 'name': 'AMD Radeon(TM) 8060S Graphics',
                           'used_gb': 31.68, 'total_gb': 89.47}], 31.68)

A single-GPU Windows AMD host that used to report Unknown now reports a real per-device figure and a real aggregate. Note the third line: the capacity path alone still yields None for the aggregate, so on this host the LUID join is what supplies it.

Item 4 (#8863): both sub-runs fail, and both are the harness contradicting itself

Even with the IS_ROCM fix applied, --split 2 gives used=None, used=None, aggregate: None, and --clone-adapter does not change it. Neither is a defect in the join.

4a, aggregate: None. This host has three counter instances against two spoofed devices, so _rocm_windows_aggregate_used_bytes hits its own guard:

if len(adapter_useds) != n:
    return None

That is the deliberate fail-closed branch, doing exactly what its docstring says it does. The expectation "aggregate survives that decline" cannot hold at --split 2 on any host with more counter instances than spoofed devices, which is every host carrying a Basic Render Driver placeholder. The item needs --split 3 here, or the expectation needs restating.

4b, the join declines. _clone_adapters does copy.deepcopy(base_record), so both synthetic LUIDs carry the real adapter's Description, while --second discrete renames ordinal 1 to AMD Radeon PRO W7900. The two flags disagree:

normalized record names: ['amd radeon 8060s graphics', 'amd radeon 8060s graphics']
normalized device names: ['amd radeon 8060s graphics', 'amd radeon pro w7900']
JOIN -> DECLINED (None)

Two counters key to amd radeon 8060s graphics, only one device position carries that key, so _attribute_adapter_useds_by_key cannot place them and the pass declines. Correct behaviour given contradictory inputs. --clone-adapter needs to rename the cloned records to match whatever --second made the devices, or refuse to run alongside --second discrete.

With the flags made consistent, --split 2 --clone-adapter --second apu:

  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=None total=44.73
  ordinal 1  AMD Radeon(TM) 8060S Graphics      used=None total=44.73
  aggregate: 1.27

The join no longer declines and the aggregate survives. Per-device stays None because both devices are same-named, which is the documented #7452 outcome rather than a failure.

Item 5 (#8863): passes, run against HKCU rather than HKLM

I could not run this one as specified: no elevated shell was available and UAC cannot be automated, so nothing was written to HKLM. Instead I pointed the reader at HKEY_CURRENT_USER — same winreg calls, same REG_QWORD write and read-back, same subkey enumeration, same scratch path, only the hive differs. Output matched the expected block exactly:

records read back through the REAL winreg path:
  luid=53730 (0xd1e2)  {'name': 'AMD Radeon PRO W7900'}
  luid=58186 (0xe34a)  {'name': 'AMD Radeon PRO W7500'}

  LUID join     : [40.0, 0.5]
  capacity rank : [40.0, None]
  truth         : [40.0, 0.5]

scratch key removed

The join recovers the idle W7500 that capacity ranking reports as None, with AdapterFamily omitted so the name pass is load bearing, as on this machine's real driver. Test-Path afterwards confirms both HKCU:\SOFTWARE\UnslothProbeDirectX and HKLM:\SOFTWARE\UnslothProbeDirectX absent.

Since it did not touch HKLM, this does not close the item on the real hive. Someone with an elevated shell should still run it as written.


Summary of what needs changing

  1. spoof_two_gpus_windows.py is missing ensure_hardware_detected(). Without it IS_ROCM is False, every classifier call returns False, and Items 2 and 4 both report total failure on both branches for a reason that has nothing to do with either PR. This is the one I would fix before anyone else runs the list.
  2. Item 1's expected total_gb contradicts _rocm_props_total_is_carve_out's own docstring. On this part the totals already agree at 89.47; the correction lands in used_gb.
  3. Item 4a's aggregate expectation assumes counter instances equal spoofed devices. Three instances against --split 2 fails closed by design.
  4. --clone-adapter and --second discrete contradict each other. The clone copies the real name while --second discrete changes the device name; consistent flags attribute correctly.

Setup was otherwise exactly as described. One extra step: structlog had to be installed into the ROCm venv, since hardware.py imports it at module level and it is not a torch dependency.

Still not covered

Everything above still runs against one physical adapter, one driver and, for the real readings, one counter instance. Item 5 supplies two registry records but no second card wrote them. The two-real-AMD-card Windows host remains untested.

@danielhanchen

Copy link
Copy Markdown
Member

Windows AMD results: all five items, on a real gfx1151

Ran all five items on the Windows Strix Halo box. Machine: AMD Radeon(TM) 8060S Graphics, gfx1151, is_integrated=1, driver 32.0.21041.1000, 95.776 GiB system RAM, 32 GiB BIOS carve-out, single integrated GPU, no discrete card. ROCm build torch==2.9.1+rocm7.13.0a20260423 with rocm-sdk-libraries-gfx1151.

Four items pass. Item 1 does not produce the expected shape, for a reason that turns out to be benign; item 2 needed a one-line fix to the harness before it could report anything at all; item 4's "failure" is a fail-closed path firing correctly on hardware the expectation did not anticipate. Details below, raw output included.

Two prerequisites worth recording: the backend needs structlog and psutil beyond torch, and origin/main does not have ensure_hardware_detected — at 20006dbce item 1 dies with AttributeError before printing anything. I moved the mainline worktree to 7a48774a1 to get a comparison leg.


Item 1 (#9314) — the reported bug under load

total_gb is 89.47 on both branches, which the item calls the failure signature. The cause is benign: props.total_memory on this part already is 89.465 GiB, so the widening has nothing to widen and is inert exactly as designed. The expectation that mainline shows "the carve-out" does not hold here — mainline shows props.total_memory, and on this machine that is the whole pool, not the 32 GiB carve-out. A machine where those two differ is still the thing nobody has found.

What does differ between the branches is the used figure, and that is the reported bug:

holding 48 GiB used_gb total_gb free aggregate
pr9314 49.39 89.47 40.08 49.39
mainline 31.70 89.47 57.77 None

Mainline overstates free VRAM by 17.69 GiB. used_gb never exceeded total_gb in any run.

raw, pr9314
detected: DeviceType.CUDA  IS_ROCM: True

----- idle
  Dedicated counters (module's own reader):
    luid_0x00000000_0x0001532a_phys_0  1.134 GiB
    luid_0x00000000_0x00017034_phys_0  0.000 GiB
    luid_0x00000000_0x00017099_phys_0  0.000 GiB
  unified sum (Dedicated+Shared): 1.417 GiB
  per-device: [{'index': 0, 'visible_ordinal': 0, 'name': 'AMD Radeon(TM) 8060S Graphics', 'used_gb': 1.48, 'total_gb': 89.47}]
  aggregate : 1.48
  >> Studio shows used 1.48 / 89.47 GiB, free 87.99 GiB
  >> Dedicated alone would have said 1.13 GiB used, free 88.34 GiB

----- holding 48.0 GiB
  Dedicated counters (module's own reader):
    luid_0x00000000_0x0001532a_phys_0  31.734 GiB
    luid_0x00000000_0x00017034_phys_0  0.000 GiB
    luid_0x00000000_0x00017099_phys_0  0.000 GiB
  unified sum (Dedicated+Shared): 49.551 GiB
  per-device: [{'index': 0, 'visible_ordinal': 0, 'name': 'AMD Radeon(TM) 8060S Graphics', 'used_gb': 49.39, 'total_gb': 89.47}]
  aggregate : 49.39
  >> Studio shows used 49.39 / 89.47 GiB, free 40.08 GiB
  >> Dedicated alone would have said 31.73 GiB used, free 57.74 GiB
raw, mainline (7a48774)
detected: DeviceType.CUDA  IS_ROCM: True

----- idle
  unified sum (Dedicated+Shared): 1.114 GiB
  per-device: [{'index': 0, ..., 'used_gb': 0.99, 'total_gb': 89.47}]
  aggregate : None
  >> Studio shows used 0.99 / 89.47 GiB, free 88.48 GiB

----- holding 48.0 GiB
  Dedicated counters (module's own reader):
    luid_0x00000000_0x0001532a_phys_0  31.692 GiB
    luid_0x00000000_0x00017034_phys_0  0.000 GiB
    luid_0x00000000_0x00017099_phys_0  0.000 GiB
  unified sum (Dedicated+Shared): 49.548 GiB
  per-device: [{'index': 0, ..., 'used_gb': 31.7, 'total_gb': 89.47}]
  aggregate : None
  >> Studio shows used 31.7 / 89.47 GiB, free 57.77 GiB
  >> Dedicated alone would have said 31.69 GiB used, free 57.78 GiB

Item 2 (#9314) — passes, after a harness fix

spoof_two_gpus_windows.py never calls ensure_hardware_detected(). _rocm_props_are_positively_unified opens with if not IS_ROCM: return False, so without that call the classifier returns False for every device including the real APU, nothing widens, and the probe list is empty on both branches. e2e_9314.py makes the call and carries a comment saying exactly why; the spoof script omits it. As shipped, this item reports a uniform False that looks like a real verdict:

  classifier says positively unified: False        <-- IS_ROCM was still False
>>> hw.IS_ROCM, hw._rocm_props_are_positively_unified(p)
(False, False)
>>> hw.ensure_hardware_detected(); hw.IS_ROCM, hw._rocm_props_are_positively_unified(p)
(True, True)

Adding hw.ensure_hardware_detected() immediately after the import, the item passes on every point:

pr9314 mainline
ordinal 0 (real APU) total=89.47 (widened from 44.73) total=44.73
ordinal 1 (fake discrete) total=44.73 total=44.73
mem_get_info called for ordinals [0] []

pr9314 logs the widening explicitly: ROCm unified memory: ordinal 0 total 44.73 -> 89.47 GB (driver pool). The classifier splits the two correctly — ordinal 0 positively_unified=True, ordinal 1 AMD Radeon PRO W7900 positively_unified=False — the discrete card is never probed, and ordinal 1's numbers are identical between the two runs.

Item 3 (#8863) — passes

key: SOFTWARE\Microsoft\DirectX
records: {86826: {'name': 'AMD Radeon(TM) 8060S Graphics'}}
  luid=86826 (0x1532a)  name='AMD Radeon(TM) 8060S Graphics'  gfx='(none)'
counter instances: ['luid_0x00000000_0x0001532a_phys_0', 'luid_0x00000000_0x00017034_phys_0', 'luid_0x00000000_0x00017099_phys_0']
  luid_0x00000000_0x0001532a_phys_0  luid=86826  0.959 GiB
  luid_0x00000000_0x00017034_phys_0  luid=94260  0.000 GiB
  luid_0x00000000_0x00017099_phys_0  luid=94361  0.000 GiB
LUIDs present on both sides: [86826]

Records non-empty, and the DirectX AdapterLuid and the counter instance LUID agree on 0x1532a. gfx absent, as predicted for this driver, so the name pass is load bearing. Note the shape: three counter instances, one DirectX record. That is what item 4 runs into.

Item 4 (#8863) — aggregate: None, and it is not a defect

Both legs give aggregate: None, with and without --clone-adapter. The cause is the cardinality gate in _rocm_windows_aggregate_used_bytes, which emits only when the counter list is the visible set. This machine reports three counter instances for one physical GPU — the real adapter plus two zero-byte placeholders — so against 2 spoofed devices the length check fails and it returns None. That is the documented fail-closed behaviour working correctly, not a lost aggregate.

--clone-adapter cannot reach the join either: it clones the biggest counter into N rows but leaves both placeholders in the list, so the list is N+2 long.

Three runs isolate the gate:

configuration counters devices aggregate per-device used
--split 2 (as scripted) 3 2 None None
--split 3 3 3 1.06 None
real single device 3 1 0.92 0.92
placeholders dropped, cloned to 2 2 2 0.91 None

The row that matters is the third: on the actual hardware configuration the LUID join attributes cleanly — used_gb 0.92 / total 89.47, aggregate 0.92. #8863 does what it says on this machine.

In the last row the aggregate survives while per-device declines, which is precisely the #7452 path the docstring describes. Per-device cannot resolve there because both clones carry an identical name and no gfx, so identity has nothing to separate them — an artifact of cloning one device, not a defect. No device was ever assigned bytes exceeding its own capacity.

Worth flagging against the docstring's stated assumption: the counter list being as long as the visible set does not imply it holds those cards and nothing else. Here one visible GPU coexists with two placeholder instances permanently, so a single-GPU visible set never matches by length. The aggregate is reachable on this machine only through the LUID join, never through the cardinality fallback.

Item 5 (#8863) — passes exactly

records read back through the REAL winreg path:
  luid=53730 (0xd1e2)  {'name': 'AMD Radeon PRO W7900'}
  luid=58186 (0xe34a)  {'name': 'AMD Radeon PRO W7500'}

  LUID join     : [40.0, 0.5]
  capacity rank : [40.0, None]
  truth         : [40.0, 0.5]

scratch key removed

Matches the expected block line for line. The join recovers the idle W7500 where capacity ranking returns None — the #7072 screenshot. I confirmed HKLM\SOFTWARE\UnslothProbeDirectX is absent after the run.


One measurement caveat for anyone repeating this

The GPU counters lag process teardown by tens of seconds. After a run holding 31.7 GiB exits, Dedicated Usage keeps reporting that memory well after the process is gone from the process list. Two of my runs sampled 31.71 GiB at nominal idle for this reason, and I initially mistook it for a stray process. If you are comparing an idle baseline against a loaded one, let the counters settle or you will read the previous run's allocation.

What this still does not cover

Unchanged from your list: an APU with a discrete card actually present. Items 2 and 4 spoof the second device and item 5 writes real registry records, but there is one adapter, one driver and one real counter instance behind all of them. The WIDENS question also remains unreproduced — this machine's props.total_memory and driver pool are identical at 89.465 GiB, so it is a fourth reading against the premise rather than the first for it.

@danielhanchen

Copy link
Copy Markdown
Member

Errata on the test list, after the Windows AMD results

Both result reports are consistent with each other and I have gone through them against the code. Four items pass. The two that did not are my errors, not either PR's: one real bug in a script I posted, and two expectations in the checklist that contradict what the code already documents. Corrections below, and a fixed script at the bottom. This comment is posted identically on #8863 and #9314.

1. The script bug, and it invalidated two items

spoof_two_gpus_windows.py never called ensure_hardware_detected(). _rocm_props_are_positively_unified opens with if not IS_ROCM: return False, so module-level IS_ROCM was still False when the classifier ran, every device came back not-unified, nothing widened, and the probe list was empty on both branches. That is an unconfigured module reporting a uniform False that reads exactly like a verdict. e2e_9314.py and real_registry.py both make the call; this one did not, and I did not notice because the Linux dry run patches IS_ROCM directly.

Fixed, with a getattr guard since older main commits predate the helper:

    detect = getattr(hw, "ensure_hardware_detected", None)
    print("detected:", detect() if detect else "(no ensure_hardware_detected on this "
          "commit; IS_ROCM may stay False and every classifier call return False)",
          " IS_ROCM:", hw.IS_ROCM)

Thanks for catching it rather than reporting the False at face value. Item 2 was already re-run with that fix applied and passes on every point, so nothing more is needed there.

2. Item 1's expected total_gb was wrong, and the PR's own test says so

The checklist said total_gb should be the driver pool on pr9314 and the carve-out on main. It is 89.47 on both, and that is correct behaviour. On this part props.total_memory already spans the pool, so there is nothing to widen. The PR's own test records this in as many words:

props.total_memory is already 89.465 GB, so nothing widens and total_is_pool never fires.
Pre-PR this reported 31.64 used against an 89.46 total, i.e. 57.82 GB free with 64 GiB resident.

So the correction lands in used_gb, not total_gb, and the measurement confirms it: 17.7 GiB of overstated free VRAM under a 48 GiB load, with Dedicated pinned at the 32 GiB carve-out and the remainder in Shared that main never adds. The mechanism in the code is that pool_confirmed is pool_bytes >= total_bytes, which holds when the two are equal, so the unified-used pairing runs even though total_is_pool stays False. That is the path deliberately, and the measurement is the first time it has executed on real hardware.

I wrote the checklist expectation from the PR title rather than from the test, and anyone following it would have filed a false negative. My mistake.

3. Item 4a's aggregate expectation cannot hold at --split 2 on this machine

Three counter instances (the adapter plus two zero-byte placeholders) against two spoofed devices. _rocm_windows_aggregate_used_bytes emits only when the counter list is the visible set, so it fails closed and returns None. That gate is correct and the report is right that it is not a lost aggregate.

The observation that came with it is the more interesting half, and it argues for #8863 rather than against it: on this host a single visible GPU coexists with two placeholder instances permanently, so a single-GPU visible set can never match by length, and the aggregate is reachable only through the LUID join. The records: {} outcome that would have made #8863 a no-op did not happen; instead the join turns out to be the only path to an aggregate on the one Windows AMD machine we can measure.

The script now says this rather than letting you find it:

  NOTE: 3 counter instances against --split 2. The aggregate emits only when the
  counter list IS the visible set, so it will read None here by design. Use
  --split 3, or --clone-adapter, to exercise that path.

4. --clone-adapter contradicted --second discrete

The clone deep-copied the real adapter's Description onto every synthetic record while --second discrete renamed ordinal 1 to AMD Radeon PRO W7900, so the two sides disagreed by construction and the join declined on inputs that contradict each other. It also left the placeholders in the counter list, making it N+2 long. Both fixed: each cloned record now takes the name of the device it stands for, and sub-threshold instances are dropped so the list is exactly the spoofed devices.

Verified on both branches. On #8863's branch, --split 2 --clone-adapter now gives per-device 15.87 / 15.87 with aggregate 31.73 instead of declining, and --split 3 gives aggregate 31.73 through the cardinality path.

5. Setup notes worth folding into the list

  • the backend needs structlog and psutil beyond torch
  • origin/main at 20006dbce predates ensure_hardware_detected and dies with AttributeError; 7a48774a1 works as the comparison leg. The getattr guard above stops that being fatal, but the mainline leg is only meaningful on a commit that has it
  • the GPU counters lag process teardown by tens of seconds, so an idle baseline sampled right after a loaded run reads the previous allocation. Worth a settle before comparing

Items still genuinely open

  • Item 5 on the real hive. One run substituted HKCU for lack of an elevated shell. Same winreg calls, same REG_QWORD round trip, same enumeration, only the hive differs, and it matched the expected block line for line. That is good evidence but it is not the HKLM read path, so the item stays open until someone runs it elevated.
  • An APU whose props.total_memory is below the driver pool. Nothing measured so far shows one: this machine reports 89.465 both ways, and the gfx1151 CI probe reports driver_exceeds_props=False. The widening in Studio: take the AMD APU total on Windows from the driver, not the carve-out #9314 is therefore inert on every AMD device we have, and its measured benefit here is entirely in used_gb. The widening is still the right thing to do when the two disagree, but it should be merged as unreproduced rather than as verified.
  • Two real AMD cards in one machine. Unchanged.
spoof_two_gpus_windows.py (corrected: use this one)
r"""Present the ONE real AMD GPU on this Windows box as two, read-only.

Unlike the off-Windows harness, nothing here is faked except the device COUNT.
The registry read, the Dedicated/Shared performance counters, the classifier and
the driver pool total are all the real ones on this machine.

Nothing is installed, written or patched on disk. `_torch_get_device_module` is a
module-level function in hardware.py, so it is swapped in process for a proxy.
The process exits and the spoof is gone. Every call this makes is a read; it
touches no registry value, no file and no driver state.

  --split N        show the one GPU as N devices, each carrying 1/N of its
                   props.total_memory. The driver pool total stays whole, so on
                   a Strix Halo this is exactly the carve-out shape the PR
                   corrects, at N times the margin. Note that every device the
                   classifier calls unified widens to the WHOLE pool, so with
                   --second apu the reported totals sum to more than the machine
                   holds. That is the harness splitting one pool N ways, not the
                   PR over-reporting.
  --second         what ordinal 1 pretends to be: `discrete` (default) gives it
                   a discrete card's name, arch and is_integrated=0, so the real
                   classifier has to decline it; `apu` leaves it a copy of the
                   real device.
  --clone-adapter  additionally clone this machine's real DirectX record and its
                   real counter row under synthetic LUIDs, so the LUID join sees
                   N records for N devices instead of declining on cardinality.

The single most useful run on a Strix Halo is the default:

    python spoof_two_gpus_windows.py ...\studio\backend --split 2

ordinal 0 is the real APU and ordinal 1 a discrete card that does not exist. The
APU's total should widen to the driver pool, the discrete card's should stay at
its own props total, and `mem_get_info called for ordinals` should read `[0]`.
That last line is the one this box can prove and CI cannot: probing a device
attaches a HIP primary context worth roughly 612 MiB for the life of the
process, so a probe of the discrete card would be a permanent cost on hardware
that never needed the correction.

Run it in a checkout of the PR and again in a checkout of main, and compare.

    python spoof_two_gpus_windows.py C:\path\to\studio\backend --split 2
"""
import argparse
import copy
import sys
import types

GB = 1024**3


class _Props:
    """A real props object with total_memory overridden. Attributes are copied,
    never mutated on the original, so torch's own record is untouched."""

    _COPY = ("name", "gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name",
             "is_integrated", "integrated", "major", "minor", "multi_processor_count")

    def __init__(self, real, total_memory, discrete = False):
        for attr in self._COPY:
            if hasattr(real, attr):
                setattr(self, attr, getattr(real, attr))
        self.total_memory = int(total_memory)
        if discrete:
            # A card the classifier must decline: no unified arch, no integrated
            # flag, and a name carrying none of the shared-pool markers.
            self.name = "AMD Radeon PRO W7900"
            for attr in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):
                if hasattr(self, attr):
                    setattr(self, attr, "gfx1100")
            for attr in ("is_integrated", "integrated"):
                if hasattr(self, attr):
                    setattr(self, attr, 0)


class SplitDeviceModule:
    """One physical device presented as N. Records every probe."""

    def __init__(self, real, props, pool_bytes):
        self._real = real
        self._props = props
        self._pool = pool_bytes
        self.mem_get_info_calls = []

    def device_count(self):
        return len(self._props)

    def is_available(self):
        return True

    def current_device(self):
        return 0

    def get_device_properties(self, i):
        return self._props[i]

    def mem_get_info(self, i):
        # A call here attaches a HIP primary context worth roughly 612 MiB,
        # permanently. Recording it is the only way to check that a device the
        # classifier did not call unified is never probed.
        self.mem_get_info_calls.append(i)
        return self._pool

    def __getattr__(self, name):
        return getattr(self._real, name)


def _clone_adapters(real_adapters, records, props):
    """Give each spoofed device its own LUID and record, carrying real bytes.

    The real counter row and the real registry record are duplicated under LUIDs
    that do not exist, and the bytes are divided so the machine's real total is
    preserved. Only the identity is synthetic.

    Two things this has to get right, both found the hard way on the real box:

    * the placeholder counter instances are dropped. A Strix Halo reports THREE
      instances for one GPU (the adapter plus two zero-byte placeholders), so
      leaving them in makes the list N+2 long and the cardinality gate in
      ``_rocm_windows_aggregate_used_bytes`` fails closed before the join is
      reached. That gate is correct; feeding it a list it cannot match is not a
      test of anything.
    * each cloned record takes the NAME OF THE DEVICE it stands for, not the
      real adapter's name. Cloning the real Description while ``--second
      discrete`` renames ordinal 1 makes the two sides disagree by construction,
      and the join declines on inputs that contradict each other rather than on
      anything either PR does.
    """
    if not real_adapters or not records:
        return real_adapters, records
    base_luid = next(iter(records))
    base_record = records[base_luid]
    # Everything the module would treat as noise, so the counter list is exactly
    # the spoofed devices and no more.
    floor = 16 * 1024**2
    real = [pair for pair in real_adapters if pair[1] >= floor] or [max(
        real_adapters, key = lambda pair: pair[1])]
    used = sum(u for _, u in real)
    out, new_records = [], {}
    for k, prop in enumerate(props):
        luid = base_luid + 0x100000 * (k + 1)
        out.append((f"luid_0x00000000_0x{luid:08x}_phys_0", used / len(props)))
        record = copy.deepcopy(base_record)
        record["name"] = prop.name
        new_records[luid] = record
    return out, new_records


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("backend", help = r"path to <checkout>\studio\backend")
    ap.add_argument("--split", type = int, default = 2)
    ap.add_argument("--second", choices = ("discrete", "apu"), default = "discrete",
                    help = "what ordinals past 0 pretend to be (default discrete)")
    ap.add_argument("--clone-adapter", action = "store_true")
    args = ap.parse_args()

    sys.path.insert(0, args.backend)
    import utils.hardware.hardware as hw

    # Without this, module-level IS_ROCM is still False, and
    # _rocm_props_are_positively_unified opens with `if not IS_ROCM: return False`.
    # Every device then classifies as not-unified, nothing widens, the probe list
    # comes back empty, and all of that looks like a verdict rather than an
    # unconfigured module. e2e_9314.py and real_registry.py both make this call.
    # getattr: older `main` commits predate this helper, and dying with an
    # AttributeError on the comparison leg is worse than saying so.
    detect = getattr(hw, "ensure_hardware_detected", None)
    print("detected:", detect() if detect else "(no ensure_hardware_detected on this "
          "commit; IS_ROCM may stay False and every classifier call return False)",
          " IS_ROCM:", hw.IS_ROCM)

    if hw.platform.system() != "Windows":
        print("This harness is for the Windows AMD box. Off Windows the counters and")
        print("the registry do not exist, and _rocm_windows_per_device_vram returns ([], None).")
        print("Use spoof_two_gpus.py for the off-Windows version.")
        return 2

    import torch

    if not torch.cuda.is_available() or torch.cuda.device_count() < 1:
        print("No ROCm device visible to torch.")
        return 2

    real_props = torch.cuda.get_device_properties(0)
    pool = torch.cuda.mem_get_info(0)          # the real driver numbers
    print(f"real device : {real_props.name}")
    print(f"  props.total_memory : {real_props.total_memory / GB:.2f} GiB")
    print(f"  driver total       : {pool[1] / GB:.2f} GiB   (free {pool[0] / GB:.2f})")
    print(f"  gcnArchName        : {getattr(real_props, 'gcnArchName', '')!r}")
    print(f"  is_integrated      : {getattr(real_props, 'is_integrated', 'absent')!r}")
    print(f"  classifier says positively unified: "
          f"{hw._rocm_props_are_positively_unified(real_props)}")

    real_adapters = hw._rocm_windows_perf_counter_vram_by_adapter()
    print(f"\nreal counters ({len(real_adapters or [])}):")
    for instance, used in (real_adapters or []):
        print(f"  {instance:44s} {used / GB:8.2f} GiB")
    if real_adapters and len(real_adapters) != args.split and not args.clone_adapter:
        print(f"  NOTE: {len(real_adapters)} counter instances against --split "
              f"{args.split}. The aggregate emits only when the counter list IS the "
              f"visible set, so it will read None here by design. Use --split "
              f"{len(real_adapters)}, or --clone-adapter, to exercise that path.")

    # The DirectX LUID join lives on #8863's branch, not on this one or on main,
    # so read it through getattr: on a branch without it there is no registry
    # half to report and the join simply does not participate.
    read_records = getattr(hw, "_windows_amd_adapter_records_by_luid", None)
    real_records = read_records() if read_records else {}
    if read_records is None:
        print("real DirectX AMD records: n/a on this branch (the LUID join is #8863)")
    else:
        print(f"real DirectX AMD records ({len(real_records)}):")
        for luid, record in real_records.items():
            print(f"  0x{luid:x}  {record}")

    n = max(1, args.split)
    props = [
        _Props(real_props, real_props.total_memory // n,
               discrete = i > 0 and args.second == "discrete")
        for i in range(n)
    ]
    print("\nclassifier verdict per spoofed ordinal, from the real classifier:")
    for i, p in enumerate(props):
        print(f"  ordinal {i}: {p.name:34s} positively_unified="
              f"{hw._rocm_props_are_positively_unified(p)}")
    spoof = SplitDeviceModule(torch.cuda, props, pool)

    adapters = real_adapters
    if args.clone_adapter:
        if read_records is None:
            print("\n--clone-adapter needs the LUID join, which is #8863's branch. Ignored.")
        else:
            adapters, cloned = _clone_adapters(real_adapters, real_records, props)
            hw._windows_amd_adapter_records_by_luid = lambda: cloned
            print(f"\ncloned {n} records/counters from the real one "
                  f"(bytes divided, identity synthetic)")

    hw._torch_get_device_module = lambda: (spoof, "cuda")

    print(f"\n=== presented as {n} device(s), each with "
          f"{props[0].total_memory / GB:.2f} GiB of props total ===")
    devices, aggregate = hw._rocm_windows_per_device_vram(
        list(range(n)), adapters = adapters
    )
    for d in devices:
        print(f"  ordinal {d['index']}  {d['name']:34s} "
              f"used={d['used_gb']} total={d['total_gb']}")
    print(f"  aggregate: {aggregate}")
    print(f"  mem_get_info called for ordinals: {spoof.mem_get_info_calls}")

    print("\nWhat to compare against main:")
    print("  total_gb  should be the DRIVER pool on this PR and the carve-out on main")
    print("  used_gb   should not appear on a device whose total was widened")
    print("  the probe list should hold only devices the classifier called unified")
    return 0


if __name__ == "__main__":
    sys.exit(main())

@danielhanchen

Copy link
Copy Markdown
Member

Turned the strongest finding from the Windows run into a permanent guard, in 2c455aa.

test_the_measured_strix_halo_needs_the_join_for_any_aggregate pins the shape the machine actually reports: three counter instances for one visible GPU, the AMD adapter at 31.681 GiB plus two placeholders that never go away. It asserts the join gives used_gb 31.68 and aggregate 31.68, then makes the registry unreadable and asserts the aggregate falls to None.

That second half is the part worth having in the suite. It is not that capacity ranking happens to lose the aggregate on this host, it is that it can never supply one: the counter list is permanently longer than the visible set, so the cardinality gate fails closed for good, and there is no load that changes it. On a single-GPU Windows AMD host the join is not a second opinion, it is the only path to a figure at all. That is why #7072's reporter saw Unknown on hardware that was plainly busy.

The test errors rather than fails against origin/main, since _windows_amd_adapter_records_by_luid does not exist there to patch. Weaker as a negative control than a clean assertion failure, but it does establish the test cannot pass without this PR.

235 passed across the ROCm suites.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 80b2291c31

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

Item 5 was run elevated against HKLM — it can come off the open list

One correction to the errata. Under "Items still genuinely open":

Item 5 on the real hive. One run substituted HKCU for lack of an elevated shell... That is good evidence but it is not the HKLM read path, so the item stays open until someone runs it elevated.

That caveat belongs to the other results report, which states plainly that no elevated shell was available and that it pointed the reader at HKEY_CURRENT_USER instead. My run was elevated and did write to the real HKLM hive, unmodified, exactly as item 5 specifies. My report showed the output and the post-run HKLM cleanup check but never used the word "elevated", which is likely why the two got merged.

Method, for the record: Start-Process -Verb RunAs against the ROCm venv's interpreter, with a UAC prompt approved interactively. sim_two_amd.py ran unmodified — SCRATCH = r"SOFTWARE\UnslothProbeDirectX" under winreg.HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, the REG_QWORD AdapterLuid round trip, and the real _windows_amd_adapter_records_by_luid reading back out of HKLM.

records read back through the REAL winreg path:
  luid=53730 (0xd1e2)  {'name': 'AMD Radeon PRO W7900'}
  luid=58186 (0xe34a)  {'name': 'AMD Radeon PRO W7500'}

  LUID join     : [40.0, 0.5]
  capacity rank : [40.0, None]
  truth         : [40.0, 0.5]

scratch key removed

assert len(records) == 2 passed against HKLM, so the enumeration and the REG_QWORD read-back are confirmed on the hive the module actually uses. The join recovers the idle W7500 where capacity ranking gives None, with AdapterFamily omitted so the name pass is load bearing. Afterwards:

if (Test-Path 'HKLM:\SOFTWARE\UnslothProbeDirectX') { 'STILL PRESENT' } else { 'confirmed absent' }
# -> confirmed absent

So the HKLM read path is exercised and the item is closed. The two HKCU-substituted runs are corroboration on top of it, not the primary evidence.

One snag worth folding into the instructions, since item 5 is the only item that needs elevation: Start-Process -Verb RunAs cannot be combined with -RedirectStandardOutput, and fails with AmbiguousParameterSet rather than anything self-explanatory. Redirect inside the elevated shell instead:

Start-Process powershell -Verb RunAs -Wait -ArgumentList '-NoProfile','-Command',
  '& ''<venv>\Scripts\python.exe'' ''sim_two_amd.py'' ''<checkout>\studio\backend'' *> ''item5.out'''

The output lands as UTF-16, so read it accordingly.

On the rest of the errata

No disagreement. The --clone-adapter diagnosis is better than mine: I attributed the per-device decline to both clones carrying an identical name, but the deeper cause is that the clone copied the real adapter's Description onto every synthetic record while --second discrete renamed ordinal 1, so the two sides contradicted each other by construction. That also explains why dropping the placeholders was necessary but not sufficient in my supplement.

I have not independently verified the corrected script's --split 2 --clone-adapter figures (15.87 / 15.87, aggregate 31.73) on this hardware — I tore the environment down after reporting. Happy to rebuild and confirm them on the real gfx1151 if that is worth a second reading before merge; it is about ten minutes of setup.

The other two open items stand as written: an APU whose props.total_memory is genuinely below the driver pool, and two real AMD cards in one host. Agreed that #9314's widening should be merged as unreproduced rather than verified — on this machine its entire measured benefit is in used_gb, via pool_confirmed holding when the two totals are equal.

@danielhanchen

Copy link
Copy Markdown
Member

Correct, and my errata was wrong to keep item 5 open. I had two result reports in front of me, one of which said plainly that no elevated shell was available and substituted HKCU, and I carried that caveat onto both. Your run wrote to the real hive and the assert len(records) == 2 passing there is the part that matters: it confirms the subkey enumeration and the REG_QWORD AdapterLuid read-back on the hive _windows_amd_adapter_records_by_luid actually reads, not on a stand-in for it. Item 5 is closed, and the HKCU runs are corroboration rather than the evidence.

The Start-Process -Verb RunAs and -RedirectStandardOutput incompatibility is worth having on the record, since AmbiguousParameterSet gives no hint about which two parameters are in conflict and item 5 is the only item needing elevation. Redirecting inside the elevated shell and reading the result as UTF-16 is the right workaround.

On the offer to rebuild and confirm the corrected --clone-adapter figures: not worth ten minutes against this PR. Those numbers came off a spoofed setup and the thing they demonstrate, the join attributing across two devices, your elevated item 5 run already demonstrated better, with real winreg against HKLM giving [40.0, 0.5] where capacity ranking gives [40.0, None]. The clone path would add real counter bytes flowing through _rocm_windows_per_device_vram end to end, which is a marginal increment on top of that, and it is a test instrument rather than shipped code either way.

If you are going to rebuild the environment, #9314 is where it would pay. There is an open review item there arguing that equal totals should not be marked pool-scoped without further proof, and your measurement speaks to it directly: equal totals plus positively_unified IS the real Strix Halo configuration, and treating it as pool-scoped is exactly what produces 49.4 instead of 31.7 under a 48 GiB load. That is the strongest evidence available on that question and it came off your run, so I am carrying it into the triage there.

This PR has converged: Codex approved 80b2291c31, which is head, all inline items are reacted with none open, and CI is green so far with the rest pending.

@danielhanchen

Copy link
Copy Markdown
Member

Verified the corrected script on the gfx1151: --clone-adapter reproduces, --split 3 does not

Rebuilt the environment and ran the corrected spoof_two_gpus_windows.py on the real hardware. One of the two verification claims holds; the other cannot hold as written, and the reason is the capacity guard doing its job.

--split 2 --clone-adapter — confirmed

Under a matching load, on #8863's branch:

=== presented as 2 device(s), each with 44.73 GiB of props total ===
  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=15.86 total=44.73
  ordinal 1  AMD Radeon PRO W7900               used=15.86 total=44.73
  aggregate: 31.72

Against the stated 15.87 / 15.87 and 31.73. The 0.01 is counter jitter between samples, not a disagreement. The same run at idle gives 0.59 / 0.59 with aggregate 1.19 — identical structure, scaled by whatever is resident. Both fixes work: attribution now succeeds where it previously declined, and the getattr guard reports the classifier correctly.

--split 3 through the cardinality path — returns None, not 31.73

=== presented as 3 device(s), each with 29.82 GiB of props total ===
  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=29.82 total=29.82
  ordinal 1  AMD Radeon PRO W7900               used=0.0   total=29.82
  ordinal 2  AMD Radeon PRO W7900               used=0.0   total=29.82
  aggregate: None

The two halves of that claim cannot coexist. At --split 3 each spoofed device carries 89.465/3 = 29.82 GiB, so a 31.73 GiB counter is one no visible card could hold, and _rocm_windows_aggregate_used_bytes fails closed. Calling it directly with this machine's numbers:

split 3: capacity/device 29.82 GiB, counter 31.72 -> aggregate None
split 2: capacity/device 44.73 GiB, counter 31.72 -> aggregate 31.72
idle counter 1.19 at split 3                      -> 1.19

So the cardinality path at --split 3 works at idle — I measured 1.19, and 1.06 on the pre-correction script earlier — but not at the load that produces a 31.7 GiB counter. The 31.73 aggregate is reachable at --split 3 only via --clone-adapter, which routes through the LUID join and divides the bytes into three rows of 10.57:

=== pr8863 --split 3 --clone-adapter ===
  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=10.57 total=29.82
  ordinal 1  AMD Radeon PRO W7900               used=None  total=29.82
  ordinal 2  AMD Radeon PRO W7900               used=None  total=29.82
  aggregate: 31.72

This is the guard working, not a defect — the same guard that produced the original item 4 None. Suggest the errata line be amended to either "--split 3 at idle" or "--split 3 --clone-adapter", since as written it would send the next person hunting for a bug that isn't there.

Two incidental readings from the same runs

  • On Studio: take the AMD APU total on Windows from the driver, not the carve-out #9314's branch, --split 3 widens ordinal 0 to 89.47 with used=None and probes [0] — still correct with three devices, and the two fake discrete cards are left alone.
  • In the --split 3 --clone-adapter run, only ordinal 0 received bytes while ordinals 1 and 2 came back None, though the aggregate survived at 31.72. Partial attribution rather than a clean three-way split; possibly worth a look if --split 3 is meant to be a supported shape, though nothing downstream depends on it.

Environment torn down afterwards: worktrees removed and pruned, venv deleted, no registry state touched by any of this (all four runs above are read-only and in-process).

@danielhanchen

Copy link
Copy Markdown
Member

Correction: my --split 3 line was measured on the wrong machine, and the partial attribution is now fixed

You are right on both counts, and the --split 3 claim in my errata was an artifact of where I measured it. I verified the corrected script on a B200 with 178.35 GiB of props total, so at --split 3 each spoofed device carried 59.45 GiB and a 31.7 GiB counter fit comfortably inside it. On an 89.465 GiB APU each device carries 29.82 GiB and the same counter is one no visible card could hold, so the guard fails closed exactly as you measured. I stated it as a property of the flag when it was a property of my hardware.

Re-ran it against your machine's numbers rather than mine (89.465 GiB props, the 31.72 counter, three instances). Everything reproduces:

run counter result
--split 2 --clone-adapter 31.72 15.86 / 15.86, aggregate 31.72
--split 3 31.72 aggregate None
--split 3 1.19 (idle) aggregate 1.19

So the errata line should read "--split 3 at idle, or --split 3 --clone-adapter", and I have corrected it below rather than leaving it to trip the next person.

The partial attribution was the harness, and it is fixed

Good catch on ordinals 1 and 2 coming back None at --split 3 --clone-adapter. That was mine: --second discrete gave every spoofed discrete card the same name, so the clone put them under one key, and several devices under one key feed only the aggregate by design (#7452). At --split 2 it never shows, because there is only one discrete ordinal. At --split 3 it looks like partial attribution and reads as a defect.

Each spoofed ordinal now takes a distinct card, so the key is identifying again:

    _DISCRETE = (
        ("AMD Radeon PRO W7900", "gfx1100"),
        ("AMD Radeon PRO W7500", "gfx1102"),
        ("AMD Radeon RX 9070 XT", "gfx1201"),
        ("AMD Radeon RX 7800 XT", "gfx1101"),
    )

With that, --split 3 --clone-adapter attributes all three instead of one:

  ordinal 0  AMD Radeon(TM) 8060S Graphics      used=10.57 total=29.82
  ordinal 1  AMD Radeon PRO W7900               used=10.57 total=29.82
  ordinal 2  AMD Radeon PRO W7500               used=10.57 total=29.82
  aggregate: 31.72

Idle behaves the same way at 0.4 each. So --split 3 is a supported shape now, which it honestly was not before.

One asymmetry your --split 3 output exposes, which is not a defect

In the loaded --split 3 run, ordinal 0 reports used=29.82 against total=29.82, a flat 100%, while the aggregate declines on the same input. That is two helpers disagreeing about an over-capacity counter: _match_adapter_used_to_devices clamps it with min(useds[rank], device_totals[pos]) (hardware.py:2439, 2446, 2459), whereas _rocm_windows_aggregate_used_bytes treats it as proof the counters are not the visible set and returns None.

I am not raising it. A Dedicated Usage counter above the device's own capacity is not reachable on real hardware: on a discrete card the counter is bounded by the card, and on a unified APU it is bounded by the carve-out, which is precisely why counters are ranked against dedicated_bytes rather than the displayed total. It is reachable here only because the harness divides one device's memory by three while the counter still reflects the whole. Worth knowing the two paths differ, not worth changing.

Status

Both fixes you verified are the ones that mattered, and #8863 has converged: Codex approved 80b2291c31, which is head, no open items, CI clean.

The pool_confirmed reading at the end of your earlier comment is the one still doing work, and it is on #9314 rather than here. I am carrying it into the open review item there.

@danielhanchen
danielhanchen merged commit e79354e into unslothai:main Aug 25, 2026
35 checks passed
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
…on LUID (#8863)

* Join the Windows GPU adapter counters to torch devices on the adapter 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.

* Decline the DirectX adapter map when a record will not read

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.

* Bound the LUID join by the carve-out, not the displayed total (#8863)

Forward guard for the interaction with #9314, which widens total_bytes to the
whole driver pool on a unified APU. _attribute_adapter_useds_by_key reads
total_bytes as the capacity a Dedicated Usage counter can fill, both to rank
positions and to reject a usage no card could hold. That counter measures the
dedicated segment, so its ceiling is the carve-out and never the pool: against a
128 GB ceiling a 9 GB counter belonging to no visible card passes the check and
gets published on a card that never held it.

Neither PR does this alone. #8863 has no widened total and #9314 has no LUID
join, so it only appears once both are in, whichever order they land.

_adapter_counter_capacity() prefers dedicated_bytes and falls back to
total_bytes, so this is correct on this branch, where dedicated_bytes does not
exist yet and the fallback makes it a no-op, and correct the moment #9314
rebases on top. The capacity-ranking fallback path takes it too, so both
consumers of a counter agree on what bounds it.

Two tests: the helper's preference either way round, and the join declining an
impossible counter against a widened total while still attributing one that
fits.

150 pass in the ROCm/VRAM files, 1768 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

* Do not stop the LUID join at a pass that answered nothing (#8863)

Two defects in _match_adapter_used_by_luid, both found by review.

A pass can succeed while naming no device: several cards under one key leave
per-device unknown and contribute only to the aggregate. Returning on the first
non-None result therefore ends the search on a vacuous success, and two cards
sharing a Description but differing in gcnArchName stay unknown even though the
gfx pass would separate them. The docstring already promised that a declined
name join falls through to gfx; it now covers a vacuous one too. The first such
result is kept for its aggregate and returned only if no later pass attributes.

And a key that leaves AMD usage unplaced is not identifying reliably. A visible
card whose Description differs from its props.name puts its own counter under a
key no device claims, while a hidden card wearing the device's name sits under
the one that is claimed, and the pairing hands the hidden card's bytes to the
visible device. Measured on the added case: 17 GiB belonging to a masked card
reported as the visible card's. The pass now declines, which costs a masked
second AMD card its join and falls back to capacity ranking, where that case
already was.

Both tests fail on the parent: [None, None] instead of [9.0, 3.0], and 17.0
instead of None.

1810 pass 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

* Tighten the comments this PR adds

Comment-only pass at convergence. Three blocks trimmed without losing intent:
the counter-capacity helper's docstring, and the two guards added this round in
_match_adapter_used_by_luid.

* Add a temporary Windows AMD LUID probe for #8863

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

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

* Add a zero-dependency Windows AMD report anyone can run

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

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

* Keep the testing instructions on the PR rather than in the tree

* Pin the measured Windows AMD registry reading, and correct the two-key note (#8863)

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

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

* Keep the LUID pass that places more devices, not the first that places any (#8863)

* Pin the measured Strix Halo: three counter instances, one GPU, join-only aggregate (#8863)

* [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>
danielhanchen added a commit that referenced this pull request Aug 26, 2026
…ys on the GPU (#9675)

* studio: placement planner that spills weights with -ot, never the cache

llama.cpp's --fit spills whole layers through n_gpu_layers, and a layer's KV
cache is allocated on model.dev_layer(il), so spilling a layer takes its cache
to host RAM with it. Measured at 128K on one B200: weights spilled with the
cache resident runs 71.63 t/s, the reverse runs 3.24. -ot overrides tensor
buffer types without touching layer assignment, so the cache stays put, and
that is what this plans.

Three pieces:

- offload_layout.py reads a GGUF into the buckets that decide placement:
  spillable per block, resident per block, lm_head, token_embd (which llama.cpp
  pins to the CPU unconditionally and so is never VRAM), the attention cache
  per token over the attention layers only, and the Mamba recurrent state.

- offload_planner.py picks the placement: nothing spilled if it fits, then the
  minimum set of blocks, then lm_head. Never -ngl and never --no-kv-offload.

- offload_cost_model.py prices a candidate in milliseconds per token, and the
  planner reports that on every plan. Time, not percentages: lm_head reads as
  43 percent alone and 16 percent on top of FFN, which looks sub-additive,
  while the same bytes cost 10.206 ms alone and 14.428 on top.

The cost model takes a host profile because spilled decode runs on the CPU
backend: ggml migrates an op to the GPU only at batch >= 32 and decode is batch
1, so the penalty tracks core count (2.42 / 5.83 / 11.82 / 14.94 t/s at 4 / 16
/ 64 / 192 threads). A planner blind to that gives desktop users server advice.

Unified memory hosts abstain outright, since there spilling moves bytes between
two names for the same chips.

* studio: wire the spill planner into the launch path, gated and off by default

The seam is the elif use_fit: arm and nothing else. That arm is entered because
_select_gpus already gave up, so it is the one place Studio has admitted it
cannot place the model; the manual and proved arms have placement decided and
must not be re-placed.

It emits -ngl -1 --fit off plus one -ot per pattern. Each token is load bearing:

- --fit off is required, not tidiness. The fitter aborts only on an
  n_gpu_layers the user really set (common/fit.cpp), and -1 is llama.cpp's own
  default (llama-model.cpp), so -ngl -1 does not hold it off. Left enabled it
  would re-place layers over the plan and put the cache back on the host, which
  is the thing this exists to prevent.
- -ngl -1 keeps every layer assigned to a GPU, so dev_layer stays a GPU and the
  cache is allocated there.
- One flag per pattern. llama-server accumulates repeated -ot and splits an -ot
  VALUE on a comma. Joining with a semicolon is llama-bench syntax and would be
  read as a single pattern.

The planner declines whenever anything else owns placement: a user -ot or
--cpu-moe, a layer count, a device list, any explicit --fit, or the env twin of
each. Declining reproduces today's argv byte for byte, which is the safety
argument: pricing a placement the child will not get is the bug class behind
most of the load-mode review traffic.

Shared devices are dropped from the credit rather than summed, since an APU or
iGPU reports host RAM as its VRAM and crediting both counts one pool twice.
Host threads are read from the machine, because spilled decode runs on the CPU
backend and its cost tracks core count.

The plan is revoked once, inside _spawn_and_wait, rather than at each retry
site, so a recovery path added later is covered without anyone remembering.

Gated behind UNSLOTH_SMART_OFFLOAD, default off.

* studio: do not count the MTP block as spillable

Caught running the planner's own output against llama-server rather than
against the unit tests. The plan for a 16 GiB budget named 16 blocks totalling
2.8378 GiB, and the child moved 2.633 GiB. The 209 MiB gap is exactly the three
FFN tensors of blk.64, the nextn/MTP block.

Confirmed directly: spilling ONLY that block leaves the host buffer at exactly
token_embd (682.03 MiB) and the device buffer unchanged at 15718.48 MiB. Those
tensors are not part of the target model and llama.cpp does not load them unless
a draft is engaged, so an -ot pattern naming them moves nothing.

The direction is the dangerous one. The planner believed it had freed 209 MiB
more than it did, which is how a load that does not fit gets planned as one that
does. Studio prices the drafter separately, so dropping the trailing nextn
blocks from the block list is the whole fix.

The measured-bucket test pinned the pre-fix totals, since the earlier hand
arithmetic also counted all 65 blocks. Corrected to the real numbers: Q4
spillable 9.888 and block-resident 4.491 GiB, Q2 5.291 and 2.471.

* Drop workspace design notes from the branch

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

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

* studio: stop the cost model under-pricing spills on small hosts

Measured against real hardware rather than the one machine the model was fitted
on. 70 runs on T4, L4, A100 and RTX PRO 6000 at 2, 8, 12 and 48 vCPU, over
Qwen3.8-27B and Qwen3.6-35B-A3B at Q2_K_XL, Q4_K_XL and Q8_K_XL, comparing the
predicted generation penalty against the measured one:

  48 cpu   1.09 median      12 cpu   0.59 median
   8 cpu   0.24 median       2 cpu   0.24 median

Accurate on a big host, optimistic by up to four times on a small one, and
optimistic is the direction that quotes a spill which then runs several times
slower than promised.

The cause is that the shipped fit varies THREADS ON ONE MACHINE. Twelve cloud
vCPUs are roughly six physical cores sharing one memory controller, not twelve
threads of a 192 core server, so the slope across machines is steeper. Fitting
dense Q4 on the 12 and 48 vCPU hosts gives a = 278.2 and b = 1.03 against the
shipped 138.4 and 5.57.

Neither fit dominates. At 192 threads the cross-machine line predicts 2.48 ms
per GiB against 5.498 measured, and at 12 the one-machine line predicts 17.1
against 24.21 measured, so the rate now takes whichever is more expensive. That
keeps the reference host's own validated numbers (1.01 at 192, 1.09 at 48) and
lifts 12 vCPU from 0.59 to 0.88.

One residual is left in place and named rather than tuned away. Cost per spilled
GiB is ordered by dequant complexity, not by byte count: at 12 vCPU the measured
rates are Q2_K 84.17, Q4_K 24.21 and Q8 19.96 ms per GiB, so Q8 is the cheapest
per GiB despite being the largest format. A quant multiplier is the obvious next
step, but the multiplier itself moves with core count, 3.5x at 12 vCPU against
1.3x at 48, and fitting that from two core counts would be overfitting. Dense
Q2_K on a very small host therefore remains under-priced, and the comment says
so.

test_a_smaller_host_makes_every_spill_worse asserted the old shortfall, that the
model under-warns at 16 threads by about 22 percent. It now predicts 2.93x
against a measured 2.885x, so the assertion is inverted to require no
under-warning and bounded at 10 percent over, which is the side worth being on.

* studio: do not emit spill flags for a plan that spills nothing

Four defects from the first review round, all in the optimistic direction.

The seam gated on `if _spill:`. Plan is a dataclass with no __bool__ or
__len__, so every instance is truthy, including the ones plan_placement returns
to say it could NOT place the load. There are six such returns: incomplete
layout, unified memory, no creditable VRAM, no usable context, insufficient, and
the rung where the load already fits. Each of those appended
-ngl -1 --fit off with no -ot at all, which switches llama.cpp's fitter off and
pins every layer to the GPU on exactly the loads the planner had just declined.
On a host that cannot fit, that is an OOM where --fit on would have placed the
model. It also made the PR's compatibility claim false: declining did not
reproduce the previous argv. Now gated on a plan that actually spills something.

The measured KV cache size was computed and never used. layout.kv_bytes
under-estimates on an f32 cache, on flash-attn-off V padding, and worst on MLA,
where the estimate prices a K-only latent against the layout's full K+V pair.
The measured value is now a floor under the estimate, taken as a max rather than
an equality because cell padding rounds to 256 and the two will not agree
exactly.

A startup failure on the first spawn had no recovery. The revocation at the top
of _spawn_and_wait needs a label, which is empty on the first spawn;
fully_gpu_offloaded is only set in the gpu_indices arm; and
_fit_off_retry_eligible returns False on use_fit, which is this arm's own
condition. All three miss, so the loop fell through to the terminal fallbacks
with the plan still applied. A third recovery now shares the existing retry slot.

A split GGUF was planned from one shard. GGUFReader memory-maps a single file
and has no split handling, while llama.cpp reads split.count and loads every
sibling, so the layout saw a fraction of the tensors. Studio passes the main
shard and already sums all siblings for the model size, so the two disagreed
silently. The planner now abstains when split.count says there are siblings.

One item was rejected. Emitting the planner's chosen load mode is real but
pessimistic: mmap costs throughput and cannot turn a fit into an OOM. It is also
not a one-line change, since --load-mode is owned by the memory policy on this
path and a bare extend would overturn a user's keep-resident setting.

Two test-quality problems came out of this. test_a_floor_that_does_not_fit
asserted insufficient on the returned plan, which is true with or without the
bug, so it passed while the seam was broken. And the test that was supposed to
defend the compatibility claim asserted the SOURCE TEXT of the else branch,
which is why it also passed while the abstain path was emitting --fit off. Both
now drive the real flag builder. A third test pinned a multi-token argv literal
through inspect.getsource, the same shape that broke CI on the sibling PR when
the formatter rewrapped it; it is now behavioural too.

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

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

* studio: raise the per-device overhead reserve to cover the prefill buffer

Measured on Colab A100 and RTX PRO 6000. At depth 32768 the dense 27B failed to
load on every budget with the plan reporting insufficient=False:

  ggml_backend_cuda_buffer_type_alloc_buffer: allocating 594.16 MiB on
  device 0: cudaMalloc failed: out of memory
  llama_init_from_model: failed to allocate compute pp buffers

It failed consistently rather than randomly, which is what made it easy to miss.
The planner fills to budget minus the reserve, so whenever it spills it leaves
exactly the reserve free WHATEVER the budget is, and 6, 7, 8 and 10 GiB budgets
therefore died with the identical shortfall.

The child needs the prefill compute buffer, 594 MiB there, plus its own CUDA
primary context, which is what consumed the rest of the old 1 GiB. That puts the
requirement just over 1.07 GiB. 1.5 GiB covers it with margin.

Ruled out first: this is not fragmentation from the benchmark pinning VRAM to
force a smaller card. Rerunning the same case with 16, 64 and 1024 MiB hog
blocks reproduced the identical 594.16 MiB failure, so the hog's block size is
not what runs out. The native runs that passed did so only because the model
fitted whole and left real headroom, which is not a test of the spilling path.

It is a measured floor, not a fitted curve. The steady-state compute buffer is
flat in context, 493 to 509 MiB from depth 4096 to 32768, but the prefill
graph's reservation is not, and two depths do not justify fitting a slope.
Erring high costs some spill at the measured 5.544 ms/GiB; erring low costs the
whole load.

Moving the constant broke 19 tests whose expected values are arithmetic against
it rather than independent measurements. Rather than rewrite the expectations,
which would bake the new constant in just as hard, those tests now pin the
reserve they were computed for, and the constant itself is pinned once with the
evidence above.

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

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

* studio: tell the planner when the host is a unified-memory APU

The planner abstains on unified memory, since there an -ot spill moves bytes
between two names for one pool: it frees no device memory and buys only the CPU
backend's slower read path. But it abstains solely on HostProfile.unified_memory,
and the seam never set it, so the default False meant that abstain could not fire
in production at all.

The neighbouring shared_gpu_ids guard does not cover this. It is populated only
when is_vulkan_backend is true, because Vulkan reports total VRAM 0 for an
integrated GPU, and is an empty set on every other backend. A Strix Halo
(gfx1151) running ROCm, which is what scripts/install_rocm_wsl_strixhalo.sh
installs, therefore arrived with its APU "VRAM" credited AND host RAM credited,
counting one pool twice, and the planner would then spill to free memory it
cannot free.

Studio already classifies these devices: _amd_apu_wants_unified_memory reads the
driver's own integrated flag first, then gcnArchName, then the device-name
substrings the AMD wheels leave behind when both are absent, covering gfx1150
Strix Point, gfx1151 Strix Halo, gfx1152 Krackan Point and the gfx1103 Phoenix
iGPUs. It is scoped by the selected GPU ids, so a discrete card on a mixed host
is not treated as unified. The seam now passes it through.

Verified no regression across the AMD and ROCm suites: 328 passed over
test_amd_apu_unified_memory, the two amd-smi inventory suites, the five rocm
guards and the Vulkan probe. tests/sh/test_strixhalo_wsl_reroute.sh, the shell
coverage of the ROCm WSL reroute, is 53 passed 0 failed.

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

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

* studio: plan against the budget the fit actually tested

Five defects from the second review round, all optimistic.

The seam credited raw free VRAM. Every other placement decision in this file
goes through _gpu_usable, which subtracts the user's VRAM-budget fraction and
the per-card reserve floor, and the planner was handed the unreduced number. It
bites at the 0.97 default, not just at the 0.80 floor, and it makes the plan
spill too little and then pin that result with --fit off.

The projector and the MTP reserve were missing from the deficit. Studio's own
model_size_fit carries the GGUF, the projector at its safety multiple and the
MTP reserve; the planner rebuilds the model from the target GGUF's tensor table,
so neither is visible to it. Both are passed in now. The compute buffer is
deliberately NOT passed: soft_overhead plus the per-device pipeline reserve
already stands in for it, and charging it twice would only spill more.

Split mode and tensor split are placement, and they were not in _DEVICE_FLAGS.
-sm none is the dangerous one: llama.cpp clears model->devices and pushes back
only devices[main_gpu] (llama.cpp:288-299), so the child runs on one card while
the planner had credited the sum of every selected card. -ts replaces the
free-memory proportional split (llama-model.cpp:1417-1447), so one device can
overflow while the pool total still fits. Both now abstain, argv and env alike.

The MTP blocks were reachable through the -ot patterns. block_count is
n_layer_all (llama-model.cpp:1206) while n_layer() subtracts the nextn blocks
(llama-hparams.cpp:301-303), and those trailing blocks are full decoder blocks
carrying ffn_down_exps and gate_up (models/qwen35moe.cpp). Since -ot is matched
with std::regex_search (llama-model-loader.cpp:1182), an unbounded \d+ pattern
reached them once a draft was loaded. Harmless for VRAM but it inflates
host_bytes, which is what gates --load-mode none.

The layout cache was keyed on pathname alone, on an instance that outlives a
load, so a GGUF replaced in place kept the old tensor table.

Three items were rejected. The spill-order counterexample is real and the
docstring's byte-minimality claim is wrong, but the overshoot is bounded by one
block and errs toward spilling more. plan_to_args has no non-test caller and the
seam leaves context_policy at NEVER_REDUCE. And the recurrent-state double count
is real but is tens of MiB in the safe direction, and removing it honestly needs
a new flag threaded through three functions.

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

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

* fix(logs): quiet the polls and drop the duplicated access lines (#8763)

* Studio: quiet the liveness poll and keep access lines out of tauri.log

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB,
of which 4056 (76%) were request_completed access records and 3355 (63%)
came from six polling endpoints. At ~216 bytes a line the 5 MiB cap fills
in about 18 hours, so a failure from the day before had already rotated
out by the time anyone asked for it.

/api/liveness is the desktop watchdog's own probe, roughly every 19s, and
was in no suppressor at all: 760 lines, 14% of the file, saying the
process is still up. Its sibling /api/health was already quiet. Put it in
_QUIET_POLL_PATHS so it heartbeats; non-2xx still logs every time, which
is the case that matters for a watchdog.

Every backend stdout line is written to disk three times: the backend's
own session log, the diagnostics phase log (stream-tagged and stamped),
and tauri.log. The access records carry nothing in the third copy that
the first two lack, so log them at debug!, below the file target's INFO
filter. Non-JSON output -- the startup banner, "Hardware detected:",
stderr, tracebacks -- keeps INFO, which is what anyone opening tauri.log
is there for. The phase log still gets the unfiltered stream, so the
support report loses nothing.

Also:

- Collapse carriage-return progress frames. Reading to \n means a tqdm bar
  arrives as every frame it drew concatenated onto one line; a single
  "Loading weights" bar measured 5086 bytes across three sinks. Keep the
  final frame, which is the one showing 100% and the elapsed total. Cap
  what reaches tauri.log at 16 KiB, the limit the phase log already used.

- Bound logs/llama-server and logs/diffusion-server. Both directories are
  created per model load and were never pruned (319 files going back two
  months here). The server session log has capped itself since it was
  added, so lift that into utils/log_retention.prune_log_dir and call it
  from all three rather than write the loop a third time.

- Log the top-models catalog at debug. Two lists of 40 repo names, one
  line each, on every boot to say a fetch succeeded; the counts say that.

- Configure structlog in run.py before the first line it logs. main.py
  configures on import, several seconds later, so "run_server startup
  begin" rendered through the defaults (console, local time) and
  everything after it as JSON in UTC -- the clock appeared to jump hours
  between the first and second line of one stream.

Not included: the same carriage-return collapse on the Python tee. Doing
it there means line-buffering the file copy, which would withhold a
partial line from server-*.log exactly when the server hangs mid-write.

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

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

* Collapse progress frames in the session log too, and quiet remote-access

The first pass collapsed carriage-return redraws on the Rust side only. It
left the Python tee alone because doing it there seemed to mean buffering
the file copy until a newline, which would withhold a partial line from
server-*.log exactly when the server hangs mid-write.

It does not have to. Hold back a frame, never a line: an unterminated chunk
containing "\r" is a redraw and is kept until the next one supersedes it,
while an unterminated chunk without one -- a prompt, or a traceback torn by
a hang -- is written the moment it arrives. So the session log gets one
line per bar instead of one per frame, and nothing diagnostic waits on a
newline that may never come.

The console side is untouched: it still sees every frame, which is the
whole point of a progress bar.

Also adds /api/settings/remote-access to the quiet polls (116 lines in the
same 4h sample), for the same reason as the others: it is a plain read of a
toggle, re-read whenever the settings dialog is open.

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

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

* Install the tee before structlog, and stop three suppressors overreaching

Four review findings, all real.

structlog was configured at import, and PrintLoggerFactory snapshots sys.stdout
while cache_logger_on_first_use freezes that snapshot into any logger that has
already logged. run_server's own logger logs at line one and the tee is not
installed until 45 lines later, so every subsequent run.py line -- the orphan
sweep warnings, the whole rest of startup -- was pinned to the console and never
reached the session log. Configure inside run_server instead, after the tee:
the ordering bug the change set out to fix (line one rendering through
structlog's defaults while line two rendered as JSON in UTC) is still fixed,
and the file gets everything from line one. Moving the tee up also means the
orphan sweep now lands on disk, where it was console-only before.

A withheld progress frame was concatenated onto whatever came next, so a
structlog record arriving mid-redraw landed as Loading 47%{"event": ...} and
stopped being parseable. Close the frame off on its own line unless the next
write is its own redraw or its terminator, and land a frame still held at
close() rather than dropping it.

The desktop watchdog polls every 15s (HEALTH_WATCHDOG_INTERVAL) plus up to a
10s probe budget, so _QUIET_POLL_DEDUP_MS at 10s could never close over two
probes and putting /api/liveness in _QUIET_POLL_PATHS collapsed nothing. Give
it its own 60s window, zeroed alongside the quiet window so --verbose still
logs every probe, and pin the floor with a test that reads both constants out
of commands.rs.

is_backend_access_log_line matched on the event name alone, so it also dropped
non-2xx records to debug! -- below tauri.log's INFO filter. Those are the ones
the backend's heartbeat suppressor deliberately exempts, and a watchdog going
red is what tauri.log is read for. Match only 2xx; a record with no status_code
keeps its INFO line too.

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

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

* run.py: keep CRLF lines, stop leaking the tee, import LogConfig lazily

Three defects in the same file, all found while checking this branch against
main. Tests for each alongside.

1. The tee destroyed every CRLF-terminated line.

_last_frame took rpartition("\r")[2] unconditionally, so the "\r" of a CRLF read
as a redraw boundary whose final frame was empty, and the payload went with it:

    "Hardware detected: NVIDIA GeForce RTX 4090\r\n"          -> "\n"
    "Traceback...\r\n  File \"run.py\"...\r\nRuntimeError\r\n" -> "\n\n\n"

On Windows that is every line a child process relays, so a relayed traceback
landed in the session log as blank lines. It is also exactly the artifact #8690
added a UI for. The desktop reader already gets this right: trim_line_endings
strips every trailing \r and \n before collapse_progress_frames sees the text.
Mirror it here so the two sinks stay interchangeable for a reader, and fall back
to the last non-blank frame the same way, so a bar that signs off with a bare \r
keeps its 100% frame instead of writing a blank line.

Also: a "\r" must never reach the file. The handle appends the platform
terminator itself, so one that survives lands as "\r\r\n" on Windows.

2. A zero-length write reopened the record corruption fixed on 08-18.

`data[:1] not in ("", "\r", "\n")` read write("") as a continuation of the held
frame, so the close-off was skipped, the frame fell through to the unterminated
branch, and the next record was glued onto it:

    ["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n']
    -> 'Loading weights:  47%{"event": "model_loaded"}'

print("", end = "") is enough to reach it. Return early on empty data instead.

3. A rejected flag combination left the streams swapped.

--secure --no-cloudflare is a deterministic preflight failure, but it now runs
after _setup_server_disk_logging() has replaced sys.stdout and sys.stderr and
opened a log handle, and nothing unwinds either. An embedder that catches the
SystemExit keeps the tee, and its next run_server() call nests a second one, so
every line is written twice. main does not do this. Validate before the tee.

4. `from loggers.config import LogConfig` at module scope broke Repo tests (CPU).

15 failures in tests/studio/install/test_selection_logic.py, all
"No module named 'loggers.config'; 'loggers' is not a package".
load_studio_run_module stands a bare types.ModuleType in for `loggers` before
exec'ing run.py; a bare module has no __path__, so the import fails during
collection and takes every test in the file with it. That fixture's own comment
names the hazard. LogConfig has one use, inside run_server, so import it there
rather than widening a stub three directories away.

* Prune the log directories after opening the new file, and protect it

Two problems with prune_log_dir as it stands.

The cap never held. All three call sites prune before creating the log, so with
keep=20 the directory settles at 21 and every load repeats the prune-to-20,
create-the-21st cycle. Measured with 25 seeded files and 10 loads: 21 with this
ordering, 20 when the prune runs after the open.

And one odd directory entry disabled retention entirely. The mtime sort ran
inside a single try/except, so a dangling symlink matching the glob raised on
stat() and the whole call returned having deleted nothing. Seeded with 30 files
plus one broken link, keep=5 left all 30. That is the unbounded growth this
helper exists to stop, reintroduced by one bad name. Stat failures are now
per-entry.

Only regular files count now, too: a directory that happens to match the glob
was taking one of the kept slots (25 files plus one such directory, keep=5, left
4 real logs).

prune_log_dir grows a `protect` argument, and the call sites move to after the
open. `protect` is never deleted and counts as one of the `keep`, so the total
stays at keep. It is not enough to trust the new file to sort newest: two loads
in the same second, or a clock that steps back, and it does not.

The retry call site benefits most. The comment right above it explains that the
-try{n} suffix exists so a respawn within the same second cannot truncate the
crash log a retry warning just pointed the user at; pruning before the open on
every attempt worked against that.

New tests cover keep values, the protected file counting toward the cap and
surviving even when it sorts oldest, dangling symlinks, symlinks pointing
outside the directory, directories matching the glob, identical mtimes, family
isolation, and a writer appending across a prune.

* process.rs: CRLF and marker tests, and say what debug! means here

collapse_progress_frames is correct on CRLF because trim_line_endings runs
first, but nothing pinned that, and the Python tee that writes the backend's own
session log got it wrong. Add the cases that hold the two implementations
together: a CRLF payload keeps its text, a CRLF-terminated bar still collapses, a
CRLF JSON record stays parseable and still classifies, a TAURI_PORT marker
survives the collapse whether or not it shares its line with a redraw, and an
all-blank line never keeps a carriage return. Plus the 16 KiB truncation landing
on a character boundary for multi-byte text.

The fallback for an all-blank line returned the whole text, which still holds the
\r the caller asked to collapse away. Return the last frame instead.

Two comment fixes. The new test module had been inserted between the
C:\Windows\system32 comment and the managed_cli_working_dir_tests module it
describes; move it back. And record what debug! actually does for a matched
record: setup_logging in main.rs builds every logger at LevelFilter::Info and
there is no RUST_LOG or any other way to raise it, so log::max_level() is Info
and a matched record is dropped outright rather than demoted, including under
backend --verbose, which makes it emit more of them. That is fine, but it is not
obvious from the call site, and the surrounding comment argued the opposite case
for non-2xx. The records are still written verbatim to the diagnostics phase log
(append_phase_line runs before this decision) and to the backend session log,
both of which the support report and Settings > Logs already offer.

Separately, test_watchdog_window_outlasts_the_probe_interval read the module
global, so it failed for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS
exported; read the default instead. Its two regex lookups now report what moved
in commands.rs rather than raising AttributeError on .group(1).

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

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

* Tighten the comments this PR adds

Comment-only pass over the 10 files the PR touches. No code change: the AST gate
(comment_tools.py check --strip-docstrings) reports 9/9 files comments-only, the
Rust file has no non-comment line in the diff, and no docstring was dropped.

114 insertions, 142 deletions. Heaviest in run.py and process.rs, where the same
explanation was being given twice, once in a doc comment and again at the call
site. Every load-bearing why is kept: the structlog factory/cache ordering, why a
CRLF terminator is not a redraw, why the watchdog window has to outlast the poll,
why prune runs after the open, and what debug! means for a matched record.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>

* Xet notice: one toast carrying both messages, three times per install, gone when the download is (#9660)

* One start, one toast: let the Xet notice yield to a caller that already explained

Picking a model in chat raised two toasts stacked in the same corner: the
Xet notice, and chat's own "Downloading model / It'll load automatically
once the download finishes". Both are true, both say the same thing in
different words, and the user is told twice for a single start.

DownloadRequest gains callerExplainsWait, set by the two chat-page paths
that toast about the start themselves. startJob passes it to
shouldShowXetNotice, which now returns false for those, so the notice
stays quiet and does not spend one of its three doing so. The Hub
download card sets nothing and is unaffected: it has no start toast of
its own, which is why the notice exists.

The UI evidence for #9658 missed this because the scene drove the Hub
download card, and only chat's picker raises a start toast. The unit test
added here covers the predicate directly.

* Fold the caller's line into the notice, count on the server, dismiss when done

Three separate reports, one feature.

ONE TOAST, CARRYING BOTH MESSAGES. #9660 suppressed the Xet notice whenever
chat had its own toast, which removed the 0%-explanation exactly where a
first big download makes it most useful. The caller now states its message
and the download manager decides how to say it: folded into the notice when
that fires, on its own when it does not. DownloadRequest.callerExplainsWait
becomes callerToast. transport-conflict's early return also announces, since
it reports "started" without ever reaching startJob and used to rely on
callers toasting for themselves.

The composed sentence is chat-only. A Hub download does not auto-load, so
"It'll load automatically" would be false there, and the Hub variant is also
the one that renders over the hub toolbar, which is what the character budget
in the tests protects.

THREE TIMES FOR THE LIFE OF THE INSTALL. The count lived in localStorage,
which is per-origin, and a Studio origin is not stable: run.py falls back past
port 8888 when Jupyter has it, and Colab and the tunnel are different origins
again. Each of those handed out a fresh three, so the notice never actually
stopped. It moves to app_settings behind a reserve endpoint that does the read
and the write in one transaction, which also retires the Web Locks dance that
existed to narrow the same race in the browser. Fails closed: an unreachable
endpoint shows nothing rather than falling back to a count that resets.

GONE WHEN THE DOWNLOAD IS. The 8s duration is a cap, not a description of the
transfer, so a small model finished, auto-loaded, and the toast was still
saying the download was running. finalize() now dismisses it.

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

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

* Drop the unused xet-notice GET route

Added alongside the reserve endpoint out of symmetry with /helper-precache,
but nothing calls it: the frontend only ever POSTs a reservation. It also had
an awkward shape, always reporting granted=false because it reused the reserve
response model. An endpoint with no caller is surface to maintain and review
for no benefit.

get_xet_notice_count stays. It is the read half of the module and the tests
assert stored state through it; the alternative is tests poking sqlite
directly, which is worse.

* Tighten the comments on PR #9660

Comment-only. Cuts about 120 lines of prose without losing the reasons: why
the copy has a character budget, why the reserve is one transaction, why the
count moved off localStorage, and why the reservation fails closed.

No code changed: the diff for this commit has zero non-comment lines in the
TypeScript, and the Python edits are docstring bodies only.

* Fix the start-toast lifetime, surface and reservation for PR #9660

- keep chat's auto-load sentence for the Xet notice to fold in, but never raise it
  on its own: #9663 removed that standalone toast as a duplicate of the panel
- drop the caller's line from a request deferred by a transport conflict; it is
  resumed from the Hub, where 'it'll load automatically' is not true
- do not announce a start the user already cancelled, and re-check the job before
  publishing a toast the reservation round trip outlived
- dismiss a start toast when its surface is left: the composed form measures 167px
  against a hub filter row at 158px
- keep the legacy notice count until the server confirms it, and stop the Tauri
  network retry from spending a second notice on this non-idempotent POST

* Hold a start toast against the route it started on for PR #9660

- the Xet reservation is a round trip, so the raise can land after the user has
  navigated; capture the route at the start and drop a raise that arrives once
  that surface is gone, instead of recording the destination as its origin
- drop the toast for a pending auto-load that a newer selection replaced: its
  completion no longer loads anything, so the promise is stale
- type the toast stub so tests/download-start-toast.test.ts typechecks

* Take the start route before the preflight, and validate the reservation for PR #9660

- capture the origin route in requestStart, before the transport preflight and
  apiStart; reading it afterwards named whatever page the user had moved to
- a 200 carrying some other JSON is not proof the backend stored the legacy hint,
  so require a reply that reports the cap it enforced before ending the migration
- dismiss the auto-load toast when the chat context changes: switching thread or
  project keeps the pathname, and onComplete refuses to load into a new context

* Don't spend a notice, or a promise, that has already gone stale for PR #9660

- check the origin route before reserving, not only when the toast is raised: the
  preflight and apiStart are round trips long enough to navigate during, and a
  reservation is one of three for the life of the install
- let a caller's line declare when it is still true; chat ties its auto-load
  sentence to the context it was staged for, so a raise landing after a thread
  switch keeps the Xet explanation and drops the promise

* Tighten the comments on PR #9660 after convergence

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* fix chat search dialog stutter on open (#8514)

* fix chat search dialog stutter on open

The dialog is centred with `top-1/2 -translate-y-1/2`, so any height change
moves both edges. `CommandList` was sized with `max-h-[420px]`, which meant it
opened at the height of the "Loading…" row and grew to full height the moment
`buildIndex()` resolved, re-laying out and re-centring the surface in the middle
of the 100ms zoom. In the Tauri WebKit view that reads as a visible stutter; in
the browser it is mostly hidden by faster compositing.

Changes in `chat-search-dialog.tsx`:

- pin `CommandList` to `h-[420px] max-h-[60dvh]` whenever a chat exists, so
  loading, arriving results and filtering never resize the surface. The list
  only collapses in the genuinely empty "No chats yet." case.
- mount `INITIAL_ROW_COUNT` (24) rows first and the remainder at 220ms, after
  the open animation, so a 200 thread history does not lay out every row
  mid-transition.
- run filtering through `useDeferredValue`, keeping `selectVisibleChats` off the
  keystroke path. It scans `searchText` for every conversation, which includes
  tool call output.
- ease the open and close at 180ms with `cubic-bezier(0.16, 1, 0.3, 1)`.

`use-chat-search-index.ts` keeps the last built index in a module-level
`cachedIndex`, so reopening paints the previous rows immediately and revalidates
in place instead of falling back to the empty state. When the dialog is closed
the hook listens for `CHAT_HISTORY_UPDATED_EVENT` and drops the cache, so a chat
deleted while search is closed cannot reappear on the next open.

`index.css` adds `will-change: transform, opacity` to `.chat-search-surface`.
The surface carries a 70px blur shadow that WebKit otherwise repaints on every
frame of the zoom.

Verified in the Tauri dev build against the same chat history that reproduced the
stutter, and in the browser at localhost:5173. `tsc -b` clean, 1960 frontend
tests pass. No GPU checks apply.

* address codex review on chat search dialog

Four items from the round one review, all reproduced against head first.

`use-chat-search-index.ts`:

- `cachedIndex` is now assigned after the cancellation and sequence checks. A
  rebuild that resolved late could otherwise overwrite a newer snapshot, or
  repopulate the cache after the closed-dialog listener invalidated it, which put
  deleted chats back on the next open with the loading state suppressed.
- the closed-dialog invalidation returns early when nothing is cached.
  `CHAT_HISTORY_UPDATED_EVENT` fires per streaming chunk, so the previous version
  allocated a new array and re-rendered on each one throughout generation.

`chat-search-dialog.tsx`:

- the query and row-limit reset moved from close to open, in a layout effect.
  Radix keeps the surface mounted for the 180ms exit animation, so trimming back
  to 24 rows on close tore down the DOM mid-transition. Resetting before the
  reopened dialog paints keeps the exit untouched and avoids a flash of the
  previous query's results.
- `matchesChatQuery` gates activation. The list trails the input by a render
  while the deferred filter catches up, so Enter could open a chat that no longer
  matches what the input shows. Re-checking the row against the live query keeps
  clicks on visible rows working while dropping the stale activation.

`tsc -b` clean, 1960 frontend tests pass. UI behaviour verified in the Tauri dev
build: open, type, close, reopen, and delete-then-open.

* address codex round two on chat search dialog

`chat-search-dialog.tsx`:

- reserve the fixed list height from `ready` rather than `loading`. `run()` calls
  `setLoading(true)` from a passive effect, so on the first open of a session the
  opening render still saw `loading === false` with no items and picked the
  compact branch, then jumped to 420px during the animation. The hook now
  reports whether an index exists, which is known on the first render.
- reset the query and row cap during the opening render instead of in a layout
  effect. Radix mounts the portal as that render commits, so a layout effect
  trimmed rows only after React had already built the previous result set into
  the DOM.
- filter on `activeQuery`, which bypasses `useDeferredValue` for an empty query.
  The deferred value keeps returning the previous query during the urgent reset,
  so a reopened dialog could paint the old filtered subset next to an empty
  input.
- validate selection against `selectVisibleChats(items, query)` rather than a
  per-item match. The per-item check ignored the two-tier rule, where a global
  `userSearchText` hit suppresses `searchText` matches, so a row outside the live
  result set could still be activated. The scan runs on activation only.

`use-chat-search-index.ts`:

- `rebuildPending` tracks a history change whose debounced rebuild has not landed.
  Closing the dialog in that window cancelled the rebuild and left a snapshot
  already known to be out of date, which the next open then showed. The cleanup
  now drops the cache in that case.
- `ready` is exported alongside `items` and `loading`, cleared wherever the cache
  is invalidated.

`tsc -b` clean, 1960 frontend tests pass.

* keep the search rebuild flag set while a rebuild is queued

* control the chat search input so a fast reopen clears its text

* decide the chat search list height once per open

The empty-history first open reserved 420px while the index was still building, then collapsed to the compact branch as soon as the empty build resolved, so the centered dialog shrank mid-animation. The height now comes from what the cache already knows at the opening render and is held for that whole open.

Closing within 300ms of a history event also cleared the rendered items from the effect cleanup, tearing every row out of the list while Radix kept the surface mounted for its 180ms exit. That path and the closed-dialog listener now drop only the module cache; the reopening render discards the stale rows before they can paint.

* scope the chat search cache to the auth session

The index cache sits at module scope so it survives the sidebar unmount, and a web logout only runs navigate({ to: "/login" }) with no reload. A second account logging in on the same page therefore opened the search dialog onto the previous user's rows until the rebuild landed.

Reads and writes now go through readCachedIndex/writeCachedIndex, stamped with getAuthSessionEpoch(), the same session marker features/credentials/bootstrap.ts uses. A build that straddles a logout is discarded rather than stamped onto the new session.

* Keep the search dialog compact before the index is built for PR #8514

* Tell an unread chat history from an empty one when sizing the search dialog for PR #8514

* Distinguish an unknown history, invalidate across tabs and bound the cache for PR #8514

* studio: drop will-change from the chat search surface

The property was applied by a permanent class rule, so the dialog kept its
own compositing layer for its whole life rather than just the open zoom. In
WebView2 that disables subpixel text antialiasing, leaving the search rows
visibly soft on Windows.

Both Blink and WebKit already promote an element while a transform/opacity
animation is actually running, so the zoom keeps its layer without the hint.

* studio: finish the chat search cross-tab and hint edges

Four review findings on the search index cache.

The storage listener dropped the module cache but told no one, so a dialog
already open kept rendering rows built before another tab's change, with
nothing scheduled to replace them. It now re-raises the change as the same
same-document event a local change fires, which every in-tab listener
already handles. Tabs only learn of a change through localStorage, so the
re-raise cannot echo back.

That write sat on the streaming path, where the history event fires per
chunk, and a synchronous setItem there blocks the producing tab and wakes
every other one. It is coalesced to at most one write per quiet window.

Releasing uncached rows happened in the closing render, inside the portal
Radix keeps mounted for the exit animation, which is the teardown the rest
of this change avoids. It waits for the exit instead.

The persisted row hint outlives the page but was not cleared on logout, so
after a reload on the login screen the next account sized its first open
from the previous one's history. It now clears when the auth session does.

* studio: close the chat search cross-tab and lifetime gaps

Four more review findings on the search index cache.

An account switch performed in another tab reached this one as a token
write and nothing else: the session epoch lives in this document's memory
and its events are same-document, so the cached rows still matched their
epoch and the next open showed the previous account's titles while the
rebuild already used the new account's token. The storage listener now
treats a token write as an invalidation, and the shared row hint goes with
it. A routine refresh writes that key too and costs one rebuild, which is
the safe way to be wrong.

The revision write was throttled rather than coalesced, so a long
generation wrote once per debounce period instead of once when it went
quiet. The timer is rescheduled on each update, and a pagehide flush keeps
a delete that is followed by closing the tab from being lost with the page.

Releasing rows was one-shot: a history event arriving after it had already
run left the hook holding the conversation text until the dialog was
reopened. Invalidation reschedules it, which moves a timer rather than
rendering, so a stream still costs nothing until it stops.

* studio: separate the cross-tab channels for chat search

Three review findings.

An account switch made elsewhere reached this document as a token write, so
a build already in flight had been started for the account that just went
away. Its epoch check could not catch that, because the epoch is this
document's and this document never signed out: the result would have been
written back to the cache and the UI as the previous account's titles. The
storage listener now raises a distinct session event, and an open dialog
answers it by dropping its rows and rebuilding at once, which advances the
request sequence and retires the older build.

The cross-tab write shared one quiet window with the per-chunk streaming
path, so a delete during a long generation stayed unannounced until the
generation finished and other tabs went on offering the deleted chat as a
live row. Only the message-write path coalesces now; everything else
publishes immediately. That logic moves to its own module so it can be
tested, the same way the row hint was.

Releasing rows restarted its countdown on each invalidation, so a stream
with the dialog closed could hold an oversized index for the whole
generation. A pending release is left to run.

* studio: key the search cache off a session mark, not the token

Two review findings.

Keying the cross-tab account check off the token meant an hourly refresh
read as an account switch: refreshSession rewrites that key with the same
session in place, so every rotation would have thrown away another tab's
warm cache and emptied an open dialog for nothing. Sessions now leave a
mark in storage, written where storeAuthTokens already detects a session
starting and removed where clearAuthTokens ends one. It moves on a session
boundary and never on a rotation, which is the question the search cache
was really asking. Nothing reads the value; only that it changed.

Pruning is how a message is deleted, and syncChatMessages was coalescing
that alongside the streaming autosave it shares an endpoint with, so an
explicit deletion could wait out an unrelated generation before other tabs
heard about it. It takes the immediate channel when pruneMissing is set.

* studio: tighten the chat search comments

Comments only, no code touched. The explanations had grown longer than the
code they sat above, several of them restating the same constraint in two
or three places. Same points, shorter, across the 13 files this branch adds
or changes: 126 lines in, 172 out.

* studio: address the codex review on the chat search index

- a manual message edit publishes its revision at once instead of sharing the
  streaming autosave's coalescing window
- Archive All emits one cross-tab revision for the batch, not one per thread
- a session predating the session marker backfills it on its next token refresh,
  so a later sign-out is visible to the other tabs
- a failed rebuild drops the snapshot it was replacing rather than restoring it
- a persisted empty history answer ages out, since chats made elsewhere never
  reach this tab

* Announce a partially failed Archive All for PR #8514

* wait for every Archive All write before announcing a partial failure

* drop the unused AUTH_TOKEN_KEY re-export and correct the storage guard comments

* retire an in-flight search build when the history changes under it

* keep the search index building through a streaming response

* Fix chat search rebuild priority and failed-read hints

* Fix structural rebuild release and partial hints

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: LeoBorcherding <[email protected]>
Co-authored-by: Etherll <[email protected]>

* Studio: scale, crop and trim MiniMax-H3 reference media (#9631)

* Studio: scale, crop and trim MiniMax-H3 reference media

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

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

* Clamp a reference soundtrack to its video rather than refusing it

An untrimmed reference whose embedded audio ran past its video was refused with "The
reference soundtrack extends past the video". Before this branch the same file decoded
fine, since the only audio bound was the 15 second one, so the check turns media that
already worked into a 400.

The allowance is two codec frames, about 43ms at 48kHz for AAC, and ordinary encoder
padding clears that on its own. An A/B over synthetic pairs decoded on main and here has
a 5s video with a 6s track, and the same video with tracks 50ms, 100ms, 1s and 9s long,
accepted on main and refused on this branch.

The untrimmed path already sets end_sample to the video's own duration, so it was
clamping the track and then refusing it anyway. Dropping the raise leaves the clamp, and
the stop condition now covers the untrimmed case too, so the tail no engine receives is
no longer decoded either. Trimmed behaviour is untouched, including the 15s pair that
main refused over padding and this branch correctly accepts.

Also floor the ordinal fallback's start frame. The frame on screen at t is the last one
that started at or before it, so the start floors where the exclusive end ceils; ceiling
both skipped the frame straddling a fractional start and shifted the selection forward by
up to one frame against the timestamp path on identical media. Nothing reached that
fallback in the suite, so it also gains the two tests that would have caught this: one
driving it against a clip whose frames encode their own index, and one proving the
dispatcher reaches it at all when timestamps are stripped.

* Export a crop at the size the model will use

The crop editor rasterized at full source resolution, so a lossless PNG of the crop had to
fit the same 32 MiB field cap this module enforces. Driving the real module through
chromium, firefox and webkit shows it usually does not: the 5712x4284 photo from the issue
serializes to 36-42 MiB with photographic content, and an ordinary 12MP phone photo to
about 52 MiB. Every engine refused the issue's own example with "The cropped picture is too
large. Select a smaller area and try again.", and the advice does not help, because the
picture was already the whole selection.

Those pixels were never going to reach the model. fit_h3_reference_image bounds a reference
at a 2048px short edge under "max", and fits to the generation area under "match", which is
far smaller, so anything above that is encoded, base64'd and shipped only to be resized away
on arrival. Bounding the export at a 2048px short edge and a 4096px long edge takes the
issue's photo to 9.6 MiB and the phone photo to 23.8 MiB, both well inside the cap, and the
long edge is bounded as well so an extreme aspect cannot keep a huge dimension just because
its short edge already fits.

It also unblocks the main thread. The synchronous toDataURL held webkit for 6.1s on the
24MP photo and produced no decodable PNG at all for high-entropy content at that size;
after the bound the same case takes 1.3s and comes back intact. images-page.tsx already
carries this guard for outpaint, with the same reasoning.

The stored crop rect stays in original source pixels, so reopening the editor still
restores the selection against the full picture. A crop already inside the bounds is
untouched, so the existing raster test passes unchanged.

* Bound the wait for a reference video's duration

readVideoDuration waits for loadedmetadata or error and has no other way to finish. An
element that fires neither leaves the promise pending for good, and the picker slot behind
it, because the staged entry is only published from the .then.

The duration is what decides whether an overlong clip gets its automatic first fifteen
seconds, so losing it sends the whole clip and earns exactly the refusal this page set out
to avoid. A timeout resolves undefined instead, which the caller already handles as "no
automatic trim", and the element is told to load() after its src is cleared so it drops
what it was decoding.

An object URL was the obvious source to probe from, and it is measurably better on chromium,
4ms against 461ms. It is not portable: webkit reports no metadata for one at all and only
times out, while it reads the data URL in 2.5s. Keeping the data URL costs a parse and keeps
the duration on every engine, which is the side worth being on.

* Agree with the backend on which trim intervals are valid

referenceVideoTrimError compared durations exactly while validate_h3_reference_trim allows
1e-6 of slack, so the form refused intervals the server would have taken. The 0.1-step
inputs reach them easily: 2.3 - 0.3 is 1.9999999999999998 and 16.1 - 1.1 is
15.000000000000002, so 0.3 to 2.3 and 1.1 to 16.1 both read as out of range. Sharing the
tolerance settles it.

Also refuse a source shorter than the two second minimum up front. No interval inside a
1.5s clip can reach 2s, so the trim fields were a dead end on one, and the feedback line
called the trim optional while the decoder was always going to refuse the clip. Saying so
at the picker turns a late 400 into an answer the user can act on.

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

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

* Shorten the comments added by the review fixes

Comment and docstring wording only. Verified comment-only against the previous commit by
AST comparison of all seven touched files.

* Keep a trim whose embedded soundtrack runs out, padding the rest with silence

A trim the embedded audio does not fully cover was refused with "Reference video trim ends
after the source soundtrack", even though the video covered the range. A 10 second video
whose track ends at 6 seconds, trimmed 2 to 8, was rejected outright.

Embedded audio is optional here: a video carrying no track at all is accepted, and the
untrimmed path clamps a mismatched track rather than refusing it, so treating the track
length as the source boundary only for a trim was inconsistent. The output buffer is
already zero-filled, so the interval past the track is silence with nothing further to do,
and a trim starting entirely after the track still returns no soundtrack as before.

Same change in the sample-counting fallback, which had the identical check.

* Shorten the comment on the short-soundtrack path

Comment text only; AST-verified as comment-only against the previous commit.

* Let a trim reach a little past the video track before refusing it

A container reports the duration of its longest track, so a file whose audio outruns its
video reads as longer than it can show. Studio takes its automatic interval from exactly
that number, HTMLMediaElement.duration, so a 14.9 second video carrying a 15.2 second
soundtrack reads as 15.2, auto-trims to 0 to 15, and is then refused with "Reference video
trim ends after the source video" even though the same file decodes fine untrimmed.

Measured on that fixture: the video track covers 14.917s in 358 frames while the container
declares 15.2s, and chromium, firefox and webkit all report 15.2.

A trim may now fall up to half a second short of the video track, holding the last frame
across the gap, which is what both trim decoders already do at their own endpoint. Past
that the range really was not there and the error stands, so a 2 to 10 second trim of a 6
second clip still fails.

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

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

* Shorten the trim coverage slack comment

Comment text only; AST-verified as comment-only against the previous commit.

* Drop the soundtrack when none of it falls inside the trim for PR #9631

An embedded track starting after the selected interval was decoded, advanced the
timeline past the interval and copied no samples, so the guard that returns None
did not fire and a target-length silent waveform was returned instead. The model
then received a fabricated soundtrack, and the positional pairing in
stage_h3_references treated the reference as having audio, so the gap it exists to
catch went unreported. A track ending before the interval already returned None;
this makes the two agree by keying on whether any sample was copied.

* Shorten the comments added by the soundtrack-gap fix

Comment and docstring text only; AST-verified as comment-only against 11f80b4f4.

* Start a replacement soundtrack at its own zero for PR #9631

A separate uploaded soundtrack was decoded with the video's absolute trim
coordinates, so an 8s replacement for a clip trimmed 5s to 13s kept only its
seconds 5 to 7 and ran silent for the rest, and a replacement shorter than the
trim start was refused outright with "That reference audio decoded to no
samples". The file is independent, the picker offers no way to offset it, and
the standalone reference audios already decode from their own zero, so it now
plays the clip from its own start, bounded to the clip length. Embedded audio
still uses the video's timeline.

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

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

* Shorten the comments added by the replacement-soundtrack fix

Comment and docstring text only; AST-verified as comment-only against 63def5d74.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* fix(amd): report AMD VRAM on Windows by joining the adapter counters on LUID (#8863)

* Join the Windows GPU adapter counters to torch devices on the adapter 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.

* Decline the DirectX adapter map when a record will not read

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.

* Bound the LUID join by the carve-out, not the displayed total (#8863)

Forward guard for the interaction with #9314, which widens total_bytes to the
whole driver pool on a unified APU. _attribute_adapter_useds_by_key reads
total_bytes as the capacity a Dedicated Usage counter can fill, both to rank
positions and to reject a usage no card could hold. That counter measures the
dedicated segment, so its ceiling is the carve-out and never the pool: against a
128 GB ceiling a 9 GB counter belonging to no visible card passes the check and
gets published on a card that never held it.

Neither PR does this alone. #8863 has no widened total and #9314 has no LUID
join, so it only appears once both are in, whichever order they land.

_adapter_counter_capacity() prefers dedicated_bytes and falls back to
total_bytes, so this is correct on this branch, where dedicated_bytes does not
exist yet and the fallback makes it a no-op, and correct the moment #9314
rebases on top. The capacity-ranking fallback path takes it too, so both
consumers of a counter agree on what bounds it.

Two tests: the helper's preference either way round, and the join declining an
impossible counter against a widened total while still attributing one that
fits.

150 pass in the ROCm/VRAM files, 1768 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

* Do not stop the LUID join at a pass that answered nothing (#8863)

Two defects in _match_adapter_used_by_luid, both found by review.

A pass can succeed while naming no device: several cards under one key leave
per-device unknown and contribute only to the aggregate. Returning on the first
non-None result therefore ends the search on a vacuous success, and two cards
sharing a Description but differing in gcnArchName stay unknown even though the
gfx pass would separate them. The docstring already promised that a declined
name join falls through to gfx; it now covers a vacuous one too. The first such
result is kept for its aggregate and returned only if no later pass attributes.

And a key that leaves AMD usage unplaced is not identifying reliably. A visible
card whose Description differs from its props.name puts its own counter under a
key no device claims, while a hidden card wearing the device's name sits under
the one that is claimed, and the pairing hands the hidden card's bytes to the
visible device. Measured on the added case: 17 GiB belonging to a masked card
reported as the visible card's. The pass now declines, which costs a masked
second AMD card its join and falls back to capacity ranking, where that case
already was.

Both tests fail on the parent: [None, None] instead of [9.0, 3.0], and 17.0
instead of None.

1810 pass 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

* Tighten the comments this PR adds

Comment-only pass at convergence. Three blocks trimmed wi…
LeoBorcherding added a commit to LeoBorcherding/unsloth that referenced this pull request Aug 28, 2026
_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.
danielhanchen pushed a commit to LeoBorcherding/unsloth that referenced this pull request Sep 2, 2026
…ization

The GPU Engine instances are named after the adapter, exactly like the memory
ones -- pid_<pid>_luid_0x<high>_0x<low>_phys_<n>_eng_<n>_engtype_3D -- and the
3D utilization summed every one of them. That is the whole host's 3D load
reported as this card's: on a laptop the display iGPU's work, and on the
reporting host the Basic Render Driver's instances were being summed in.

Narrowed to the card's own LUID. Which LUID is safe to filter on is not
obvious: a linked-node adapter puts several ordinals behind one, and the node
mask alone cannot settle it, since one bit set reads the same whether the
ordinal owns the only node or one of two. What settles it is the node count
the VRAM join already checks, the number of counter instances that LUID has.
So the join hands the LUID back only for a device it established is the whole
of what that LUID names, and the engine query filters on that. Where it did
not establish that, the LUID is absent and the sum stays the host's, which is
what it has always been.

That also drops a second identity probe per poll: the utilization path was
asking HIP again for something the VRAM path had just resolved. The key is
internal, and neither endpoint spreads these dicts into its payload.

Stacks on the HIP probe, which is what supplies the LUID. Split out of unslothai#8863
at review request.
danielhanchen pushed a commit that referenced this pull request Sep 3, 2026
…ization (#9317)

* Join the Windows GPU adapter counters to torch devices on the adapter 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.

* Decline the DirectX adapter map when a record will not read

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.

* Studio: ask HIP for the adapter LUID before inferring it from the DirectX record

Stacks on #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 #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 #8863 at review request.

* Bound the HIP-joined counter by the carve-out, not the displayed total

_adapter_counter_capacity arrived with #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.

* Studio: count only this adapter's engines in the Windows AMD GPU utilization

The GPU Engine instances are named after the adapter, exactly like the memory
ones -- pid_<pid>_luid_0x<high>_0x<low>_phys_<n>_eng_<n>_engtype_3D -- and the
3D utilization summed every one of them. That is the whole host's 3D load
reported as this card's: on a laptop the display iGPU's work, and on the
reporting host the Basic Render Driver's instances were being summed in.

Narrowed to the card's own LUID. Which LUID is safe to filter on is not
obvious: a linked-node adapter puts several ordinals behind one, and the node
mask alone cannot settle it, since one bit set reads the same whether the
ordinal owns the only node or one of two. What settles it is the node count
the VRAM join already checks, the number of counter instances that LUID has.
So the join hands the LUID back only for a device it established is the whole
of what that LUID names, and the engine query filters on that. Where it did
not establish that, the LUID is absent and the sum stays the host's, which is
what it has always been.

That also drops a second identity probe per poll: the utilization path was
asking HIP again for something the VRAM path had just resolved. The key is
internal, and neither endpoint spreads these dicts into its payload.

Stacks on the HIP probe, which is what supplies the LUID. Split out of #8863
at review request.

* Filter the engine samples here rather than in the counter path

The narrowing is right and the reading it corrects is real: simulated against
the shape off the reporting host, this card at 17% beside an iGPU and the Basic
Render Driver at 61% between them, the poll reported 78 before and 17 after.

Where it was done is the problem. Putting the LUID in the counter path hands the
selection to PDH, and no test in this repo can run PDH, so the three tests here
were asserting the shape of a string while a mock decided the number. Both of
these mutants left them green: dropping engtype_3D from the pattern, so Copy and
VideoDecode instances sum in, and unioning *engtype_3D* back in beside the LUID,
which is the whole-host sum this branch exists to stop reporting.

It also left the value unguarded. Utilization Percentage is a cooked counter over
an instance list that is created and destroyed as work starts, and the previous
form took whatever the pre-summed expression printed: a non-finite sample reached
the payload as inf, which json.dumps rejects and no browser will parse, and a
value above the PowerShell clamp passed straight through at 250.

So the path goes back to a bare wildcard and the rows are filtered here, which is
what _rocm_windows_perf_counter_vram_by_adapter -- the counter that resolves the
LUID being matched -- already does. The sum, the clamp and the sanity checks are
in Python now, where the tests reach them, and the three tests assert numbers.

Ten cases added, all of them things the old shape could not ask: a longer LUID
that starts the same, engtype_3d in lower case (hosts emit both spellings and the
old pattern relied on PDH folding it), compute engines only, an idle engine
reading 0 rather than unknown, NaN and infinite and negative and unparseable
samples, the clamp, an instance name with no LUID in it, no instances at all, a
high LUID half, and the internal luid key staying out of both payloads with a
negative control so a declined join cannot pass it. 53 in the file.

Also .get("luid") at the call site instead of ["luid"]: two suites already stub
_rocm_windows_per_device_vram with records that have no such key, and they reach
this line the moment one of them is used with get_gpu_utilization.

Simulated across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only] with the
vendor SMI answering and unavailable, on 3.11 and 3.13: 42 of 58 host shapes
produce byte-identical payloads, and every one that moves is Windows ROCm with
the join having proved ownership.

* Trim the comments on the engine utilization filtering

* Take node identity, not node count, as whole-adapter ownership

Equal counts say how many nodes an ordinal owns, never which. One ordinal
holding node 0 of a linked adapter, whose own counter instance is missing while
the node it does not own still reports, gives one counter against one owned node
and passes:

    only the HIDDEN node emits -> ([5368709120.0], 5368709120.0, [86889])

The third element is the LUID being handed back as whole-adapter, so the engine
query then sums the other node's 3D work as this card's, on top of the hidden
node's bytes landing in used_gb.

luidDeviceNodeMask names the nodes rather than counting them (bit i is node i,
so a plain adapter reads 1 and not 0), so where the mask is present the observed
phys_N set has to be exactly those nodes. A zero mask names nothing and keeps
the count check alone, which is the pre-existing behaviour for adapters that are
not linked.

The check only ever withdraws an ownership claim, never grants one, so a host
where phys_N and the mask index differently loses the narrowing and falls back
to the unfiltered sum rather than attributing wrongly.

Reported by Codex. The used_gb half of the same shape belongs to the HIP join
underneath this branch and is left alone here.

* Keep the engine type in the counter path, match the adapter here

GPU Engine is instanced per process AND per engine, so a bare wildcard asks
PowerShell to format every engine type of every GPU-using process into text that
the loop here then discards down to 3D. On a busy host that is the bulk of the
sample set, inside a 5 second timeout on the monitor poll, and a timeout reads as
no utilization rather than as an error.

The engine type is not what this branch narrows. It was in the path before it and
belongs there: one segment, no interior wildcard, and it is the restriction that
keeps the set small. Only the adapter LUID moved into Python, which is the part
the tests need to reach.

The Python engtype check stays as well, since it costs nothing and covers the
engtype_3d spelling directly rather than relying on PDH folding the case.

Reported by Codex.

* Unpack the carve-out join test three-wide

_match_adapter_used_by_hip_luid returns the whole-adapter LUID as a third value,
so the carve-out bound test on this base cannot unpack it two-wide any more:

    ValueError: too many values to unpack (expected 2)

Only reachable once this branch sits on a base that has that test, which is why
it did not show up while the branch was behind.

* Tighten the comments on the engine LUID filter

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit that referenced this pull request Sep 8, 2026
* Publish only the wheel to PyPI, not the sdist (#10202)

Co-authored-by: danielhanchen <[email protected]>

* Bump install.sh / install.ps1 pin to unsloth>=2026.9.2 (#10203)

Co-authored-by: danielhanchen <[email protected]>

* Add DeepSeek Harness to unsloth start (#10097)

* Add DeepSeek Harness (dsh) to unsloth start

Claude-Session: https://claude.ai/code/session_01NMn7rbPGP6zaxhFu6tcaFg

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

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

* Pin dsh permission mode and forward --reasoning-effort

* Apply repo kwarg-spacing format to the new dsh tests

* fix: reject unrelated dsh executables

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

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

* fix: resolve the intended DeepSeek Harness binary

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: imagineer99 <[email protected]>

* Studio: stop generating when the client goes away (#10096)

* Stop non-streaming Anthropic generation when the client disconnects

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

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

* Studio: record an abandoned non-streaming run as cancelled

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: keep an instruction typed with an attachment through a compaction (#10165)

* Order the Ollama stop-token scan instead of leaving it to a set (#10101)


---------

Co-authored-by: oobabooga <[email protected]>

* Studio: replay a web_search result the way the client sent it (#10131)


---------

Co-authored-by: oobabooga <[email protected]>

* Studio: report context overflow the way Anthropic does, so Claude Code can compact (#10090)

* Restore the comment tails the trim cut off (#10205)

* Restore the comment tails the trim cut off

The comment passes in #10112, #10115, #10116 and #10118 enforced the 120-column
limit by chopping the physical line rather than rewrapping it, so a block's last
sentence stops mid-thought and the clause carrying the reason goes with it. 63
blocks across 38 files, restored from the pre-merge text and rewrapped at word
boundaries.

The ones that matter most are load-bearing:

    -# The FLAVOR, never the index URL it came from
    +# The FLAVOR, never the index URL it came from: a pinned index can carry a token in its userinfo, query or
    +# fragment, and the manifest is world readable.

    -# Do not guess the cause: the preflight line the app already printed says
    +# Do not guess the cause: the preflight line the app already printed says which of the two it is, and naming the
    +# wrong one sends the reader to the wrong fix.

Only blocks where the pre-merge text continues the same sentence where the
current text stops are touched: a dangling function word, an unbalanced bracket
or code span, a trailing abbreviation, or a lowercase continuation. A block that
ends on punctuation before a new sentence was shortened on purpose and is left
alone. No word is invented; every restored word comes from the pre-merge text.
Pragmas, shebangs, coding lines, licence headers and rule-line banners are
skipped, and the change is scoped to the 569 files those four PRs touched.

comment_tools.py check is 38/38 comment-only. Full suite is 65 failed / 18693
passed, matching main exactly.

* Revert the geglu restoration, that block was never truncated

* Restore five comments the trim overwrote with another comment's text

* Studio: accept subtitle, caption and the rest of the common attachment formats (#9738)

* Studio: accept subtitle, caption and the rest of the common attachment formats

.srt and .vtt are plain UTF-8 but were on no allowlist, so the picker greyed
them out and a native drop was refused outright. Same story for a long tail of
ordinary text formats, and for audio and video containers the backend already
decodes.

Text: 80 extensions to 285. Subtitles (.srt .vtt .sbv .ass .ssa .sub .lrc),
docs (.tex .bib .adoc .org .rmd .qmd), data (.jsonc .json5 .geojson .har .plist
.avsc), localisation (.po .strings .resx .xliff .ics .vcf .eml), templates
(.erb .ejs .hbs .jinja .twig .liquid .razor .pug) and ~120 more languages
(.hs .ml .ex .erl .fs .clj .zig .nim .cr .cu .cuh .sol .cairo .mojo .f90 .cob
.ada), shaders, shells and build files.

Audio: .opus .aac .aiff .aif .aifc .caf .wma .amr .mp2. Every one of these
already decodes through libsndfile or librosa in _decode_audio_mono, so the
picker was stricter than the pipeline. .webm and .mp4 stay off the extension
list: the audio adapter runs before the video one and would claim video files.

Video: .m4v .mpg .mpeg .wmv .flv .3gp .ogv, all of which ffmpeg reads. .ts and
.mts stay off because they are TypeScript here.

Also mirrors the lists into native_path_policy.rs and the MIME tables in
native_intents.rs, and replaces native_clipboard.rs's hand-copied 70-extension
duplicate with a TEXT_ATTACHMENT_EXTS lookup so it cannot drift again.
Syntax highlighting gains 167 shiki mappings for the new formats.

Images stay at jpeg/png/webp/gif on purpose: files go to the model as raw
base64, and the external providers accept only those four.

* Fix attachment type detection edge cases

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

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

* Fix remaining attachment review issues

* Fix attachment review edge cases

* Fix remaining attachment review findings

* Fix latest attachment review findings

* Fix attachment format parity edge cases

* Handle legacy attachment format edge cases

* Bound the audio-input decode and handle two more legacy attachment cases

Three findings from the latest review round.

The non-GGUF audio-input path decoded with torchaudio and never applied the
decoded-duration cap, unlike the GGUF path. A low-bitrate AMR or WMA under the
25 MB upload limit can hold hours of PCM, so the decode now checks the reported
length, reads at most one frame past the cap when the container hides its
length, and returns 413 rather than a server error.

A subtitle saved in a legacy code page decoded as lenient UTF-8, replacing
every non-ASCII byte. Text attachments now decode UTF-8 strictly and fall back
to windows-1252, which maps every byte, so the text arrives readable. A
streaming decode keeps a bounded preview that cuts a character in half on
UTF-8 rather than treating the cut as a legacy encoding.

Compiled gfortran .mod modules are gzip, which the tracker-module check does
not see, so they were decoded as text. Browser, native drop and native
clipboard intake now reject them; text .mod files including go.mod and
uncompressed gfortran modules stay accepted.

The fourth finding, that the generic text MIME fallback in native_intents.rs
and native_clipboard.rs stamps every text extension text/plain, is not
reproducible. is_text_attachment_name matches the whole filename against
TEXT_ATTACHMENT_NAMES, which holds only "containerfile", so the early return
cannot fire for .json, .csv, .plist or .vtt. The Rust tests said to be failing
pass: 429 of 429, including clipboard_file_mime_types_cover_text_attachments,
which asserts data.json stays application/json.

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

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

* Name an undecodable encoding instead of guessing it, and reject OLE templates

Two findings from the latest review round.

The windows-1252 fallback added in the previous commit was wrong for anything
outside Western Europe: the same byte is a different letter in windows-1252,
windows-1251 and Shift-JIS, so a Russian or Japanese subtitle decoded cleanly
into confident mojibake. Which one it is cannot be known from the bytes, and
mojibake is worse than a refusal here because nothing downstream can tell it is
wrong. Text attachments now fail with UndecodableTextError naming the file and
asking for UTF-8. The composer decodes while attaching so the message arrives
with the file rather than at send, and the preview already renders a failed
read as an error state.

This also covers the earlier lenient-UTF-8 behaviour, which replaced every
non-ASCII byte and attached the file as though it had been read.

Legacy Word .dot and PowerPoint .pot templates are OLE compound files sharing
their extensions with Graphviz and gettext, so they were decoded as text.
Browser, native drop and native clipboard intake now reject the OLE signature;
Graphviz .dot and gettext .pot stay accepted.

* Bound text attachments, and honour the charset an email declares

Two findings from the latest review round, both on the previous commit.

Reading while attaching made the missing size bound reachable much earlier: a
multi-gigabyte .mbox held its bytes and its decoded string at once, in the
webview, before the user could send anything. The adapter now stops at 20 MB
before any read, matching MAX_NATIVE_TEXT_BYTES so the browser and desktop
paths accept the same sizes. A test reads the Rust constant and asserts the two
agree.

Refusing every non-UTF-8 file was too broad for email. An 8-bit .eml or .mbox
declares its charset in the Content-Type header, so that is knowable rather
than guessed, and is now honoured, including across folded header lines. It is
tried only after UTF-8 fails, so a modern message is never remapped by a stale
declaration, and a message declaring nothing is still reported rather than
guessed at.

Writing those tests turned up a hole in the previous commit: decoding always
passed stream:true, so a file whose last byte was a dangling UTF-8 lead byte
had that byte dropped silently instead of reported. Tolerating a cut tail is
only correct when the input really was cut, which only the caller knows, so
that is now a parameter the bounded preview sets and a whole-file read does
not.

* Read a text attachment once instead of once per stage

Decoding while attaching, added in the previous commit to report a bad encoding
early, left the file being read twice: add() decoded all of it, discarded the
result, and send() decoded it again. At the 20 MB cap that is two full reads and
two decoded strings per attachment.

Both stages now go through readTextAttachmentOnce, which caches the decoded text
in a WeakMap keyed by the File, so a removed attachment retains nothing. A
regression counts arrayBuffer calls across the two stages.

* Accept a dropped Dockerfile and Makefile, as the picker already does

assistant-ui derives a file's extension as `.${name.split(".").pop()}`, so an
extensionless Dockerfile reads as ".dockerfile" and the picker claims it through
the token already in the accept list. The drop classifier and the mirrored Rust
policy recognised only Containerfile, so the same file dropped from the desktop
shell was refused.

Both lists now carry every conventional extensionless name whose token is
present. A name with no such token, GNUmakefile for instance, stays out of both
rather than being widened. The regression derives the expectation from the
matcher's own rule instead of restating the list.

* Bound the probe-failure decode, and read declared charsets per container

Four findings from the latest review round.

A container torchaudio.info cannot read was still loaded whole to find out how
long it was, which is what the duration cap exists to prevent. That case now
goes to the bounded decoder the GGUF path uses, which stops at the cap as
frames arrive. torchaudio.load is never called without a frame bound.

Reading only the first Content-Type meant a multipart message with the charset
on its parts was refused, while an mbox holding messages in different charsets
was decoded end to end with the first one and silently corrupted. The scan now
collects every declaration: one distinct charset decodes the file, several
refuse it by name rather than corrupting all but one part.

A vCard 2.1 declares its encoding on the property, so .vcf files now use the
same scan instead of being refused for carrying bytes they describe.

Compare mode classified audio only by file.type, which browsers leave empty for
several of the containers this branch added, so a dropped .wma or .amr was
ignored and the picker hid it. It now shares the chat composer's accept list
and its name fallback.

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

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

* Scan the whole file for charset declarations, not the first pages

The declaration scan stopped at 64 KiB, so an mbox whose later message declared
a different charset was decoded end to end as the first one. Reproduced with an
ISO-8859-1 message followed past the cutoff by a windows-1251 one: the Cyrillic
came out as Latin mojibake, which is the failure the unanimity rule was added to
prevent, just moved behind a byte offset.

Any cutoff has that failure, so there is no longer one. The attachment is
already capped at 20 MB and the scan only runs once UTF-8 has failed, which at
that size costs 46 ms; a valid UTF-8 file never reaches it.

* Bound decoded audio by samples, and honour two more declared encodings

Five findings from the latest review round.

The decoders capped audio by duration alone, which is rate-relative: 30 minutes
at 48 kHz retains 86M float32 samples where the same speech at 16 kHz retains
29M, and np.concatenate doubles whichever it is. An absolute ceiling now sits
beside the clock, set at 48 kHz for the full 30 minutes so it never bites before
the advertised limit at any ordinary rate.

The librosa fallback ran the whole file through audioread and checked the length
afterwards, which is too late to matter. It now asks for the native rate and
reads a window bounded by both the clock and that ceiling.

The email scan matched any line starting with Content-Type, so quoted mail or a
config snippet in a body counted as a second declaration and refused a file that
says one thing. It now reads only header blocks: from the start, an mbox
separator, or a MIME boundary, to the first blank line. Real part headers still
count, so genuinely mixed containers are still refused.

An XML document states its encoding in the prolog. That is read from the bytes
rather than the extension, so .resx, .xliff, .xlf, .svg and the project files
are all covered rather than refused for carrying what they describe.

Pasting a video used the 20 MB source cap while the picker and the drop path
took up to 72 MB, so most clips reported no readable clipboard files. Video now
has its own budget, mirrored from the drop path with a test that reads it.

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

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

* Apply the sample ceiling to torchaudio, and decode declarations strictly

Three findings from the latest review round.

A successful torchaudio.info bypassed _decode_audio_mono, so the decoded-sample
ceiling never ran on that path and load() still bounded only by the clock, at
every channel and the native rate. load() is now used only when info reports a
length that fits the ceiling; anything wider goes to the bounded reader, which
downmixes as it reads. A file inside the 30-minute limit is streamed rather than
refused, so the advertised limit still means what it says.

The declared-charset paths decoded leniently, so a .po or an XML prolog claiming
UTF-8 while holding broken bytes came through as replacement characters. That is
the corruption the strict default exists to prevent, reached through the branch
that trusts the file. Declarations are now decoded strictly and refused by name
when the bytes do not match, with the same allowance for a preview that cut a
character in half. Single-byte charsets map every byte and are unaffected.

Pasting a 3GP still used the audio-sized provisional limit while other videos
moved to the video budget last commit, so a 3GP video above 25 MB was skipped
before its tracks could be read. It is read under the video bound like the drop
path, and the audio cap is reapplied afterwards if the tracks say audio-only.

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

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

* Fix a quadratic header scan, and decode every declaration strictly

Six findings from the latest review round.

The header-block scan restarted its search from every candidate boundary, so a
body of diff hunks, where every line begins with dashes, was quadratic: a
megabyte took 14 seconds, on the UI thread inside add(). One forward pass over
the lines, slicing only the header regions, takes 8 ms for the same input.

An XML prolog is the document's encoding by specification, but it was only
consulted after UTF-8 failed, so bytes that happen to be valid UTF-8 decoded
into different characters than the document states it holds. The prolog now
decides first. Mail and vCard declarations stay a fallback, since mislabelled
8-bit mail is common and its bytes being valid UTF-8 is the better evidence.

The UTF-16 BOM branch decoded leniently and ignored the truncation flag, so an
odd trailing byte or an unpaired surrogate was padded with a replacement
character and attached as though it had been read. It goes through the same
strict decoder as everything else now.

Without a sample rate there is no window that bounds the librosa fallback: 30
minutes is gigabytes at a high rate. An unprobeable rate is refused rather than
read to find out, which costs nothing a container that soundfile and PyAV both
declined would otherwise get.

An overlong upload on the GGUF path reported 400 "Could not decode" while the
non-GGUF path reported 413 with the limit, so a long but valid file was
indistinguishable from corrupt audio.

The sample-ceiling regression allocated the production constant, 346 MB per
run. It uses a small monkeypatched ceiling, since the check is what is
under test.

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

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

* Read a 3GP's tracks, and only trust a declaration where one can be made

Cap a torchaudio read by the sample ceiling as well as the clock. num_frames
is the value being distrusted there, so a container that understates it was
still allowed to read rate * 30 minutes: 345M frames per channel at 192 kHz.

Classify an audio-only 3GP from its BMFF handlers before an adapter is picked.
A composite matches on name and MIME, both of which say video, so a voice
recording was refused on an audio model and sent as frames on a video one. The
native readers already inspect the tracks; the browser and compare now do too.

Reopen mail headers only at a boundary a header declared. Any line starting
with "--" reopened them, so a signature marker or a closing delimiter turned
the body back into headers and a quoted Content-Type became a second charset.

Read a vCard charset only from a property's parameters. The whole-file scan
matched inside values, so an escaped ";CHARSET=" in a NOTE counted as a second
declaration and refused a card that names exactly one.

Make PyAV optional in the audio container tests, as the other suites do.

* Read a 3GP's track table without holding the container

Walk the top-level boxes through slices and read only moov. The handlers are
there and the samples are in mdat beside it, so reading the file to reach one
retained the whole clip: 64 MB for a single drop, and a batch of ten at once
through Promise.all. A 2 MB container now costs under 4 KB of reads, and a
batch is inspected one file at a time.

Treat a "From " line as a separator only in an mbox. An archive escapes the
one a body starts with; a standalone .eml has no separator at all, so an
ordinary sentence opening that way reopened the headers and a quoted
Content-Type below it became a second charset.

Offer .3gp in the compare audio dialog. A platform that maps the extension to
video/3gpp, or to nothing, greys out a voice recording the surface would take,
and the track inspection cannot run on a file that was never selectable. The
dialog hint and the routing accept are separate constants now: the audio
adapter is matched before the video one, so claiming the name for routing
would take every 3GP video as audio.

* Decide a vCard's encoding from its own parameters, before UTF-8

A card declaring CHARSET=windows-1252 whose bytes happen to be valid UTF-8
decoded as UTF-8, delivering characters it never named. A property parameter
is written by the exporter, like an XML prolog and a gettext header, so it
decides first now. Only when the card names exactly one: several stays the
ambiguous case and keeps its existing path. A mail Content-Type remains the
one fallback, because clients mislabel 8-bit mail constantly.

Clear MIME boundaries at an mbox separator. A boundary belongs to the message
that named it, and carrying one forward let a later body line repeating it
reopen the headers there.

Read a gettext header past the 64 KiB prefix. A catalog with more comments
than that above its header entry was refused for carrying exactly the bytes
the header describes. The prefix still settles the common case; only a miss
reads the rest, which the attachment cap already bounds.

Give the video reference picker the same accept and classification as its own
drop path. This PR widened the drop list to wma, amr, caf and the rest, but
the button still asked for audio/* and the check still demanded a MIME, so a
browser reporting "" hid those files and then refused them.

* Read every vCard property under its own charset, and bound a decode block

CHARSET is a property parameter, so a 2.1 card may put windows-1252 on FN and
windows-1251 on NOTE. Refusing that as an ambiguous container was wrong: the
card says plainly what each value holds. Names and parameters are ASCII by the
grammar, so only the value after the delimiter takes the property's charset,
and a folded line continues the one above. The reading is all-or-nothing: a
property whose bytes break its own declaration, or that names a charset the
platform lacks, falls back to the refusal rather than emitting a guess. A MIME
container still needs a parser this is not, so mail is unchanged.

Size a libsndfile block by channels as well as frames. blocks() allocates
frames * channels and yields a copy, so a frame budget chosen for mono let a
255-channel container reach 49 MB twice over from an upload capped at 25. The
samples kept are mono, since each block is downmixed as it arrives, so this
bounds the transient only. Nothing common moves: the divisor first bites past
about 20 channels at 48 kHz.

* Let each declaration speak for what it actually covers

A vCard CHARSET covers its own property whatever the count, so one declaration
does not settle the file. An export holding a 2.1 card beside a 3.0 one, which
cannot declare anything, read the whole bundle in the 2.1 card's charset and
turned the other into mojibake. Every card with a declaration takes the
per-property read now, and falls back to the old whole-file one when it cannot
account for a value.

Unfold a header block before pulling its boundary out. A wrapped
"multipart/mixed;\r\n boundary=..." was never matched, so no part header was
scanned and the charset those parts declare went unread.

Drop a boundary at its closing delimiter. "--inner--" ends that multipart for
good, and keeping the token let a later sibling repeating the line reopen the
headers.

Compare declarations by encoding rather than spelling. windows-1252, CP1252
and latin1 are three names for one decoder, so an archive using two of them
was refused as multi-charset when a single decoder reads all of it.

Read an XML declaration to its own ">". The grammar puts no bound on the
whitespace between the parts, so the 256-byte prefix could cut `encoding` off.
Five bytes still settle whether there is a declaration at all.

Read a 3GP's tracks in the reference picker too. The audio dialog offers .3gp
now, the picker classifies before the kind check as chat and compare do, and a
file already stamped audio is no longer claimed by the video extension list.

* Match a charset parameter by its name, not by where it appears

An unanchored search took the first "charset=" anywhere in a Content-Type, so
`text/plain; name="charset=windows-1251.txt"; charset=windows-1252` read the
filename: an unsupported label that refused a valid message, or a supported
one that quietly picked the wrong decoder. The value's parameters are split
outside quotes now and only a parameter actually named charset counts.

Read a truncated vCard per property as well. The preview pane decodes a
prefix, and applying the sole declaration to all of it showed Café for text
the sent attachment renders as Café. Only a prefix's last line can end
mid-character, so that one line is read leniently and the rest stay strict.

Drop the size condition on 3GP track inspection. It sat at the composer's
video cap while the video reference surface accepts a larger file, so a
recording in between skipped inspection and was staged as a video reference on
its extension alone. A ceiling that has to track every surface's limit is one
that will fall behind another, and the box walk is already bounded by box
count and by the size of the track table rather than by the file.

* Hold a forwarded container to the duration limit its headers declare

wav and mp3 are passed to llama-server untouched, and that return sits ahead
of every bounded decoder, so neither the duration cap nor the sample ceiling
ever ran on them. A 16 kbps mp3 holds hours inside the 25 MB upload cap. Both
are now measured from their own headers: a RIFF byte rate against the PCM
actually carried, and a walk of the MPEG frame headers that stops as soon as
the running total passes the cap. A container whose headers cannot say is
still forwarded, so this refuses what it can prove and invents nothing.

Take boundaries only from a multipart Content-Type, parsed as parameters. A
quoted `filename="report; boundary=fake"` on any header at all registered a
delimiter, and a body line repeating it reopened the headers.

Look for a declaration in the whole file when previewing a prefix. A gettext
header below a megabyte of translator comments sat outside the preview slice,
so the preview reported an error for a file the attachment decodes.

Inspect a 3GP whatever MIME the browser gave it, and correct the type in both
directions. The type comes from the same ambiguous extension, so a platform
reporting audio/3gpp reports it for a clip too, and the audio adapter is
matched before the video one.

Give the reference drop zone the accept its own dialog uses. The zone filters
on the name before the classifier can see the file, so the narrower chat list
refused a recording the button takes.

* Answer an overlong upload the same way whether or not a swap is running

The pre-switch preflight caught every exception and reported "could not be
decoded" with a 400, so the same valid file read as a 413 with an actionable
limit when the model was already loaded and as a decode failure when a model
switch happened to be in flight. Both preflight paths now let the duration
error through, and one helper owns the message so the three sites cannot drift.

Resolve escapes when unquoting a header parameter. The splitter already
honoured them, so a value carrying an escaped quote stopped at that quote and
kept its backslashes: the boundary never matched its own delimiter line, and
the part headers below it went unread.

Take a pasted video up to the limit the native reader uses. Rust reads a clip
to 75,497,280 bytes while the frontend held every non-audio file to 20 MB with
a 25 MB total, so a larger clip was read and encoded natively and then thrown
away, taking the rest of the paste with it.

* Transcode audio without holding three copies of it, and honour every vCard charset declaration

A 17.5 MB six-minute FLAC, well inside the upload cap, drove 573 MB of
transient through the llama audio path. The resampler built two float64
grids the length of the recording, the WAV encoder allocated the whole
array again for each of flatten, the nan scrub, abs, normalise and scale,
and the block reader held every block and then joined them into a second
full array. Same bytes out, 188 MB in.

A vCard that declared a charset with no decoder here was refused when it
declared nothing else and accepted, escapes left literal, when another
property declared a second one: the fallback read the card as UTF-8 and
its other bytes happened to be ASCII. A declaration the per-property read
cannot honour is now reported.

* Read an XML declaration and a gettext header for what they are

A processing instruction opens with the same five bytes as a declaration:
`<?xml-stylesheet ... encoding="windows-1252"?>` on a UTF-8 document was
taken for the prolog and the file came back as mojibake, with nothing
raised. XML's grammar puts whitespace after the target, which is exactly
what separates the two, so that is now required.

PO concatenates adjacent quoted pieces, so a header split as
`charset=windows-` then `1252\n` read as the label `windows-` and the
catalog was refused for declaring a charset it does not. The entry's pieces
are joined and unescaped before the charset is taken from them. The 64 KiB
prefix reached the same truncation on its own, so an entry that runs to the
cut is now re-read from the whole file rather than answered from half a
value.

* Keep decoded audio in order, and hold every forwarded container to the cap

Four things the bounded audio path got wrong.

The soundfile reader preallocates a buffer from the header's frame count and
re-tested the fit for every block. Once a block overflowed into the tail, a
shorter later block still fit the space left over and was written there,
landing ahead of the blocks that overflowed before it. The length stayed
right, so nothing downstream noticed, and what reached the model was the same
recording with a piece of it moved. Sweeping the block-length and declared-
length space, 144 combinations came back reordered. The buffer is now latched
closed by the first block it cannot hold.

_wav_seconds divided by nAvgBytesPerSec, which is redundant with the sample
rate and block alignment beside it and so is the one field that can be moved
alone. Inflating it by ten thousand made fifty minutes of PCM read as fractions
of a second, and a short file is forwarded to llama-server without any bounded
decoder seeing it. It is recomputed now, and the declaration is taken only
where it agrees.

_mp3_seconds returned the seconds it had counted whenever the frame walk
stopped, including when it stopped on bytes it could not read. A decoder
resynchronises past junk and plays the rest, so four stray bytes after the
tenth frame presented two hours as two and a half seconds. It now distinguishes
a complete walk from an abandoned one, and _prepare_audio_for_llama treats an
unestablished length as a reason to decode rather than a reason to forward.
That costs a transcode and puts the file back under both ceilings.

Last, _decode_audio_base64 used to call torchaudio.load outright, so an
environment carrying only torchaudio could decode audio. torchaudio 2.9 removed
info(), which is what routes such an install into the streaming chain, and that
chain needs libsndfile, PyAV or librosa. An install predating PyAV as a base
requirement would have lost audio input on upgrade; it falls back to load()
now, under the same backstop.

* Say why a text attachment was refused, and know one more tracker module

Three things in the intake path, found by running it in Chromium, Firefox and
WebKit rather than only under Node.

unsupportedCharsetError returned a plain Error. The composer toasts an
UndecodableTextError and rethrows anything else, so this one refusal, alone
among the seven in TextAttachmentAdapter.add, produced no message: the drop
path logged it to the console and the picker path turned it into an unhandled
rejection, and either way the attachment simply never appeared. The labels that
reach it are not exotic. The Encoding Standard maps ISO-2022-KR, HZ-GB-2312 and
the ISO-2022-CN family to "replacement", which TextDecoder is required to
refuse, so a Korean or Chinese card or message declaring its own charset
vanished silently on every engine. It carries the file name and the charset now,
and the message that was already written for it is finally shown.

TRACKER_MOD_MAGICS was missing !PM!, ProTracker's other four-channel marker,
which file(1) lists at offset 1080 beside M.K. The Soundtracker fallback does
not rescue one either: in a 31-sample layout byte 470 lands inside a sample
name rather than the order table, so a !PM! module was read as UTF-8 text,
which is the outcome these sniffers exist to prevent. The two tables are
hand-mirrored, so there is now a test that compares them.

The BMFF fixtures returned a bare Uint8Array, which is generic over
ArrayBufferLike and so includes SharedArrayBuffer. BlobPart accepts neither
that nor a view onto it, and every one of these ends up inside a File, so
tsc reported twelve errors and the frontend build gate was red.

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

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

* Measure a forwarded WAV only when it is PCM, and bound the last-resort decode

Two things the previous round got wrong.

_wav_seconds recomputed nAvgBytesPerSec as sample_rate * nBlockAlign. Those
identities hold only for WAVE_FORMAT_PCM: for every other tag both fields are
the codec's business, and an IMA ADPCM nBlockAlign is a whole compressed block
rather than one sample frame. A 505-frame block therefore overstated the byte
rate 505-fold, and a three-hour ADPCM recording well inside the 25 MB upload cap
read as twenty-one seconds, which is short enough to forward untouched. The
format tag now decides: PCM and IEEE float keep the arithmetic, extensible is
resolved through its SubFormat GUID, and everything else reports no duration and
goes to the bounded decoder.

The torchaudio-only fallback called load() with no bound. torchaudio 2.9's load
is an alias for load_with_torchcodec, whose body decodes the whole file with
get_all_samples() and only then slices to num_frames, so passing num_frames
would have bounded the return value and not the allocation. Since it is exactly
2.9 dropping info() that routes an install into this fallback, that read was
unbounded, and 25 MB of Opus holds hours of PCM. It asks torchcodec for the
sample rate, channel count and duration first, refuses past the ceilings, and
reads a bounded range; with no bounded reader available it refuses rather than
reading.

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

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

* Keep a preview as lenient as its own adapter, and stop holding PyAV output twice

Two findings from the round before last that were never answered.

readBoundedText used to call Blob.text(). It now decodes through the strict text
path, and that path belongs to the files the text adapter owns, where refusing
beats sending mojibake to a model. A .html file is the HTML adapter's, and it
sends a windows-1252 page happily, so routing its preview through the strict
decoder meant opening an attachment that had already been accepted threw
UndecodableTextError on a byte the adapter itself reads. The preview follows the
adapter now: text-adapter names stay strict, everything else reads as before.

The PyAV decoder held every resampled block in a list and then handed the list to
np.concatenate, which allocates the result while the list is still live. At the
48 kHz sample ceiling that is two 346 MB arrays for one 30-minute upload. It
fills the output as it copies, dropping each block on the way, so the cost is one
array and one block. The copy order is the decode order.

* Studio: stream PyAV output and validate MP3 trailers to EOF

The PyAV decoder collected every resampled block and joined them at the end.
Dropping each block after copying it does not bound anything: the blocks are
small enough that freeing them returns them to the allocator's free lists
rather than to the OS, so resident memory only grows. Measured on 30 minutes
of 48 kHz mono, peak was 672 MB with np.concatenate and 665 MB with the fill
loop, against a 330 MB waveform. Each block is now written into one output
buffer as it arrives, sized from the container duration and doubling when that
was absent or under-reported: 330 MB declared, 354 MB undeclared.

_mp3_seconds recognised a metadata trailer by its magic alone, so the ID3v1 tag
that 'cat one.mp3 two.mp3' leaves between the two streams read as the end of the
recording. Five seconds of frames, a TAG, then forty minutes of frames reported
4.99 seconds and was forwarded past the duration cap. Trailers now have to
account for their own length and reach EOF, and a walk that cannot returns None
so the file is decoded instead.

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

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

* Studio: make the audio attachment tests run on a Windows checkout

Two failures from a Windows staging run of this suite, neither of them about
audio. read_text() follows the locale encoding, which is cp1252 on a stock
Windows runner, and the module the parity test reads holds bytes cp1252 cannot
decode, so it raised UnicodeDecodeError instead of comparing anything. And five
tests imported torch directly for the fake tensors they hand to the fake
torchaudio, which fails rather than skips where torch is absent; they now use
importorskip, as the PyAV fixtures in the same file already do.

* Studio: hold PyAV allocations to the limit the decode enforces

Two limits bind a decode at once, the thirty-minute clock and a rate-independent
sample count, and the decode refuses at whichever is smaller. The buffer sizing
did not read the same bound. The initial allocation clamped only to the sample
count, so an 8 kHz file declaring three hours reserved 86.4M floats (330 MB) on
the way to being refused at 14.4M (55 MB), and the doubling that covers an
under-reported duration was not clamped at all: 48 kHz declaring twenty minutes
and holding twenty-one grew to 115.2M against an 86.4M limit, with the old
buffer still live for the copy.

_decoded_sample_ceiling is now the single source for all three, so the
allocation, the growth target and the refusal cannot drift apart. The growth
clamp cannot starve a write, since the sample count has already been checked
against that same ceiling.

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

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

* Studio: stream the soundfile decode into one bounded buffer too

The PyAV path was fixed to write each block into a single growing buffer, but
the soundfile path kept the branch that motivated it. When libsndfile reports
no usable frame count, or one past the ceiling, the declared length is dropped,
nothing is preallocated, and every block is held until a final concatenate
allocates a second copy of the recording. Measured with a source reporting zero
frames for a 30-minute 48 kHz decode: 592.6 MB peak against a 329.6 MB
waveform.

Now one append-only buffer that doubles when it runs short and is clamped to
_decoded_sample_ceiling: 352.0 MB for the same decode, with the returned array
byte-identical. An honest header is still only trusted once the decode has met
half of it, so it sizes the growth rather than buying an array up front, and
ordering is now correct by construction rather than by a latch.

Two tests asserted the old mechanism instead of the behaviour and were restated:
one required the final concatenate to happen, and one required no allocation at
all before the cap refuses, which a streaming buffer cannot promise. The
guarantee they were protecting, that nothing the header claims is allocated, is
now asserted directly against the ceiling.

---------

Co-authored-by: Unsloth <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>

* Studio: count only this adapter's engines in the Windows AMD GPU utilization (#9317)

* Join the Windows GPU adapter counters to torch devices on the adapter 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.

* Decline the DirectX adapter map when a record will not read

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.

* Studio: ask HIP for the adapter LUID before inferring it from the DirectX record

Stacks on #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 #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 #8863 at review request.

* Bound the HIP-joined counter by the carve-out, not the displayed total

_adapter_counter_capacity arrived with #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.

* Studio: count only this adapter's engines in the Windows AMD GPU utilization

The GPU Engine instances are named after the adapter, exactly like the memory
ones -- pid_<pid>_luid_0x<high>_0x<low>_phys_<n>_eng_<n>_engtype_3D -- and the
3D utilization summed every one of them. That is the whole host's 3D load
reported as this card's: on a laptop the display iGPU's work, and on the
reporting host the Basic Render Driver's instances were being summed in.

Narrowed to the card's own LUID. Which LUID is safe to filter on is not
obvious: a linked-node adapter puts several ordinals behind one, and the node
mask alone cannot settle it, since one bit set reads the same whether the
ordinal owns the only node or one of two. What settles it is the node count
the VRAM join already checks, the number of counter instances that LUID has.
So the join hands the LUID back only for a device it established is the whole
of what that LUID names, and the engine query filters on that. Where it did
not establish that, the LUID is absent and the sum stays the host's, which is
what it has always been.

That also drops a second identity probe per poll: the utilization path was
asking HIP again for something the VRAM path had just resolved. The key is
internal, and neither endpoint spreads these dicts into its payload.

Stacks on the HIP probe, which is what supplies the LUID. Split out of #8863
at review request.

* Filter the engine samples here rather than in the counter path

The narrowing is right and the reading it corrects is real: simulated against
the shape off the reporting host, this card at 17% beside an iGPU and the Basic
Render Driver at 61% between them, the poll reported 78 before and 17 after.

Where it was done is the problem. Putting the LUID in the counter path hands the
selection to PDH, and no test in this repo can run PDH, so the three tests here
were asserting the shape of a string while a mock decided the number. Both of
these mutants left them green: dropping engtype_3D from the pattern, so Copy and
VideoDecode instances sum in, and unioning *engtype_3D* back in beside the LUID,
which is the whole-host sum this branch exists to stop reporting.

It also left the value unguarded. Utilization Percentage is a cooked counter over
an instance list that is created and destroyed as work starts, and the previous
form took whatever the pre-summed expression printed: a non-finite sample reached
the payload as inf, which json.dumps rejects and no browser will parse, and a
value above the PowerShell clamp passed straight through at 250.

So the path goes back to a bare wildcard and the rows are filtered here, which is
what _rocm_windows_perf_counter_vram_by_adapter -- the counter that resolves the
LUID being matched -- already does. The sum, the clamp and the sanity checks are
in Python now, where the tests reach them, and the three tests assert numbers.

Ten cases added, all of them things the old shape could not ask: a longer LUID
that starts the same, engtype_3d in lower case (hosts emit both spellings and the
old pattern relied on PDH folding it), compute engines only, an idle engine
reading 0 rather than unknown, NaN and infinite and negative and unparseable
samples, the clamp, an instance name with no LUID in it, no instances at all, a
high LUID half, and the internal luid key staying out of both payloads with a
negative control so a declined join cannot pass it. 53 in the file.

Also .get("luid") at the call site instead of ["luid"]: two suites already stub
_rocm_windows_per_device_vram with records that have no such key, and they reach
this line the moment one of them is used with get_gpu_utilization.

Simulated across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only] with the
vendor SMI answering and unavailable, on 3.11 and 3.13: 42 of 58 host shapes
produce byte-identical payloads, and every one that moves is Windows ROCm with
the join having proved ownership.

* Trim the comments on the engine utilization filtering

* Take node identity, not node count, as whole-adapter ownership

Equal counts say how many nodes an ordinal owns, never which. One ordinal
holding node 0 of a linked adapter, whose own counter instance is missing while
the node it does not own still reports, gives one counter against one owned node
and passes:

    only the HIDDEN node emits -> ([5368709120.0], 5368709120.0, [86889])

The third element is the LUID being handed back as whole-adapter, so the engine
query then sums the other node's 3D work as this card's, on top of the hidden
node's bytes landing in used_gb.

luidDeviceNodeMask names the nodes rather than counting them (bit i is node i,
so a plain adapter reads 1 and not 0), so where the mask is present the observed
phys_N set has to be exactly those nodes. A zero mask names nothing and keeps
the count check alone, which is the pre-existing behaviour for adapters that are
not linked.

The check only ever withdraws an ownership claim, never grants one, so a host
where phys_N and the mask index differently loses the narrowing and falls back
to the unfiltered sum rather than attributing wrongly.

Reported by Codex. The used_gb half of the same shape belongs to the HIP join
underneath this branch and is left alone here.

* Keep the engine type in the counter path, match the adapter here

GPU Engine is instanced per process AND per engine, so a bare wildcard asks
PowerShell to format every engine type of every GPU-using process into text that
the loop here then discards down to 3D. On a busy host that is the bulk of the
sample set, inside a 5 second timeout on the monitor poll, and a timeout reads as
no utilization rather than as an error.

The engine type is not what this branch narrows. It was in the path before it and
belongs there: one segment, no interior wildcard, and it is the restriction that
keeps the set small. Only the adapter LUID moved into Python, which is the part
the tests need to reach.

The Python engtype check stays as well, since it costs nothing and covers the
engtype_3d spelling directly rather than relying on PDH folding the case.

Reported by Codex.

* Unpack the carve-out join test three-wide

_match_adapter_used_by_hip_luid returns the whole-adapter LUID as a third value,
so the carve-out bound test on this base cannot unpack it two-wide any more:

    ValueError: too many values to unpack (expected 2)

Only reachable once this branch sits on a base that has that test, which is why
it did not show up while the branch was behind.

* Tighten the comments on the engine LUID filter

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>

* Fix diffusion offload host RAM retention (#10184)

* Fix diffusion offload host RAM retention

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

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

* Keep diffusion benchmark JSON standards compliant

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

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

* Harden the offload reclaimer and cover the video path

Follow-ups from reviewing this branch, verified against a real whole-model
offloaded run (Z-Image-Turbo bnb-4bit, low_vram forcing offload on one B200).

Do not make ctypes a hard import. diffusion_memory sits on the import path of
diffusion, video, llama_cpp, sd_cpp_backend and routes.inference, so on a
Python built without libffi (no _ctypes, a common source or pyenv build) this
branch turned "allocator pressure is unavailable" into "the whole inference
stack fails to import". Import it defensively and decline to resolve when it
is missing. It stays a module attribute so the existing reclaimer tests keep
patching diffusion_memory.ctypes.

Say something when the allocator cannot be trimmed. The call site discards the
return value and an unresolved reclaimer returned False silently, so a
permanent no-op on musl, an unsupported platform, or a ctypes-less build was
invisible while host RAM climbed. Log it once at info.

Reclaim on the video path too. video.py plans the same policies through the
same apply_memory_plan and can engage offload_policy "model", but never
reclaimed, so video generations kept the retention this branch fixes for
images. Video weights are larger, so the retention is worse there. Placed
after progress is cleared: the trim can block for a few hundred ms on a large
heap and the page should not still read active while it runs.

Tests: a Linux-guarded case that calls the real glibc malloc_trim and asserts
argtypes/restype by value, since every existing reclaimer test replaces ctypes
and none of them would notice the symbol or the ABI breaking; the ctypes-less
path; the log-once behaviour; the video call site across all five policies;
and the benchmark's /proc RSS fallback plus the new flag defaulting to off.

Measured against this branch's base, 1024x1024, 9 steps, fixed seed, 1 warmup
plus 8 measured generations: host RSS growth 3103.8 -> 33.7 MiB, steady-state
RSS 15.8 -> 8.6 GB, peak VRAM 0.0%, median latency +1.9%, PSNR infinite (bit
identical). A gc.collect() only arm stayed at 16.6 GB, so the native trim is
what does the work. Trim cost measured in place: 288 ms on the first
generation, then 34 to 59 ms steady.

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

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

* Correct the video reclaim comment about progress state

generate_progress() re-asserts active from _generate_job_active after
self._gen is cleared, so the claim that the page is idle across the trim was
only true for the synchronous path, not a background begin_generate job.
Comment only, no behaviour change.

* Tighten the comments added by this branch

Post-convergence comment pass: 30 comment lines down to 10 across the six
files with non-docstring comments. Kept the facts a reader would otherwise
have to rediscover: why ctypes is optional and must stay a module attribute,
why the trim runs after progress is cleared, and the glibc malloc_trim return
convention the ABI assertion relies on.

* Close the cancel window the video reclaim opened, and guard the baseline path

Two review catches, both reproduced with a failing test first.

The video epilogue ran the host-allocator trim after its last cancel.is_set()
check but before the finally that deregisters the event. The trim blocks for a
few hundred ms, so a Stop landing in that window was answered true by
cancel_generate() while this clip was still returned and persisted by
_run_generate_body. Deregister under the same lock cancel_generate takes and
re-check inside it, matching the image backend's epilogue. Before the fix the
new test fails with "cancel_generate answered true for a clip that was still
persisted".

--write-baseline accepts any path, so a baseline can legitimately sit on
compare.json or compare.png inside the directory a later --compare writes to;
the report then overwrote the reference metrics. Refuse the collision up front,
before the generation is paid for rather than after. Before the fix the new
test sees _compare return 0 with the baseline clobbered.

* Apply the repo kwarg-spacing formatter to the new tests

The two tests added in b8064188b were not clean under the pinned
ruff-format-with-kwargs hook, so pre-commit.ci kept trying to fix them and its
autofix push kept losing a race with mine. Run the hook's own output instead.

* Tighten the comments added by the last two fixes

Final post-convergence pass over the comments this branch added after the
previous one: 10 lines down to 6. Dropped the assertion restatement whose
message already says the same thing, and collapsed the two rationale blocks
while keeping why the deregistration has to precede the trim and why the
baseline path collision is refused up front.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* Let audio models load into CPU RAM instead of the GPU (#10054)

* Add a CPU option for loading audio models

Audio loads take an accelerator whenever one exists, with no way to say
otherwise. That is a problem when the GPU is the scarce resource: a card
already holding a chat model, a training run wanting every spare byte, or a
checkpoint that will not fit at all. Whisper and the smaller TTS models run
fine on CPU, so this makes the placement the user's call.

Adds an auto/cpu/gpu preference, defaulting to auto (today's behaviour):

- Settings > Voice > "Load into" for dictation, sent with the explicit load
  and with the implicit one dictation triggers on first use.
- Audio page > "Load model into" for TTS. Changing it ejects the resident
  model so the choice takes effect instead of sitting unapplied.
- UNSLOTH_AUDIO_DEVICE for headless and CLI use.
- API: device on SttLoadRequest, TranscribeRequest and
  /audio/transcribe/raw; audio_device on LoadRequest and
  ValidateModelRequest.

All three audio stacks honour it through the CPU path each already had for
training: Transformers Whisper picks cpu/float32, whisper.cpp gets --no-gpu,
llama.cpp gets -ngl 0, and native audio picks its device in the constructor.
GGUF TTS translates the same choice into gpu_layers 0, since audio_device
does nothing there.

Notable decisions:

- device=None means no opinion, not auto. A caller that never sends one (the
  OpenAI-compatible route) must not drag a model off the device another
  surface asked for, or the two thrash a reload apiece.
- One gate, keyed on the audio type, keeps a CPU-placed load out of the
  training coexistence check, the GPU arbiter, the memory preflight and the
  already-loaded shortcut. Keyed on the type so a chat model cannot send
  audio_device and walk past those guards.
- MiniMax Music 3 on CPU is refused in preflight, not in the worker, since
  past preflight the switch has already evicted the resident model.
- No training-teardown exemption for CPU native audio: that worker runs
  detect_hardware() before it places anything, so it holds a CUDA context
  whatever the weights are on. The STT sidecars do get one, because their
  worker never touches CUDA.

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

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

* Stop a CPU audio load taking, needing and holding the GPU it asked to avoid

Three placement bugs, all reachable in the case the option exists for: a card
that is already full.

A forced-CPU load still ran GPU selection. Automatic selection returns every
card needed to hold the checkpoint and the worker forwards that list to
NativeAudioBackend.load_model, which rejects more than one as unsupported
sharding. The same estimate also becomes expected_free_gb, so the settle wait
raises "GPU memory from the previous inference worker was not released" when an
Images or Video pipeline holds the card, aborting the load after the previous
worker has already been shut down. A load that takes no card now selects none,
which closes both paths at once.

The stale CHAT claim was dropped only after the load returned. A download and
load can run for minutes, and across that window an Images or Video acquire_for
still finds CHAT owning the GPU, runs the chat evictor, sees this model in
loading_models and cancels it. acquire_for evicts only when the arbiter has an
owner, so releasing before the load lets the two coexist. The post-load release
stays, since it covers a claim re-taken while the load ran.

A GPU-resident mtmd server could report holding no VRAM. _load_locked records
the user's standing CPU wish in _forced_cpu even on the branch that deliberately
does not restart a server with a request in flight, and the training probe ORed
that wish with _gpu_disabled, which is the fact. Training then skipped the
teardown and started beside a server still at -ngl 99. The probe now prefers the
fact wherever a sidecar keeps one. whisper.cpp is unaffected: it writes
_forced_cpu only next to a spawned --no-gpu and clears it on release, so there
the flag is the fact.

Also, the audio suites no longer depend on UNSLOTH_AUDIO_DEVICE being unset.
Seven tests asserted placement against no opinion, so a host configured with the
server-wide default this PR adds failed them on correct behaviour.

Four regression tests, each confirmed to fail without its fix. Backend 38981
passing, every remaining failure already present on main and none introduced.

* Add the missing AGPL-3.0 header to audio_device.py

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

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

* Read source under test as UTF-8 so the guard tests run on Windows

read_text() defaults to the locale encoding. On windows-latest that is cp1252,
and routes/inference.py is UTF-8, so four tests died with a UnicodeDecodeError
on byte 0x81 while passing on every other runner. Found by the cross-platform
staging run, not reproducible on Linux without forcing the locale.

* Say where UNSLOTH_AUDIO_DEVICE reaches, since it does not reach GGUF

It was documented as a server-wide default, but the llama.cpp path never
consults it: placement there comes from gpu_memory_mode and gpu_layers, read at
request time, and nothing knows a GGUF is audio until llama-server reports its
audio_type after the load. There is no point early enough to translate the
default into zero offload, so an operator who set it to keep VRAM free still got
automatic GPU offload for a GGUF TTS, with nothing saying so.

The Audio page translates it from the catalog it already has. A headless caller
has to send the placement fields itself, and both docstrings now say that.

* Keep a CPU-mode GGUF audio codec off the GPU, and keep MiniMax loaded

Two placement bugs the audio device preference did not reach.

The GGUF audio codec picked its own device. A CPU-mode load sets zero
offload for the language model, so nothing else in that load touches the
GPU, but init_audio_codec still read torch.cuda.is_available() on its own
and put the codec on the card. The load then held VRAM after being
classified as holding none. It now follows the placement the server
already decided for that load.

Selecting CPU RAM also ejected a resident MiniMax Music 3, which cannot
run on CPU at all. The user lost the loaded model and got nothing back.
Selecting CPU now says why it is not available and leaves the model
where it is.

* Decode audio where the codec is, and stop a CPU load taking things it does not need

Three placements a CPU RAM audio load still got wrong.

The GGUF codec now loads on CPU, but decoding still asked for CUDA
whenever a card existed. The decoders build their input tensors on the
device they are handed, so SNAC and DAC failed on a device mismatch and
BiCodec moved the codec onto the card, taking the VRAM the mode exists to
avoid. The codec manager records where each codec actually went and
decoding follows it. That also covers the reuse case, where a codec
already resident from an earlier load never moves to the device a later
request asked for.

Releasing the CHAT claim before the load left a still-resident GPU model
unowned, and acquire_for evicts nobody when the arbiter has no owner, so
an Images or Video load could allocate straight over it. The release is
now handed to load_model, which runs it once the previous worker has
exited and its memory is back: after the danger, still ahead of the
download that made holding the claim untenable. A worker that will not
exit keeps the claim, which is then telling the truth.

The export teardown ran unconditionally to free VRAM for the incoming
model. A CPU load masks the accelerators and wants none of it, so this
was killing a running export for nothing.

* Decide whisper.cpp placement under the loading flag, and keep the catalog's GGUF answer

Two ways a CPU RAM choice still ended up on the GPU.

whisper.cpp chose between GPU and --no-gpu before publishing _loading.
The training hook reads is_loading() without that method's lock, so a
switch from a CPU-resident model to Auto landing in that window was
invisible to a training run starting concurrently: training saw no load
in flight, read the outgoing model's CPU placement, preserved it as
holding no VRAM…
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.

Studio: AMD on Windows reports VRAM as Unknown on every single-GPU host

3 participants