Skip to content

[PG] Add Tree AllReduce with the Simple protocol - #4747

Open
LYAccc wants to merge 1 commit into
kvcache-ai:mainfrom
LYAccc:lyaccc/pg-tree-allreduce
Open

LYAccc wants to merge 1 commit into
kvcache-ai:mainfrom
LYAccc:lyaccc/pg-tree-allreduce

Conversation

@LYAccc

@LYAccc LYAccc commented Oct 18, 2026 •

Copy link
Copy Markdown

Description

Part of #3483 (Phase 2), built on the collective framework introduced in #4372.

I added a Tree AllReduce algorithm to the new PG collective framework. It uses a single NCCL-style binary tree with the Simple protocol, reusing the framework's execution ordering, shared workspace, device transfers, and failure recovery.

This builds on the algorithm/protocol separation in #4372. Tree needs several neighbor connections per channel, so this PR also extends Simple's connection binding and readiness handshake to support that execution pattern.

User-visible behavior

Enable Tree by setting these variables on the worker processes before startup:

export MOONCAKE_PG_PREFERRED_GPU_COLLECTIVE_BACKEND=new
export MOONCAKE_PG_COLLECTIVE_ALGORITHM=tree
  • The Coordinator reads the algorithm override at startup and publishes a group-wide choice. Changing the environment afterward does not change an existing Coordinator's selection.
  • Explicit Tree requires the new backend and compatible Tree/Simple endpoints on every active GPU rank. Incompatible initialization or activation is rejected.
  • auto, ring, and oneshot retain their existing selection and fallback behavior. Auto does not select Tree, and CPU groups are unaffected.
  • Tree supports the existing device AllReduce datatypes with Sum, Product, Min, and Max, including in-place and out-of-place buffers.
  • The public C API is unchanged. C API callers select mooncakePgGpuCollectiveBackendNew through the existing communicator configuration; its initializer still defaults to legacy.

Tree planning from active membership

The planner constructs a binary tree in the dense order of ResolvedGroupView.participants, then resolves its parent and children to actual peers. This lets the same topology builder handle sparse global ranks, inactive members, and group sizes that are not powers of two.

Each participant has at most one parent and two children. Child slots retain their logical positions, including the root's single child in slot 1, so both ends agree on the receive region for each edge.

For four active participants, the data flow is as follows. Labels are dense participant indices:

flowchart LR
    subgraph reduction[Reduction]
        R1["1"] --> R2["2"]
        R3["3"] --> R2
        R2 --> R0["0"]
    end
    subgraph broadcast[Broadcast]
        B0["0"] --> B2["2"]
        B2 --> B1["1"]
        B2 --> B3["3"]
    end
Loading

The current implementation uses one topology for all channels. The planner validates reciprocal parent/child relationships before publishing a plan.

Simple connections and shared workspace

Ring binds one incoming and one outgoing connection per channel. Tree needs separate connections to its parent and children, with different local and remote receive offsets. SimplePrimitives::bindConnection() now accepts those offsets explicitly, along with the staging offset.

Each Tree channel reserves three receive roles: child 0, child 1, and parent. Each role has two payload slots. Staging follows the same layout, giving each neighbor a separate source region. These regions are subdivisions of the existing process workspace; Tree reuses Simple's signals and per-peer progress storage. StrongStream continues to order communicators sharing that workspace.

Channel selection uses the request size and the common workspace capacity across participants. It selects up to 32 channels, with 16-byte-aligned chunks capped at 512 KiB. Every rank therefore derives the same channel and tile boundaries even when local workspace capacities differ.

Readiness and execution ordering

With several neighbors, waiting inside the first connection's handshake could prevent a rank from notifying another neighbor that its receive buffer is ready. I split Simple's readiness step into publishRecvBufferReady() and waitSendBufferReady(). Tree publishes readiness to every neighbor before waiting on any of them. Ring keeps its existing begin() wrapper and ordering.

An invocation then proceeds as follows:

  1. Bind one Simple connection per neighbor and complete the readiness exchange.
  2. Reduce each tile from the children into the local contribution and send the partial result toward the root.
  3. After completing the upward stream, receive the final result from the parent and broadcast it to the children.
  4. Wait for outstanding sends to be consumed and commit connection progress.

Each connection keeps the same cursor snapshot across both phases. Completing the upward stream before starting the downward stream avoids a cross-phase wait cycle with bounded two-slot connections. A singleton group copies locally when needed, and an empty request performs no payload transfers.

Membership changes, CUDA Graphs, and recovery

