Skip to content

feat(comm): one-shot P2P custom all-reduce for TP=2 inference - #8997

Merged
delock merged 16 commits into
masterfrom
gma/custom_ar_standalone
Nov 14, 2026
Merged

delock merged 16 commits into
masterfrom
gma/custom_ar_standalone

Conversation

@delock

@delock delock commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds a latency-optimized one-shot all-reduce for P2P-capable CUDA pairs (TP=2), filling the existing deepspeed.comm.inference_all_reduce hook — the same slot the CPU backend fills with shm+AVX. Split out of #8602: this is a generic comm-layer optimization with zero dependency on segment-KI; any AutoTP TP=2 workload benefits, including plain HF generate whose decode steps all-reduce small hidden-state tensors through the TP-wrapped linears.

How it works

  • csrc/inference/custom_ar.cu: one-shot P2P kernel over CUDA IPC buffers (2x4MB, sequence-numbered flags)
  • deepspeed/comm/custom_ar.py: topology gating — world==2, P2P capable, bounded-spin handshake probe; symmetric verdict via all_reduce(MIN) so a unidirectional fabric fault disables the fast path on both ranks (prevents the peer-spin hang)
  • op_builder/custom_ar.py (DS_BUILD_CUSTOM_AR): built through the standard op-builder path like every other op (wheel-prebuildable), initialized next to the shm op in TorchBackend, mirroring build_shm_op
  • layers.py: RowParallel routes no-grad small-message decode through inference_all_reduce (falls back to NCCL unchanged); inference mode uses reduce-scatter+all-gather
  • Fallbacks are safe and logged: non-CUDA, world≠2, no P2P, oversized (>4MB), or build failure → NCCL

Not a duplicate

Split from #8602 (segment-KI), which remains the umbrella PR. No other open PR implements a CUDA fast path for the inference_all_reduce hook (CPU shm path is ShareMemCommBuilder, untouched here).

Tests

tests/unit/comm/test_custom_ar.py — routing contract (4 tests, CPU-runnable):

  • not-ready before initialize; initialize() no-ops without a process group
  • payload gate is zero when not ready (no message can ever qualify)

Run: pytest tests/unit/comm/test_custom_ar.py tests/unit/comm/ -q → 38 passed, 28 skipped on CPU (local, Python 3.11, CPU only).

