Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: read the NVLink fabric from NVML instead of a 1.2s nvidia-smi shell-out (#10720)
Daniel Han0fe1e502321c
diff --git a/scripts/p2p_integrity_probe.py b/scripts/p2p_integrity_probe.pyindex 3dabf759aa3..e5e1e7de0a6 100644--- a/scripts/p2p_integrity_probe.py+++ b/scripts/p2p_integrity_probe.py@@ -30,6 +30,7 @@ import argparseimport shutilimport subprocessimport sys+from pathlib import PathSENTINEL = -7.0SIZES_MIB = (1, 4, 16, 64)@@ -65,6 +66,56 @@ def _print_topology() -> None:print()+def _print_nvml_agreement() -> None:+ """Compare the NVML fast path (~230 ms) against `nvidia-smi topo -m` (~1.2 s).++ They agree exactly on an 8x B200 NVSwitch host, but PCIe-only and partially+ bridged boxes were not available to test. The line that matters is an+ NVML-positive / topo-negative pair, the fast path claiming a link the slow path+ denies. Please report it on #10613 if you see one."""+ try:+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "studio" / "backend"))+ from core.inference.llama_cpp import LlamaCppBackend as backend+ except Exception as e: # noqa: BLE001 -- diagnostic, never fatal+ print(f"could not import the Studio backend to cross-check NVML: {e}\n")+ return+ try:+ nvml = backend._probe_nvml_nvlink_topology()+ topo = backend._probe_nvlink_topology()+ except Exception as e: # noqa: BLE001+ print(f"topology cross-check failed: {e}\n")+ return+ print("=== NVML vs nvidia-smi topo -m ===")+ if nvml is None:+ print("NVML gave no verdict here; Studio would use `nvidia-smi topo -m`.\n")+ return+ if topo is None:+ print("`nvidia-smi topo -m` gave no verdict; nothing to compare against.\n")+ return+ nvml_yes = {k for k, v in nvml.items() if backend._label_is_nvlink(v)}+ topo_yes = {k for k, v in topo.items() if backend._label_is_nvlink(v)}+ print(f"NVLinked pairs: NVML {len(nvml_yes)}, topo -m {len(topo_yes)}")+ if nvml_yes == topo_yes:+ print("They agree exactly.\n")+ return+ only_nvml = sorted(nvml_yes - topo_yes)+ if only_nvml:+ print(+ f"MISMATCH, and in the direction that matters: {only_nvml} are NVLink to\n"+ "NVML but not to topo -m. Please report this on #10613 with the output of\n"+ "`nvidia-smi topo -m`, and set UNSLOTH_DISABLE_DC_P2P=1 meanwhile."+ )+ if topo_yes - nvml_yes:+ print(+ f"{sorted(topo_yes - nvml_yes)} are NVLink to topo -m but not to NVML.\n"+ "This is the conservative direction: by default NVML answers first, so "+ "Studio\nwould not enable P2P for them. Setting "+ "UNSLOTH_P2P_TOPO_CROSSCHECK=1 makes topo -m\nwin any disagreement, which "+ "would enable them instead."+ )+ print()++def main() -> int:parser = argparse.ArgumentParser(description = __doc__.splitlines()[0])parser.add_argument(@@ -90,6 +141,7 @@ def main() -> int:parser.error("--sizes-mib values must all be positive")_print_topology()+ _print_nvml_agreement()try:import torchdiff --git a/studio/NVLINK_P2P.md b/studio/NVLINK_P2P.mdindex 4043b0607ec..e444ac33e36 100644--- a/studio/NVLINK_P2P.md+++ b/studio/NVLINK_P2P.md@@ -51,12 +51,39 @@ A product name cannot tell you whether the box has a bridge.asking it again is not verification. vLLM reached the same conclusion and performs a realdata-integrity check (`can_actually_p2p`, from vllm#2728).-Studio reads `nvidia-smi topo -m` instead and requires `NV#` between every selected pair.+Studio reads the topology itself and requires a confirmed NVLink between every selected pair.NVLink traffic does not traverse the PCIe root complex, so the IOMMU fault class abovecannot apply to it. The probe fails closed: a missing `nvidia-smi`, a non-zero exit, atimeout, an unparsable matrix, or a device mask that cannot be mapped to PCI indices allmean no P2P.+### Where the answer comes from++Two sources, in order. The first conclusive one wins; if neither answers, no P2P.++| tier | source | cost on an 8x B200 |+|---|---|---|+| 1 | NVML, via `ctypes` against the driver's own `libnvidia-ml.so.1` / `nvml.dll` | ~230 ms |+| 2 | `nvidia-smi topo -m` | ~1200 ms |++NVML ships with the driver, so it is present exactly when `nvidia-smi` is (`nvidia-smi` is+itself an NVML client) and this adds no Python dependency. Tier 1 asks+`nvmlDeviceGetP2PStatus(a, b, NVML_P2P_CAPS_INDEX_NVLINK)`, which is a question about one+pair. Note what it deliberately does not do: an active link whose remote endpoint is an+NVSwitch proves only that 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".++Anything short of a complete, unambiguous answer falls to tier 2: a missing library or+symbol, any non-zero NVML return, fewer than two devices, a partial walk, or a positive+that contradicts the live NVLink count on either endpoint. The result is cached for the+process, primed on the startup warm thread so the first model load reads it warm, and+never gates startup.++Whichever tier answers, the verdict is identical on the hardware tested here: NVML and+`topo -m` agree exactly on an 8x B200 NVSwitch host, 56 of 56 ordered pairs, in both+directions. PCIe-only and partially bridged hosts were not available to test, which is what+`UNSLOTH_P2P_TOPO_CROSSCHECK=1` and `scripts/p2p_integrity_probe.py` are for.+### Partially bridged boxes, and which pairs get checkedOnly the pairs actually selected are checked, so on a 4-way or 8-way box with NVLink@@ -100,6 +127,7 @@ at several sizes. Exit 0 means intact, 1 means data was lost, 2 means it could n| `UNSLOTH_DISABLE_DC_TUNING=1` | disables all data-center tuning, including FP32 accumulate || `UNSLOTH_DISABLE_DC_P2P=1` | disables `GGML_CUDA_P2P` only, keeping FP32 accumulate and `CUDA_SCALE_LAUNCH_QUEUES`. Also removes an inherited `GGML_CUDA_P2P`, so it holds even if the variable is already set elsewhere in your environment || `UNSLOTH_FORCE_DC_P2P=1` | enables P2P on an unverified fabric (use after the probe passes). It cannot override `UNSLOTH_DISABLE_DC_P2P=1`, an off-meaning `GGML_CUDA_P2P` in your environment, or the data-center gate itself |+| `UNSLOTH_P2P_TOPO_CROSSCHECK=1` | runs both topology tiers and logs any disagreement, preferring `nvidia-smi topo -m` when they differ. Diagnostic only; costs the slow probe on every process. The startup prime stands down while it is set, since a primed NVML-only answer would satisfy the cache before the load path could compare the two |`CUDA_SCALE_LAUNCH_QUEUES` is deliberately not gated on the fabric: it sizes a CUDA commandbuffer, moves no data between devices, and the reporter of #10613 measured it clean indiff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex a58aaf8c14b..9017750bae7 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -10,6 +10,7 @@ OpenAI-compatible /v1/chat/completions endpoint.import astimport atexitimport contextlib+import ctypesimport errnoimport functoolsimport hashlib@@ -9154,9 +9155,195 @@ class LlamaCppBackend:_TOPO_NVLINK_RE = re.compile(r"^NV\d+$")_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")- # One shell-out per process, not per launch. None = not yet probed; otherwise a+ # One probe per process, not per launch. None = not yet probed; otherwise a# 1-tuple whose value may itself be None ("probed and unavailable")._NVLINK_TOPO_CACHE = None+ # Bumped on refresh so a slow prime cannot publish over a newer invalidation.+ _NVLINK_TOPO_GENERATION = 0+ _NVLINK_TOPO_LOCK = threading.Lock()++ # Its own vocabulary: a fabricated NV18 could be misread as a link count.+ _NVML_NVLINK_LABEL = "NVLINK"+ _NVML_NO_NVLINK_LABEL = "NO-NVLINK"++ # nvml.h. Only scalars and opaque handles cross, so no struct layout to get wrong.+ _NVML_SUCCESS = 0+ _NVML_P2P_CAPS_INDEX_NVLINK = 2+ _NVML_P2P_STATUS_OK = 0+ # 1..5 are the documented denials; UNKNOWN (6) and anything past the enum are not.+ _NVML_P2P_STATUS_DEFINITE_NEGATIVES = frozenset({1, 2, 3, 4, 5})+ _NVML_FEATURE_ENABLED = 1+ # Link enumeration stops at the first error; this only bounds a runaway loop.+ _NVML_MAX_LINKS = 64++ @classmethod+ def _matrix_is_nvml(cls, matrix: dict) -> bool:+ """Whether this matrix came from NVML, i.e. whether nvidia-smi is known to+ have answered."""+ return any(+ v in (cls._NVML_NVLINK_LABEL, cls._NVML_NO_NVLINK_LABEL) for v in matrix.values()+ )++ @classmethod+ def _label_is_nvlink(cls, label: str) -> bool:+ """The one place that decides whether a label means NVLink, so the+ selected-pair check and the whole-box check cannot drift apart."""+ return bool(cls._TOPO_NVLINK_RE.match(label)) or label == cls._NVML_NVLINK_LABEL++ @staticmethod+ def _nvml_library():+ """The driver's own NVML, via ctypes: present exactly when nvidia-smi is, and+ no Python dependency (nvidia-ml-py is NOT installed in a Studio env). None+ when it cannot be loaded."""+ if os.name == "nt":+ # nvml.dll can sit in NVSMI\ rather than a DLL search path, as nvidia-smi.exe+ # does (see _nvidia_smi_executable in utils/hardware/nvidia.py).+ names = ["nvml.dll"]+ for root in (os.environ.get("ProgramFiles"), os.environ.get("ProgramW6432")):+ if root:+ names.append(os.path.join(root, "NVIDIA Corporation", "NVSMI", "nvml.dll"))+ windir = os.environ.get("SystemRoot")+ if windir:+ names.append(os.path.join(windir, "System32", "nvml.dll"))+ else:+ names = ["libnvidia-ml.so.1", "libnvidia-ml.so"]+ for name in names:+ try:+ return ctypes.CDLL(name)+ except OSError:+ continue+ return None++ # ctypes has no subprocess timeout and a wedged driver blocks nvmlInit_v2 forever.+ _NVML_PROBE_TIMEOUT_SECONDS = 10++ @classmethod+ def _probe_nvml_nvlink_topology(cls) -> Optional[dict]:+ """_probe_nvml_nvlink_topology_inner under a wall-clock bound. A stalled NVML+ call cannot be cancelled, so the thread is abandoned as a daemon and the caller+ falls through to the shell-out, which has a timeout of its own."""+ box = {}++ def _run():+ box["matrix"] = cls._probe_nvml_nvlink_topology_inner()++ worker = threading.Thread(target = _run, daemon = True, name = "nvml-nvlink-probe")+ worker.start()+ worker.join(cls._NVML_PROBE_TIMEOUT_SECONDS)+ if worker.is_alive():+ logger.debug(+ f"NVML NVLink probe still running after "+ f"{cls._NVML_PROBE_TIMEOUT_SECONDS}s; abandoning it"+ )+ return None+ return box.get("matrix")++ @classmethod+ def _probe_nvml_nvlink_topology_inner(cls) -> Optional[dict]:+ """Same matrix as _probe_nvlink_topology, from NVML instead of a shell-out:+ ~85 ms against ~1200 ms on an 8x B200. Keyed by the NVML device index, which+ is the nvidia-smi index (both enumerate in PCI order and both ignore+ CUDA_VISIBLE_DEVICES, verified on 8x B200). None when the answer is not+ conclusive, which sends the caller to the shell-out.++ Evidence is per PAIR: an active link whose remote endpoint is an NVSwitch+ proves only that the GPU is attached to a switch, and switch fabrics can be+ partitioned, so "every GPU has a switch link" must NOT be read as "every pair+ is reachable"."""+ lib = cls._nvml_library()+ if lib is None:+ return None+ initialised = False+ try:+ try:+ get_status = lib.nvmlDeviceGetP2PStatus+ get_count = lib.nvmlDeviceGetCount_v2+ get_handle = lib.nvmlDeviceGetHandleByIndex_v2+ get_link_state = lib.nvmlDeviceGetNvLinkState+ nvml_init = lib.nvmlInit_v2+ except AttributeError as e:+ # An older driver missing these still has the working shell-out.+ logger.debug(f"NVML lacks a required symbol: {e}")+ return None+ for fn in (get_status, get_count, get_handle, get_link_state, nvml_init):+ fn.restype = ctypes.c_int+ if nvml_init() != cls._NVML_SUCCESS:+ return None+ initialised = True++ count = ctypes.c_uint()+ if get_count(ctypes.byref(count)) != cls._NVML_SUCCESS:+ return None+ if count.value < 2:+ return None # peer copies need two devices; nothing to say++ handles = []+ for i in range(count.value):+ handle = ctypes.c_void_p()+ if get_handle(ctypes.c_uint(i), ctypes.byref(handle)) != cls._NVML_SUCCESS:+ return None # partial inventory: never approve the rest+ handles.append(handle)++ # Per-device active links, used only to contradict a positive.+ active_links = []+ for handle in handles:+ seen = 0+ for link in range(cls._NVML_MAX_LINKS):+ state = ctypes.c_uint()+ rc = get_link_state(handle, ctypes.c_uint(link), ctypes.byref(state))+ if rc != cls._NVML_SUCCESS:+ break # past this device's last link, or unsupported+ if state.value == cls._NVML_FEATURE_ENABLED:+ seen += 1+ active_links.append(seen)++ matrix: dict = {}+ for a in range(count.value):+ for b in range(count.value):+ if a == b:+ continue+ status = ctypes.c_uint()+ rc = get_status(+ handles[a],+ handles[b],+ ctypes.c_uint(cls._NVML_P2P_CAPS_INDEX_NVLINK),+ ctypes.byref(status),+ )+ if rc != cls._NVML_SUCCESS:+ return None # unknown for one pair is unknown for all+ linked = status.value == cls._NVML_P2P_STATUS_OK+ if not linked and status.value not in cls._NVML_P2P_STATUS_DEFINITE_NEGATIVES:+ # NO-NVLINK would read as conclusive and rob `topo -m` of the say.+ logger.debug(+ f"NVML P2P status {status.value} for GPU {a}<->{b} is not a "+ "definite answer; treating the topology as unreadable"+ )+ return None+ # No live NVLink on an endpoint means the pair cannot be NVLinked.+ # An OK on a PCIe-only box becomes unknown, not a false positive (#10613).+ if linked and not (active_links[a] and active_links[b]):+ logger.debug(+ f"NVML says GPU {a}<->{b} is NVLink but they report "+ f"{active_links[a]}/{active_links[b]} active links; "+ "treating the topology as unreadable"+ )+ return None+ matrix[(a, b)] = cls._NVML_NVLINK_LABEL if linked else cls._NVML_NO_NVLINK_LABEL++ # By key, not count: right-sized with wrong keys passes a length check.+ expected = {(a, b) for a in range(count.value) for b in range(count.value) if a != b}+ if set(matrix) != expected:+ return None+ return matrix+ except Exception as e:+ logger.debug(f"NVML NVLink probe failed: {e}")+ return None+ finally:+ if initialised:+ try:+ lib.nvmlShutdown()+ except Exception:+ pass@staticmethoddef _probe_nvlink_topology() -> Optional[dict]:@@ -9215,11 +9402,11 @@ class LlamaCppBackend:# output still exits 0 and parses cleanly, and the rows that arrived can# be uniformly NV#, which reads as "the whole box is NVLinked" and would# enable P2P on cards whose links were never seen (#10613).- if len(matrix) != len(columns) * (len(columns) - 1):+ expected = {(a, b) for a in columns for b in columns if a != b}+ if set(matrix) != expected:logger.debug(f"nvidia-smi topo -m: {len(matrix)} pairs for {len(columns)} "- "GPUs, expected "- f"{len(columns) * (len(columns) - 1)}; treating as unreadable"+ f"GPUs, expected {len(expected)}; treating as unreadable")return Nonereturn matrix or None@@ -9228,11 +9415,95 @@ class LlamaCppBackend:return None@classmethod- def _nvlink_topology(cls, refresh = False) -> Optional[dict]:- """_probe_nvlink_topology, cached for the life of the process."""- if refresh or cls._NVLINK_TOPO_CACHE is None:- cls._NVLINK_TOPO_CACHE = (cls._probe_nvlink_topology(),)- return cls._NVLINK_TOPO_CACHE[0]+ def _probe_interconnect_matrix(cls) -> Optional[dict]:+ """NVML first, `nvidia-smi topo -m` second, nothing third. Both answer in the+ same index space and shape; NVML is ~14x faster, so the shell-out is only paid+ on drivers too old to answer.++ UNSLOTH_P2P_TOPO_CROSSCHECK=1 runs both and logs any disagreement, to qualify+ the fast path on fabrics not available here (PCIe-only, partially bridged); an+ NVML-positive / topo-negative pair is the result that would matter."""+ matrix = cls._probe_nvml_nvlink_topology()+ if matrix is not None and os.environ.get("UNSLOTH_P2P_TOPO_CROSSCHECK") == "1":+ topo = cls._probe_nvlink_topology()+ if topo is not None:+ nvml_yes = {k for k, v in matrix.items() if cls._label_is_nvlink(v)}+ topo_yes = {k for k, v in topo.items() if cls._label_is_nvlink(v)}+ if nvml_yes != topo_yes:+ logger.warning(+ "P2P topology cross-check disagreement: NVML-only pairs "+ f"{sorted(nvml_yes - topo_yes)}, topo-only pairs "+ f"{sorted(topo_yes - nvml_yes)}. Using topo -m. Please "+ "report this with `nvidia-smi topo -m` output (#10613)."+ )+ return topo+ if matrix is not None:+ return matrix+ return cls._probe_nvlink_topology()++ @classmethod+ def prime_nvlink_topology(cls) -> None:+ """Warm the cache with NVML only, for a speculative caller off the load path.++ Deliberately skips the `nvidia-smi` fallback. A prime is an optimisation, so+ it may pay the cheap path and nothing else: spawning a subprocess that can run+ for its full timeout, on a background thread, perturbs whatever else shares+ the process. 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.++ Publishes only a success, for the reason cache_failure documents below: a miss+ cached this early would outlive the condition that caused it."""+ if cls._NVLINK_TOPO_CACHE is not None:+ return+ if os.environ.get("UNSLOTH_P2P_TOPO_CROSSCHECK") == "1":+ # The cross-check lives in _probe_interconnect_matrix, which only the load+ # path reaches, and the warm stage always primes first: publishing here+ # would retire the diagnostic. Cold cache costs the inline slow probe.+ return+ matrix = cls._probe_nvml_nvlink_topology()+ if matrix is None:+ return+ with cls._NVLINK_TOPO_LOCK:+ if cls._NVLINK_TOPO_CACHE is None:+ cls._NVLINK_TOPO_CACHE = (matrix,)++ @classmethod+ def _nvlink_topology(+ cls,+ refresh = False,+ cache_failure = True,+ ) -> Optional[dict]:+ """_probe_interconnect_matrix, cached for the life of the process.++ The probe runs outside the lock (slow, and a duplicate pass is harmless), but+ publication is guarded: a background prime and a model load can both be in+ flight, and the generation check stops a slow winner from overwriting a newer+ invalidation."""+ if not refresh and cls._NVLINK_TOPO_CACHE is not None:+ return cls._NVLINK_TOPO_CACHE[0]+ with cls._NVLINK_TOPO_LOCK:+ generation = cls._NVLINK_TOPO_GENERATION+ if refresh:+ cls._NVLINK_TOPO_GENERATION += 1+ generation = cls._NVLINK_TOPO_GENERATION+ elif cls._NVLINK_TOPO_CACHE is not None:+ return cls._NVLINK_TOPO_CACHE[0]+ probed = cls._probe_interconnect_matrix()+ with cls._NVLINK_TOPO_LOCK:+ if generation == cls._NVLINK_TOPO_GENERATION:+ if probed is None and not cache_failure:+ # A miss probed mid driver init would keep P2P off for the process.+ return None+ existing = cls._NVLINK_TOPO_CACHE+ if probed is None and existing is not None and existing[0] is not None:+ # The generation only guards a refresh, so without this a racing+ # transient failure would erase a concurrent pass's good matrix.+ return existing[0]+ cls._NVLINK_TOPO_CACHE = (probed,)+ return probed+ # A refresh started mid-pass owns the answer; discard this one as stale.+ cached = cls._NVLINK_TOPO_CACHE+ return probed if cached is None else cached[0]@staticmethoddef _running_virtualized() -> bool:@@ -9312,12 +9583,13 @@ class LlamaCppBackend:cls,gpu_indices = None,launch_order_pinned = False,+ ids_are_pci_indices = None,) -> Optional[str]:"""Fail-closed wrapper around _p2p_veto_reason_inner: anything unexpectedreads as "do not set P2P", since losing the tuning beats an exceptionescaping into load_model and failing the load."""try:- return cls._p2p_veto_reason_inner(gpu_indices, launch_order_pinned)+ return cls._p2p_veto_reason_inner(gpu_indices, launch_order_pinned, ids_are_pci_indices)except Exception as e:logger.debug(f"peer-fabric check failed: {e}")return f"the peer-fabric check could not complete ({type(e).__name__})"@@ -9327,6 +9599,7 @@ class LlamaCppBackend:cls,gpu_indices = None,launch_order_pinned = False,+ ids_are_pci_indices = None,) -> Optional[str]:"""Why GGML_CUDA_P2P must NOT be set for this selection, or None once aworking NVLink fabric is confirmed for every selected pair. Fails CLOSED on@@ -9372,7 +9645,7 @@ class LlamaCppBackend:matrix = cls._nvlink_topology()if not matrix:- return "nvidia-smi topo -m gave no usable interconnect matrix"+ return "neither NVML nor nvidia-smi topo -m gave a usable interconnect matrix"gpu_ids = sorted({i for pair in matrix for i in pair})@@ -9390,10 +9663,11 @@ class LlamaCppBackend:# NVLink for a pair that is not the one about to run (#10613).# Unless the whole box is NVLinked, where the mapping cannot matter and# vetoing would lose P2P on every auto-fit NVSwitch launch (#6098).+ uniformly_nvlinked = all(cls._label_is_nvlink(v) for v in matrix.values())if not (launch_order_pinnedor os.environ.get("CUDA_DEVICE_ORDER") == "PCI_BUS_ID"- or all(cls._TOPO_NVLINK_RE.match(v) for v in matrix.values())+ or uniformly_nvlinked):return _pcie("the child's device order is not pinned to PCI_BUS_ID and the "@@ -9401,6 +9675,20 @@ class LlamaCppBackend:"the ones it runs on; set CUDA_DEVICE_ORDER=PCI_BUS_ID to ""enable P2P here")+ # A usable `topo -m` proved nvidia-smi enumerated the selection; NVML does+ # not, and torch ordinals index this matrix wrongly under FASTEST_FIRST (#10613).+ pci_ids = (+ cls._GPU_IDS_ARE_PCI_INDICES is True+ if ids_are_pci_indices is None+ else ids_are_pci_indices+ )+ # As above: every mapping agrees on a uniform box, and stray ids still veto.+ if cls._matrix_is_nvml(matrix) and not pci_ids and not uniformly_nvlinked:+ return _pcie(+ "the GPU selection came from torch rather than nvidia-smi, so "+ "its ids are CUDA ordinals and cannot be matched against the "+ "NVML interconnect matrix"+ )selected = sorted(set(gpu_indices))else:# No explicit selection: the child uses every VISIBLE GPU. nvidia-smi@@ -9430,7 +9718,7 @@ class LlamaCppBackend:label = matrix.get((a, b))if label is None:return f"GPU {a} and GPU {b} are absent from the interconnect matrix"- if not cls._TOPO_NVLINK_RE.match(label):+ if not cls._label_is_nvlink(label):return _pcie(f"GPU {a} to GPU {b} is {label}, not NVLink")return None@@ -9504,6 +9792,7 @@ class LlamaCppBackend:gpu_indices = None,p2p_opted_out = False,launch_order_pinned = False,+ ids_are_pci_indices = None,) -> bool:"""Inject DC llama.cpp tuning into env in place via setdefault (user valueswin); return whether the box qualified. Only datacenter NVIDIA parts qualify@@ -9545,7 +9834,9 @@ class LlamaCppBackend:veto = ("GGML_CUDA_P2P was turned off in the environment"if p2p_opted_out- else LlamaCppBackend._p2p_veto_reason(gpu_indices, launch_order_pinned)+ else LlamaCppBackend._p2p_veto_reason(+ gpu_indices, launch_order_pinned, ids_are_pci_indices+ ))if veto is None:applied.append(_apply("GGML_CUDA_P2P", "1"))@@ -24298,6 +24589,13 @@ class LlamaCppBackend:os.environ.get("CUDA_VISIBLE_DEVICES") is Noneand LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES is True)+ # Whether THESE ids live in the matrix's index space. An explicit pick+ # is not evidence: with nvidia-smi gone the picker lists torch ordinals.+ # Ask instead: nvidia-smi produced the ids, or PCI order is pinned.+ _p2p_ids_are_pci = (+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES is True+ or os.environ.get("CUDA_DEVICE_ORDER") == "PCI_BUS_ID"+ )# Only when the fabric is NOT confirmed: on a verified NV# pair the# flag is the benchmarked configuration. Datacenter boxes are@@ -24311,7 +24609,9 @@ class LlamaCppBackend:and self._effective_gpu_count(gpu_indices) > 1and not LlamaCppBackend._warned_no_nvlink):- _p2p_veto = self._p2p_veto_reason(gpu_indices, _p2p_launch_order_pinned)+ _p2p_veto = self._p2p_veto_reason(+ gpu_indices, _p2p_launch_order_pinned, _p2p_ids_are_pci+ )if _p2p_veto is not None:LlamaCppBackend._warned_no_nvlink = Truelogger.warning(@@ -24336,6 +24636,7 @@ class LlamaCppBackend:gpu_indices,p2p_opted_out = self._p2p_user_opted_out(),launch_order_pinned = _p2p_launch_order_pinned,+ ids_are_pci_indices = _p2p_ids_are_pci,)# Pin to selected GPU(s) (issue #7164; resolved above into gpu_indices).diff --git a/studio/backend/tests/test_datacenter_gpu_tuning.py b/studio/backend/tests/test_datacenter_gpu_tuning.pyindex cd0e59d1d67..6977244cde2 100644--- a/studio/backend/tests/test_datacenter_gpu_tuning.py+++ b/studio/backend/tests/test_datacenter_gpu_tuning.py@@ -12,6 +12,8 @@ link across the selection and fails CLOSED on unknowns.from __future__ import annotations+import ctypes+import osimport subprocessimport sysimport types@@ -85,6 +87,7 @@ def _clear_cuda_visible_devices(monkeypatch):# Captured before the autouse fixture stubs it, so the probe can run for real._REAL_IOMMU_IS_TRANSLATING = LlamaCppBackend.__dict__["_iommu_is_translating"].__func__+_REAL_NVML_LIBRARY = LlamaCppBackend.__dict__["_nvml_library"].__func__def _no_nvidia_smi(*a, **k):@@ -95,10 +98,17 @@ def _no_nvidia_smi(*a, **k):def _isolate_host_topology(monkeypatch):"""Keep the P2P gate off the real host: only nvidia-smi's output is stubbed (theparser always runs), caches are dropped either side, and the platform probes are- pinned so a CI box with GPUs cannot colour the results."""+ pinned so a CI box with GPUs cannot colour the results.++ NVML is stubbed absent by default so the topo tests still exercise the parser;+ with a real driver the fast path would answer first and the canned `nvidia-smi`+ output would never be read. The NVML tests install their own fake."""LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend._NVLINK_TOPO_GENERATION = 0LlamaCppBackend._IOMMU_CACHE = Nonemonkeypatch.setattr(subprocess, "run", _no_nvidia_smi)+ monkeypatch.setattr(LlamaCppBackend, "_nvml_library", staticmethod(lambda: None))+ monkeypatch.delenv("UNSLOTH_P2P_TOPO_CROSSCHECK", raising = False)monkeypatch.setattr(LlamaCppBackend, "_iommu_is_translating", staticmethod(lambda *a: False))monkeypatch.setattr(LlamaCppBackend, "_running_virtualized", staticmethod(lambda: False))# Overrides off and the warn-once latch reset: no host env, no ordering leak.@@ -110,6 +120,7 @@ def _isolate_host_topology(monkeypatch):LlamaCppBackend._warned_no_nvlink = FalseyieldLlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend._NVLINK_TOPO_GENERATION = 0LlamaCppBackend._IOMMU_CACHE = NoneLlamaCppBackend._warned_no_nvlink = False@@ -1060,3 +1071,579 @@ def test_gpu_id_provenance_is_recorded(monkeypatch):LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = NoneLlamaCppBackend._get_gpu_memory("llama-server")assert LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES is not True+++# ---------------------------------------------------------------------------+# NVML fast path: the same matrix from the driver's own NVML instead of+# `nvidia-smi topo -m`. These drive a fake libnvidia-ml so the failure modes are+# reachable without hardware.+# ---------------------------------------------------------------------------++_NVML_OK = 0+_NVML_ERROR = 999+++class _FakeNvml:+ """Stand-in for libnvidia-ml.so.1 with the real calling convention: rc out,+ values written through byref pointers."""++ def __init__(+ self,+ count = 2,+ linked_pairs = None,+ active_links = None,+ status_rc = _NVML_OK,+ status_value = None,+ handle_rc = _NVML_OK,+ init_rc = _NVML_OK,+ count_rc = _NVML_OK,+ missing = (),+ fail_status_after = None,+ ):+ self.count = count+ # None = every pair NVLinked.+ self.linked_pairs = linked_pairs+ # None = every device has links.+ self.active_links = active_links+ self.status_rc = status_rc+ self.status_value = status_value+ self.handle_rc = handle_rc+ self.init_rc = init_rc+ self.count_rc = count_rc+ self.missing = set(missing)+ self.fail_status_after = fail_status_after+ self.status_calls = 0+ self.shutdown_calls = 0++ def _fn(self, name, impl):+ if name in self.missing:+ raise AttributeError(name)+ return impl++ # ctypes attribute lookups happen once, up front, in the probe.+ @property+ def nvmlInit_v2(self):+ return self._fn("nvmlInit_v2", lambda: self.init_rc)++ @property+ def nvmlShutdown(self):+ def _shutdown():+ self.shutdown_calls += 1+ return _NVML_OK++ return _shutdown++ @property+ def nvmlDeviceGetCount_v2(self):+ def _count(ref):+ ref._obj.value = self.count+ return self.count_rc++ return self._fn("nvmlDeviceGetCount_v2", _count)++ @property+ def nvmlDeviceGetHandleByIndex_v2(self):+ def _handle(index, ref):+ ref._obj.value = 1000 + int(getattr(index, "value", index))+ return self.handle_rc++ return self._fn("nvmlDeviceGetHandleByIndex_v2", _handle)++ @property+ def nvmlDeviceGetNvLinkState(self):+ def _state(handle, link, ref):+ device = int(handle.value) - 1000+ links = 4 if self.active_links is None else self.active_links[device]+ if int(getattr(link, "value", link)) >= links:+ return _NVML_ERROR+ ref._obj.value = 1 # NVML_FEATURE_ENABLED+ return _NVML_OK++ return self._fn("nvmlDeviceGetNvLinkState", _state)++ @property+ def nvmlDeviceGetP2PStatus(self):+ def _status(a, b, index, ref):+ self.status_calls += 1+ if self.fail_status_after is not None and self.status_calls > self.fail_status_after:+ return _NVML_ERROR+ if self.status_rc != _NVML_OK:+ return self.status_rc+ pair = (int(a.value) - 1000, int(b.value) - 1000)+ linked = self.linked_pairs is None or pair in self.linked_pairs+ if self.status_value is not None:+ ref._obj.value = self.status_value+ else:+ ref._obj.value = 0 if linked else 5 # OK / NOT_SUPPORTED+ return _NVML_OK++ return self._fn("nvmlDeviceGetP2PStatus", _status)+++def _use_nvml(monkeypatch, fake):+ monkeypatch.setattr(LlamaCppBackend, "_nvml_library", staticmethod(lambda: fake))+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ return fake+++def test_nvml_all_pairs_nvlinked_is_a_complete_matrix(monkeypatch):+ _use_nvml(monkeypatch, _FakeNvml(count = 4))+ matrix = LlamaCppBackend._probe_nvml_nvlink_topology()+ assert set(matrix) == {(a, b) for a in range(4) for b in range(4) if a != b}+ assert all(LlamaCppBackend._label_is_nvlink(v) for v in matrix.values())+++def test_nvml_is_preferred_over_the_shell_out(monkeypatch):+ """The whole point: on a host where both answer, nvidia-smi is never spawned."""+ _use_nvml(monkeypatch, _FakeNvml(count = 2))+ calls = []+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: calls.append(a)+ or types.SimpleNamespace(returncode = 0, stdout = TOPO_PCIE_2X, stderr = ""),+ )+ matrix = LlamaCppBackend._nvlink_topology()+ assert LlamaCppBackend._matrix_is_nvml(matrix)+ assert calls == []+++def test_nvml_absent_falls_back_to_topo(monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_nvml_library", staticmethod(lambda: None))+ _use_topo(monkeypatch, TOPO_NVLINK_8X)+ matrix = LlamaCppBackend._nvlink_topology()+ assert matrix and not LlamaCppBackend._matrix_is_nvml(matrix)+++ "kwargs",+ [+ {"init_rc": _NVML_ERROR},+ {"count_rc": _NVML_ERROR},+ {"handle_rc": _NVML_ERROR},+ {"status_rc": _NVML_ERROR},+ {"missing": ("nvmlDeviceGetP2PStatus",)},+ {"missing": ("nvmlDeviceGetNvLinkState",)},+ {"count": 1},+ ],+)+def test_nvml_unknown_falls_through_to_topo(monkeypatch, kwargs):+ """Every way NVML can fail to answer must reach the shell-out, not a verdict."""+ _use_nvml(monkeypatch, _FakeNvml(**kwargs))+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+ _use_topo_after_nvml(monkeypatch, _FakeNvml(**kwargs), TOPO_NVLINK_8X)+ matrix = LlamaCppBackend._nvlink_topology()+ assert matrix and not LlamaCppBackend._matrix_is_nvml(matrix)+++def _use_topo_after_nvml(monkeypatch, fake, text):+ monkeypatch.setattr(LlamaCppBackend, "_nvml_library", staticmethod(lambda: fake))+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: types.SimpleNamespace(returncode = 0, stdout = text, stderr = ""),+ )+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+++def test_nvml_partial_walk_is_not_a_partial_matrix(monkeypatch):+ """A failure mid-walk must discard the successes, not approve the pairs that+ happened to answer first."""+ _use_nvml(monkeypatch, _FakeNvml(count = 4, fail_status_after = 3))+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+++def test_nvml_positive_without_active_links_is_a_contradiction(monkeypatch):+ """Guard for hardware not available here: an OK on a box with no live NVLinks is+ unknown, not a green light."""+ _use_nvml(monkeypatch, _FakeNvml(count = 2, active_links = [0, 0]))+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+++def test_nvml_unlinked_pair_vetoes_p2p(monkeypatch):+ """Two islands, 0-1 and 2-3. A cross-island selection must not get P2P."""+ linked = {(0, 1), (1, 0), (2, 3), (3, 2)}+ _use_nvml(monkeypatch, _FakeNvml(count = 4, linked_pairs = linked))+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True+ assert LlamaCppBackend._p2p_veto_reason([0, 2]) is not None+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is None+++def test_nvml_matrix_needs_nvidia_smi_provenance(monkeypatch):+ """`topo -m` answering proves nvidia-smi enumerated the selection; NVML does not,+ so torch-ordinal ids must not be matched against an NVML matrix. Partially+ bridged, since on a uniform fabric the mapping cannot change the verdict and+ provenance is deliberately not required."""+ _use_nvml(+ monkeypatch,+ _FakeNvml(count = 4, linked_pairs = {(0, 1), (1, 0), (2, 3), (3, 2)}),+ )+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is not None+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is None+++def test_nvml_shuts_down_what_it_started(monkeypatch):+ fake = _use_nvml(monkeypatch, _FakeNvml(count = 2))+ LlamaCppBackend._probe_nvml_nvlink_topology()+ assert fake.shutdown_calls == 1+ # A failed init owns no session, so it must not shut one down.+ failed = _use_nvml(monkeypatch, _FakeNvml(count = 2, init_rc = _NVML_ERROR))+ LlamaCppBackend._probe_nvml_nvlink_topology()+ assert failed.shutdown_calls == 0+++def test_nvml_single_gpu_gives_no_verdict(monkeypatch):+ """One device cannot make a pair, and an empty matrix must never read as+ 'everything is NVLinked' through a vacuous all()."""+ _use_nvml(monkeypatch, _FakeNvml(count = 1))+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+++def test_crosscheck_prefers_topo_on_disagreement(monkeypatch):+ """When both answer and differ, the slow one wins and it is logged."""+ monkeypatch.setenv("UNSLOTH_P2P_TOPO_CROSSCHECK", "1")+ _use_topo_after_nvml(monkeypatch, _FakeNvml(count = 2), TOPO_PCIE_2X)+ records = _capture_warnings(monkeypatch)+ matrix = LlamaCppBackend._probe_interconnect_matrix()+ assert not LlamaCppBackend._matrix_is_nvml(matrix)+ assert any("cross-check disagreement" in r for r in records)+++def test_nvml_unknown_status_is_not_a_denial(monkeypatch):+ """UNKNOWN (6), or a status from a newer driver, is not evidence of no NVLink:+ recording it as NO-NVLINK would deny topo -m the chance to confirm a real+ fabric."""+ for status in (6, 42):+ _use_nvml(monkeypatch, _FakeNvml(count = 2, status_value = status))+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+ # A documented "not supported, and here is why" IS a denial, and stays one.+ for status in (1, 2, 3, 4, 5):+ _use_nvml(monkeypatch, _FakeNvml(count = 2, status_value = status))+ matrix = LlamaCppBackend._probe_nvml_nvlink_topology()+ assert matrix and not any(LlamaCppBackend._label_is_nvlink(v) for v in matrix.values())+++def test_a_failed_prime_does_not_poison_the_cache(monkeypatch):+ """The prime runs early, possibly mid driver init. A miss cached there would keep+ P2P off for the whole process even once the topology is readable."""+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_interconnect_matrix", classmethod(lambda cls: None)+ )+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._nvlink_topology(cache_failure = False) is None+ assert LlamaCppBackend._NVLINK_TOPO_CACHE is None, "a failed prime cached its miss"+ # The load path still caches its own miss, as it did before this change.+ assert LlamaCppBackend._nvlink_topology() is None+ assert LlamaCppBackend._NVLINK_TOPO_CACHE == (None,)+++def test_a_successful_prime_is_still_cached(monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend,+ "_probe_interconnect_matrix",+ classmethod(lambda cls: {(0, 1): "NVLINK", (1, 0): "NVLINK"}),+ )+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._nvlink_topology(cache_failure = False) is not None+ assert LlamaCppBackend._NVLINK_TOPO_CACHE is not None+++def test_windows_nvml_candidates_include_the_nvsmi_directory(monkeypatch):+ """A driver install can leave nvml.dll in NVSMI rather than a DLL search path,+ as it does nvidia-smi.exe."""+ tried = []+ # From the module-level capture, since the autouse fixture already replaced the+ # class attribute with the absent stub.+ monkeypatch.setattr(LlamaCppBackend, "_nvml_library", staticmethod(_REAL_NVML_LIBRARY))+ monkeypatch.setattr(os, "name", "nt")+ monkeypatch.setenv("ProgramFiles", r"C:\Program Files")+ monkeypatch.setenv("SystemRoot", r"C:\Windows")++ def _fake_cdll(name):+ tried.append(name)+ raise OSError("not here")++ monkeypatch.setattr(ctypes, "CDLL", _fake_cdll)+ assert LlamaCppBackend._nvml_library() is None+ assert any("NVSMI" in t for t in tried), tried+ assert tried[0] == "nvml.dll", "the search path should still be tried first"+++def test_an_explicit_pick_keeps_its_pci_provenance(monkeypatch):+ """The UI's picker hands back PCI-ordered ids. A torch fallback in the unrelated+ memory query sets _GPU_IDS_ARE_PCI_INDICES False process-wide, and that must not+ cost an explicitly selected NVLinked pair its P2P. Partially bridged, so the+ mapping matters and provenance is load-bearing."""+ _use_nvml(+ monkeypatch,+ _FakeNvml(count = 4, linked_pairs = {(0, 1), (1, 0), (2, 3), (3, 2)}),+ )+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False++ # Caller says nothing: fall back to the process-wide flag, which vetoes.+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is not None++ # Caller knows these ids came from the PCI-ordered picker: no veto.+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, ids_are_pci_indices = True) is None++ # And an explicit False from the caller still vetoes.+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, ids_are_pci_indices = False) is not None+++def test_a_stalled_nvml_call_cannot_hang_the_load(monkeypatch):+ """ctypes has no timeout and the shell-out it replaced had one, so a wedged+ driver must cost a fallback rather than the load."""+ import threading as _threading++ release = _threading.Event()++ def _hang(cls):+ release.wait(30)+ return {(0, 1): "NVLINK", (1, 0): "NVLINK"}++ monkeypatch.setattr(LlamaCppBackend, "_probe_nvml_nvlink_topology_inner", classmethod(_hang))+ monkeypatch.setattr(LlamaCppBackend, "_NVML_PROBE_TIMEOUT_SECONDS", 0.2)+ try:+ assert LlamaCppBackend._probe_nvml_nvlink_topology() is None+ # And the caller still reaches the shell-out.+ _use_topo(monkeypatch, TOPO_NVLINK_8X)+ matrix = LlamaCppBackend._probe_interconnect_matrix()+ assert matrix and not LlamaCppBackend._matrix_is_nvml(matrix)+ finally:+ release.set()+++def test_a_racing_failure_does_not_erase_a_published_matrix(monkeypatch):+ """The prime publishes a good matrix; a load whose own probe fails transiently+ must not overwrite it with a miss and disable P2P for every later load."""+ good = {(0, 1): "NVLINK", (1, 0): "NVLINK"}+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_interconnect_matrix", classmethod(lambda cls: good)+ )+ assert LlamaCppBackend._nvlink_topology() == good++ # Now a pass that probes and fails while the good matrix is already published.+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_interconnect_matrix", classmethod(lambda cls: None)+ )+ assert LlamaCppBackend._nvlink_topology(refresh = True) == good+ assert LlamaCppBackend._NVLINK_TOPO_CACHE == (good,)+++def test_the_prime_skips_work_the_opt_outs_make_useless(monkeypatch):+ """UNSLOTH_DISABLE_DC_TUNING=1, UNSLOTH_DISABLE_DC_P2P=1 or a falsy GGML_CUDA_P2P+ all mean the answer can never be used, so the prime must not pay for it."""+ from utils import torch_warmup++ probed = []+ monkeypatch.setattr(+ LlamaCppBackend,+ "_probe_nvml_nvlink_topology",+ classmethod(lambda cls: (probed.append(1), {(0, 1): "NVLINK", (1, 0): "NVLINK"})[1]),+ )+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 8))++ for var, value in (+ ("UNSLOTH_DISABLE_DC_TUNING", "1"),+ ("UNSLOTH_DISABLE_DC_P2P", "1"),+ ("GGML_CUDA_P2P", "0"),+ ):+ monkeypatch.setenv(var, value)+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ probed.clear()+ torch_warmup._prime_nvlink_topology().join(10)+ assert probed == [], f"{var}={value} still primed"+ monkeypatch.delenv(var, raising = False)++ # Without an opt-out it still primes.+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ probed.clear()+ torch_warmup._prime_nvlink_topology().join(10)+ assert probed == [1]+++def test_the_prime_never_blocks_the_warm_sequence(monkeypatch):+ """The probe can spend its NVML bound plus the shell-out timeout. A warm stage+ that waits that long delays every stage behind it, and on a loaded CI worker that+ is enough to tip unrelated timing-sensitive tests over."""+ from utils import torch_warmup+ import threading as _threading+ import time as _time++ release = _threading.Event()++ def _slow(cls, **kw):+ release.wait(30)+ return {(0, 1): "NVLINK", (1, 0): "NVLINK"}++ # The prime calls _probe_nvml_nvlink_topology, not _nvlink_topology. Patching the+ # latter left the probe on the fixture's NVML-absent default, which returns at+ # once, so the worker was usually dead before `is_alive` ran and nothing slow was+ # ever exercised.+ monkeypatch.setattr(LlamaCppBackend, "_probe_nvml_nvlink_topology", classmethod(_slow))+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 8))+ try:+ started = _time.perf_counter()+ worker = torch_warmup._prime_nvlink_topology()+ elapsed = _time.perf_counter() - started+ assert elapsed < 1.0, f"the prime blocked its caller for {elapsed:.2f}s"+ assert worker.is_alive()+ finally:+ release.set()+ worker.join(10)+++def test_a_uniform_fabric_does_not_need_pci_provenance(monkeypatch):+ """On a box where every pair is NVLinked, which ids name which cards cannot+ change the verdict, so torch-ordinal provenance must not veto. Same argument the+ ordering check above already makes for an unpinned device order."""+ _use_nvml(monkeypatch, _FakeNvml(count = 4))+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is None++ # Partially bridged, so the mapping DOES matter: provenance is required again.+ linked = {(0, 1), (1, 0), (2, 3), (3, 2)}+ _use_nvml(monkeypatch, _FakeNvml(count = 4, linked_pairs = linked))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False+ assert LlamaCppBackend._p2p_veto_reason([0, 1]) is not None++ # And with provenance it is allowed on the bridged pair.+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, ids_are_pci_indices = True) is None+++def test_ids_outside_a_uniform_matrix_still_veto(monkeypatch):+ """The uniform escape must not become a blanket pass: ids the matrix does not+ cover are still unknown."""+ _use_nvml(monkeypatch, _FakeNvml(count = 2))+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 8))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False+ assert LlamaCppBackend._p2p_veto_reason([0, 5]) is not None+++def test_explicitness_is_not_evidence_of_pci_indexing(monkeypatch):+ """An explicit pick is PCI-indexed only because hardware.py setdefaults+ CUDA_DEVICE_ORDER=PCI_BUS_ID. Under a user override to FASTEST_FIRST with+ nvidia-smi unavailable, the picker lists torch's ordinals, and on a partially+ bridged host the same numbers can name different cards. Trusting explicitness+ there would approve the wrong pair and enable P2P on a PCIe path."""+ linked = {(0, 1), (1, 0), (2, 3), (3, 2)}+ _use_nvml(monkeypatch, _FakeNvml(count = 4, linked_pairs = linked))+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))+ LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = False++ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, ids_are_pci_indices = False) is not None++ # Pinned order: torch's ordinals and nvidia-smi's indices coincide, so the+ # explicit pick is usable again. This is the default the backend sets.+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, ids_are_pci_indices = True) is None+++def test_the_prime_never_spawns_the_shell_out(monkeypatch):+ """A prime may pay the cheap path and nothing else. A subprocess that can run for+ its full timeout, on a background thread, perturbs whatever else shares the+ process, and that is how an earlier version of this tipped unrelated+ timing-sensitive tests over in CI."""+ calls = []+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: calls.append(a)+ or types.SimpleNamespace(returncode = 0, stdout = TOPO_NVLINK_8X, stderr = ""),+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_nvml_nvlink_topology", classmethod(lambda cls: None)+ )+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend.prime_nvlink_topology()+ assert calls == [], "the prime reached the nvidia-smi fallback"+ assert LlamaCppBackend._NVLINK_TOPO_CACHE is None, "a failed prime cached its miss"++ # The load path still gets its fallback.+ assert LlamaCppBackend._nvlink_topology() is not None+ assert calls+++def test_the_prime_publishes_an_nvml_success(monkeypatch):+ good = {(0, 1): "NVLINK", (1, 0): "NVLINK"}+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_nvml_nvlink_topology", classmethod(lambda cls: good)+ )+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend.prime_nvlink_topology()+ assert LlamaCppBackend._NVLINK_TOPO_CACHE == (good,)+++def test_the_prime_does_not_retire_the_cross_check(monkeypatch):+ """UNSLOTH_P2P_TOPO_CROSSCHECK=1 asks for both tiers to run and disagreements to+ be logged. The cross-check lives in _probe_interconnect_matrix, which only the+ load path reaches, so a prime that published an NVML-only answer would satisfy+ the cache first and silently retire the diagnostic -- and the warm stage always+ primes before any load, so that is the shipping configuration, not a corner case.++ The pair below is the result the variable exists to surface: NVML says NVLink,+ topo -m says SYS."""+ monkeypatch.setenv("UNSLOTH_P2P_TOPO_CROSSCHECK", "1")+ nvml = {(0, 1): "NVLINK", (1, 0): "NVLINK"}+ topo = {(0, 1): "SYS", (1, 0): "SYS"}+ monkeypatch.setattr(+ LlamaCppBackend, "_probe_nvml_nvlink_topology", classmethod(lambda cls: nvml)+ )+ monkeypatch.setattr(LlamaCppBackend, "_probe_nvlink_topology", staticmethod(lambda: topo))++ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend.prime_nvlink_topology()+ assert LlamaCppBackend._NVLINK_TOPO_CACHE is None, (+ "the prime published under cross-check, so the load path will read the cache "+ "and the two tiers will never be compared"+ )++ # The load path still answers, and the cross-check gets to do its job: topo -m+ # wins the disagreement, so the gate vetoes rather than trusting the fast path.+ assert LlamaCppBackend._nvlink_topology() == topo++ # Without the variable the prime is unchanged.+ monkeypatch.delenv("UNSLOTH_P2P_TOPO_CROSSCHECK", raising = False)+ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ LlamaCppBackend.prime_nvlink_topology()+ assert LlamaCppBackend._NVLINK_TOPO_CACHE == (nvml,)+++def test_cross_check_survives_the_full_warm_then_load_sequence(monkeypatch):+ """End to end in the order Studio actually runs: warm stage primes on its own+ thread, then a load hits the gate. Before the prime learned about the variable+ this spawned zero nvidia-smi and reported the NVML verdict unchallenged."""+ from utils import torch_warmup++ monkeypatch.setenv("UNSLOTH_P2P_TOPO_CROSSCHECK", "1")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 8))+ nvml = {(a, b): "NVLINK" for a in range(8) for b in range(8) if a != b}+ topo_calls = []++ def _topo():+ topo_calls.append(1)+ return {(a, b): "SYS" for a in range(8) for b in range(8) if a != b}++ monkeypatch.setattr(+ LlamaCppBackend, "_probe_nvml_nvlink_topology", classmethod(lambda cls: nvml)+ )+ monkeypatch.setattr(LlamaCppBackend, "_probe_nvlink_topology", staticmethod(_topo))++ LlamaCppBackend._NVLINK_TOPO_CACHE = None+ torch_warmup._prime_nvlink_topology().join(10)+ assert LlamaCppBackend._p2p_veto_reason([0, 1], True, True) is not None+ assert topo_calls, "the cross-check never ran the slow tier"diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pyindex 5db73ca0ca3..6e9f84e4e25 100644--- a/studio/backend/utils/torch_warmup.py+++ b/studio/backend/utils/torch_warmup.py@@ -207,6 +207,42 @@ def _warm_inference_backend() -> None:# Its constructor reaches hw.get_device(), so whoever builds it first pays for detection, which lazily is some request, and sync helpers call the getter inline from async handlers. Building it here makes the getter a dict read. After hardware, to reuse it.from core.inference import get_inference_backendget_inference_backend()+ _prime_nvlink_topology()+++def _prime_nvlink_topology() -> Optional[threading.Thread]:+ """Build the P2P gate's interconnect matrix off the load path. Returns the thread,+ for tests to join.++ Fire and forget on its own thread: the probe can spend its NVML bound plus the+ shell-out timeout, and a warm stage blocking that long delays every stage behind+ it. Nothing here is critical-path, so a prime that never finishes costs one load+ its head start. prime_nvlink_topology stays NVML-only and success-only: a+ subprocess running its full timeout perturbs the process, and a miss cached this+ early would keep P2P off for the life of it (#10613)."""++ def _probe() -> None:+ try:+ from core.inference.llama_cpp import LlamaCppBackend++ # Opted out, so the answer could never be used; the load path skips it too.+ if os.environ.get("UNSLOTH_DISABLE_DC_TUNING") == "1":+ return+ if LlamaCppBackend._p2p_user_opted_out():+ return+ if LlamaCppBackend._effective_gpu_count() < 2:+ return+ if not LlamaCppBackend._all_selected_gpus_match(+ LlamaCppBackend._NVLINK_FABRIC_GPU_RE, None+ ):+ return+ LlamaCppBackend.prime_nvlink_topology()+ except Exception as e: # noqa: BLE001 -- a warm miss costs latency, never correctness+ logger.debug("NVLink topology prime skipped: %r", e)++ worker = threading.Thread(target = _probe, daemon = True, name = "nvlink-topology-prime")+ worker.start()+ return worker_STAGES = (