Skip to content

[PG][5/N] Generalize device collectives and implement AllGather - #4791

Draft
caozhanhao wants to merge 1 commit into
czh/pg-device-collectives-pr4-splitfrom
czh/pg-device-collectives-pr5
Draft

caozhanhao wants to merge 1 commit into
czh/pg-device-collectives-pr4-splitfrom
czh/pg-device-collectives-pr5

Conversation

@caozhanhao

@caozhanhao caozhanhao commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Part of #3483 (Phase 3), stacked on #5364.

Previously, the device collective framework was structured around two algorithms, two protocols, and a single collective operation (AllReduce). Algorithm selection, control endpoint distribution, and GPU execution state were tightly bound to this AllReduce-centric setup.

This PR refactors and generalises the framework to dispatch arbitrary collective operations. PR 6/N will build upon this foundation to expand the remaining collective operations and reduction operators.

User-visible behavior

  • The new GPU collective backend (GpuCollectiveBackend::New) now supports all_gather alongside all_reduce.
  • Algorithm selection can be configured via the MOONCAKE_PG_COLLECTIVE_ALGORITHM environment variable.

Algorithm policy syntax and semantics

The policy string uses the following grammar:

<op>:<rule>[,<rule>...][;<op>:<rule>...]
where each <rule> is:
<algorithm>[@<max_bytes>]
  • Operations are separated by ;, and per-operation rules by ,.
  • @max_bytes specifies an inclusive upper bound on the message size (in bytes). If omitted, the rule applies without an upper bound.
  • Sizes support optional KiB, MiB, and GiB suffixes (e.g., 512KiB, 1MiB).
  • Rules for an operation are evaluated by bound, in ascending order.
  • Unset, empty, or "auto" uses the Coordinator's automatic capability-based policy.
  • For each specified operation, explicit rules cover [0, largest max_bytes]. Sizes above that bound, as well as unspecified operations, retain the default automatic policy.
  • If a configured algorithm is unavailable or unsupported, the runtime fails immediately without falling back.

Examples

  • unset, "", or "auto":
    The Coordinator chooses algorithms automatically based on advertised route capabilities.
  • "allreduce:ring":
    Forces Ring for AllReduce across all sizes. AllGather keeps its automatic policy.
  • "allreduce:oneshot@512KiB":
    Uses OneShot for AllReduce inputs $\le$ 512 KiB. Larger AllReduce inputs and AllGather retain their automatic policy.
  • "allreduce:ring;allgather:ring":
    Forces Ring for both AllReduce and AllGather across all input sizes.
  • "allreduce:oneshot@512KiB,ring;allgather:ring":
    AllReduce uses OneShot for inputs $\le$ 512 KiB and Ring for larger inputs. AllGather uses Ring across all sizes.
  • "allreduce:ring@1048576":
    Forces Ring for AllReduce inputs $\le$ 1 MiB (overriding the automatic OneShot default), while larger inputs and AllGather follow the automatic policy.

Framework generalization and architecture

To support more operations, algorithms, and protocols cleanly, this PR introduces several abstractions:

AlgorithmProvider and ProtocolProvider

  • ProtocolProvider manages transport resources and communication state (e.g., SimpleProtocol, LLProtocol). It provides communication primitives and exposes a serialized ProtocolEndpoint for group negotiation.
  • AlgorithmProvider defines collective algorithm and GPU kernel launch logic (e.g., RingAlgorithm, OneShotAlgorithm). Each algorithm references a ProtocolProvider without owning it, declaring the set of OpType operations it supports (supports(operation)).
  • Multiple operations can share one AlgorithmProvider, and multiple algorithms can share one ProtocolProvider.

Centralized dispatch: DeviceCollectiveDispatcher