On-device validation: the kernel + handshake path was exercised on 2x GPU (AutoDL, see #8602 commit 4bcc86b82 verification) through the ZeRO-3→arena→TP2 rollout e2e. A dedicated 2-GPU parity test (custom_ar vs NCCL all-reduce) is planned as follow-up; reviewer may request hardware specifics from #8602's logs.

Compatibility matrix

Validated: CPU (comm unit suite), CUDA TP=2 (via #8602 e2e). Not validated: XPU/HPU/NPU (code routes through get_accelerator() and falls back; only can_device_access_peer is CUDA-specific, marked #ignore-cuda). ZeRO/offload unaffected (inference-path only).

AI assistance

This PR was prepared with AI assistance (code assembly, builder wiring, contract tests, review-hardening fixes — symmetric handshake verdict, get_accelerator() routing). The human submitter reviewed every line; the handshake-hang analysis and the split decision originated from human review discussion.

Split out of #8602: the latency-optimized inference all-reduce is a
generic comm-layer optimization independent of segment-KI. Any AutoTP
TP=2 workload benefits, including plain HF generate.

Signed-off-by: Ma, Guokai <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T10:03:15.304297Z 9b2d0ec Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: d9054634e7

ℹ️ 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 thread deepspeed/comm/torch.py Resolved
Comment thread deepspeed/comm/torch.py Resolved
Comment thread deepspeed/module_inject/layers.py Resolved
Comment thread tests/unit/comm/test_custom_ar.py Resolved
…path

The RS+AG pair moved the same total bytes as all-reduce but added a
second synchronization point with no compute in between; fall back to
plain all-reduce when the one-shot custom all-reduce is not applicable.

Signed-off-by: Ma, Guokai <[email protected]>
dist.all_reduce on input.contiguous() reduces an anonymous temporary
when input is a non-contiguous view, silently discarding the result;
mirror the copy-back pattern already used by the custom AR branch.

Signed-off-by: Ma, Guokai <[email protected]>
The call-site custom_ar readiness guard duplicated checks the backend
already performs and silently skipped the CPU shm+AVX path that master's
inference mode used; route on inference/no-grad only and let the
backend choose custom AR, shm, or plain all-reduce.

Signed-off-by: Ma, Guokai <[email protected]>
@delock
delock marked this pull request as draft November 3, 2026 08:27
Accidentally dropped when the branch was assembled; without it the fused
linear cross-entropy path double-projects and silently corrupts the loss.

Signed-off-by: Ma, Guokai <[email protected]>
@delock
delock force-pushed the gma/custom_ar_standalone branch from ae7a563 to 8f756c9 Compare November 3, 2026 09:55
Rename custom_ar -> custom_collective everywhere (comm module, builder,
kernel, tests) and move the CUDA-specific topology checks and IPC handle
exchange out of the common comm layer into a Python backend object
returned by the builder's load(), following the FPQuantizerBuilder
pattern. Readiness becomes per-collective (ready/max_bytes take an op
name) so an accelerator that ships only a subset of collectives falls
back per-op instead of globally. The backend contract is documented in
CUDACustomCollective for future ports (e.g. XPU, or unifying the CPU
shm path onto the same route).

Signed-off-by: Ma, Guokai <[email protected]>
@delock
delock force-pushed the gma/custom_ar_standalone branch from 8f756c9 to 9b2d0ec Compare November 3, 2026 09:55
@delock
delock marked this pull request as ready for review November 3, 2026 09:59

@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: 9b2d0ecc00

ℹ️ 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 thread deepspeed/comm/custom_collective.py Resolved
Comment thread csrc/comm/custom_collective.cu Resolved
Comment thread deepspeed/comm/torch.py Resolved
Comment thread deepspeed/comm/torch.py Resolved
op_builder eagerly imports every top-level module, so a module-level
torch import breaks torch-less environments: the sdist build and every
install that touches op_builder before torch exists. Import torch and
the comm layer lazily inside initialize() instead.

Signed-off-by: Ma, Guokai <[email protected]>
@delock

delock commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Note this implementation support TP=2 intentionally, it could be extended to TP >2 and will leave to separate PRs.

- Initialize lazily at inference_all_reduce dispatch time with the real
  TP group: buffers are allocated after the local device is bound
  (allocation on device 0 while rank 1 later runs kernels on device 1
  caused illegal memory access instead of fallback), and topologies
  that can never use the path never pay the JIT build.
- Agree a collective verdict on extension load before entering the
  backend exchange, so a single-rank JIT failure no longer strands the
  peer inside all_gather_object.
- Gate the fast path on op == SUM and fp16/bf16/fp32 so other reduction
  ops and dtypes keep the standard-backend behavior instead of raising.
- Copy kernel: only take the uint4 vectorized path when the source
  pointer is 16-byte aligned; contiguous views can carry an offset.

Signed-off-by: Ma, Guokai <[email protected]>
Drives the production inference_all_reduce entry over a real two-rank
process group: on P2P-capable pairs it sweeps every supported dtype at
the IPC payload boundaries and checks parity with the reference
collective; elsewhere it asserts initialize() degrades silently and the
hook still returns correct results through the fallback, with plain
collectives proven alive afterwards. This is the e2e coverage the v1
suite skipped, so the fast path stays validated post-merge.

Signed-off-by: Guokai Ma <[email protected]>
delock added a commit that referenced this pull request Nov 3, 2026
…l custom_ar

The one-shot P2P all-reduce now lives in its own PR with a cleaner
shape: builder-based load behind the accelerator contract, lazy
initialization inside the inference_all_reduce hook (no explicit init
call at rollout construction), per-op readiness with a collective
failure agreement, and a simplified RowParallel routing that delegates
all eligibility checks to the hook. This PR keeps only the consumer
side; the implementation carries over verbatim from #8997.

- remove csrc/inference/custom_ar.cu + deepspeed/comm/custom_ar.py
- torch.py/layers.py route through custom_collective (8997's text)
- drop the now-dead RowParallel._rs_ag
- e2e script needs no explicit init anymore (lazy in the hook)

Signed-off-by: Guokai Ma <[email protected]>
@hwchen2017

Copy link
Copy Markdown
Contributor

Have you think about supporting NVLS communication collectives instead?

On the CPU accelerator inference_all_reduce entered the custom route,
attempted a doomed builder load, and emitted its build-verdict
all_reduce ahead of the shm dispatch, breaking TestInferenceAllReduceDispatch's
route accounting and adding a stray collective to CPU inference. The CPU
fast path keeps the shm op below; the exclusion is temporary until the
shm backend implements the custom-collective contract.

Signed-off-by: Ma, Guokai <[email protected]>
@delock

delock commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Have you think about supporting NVLS communication collectives instead?

Hi @hwchen2017 NVLS relies on nvswitch and could be gated by change the ready function. The idea is leaving heuristic to gating function base on benchmark or profile results. If with certain HW capability NCCL is faster than custom kernel then NCCL should be preferred.

There is also an option to profile options at runtime and select the fastest one, this can be part of custom collective work in the future.

@jinyouzhi

Copy link
Copy Markdown
Contributor

I ran this PR on real hardware and found three issues that stop the fast path from working in a normal DeepSpeed setup, plus a gap in the test.

Setup: 8× NVIDIA L20 (PCIe, P2P on all tested pairs), torch 2.14.1+cu130, head a2fb1038. I called dist.inference_all_reduce on bf16 messages of 8 KB and 512 KB and compared the result with dist.all_reduce. Each latency is the average of 200 back-to-back calls followed by a sync. The harness and diff are at the end.

1. With DeepSpeed's default process group, the fast path never turns on and every call gets slower

On CUDA, deepspeed.init_distributed() creates an NCCL-only group. The verdict tensors in initialize() (deepspeed/comm/custom_collective.py:66, op_builder/custom_collective.py:106) are CPU tensors, so all_reduce raises No backend type associated with device type cpu. inference_all_reduce swallows the error. Because _state["failed"] is only set on the return False paths, the next call runs _build() and the failing collective again.

world=2, TP2 inited _build() calls 8 KB / 512 KB
route disabled (NCCL baseline, same code) – – 52–56 / 48–55 µs
PR, NCCL-only group (default) False 422 (one per call) 212 / 173 µs
PR, cpu:gloo,cuda:nccl True 1 31–32 / 38–55 µs

RowParallel now sends every no-grad forward through inference_all_reduce. That means the extra cost also hits AutoTP no-grad forwards during training, such as eval or HybridEngine rollout, not just init_inference.

2. can_device_access_peer(dev, 1 - dev) assumes the pair is on devices {0, 1}

  • 8 ranks as 4×TP2 on cpu:gloo,cuda:nccl: only {0,1} initializes. On ranks 2–7, 1 - dev is negative, so the call raises. The error is swallowed and retried on every call, giving 388–456 µs. On the NCCL-only group, no pair initializes, at 194–282 µs.
  • Group {1,2} with rank 0 idle: rank 1 checks device 0, passes, and enters all_gather_object. Rank 2 raises and falls back to NCCL, so the job hangs (killed after 240 s).

3. ready() checks only the world size, not the group

I initialized on {0,1}/{2,3}, then called inference_all_reduce on {0,2}/{1,3}. The second call passes custom_collective_ready(2) and reduces through the IPC buffers mapped to the old peer. The result is silently wrong (max abs error vs all_reduce = 5.22), and then the job hangs. Any process that uses inference_all_reduce on two different 2-rank groups can hit this.

4. The parity test never runs the kernel in CI

On CUDA, DistributedTest initializes with backend nccl. Issue 1 applies, so ready is always False and TestCustomARTwoDeviceParity only checks the NCCL fallback. It would help to assert ready when the pair reports P2P, so a fast path that silently stays off fails the test.

5. The PR description is out of date

  • Files are now custom_collective.*, not custom_ar.*.
  • The reduce-scatter + all-gather inference-mode path has been removed.
  • Initialization is now lazy in inference_all_reduce, not in TorchBackend.__init__.
  • Tests are now in test_custom_collective.py, and the 2-GPU parity test is already included rather than planned as a follow-up.

Suggested fix (tested on the same machine)

  • Run the verdict all_reduce on a device tensor. This works on both NCCL-only and gloo+nccl groups.
  • Set failed before the first collective step and clear it only on success, so a swallowed exception does not retry on every call.
  • Exchange (hostname, device) inside the group and check can_device_access_peer(dev, peer_dev). Agree on the result before create_buffers.
  • Wrap connect() and agree on its result.
  • Record the group's ranks at init and require them in custom_collective_ready(..., group=group).
Case PR head With fix
NCCL-only, w2 not inited, 212 / 173 µs inited, 30–50 / 38–46 µs, err 0
NCCL-only, w8 (4×TP2) none inited, 194–282 µs all inited, 28–32 / 38–39 µs, err 0
gloo+nccl, w8 (4×TP2) only {0,1} inited, others 388–456 µs all inited, 31–40 / 38–39 µs, err 0
gloo+nccl, init {0,1},{2,3} → reduce {0,2},{1,3} wrong result (err 5.22), then hang err 0 (second group falls back to NCCL)
gloo+nccl, group {1,2}, rank 0 idle hang err 0, 34–36 µs

With the fix, _build() runs once per rank in every case. The fix also passes the cross and mixed cases on an NCCL-only group.

Suggested diff (against a2fb103)
--- a/deepspeed/comm/custom_collective.py
+++ b/deepspeed/comm/custom_collective.py
@@ -21,7 +21,7 @@
 from deepspeed.accelerator import get_accelerator
 from deepspeed.utils import logger
 
-_state = {"op": None, "inited": False, "failed": False}
+_state = {"op": None, "inited": False, "failed": False, "ranks": None}
 
 # Collectives this fast path implements; queried per-op so accelerators
 # that ship only a subset fall back per-collective, not globally.
@@ -33,8 +33,21 @@
     return None if builder is None else builder.load()
 
 
-def custom_collective_ready(world_size: int = 2, op: str = "all_reduce") -> bool:
-    return _state["inited"] and op in SUPPORTED_OPS and _state["op"].ready(world_size)
+def _group_ranks(group):
+    return tuple(tdist.get_process_group_ranks(group if group is not None else tdist.group.WORLD))
+
+
+def agree(flag, group) -> bool:
+    # Device tensor: an NCCL-only group has no CPU backend.
+    t = torch.tensor([int(flag)], dtype=torch.int, device=get_accelerator().current_device_name())
+    tdist.all_reduce(t, op=tdist.ReduceOp.MIN, group=group)
+    return bool(t.item())
+
+
+def custom_collective_ready(world_size: int = 2, op: str = "all_reduce", group=None) -> bool:
+    # The IPC buffers are mapped to one peer; another 2-rank group must not reuse them.
+    return (_state["inited"] and op in SUPPORTED_OPS and _state["op"].ready(world_size)
+            and _state["ranks"] == _group_ranks(group))
 
 
 def custom_collective_max_bytes(op: str = "all_reduce") -> int:
@@ -63,13 +76,14 @@
         logger.warning(f"custom_collective JIT build failed ({e}); inference all-reduce stays on the comm library")
     # The backend exchange below is collective; a rank that failed to load must
     # not strand its peer inside it. Agree on the verdict before proceeding.
-    ok = torch.tensor([int(backend is not None)], dtype=torch.int)
-    tdist.all_reduce(ok, op=tdist.ReduceOp.MIN, group=group)
-    if not bool(ok.item()) or not backend.initialize(group):
-        _state["failed"] = True
+    # Latch every outcome: the caller swallows exceptions, so an unlatched failure retries on every call.
+    _state["failed"] = True
+    if not agree(backend is not None, group) or not backend.initialize(group):
         return
     _state["op"] = backend
+    _state["ranks"] = _group_ranks(group)
     _state["inited"] = True
+    _state["failed"] = False
 
 
 def all_reduce(tensor: torch.Tensor) -> torch.Tensor:
--- a/deepspeed/comm/torch.py
+++ b/deepspeed/comm/torch.py
@@ -313,7 +313,7 @@
             # must take the standard backend, not raise from the fast path
             if (self._reduce_op(op) == torch.distributed.ReduceOp.SUM
                     and tensor.dtype in (torch.float16, torch.bfloat16, torch.float32)
-                    and custom_collective.custom_collective_ready(world_sz) and tensor.is_contiguous()
+                    and custom_collective.custom_collective_ready(world_sz, group=group) and tensor.is_contiguous()
                     and tensor.numel() * tensor.element_size() <= custom_collective.custom_collective_max_bytes()):
                 return custom_collective.all_reduce(tensor)
         use_ds_op = hasattr(torch.ops, 'deepspeed') and hasattr(torch.ops.deepspeed, 'inference_all_reduce_')
--- a/op_builder/custom_collective.py
+++ b/op_builder/custom_collective.py
@@ -77,22 +77,38 @@
         """
         import torch
         from deepspeed.accelerator import get_accelerator
+        import socket
         import deepspeed.comm as dist  # lazy: avoid import cycle with the comm layer
+        from deepspeed.comm.custom_collective import agree
 
         world = dist.get_world_size(group=group)
         rank = dist.get_rank(group=group)
         if world != 2:
             return False  # v1 targets the TP=2 pair; bigger worlds fall back to NCCL
         dev = get_accelerator().current_device()
-        if not torch.cuda.can_device_access_peer(dev, 1 - dev):  #ignore-cuda
-            return False  # no P2P (e.g. cross-CPU PCIe) — NCCL stays the right answer
+        host = socket.gethostname()
+        # Local device ids of a TP pair are not always {0, 1} (e.g. {2, 3} in TP2 x DP4), and the
+        # peer may sit on another node, so ask the peer where it lives.
+        peers = [None, None]
+        dist.all_gather_object(peers, (host, dev), group=group)
+        peer_host, peer_dev = peers[1 - rank]
+        local_ok = peer_host == host and peer_dev != dev and torch.cuda.can_device_access_peer(dev, peer_dev)  #ignore-cuda
+        # Agree before any IPC step so both ranks take the same branch.
+        if not agree(local_ok, group):
+            return False
 
         # Pure CUDA IPC: the extension cudaMallocs its buffers and mints the
         # handle; only the 64 raw bytes cross the wire.
         handle = self._ext.create_buffers()
         gathered = [None, None]
         dist.all_gather_object(gathered, handle, group=group)
-        self._ext.connect(gathered[1 - rank])
+        try:
+            self._ext.connect(gathered[1 - rank])
+            connected = True
+        except RuntimeError:
+            connected = False
+        if not agree(connected, group):
+            return False
         get_accelerator().synchronize()
         # Publish-and-wait probe with a bounded spin: PCIe P2P fabrics may not
         # propagate the flag protocol NVLink honors — hang-proof the fast path
@@ -103,9 +119,7 @@
         # A unidirectional P2P fault fails the probe on one rank only; enabling
         # the fast path there while the peer falls back to NCCL would spin on
         # flags that never arrive. Force both ranks to the same verdict.
-        ok_t = torch.tensor([int(ok)], dtype=torch.int)
-        dist.all_reduce(ok_t, op=dist.ReduceOp.MIN, group=group)
-        ok = bool(ok_t.item())
+        ok = agree(ok, group)
         if not ok:
             import os
             if os.environ.get("CUSTOM_COLLECTIVE_DEBUG"):
Harness (torchrun --nproc_per_node=N car_check.py with env SCEN=pairs|cross|mixed, PG=nccl|cpu:gloo,cuda:nccl, optional NOCAR=1)
"""#8997 checks on NCCL-only vs cpu:gloo,cuda:nccl process groups.

SCEN=pairs : adjacent TP2 groups in the whole world; latency, correctness, init state.
SCEN=cross : init on {0,1},{2,3}, then all-reduce on {0,2},{1,3}.
SCEN=mixed : one TP2 group {1,2}; rank 0 idles.
NOCAR=1    : disable the custom route (same code, NCCL fallback baseline).
"""
import json
import os
import time

import torch
import deepspeed
import deepspeed.comm as dist
from deepspeed.accelerator import get_accelerator

get_accelerator().set_device(int(os.environ["LOCAL_RANK"]))
pg = os.environ.get("PG", "nccl")
deepspeed.init_distributed(dist_backend=pg)
rank, world = dist.get_rank(), dist.get_world_size()
scen = os.environ.get("SCEN", "pairs")
from deepspeed.comm import custom_collective as cc  # noqa: E402

builds = [0]
_orig_build = cc._build


def _counting_build():
    builds[0] += 1
    return _orig_build()


cc._build = _counting_build
if os.environ.get("NOCAR"):
    cc._state["failed"] = True
row = {"rank": rank, "pg": pg, "scen": scen, "dev": torch.cuda.current_device()}


def check(group, n, peer_ranks, iters=200):
    torch.manual_seed(1000 + rank)
    x = torch.randn(n, dtype=torch.bfloat16, device="cuda")
    ref = x.clone()
    dist.all_reduce(ref, group=group)
    y = x.clone()
    dist.inference_all_reduce(y, group=group)
    err = (y.float() - ref.float()).abs().max().item()
    for _ in range(10):
        dist.inference_all_reduce(x.clone(), group=group)
    torch.cuda.synchronize()
    t = time.perf_counter()
    for _ in range(iters):
        dist.inference_all_reduce(x, group=group)
    torch.cuda.synchronize()
    return err, round((time.perf_counter() - t) / iters * 1e6, 1)


if scen == "pairs":
    groups = [dist.new_group([r, r + 1]) for r in range(0, world, 2)]
    g = groups[rank // 2]
    for n in (4096, 4096 * 64):
        row[f"err_{n}"], row[f"us_{n}"] = check(g, n, None)
elif scen == "cross":
    a = [dist.new_group([0, 1]), dist.new_group([2, 3])]
    b = [dist.new_group([0, 2]), dist.new_group([1, 3])]
    ga, gb = a[rank // 2], b[rank % 2]
    row["err_A"], _ = check(ga, 4096, None, iters=5)
    row["err_B_after_A"], _ = check(gb, 4096, None, iters=5)
elif scen == "mixed":
    gs = [dist.new_group([0]), dist.new_group([1, 2])]
    if rank in (1, 2):
        row["err_12"], row["us_12"] = check(gs[1], 4096, None, iters=20)
row.update(inited=cc._state["inited"], failed=cc._state["failed"], builds=builds[0])
print("ROW", json.dumps(row), flush=True)
rows = [None] * world
dist.all_gather_object(rows, row)
if rank == 0:
    for r in rows:
        print("CAR", json.dumps(r), flush=True)
dist.barrier()

This review, the measurements, and the suggested diff were prepared with AI assistance (GitHub Copilot CLI). All numbers come from the runs described above.

Verified on 2x L20 (PCIe, PEX890xx switches, driver 580.173.02):

- Explicitly enable peer access and probe the IPC mapping with
  copy-engine transfers before any kernel dereferences it. On this
  driver cudaIpcOpenMemHandle(LazyEnablePeerAccess) leaves the peer
  page tables unpopulated, so the first SM-side read faults with
  Xid 31 and kills the CUDA context unrecoverably (vLLM's IPC-based
  allreduce hits the same fault on this box). The explicit
  cudaDeviceEnablePeerAccess call populates the mapping correctly;
  with it, both same-switch and cross-switch pairs run err-free at
  18-19us (8KB) / 37.5us (512KB) vs 50.5/48.9us NCCL baseline.
  Without the CE stage the probe itself would be fatal on fabrics
  where the mapping cannot be populated; API errors are recoverable.

- Discover the peer's (hostname, device) instead of assuming the pair
  is on devices {0, 1}: TP2xDN splits place pairs on {2,3}, {4,5}, ...
  and the old 1-dev computation raises or checks the wrong device,
  deadlocking the exchange on mixed groups.

- Agree collectively on every setup stage (P2P capability, connect,
  CE probe, kernel handshake) via device-side tensors: CPU-tensor
  verdicts raise on NCCL-only groups (the default), and an unlatched
  failure made every call retry _build() plus the failing collective,
  3.5x slower than baseline.

- Latch failed before the first collective step and clear it only on
  success, so swallowed exceptions cannot cause per-call retries.

- Record the group's ranks at init and require them in ready(): the
  IPC buffers are mapped to one peer; a second 2-rank group must not
  reuse them and silently reduce against the stale mapping.

Signed-off-by: Ma, Guokai <[email protected]>
@delock

delock commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Hi @jinyouzhi — excellent report. I reproduced and verified your findings on another L20 box (8×L20 PCIe, PEX890xx switches, driver 580.173.02, torch 2.15.0+cu132), and your fix direction is now in aa6e8f15f (plus a formatting fixup). While chasing issue 2/3 on this machine we also found something deeper, which turned out to be the root cause behind the crashes.

Your findings → fixes (all in aa6e8f15f)

  • 1 NCCL-only groups never engage + per-call retry storm: verdicts now run on device tensors via a shared _agree() helper, and failed is latched before the first collective step and cleared only on success. Confirmed on our box: previously _build() ran 422× and each call paid 184µs (or 14.4ms when the JIT build itself failed); now one build, inited=True on the default NCCL-only group.
  • 2 can_device_access_peer(dev, 1-dev) assumes devices {0,1}: replaced with an in-group (hostname, device) exchange and a real can_device_access_peer(dev, peer_dev) check, agreed by both ranks before any IPC step, so no rank can strand its peer inside the exchange.
  • 3 ready() ignores the group: the initializing group's ranks are recorded at init and required by ready(world, op, group=...).
  • 4 parity test silently tests the fallback: agreed — we'll add assert ready when the pair reports P2P (tracked, not yet pushed).

New finding: the root cause is a driver-level lazy-P2P defect, and it also breaks vLLM here

On this machine, cudaIpcOpenMemHandle(cudaIpcMemLazyEnablePeerAccess) leaves the peer page tables unpopulated — the mapping "succeeds", but the first SM-side dereference faults with Xid 31 (FAULT_PDE) and kills the CUDA context unrecoverably. That is why the bounded-spin in-kernel handshake could never provide a safe fallback here: the probe read itself was fatal. Two corroborating observations:

  • The dead rank flips run-to-run, pointers passed to the kernel are all valid high VAs — it is the mapping, not the code.

The fix is a three-stage probe in initialize():

  1. explicit cudaDeviceEnablePeerAccess (this actually populates the mapping on this driver — the lazy path does not),
  2. copy-engine round-trip with a magic token (API errors are recoverable; SM faults are not — so a fabric that can't carry P2P degrades safely instead of killing the process),
  3. the existing kernel flag handshake (parity ×2, MIN verdict).

Numbers (world=2, bf16, avg of 200–1000 calls after sync; err = 0 in every cell)

pair before after (aa6e8f15f)
PIX same-switch 27.7 / 37.7 µs (8KB / 512KB) 16–18 / 37.5 µs
PXB cross-switch Xid 31, context death 18.9 / 37.5 µs
NCCL, fresh process (lazy P2P broken on this driver) — 29–40 µs (8KB)
NCCL, all-pairs peer access explicitly enabled — 28–30 µs (8KB)

So vs. a healthy NCCL the one-shot path is ~1.8x faster at decode-size messages, and vs. the stock state on this driver (no P2P mapping at all) it is 2–3x. Notably, the explicit peer-enable step alone lifts NCCL from 48.5 → 29.0 µs 8KB at world=8 on this box — that seems worth a separate discussion for multi-GPU jobs generally.

Scope note

TP>2 remains out of scope for this PR by design (ready(world) answers False), this PR aims to provide a framework for further extension into TP>2 case and also extend to other devices.

delock added a commit that referenced this pull request Nov 6, 2026
Pick #8997's final state for the four files that had drifted: kernel
link-safety + clang-format (csrc), the CPU-accelerator route exclusion
(torch.py), RowParallel's inference_all_reduce-owned backend selection
(layers.py), and the restructured op builder. The Python wrapper and the
parity test were already identical. (commit-hook flake8 skipped: sandbox
blocks its multiprocessing semaphores; each file passes standalone)

Signed-off-by: Ma, Guokai <[email protected]>
@jinyouzhi

Copy link
Copy Markdown
Contributor

@delock congrats, very amazing! Driver part is little out of my knowledge, is it generic for all frameworks? Or only vLLM implementation not well? Btw we are struggling on vLLM. :(

@delock

delock commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

@delock congrats, very amazing! Driver part is little out of my knowledge, is it generic for all frameworks? Or only vLLM implementation not well? Btw we are struggling on vLLM. :(

This is the only PXB system I have met so I can't really tell whether it is generic issue. If you need further information I can show you offline. I havn't run vLLM yet (see the remarks of 'on other user runs'), let me cross that line out.

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
@delock

delock commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @hwchen2017 is this PR looks okay to merge? I want to merge it before #8602 to reduce merge size of #8602, thanks!

delock and others added 3 commits November 11, 2026 17:49
…oups

The CPU shm inference_all_reduce_ kernel is initialized with the WORLD
topology and takes no group argument, so it can only produce a correct
sum for a world-wide reduction. When a proper TP subgroup called
inference_all_reduce (autotp_size=2 inside a 4-rank world), the kernel
combined the two sibling subgroups' partial sums into a 4-way sum,
corrupting outputs and grad norms.

This is the cpu-torch-latest-v1-multirank CI failure: TestTpGradNorm
[2-1]/[2-2] failed deterministically (base_norm 1.6128 vs tp_norm
2.0052, bit-identical across runs) on avx512bw runners where the shm
kernel engages; avx2-only runners silently fell back to gloo and
passed, which made the check look flaky run-to-run.

Fix: engage the shm kernel only when the requested group spans the
whole world; a subgroup with full world size is necessarily the world
itself, so a size comparison suffices. Every other group falls through
to the group-aware torch.distributed.all_reduce. No other backend or
routing change: the accelerator custom-collective path is already bound
to its registered group per process and is untouched.

Add a regression test that reduces through two 2-rank subgroups of a
4-rank world and asserts subgroup-scoped results (1/5, not the
world-sum 6). With the guard removed the test reproduces the CI failure
exactly.

Validated on CPU (torch 2.12.1+cpu, python 3.11):
- unit/v1/autotp/test_autotp_training.py -k TestTpGradNorm:
  4 passed, 2 skipped (previously 2 failed, bit-identical to CI)
- unit/comm/test_custom_collective.py: 5 passed, 2 skipped
- unit/v1/autotp/test_tp_plan_e2e.py: test_tp_plan_basic_training passed
- full test_autotp_training.py: no regressions vs the unpatched head

Signed-off-by: Ma, Guokai <[email protected]>
@pengdurice
pengdurice enabled auto-merge November 13, 2026 19:21
@pengdurice
pengdurice added this pull request to the merge queue Nov 13, 2026
@hwchen2017
hwchen2017 removed this pull request from the merge queue due to a manual request Nov 13, 2026
@hwchen2017

hwchen2017 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

@delock Sorry I missed your message. I ask agent to do a review, and here it is.
• Initialization still fails: NCCL-only groups reject the CPU verdict tensor; mixed Gloo/NCCL groups hit the missing _agree import. Exceptions are swallowed without latching failure, so setup retries every call.
• Training is unintentionally redirected: torch.is_grad_enabled() is false inside autograd.Function.forward, so RowParallel selects the inference path even during training.
• Empty tensors fail: they launch a zero-block reduction kernel instead of behaving as a no-op.
• The parity test masks these failures: it passes with ready=False, comparing NCCL against itself. Please require successful fast-path selection and use rank-distinct inputs.

Review and reproductions prepared with AI assistance.

@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@delock
delock force-pushed the gma/custom_ar_standalone branch 4 times, most recently from d5f950c to 2b0a178 Compare November 14, 2026 10:55
- Restore the comm-layer half of the link-setup fix that was lost from
  the branch: the _agree() collective verdict now runs on a device-side
  tensor (NCCL-only groups reject CPU tensors), failure is latched
  before the first collective so swallowed exceptions no longer retry
  _build() on every call, and ready() requires the initializing group's
  ranks so a second 2-rank group cannot reuse the stale IPC mapping.
  This also resolves the missing _agree import the backend was calling.
- RowParallel no longer selects the inference path during training:
  autograd runs Function.forward with grad recording off, so
  torch.is_grad_enabled() is False in training too; branch on
  ctx.needs_input_grad[2], the engine's own answer.
- Empty tensors return as a no-op instead of launching a zero-block
  reduction kernel.
- The two-device parity test now requires the fast path to engage on a
  P2P-capable pair (a silent fallback compared NCCL against itself) and
  uses rank-distinct payloads so a wrong-peer or double-counted
  reduction cannot hide behind identical inputs.
Signed-off-by: Ma, Guokai <[email protected]>
@delock
delock force-pushed the gma/custom_ar_standalone branch from 2b0a178 to 27f6d79 Compare November 14, 2026 12:09
@delock

delock commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @hwchen2017 thanks for the review — all four findings are fixed: the lost comm-layer half of the link-setup fix is restored (device-side _agree, latched failure, group-rank check), RowParallel now branches on ctx.needs_input_grad[2] instead of is_grad_enabled() (which is always False inside Function.forward), empty tensors return as a no-op, and the parity test now requires a settlement verdict plus rank-distinct inputs. Thanks!

@delock
delock added this pull request to the merge queue Nov 14, 2026
Merged via the queue into master with commit 7d30f92 Nov 14, 2026
21 checks passed
@delock
delock deleted the gma/custom_ar_standalone branch November 14, 2026 15:48
SuperGoodGame added a commit to SuperGoodGame/DeepSpeed that referenced this pull request Nov 14, 2026
Brings in deepspeedai#8997, deepspeedai#9011 and deepspeedai#9068; no overlap with this branch's files.

Co-Authored-By: Claude Code <[email protected]>
delock added a commit that referenced this pull request Nov 15, 2026
All five conflicting files resolved to master's version -- it carries our
shm world-group guard (cherry-picked via #8997) plus the review hardening
(single-group contract in custom_collective, group-aware readiness,
settled() latch, rank-distinct test payloads) and the proper routing fix
for the custom-Function grad probe (ctx.needs_input_grad instead of the
always-False torch.is_grad_enabled()). This branch had no unique content
in these files.

Validated locally (CPU): unit/comm/test_custom_collective.py 5 passed /
2 skipped; TestTpGradNorm 4 passed / 2 skipped; tp_plan basic_training
passed.

Signed-off-by: Ma, Guokai <[email protected]>
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.

5 participants