Skip to content

[Perf] [SM120] all-gather: Speed up TP4 logits and DSpark vocab all-gathers on PCIe-only hosts - #42863

Closed
ormandj wants to merge 3 commits into
sgl-project:mainfrom
ormandj:pcie-ipc-tp-gathers
Closed

ormandj wants to merge 3 commits into
sgl-project:mainfrom
ormandj:pcie-ipc-tp-gathers

Conversation

@ormandj

@ormandj ormandj commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

On hosts without NVLink, make_vocab_gather and MultimemAllGatherer fall back to NCCL because there is no multicast. Decode-sized gathers are latency-bound on that path. Per decode step, the logits processor gathers the target's vocab-sharded logits, and on the sharded sampling path the DSpark Markov head gathers one FP32 [bs, vocab/tp] row block per draft position. (Sharded greedy gathers compact candidate pairs.) On 4x RTX PRO 6000 Blackwell (PCIe) at TP4, one NCCL gather of [1, 32320] takes 38 us in BF16 and 53 us in FP32 (tables below).

#34528 added FlashInfer's PCIe-IPC all-reduce for these hosts. FlashInfer also provides a PCIe-IPC all-gather (PcieIpcAllGatherWorkspace, flashinfer-ai/flashinfer#5023). It copies opaque 16-byte packs, so its output is bit-identical to NCCL's.

Requires the PCIe-IPC all-gather API, available since FlashInfer 0.7.1rc1. The version SGLang pins in python/pyproject.toml, 0.7.0.post1, has the PCIe-IPC all-reduce but not the all-gather, so with that version the gathers stay on NCCL. There is no version check. Before the build, each rank imports the API it uses (PcieIpcAllGatherWorkspace, PcieIpcAllGatherLaunchConfig, PcieIpcAllGatherVariant); if that fails, it logs a warning, reports itself not ready to the other ranks, and every rank keeps NCCL. The multi-GPU test skips on such a FlashInfer, so in SGLang's CI it skips until the FlashInfer pin includes the all-gather API (0.7.1rc1 or later).

Modifications

  • vocab_gather.py: add PcieIpcVocabGather behind the existing VocabGather interface. It covers both the side-by-side (__call__) and rank-major (gather_stacked) layouts. Slices the workspace cannot take go to the NCCL fallback: more rows than it was sized for (max_rows, checked by the adapter because FlashInfer bounds only the element count), more than max_rows * width elements, or another dtype. Non-contiguous or misaligned inputs are copied rather than sent to NCCL, so the path depends only on dtype and shape, which every rank shares. The workspace is rebound when the caller's stream changes, as the PCIe-IPC all-reduce adapter does.
  • make_pcie_ipc_gather builds it only when the PCIe-IPC all-reduce is configured for the group (SGLANG_ENABLE_PCIE_IPC_ALLREDUCE, off by default) and enabled on every rank, the group is TP4, and its ranks share one host.
  • Collective safety: whether a group takes part is decided only from settings every rank shares, so either every rank enters the agreements below or none does. These are the new GroupCoordinator.pcie_ipc_eligible (the existing eligible_group result, recorded because a rank-local setup failure leaves pcie_ipc_comm as None on that rank only), the world size and the row capacity. FlashInfer allocates and maps the IPC buffer without coordinating a failure on one rank, which would leave the others waiting. So before the build, the ranks agree over the group's CPU group (one-int all_reduce(SUM)) that the group is on one host (in_the_same_node_as, as the custom all-reduce checks it; FlashInfer's TP4 all-gather does not reject a group spanning hosts, and its failed IPC handle exchange there leaves the buffers allocated) and that each rank has its PCIe-IPC communicator set up and enabled, the all-gather API, and enough free GPU memory. Any exception in that local check counts as not ready, and if any rank is not ready, no rank starts the build. After the build, they count the ranks that built a workspace, which is the last thing the adapter constructs. If all did, the gather is used. If none did, every rank keeps NCCL; FlashInfer validates and binds the workspace jointly, so its own construction errors are raised on every rank. If only some did, every rank raises and startup fails: releasing a FlashInfer workspace is collective over the whole group (a group barrier before the IPC buffers are freed), so the ranks that built one cannot release it alone, and serving on would leave its IPC buffers mapped. A failure inside FlashInfer's buffer exchange itself (for example cudaIpcOpenMemHandle on one rank) can still hang; that is inside FlashInfer, and I plan to report it there separately.
  • The workspace is handed to the group's PcieIpcCommunicator, which releases it in GroupCoordinator.destroy before the process groups (new adopt()).
  • Opt-in per call site: make_vocab_gather(prefer_pcie_ipc=...), default off, set by the DSpark Markov head for DeepSeek-V4.1, and MultimemAllGatherer(pcie_ipc=...), default off, set by the logits processor (all models). Servers without SGLANG_ENABLE_PCIE_IPC_ALLREDUCE, or not at TP4, are unchanged. Order in make_vocab_gather: NVLink multicast, then PCIe-IPC, then NCCL.
  • MultimemAllGatherer with pcie_ipc=True still tries multimem first on its first eager call, never under capture; when multimem is unavailable (no multicast), it calls make_pcie_ipc_gather. The workspace is sized for decode (recommended_max_tokens(include_prefill=False)), as the PCIe-IPC all-reduce is, and larger inputs stay on NCCL.
  • Launch config: one fixed config, 24 blocks x 512 threads, recursive doubling, for every shape. FlashInfer's default runs its seed policy for any shape it has not tuned exactly. On this host the seed policy was 1.5-1.9x slower than NCCL at 16-96 BF16 rows (table below); decode row counts vary. At the three BF16 shapes tuned exactly (1, 2, 4 rows), the fixed config is within 0.4 us of the tuned one, and for FP32 the tuner picked it at 4 and 16 rows. It is the same on every rank and needs no tuning collectives. It was measured only at TP4, so TP2/TP8 stay on NCCL.
  • Docs: the SGLANG_ENABLE_PCIE_IPC_ALLREDUCE entry mentions the gathers.