DeviceCollectiveDispatcher extracts algorithm selection, plan installation, and dispatch logic from DeviceCollectiveRuntime:

  • Manages the lifetimes of loaded protocol and algorithm providers.
  • Collects protocol and algorithm endpoints into the rank's DeviceGroupEndpoint.
  • During installGroupView(), inspects the active GroupView::collective_algorithm_choices, identifies which algorithms are selected, updates shared protocols exactly once, and updates or invalidates algorithm plans via ControlUpdateBuilder.
  • Dispatches collective enqueue requests dynamically: selectAlgorithm(request) matches the request's (OpType, byte_size) against the active algorithm policy and routes execution to the corresponding provider.

Route capability-aware collective selection

PR 4/N introduced coordinated transfer endpoint installations managed by the Coordinator. This PR takes advantage of that coordinated handshake to collect hardware and route capabilities from the data plane before selecting collective algorithms.

  1. Route capability reporting: When DTS completes an endpoint installation, its ACK returns a DeviceTransferInstallResult containing the DeviceTransferRouteInfo (reachable, directly_addressable, and native_atomics) for each GlobalRank.
  2. Coordinator aggregation: The Coordinator saves these route capabilities across all ranks. When forming a new GroupView, it passes the verified routes of all active members to CollectiveSelection.
  3. Capability-gated algorithm selection:
    • Algorithms with strict route requirements are only selected when verified across all active members. For instance, OneShot requires that every directed pair of active ranks has a directly addressable route with native atomics. If any peer pair lacks direct addressing or native atomics, the Coordinator automatically avoids OneShot and selects Ring.
    • User-defined environment overrides are merged on top of this automatic baseline: explicit overrides take precedence within their declared bounds, while default rules cover the remaining operations and size ranges.

Unified invocation lifecycle, local-only execution, and recovery

Collective kernels previously duplicated startup boilerplate, view epoch synchronization, local-only execution, and failure reporting. This PR consolidates them into shared device-side primitives and host runtime management.

Unified kernel lifecycle: runCollectiveInvocation

All collective kernels now enter and exit through a common template wrapper: runCollectiveInvocation<Execution, Request, Plan>():

  • Startup & pause handling: The startup leader CTA checks for DTS pause requests, consumes pending control updates (applyPendingControlUpdate), and prepares execution.
  • View epoch synchronization: Multi-rank invocations execute a common handshake (synchronizeCollectiveViewEpoch), setting view.synchronized = true. Subsequent collectives executing against the same GroupView generation skip redundant handshakes entirely, eliminating per-collective synchronization overhead on the hot path.

Algorithm-agnostic local-only execution

When a group has only one active participant (participant_count == 1), or when a rank transitions into Isolated during extension, cross-rank communication is bypassed.

Rather than requiring each algorithm kernel to implement single-rank special cases, the runtime routes these requests directly to executeLocalOnlyCollective():

  • Handled via a simple local memory copy performed by CTA 0 (e.g., copying input to output for AllReduce/Broadcast, copying to the rank's offset for AllGather, or no-op for Barrier).
  • Algorithms no longer need special single-rank code paths, simplifying kernel logic.

Adapting failure recovery to the dispatcher

In the existing recovery mechanism, a kernel encountering an unrecoverable failure parks the last arriving CTA in recoverCollectiveFailure(), reports the failure to the host, and waits for a pinned control update via recovery.poll().

Previously, host recovery re-published a monolithic static Configuration snapshot with hardcoded plans. With PR 5/N's decoupling into Dispatcher and dynamic providers, recovery updates are restructured accordingly:

  • The runtime tracks the latest published view update via published_view_update_.
  • If host recovery installs a new GroupView that has not yet been consumed by the GPU (!published_view_update_->handle.poll()), recovery directly merges the active rank mirror update into this pending update and re-publishes it as a pinned control update.
  • If recovery fails or no new view is produced, the runtime uses dispatcher_->invalidatePlans() to invalidate active plans instead.
  • This decouples the failure recovery path from specific collective algorithms, allowing future algorithms to participate in recovery automatically.

Supporting changes

  • Unified ProviderEndpoint: Extracted a generic ProviderEndpoint based on struct_pack serialization, replacing standalone endpoint structs for routes, protocols, and algorithms.
  • GPU RAII utilities: Added GpuBuffer<T>, PinnedHostBuffer<T>, and MappedHostBuffer<T> to gpu_runtime.h, replacing manual allocation and deallocation boilerplates.

Scope and follow-up work

To thoroughly validate the generalized framework, PR 5/N and PR 6/N were developed together. To keep the review manageable, they are split into two PRs: PR 5/N establishes the core framework abstractions and ships Ring / OneShot AllGather to validate multi-output collectives, while the remaining operations and algorithms follow in PR 6/N.

Related work and suggested merge order

PR #4747 introduces Tree AllReduce stacked on PR 3/N (#4372). The recommended review and merge order is:

#4372 (3/N) -> #4747 -> #4575 (4/N) -> 5/N -> 6/N
  1. Merge PR 3/N ([PG][3/N] Add OneShot AllReduce and decouple algorithms from protocols #4372) first, as it decouples algorithms and protocols. [PG] Add Tree AllReduce with the Simple protocol #4747 is based directly on 3/N.
  2. Retarget PR [PG] Add Tree AllReduce with the Simple protocol #4747 to main and merge it.
  3. Merge PR 4/N ([PG][4a/N] Coordinate device route setup and updates #4575), providing the coordinated transfer endpoint installation and DTS route infrastructure.
  4. Merge PR 5/N after [PG] Add Tree AllReduce with the Simple protocol #4747 and [PG][4a/N] Coordinate device route setup and updates #4575. Re-basing PR 5/N on top of Tree AllReduce will expose any limitations or blind spots in 5/N's refactor when accommodating tree topologies, allowing the abstractions to be refined before final merge.
  5. Merge PR 6/N last, as it expands operations and reduction support on top of 5/N's generalized framework.

Suggested Merge Priority

  • P0 — Urgent: Critical security vulnerability, data loss/corruption, or widespread production outage requiring immediate action
  • P1 — High: Significant correctness or stability issue in existing functionality, or a regression blocking users without a practical workaround
  • P2 — Normal: Routine bug fix, validated performance/compatibility improvement, or new feature for a confirmed use case
  • P3 — Low: Experimental feature, optional enhancement, refactoring, or cleanup with no urgent user impact

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?

TBD

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

AI Assistance Disclosure

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

Codex was used to assist in designing and implementing this PR. All code and architectural changes have been thoroughly reviewed and verified by me in person.

@caozhanhao
caozhanhao added this pull request to stack #3915 October 20, 2026 03:51
@caozhanhao
caozhanhao force-pushed the czh/pg-device-collectives-pr5 branch from 48f65da to 7edbd09 Compare November 9, 2026 13:32
@caozhanhao
caozhanhao removed this pull request from stack #3915 November 9, 2026 13:34
@caozhanhao
caozhanhao changed the base branch from czh/pg-device-collectives-pr4 to czh/pg-device-collectives-pr4-split November 9, 2026 13:35
@caozhanhao
caozhanhao added this pull request to stack #5365 November 9, 2026 13:39
@caozhanhao
caozhanhao force-pushed the czh/pg-device-collectives-pr5 branch from 7edbd09 to 0dad5f6 Compare November 9, 2026 14:14
@github-actions github-actions Bot added the size/L 1001+ changed lines (additions + deletions) label Nov 9, 2026
@yuechen-sys
yuechen-sys force-pushed the czh/pg-device-collectives-pr5 branch from 0dad5f6 to ac2d7dc Compare November 10, 2026 07:37
Signed-off-by: caozhanhao <cao2013zh@163.com>
@caozhanhao
caozhanhao force-pushed the czh/pg-device-collectives-pr5 branch from ac2d7dc to 9f5b766 Compare November 14, 2026 13:57

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.

1 participant