Repository navigation
Studio: cache and coalesce nvidia-smi reads in the backend - #11995
Conversation
Every nvidia-smi call in studio/backend now goes through utils/hardware/gpu_query.run_nvidia_smi, a drop-in for subprocess.run: - concurrent identical queries share one child process - static queries (-L, name/memory.total, compute_cap) are cached for 600 s and dropped on hardware re-detection - live queries are cached for 1 s by default (fit checks, placement, GPU selection) and for 3 s with stale-while-revalidate under display_reads() (the hardware panel polls) - a generation counter (utils/gpu_memory_events.py) is bumped on every model load/unload, training start/stop and llama-server spawn; a decision-critical read never reuses an older sample - fresh_reads() bypasses the cache for VRAM settle loops and fenced readings - the caller waits only its own timeout; subprocess.run's unbounded wait() after killing a child stuck in the driver no longer holds a request - when the CLI does not answer: last good answer (for fit checks only a recent same-generation sample, rewritten to the lowest free / highest used seen), then NVML via studio/nvidia_probe.py, then the caller's existing fallback exactly as before Non-NVIDIA hosts, missing nvidia-smi and non-zero exits are unchanged. UNSLOTH_GPU_QUERY_CACHE=0 disables the layer.
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. |
A timed-out fit check used to get the lowest free memory seen in the last 60 s. Memory another process allocated since then was invisible to it, while the old code fell back to a fresh torch or NVML reading. Fit checks now take only a new NVML reading or the caller's own fallback, never join a child older than the critical TTL, and do not start another child behind a stuck one. Display reads may be at most 60 s stale instead of 300 s.
…n timeout fallback A fit check (placement, GPU auto-selection, training coexistence) reused a reading up to 1 s old or joined a query already in flight. Another process's allocation raises no Studio event, so that window could pick a GPU that had just filled up. Critical reads now always start their own nvidia-smi and wait their whole timeout, as before. The NVML stand-in on a hung CLI is removed: it returned the parent GPU for a MIG slice and ignored CUDA_VISIBLE_DEVICES, while llama.cpp's own NVML branch handles both. Static reads no longer join a query started before a re-detection.
…ncurrent fit checks A PATH change must not be answered by a different nvidia-smi's cached output. The lookup never raises. Adds a 16-thread test that every fit-check answer is a reading taken after its call began, and makes the MIG fallback test fail when a whole-GPU NVML answer stands in for llama.cpp's own fallback.
|
@codex security review |
🛡️ 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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 490dba717e
ℹ️ 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".
| @_invalidates_gpu_memory("training start") | ||
| @owned_job() |
There was a problem hiding this comment.
Invalidate when the training worker changes GPU residency
When training starts asynchronously, this decorator's exit invalidation occurs immediately after proc.start() and start_training() returns, before the worker actually loads anything onto the GPU. A display poll in that interval can therefore cache the pre-load reading under the newest generation, and the later allocation does not invalidate it; stopping has the symmetric problem because stop_training() only queues a stop request before its decorator exits. Invalidate from the worker-resident and worker-termination paths so the hardware panel refreshes when VRAM actually changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Display-only: fit, placement and training coexistence checks always run a new nvidia-smi and never read this cache. A display reading is at most one poll behind the worker's allocation (3 s TTL, then one background refresh), which is the intended trade-off for the panels.
On a congested driver nvidia-smi times out and the torch fallback's device queries fail with it, so /api/system reported available: False and Settings > Resources said "No GPU detected" on a host that had reported its GPU one poll earlier. get_backend_visible_gpu_info now keeps the last inventory that found devices (per device type and visibility mask) and returns it marked stale, with live usage unknown, until a probe answers again. Only nvidia-smi answering with zero rows counts as proof there is no GPU; a failed read with no earlier inventory still reports none.
|
Added 01dbe8e: on a congested driver nvidia-smi times out and the torch fallback fails with it, so |
… key the last good inventory on ROCR_VISIBLE_DEVICES
…no pre-load display reading on timeout
…are physical inventory
…heck=True failures replace cached answers
…wait on a hung inventory child
…les; an older inventory probe never overrides a newer one
…instead of serving the previous one
…ds behave as on main
|
Codex Review: Didn't find any major issues. 🚀 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". |
…#11995) * Studio: cache and coalesce nvidia-smi reads in the backend Every nvidia-smi call in studio/backend now goes through utils/hardware/gpu_query.run_nvidia_smi, a drop-in for subprocess.run: - concurrent identical queries share one child process - static queries (-L, name/memory.total, compute_cap) are cached for 600 s and dropped on hardware re-detection - live queries are cached for 1 s by default (fit checks, placement, GPU selection) and for 3 s with stale-while-revalidate under display_reads() (the hardware panel polls) - a generation counter (utils/gpu_memory_events.py) is bumped on every model load/unload, training start/stop and llama-server spawn; a decision-critical read never reuses an older sample - fresh_reads() bypasses the cache for VRAM settle loops and fenced readings - the caller waits only its own timeout; subprocess.run's unbounded wait() after killing a child stuck in the driver no longer holds a request - when the CLI does not answer: last good answer (for fit checks only a recent same-generation sample, rewritten to the lowest free / highest used seen), then NVML via studio/nvidia_probe.py, then the caller's existing fallback exactly as before Non-NVIDIA hosts, missing nvidia-smi and non-zero exits are unchanged. UNSLOTH_GPU_QUERY_CACHE=0 disables the layer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: never answer a fit check from an old nvidia-smi reading A timed-out fit check used to get the lowest free memory seen in the last 60 s. Memory another process allocated since then was invisible to it, while the old code fell back to a fresh torch or NVML reading. Fit checks now take only a new NVML reading or the caller's own fallback, never join a child older than the critical TTL, and do not start another child behind a stuck one. Display reads may be at most 60 s stale instead of 300 s. * Studio: fit checks always read nvidia-smi afresh; keep llama.cpp's own timeout fallback A fit check (placement, GPU auto-selection, training coexistence) reused a reading up to 1 s old or joined a query already in flight. Another process's allocation raises no Studio event, so that window could pick a GPU that had just filled up. Critical reads now always start their own nvidia-smi and wait their whole timeout, as before. The NVML stand-in on a hung CLI is removed: it returned the parent GPU for a MIG slice and ignored CUDA_VISIBLE_DEVICES, while llama.cpp's own NVML branch handles both. Static reads no longer join a query started before a re-detection. * Studio: key cached nvidia-smi answers on the resolved binary; test concurrent fit checks A PATH change must not be answered by a different nvidia-smi's cached output. The lookup never raises. Adds a 16-thread test that every fit-check answer is a reading taken after its call began, and makes the MIG fallback test fail when a whole-GPU NVML answer stands in for llama.cpp's own fallback. * Studio: invalidate the GPU memory cache around the sd.cpp load thread * Studio: keep the last good GPU inventory when a probe times out or fails On a congested driver nvidia-smi times out and the torch fallback's device queries fail with it, so /api/system reported available: False and Settings > Resources said "No GPU detected" on a host that had reported its GPU one poll earlier. get_backend_visible_gpu_info now keeps the last inventory that found devices (per device type and visibility mask) and returns it marked stale, with live usage unknown, until a probe answers again. Only nvidia-smi answering with zero rows counts as proof there is no GPU; a failed read with no earlier inventory still reports none. * Trim comments in nvidia-smi query cache change * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio tests: reset the last good GPU inventory between tests * Studio: drop a cached inventory once nvidia-smi answers with no rows; key the last good inventory on ROCR_VISIBLE_DEVICES * Studio: a failed or empty nvidia-smi answer replaces the cached one; no pre-load display reading on timeout * Studio: cache the nvidia-smi GPU inventory for 60 s, like the eGPU-aware physical inventory * Studio: an expired GPU inventory waits for a new nvidia-smi answer; check=True failures replace cached answers * Studio: treat nvidia-smi 'No devices were found' as an answer; never wait on a hung inventory child * Studio: invalidate GPU readings on STT and diffusion training lifecycles; an older inventory probe never overrides a newer one * Studio: /api/system reads a new nvidia-smi answer on each cache miss instead of serving the previous one * Studio: keep the last good GPU inventory on NVIDIA only; other backends behave as on main * Trim comments in nvidia-smi query cache change --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
The Studio backend shells out to
nvidia-smifrom every hardware poll, fit check and model load. On a busy multi-GPU host with a congested driver (measured on 8x B200) each call took 25 to 100 s,/api/system/hardwaretook up to 671 s, one utilisation read 221 s,get_device64 s andget_gpu_summary55 s, and pages stalled for minutes.Two things compound:
nvidia-smi, so a page that opens six panels starts six CLIs on a driver that is already struggling (measured below: 172 CLI runs for 178 hardware requests).subprocess.run(..., timeout=5)does not bound the call. On timeout it kills the child and then callsprocess.wait()with no deadline (CPythonsubprocess.run, POSIX branch), so a child stuck in a driver ioctl holds the request until the kernel lets it die. After that the caller falls back to torch, which queries each GPU withmem_get_infoand opens a CUDA context on it.Change
One helper,
utils/hardware/gpu_query.py, that everynvidia-smicall in the backend now goes through (run_nvidia_smi). It is a drop-in forsubprocess.run: sameCompletedProcess, sameFileNotFoundError/OSError/TimeoutExpired, so every caller keeps its parsing and its existing fallback chain.static(GPU list, names, total memory, compute capability): cached 60 s (the same TTL as the eGPU-aware physical inventory), dropped on hardware re-detection. An expired entry waits for a new answer rather than being served while one refreshes, so an unplugged card is not reported. A read never joins a child started before a re-detection, nor one already running longer than its own timeout (a hung child).display(the hardware panel pollers, insidedisplay_reads()): 3 s, then stale-while-revalidate with one background refresh, at most 60 s old./api/systemalready has its own 10 s cache, so it usesdisplay_reads(max_stale=0): each miss waits for a new (shared) reading, and only a hung CLI falls back to the last good one.critical(everything else: fit checks, llama.cpp placement, GPU auto-selection, training coexistence, settle loops): never cached and never shared. Every call starts its ownnvidia-smiafter the call began and waits its whole timeout, exactly as onmain. Memory another process allocates raises no Studio event, so no reuse window is safe for a decision; an instrumented model load issued one critical read with or without caching, so this costs nothing measurable. Its answer still refreshes the display cache.utils/gpu_memory_events.pyholds a generation counter, bumped on entry and on exit of every load, unload and training start or stop (llama.cpp, transformers, orchestrator, diffusion, video, sd.cpp, audio, speech-to-text, RAG embedding server, LLM and diffusion training) and right after eachllama-serverspawn. The next display read then fetches afresh, so the panel shows the new usage at once.TimeoutExpired, so the caller's own fallback runs exactly as before (for llama.cpp that is its MIG- andCUDA_VISIBLE_DEVICES-aware NVML branch).nvidia-smiresolves to onPATH, so aPATHchange is never answered by another binary's output. The lookup never raises.fresh_reads()forces a new reading for display-context code that compares consecutive samples (VRAM settle loops) or pairs a reading with another measurement under a fence.display_reads()is used only by the display pollers:/api/train/hardware,/api/train/hardware/visibleand the/api/systempanel poll (notrefresh_memory=true).Failures: a missing
nvidia-smiand otherOSErrors pass through untouched. A non-zero exit or an answer with no rows (for example exit 6, "No devices were found") is returned to the caller as before, is never served from the cache, and replaces any older cached answer, so a card that went away is not reported from the cache. So AMD/ROCm (amd-smi, sysfs), Apple (ioreg/MLX), Intel XPU, CPU-only and Windows paths behave exactly as before. In-process torch reads (mem_get_info,memory_allocated,get_device_properties) are already cheap and live, and are untouched.UNSLOTH_GPU_QUERY_CACHE=0turns the whole layer off (plainsubprocess.run). The TTLs can be tuned withUNSLOTH_GPU_QUERY_{STATIC,DISPLAY}_TTLandUNSLOTH_GPU_QUERY_BACKGROUND_TIMEOUT.Site inventory
Every place the backend runs
nvidia-smi(7 command lines):nvidia.get_physical_gpu_count-Lnvidia._query_gpu_inventory(physical inventory, backend-visible GPU info,/api/system/gpu-visibility,include_details)index,name,memory.totalLlamaCppBackend._cuda_compute_capsindex,compute_capLlamaCppBackend._probe_nvlink_topologytopo -mcache=False:_nvlink_topologyalready caches it per process and has its ownrefresh=Truenvidia.get_primary_gpu_utilizationdisplay_reads()nvidia.get_visible_gpu_utilizationdisplay_reads()LlamaCppBackend._get_gpu_memoryindex,memory.free,memory.totalConsumers of the live readings, by category:
GET /api/train/hardware(get_gpu_utilization)GET /api/train/hardware/visiblemain._get_cached_system_gpu_info(/api/system)refresh_memory=trueget_gpu_memory_info/_context_free_cuda_memory_info(get_gpu_summary,/api/system/hardware,log_gpu_memory)vram_free_gbfeeds training-method auto-selectionauto_select_gpu_idsroutes/training_vram.py(2 reads)LlamaCppBackend._get_gpu_memory/_get_gpu_free_memory(7 callers in llama_cpp,/api/inferencepre-load path, RAG embedding server andembeddings._resolve_auto)--fitdecisionLlamaCppBackend._wait_for_vram_settleInferenceOrchestrator._wait_for_worker_vram_settleInferenceOrchestratorpost-handoff reading (under_send_order_lock)routes/inferencereclaimable-VRAM_read_liveroutes/inference._wait_for_native_audio_gpu_free_gbCounts: 7 CLI sites (4 static, 3 live). 13 live consumer sites: 3 display, 5 critical (
training_vramcounted as its 2 reads, the llama.cpp probe once for its 10 callers), 5 fresh. Unchanged and not routed: 29 in-processmem_get_info/trusted_mem_get_infosites, plus the torchmemory_*/get_device_properties/device_countreads, amd-smi, sysfs, ioreg and Windows perf counters.Measurements
Host: 8x NVIDIA B200, driver currently healthy (
/usr/bin/nvidia-smiabout 0.15 s). The GPUs also run other jobs, so free memory, and which GPU a load picks, varies between runs. Studio was built from this branch and frommainwithUNSLOTH_STUDIO_HOME=<scratch> ./install.sh --localandUNSLOTH_TORCH_INDEX_URL=https://download.pytorch.org/whl/cu130, then driven over HTTP. Times are median / max in seconds. "Page" means the six hardware requests the Settings / System view fires, sent concurrently. "Burst" means 16 concurrent/api/system/hardwarecalls.Real
/usr/bin/nvidia-smi, no shim on PATH (10 sequential calls per endpoint):/api/system/hardware/api/system/hardware?include_details=true/api/train/hardware/api/train/hardware/visible/api/system/gpu-visibilityunsloth/gemma-3-270m-it-GGUFUD-Q4_K_XL, 3 warm loadsnvidia-smiruns for the same 178 requests (counted with a pass-through wrapper): 172 before, 8 after.Slow or hung driver, emulated with a pass-through wrapper that sleeps before calling the real
nvidia-smi(3 calls per endpoint):/api/system/hardware/api/system/hardware?include_details=true/api/train/hardware/api/system/gpu-visibilityThese slow-driver numbers are from the previous revision, in which a fit check could reuse a reading for 1 s or fall back to NVML after a short wait. Fit checks now read afresh and wait their whole timeout, exactly as on
main, so the rows that go through a fit check (/api/system/hardware,include_details=true, page, and the GGUF loads) are expected to match the "before" column on a slow driver rather than the "after" one. The display rows (/api/train/hardware,/api/system/gpu-visibility) and the healthy-driver table above are unaffected: those reads are still cached and shared. This trade was made on purpose: faster fit checks on a slow driver are not worth acting on stale memory numbers.With 12 s per call,
mainanswered/api/train/hardwarefrom the torch fallback (gpu_utilization_pct,temperature_candpower_draw_wall null). This branch answered from the last good reading. A killedsleepexits immediately, so this emulation cannot reproduce a child stuck in the driver, which is what made the 25 to 100 s calls.test_a_child_the_kernel_cannot_reap_does_not_hold_the_callercovers that case: with a runner that returns only after 12 s, each caller gets its answer at its own timeout (5 s, plus 1 s reaping grace), not after the 12 s.Fit checks still see fresh numbers
Live, on both builds: load gemma-3-270m with the real free VRAM, prime a critical read (
/api/system/hardwarereports about 176 GB free), switch the wrapper to report 100 MiB free on every GPU, and start the second load under 1 ms after the primed read returned:CUDA_VISIBLE_DEVICES=4on that run),--fit off -ngl -1CUDA_VISIBLE_DEVICES=7on that run),--fit off -ngl -1--fit on--fit on/api/system/hardwarevram_free_gbafterwardsStudio's own placement check sees the cards as full and hands the load to llama.cpp's
--fitinstead of pinning a GPU, same as onmain.Tests
tests/test_gpu_query_cache.py(38 tests) drives a real executable namednvidia-smion PATH whose answers, latency and exit status each test controls. It covers:UNSLOTH_GPU_QUERY_CACHE=0; results returned as copies.10 of these fail against the previous revision of this PR and pass now. The backend's other tests that touch these paths (60 files, 8481 tests) give identical results on this branch and on the pre-PR base in the same environment.
Five independent reviews of the previous revision (call-site routing, concurrency, compatibility with
main, memory staleness, invocation design) all found the two problems this revision fixes: the 1 s critical reuse window, and a timeout stand-in that bypassed llama.cpp's MIG/UUID handling. Their suites pass on this revision: memory-safety matrix 17/17, regressions 10/10,maincompatibility 138/138 cells, platform contracts 23/23.studio/backend/testsas CI runs it (-n 32, same ignores and-k) on this host, before and after rebasing onto currentmain:mainin the same checkout: sandbox/bubblewrap, cache-dir containment, offline media assembler and similar host-environment tests.conftest.pyresets the cache per test, so one test's fake CLI cannot answer for the next.ruff check,scripts/verify_import_hoist.py(compare mode, every modified file),scripts/lint_duplicate_definitions.py,ruff formatplusscripts/enforce_kwargs_spacing.pyon the new files, and codespell on the new files are clean.Settings no longer says "No GPU detected" on a slow driver
When the driver is congested, nvidia-smi times out and the torch fallback's device queries fail along with it, so
/api/systemreportedavailable: Falseand Settings > Resources showed "No GPU detected" on a host that had reported its GPU one poll earlier.On NVIDIA hosts (CUDA without ROCm),
get_backend_visible_gpu_infonow keeps the last inventory that found devices (per visibility mask) and returns it markedstale: true, with live usage unknown, until a probe answers again. Only nvidia-smi answering with zero rows, or exiting 6 ("No devices were found", as it does after an eGPU is unplugged), counts as proof there is no GPU. An older, slower probe never overrides a newer answer. A failed read with no earlier inventory still reports none, and a different mask never inherits one.Emulated on a B200 with a proxy
nvidia-smiplus failing torch device queries (/api/systemgpu block, query cache off):mainTests:
tests/test_gpu_inventory_stale.py(11). ROCm, XPU, MLX and CPU hosts return the probe's own answer, exactly as onmain. All 13 test files that touch the visibility probe or the route cache pass (991).Not verified
nvidia-smiand are not routed through the helper, but they were not run live.