The captured kernel references a stable device state object. Membership changes update its Tree plan through the existing control-update mechanism, and the next invocation reads the current plan before partitioning the request. The fixed launch shape allows the active channel count and topology to change without recapturing the kernel.

For example, a group can move from two active ranks to three and back to two within its configured capacity while reusing the same Graph. An isolated joiner also preserves the group's algorithm choice during local preparation, so it captures Tree before activation.

Recovery uses the framework's existing safe point: all channel CTAs stop using the old plan before the host publishes replacement state. Tree is included in both normal plan updates and failure invalidation. The next replay uses the updated membership. Captured buffer addresses, count, datatype, reduction operation, and algorithm remain fixed; changing those requires recapture.

A failed AllReduce may partially overwrite output. The runtime does not roll back or retry the operation, so callers must restore input before replay and clear caller-owned failure hints when reusing them. Captured Work queries also require replay synchronization; this PR avoids synchronizing a capture-time event inside get_local_success() or get_failed_ranks_hint().

Admission and compatibility

Tree publishes a versioned capability alongside the existing Simple endpoint. The Coordinator validates that capability, the backend preference, workspace alignment/capacity, and signal ranges before accepting GPU endpoints. An incompatible joiner is rejected without replacing the active group's Tree configuration. A registration rejected for explicitly requesting Tree with the legacy backend fails that communicator while leaving the process Agent alive.

The new endpoint capability and registration fallback flag use struct_pack::compatible to preserve the #4372 wire schema. Older messages decode with the added fields absent. Non-Tree groups can continue using Ring or OneShot when some members do not advertise Tree.

Module

  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake Store (mooncake-store)
  • Mooncake Conductor (mooncake-conductor)
  • Reshard (mooncake-reshard)
  • Mooncake EP (mooncake-ep)
  • Mooncake PG (mooncake-pg)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • Common (mooncake-common)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Breaking change
  • Documentation update
  • Performance improvement
  • Other

How Has This Been Tested?

  • The standalone Tree host target passed all 16 tests, covering topology for 1–64 participants, sparse rank mapping, logical child slots, buffer alignment and isolation, channel/tile coverage, and capacity boundaries. It uses the repository-pinned yalantinglibs dependency and GoogleTest 1.17.0. The existing host IP resolution target also passed.
  • All 6 Coordinator admission and policy tests passed in a host test harness after adapting the fixture to acknowledge endpoint installation.
  • test_pg_tree.py passed its Python syntax check.
  • Changed-file pre-commit checks passed, including clang-format 20, Ruff, codespell, CMake formatting, and generic checks.

The added test suite also covers Coordinator admission and policy regressions, the recovery control-update budget, eager datatype/operation combinations, fixed Graph replay, 2→3→2 membership changes, rejection of a legacy joiner, and root/internal/leaf failures followed by reuse of the same Graph. Test and benchmark commands are documented under mooncake-pg/tests and mooncake-pg/benchmark.

Benchmark

Following #4372, this comparison uses the same nccl-tests v2.17.9 executable for PG and native NCCL. A minimal NCCL compatibility shim forwards AllReduce calls to the Mooncake PG C API, avoiding Python/PyTorch dispatch overhead.

The sweep compares four forced Simple paths on a single node of 8 × NVIDIA L20 (PCIe):

  • PG Tree / Simple: the Tree implementation in this PR, selected with MOONCAKE_PG_COLLECTIVE_ALGORITHM=tree.
  • PG Ring / Simple: the existing device Ring implementation, selected with MOONCAKE_PG_COLLECTIVE_ALGORITHM=ring.
  • NCCL Tree / Simple: native NCCL with NCCL_ALGO=TREE and NCCL_PROTO=SIMPLE.
  • NCCL Ring / Simple: native NCCL with NCCL_ALGO=RING and NCCL_PROTO=SIMPLE.

PG uses MOONCAKE_PG_PREFERRED_GPU_COLLECTIVE_BACKEND=new. Native NCCL is 2.27.5+cuda12.9.

All four paths use float32 SUM, one MPI process per GPU, 50 warmup iterations, 500 measured iterations, CUDA Graphs (-G 10), three cycles per start (-N 3), no symmetric buffer registration (-R 0), and correctness checking (-c 1). Each configuration is measured across three independent process starts; each reported value is the median of the three per-start cycle medians.

The figure and table show out-of-place latency in microseconds for 17 message sizes from 8 B through 512 KiB, measured on 2026-10-22. Shaded bands show the minimum and maximum per-start medians. All correctness checks for these runs passed, and separate NCCL tuning probes verified the forced Tree/Ring and Simple selections.