Workspace memory per gather is about 2 * world_size * max_rows * width * itemsize per rank. For example, logits BF16 [128, 32320] at TP4 is 66 MB. With both gathers enabled on DeepSeek-V4.1-Flash at TP4, the KV cache pool was 3.6% smaller (2,219,008 vs 2,301,952 tokens).

Accuracy Tests

The change is a copy and is bit-identical to NCCL all_gather_into_tensor. I checked the FlashInfer primitive on the target hardware for every microbenchmark shape below (torch.equal against NCCL; BF16 with the fixed config, FP32 with the tuned configs). The wrapper benchmark below also checked every one of its shapes bitwise (torch.equal) against SGLang's NCCL gather before timing.

New tests. With this branch head, the multi-GPU test passed on 4x RTX PRO 6000 with torchrun --nproc-per-node 4 -m pytest (27 passed on each rank). I did not run it at world size 2. The CPU test test/registered/unit/distributed/test_pcie_ipc_gather_selection.py passed without a GPU (30 passed).

  • test/registered/kernels/ops/communication/test_pcie_ipc_vocab_gather.py (multi-GPU, world sizes 2 and 4). It needs a FlashInfer with the PCIe-IPC all-gather and skips otherwise, so it skips in SGLang's CI with the current pin (0.7.0.post1). It compares bitwise against NCCL in both layouts for FP32/BF16, 1-16 rows, with NaN/inf/-0.0 in the inputs. It also checks CUDA-graph capture on a side stream, replay with new inputs, and eager calls between replays, the copy path for strided and misaligned inputs, and the NCCL fallback for wrong-dtype slices and for slices past the row bound, including a narrow one that fits by element count.
  • test/registered/unit/distributed/test_pcie_ipc_gather_selection.py (CPU). It replaces the FlashInfer workspace with a fake, so it covers selection, the cross-rank agreements and the output layout, not the kernel. It covers selection and fallback: opt-in only, TP4 only, PCIe-IPC all-reduce on/off/disabled or missing on this rank, NVLink first, a group spanning hosts, too little free memory, a missing all-gather API symbol or an exception in the local check, a workspace failure falling back to NCCL, and release order on destroy. Six cases run four real gloo ranks. When one rank lacks memory, lacks its communicator, or raises in its local check, or when ranks 2 and 3 are on another host, every rank ends on NCCL and no rank starts the build. When the build fails on every rank, every rank ends on NCCL. When it fails on one rank, every rank raises and no workspace is destroyed. It also checks the output layout, the single launch config, the row bound for a narrow slice that fits by element count, the copy of strided and misaligned inputs, stream rebinding only on stream change, and that MultimemAllGatherer switches only when opted in on a PCIe-IPC group (other users keep multimem/NCCL, and a group without PCIe-IPC makes no agreement), defers under capture, and sizes the workspace for decode.

Speed Tests and Profiling

