Skip to content

Studio: tune llama.cpp env for data-center GPUs - #6098

Merged
danielhanchen merged 5 commits into
mainfrom
studio/datacenter-gpu-tuning
Jun 12, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio/datacenter-gpu-tuning

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Studio now detects datacenter / professional NVIDIA GPUs at llama-server launch and sets the llama.cpp env flags that help them, gated so consumer GeForce, AMD/ROCm, CPU and macOS are never touched. This is runtime-only (no new prebuilt binary, no manifest or installer changes): the flags are injected into the llama-server child process env via setdefault, right next to the existing AMD unified-memory APU block.

The flags and the gate come from a benchmark on this 6x B200 box (NVLink, driver 13.1), built from llama.cpp b9518 with CMAKE_CUDA_ARCHITECTURES=80;90;100;120. Runtime flags were toggled per run, no rebuild.

What it sets

flag scope effect
GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F=1 every DC GPU FP32 cuBLAS accumulation (prevents FP16 overflow)
GGML_CUDA_P2P=1 DC multi-GPU peer-to-peer transfers over NVLink
CUDA_SCALE_LAUNCH_QUEUES=4x DC multi-GPU larger CUDA command buffer

All three use setdefault, so a user-supplied value always wins, and UNSLOTH_DISABLE_DC_TUNING=1 turns the whole thing off.

Why these flags (B200 benchmark)

FP32 accumulation, single B200 (tokens/s):

model test baseline fp32acc delta
8B-Q4 pp512 10271 9758 -5.0%
8B-Q4 pp2048 10510 10499 -0.1%
8B-Q4 tg128 279.4 279.5 +0.0%
8B-BF16 pp2048 24659 24663 +0.0%
8B-BF16 tg128 179.0 178.9 -0.1%

Perplexity (wikitext-2-raw, 8B-Q4) is identical: 7.3230 +/- 0.04674 with and without the flag. Cost on B200 is ~0% everywhere except one short-prefill corner; on GeForce the same flag carries a real throughput cost, which is exactly why it is DC-gated.

Multi-GPU, 70B-Q4 across B200s (prompt processing / token gen, tokens/s):

GPUs split env pp2048 tg128
4 layer (default) none 2408 45.6
4 layer (default) p2p+lq 2812 (+16.8%) 45.7
2 row (tensor) none 988 20.2
2 row (tensor) p2p+lq 1492 (+51.1%) 26.8 (+32.6%)
4 row (tensor) p2p+lq 973 (+46.0%) 24.4 (+48.9%)

P2P carries the tensor (row) split (+33-49%), launch-queues carries the default pipeline (layer) split (+8-16% prompt processing); together they never regress, so both are enabled for any multi-DC-GPU launch.

GGML_CUDA_PEER_MAX_BATCH_SIZE is intentionally left out: it is compile-time and would need a separate binary, and this change is runtime-only.

Detection

_is_datacenter_gpu(gpu_indices) reads torch.cuda.get_device_properties(i).name for the selected GPUs and matches a case-insensitive allowlist (A100, A30, H100, H200, H800, GH200, B200, B100, B300, GB200, GB300, L40/L40S, L4, RTX PRO 6000, RTX 6000 Ada). It is NVIDIA-only and fails open to False, so consumer GeForce, ROCm, CPU, macOS and any error path are untouched. A mixed box with one consumer GPU in the selection is treated as non-DC so the tuning never lands on a GeForce card.

Tests

studio/backend/tests/test_datacenter_gpu_tuning.py (37 tests): DC names match, consumer GeForce (4090/5090/3090/2080/1080) rejected, mixed box rejected, per-selection gating, out-of-range indices skipped, ROCm/no-CUDA/missing-torch fail open, single vs multi-GPU flag set, gpu_indices=None falls back to visible device count, user-supplied env value wins over setdefault, and UNSLOTH_DISABLE_DC_TUNING=1 respected.

37 passed in 0.36s

The neighboring test_amd_apu_unified_memory.py / test_rocm_oom_guard.py still pass (43 passed).

shimmyshimmer and others added 2 commits June 8, 2026 15:02
Detect datacenter/professional NVIDIA GPUs at llama-server launch and set
the llama.cpp env flags that help them, gated so consumer GeForce, AMD/ROCm,
CPU and macOS are never touched.

- GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F=1 for any DC GPU (FP32 cuBLAS
  accumulation). On a B200 this is ~0% throughput cost with identical
  perplexity (7.3230 wikitext-2-raw, baseline and on), where on GeForce the
  same flag costs real throughput, hence the gate.
- GGML_CUDA_P2P=1 and CUDA_SCALE_LAUNCH_QUEUES=4x for multi-GPU DC boxes.
  Benchmarked on 6x B200: +33-51% prompt processing on tensor (row) split and
  +8-16% on the default pipeline (layer) split, with no regression on the
  other split or on token generation.

Detection uses torch device names (A100/A30/H100/H200/H800/GH200/B200/GB200/
GB300/L40/L4/RTX PRO 6000/RTX 6000 Ada). A mixed box with one consumer GPU in
the selection is treated as non-DC. All writes are setdefault so a user value
always wins, and UNSLOTH_DISABLE_DC_TUNING=1 turns the whole thing off.

37 unit tests cover detection, multi-GPU gating, user-override precedence, the
disable flag and fail-open on error.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces automatic environment tuning for datacenter and professional NVIDIA GPUs in the llama.cpp backend, configuring performance-optimizing variables such as FP32 cuBLAS accumulation and peer-to-peer launch queues. The review feedback highlights a potential false-positive bug where simple substring matching for "a100" would incorrectly flag low-end professional or laptop GPUs like "NVIDIA RTX A1000" as datacenter parts. To address this, the reviewer suggests utilizing a regular expression with word boundaries for precise matching, updating the detection logic, and adding a corresponding test case.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +1246 to +1255
# Datacenter / professional NVIDIA parts where the llama.cpp FP32-accumulation
# and peer-to-peer tunings help (and where FP32-accum has negligible cost,
# unlike GeForce). Matched as case-insensitive substrings of the torch device
# name (e.g. "NVIDIA A100-SXM4-80GB", "NVIDIA H100 80GB HBM3",
# "NVIDIA RTX PRO 6000 Blackwell Server Edition").
_DATACENTER_GPU_MARKERS = (
"a100",
"a30",
"h100",
"h200",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using a raw substring check (marker in name) to identify datacenter GPUs introduces a false positive bug. For example, the low-end professional/laptop GPU "NVIDIA RTX A1000" contains "a100" as a substring. This causes the method to incorrectly classify it as a high-end datacenter GPU (like the A100), leading to inappropriate environment variables (such as forcing FP32 accumulation, which carries a real performance cost on low-end GPUs, and enabling peer-to-peer/launch queues) being set on consumer/laptop systems.

To prevent this, we should use a regular expression with word boundaries (\b) to match the GPU models as whole words. This matches "a100" in "NVIDIA A100-SXM4-80GB" (since - is a word boundary) but correctly rejects "a1000" in "NVIDIA RTX A1000".

    # Datacenter / professional NVIDIA parts where the llama.cpp FP32-accumulation
    # and peer-to-peer tunings help (and where FP32-accum has negligible cost,
    # unlike GeForce). Matched as whole-word case-insensitive patterns of the torch
    # device name (e.g. "NVIDIA A100-SXM4-80GB", "NVIDIA H100 80GB HBM3",
    # "NVIDIA RTX PRO 6000 Blackwell Server Edition") to prevent false positives
    # on low-end professional/laptop GPUs like "NVIDIA RTX A1000".
    _DATACENTER_GPU_RE = re.compile(
        r"\b(a100|a30|h100|h200|h800|gh200|b200|b100|b300|gb200|gb300|l40s?|l4|rtx pro 6000|rtx 6000 ada)\b"
    )

Comment on lines +1273 to +1286
llama.cpp env tuning. NVIDIA-only and fails open to False, so consumer
GeForce, ROCm, CPU and any error path are left untouched. A mixed box
(one DC + one consumer GPU in the selection) is treated as non-DC so the
tuning never lands on a GeForce card."""
try:
import torch

if getattr(torch.version, "hip", None) is not None:
return False # ROCm reuses torch.cuda.*; not a CUDA datacenter part
if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
return False
count = torch.cuda.device_count()
indices = list(gpu_indices) if gpu_indices else list(range(count))
markers = LlamaCppBackend._DATACENTER_GPU_MARKERS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Update the matching logic in _is_datacenter_gpu to use the compiled regular expression _DATACENTER_GPU_RE instead of raw substring checks.

Suggested change
llama.cpp env tuning. NVIDIA-only and fails open to False, so consumer
GeForce, ROCm, CPU and any error path are left untouched. A mixed box
(one DC + one consumer GPU in the selection) is treated as non-DC so the
tuning never lands on a GeForce card."""
try:
import torch
if getattr(torch.version, "hip", None) is not None:
return False # ROCm reuses torch.cuda.*; not a CUDA datacenter part
if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
return False
count = torch.cuda.device_count()
indices = list(gpu_indices) if gpu_indices else list(range(count))
markers = LlamaCppBackend._DATACENTER_GPU_MARKERS
indices = list(gpu_indices) if gpu_indices else list(range(count))
pattern = LlamaCppBackend._DATACENTER_GPU_RE
saw = False
for _i in indices:
if _i is None or _i < 0 or _i >= count:
continue
try:
name = (torch.cuda.get_device_properties(_i).name or "").lower()
except Exception:
continue
saw = True
if not pattern.search(name):
return False
return saw

Comment on lines +60 to +64
(["NVIDIA GB200"], True),
(["NVIDIA L40S"], True),
(["NVIDIA L4"], True),
(["NVIDIA RTX PRO 6000 Blackwell Server Edition"], True),
(["NVIDIA RTX 6000 Ada Generation"], True),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Add a test case for "NVIDIA RTX A1000 Laptop GPU" to verify that low-end professional/laptop GPUs are correctly classified as non-datacenter GPUs and do not trigger the tuning flags.

Suggested change
(["NVIDIA GB200"], True),
(["NVIDIA L40S"], True),
(["NVIDIA L4"], True),
(["NVIDIA RTX PRO 6000 Blackwell Server Edition"], True),
(["NVIDIA RTX 6000 Ada Generation"], True),
(["NVIDIA GeForce RTX 4090"], False),
(["NVIDIA GeForce RTX 5090"], False),
(["NVIDIA GeForce RTX 3090"], False),
(["NVIDIA GeForce RTX 2080 Ti"], False),
(["NVIDIA GeForce GTX 1080"], False),
(["NVIDIA RTX A1000 Laptop GPU"], False),

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b99e9cfdc5

ℹ️ 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".

Comment on lines +1288 to +1292
for _i in indices:
if _i is None or _i < 0 or _i >= count:
continue
try:
name = (torch.cuda.get_device_properties(_i).name or "").lower()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Map physical GPU IDs before probing torch ordinals

When the parent process already has a numeric CUDA_VISIBLE_DEVICES mask, gpu_indices contains physical IDs from _get_gpu_free_memory() and is later passed through to the child as physical IDs, but torch.cuda.get_device_properties() here expects ordinals relative to the parent mask. On a masked mixed host such as CUDA_VISIBLE_DEVICES=1,3, selecting physical GPU 1 can probe ordinal 1 (physical 3) instead, so the DC tuning can be skipped for a selected datacenter GPU or applied to a selected GeForce card if the other visible ordinal is datacenter.

Useful? React with 👍 / 👎.

Comment on lines +1295 to +1297
saw = True
if not any(marker in name for marker in markers):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Tighten DC GPU marker matching

Because the allowlist is checked as an unbounded substring, shorter markers like a100 and a30 also match non-datacenter device names such as NVIDIA RTX A1000 Laptop GPU or NVIDIA RTX A3000 Laptop GPU. On those workstation/mobile GPUs this will opt them into the same FP32 accumulation and multi-GPU CUDA env tuning that the change is trying to reserve for benchmarked datacenter-class parts, so the match should require whole model tokens (or explicit full-name patterns) instead of arbitrary substrings.

Useful? React with 👍 / 👎.

shimmyshimmer and others added 2 commits June 12, 2026 04:39
… mapping

Two issues in the data-center llama.cpp env tuning gate:

- _is_datacenter_gpu matched the marker allowlist as unbounded substrings, so
  workstation/laptop parts "NVIDIA RTX A1000" and "NVIDIA RTX A3000" matched
  "a100"/"a30" and were wrongly tuned as data-center GPUs (forcing FP32 cuBLAS
  accumulation and the multi-GPU env, which carry a real cost on those cards).
  Switch to a word-boundary regex.

- gpu_indices carries physical GPU ids (translated from torch ordinals by
  _get_gpu_free_memory via CUDA_VISIBLE_DEVICES), but they were passed straight
  into torch.cuda.get_device_properties, which expects mask-relative ordinals.
  On a masked host (e.g. CUDA_VISIBLE_DEVICES=4,5,6,7) a selection like [4,5]
  fell out of range and silently dropped the tuning, and on a mixed mask it could
  probe the wrong GPU class. Build a physical-id to device-name map mirroring
  _get_gpu_free_memory, then look up the selection by physical id.

Add regression tests for the A1000/A3000 false positives and for masked-host
physical-id selection (reordered and mixed-class masks included).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ab3d0e270

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1293 to +1296
try:
physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
except ValueError:
physical_ids = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail closed for UUID CUDA masks

When CUDA_VISIBLE_DEVICES contains UUID/MIG entries, this fallback makes gpu_indices (physical IDs from the nvidia-smi path) get looked up as torch ordinals. On a mixed visible set such as UUID(GeForce),UUID(B200), selecting physical GPU 1 can read ordinal 1's B200 name, so _apply_datacenter_env enables the DC flags even though the child is later pinned to CUDA_VISIBLE_DEVICES=1 (the GeForce). Please fail closed for nonnumeric masks or map the UUIDs explicitly instead of treating physical IDs as ordinals.

Useful? React with 👍 / 👎.

Comment-only pass over the DC tuning block and its tests: shorten verbose
docstrings/comments, drop ones that restate the code, collapse multi-line
blocks. Keep the load-bearing rationale (physical-id vs ordinal mapping, the
word-boundary reason, the B200 benchmark numbers). No code change: verified
with comment_tools.py check --strip-docstrings (code unchanged, comments only).
@danielhanchen
danielhanchen merged commit 25ccfeb into main Jun 12, 2026
1 of 32 checks passed
@danielhanchen
danielhanchen deleted the studio/datacenter-gpu-tuning branch June 12, 2026 09:39
danielhanchen added a commit that referenced this pull request Sep 9, 2026
… warning

Two review findings on the previous commit.

The selection was being remapped as if it held CUDA ordinals. It does not:
_get_gpu_memory sources gpu_indices from `nvidia-smi --query-gpu=index`, the same
tool and the same enumeration as `topo -m`, so they index the matrix directly.
With CUDA_DEVICE_ORDER left at its FASTEST_FIRST default on a partially bridged
host, the remap could turn a PCIe-crossing selection into an NVLinked-looking one
and set GGML_CUDA_P2P on exactly the configuration this gate exists to refuse.
Reading the selection verbatim also removes the whole-matrix fallback and the uuid
join it needed, so a bridged pair now keeps P2P under any device order.

The 'no confirmed NVLink' warning ran before the topology check, so someone who
had deliberately set GGML_CUDA_P2P=1 on a verified NV# pair, the configuration
PR #6098 benchmarked, was told to turn it off. It is now gated on an actual veto.

Tests: 89, including every pair of a bridged 4x fixture under unset, PCI_BUS_ID
and FASTEST_FIRST orderings, and both directions of the warning.
danielhanchen added a commit that referenced this pull request Sep 10, 2026
The unpinned-order veto added in the previous commit was too broad. When every
pair on the box is NV#, the index mapping cannot change the answer: whichever
cards the child resolves, they are linked. Requiring a pinned order there stripped
P2P from every auto-fit launch on an NVSwitch DGX/HGX, which is the configuration
PR #6098 benchmarked and the one this change is most obliged not to regress.

The veto now applies only when the box is not uniformly NVLinked, which is where a
permutation really can select a different pair. Verified against this host's real
nvidia-smi topo -m: 56 pairs, all NV18, and selections [0,1], [0,7], all eight and
None all allowed with no CUDA_DEVICE_ORDER set.

Reported by oobabooga on the PR, who tested both an affected host and an 8x B200.
danielhanchen added a commit that referenced this pull request Sep 10, 2026
…t name (#10646)

* Studio: require a confirmed NVLink fabric before setting GGML_CUDA_P2P

_apply_datacenter_env inferred a working peer-to-peer fabric from the GPU
name. The datacenter allowlist includes RTX 6000 Ada, RTX PRO 6000, L40,
L40S and L4, none of which have an NVLink connector, so on a multi-GPU box
built from those parts the only peer path is PCIe. On bare-metal Linux
behind a translating IOMMU CUDA does not support PCIe peer copies at all:
the write is discarded, the copy still returns cudaSuccess, and every model
emits garbage with nothing logged (#10613).

Split the gate. GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F is about FP32
accumulation, is safe on every part in the list and keeps the existing
allowlist. GGML_CUDA_P2P and CUDA_SCALE_LAUNCH_QUEUES now need both a
narrower NVLink-capable name gate and positive NV# evidence for every
selected pair from nvidia-smi topo -m, cached once per process. Name
membership is necessary, never sufficient: cudaDeviceCanAccessPeer and
nvidia-smi topo -p2p both answered OK on the failing host.

Everything unknown now fails closed. No nvidia-smi, a non-zero exit, a
timeout, a truncated table or an index space we cannot join all withhold
P2P rather than assume it. Where CUDA_DEVICE_ORDER is not PCI_BUS_ID,
physical ids and nvidia-smi indices need not agree, so the whole matrix
must be uniformly NVLinked for the conclusion to hold under any
permutation; the veto says so and names the variable to set.

ggml tests GGML_CUDA_P2P for presence rather than value, so the documented
GGML_CUDA_P2P=0 opt-out was enabling what it looked like it disabled. A
falsy user value is now removed from the child environment and suppresses
the default, matching the GGML_CUDA_ENABLE_UNIFIED_MEMORY handling (#8651).
CUDA_SCALE_LAUNCH_QUEUES is unrelated to peer copies and still applies.

The log now names every variable and value it sets, and on withholding P2P
names the signal that vetoed it. The old message named none of them.

Tests: 72 in test_datacenter_gpu_tuning.py (was 37), including the reported
2x RTX 6000 Ada host, L40S/L40/L4/RTX PRO 6000, a real 8x B200 topo table
with its ANSI header, NIC rows and legend, PCIe-wired A100s, unknown
topology, exact and inexact index mappings, IOMMU group states and the
falsy opt-out.

* Studio: gate GGML_CUDA_P2P on a confirmed NVLink fabric (#10613)

A data-center product name does not imply a working peer fabric. RTX 6000 Ada,
RTX PRO 6000, L40, L40S and L4 are on the allowlist and have no NVLink connector
at all, so their only peer path is PCIe, and a PCIe peer copy on bare-metal Linux
behind a translating IOMMU is unsupported by CUDA: the write is discarded, the
copy still returns cudaSuccess, and every model emits garbage with nothing logged.

GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F is a property of the silicon, not the
interconnect, and keeps the existing allowlist. GGML_CUDA_P2P now additionally
requires positive NV# evidence for the selection from nvidia-smi topo -m, failing
closed on every unknown. The driver is not consulted: can_device_access_peer and
topo -p2p w both answer OK on the affected hosts. CUDA_SCALE_LAUNCH_QUEUES sizes a
command buffer and moves no data, so it is not gated with P2P.

llama.cpp tests GGML_CUDA_P2P for presence, not value, so a user-supplied 0
ENABLED what they were turning off. Falsy values are now removed from the child
env on every launch path, consumer and Vulkan included, since those boxes never
reach the data-center gate. UNSLOTH_DISABLE_DC_P2P=1 drops the peer flag while
keeping FP32 accum; UNSLOTH_FORCE_DC_P2P=1 opts back in. The log now names every
variable set and the signal that withheld P2P.

Adds scripts/p2p_integrity_probe.py, a sentinel-buffer peer-copy check to hand to
anyone reporting garbled multi-GPU output, and studio/NVLINK_P2P.md.

* Drop fork design notes from the branch

* tests: pin three gaps found reviewing the #10613 P2P gate

Three strict xfails, so each passes while the gap is open and fails the moment
it is closed:

- UNSLOTH_DISABLE_DC_P2P=1 vetoes the default but leaves an inherited
  GGML_CUDA_P2P in place, so peer copies stay on despite the user disabling them.
- _apply_datacenter_env setdefault()s over a falsy value when called without the
  call site's _sanitize_p2p_env, leaving GGML_CUDA_P2P=0 present (ON upstream).
- The sanitizer runs only in load_model; the STT sidecar and RAG embedding
  server build their child env from dict(os.environ) and spawn llama-server on
  the GPU without it.

* Remove scratch files swept in by a review pass

_scratch_{routes,topo_probe,veto}.py were my throwaway review harnesses and
test_zz_scratch.py was another reviewer's; none belongs on the branch.

* Address review: cover every launch path, join index spaces on GPU uuid

Review of the first commit, plus a platform/hardware simulation matrix, found
six gaps. All are fixed here.

- The falsy-value strip ran only in load_model. The STT sidecar and the RAG
  embedding server build their own child env and spawn llama-server on the GPU,
  so an inherited GGML_CUDA_P2P=0 still enabled peer copies there. Stripping now
  happens in _llama_server_env_for_binary, which chat, STT and the embedding
  probe all build from, and in the embedding server's own builder. A corrupt
  embedding degrades retrieval silently, with no garbled text to notice.

- UNSLOTH_DISABLE_DC_P2P=1 suppressed our default but did not remove an
  inherited GGML_CUDA_P2P, so a knob named DISABLE left peer copies enabled.

- _apply_datacenter_env trusted the call site to have sanitized first. Called
  directly with a falsy value it kept GGML_CUDA_P2P=0 and logged it as
  "(user)", which reads as off to a human and ON to ggml.

- The index spaces are now joined on GPU uuid, which torch and nvidia-smi both
  report, instead of trusting CUDA_DEVICE_ORDER. The old fallback demanded the
  whole matrix be NV#, which vetoed a genuinely NVLinked pair on a partially
  bridged 4x or 8x box. FASTEST_FIRST is the CUDA default, so that fallback was
  the normal path, not the exotic one. A partial join is refused rather than
  half-trusted.

- The IOMMU diagnosis was unreachable for the host that needs it: a 2x RTX 6000
  Ada fails the NAME gate first and returned before the IOMMU clause. It now
  hangs off every veto that implies a PCIe peer path.

- A raising probe propagated out of _p2p_veto_reason and failed the whole model
  load. It is now total and fail-closed. The IOMMU scan is also cached, since it
  is a boot-time property and the reporter's host has 175 groups to walk.

Warn on a consumer multi-GPU box carrying its own truthy GGML_CUDA_P2P: that
path never reaches the datacenter block, so it warned nowhere before.

scripts/p2p_integrity_probe.py compared against the sentinel only, so a copy
that wrote the wrong data scored a PASS. It now compares against the source.
Non-positive --repeats or --sizes-mib printed PASS without testing anything.

Tests: 88 in test_datacenter_gpu_tuning.py, up from 37 on main.

* Tighten comments in the P2P gate without losing the causal reasons

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Index the topology matrix with the selection verbatim, narrow the P2P warning

Two review findings on the previous commit.

The selection was being remapped as if it held CUDA ordinals. It does not:
_get_gpu_memory sources gpu_indices from `nvidia-smi --query-gpu=index`, the same
tool and the same enumeration as `topo -m`, so they index the matrix directly.
With CUDA_DEVICE_ORDER left at its FASTEST_FIRST default on a partially bridged
host, the remap could turn a PCIe-crossing selection into an NVLinked-looking one
and set GGML_CUDA_P2P on exactly the configuration this gate exists to refuse.
Reading the selection verbatim also removes the whole-matrix fallback and the uuid
join it needed, so a bridged pair now keeps P2P under any device order.

The 'no confirmed NVLink' warning ran before the topology check, so someone who
had deliberately set GGML_CUDA_P2P=1 on a verified NV# pair, the configuration
PR #6098 benchmarked, was told to turn it off. It is now gated on an actual veto.

Tests: 89, including every pair of a bridged 4x fixture under unset, PCI_BUS_ID
and FASTEST_FIRST orderings, and both directions of the warning.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Honour the visibility mask, and stop warning at users who opted out

Three review findings.

nvidia-smi ignores CUDA_VISIBLE_DEVICES (verified here: it lists all 8 cards on a
host masked to one), so the interconnect matrix covers devices the llama-server
child will never touch. With no explicit selection, a mask exposing a clean
NVLinked pair on a partially bridged box was vetoed by a PCIe edge to a hidden
device, losing the speedup for no reason. The no-selection path now filters the
matrix through the resolved mask.

UNSLOTH_DISABLE_DC_P2P=1 returns before the topology is ever inspected, so the
follow-on branch reported the box as having no confirmed NVLink fabric and
suggested forcing P2P back on. That is a corruption warning about a possibly
healthy machine, aimed at someone who had already decided. It now logs at info.

p2p_integrity_probe.py told every passing host to set UNSLOTH_FORCE_DC_P2P=1, but
that override sits behind the data-center name gate and does nothing on a consumer
card. It now gives the right knob for each case and repeats that 0 does not
disable GGML_CUDA_P2P upstream.

Tests: 91.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not trust a numeric visibility mask against the topology matrix

Three more review findings, one of them a bug in the previous commit.

The mask filter added last round treated CUDA_VISIBLE_DEVICES entries as
nvidia-smi indices. They are CUDA ordinals, and CUDA reorders under the default
FASTEST_FIRST, so mask 0,1 can expose physical 0,2. Filtering the matrix with
them could confirm NV# for a pair that is not the one in use and enable P2P
across a real PCIe link, which is the corruption this gate exists to prevent.
_cuda_compute_caps already declines the same mapping on the same grounds. The
filter now applies only under CUDA_DEVICE_ORDER=PCI_BUS_ID and otherwise falls
back to requiring the whole box, which costs the optimisation rather than
correctness.

A deliberate zero-offload load is masked to CUDA_VISIBLE_DEVICES=-1 and moves no
tensors between GPUs, but the tuning and the peer-copy warning both ran before
that state was known. _cpu_only_zero_offload is computed earlier and gates both.

p2p_integrity_probe.py counted an allocation failure, typically a resident model
holding the VRAM, as a lost peer copy: it reported data loss and told the user P2P
was unsafe without having tested a single transfer. Allocation failures are now
reported separately and exit 2, the documented inconclusive code, leaving exit 1
for copies that were tested and did lose data.

Tests: 91.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin PCI_BUS_ID for every gpu_indices mask, warn once, decline ROCm

The gate verifies nvidia-smi physical ids, so the child's mask has to select the
same devices. CUDA_DEVICE_ORDER=PCI_BUS_ID was pinned only for an explicit user
pick, while the mask itself is emitted from gpu_indices in both cases, so an
auto-fit selection verified as physical [0,1] could launch on [0,2] under the
default FASTEST_FIRST: NVLink confirmed for one pair, peer traffic on another.
The ids come from the same nvidia-smi enumeration on both arms, and the existing
comment already describes aligning CUDA with the picker's PCI-bus order, so the
pin now applies whenever that mask is built.

The call-site warning is for hosts that never reach _apply_datacenter_env. A
datacenter box does reach it and is warned there too, so both fired on the first
load. It is now scoped to non-datacenter, non-Vulkan selections.

p2p_integrity_probe.py ran happily under a ROCm torch, since HIP reuses the
torch.cuda namespace, then told the user to set GGML_CUDA_P2P, which only the
CUDA backend reads. It now declines with exit 2 rather than passing and giving an
instruction that does nothing.

Tests: 93, and 2099 across the launch-path suites for the ordering change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Revert the unconditional PCI_BUS_ID pin; withhold P2P instead

The previous commit made CUDA_DEVICE_ORDER=PCI_BUS_ID unconditional for any mask
built from gpu_indices. That reaches further than it should: when the process
inherits a numeric CUDA_VISIBLE_DEVICES under the default FASTEST_FIRST, those
numbers are CUDA ordinals, so forcing PCI order re-reads a scheduler's 0,1
meaning physical 2,0 as physical 0,1 and runs on a GPU that was hidden on
purpose. Exposing a hidden device is a worse outcome than losing a tuning flag.

The pin goes back to explicit user picks only, and the gate handles its own
problem instead: verifying nvidia-smi ids only means something if the child
resolves the same cards, so an auto-fit selection with no pinned order now
withholds GGML_CUDA_P2P and says how to enable it. Same fail-closed rule as every
other unknown here, and it costs an optimisation rather than correctness.

p2p_integrity_probe.py let a later allocation failure downgrade a pair where an
earlier repeat had already seen a mismatch, reporting SKIPPED and exiting 2 while
saying no copy was shown to lose data. Repeats exist to catch intermittent drops,
so observed corruption now outranks a subsequent setup failure.

Tests: 94, plus 2141 across the launch-path suites.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep P2P on a uniformly NVLinked box when the device order is unpinned

The unpinned-order veto added in the previous commit was too broad. When every
pair on the box is NV#, the index mapping cannot change the answer: whichever
cards the child resolves, they are linked. Requiring a pinned order there stripped
P2P from every auto-fit launch on an NVSwitch DGX/HGX, which is the configuration
PR #6098 benchmarked and the one this change is most obliged not to regress.

The veto now applies only when the box is not uniformly NVLinked, which is where a
permutation really can select a different pair. Verified against this host's real
nvidia-smi topo -m: 56 pairs, all NV18, and selections [0,1], [0,7], all eight and
None all allowed with no CUDA_DEVICE_ORDER set.

Reported by oobabooga on the PR, who tested both an affected host and an 8x B200.

* Pin the device order for an unmasked auto-fit launch, skip the probe when off

The revert two commits ago was blanket. The hazard is an INHERITED numeric mask,
not auto-fit itself: a scheduler's CUDA_VISIBLE_DEVICES=0,1 meaning physical 2,0
must not be re-read as physical 0,1. When no mask is in the environment there is
nothing to reinterpret, and the mask we emit is our own, built from nvidia-smi
indices, so pinning PCI_BUS_ID is what makes it name those cards.

Without this, an ordinary Auto load on a partially bridged NVLink box lost the
33-51% win for no reason, since gpu_indices is populated while gpu_ids stays
empty. Uniformly NVLinked boxes were already covered by the previous commit; this
covers the rest.

An explicit opt-out also no longer pays for the topology probe. It ran before
p2p_opted_out was consulted, so on a host where nvidia-smi hangs a user who had
turned P2P off wore up to the full 10s timeout on the first load to decide
something they had already decided.

Tests: 98, plus 1983 across the launch-path suites.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require a complete interconnect matrix, not just the rows that arrived

nvidia-smi topo -m output cut at a ROW boundary still exits 0 and parses cleanly,
just short: the header names 8 GPUs and only 4 rows arrive. Reproduced against
this host, 28 of the 56 directed pairs, every surviving value NV18.

That is enough to look uniformly NVLinked, which is exactly the condition the
unpinned-order escape added two commits ago trusts, so P2P could be enabled for
cards whose links were never read. The parser now requires every directed pair the
header promised and returns None otherwise, which callers already treat as
unreadable and therefore fail closed on.

The real 8x B200 matrix is unaffected: 56 pairs, all four selections still allowed.

Tests: 100.

* Track whether GPU ids are PCI indices, and widen the probe's ROCm check

_get_gpu_memory returns nvidia-smi PCI indices from its primary branch and torch
CUDA ordinals from the fallback it takes when the nvidia-smi memory query fails.
The unmasked-auto-fit pin added last commit assumed the former, so on a host where
that query fails and PCI and CUDA order differ, pinning PCI_BUS_ID re-emitted
ordinals as a different set of cards: Auto could run on GPUs other than the ones
whose free memory it measured, and the topology check could verify the wrong pair.

The two branches now record which index space they returned, and the pin requires
PCI indices. An explicit user pick is unaffected, since those ids come from the
UI's own PCI-ordered picker.

The probe's ROCm guard only tested torch.version.hip. AMD SDK wheels leave that
unset and encode rocm in __version__ instead, which is why the backend's
_torch_is_rocm checks both, so a multi-GPU AMD host could still run the CUDA-only
probe and be told to set GGML_CUDA_P2P. It now checks both.

Tests: 102, plus 2027 across the launch-path suites.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the #10613 P2P gate comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants