Repository navigation
Studio: read the NVLink fabric from NVML instead of a 1.2s nvidia-smi shell-out - #10720
Conversation
…-out The P2P gate added in #10646 verifies NVLink between every selected GPU pair before setting GGML_CUDA_P2P. It reads nvidia-smi topo -m, which costs ~1200ms on an 8x B200, paid once per process on the model-load path. Ask the driver instead. NVML ships with the driver, so it is present exactly when nvidia-smi is, and ctypes against libnvidia-ml.so.1 needs no new dependency: nvidia-ml-py is not installed in a Studio env. The same 8x B200 answers in ~230ms with no subprocess at all, and the verdict is identical: 56 of 56 ordered pairs, both directions. Evidence stays per pair. nvmlDeviceGetP2PStatus with the NVLink capability index asks about one pair; an active link to an NVSwitch proves only that the GPU is attached to a switch, and switch fabrics can be partitioned, so switch attachment is never read as all-pairs reachability. Everything short of a complete answer falls back to topo -m and then to no P2P: missing library or symbol, any non-zero return, fewer than two devices, a partial walk, or a positive contradicted by zero live NVLinks on an endpoint. A usable topo -m proved nvidia-smi had enumerated the selection; NVML does not carry that implication, so an NVML matrix is only matched against ids known to come from nvidia-smi. Also prime the cache on the existing startup warm thread so the first load reads it warm, validate the topo key set rather than its length, and add UNSLOTH_P2P_TOPO_CROSSCHECK=1 plus probe reporting to qualify the fast path on PCIe-only and partially bridged hosts, which were not available to test here.
A separate warm stage broke two startup guards, correctly. Every importing stage needs an entry in _STAGE_PACKAGE so a failed import is purged rather than left half-cached, and inference_backend is exempt only because it imports first-party code. The topology prime imports that same module, so it belongs on that stage instead of asking for an exemption of its own. The prime is wrapped so it can never fail the stage it rides: a warm miss costs latency, and the gate re-probes on demand and fails closed by itself.
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. |
Three fixes from review. An NVML P2P status that is not OK is not automatically a denial. Statuses 1 to 5 say not supported and give a reason; 6 is UNKNOWN, and a newer driver could return something past the end of the enum. Recording either as NO-NVLINK made the matrix look conclusive and denied topo -m the chance to confirm a fabric that is really there, so both now fall through. The startup prime runs early, possibly mid driver initialisation. It went through the same cache as the load path, so a miss there kept P2P off for the life of the process even once the topology became readable. It now primes with cache_failure=False: a failed prime leaves the cache cold and the load path probes as it would have. A successful prime still caches, and the load path still caches its own miss exactly as before. A driver install can leave nvml.dll in the NVSMI directory rather than a DLL search path, the same way it does nvidia-smi.exe. Include that location, and System32, among the Windows candidates, mirroring _nvidia_smi_executable.
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f70743acaa
ℹ️ 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".
| f"{sorted(topo_yes - nvml_yes)} are NVLink to topo -m but not to NVML. " | ||
| "This is the\nconservative direction: Studio would simply not enable P2P " | ||
| "for them." |
There was a problem hiding this comment.
Describe the topo-only mismatch fallback accurately
When topo -m reports NVLink for a pair that NVML denies, this diagnostic says Studio would leave P2P disabled, but _probe_interconnect_matrix() does the opposite: any disagreement returns the topo matrix, so the pair is accepted. Operators running this probe to qualify an untested fabric therefore receive an incorrect description of the behavior Studio will actually use; either report that topo -m wins or change the fallback policy to match this message.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not quite: the topo matrix is returned on disagreement only under UNSLOTH_P2P_TOPO_CROSSCHECK=1, which is off by default. The env check is the guard on that branch, and with it unset the NVML matrix is returned instead, so a topo-only pair is not enabled and the message is accurate for the default path. That said the message never mentioned the exception, which is a fair thing to misread, so 0230737 now spells out both: NVML answers first by default, and the cross-check makes topo -m win any disagreement.
…hands _GPU_IDS_ARE_PCI_INDICES records where _get_gpu_memory last got its ids, which is not the same question as whether THIS selection is nvidia-smi indexed. An explicit pick comes from the UI's PCI-ordered picker and is PCI-ordered by construction, but a transiently missing or off-PATH nvidia-smi sends the unrelated memory query down the torch fallback and flips that flag process wide. The NVML provenance gate then read the explicit ids as CUDA ordinals and vetoed a verified fabric. The two veto entry points and _apply_datacenter_env now take the caller's provenance, and load_model passes it, keeping the process-wide flag only as the default for callers that do not know. Same reasoning as the existing launch_order_pinned comment two lines up. Also state the probe's mismatch message precisely: NVML answers first by default, so a topo-only pair is not enabled, and UNSLOTH_P2P_TOPO_CROSSCHECK=1 is what makes topo -m win instead.
…k nobody wants Three from review. ctypes has no timeout. The shell-out this replaced ran under one, so a wedged driver that blocks rather than returning an error could hang nvmlInit_v2 and with it the model load, and never reach the fallback that has a timeout of its own. The walk now runs on a daemon thread with a wall-clock bound; a stalled call is abandoned and the caller falls through to topo -m. Publication was unconditional, and the generation counter only guards against a refresh. A load whose own probe failed transiently could therefore overwrite a matrix the startup prime had already published, turning P2P off for every later load. A miss no longer replaces a cached success. The prime also ignored the opt-outs. UNSLOTH_DISABLE_DC_TUNING=1, UNSLOTH_DISABLE_DC_P2P=1 and a falsy GGML_CUDA_P2P all mean the answer can never be used, and the load path already skips the probe for exactly that reason.
|
Confirmed the 1.3s topo -m shell-out from #10646 lands once per model load in studio/backend/core/inference/llama_cpp.py, and the NVML path keeps the same fail-closed fallback plus the active-link contradiction guard. Will get this reviewed. |
|
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". |
Bisected from CI. test_idle_loop_resets_timer_for_same_repo_different_variant failed on this branch in 3 of 3 runs and on none of 14 other branches, and a branch identical to this one except with the prime removed did not fail it. The prime sat inline in the inference_backend stage, so it could spend its NVML bound plus the shell-out timeout before the transformers and datasets stages even started. That is reachable in the test suite, where a fake torch reporting datacenter GPUs is installed process-wide for the worker: the warm thread then walks past every guard into the real probe and stalls its worker long enough to tip a 0.05s idle threshold in an unrelated async test. It now runs on a daemon thread of its own and returns immediately, so it cannot delay a stage or anything sharing the process. Nothing waits on it: the gate re-probes on demand, so a prime that never finishes costs one load its head start and nothing else. This is the half of the earlier delaying-later-stages report I did not fix; I addressed the opt-out skip and left the blocking.
|
Codex Review: Didn't find any major issues. Swish! 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: Didn't find any major issues. Swish! 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". |
Third time this prime has perturbed CI. Making it non-blocking to the warm sequence was not enough: the thread still ran the full probe, including a nvidia-smi subprocess that can run for its whole timeout, and on a worker where a fake torch reports datacenter GPUs that lands next to tests whose entire assertion is that the event loop was not blocked. Two more of them failed on this branch and on none of 5 recent main runs. A prime is an optimisation, so it should only take the cheap path. It is now NVML-only: if NVML cannot answer, the cache stays cold and the load path does the slow probe inline exactly as it would have without a prime. The production benefit is unchanged on the hosts that have NVML, which is every host with a driver, since nvidia-smi is itself an NVML client. It also publishes only a success, so the earlier cache_failure argument now falls out of the shape rather than needing a flag at this call site.
UNSLOTH_P2P_TOPO_CROSSCHECK=1 is the mechanism this PR offers for qualifying the NVML fast path on the fabrics it could not test. It did not work in a Studio process. The cross-check lives in _probe_interconnect_matrix, which only the load path reaches. prime_nvlink_topology calls _probe_nvml_nvlink_topology directly and publishes to the cache, and the warm stage always primes before any load, so the cache was warm by the time the gate asked and the two tiers were never compared. That is the shipping configuration, not a corner case. Measured on the 8x B200 before this commit: with the variable set, a prime followed by a gate call spawned zero nvidia-smi and returned the NVML verdict unchallenged. The consequence is not only a missing log line. On a host where the tiers disagree, topo -m is supposed to win and veto; instead _p2p_veto_reason returned None and P2P was enabled, which is the #10613 failure the gate exists to prevent, reached through the flag meant to guard against it. The prime now stands down while the variable is set and leaves the cache cold, so the load path runs both tiers inline. That is what the variable already advertises ("costs the slow probe on every process"), and it keeps the prime's rule that it may pay the cheap path and nothing else: no shell-out is added to a background thread, so the CI timing coupling fixed earlier in this branch stays fixed. Default behaviour is untouched. Without the variable the prime still publishes an NVML success, the fast path still spawns no nvidia-smi, and the warm read is still ~0.0001 ms. Two tests, both of which fail without the change: one on prime_nvlink_topology directly, one end to end in the order Studio runs it (warm stage primes on its own thread, then the gate is asked) asserting that the slow tier really ran and won the disagreement.
|
Verified this on an 8x B200 NVSwitch host, the same class the numbers in the description were measured on, plus a simulated platform matrix for the classes that box cannot represent. One real defect found and fixed in 4a9b472; everything else held up. The defect: the prime retired the cross-check
The cross-check lives in
Not just a missing log line. On a host where the tiers disagree, Agreement, measured independentlyA harness that does its own NVML walk and its own Complete key sets, not just positive sets. Byte-identical Timing, 10 fresh processes per path, orders alternated
About 3.9x, against the 5x in the description. This box is shared, so both paths read slower than yours; the ratio is the comparable part. Zero Platform matrix, 33 scenarios, each run against this branch and against the merge base[Linux, WSL, Windows, macOS] x [NVIDIA datacenter NVLink, NVIDIA datacenter PCIe, partially bridged, NVIDIA consumer, AMD/ROCm, CPU-only], plus every NVML failure mode: missing symbol, init failure, count failure, partial handle walk, partial pair walk, status UNKNOWN (6), an unknown future status (99), OK contradicted by zero active links, Exactly one behaviour change versus the merge base, and it is the conservative direction: a synthetic host where NVML denies a link Backwards compatibility holds where it matters most. These classes load zero NVML and spawn zero subprocesses, exactly as before: L40S, RTX 6000 Ada, consumer 3090/4090 on Linux/WSL/Windows, AMD ROCm on Linux and Windows, CPU-only, and macOS. Every NVML failure mode falls through to Concurrency and lifetime
CompatibilityEvery Python in The no-new-dependency claim checks out: the full walk runs in a Suites
Still not qualifiedSame gap as before, and I could not close it: no PCIe-only or partially bridged multi-GPU host was available here either, so the NVML capability index reading OK on a PCIe-only box remains unconfirmed empirically. Windows One note, no change made: |
test_the_prime_never_blocks_the_warm_sequence patched _nvlink_topology, but _prime_nvlink_topology goes through prime_nvlink_topology, which calls _probe_nvml_nvlink_topology directly. The patch therefore never ran: the probe stayed on the autouse fixture's NVML-absent default and returned immediately, so the worker was already dead by the time `assert worker.is_alive()` looked at it. Measured on this tree before the change: the patched function was called 0 times and the worker was not alive 0.5s in, so that assertion was passing on timing rather than on behaviour and could fail on a loaded runner. The elapsed-time assertion was still doing real work, so only the patch target changes. 30 consecutive runs of the test, 0 failures.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
Comments and docstrings only, AST-verified against 8b6c067. The load-bearing facts stay: the #10613 contradiction guard, the NVSwitch partition argument, why the prime must not shell out, and why torch ordinals cannot index an NVML matrix. What went is the restatement around them. Comment lines added by this branch in the two source files: 59 to 29.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
Follow-up to #10646, which fixed #10613 by gating
GGML_CUDA_P2Pon a confirmed NVLink fabric instead of a product name. That gate readsnvidia-smi topo -m, and the shell-out is slow.Measured on an 8x B200 host:
nvidia-smi --query-gpu=index,compute_capnvidia-smi --query-gpu=index,memory.free,memory.totalnvidia-smi topo -mThe cost lands once per process, on the model-load path. It is narrow (only multi-GPU hosts whose cards are NVLink-capable by name ever probe) but it is real, and
topo -mis by far the most expensive of the three: it walks the fabric rather than reading per-device properties.What changes
Ask the driver directly. NVML ships with the driver, so it is present exactly when
nvidia-smiis, sincenvidia-smiis itself an NVML client.nvidia-smispawnsThe affected class gets roughly 5x faster and stops spawning a subprocess entirely. Every other class loads nothing new: zero NVML loads and zero subprocesses on consumer, single-GPU, L40S, RTX 6000 Ada, ROCm and CPU, exactly as before. The result is cached for the process and primed in the background at startup, so the first model load reads it warm at 0.004 ms.
No new dependency.
nvidia-ml-pyis not declared inpyproject.toml'sstudioextra, anystudio/backend/requirements/*.txt, either installer, or torch's transitive deps, and it is absent from a real installed Studio venv. The two references in the tree are a Colab pip-freeze snapshot and a pin for the isolated.venv_llmcompressorsidecar, neither of which reaches the backend. So this goes throughctypesagainstlibnvidia-ml.so.1/nvml.dll. Only opaque handles andunsigned intout-params cross that boundary, so there is no struct layout to get wrong across driver versions.Evidence stays per pair
nvmlDeviceGetP2PStatus(a, b, NVML_P2P_CAPS_INDEX_NVLINK)asks about one pair. It agrees withtopo -mexactly on the 8x B200: 56 of 56 ordered pairs NVLinked, in both directions, zero disagreement either way.What this deliberately does not do is infer connectivity from switch attachment. An active link whose remote endpoint is an NVSwitch proves the GPU is attached to a switch, and switch fabrics can be partitioned, so "every GPU has a switch link" is not read as "every pair is reachable". An earlier version of this patch made that inference and it was wrong.
Index spaces line up, which is what makes this a drop-in: NVML and
nvidia-smireport byte-identicalbusIdfor all 8 devices, and both ignoreCUDA_VISIBLE_DEVICESidentically (8 GPUs visible underCUDA_VISIBLE_DEVICES=2,5and under=7, with NVML index 0 pinned to bus51:00.0either way).Fail-closed behaviour is unchanged
Evidence chain: NVML, then
nvidia-smi topo -m, then no P2P. Anything short of a complete answer falls through: missing library or symbol, any non-zero NVML return, fewer than two devices, a partial walk, or a positive contradicted by zero live NVLinks on an endpoint.One implication needed restating. A usable
topo -mprovednvidia-smihad enumerated the selection, so the ids indexed the matrix verbatim. NVML does not carry that implication: it answers from the driver even whennvidia-smidid not, and_get_gpu_memory's torch fallback returns CUDA ordinals, which index the matrix wrongly underFASTEST_FIRST. So an NVML matrix is only matched against ids known to have come fromnvidia-smi, and otherwise vetoes.Also hardened while here: the
topo -mparser now validates the exact pair key set rather than the matrix length, since a matrix of the right size built from the wrong keys would previously have passed.What is not qualified
No PCIe-only or partially bridged multi-GPU host was available to test. I have not empirically confirmed that the NVLink capability index never reads OK on a PCIe-only box. Three things address that:
UNSLOTH_P2P_TOPO_CROSSCHECK=1runs both tiers and logs any disagreement, preferringtopo -mwhen they differscripts/p2p_integrity_probe.pynow prints the NVML verdict beside thetopo -mverdict and flags a mismatch, so a report from such a host supplies the missing dataAn NVML-positive with a topo-negative pair is the result that would matter. The gate is no weaker than before either way, since every inconclusive path lands on today's behaviour.
Testing
test_datacenter_gpu_tuning.py(102 pre-existing, unchanged, plus 26 new) covering each NVML failure mode, the contradiction guard, cross-island vetoes, provenance, shutdown balance, the probe's time bound, the cache-overwrite protection, and single-GPU and empty selections so no vacuousall([])can approve anythingmainon frozen worktrees, comparing failure id sets rather than countsThe comparison earned its keep twice.
It found two failures unique to this branch, both real. A separate
nvlink_topologywarm stage tripped the_STAGE_PACKAGEpurge guard, since every importing stage needs a purge mapping andinference_backendis exempt only because it imports first-party code. The prime imports that same module, so it rides that stage instead of asking for an exemption of its own. Those guards are unmodified.Then CI turned up a third, which took a bisect to pin down.
test_openai_auto_switch.py::test_idle_loop_resets_timer_for_same_repo_different_variantfailed here in 3 of 3 runs and on 0 of 14 other branches, and never reproduced locally, including under the exact CI command with-n 4. A throwaway branch identical to this one except with the prime removed did not fail it, which settled the question. The coupling was not through imports, it was through time: the prime ran inline in the warm stage, so it could spend its NVML bound plus the shell-out timeout before the stages behind it started, and the suite installs a fake torch reporting datacenter GPUs process-wide for a worker, so the warm thread walked past every guard into the real probe and stalled that worker long enough to tip a 0.05s idle threshold in an unrelated async test. The prime now runs on a daemon thread of its own and returns in about 0.4ms rather than blocking for up to 20s.(Python 3.13)is now down to the one failure every other branch has.Final comparison, both suites run on frozen worktrees:
main10a95daFailure sets are identical: 0 unique to the baseline, 0 unique to this branch. The extra passes are the new tests. That sweep was run at the time; the branch has taken review fixes since, and the
-n 4re-run described above also showed 0 failures unique to this branch.Closes nothing on its own; this is a performance follow-up to #10646 and #10613.