Hardware: 4x RTX PRO 6000 Blackwell Max-Q Workstation Edition (SM120, 188 SMs), PCIe only, TP4, power limit 250 W, GPUs used only by this benchmark. Software: torch 2.14.1+cu130, FlashInfer 0.7.1 (main d4b19b87 plus the carried SM120 MXFP8 default-tactic patch, which does not touch communication). FlashInfer primitive. Method: torchrun --nproc_per_node=4. Each case is 50 gathers captured in one CUDA graph and replayed 20 times; the table shows time per gather on rank 0. The NCCL baseline is dist.all_gather_into_tensor. The FlashInfer rows call PcieIpcAllGatherWorkspace.all_gather directly (rank-major output); SGLang wrapper and layout-conversion costs are excluded; the wrapper table below includes them.

BF16 [rows, 32320] (logits shard), us per gather. In the FlashInfer default row, rows 1/2/4 were tuned for that exact shape and the other rows ran the seed policy.

rows 1 2 4 6 16 24 48 96
FlashInfer fixed config (this PR) 13.0 20.5 36.3 53.1 131.1 220.6 400.4 769.1
FlashInfer default 12.6 20.5 36.1 58.4 308.8 482.1 1052.4 2099.6
NCCL 37.9 53.4 77.3 94.3 207.1 301.6 577.6 1130.9

FP32 [rows, 32320] (DSpark vocab gather), us per gather, with FlashInfer tuned for each shape. The tuner picked 24x512 recursive doubling, the fixed config, at 4 and 16 rows; at 1, 2 and 8 rows it picked 16x512, 48x256 and 48x256. This table does not measure the PR's fixed config at 1, 2 and 8 FP32 rows; the wrapper table below does.

rows 1 2 4 8 16
FlashInfer, tuned per shape 20.4 37.6 70.0 131.3 258.2
NCCL 53.1 77.2 120.9 210.4 397.8

SGLang wrapper path, same hardware and software. make_pcie_ipc_gather (both agreements, the fixed config, max_rows 128) on a TP4 GroupCoordinator, timed through PcieIpcVocabGather.__call__ including the conversion to the side-by-side layout, against NcclVocabGather.__call__ (GroupCoordinator.all_gather(dim=-1), pynccl under graph capture). Each case is 50 calls captured in one CUDA graph and replayed 20 times; the table shows the median of 3 such measurements, time per call on rank 0.

dtype rows PCIe-IPC, fixed config (us) NCCL (us) NCCL / PCIe-IPC
bfloat16 1 13.2 38.3 2.91x
bfloat16 2 22.7 51.4 2.27x
bfloat16 4 38.6 75.3 1.95x
bfloat16 6 55.7 93.0 1.67x
bfloat16 16 135.8 208.3 1.53x
bfloat16 24 223.5 303.8 1.36x
bfloat16 48 408.8 586.0 1.43x
bfloat16 96 788.2 1140.8 1.45x
float32 1 20.6 53.2 2.59x
float32 2 38.1 74.7 1.96x
float32 4 72.0 118.7 1.65x
float32 8 134.2 206.1 1.54x
float32 16 266.0 396.9 1.49x
pcie_gather_wrapper_bench.py
"""TP4 vocab all-gather through SGLang's wrappers: PCIe-IPC (fixed launch config)
vs the NCCL path it replaces, BF16 and FP32 [rows, 32320], side-by-side layout.

  torchrun --nproc-per-node 4 pcie_gather_wrapper_bench.py [--max-rows 128]

Both sides go through the code the server runs. The PCIe-IPC side is built by
make_pcie_ipc_gather (both cross-rank agreements, the fixed 24x512 recursive-
doubling config) and timed through PcieIpcVocabGather.__call__, including the
rank-major to side-by-side copy. The NCCL side is NcclVocabGather.__call__, i.e.
GroupCoordinator.all_gather(dim=-1) on a "tp" group, captured inside
group.graph_capture() so pynccl serves it as it does in decode graphs.
Each case: 50 calls captured in one CUDA graph, 20 replays, us per call on
rank 0; the median of --trials such measurements is printed. Every case is
checked bitwise against NCCL before timing. Prints a markdown table on rank 0.
"""

import argparse
import logging
import os
import statistics

# Before any SGLang import: the "tp" group must get its PCIe-IPC communicator.
os.environ["SGLANG_ENABLE_PCIE_IPC_ALLREDUCE"] = "1"

import torch
import torch.distributed as dist

import sglang.srt.distributed.parallel_state as ps
from sglang.srt.distributed.device_communicators import vocab_gather
from sglang.srt.distributed.device_communicators.vocab_gather import (
    NcclVocabGather,
    PcieIpcVocabGather,
    make_pcie_ipc_gather,
)
from sglang.srt.runtime_context import get_parallel

WIDTH = 32320  # DeepSeek-V4 vocab shard per rank at TP4
CASES = {
    torch.bfloat16: (1, 2, 4, 6, 16, 24, 48, 96),  # logits gather
    torch.float32: (1, 2, 4, 8, 16),  # DSpark vocab gather
}


def setup():
    local_rank = int(os.environ["LOCAL_RANK"])
    world_size = int(os.environ["WORLD_SIZE"])
    assert world_size == 4, "the PCIe-IPC gather is taken at TP4 only"
    torch.cuda.set_device(local_rank)
    dist.init_process_group(backend="gloo")
    ranks = list(range(world_size))
    ps._WORLD = ps.init_world_group(ranks=ranks, local_rank=local_rank, backend="nccl")
    get_parallel().override_permanently(world_group=ps._WORLD)
    group = ps.init_model_parallel_group(
        group_ranks=[ranks],
        local_rank=local_rank,
        backend="nccl",
        use_custom_allreduce=False,
        group_name="tp",
    )
    assert group.pcie_ipc_eligible and group.pcie_ipc_comm is not None
    return group


def time_call(group, fn, x, calls, reps):
    stream = torch.cuda.Stream()
    with group.graph_capture(stream=stream):
        for _ in range(3):
            fn(x)  # warm up on the capture stream
        graph = torch.cuda.CUDAGraph()
        with torch.cuda.graph(graph, stream=stream):
            for _ in range(calls):
                fn(x)
    torch.cuda.current_stream().wait_stream(stream)
    dist.barrier()
    graph.replay()
    torch.cuda.synchronize()
    dist.barrier()
    start, end = torch.cuda.Event(True), torch.cuda.Event(True)
    start.record()
    for _ in range(reps):
        graph.replay()
    end.record()
    torch.cuda.synchronize()
    dist.barrier()
    return start.elapsed_time(end) * 1e3 / (calls * reps)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--max-rows", type=int, default=128)
    parser.add_argument("--calls", type=int, default=50)
    parser.add_argument("--reps", type=int, default=20)
    parser.add_argument("--trials", type=int, default=3)
    args = parser.parse_args()

    logging.disable(logging.INFO)
    group = setup()
    rank = dist.get_rank()
    if rank == 0:
        print(f"sglang vocab_gather: {vocab_gather.__file__}", flush=True)
        print(f"torch {torch.__version__}, {torch.cuda.get_device_name()}", flush=True)
    nccl = NcclVocabGather(group)
    lines = [
        "| dtype | rows | SGLang PCIe-IPC, fixed config (us) | SGLang NCCL (us) | NCCL / PCIe-IPC |",
        "|---|---|---|---|---|",
    ]
    for dtype, row_counts in CASES.items():
        gather = make_pcie_ipc_gather(
            group,
            local_width=WIDTH,
            dtype=dtype,
            max_rows=args.max_rows,
            fallback=nccl,
        )
        assert isinstance(gather, PcieIpcVocabGather), "PCIe-IPC gather not built"
        for rows in row_counts:
            assert rows <= args.max_rows
            x = (torch.randn(rows, WIDTH, device="cuda") * (rank + 1)).to(dtype)
            same = torch.equal(
                gather(x).view(torch.uint8), nccl(x).contiguous().view(torch.uint8)
            )
            flags = torch.tensor([int(same)], dtype=torch.int32)
            dist.all_reduce(flags, op=dist.ReduceOp.MIN)
            assert flags.item() == 1, f"{dtype} rows={rows}: not bit-identical"
            pcie, ref = [], []
            for _ in range(args.trials):
                pcie.append(time_call(group, gather, x, args.calls, args.reps))
                ref.append(time_call(group, nccl, x, args.calls, args.reps))
            p, n = statistics.median(pcie), statistics.median(ref)
            name = str(dtype).removeprefix("torch.")
            lines.append(f"| {name} | {rows} | {p:.1f} | {n:.1f} | {n / p:.2f}x |")
            if rank == 0:
                print(lines[-1], flush=True)
    if rank == 0:
        print(
            f"\nTP4, [rows, {WIDTH}], side-by-side layout, workspace max_rows="
            f"{args.max_rows}; {args.calls} calls per CUDA graph, {args.reps} "
            f"replays, median of {args.trials} trials, rank 0.\n"
        )
        print("\n".join(lines), flush=True)
    group.destroy()
    ps._WORLD.destroy()
    dist.destroy_process_group()


if __name__ == "__main__":
    main()

Run on a host with 4 GPUs and a FlashInfer that has the PCIe-IPC all-gather:

SGLANG_ENABLE_PCIE_IPC_ALLREDUCE=1 torchrun --nproc-per-node 4 pcie_gather_wrapper_bench.py

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

Developed with AI assistance.


CI States

Latest PR Test (Base): ❌ Run #40964965915
Latest PR Test (Extra): ❌ Run #40964966007
Latest PR Test (AMD ROCm 10): ❌ Run #40964966051

@github-actions github-actions Bot added documentation Improvements or additions to documentation deepseek labels Oct 7, 2026
@ormandj
ormandj force-pushed the pcie-ipc-tp-gathers branch from 4622f4b to 1581a8f Compare October 7, 2026 05:42
@ormandj ormandj mentioned this pull request Oct 7, 2026
17 of 56 tasks
@ormandj ormandj changed the title [SM120] Speed up TP4 logits and DSpark vocab all-gathers on PCIe-only hosts [Perf] [SM120] all-gather: Speed up TP4 logits and DSpark vocab all-gathers on PCIe-only hosts Oct 19, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 20, 2026
…multicast probe in the gather-selection test

sgl-project#42863's selection tests predate sgl-project#41888's has_multicast_support() probe, which
now runs before the symmetric-memory rendezvous inside _build_multimem. Without
a stub they only pass on a multicast-capable host (the probe is real in the
test process), so sgl-project#38565's own CI would flip on hardware. Drive the probe from
the tests' existing multicast= knob and cover the claims-support-but-no-alias
case with the new probe= override.
detain added a commit to detain/sglang that referenced this pull request Oct 20, 2026
…/deferred/avoid map

- 3A [24-35]: NVFP4 MoE boot sgl-project#39807/sgl-project#40173, block-FP8 TP refine sgl-project#42566, k-pool indexer split sgl-project#43619,
  SM120 skinny GEMM sgl-project#42865/sgl-project#42867, DeepGEMM warmup guards sgl-project#32686/sgl-project#43712, autotune sgl-project#43363/sgl-project#40420,
  mHC overlap sgl-project#42985, FP8-einsum precompile sgl-project#42821.
- 3B [36-43]: PCIe CustomAllreduce VMM sgl-project#44448, EP local expert ids sgl-project#44480, shm TP broadcast sgl-project#44202,
  PCIe-IPC all-gather sgl-project#42863 + multicast guard sgl-project#41888, TP-sampling consistency sgl-project#41916/sgl-project#38565,
  draft embed/lm_head VRAM sgl-project#37155.
- sgl-project#39807 toolchain commit verified safe against our CUDA_HOME=12.9 pin (cu13 fallback needs CUDA_HOME unset AND glibc>=2.41; we are 2.39).
- stack_want.txt: execution-status banner. Branch tip 5dd6ec7.
… hosts

On a TP group whose FlashInfer PCIe-IPC all-reduce is enabled (no NVLink,
no multicast), the DSpark Markov vocab gathers (DeepSeek-V4.1) and the
logits processor's last-dim TP gather opt in to FlashInfer's PCIe-IPC
all-gather instead of the NCCL ring; other users of make_vocab_gather and
MultimemAllGatherer are unchanged. The gather is a copy of 16-byte packs,
bit-identical to NCCL. It runs one fixed launch config (24 blocks x 512
threads, recursive doubling) at TP4 only: FlashInfer's seed policy for
untuned shapes is up to 6x slower than NCCL there, and the fixed config
needs no tuning collectives at startup. Ranks agree before and after the
workspace build, so a failure on one rank keeps every rank on NCCL; the
workspaces are released with the group's PCIe-IPC all-reduce workspace.
Decide whether a group takes part in the PCIe-IPC gather setup from
settings every rank shares (GroupCoordinator.pcie_ipc_eligible), and
report a missing or disabled communicator, a missing FlashInfer symbol or
any exception in the local probe through the agreement instead of
skipping or escaping it. Build the FlashInfer workspace last; if it was
built on only some ranks, raise on every rank, since its release is
collective. Bound the gather by rows as well as by elements.
FlashInfer's TP4 all-gather does not reject a group spanning hosts, and its
failed IPC handle exchange there leaves the buffers allocated. Check that
the group shares one host (in_the_same_node_as, as the custom all-reduce
does) as part of the readiness agreement, before any rank builds.
@ormandj
ormandj force-pushed the pcie-ipc-tp-gathers branch from 1581a8f to cac55f5 Compare October 29, 2026 22:19
@mintlify

mintlify Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit cac55f5.

Approve preview

@github-actions

Copy link
Copy Markdown
Contributor

Thanks @ormandj. Closing this because you have 25 PRs open and none updated in 7 days, over our soft cap of 5 for idle PRs.

Reopen the two or three you most want reviewed - a short active set moves faster than a long idle one.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant