Repository navigation
Studio: keep the AMD gfx target and HIP id map until hardware re-detection - #14970
Conversation
…ction rocminfo brings up the whole HSA runtime and ran on every 60 s physical inventory pass on a Linux AMD host. The gfx target is the silicon's, so the answer is now kept until hardware re-detection (gpu_query's static generation), keyed on the resolved rocminfo / amd-smi binaries and the device masks and gfx override they inherit. A timed-out probe is not kept, and UNSLOTH_GPU_QUERY_CACHE=0 turns it off. The amd-smi list -e HIP id map was cached for the process; it now follows the same static generation, so a re-detection after a swapped card reads it again. Live VRAM and utilization reads are unchanged.
|
@codex review |
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 56a9368410
ℹ️ 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".
| cached = _gfx_candidates_cache | ||
| if key is not None and cached is not None and cached[0] == key: | ||
| return list(cached[1]) |
There was a problem hiding this comment.
Invalidate the gfx cache when AMD topology changes
When an AMD GPU is attached or swapped while another AMD GPU remains present, the 60-second physical-inventory refresh sees the new sysfs rows, but this cache key remains unchanged because the binaries, environment, and gpu_query._static_gen have not changed. The cached targets are consequently assigned to every refreshed AMD row, so the new card can be misclassified and receive an incorrect hardware fingerprint indefinitely; include the observed AMD topology in the key or bump the static generation when the inventory detects a topology change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in fa025d7. Re-detection only fires on a GPU / no-GPU flip, so a card attached or swapped beside one that stays was invisible to the key. The key now carries _linux_amd_pci_topology(): the (PCI address, device id) of every AMD card DRM has bound, read from sysfs with no subprocess, so a new, removed or swapped card makes the next refresh ask rocminfo again. An unreadable walk never hits the cache.
The same push also stops keeping an answer when rocminfo failed and the amd-smi fallback answered, when the binary exists but cannot start (ENOENT from a missing interpreter), when a numbered HSA_OVERRIDE_GFX_VERSION_<n> changes, and after a forced detect_hardware(). Tests for each in test_static_gpu_inventory_cache.py (18 pass); AMD / detection / inventory suites have identical failing test IDs on main and this branch.
There was a problem hiding this comment.
Fixed in 5deba44: the gfx cache key now includes the bound AMD cards' PCI addresses and device ids from sysfs.
…resses and device ids
…y, a per-device override or a forced detection [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fa025d7bcd
ℹ️ 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".
| if ( | ||
| cached is None | ||
| or cached[2] != static_gen | ||
| or (cached[1] is None and time.monotonic() - cached[0] >= _HIP_ID_MAP_NONE_TTL_S) |
There was a problem hiding this comment.
Include AMD topology in the HIP-map cache key
When an AMD GPU is attached, removed, or swapped while another AMD GPU remains, the automatic inventory refresh does not bump gpu_query._static_gen; only the gfx cache separately observes _linux_amd_pci_topology(). A successful HIP map therefore remains cached indefinitely here even if amd-smi/KFD enumeration changes. On a same-size reorder, llama_cpp.py::_amd_smi_hip_id_map accepts the stale map because all row IDs still exist, potentially attributing fresh VRAM rows to the wrong HIP ordinal and pinning the child to the wrong GPU. Key this cache on the AMD topology too, or invalidate it when that topology changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fdee8d3. The HIP id map now records the AMD topology it was read under (the same sysfs (PCI address, device id) set the gfx cache keys on) and is read again when a card is attached, removed or swapped beside one that stays. An unreadable sysfs walk keeps the map, as main does, rather than re-running amd-smi every call. The same push makes a missing /sys/class/drm read as no cards, so the caches still work where there is no DRM class. Tests: map refresh on a topology change, unreadable topology keeps the map, and an unreadable topology probes the gfx target every pass; AMD / detection / inventory / HIP suites have identical failing test IDs on main and this branch.
…M class means no cards [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fdee8d3dfa
ℹ️ 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".
| found = {match.group(0).lower() for match in re.finditer(pattern, result.stdout or "")} | ||
| if found: | ||
| return sorted(found) | ||
| return [] | ||
| # An answer from the fallback after rocminfo failed is used, not kept: rocminfo is asked again. | ||
| return sorted(found), settled |
There was a problem hiding this comment.
Avoid caching output from failed gfx probes
When rocminfo or amd-smi emits a gfx token but exits nonzero—for example, after producing only partial output during a multi-device probe—this branch returns before checking result.returncode, leaving settled true and caching the incomplete/error output until hardware, topology, or environment invalidation. Inspect the return code before accepting the matches, or return the matches with settled = False, so failed probes are retried.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 44e3b6b. A gfx answer from a CLI that exited non-zero is still used for that pass but no longer kept, so possibly partial output from a failing multi-device probe is asked again on the next refresh. Test: test_partial_output_from_a_failing_probe_is_used_not_kept.
| global _MLX_BLOCKERS_MEASURED, CHAT_ONLY_MISMATCH_VENDORS | ||
| global _MLX_BLOCKERS_MEASURED, CHAT_ONLY_MISMATCH_VENDORS, _gfx_candidates_cache | ||
| CHAT_ONLY = True # reset -- only CUDA/ROCm/XPU/MLX sets it to False | ||
| _gfx_candidates_cache = None # a forced detection asks the ROCm CLIs again |
There was a problem hiding this comment.
Invalidate the HIP map during forced detection
When a caller invokes detect_hardware() directly for its documented forced re-detection path, gpu_query._static_gen is not incremented because only invalidate_detection() does that. This line explicitly clears the gfx cache, but a successful _hip_id_map_cache survives when the PCI topology is unchanged, so a driver reset or re-enumeration can leave later placement using the previous HIP ordinals despite the forced pass. Clear the HIP map here as well, or include the detection generation in its cache key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 44e3b6b. A forced detect_hardware() now drops the HIP id map along with the gfx answer, so a driver reset or re-enumeration with an unchanged PCI topology re-reads amd-smi list -e. Test: test_forced_hardware_detection_reads_the_hip_id_map_again (fails with the reset removed). AMD / detection / inventory / HIP suites: 2 failed / 2005 passed, the same two pre-existing failures as main.
…orced detection re-reads the HIP id map [skip ci]
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d2d9f59059
ℹ️ 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".
| cached is None | ||
| or cached[2] != static_gen | ||
| # A card attached, removed or swapped beside one that stays; an unreadable walk keeps the map. | ||
| or (topology is not None and cached[3] is not None and cached[3] != topology) |
There was a problem hiding this comment.
Refresh the HIP map when topology becomes readable
If the first successful amd-smi mapping is cached while the sysfs topology walk returns None, cached[3] remains None. When sysfs becomes readable, this condition refuses to compare or establish a baseline, so even a later card attachment or reorder with the same static generation never invalidates the map; callers can then translate an amd-smi row to the wrong HIP ordinal and pin work to the wrong GPU. A readable current topology should trigger a refresh when the cached topology is unknown, while only retaining the map when the current walk itself is unreadable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7f34a0d. The HIP id map is now read again whenever the current sysfs walk is readable and differs from the topology it was cached under, including when that cached topology was unknown, so the first readable walk sets the baseline and later attachments or reorders invalidate it. Only an unreadable current walk keeps the map. Test: test_a_topology_that_becomes_readable_sets_the_hip_id_map_baseline (fails on the previous head). The AMD / HIP suites show the same failing test IDs with and without the change and on main (20 order-dependent failures in test_rocm_vram_probe_no_hip_context.py that pass in isolation).
…sysfs walk [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f34a0da12
ℹ️ 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".
| _gfx_candidates_cache = None # a forced detection asks the ROCm CLIs again | ||
| try: | ||
| from . import amd as _amd | ||
| _amd._hip_id_map_cache = None # and re-reads the HIP id map |
There was a problem hiding this comment.
Synchronize forced HIP-map invalidation with readers
When a system poll or placement request is already inside get_hip_id_by_gpu_index() while forced detection runs, this assignment clears the cache without taking _hip_id_map_lock; the in-flight reader can then finish amd-smi list -e and overwrite the cleared value with its pre-detection result. Because direct detect_hardware() does not increment gpu_query._static_gen, later reads accept that map indefinitely when topology is unchanged, potentially translating an amd-smi row to the wrong HIP device after a driver reset or re-enumeration. The fresh evidence beyond the earlier sequential fix is this unsynchronized write racing the locked cache write at amd.py:404; clear the cache under the same lock or advance a generation that an older probe cannot publish into.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in de984cb. Forced detection now calls amd.invalidate_hip_id_map(), which clears the map under _hip_id_map_lock. A reader already refreshing the map holds that lock while amd-smi list -e runs, so the clear waits for it and lands after its write instead of being overwritten by the pre-detection answer. Test: test_an_invalidation_during_a_hip_id_map_read_is_not_overwritten holds a read open, starts the clear, then releases the read; it fails with an unlocked clear and passes with this one.
… in-flight read cannot land after it [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: de984cbf65
ℹ️ 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".
| found, settled = _probe_linux_amd_gfx_candidates() | ||
| # A timed-out or failing CLI is not an answer about the silicon: ask again next pass. | ||
| if key is not None and settled: | ||
| _gfx_candidates_cache = (key, list(found)) |
There was a problem hiding this comment.
Synchronize forced gfx-cache invalidation with probes
When an inventory refresh is already inside _probe_linux_amd_gfx_candidates() while a direct detect_hardware() starts, _detect_hardware_locked() can clear the cache and then this unsynchronized assignment can republish the pre-detection result. Direct forced detection does not increment gpu_query._static_gen, so with unchanged topology and environment the old key remains valid and subsequent refreshes can retain the stale gfx answer indefinitely, defeating the forced re-probe after a driver/runtime reconfiguration. Protect probing and clearing with the same lock, or use a generation that prevents an older probe from publishing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a13d872. Forced detection now bumps _gfx_detect_epoch, which is part of the gfx cache key. A probe that started before detection publishes under its old key, which no later read matches, so the next refresh asks rocminfo again; no lock is held across a rocminfo call that can take seconds. Test: test_a_probe_running_across_a_forced_detection_cannot_republish holds a probe open, applies the detection reset, then lets the probe publish; it fails without the epoch in the key and passes with it.
…obe running across detection cannot republish [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a13d872023
ℹ️ 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".
| return [] | ||
| # Used but not kept when this CLI exited non-zero (possibly partial output) or rocminfo failed | ||
| # before the fallback answered: the next pass asks again. | ||
| return sorted(found), settled and result.returncode == 0 |
There was a problem hiding this comment.
Update the existing gfx probe test double
When test_the_gfx_probe_answers_nothing_without_a_rocm_userspace in test_torch_cpu_build_on_nvidia_host.py returns its established _Result, the object has stdout but no returncode; a gfx match therefore reaches this newly added attribute access and raises AttributeError instead of returning ['gfx1030']. Update that existing test double as part of this change so the hardware test suite does not fail.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7ab2d21. The _Result double in test_the_gfx_probe_answers_nothing_without_a_rocm_userspace now carries returncode = 0; that file passes (171) with fastmcp available, and the test fails on the previous head as you describe. Running the other hardware suites that stub subprocess.run alongside this PR's test file also showed the new cache tests depending on amd-smi state another file can latch off, so the fixture now resets _amd_smi_disabled, the failure count and the platform gate. Those suites now fail the same test IDs as main (three pre-existing in test_rocm_torch_explicit_request.py).
There was a problem hiding this comment.
Fixed in 7ab2d21: the existing probe double now carries returncode = 0.
| # A CLI that ran and failed (no /dev/kfd access yet, driver still loading) said nothing about the silicon. | ||
| if result.returncode != 0: | ||
| settled = False | ||
| return [], settled |
There was a problem hiding this comment.
Retry successful probes that return no gfx target
If an installed rocminfo exits successfully but temporarily reports no GPU gfx token—for example, it sees only a CPU agent while the GPU runtime is still becoming available—and the fallback is absent or likewise returns success without a token, settled remains true and the empty result is cached indefinitely. Because recovery does not change the binary paths, environment, PCI topology, or generation, later 60-second inventory passes never probe again and never publish the recovered GPU's gfx candidates; treat an empty response from a present CLI as retryable or retain a bounded TTL for empty results.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7ab2d21. A probe that ran successfully but reported no gfx target is still used, but kept only for _GFX_EMPTY_TTL_S (300 s), so a GPU runtime that comes up later is seen within five minutes; non-empty answers keep the until-re-detection lifetime. Test: test_an_empty_answer_is_asked_again_after_its_window.
There was a problem hiding this comment.
Fixed in 7ab2d21: an empty answer is kept only for _GFX_EMPTY_TTL_S (300 s), then asked again.
…double a returncode, isolate the cache tests from amd-smi latches [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…es contain ':') [skip ci]
…m / AdamW on local shards (#15049) `Repo tests (CPU, fsdp2)` fails on `main` since #15008, for example on #14970 and #15000: ``` tests/test_fsdp2_native_optim_reentry_gloo.py::test_bnb_optimizer_cls_and_kwargs_is_refused AssertionError: (0, 'bnb.keyword', {'error': '', 'sharded': True}) ``` ## Cause #15008 made native FSDP2 keep a bitsandbytes Adam / AdamW and step each rank's local shard. `_refuse_bnb_optimizer_cls` now lets `optimizer_cls_and_kwargs = (bnb.optim.AdamW8bit, ...)` through whenever this bitsandbytes can step local shards, and refuses it otherwise (`UNSLOTH_FSDP2_BNB_LOCAL=0`). The test still expected every bitsandbytes class to be refused. The product change is intended, as the #15008 description says, so the test was out of date. ## Fix The worker now also reports `native._bnb_local_shards_available()`, and the test asserts each arm against it: - `torch.*`: accepted and sharded. - `bnb.*`: accepted and sharded when local shards are available, otherwise refused with the bitsandbytes `ValueError`. - `like.*` (`AdamW8bitLike`, a torch AdamW that only claims the bitsandbytes module): always refused, since it cannot step local shards. ## Verification The whole file gives 5 passed. Both `bnb` branches run: | `UNSLOTH_FSDP2_BNB_LOCAL` | bnb local | `bnb.*` | `like.*` | `torch.*` | |---|---|---|---|---| | 1 (default) | True | accepted, sharded | refused | accepted, sharded | | 0 | False | refused | refused | accepted, sharded | Sabotage check: making `_refuse_bnb_optimizer_cls` return early fails the test.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
On a Linux AMD host the Studio GPU inventory refresh (every 60 s) re-ran
rocminfo(falling back toamd-smi static --asic) to read the gfx target.rocminfobrings up the whole HSA runtime on each call, and the answer is a property of the silicon. This keeps it until hardware re-detection instead.hardware.py_linux_amd_gfx_candidates: the gfx target is cached, keyed on gpu_query's static generation (bumped by hardware re-detection), the resolvedrocminfo/amd-smibinaries (a ROCm install landing mid-session is seen) and the device masks / override the CLIs inherit (ROCR_VISIBLE_DEVICES,HIP_VISIBLE_DEVICES,CUDA_VISIBLE_DEVICES,GPU_DEVICE_ORDINAL,HSA_OVERRIDE_GFX_VERSION). A CLI that timed out, could not start, or exited non-zero without a gfx target is not cached, so the next pass asks again.UNSLOTH_GPU_QUERY_CACHE=0turns it off, same as the existing nvidia-smi static cache.amd.pyget_hip_id_by_gpu_index: theamd-smi list -eHIP id map was cached for the life of the process. It is now also refreshed after hardware re-detection, so a swapped or re-seated card gets a fresh map.Spawn counts with fake CLIs, 10 inventory refreshes (each followed by 3 HIP map reads and 3 live VRAM reads) with one re-detect after the fifth:
rocminfoamd-smi list -e(HIP map)amd-smi metric(live VRAM)Tests
studio/backend/tests/test_static_gpu_inventory_cache.py(28 cases). On the merge base, 17 fail: therocminfospawn count, the mask / override and per-device override changes, a card attached beside another, the HIP map refresh after re-detect or a topology change, the empty-answer retry window, and the forced-detection epoch. The other 11 pass on both and guard what must not change: re-detect re-reads the gfx target, a mid-session ROCm install is seen, a timed-out or failing probe is not kept, the off switch, and live reads stay live.Existing AMD inventory suites: same failing test IDs on main and on this branch (7, environment related on this host); hardware suites 1365 passed, with one pre-existing failure identical on both.
Not covered here
No AMD GPU or ROCm userspace on the test host, so
rocminfo/amd-smiare faked and the real HSA start-up time saved per refresh is not measured.