Repository navigation
Studio: stop the /api/system poll from pinning a CUDA/HIP primary context - #8677
Conversation
The frontend polls GET /api/system every 5s from the root-mounted floating monitor and every 3s from Settings -> Resources. On any host where the smi shortcut returns None (ROCm, or no nvidia-smi on PATH) both handlers reached torch.cuda.mem_get_info, which attaches a primary context worth ~612 MiB on a B200. A context is never released while the process lives, so an otherwise idle Studio lost that memory to telemetry alone. get_backend_visible_gpu_info only reads name and total and discards used, so it now goes through _torch_get_device_inventory, which answers from get_device_properties. props.total_memory is byte-identical to mem_get_info's total half (191505498112 measured both ways here), so no displayed number moves. On Linux ROCm get_visible_gpu_utilization asked torch for occupancy and then overwrote it with sysfs figures in _overlay_system_wide_vram, spending a context on numbers that were discarded. The overlay's decision is now split out from its mutation, so the sysfs answer is taken first when it covers every visible device and torch is consulted only when the overlay declines, which keeps a device sysfs cannot speak for on its old path. clear_gpu_cache called torch.cuda.synchronize() unconditionally on the CUDA branch. With nothing reserved there is no work in flight to wait on, so the synchronize is skipped when memory_reserved is zero across the visible devices; memory_reserved needs no context itself, while is_initialized is useless as a guard because reading device properties already flips it. empty_cache and ipc_collect still run unconditionally, and the branch is deliberately left unwrapped because the diffusion and video unload paths document that a sticky CUDA fault has to propagate out of it. Measured per fresh process with per-PID nvidia-smi: the visibility path went 612 MiB -> 0 MiB with name, total_gb, index and visible_ordinal unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f0dd3ea1d
ℹ️ 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".
| # try/except: the diffusion and video unload paths document that a sticky | ||
| # CUDA fault has to propagate out of here. | ||
| if torch.cuda.is_available() and any( | ||
| torch.cuda.memory_reserved(i) for i in range(torch.cuda.device_count()) |
There was a problem hiding this comment.
Fall back when allocator statistics are unavailable
When Studio uses a CUDA allocator without device-stat support (for example, PyTorch's CUDAPluggableAllocator), memory_reserved(i) raises instead of returning zero. This new guard therefore exits before synchronize, empty_cache, and ipc_collect, regressing every unload/export path that calls clear_gpu_cache; the nearby trusted_mem_get_info already treats this probe as fallible. If reservation statistics cannot be read, fall back to the previous synchronization path while continuing to propagate errors from synchronize itself.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, though the mechanism is real and I verified it rather than assuming. strings on libtorch_cuda.so does contain CUDAPluggableAllocator does not yet support getDeviceStats, and I built a pluggable allocator .so, loaded it, and confirmed the split: memory_reserved raises while synchronize, empty_cache and ipc_collect all work. So under that allocator the new guard would raise where the old unconditional synchronize() did not.
What sinks it is reachability. Nothing in the repo installs one: grepping PluggableAllocator|change_current_allocator finds only an unrelated PYTORCH_CUDA_ALLOC_CONF deprecation filter, and it needs a compiled C++ .so plus an explicit change_current_allocator before CUDA init. I had to write and nvcc-compile one to reproduce at all, and Studio offers no way to install one.
I also checked the plausible env-var route, which would have made this genuinely reachable, and it does not exist: with PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync and 256 MiB live, memory_reserved(0) returns 268435456 correctly. The memory_stats docstring caveat about cudaMallocAsync reporting zeros is stale in torch 2.9. And memory_stats_as_nested_dict returns {} when not is_initialized(), so the uninitialized case the guard exists for never touches CUDA.
Worth noting video.py:4857 already calls device_module.memory_reserved(device_obj) behind only a hasattr guard, so such a host is already broken on the video load path independently of this PR.
One correction in your favour: your nearby-precedent point is factually right, trusted_mem_get_info does wrap its memory_reserved probe. But that wrapper is a Windows-ROCm-only refinement with a valid driver-figure fallback, not evidence that a pluggable allocator is a supported configuration.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f0dd3ea1d
ℹ️ 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".
| # try/except: the diffusion and video unload paths document that a sticky | ||
| # CUDA fault has to propagate out of here. | ||
| if torch.cuda.is_available() and any( | ||
| torch.cuda.memory_reserved(i) for i in range(torch.cuda.device_count()) |
There was a problem hiding this comment.
Support CUDA allocators without memory stats
When a process installs a torch.cuda.memory.CUDAPluggableAllocator, memory_reserved() can raise because that allocator does not implement getDeviceStats; this newly makes every clear_gpu_cache() caller abort before synchronization or cache cleanup, whereas the previous unconditional synchronization worked. Treat an unavailable allocator-stat probe as a reason to synchronize conservatively, while still allowing errors from synchronize() itself to propagate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as the sibling comment on clear_gpu_cache: the mechanism is real and I reproduced it with a hand-compiled pluggable allocator, but nothing in the repo installs one and there is no supported way for a user to. Declining both for the same reason rather than adding a branch for a configuration Studio cannot reach.
| "index": phys_idx, | ||
| "visible_ordinal": ordinal, | ||
| "name": props.name, | ||
| "total_gb": round(props.total_memory / (1024**3), 2), |
There was a problem hiding this comment.
Preserve the driver total on older ROCm APUs
On unified-memory ROCm hosts running torch 2.9 or earlier, this repository's allocator compatibility logic documents that props.total_memory and the hipMemGetInfo total differ; the old helper returned the latter because mem_get_info() replaced total_bytes. Switching backend visibility unconditionally to the property value therefore changes memory_total_gb on those hosts, causing hardware details and direct visibility consumers to budget against a different capacity. Retain the previous total source for affected ROCm versions/APUs or obtain an equivalent context-free driver total.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and it is the kind of regression this PR was most at risk of: trading a correct number for a cheap one. On a unified ROCm APU props.total_memory is the dedicated carve-out, not the GTT pool, so the visibility endpoint capacity collapsed from 100.0 GB to 8.0 GB on a gfx1151 Strix Halo shape. memory_total_gb feeds use-gpu-info.ts maxDeviceMemoryGb and loadDeviceMemoryGb, which gate whether a model is offered at all, so the user would simply stop being offered models that fit.
The repo already documents the divergence, which is what let me clear the bar without the hardware: worker.py:1726 notes c10 caps at fraction * props.total_memory from torch 2.10 and at fraction * hipMemGetInfo total through 2.9, and test_rocm_oom_guard.py:361 says outright that the two "differ on a unified APU (carve-out against the GTT-spanning budget)". _apply_unified_memory_correction already adopts the mem_get_info total over amd-smi for the same reason, and sibling #8669 hit the identical wall from the amd-smi side.
There is a second consequence you did not mention, introduced by the sysfs-first path in this PR. The probe fed to _rocm_system_wide_vram_by_index carried the carve-out, so the overlay 10 percent total check started AGREEING with sysfs and adopted it, instead of declining as its docstring says it does for a unified APU whose sysfs total is below the GTT-backed total. Pre-fix that assertion failed with assert {0: (1.0, 8.0)} == {}. Fixing it inside _torch_get_device_inventory repairs both call sites at once.
Fixed in 8ce9d23c5: _rocm_props_total_is_carve_out(props), gated on IS_ROCM and delegating to _rocm_classify_unified_memory, so the inventory asks mem_get_info for the total on unified devices only. A failed probe keeps the carve-out rather than dropping the device. Discrete ROCm and every NVIDIA host keep the context-free path.
Stating the trade plainly: a ROCm APU now pays for a context on this endpoint again. That is deliberate, and confined to the one device class where the two totals disagree. A correct capacity number is worth more than 612 MiB on a machine with a 100 GB unified pool.
get_backend_visible_gpu_info moved to _torch_get_device_inventory on the strength of props.total_memory being byte-identical to mem_get_info's total half. That holds on NVIDIA and on discrete ROCm, but not on a unified-memory APU, where this repo already documents the two as different numbers: _allocator_divides_by_props_total records that c10 caps at fraction * props.total_memory from torch 2.10 and at fraction * hipMemGetInfo total through 2.9 precisely because they differ there, and _apply_unified_memory_correction adopts the mem_get_info total over amd-smi's because props reports the dedicated carve-out while hipMemGetInfo spans the GTT pool. So on a Strix Halo the visibility endpoint went from the ~100 GiB pool torch can actually allocate into to the ~8 GiB carve-out, and memory_total_gb feeds use-gpu-info's maxDeviceMemoryGb and loadDeviceMemoryGb, which gate whether a model is offered at all. The same substitution also fed the new sysfs-first probe: with the carve-out in hand the overlay's 10 percent total check starts agreeing with the sysfs figure, so it adopts it instead of declining, which is the exact APU case its docstring says it keeps torch's number for. The inventory now asks mem_get_info for the total on unified devices only, using the same classifier the training worker and the llama.cpp backend use so all three agree on what an APU is. There is no context-free source for the GTT total, so an APU pays for a context here; every discrete card and every NVIDIA host keeps the free path, which is where the 612 MiB was being lost. A failed probe keeps the carve-out rather than dropping the device.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 385ddccd25
ℹ️ 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".
| from core.training.worker import _rocm_classify_unified_memory | ||
| return _rocm_classify_unified_memory(props)[1] |
There was a problem hiding this comment.
Preserve driver totals for unclassified ROCm APUs
On a unified ROCm APU whose properties omit is_integrated and whose architecture is outside the classifier's hardcoded gfx1150/1151/1152 set (for example, gfx1103 on an older torch build), this returns false even though props.total_memory is only the dedicated carve-out. The inventory then skips mem_get_info; on Linux, the new sysfs-first path can additionally accept the matching carve-out and report an 8 GiB-class capacity instead of the full GTT pool. The fresh evidence after the earlier review is that _rocm_classify_unified_memory explicitly returns false for a present gfx1103 architecture when is_integrated is unavailable, so retain the driver-total fallback for APUs that this classifier cannot conclusively classify as discrete.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and it is the same failure mode as the fix it follows: the endpoint publishing a carve-out as the whole device, so models that fit stop being offered.
Your literal wording is not the reachable form, and chasing that down is what made the real one obvious. .def_readonly("is_integrated", &cudaDeviceProp::integrated) is unguarded in torch/csrc/cuda/Module.cpp back to v2.0, so the attribute exists on every ROCm wheel Studio supports. What varies is the VALUE. clr sets deviceProps.integrated = info.hostUnifiedMemory_, and rocdevice.cpp only sets that from HSA_AMD_MEMORY_PROPERTY_AGENT_IS_APU from tag rocm-6.1.2 onward: absent in 6.0.0, 6.0.2 and 6.1.0, present 6.1.2 through 6.4. install_python_stack.py maps host ROCm 6.0 and 6.1 to rocm6.0 and rocm6.1 wheels, so the hole is inside supported installs.
The classifier has no "cannot tell" answer, so a real APU outside the hardcoded gfx1150/1151/1152 set whose runtime leaves the flag at 0 reads as discrete. gfx1103 Phoenix, carve-out 8 GiB against a 100 GiB GTT pool:
classifier: unified? False carve-out risk? False
inventory (this PR) 8.0 GB occupancy (pre-PR) 100.0 GB
The repo already models the wheel half of this: test_rocm_oom_guard.py::test_zero_does_not_downgrade_known_apu is titled "a wheel that zeroes the field must not flip Strix Halo to discrete", and the hardcoded set only rescues gfx115x.
Fixed in f72acda9b: _hip_runtime_version() parses torch.version.hip and falls back to the +rocmX.Y tag the AMD SDK and Radeon wheels use, and _rocm_props_total_is_carve_out now returns True on unified, when the flag is absent, when the runtime predates 6.2, or when the classifier raises. That last branch previously returned False and kept the carve-out, which was the same bug in miniature. 6.1 as a whole is untrusted because HIP last version field is a build number, so 6.1.2 cannot be told from 6.1.0. Discrete cards on ROCm 6.2 and later keep the context-free inventory.
Four tests plus a widened discrete case, all failing pre-fix.
| # Inventory only: this endpoint reads name and total and discards used, so | ||
| # there is nothing here worth a permanent driver context. | ||
| torch_devices = _torch_get_device_inventory(torch_indices) |
There was a problem hiding this comment.
Make the full system poll avoid the occupancy fallback
On an NVIDIA CUDA host where nvidia-smi is missing or fails—the scenario this change explicitly targets—switching this visibility query to the inventory helper does not keep /api/system context-free. Checked main.py::_get_cached_system_gpu_info: immediately after this call it invokes get_visible_gpu_utilization(), and the non-ROCm fallback at hardware.py:2482 still calls _torch_get_per_device_info(), whose mem_get_info attaches the same permanent context. Thus the combined poll still pins the reported ~612 MiB; the new fresh-process test misses this because it calls only get_backend_visible_gpu_info() rather than the combined system-poll path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your code reading is right and I checked it rather than assuming: _get_cached_system_gpu_info does call get_visible_gpu_utilization() straight after the visibility probe, and on an NVIDIA host without nvidia-smi that reaches _torch_get_per_device_info at hardware.py:2482 and takes the context.
I am not making the change, because that path genuinely consumes what it asks for. main.py:1833 reads vram_used_gb from that result and :1843 its vram_utilization_pct, which is exactly what the floating monitor and Settings, Resources display. Line 2482 is also the only Intel XPU path, and its _torch_get_per_device_info branch exists specifically to keep a device whose free-memory query fails. There is no context-free source for USED VRAM on a host with no nvidia-smi; device properties answer capacity, not occupancy. Suppressing it would blank live VRAM usage on every such host, and a wrong or missing number that silently changes what the UI reports ranks above the context saving here. test_nvidia_torch_fallback_keeps_using_occupancy already pins that.
There is an honest residue in your favour, though it is a description matter rather than a code one: this PR body says "on ROCm, or an NVIDIA host with no nvidia-smi on PATH, that is every install", which overstates the NVIDIA-without-nvidia-smi case, where the net saving across the combined poll is zero. I will correct the description.
_rocm_props_total_is_carve_out delegated the whole decision to _rocm_classify_unified_memory, which answers unified or not-unified and never "cannot tell". It knows an APU by hipDeviceProp_t.integrated or by a hardcoded gfx1150/1151/1152 set, so a gfx1103 Phoenix iGPU whose runtime leaves that flag at 0 came back not-unified, the inventory kept props.total_memory, and the endpoint published the dedicated carve-out as the whole device. On such a part that is an 8 GiB-class number standing in for the GTT pool, and it gates which models are offered. clr only fills the flag in from the HSA "agent is APU" property from ROCm 6.1.2 on; before that an APU answers 0 exactly like a discrete card, and the last field of torch.version.hip is a build number, so 6.1.2 cannot be told from 6.1.0. The flag is therefore trusted from 6.2 on, and on anything older, on a wheel that omits the field, and when the classifier itself raises, the driver total is worth a context. A total that is too small hides models; the context does not. Discrete cards on a current ROCm runtime keep the context-free inventory, which is the case this path was added for.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
GET /api/systemreaches_torch_get_per_device_info, which callstorch.cuda.mem_get_info. That call creates a primary context the process never gives back. The endpoint is polled every 5s by the root-mounted floating monitor and every 3s by Settings, Resources, so on any host where the smi shortcut does not answer, an otherwise idle Studio permanently acquires a context from telemetry alone. On ROCm that is every install. Scoping this honestly after review: on an NVIDIA host with no nvidia-smi the net saving across the combined poll is zero, because the same request also asksget_visible_gpu_utilization()for live occupancy, and there is no context-free source for USED VRAM. That call is left alone deliberately (see below).The structural cause:
_torch_get_per_device_infoconflates inventory (name and total capacity) with live occupancy (used). Only occupancy needs a context. Andget_backend_visible_gpu_infodiscardsused_gbentirely, building each device fromindex,index_kind,visible_ordinal,nameandtotal_gb(hardware.py:3382-3390).Measured
Fresh process, per-PID via nvidia-smi, GPU 5 on a B200:
import torch,get_device_propertiesandmemory_reservedall cost 0 MiB;mem_get_infoandsynchronizecost 612 MiB, permanently.Endpoint level, same process shape and device:
_torch_get_per_device_info_torch_get_device_inventoryEvery field the caller actually consumes is identical. Raw bytes agree exactly:
get_device_properties(0).total_memory == mem_get_info(0)[1] == 191505498112, delta 0, in both orderings.Three changes
1. An inventory path that needs no context.
_torch_get_device_inventoryanswers name and total fromget_device_properties, andget_backend_visible_gpu_infouses it. Nothing that genuinely needs live free memory was touched.2.
clear_gpu_cacheno longer synchronises a device with nothing to synchronise.torch.cuda.synchronize()creates a context;empty_cacheandipc_collectdo not. The guard sumsmemory_reserved(i)acrossdevice_count()rather than reading the current device only, so a process that allocated solely on a non-current device is not skipped.empty_cacheandipc_collectstill run unconditionally, which an existing test pins.Worth recording: I first added a
try/exceptaround that branch to match the XPU branch, then removed it. The missingtry/exceptis deliberate and load-bearing.diffusion.py:5652andvideo.py:5552both comment thatclear_gpu_cache()raises on a sticky CUDA fault, and both wrap the unload intry/finallyto decrement a waiter counter on that raise. Swallowing there would have silently broken both.3. Linux ROCm tries sysfs before torch. The sysfs branch was Windows-only, so Linux ROCm always fell to torch and then
_overlay_system_wide_vramoverwrote the result with sysfs figures anyway: a context spent producing numbers that were immediately discarded.With one qualification found while checking: the overlay does not always overwrite. It declines per device on no PCI match, any visibility mask, a device-count mismatch, or a total mismatch over 10 percent (APU and MI300 partition cases). So sysfs-first is taken only when it covers every visible device, and otherwise the unchanged torch path runs.
Deliberately not changed
_reconcile_rocm_unified_memoryand_reconcile_primary_rocm_unified_memoryalso reach_torch_get_per_device_infofrom the same poll, on the ROCm path where amd-smi succeeds. They genuinely consumeused_gb, so a ROCm APU with working amd-smi still acquires a context. Early-returning on totals alone would assumeprops.total_memoryequals themem_get_infototal on a ROCm APU, which I cannot verify on an NVIDIA box, and getting it wrong would break the exact APU correction that code exists for. Left alone on purpose.The same caution applies generally: totals parity is verified on NVIDIA only. In-file precedent supports it on ROCm, since
_rocm_windows_per_device_vramalready takes totals frompropsand calls them reliable, but ROCm APU and Intel XPU equality is unverified here.Tests
New
tests/test_system_poll_no_cuda_context.py, 22 tests, including subprocess-based assertions that the poll path leaves the process context-free.18 hardware, GPU, VRAM and system test files:
Identical failure names on both sides. Widened to include the diffusion and video backends: 10 failed, 1354 passed, the extra name being
test_video_backend.py::test_a_quantized_reference_load_resolves_the_reference_denoiser, which is pre-existing at the base commit and reproduces with these changes removed.Two existing tests needed updating because the endpoint legitimately calls a different helper now:
test_gpu_selection.py:382patches_torch_get_device_inventory, andpatch_targets.jsonrecords the rename. I hand-edited that one key rather than re-snapshotting, which would have swept in unrelated pre-existing drift.ruff checkclean on all three touched files.What this deliberately does not change
_reconcile_rocm_unified_memory,_reconcile_primary_rocm_unified_memoryandget_visible_gpu_utilizationalso reach_torch_get_per_device_infofrom the same poll, and theygenuinely consume
used_gb:main.py:1833readsvram_used_gband:1843itsvram_utilization_pct, which is what the floating monitor and Settings, Resources display. Deviceproperties answer capacity, not occupancy, so there is no context-free substitute on a host without
an smi tool, and
hardware.py:2482is additionally the only Intel XPU path, whose branch exists tokeep a device whose free-memory query fails. Those paths keep paying for a context on purpose;
test_nvidia_torch_fallback_keeps_using_occupancypins it.So the saving is real on the ROCm and inventory paths and zero on the NVIDIA-without-nvidia-smi
occupancy path. A wrong or blank number in the UI is worse than 612 MiB.