On this host, PG Tree has lower latency than PG Ring at the sampled sizes from 8 B through 64 KiB; PG Ring is faster from 128 KiB through 512 KiB. Native NCCL still has lower latency than the faster PG path at every sampled size shown here. The Simple protocol family is fixed, while the implementations, topologies, channel choices, and transport paths differ.

AllReduce latency on 8 NVIDIA L20, forced Simple paths, CUDA Graph, out-of-place, 8 B to 512 KiB
Detailed results (median latency, µs; lower is better)
Message size PG Tree / Simple PG Ring / Simple NCCL Tree / Simple NCCL Ring / Simple
8 B 110.56 145.16 71.09 60.20
16 B 110.63 145.15 70.71 59.89
32 B 110.63 145.15 70.69 60.32
64 B 110.64 145.15 70.62 64.26
128 B 110.63 145.13 70.78 76.09
256 B 110.66 145.11 70.86 76.11
512 B 110.75 145.12 70.57 75.90
1 KiB 110.96 145.12 70.78 75.92
2 KiB 111.19 145.16 71.05 76.01
4 KiB 111.49 145.24 73.49 75.55
8 KiB 113.01 145.36 76.16 78.75
16 KiB 123.84 145.61 80.36 89.26
32 KiB 135.88 146.09 93.08 110.20
64 KiB 145.37 148.59 104.69 113.59
128 KiB 174.59 161.71 148.20 116.36
256 KiB 237.03 182.39 225.85 123.57
512 KiB 357.26 208.79 385.10 147.38

Checklist

  • I have performed a self-review of my own code
  • I have formatted my code using ./scripts/code_format.sh
  • I have run pre-commit on the files changed in this PR and all hooks pass
  • I have updated the documentation (if applicable)
  • I have added tests to prove my changes are effective
  • For changes >500 LOC: I have filed an RFC issue

RFC/design discussion: #3483, with maintainer agreement to build on #4372.

AI Assistance Disclosure

  • No AI tools were used
  • AI tools were used (specify below)

I used Codex to assist with implementation, testing, and PR preparation. I have reviewed all code and architectural changes and take responsibility for this contribution.

@LYAccc
LYAccc marked this pull request as ready for review October 27, 2026 09:31
@github-actions github-actions Bot added the size/L 1001+ changed lines (additions + deletions) label Oct 27, 2026
@anranxia anranxia mentioned this pull request Oct 30, 2026
9 tasks done
@caozhanhao
caozhanhao self-requested a review November 2, 2026 06:43
@caozhanhao
caozhanhao changed the base branch from czh/pg-device-collectives-pr3 to main November 6, 2026 11:04
@caozhanhao

Copy link
Copy Markdown
Collaborator

Thanks a lot for putting this together! The data plane implementation looks solid to me. Also, given that the control plane is undergoing heavy refactoring in 4/N (#4575) and 5/N (#4791), the current control-plane wiring here is fine for this PR.

My only suggestion is to trim down the test suite a bit -- some parts feel slightly defensive for this stage. Since this device collective path is still in early development, we don't necessarily need to cover advanced scenarios like mixed PG versions within the same group just yet. Keeping the tests focused at this stage will make future iterations much easier to maintain.

Specifically, I'd suggest dropping:

  • pg_tree_c_api.py
  • tree_geometry_cxx17_test.cpp
  • tree_policy_test.cpp
  • wire-format compatibility tests in tree_coordinator_test.cpp

Also, a quick heads-up: now that 3/N (#4372) has landed, I've retargeted this PR to main. Could you please rebase it and resolve the conflicts when you get a chance?

Thanks again for the fantastic work!

@LYAccc

LYAccc commented Nov 10, 2026

Copy link
Copy Markdown
Author

@caozhanhao Thanks for the review, and good catch on the overly defensive tests! I’ll remove the suggested tests and rebase the branch later on.

@LYAccc
LYAccc force-pushed the lyaccc/pg-tree-allreduce branch from 605779d to 0603634 Compare November 11, 2026 11:42
@LYAccc

LYAccc commented Nov 11, 2026

Copy link
Copy Markdown
Author

Hi @caozhanhao, I’ve removed the suggested tests and rebased this PR onto main. Plz take another look when you get time.

@caozhanhao caozhanhao left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM, thanks for the follow-up! @yuechen-sys PTAL.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

PyTorch Backend run-ci size/L 1001+ changed lines (additions + deletions)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants