Repository navigation
[PG][1/N] Initialize the new collective framework - #3484
Conversation
c3c55f5 to
7da45be
Compare
cf04797 to
fcebb93
Compare
yuechen-sys
left a comment
There was a problem hiding this comment.
This is a wonderful start as the new collective framework! Thanks for your contribution.
I have several questions and concerns. You can resolve them in the future.
| // Apply an authoritative group view together with the current rank-state | ||
| // snapshot as one communicator update. | ||
| void applyGroupState(const GroupView& view, | ||
| const std::vector<RankState>& rank_states, | ||
| const std::vector<uint64_t>& rank_epochs, | ||
| const std::vector<bool>& activatable); | ||
| // Apply one rank-state change without reapplying the GroupView or | ||
| // propagating to the selected collective backend. | ||
| void applyRankStateUpdate(GlobalRank rank, InGroupRank in_group_rank, | ||
| RankState state, uint64_t rank_epoch, | ||
| bool activatable); | ||
| // Called by AgentHost when a TE link to a peer comes back up. |
There was a problem hiding this comment.
What's the purpose of GroupView and RankState? I am quite confused with the relationship between them.
There was a problem hiding this comment.
A global rank can belong to multiple groups at the same time. RankState represents state shared by those groups, such as the rank's health. The coordinator maintains this state per global rank so that groups share a common health assessment and do not make independent, potentially conflicting decisions about the same process's health.
GroupView describes how a group is composed from global ranks. It provides a group-specific view of those ranks: whether each member is active, its in-group rank number, and the buffer addresses/offsets used for communication. The same global rank can be active in one group and inactive in another, with different in-group rank numbers and communication resources.
The two functions here synchronize communicator state with the Agent. applyGroupState() performs a full communicator update, applying the GroupView together with the Agent's current rank-state snapshot and rebuilding the collective plan as needed. applyRankStateUpdate() propagates incremental rank-state changes without modifying the group configuration or collective plan.
| enum class DeviceRouteKind : uint32_t { | ||
| Unreachable = 0, | ||
| P2p = 1, | ||
| HostProxy = 2, | ||
| }; | ||
|
|
There was a problem hiding this comment.
Consider renaming it to DeviceRouteType. Type is more common in technical taxonomies than Kind
| // Owns the host-side decisions specific to Ring AllReduce. The common runtime | ||
| // supplies view-epoch signal storage, ordering, and recovery lifecycle; the | ||
| // Ring Plan supplies the exact peers that preparation must check. | ||
| class RingAllReduceProtocol { |
There was a problem hiding this comment.
Name a collective algorithm with XXXProtocol is confusing. We may use Simple/LL128 protocol in the future. Consider naming it with XXXAlgorithm or others.
There was a problem hiding this comment.
Thanks for catching this. I've renamed it to RingAllReduceAlgorithm and moved the implementation from protocols/ring to algorithms/ring. I'll address the decoupling between the algorithm and protocol in follow-up PRs.
| __device__ __forceinline__ bool transferTimedOut(uint64_t start, | ||
| uint64_t timeout_ticks) { | ||
| return timeout_ticks != 0 && clock64() - start >= timeout_ticks; | ||
| } |
There was a problem hiding this comment.
transferTimedOut (transfer_lane.cuh:17) and hostProxyTimedOut (host_proxy_route.cuh:64) have identical bodies. Could you resolve this duplicate?
There was a problem hiding this comment.
Done. Extracted the common logic into deviceTimedOut().
| // One mapped SPSC command slot belongs to each device lane: | ||
| // | ||
| // GPU producer Host proxy consumer | ||
| // ------------ ------------------- | ||
| // acquire completed_sequence == N - 1 | ||
| // write command | ||
| // system fence | ||
| // release submitted_sequence = N --> acquire submitted_sequence == N | ||
| // snapshot command | ||
| // execute payload, then signal action | ||
| // write result | ||
| // acquire completed_sequence = N <-- release completed_sequence = N | ||
| // read result | ||
| // | ||
| // The service contract permits only one producer per lane at a time. | ||
| struct HostProxyCommandSlot { | ||
| uint64_t submitted_sequence = 0; | ||
| uint64_t completed_sequence = 0; | ||
|
|
||
| HostProxyCommandResult result = HostProxyCommandResult::Succeeded; | ||
|
|
||
| HostProxyCommand command; | ||
| }; |
There was a problem hiding this comment.
HostProxyCommandSlot implements an SPSC serving as communication buffer for Host and Device. But ControlMailbox serves as the same role and implementation is quite abundant. could you propose an abstraction for them?
There was a problem hiding this comment.
Done. Added D2HRequestSlot<Request, Reply> for both host-proxy commands and the failure-recovery requests in ControlMailbox.
yuechen-sys
left a comment
There was a problem hiding this comment.
LGTM. Thanks for your principle contribution!
d4a5ea4 to
ff87188
Compare
|
Hi, I've rebased this PR onto the latest main (no functional changes). It looks like GitHub's stacked PR requires a linear history before a PR be merged (GitHub docs). |
Description
Phase 1 of #3483.
This PR introduces an opt-in device collective framework for Mooncake PG and implements GPU Ring AllReduce on that framework.
The legacy GPU path couples collective algorithms to host workers, transfer submission, synchronization, and failure handling. The new framework gives algorithms a narrower contract: execute a rank-local plan through a device-facing transfer interface, while the Coordinator, runtime, and route providers handle group-wide decisions and shared execution rules. #3483 contains the broader design and rollout plan; this PR implements its first vertical slice.
User-visible behavior and backend selection
The new backend is opt-in. For the PyTorch backend, set the following consistently in every worker before creating the GPU communicator:
export MOONCAKE_PG_PREFERRED_GPU_COLLECTIVE_BACKEND=newAn unset value or
legacyrequests the legacy backend. Any other value is rejected as a configuration error. The C API exposes the same preference throughmooncakePgCommConfig_t.preferredGpuCollectiveBackend.The preference is local input to a group-wide decision, not permission for one rank to switch independently. The Coordinator selects the new backend only when all active ranks request it and advertise the required capability. Conflicting preferences or incomplete capabilities select the legacy backend for the entire group. The selected backend is published in
GroupViewduring bootstrap and recomputed after membership transitions.MooncakeCommunicatorapplies the selected backend before group-ready or rank-activation waiters are released. GPU AllReduce then dispatches toDeviceCollectiveRuntime; the existing worker path remains the fallback and continues to serve all other collective operations.Architecture
flowchart LR Communicator -->|"default"| Legacy["Legacy backend"] Communicator -->|"opt-in GPU AllReduce"| Runtime["Device collective runtime"] Runtime --> Ring["Ring AllReduce"] Ring --> Transfer["Device transfer service"] Transfer -->|"direct"| P2P["CUDA P2P"] Transfer -->|"fallback"| Host["Host Proxy + Transfer Engine"]Implementation details
Control plane and dispatch
Rank and communicator registration publish the transfer, workspace, view-epoch, and Ring endpoints required by the new backend.
CentralizedCoordinatorStateMachine::resolveGpuCollectiveBackendvalidates group-wide preference and capability agreement and records one decision in the authoritativeGroupView.The control-plane now:
GroupViewover a newer device plan.kMaxNumRanks.Device transfer service
DeviceTransferServicegives device code one contract for payload transfer, notification, signal waiting, and completion. Algorithms address peers byGlobalRankand registered-region offset throughDeviceTransferHandle, without depending on route-specific host objects.Each
RouteProviderresolves the same endpoint snapshot, and the service selects the first reachable route for each peer. CUDA P2P directly addresses an imported peer mapping; Host Proxy uses mapped command slots andHostTransferProxyto submit work through the Transfer Engine host API. Route selection is independent of backend and algorithm selection and is recomputed from endpoint updates; this PR does not switch routes after an in-flight failure.Ring AllReduce
RingAllReduceProtocolderives one flat ring from the active members in the committedGroupView. The plan binds the rank's position, neighbors, peer offsets, transfer handle, and protocol state. The kernel keeps a fixed launch shape while selecting the active channel count and tile layout from the current plan and request, then runs a pipelined reduce-scatter followed by all-gather.Before data movement starts, the startup leader publishes the invocation's view epoch to every required peer and waits for their epochs locally. Readiness and consumption sequences protect reused payload slots and are reset together with each plan update.
Stream ordering and CUDA Graphs
StrongStreamgives device collective invocations one logical order while leaving each kernel on the caller's CUDA stream. Event handoffs preserve order across eager calls on different streams. During capture, graph-order streams establish dependencies within a graph, while external event nodes carry the latest collective tail between eager work and graph replays.Captured kernels retain stable runtime and protocol state addresses, and a graph user object prevents their release while a live graph refers to them. Membership-dependent topology lives in the device plan, allowing a control update to change membership without changing captured kernel arguments or requiring recapture.
Host-to-device control update protocol
A plan cannot be replaced with an asynchronous copy while a previous invocation may still read it. Recovery adds another constraint: its final CTA can remain parked in the failed kernel, so waiting for a separate
cudaMemcpyAsyncbefore releasing that CTA may deadlock.ControlUpdateinstead carries a complete, idempotent batch that device code applies at a protocol-defined safe point.ControlUpdateBuilderorders state resets before the plan copy. Device execution fences each operation, so a Ready plan cannot become visible before the protocol state it depends on. The mappedControlUpdateSlotfollows the publication protocol defined byControlUpdateState:stateDiagram-v2 [*] --> Idle Idle --> Writing: host begins publication Published --> Writing: host replaces an unclaimed update Writing --> Published: ordinary GroupView update Published --> Claimed: startup leader claims Writing --> Pinned: recovery update Pinned --> Claimed: parked last CTA claims Claimed --> Idle: ordered operations completeA published but unclaimed ordinary update can be replaced by a newer complete image, coalescing intermediate
GroupViewchanges. The first CTA that becomes resident is elected startup leader and claims the latest update before any CTA reads protocol state.Other CTAs remain outside protocol state until startup completes, and
StrongStreamexcludes a concurrent invocation. A recovery update becomesPinnedinstead ofPublished, preventing replacement until the parked final CTA applies that exact update and leaves the failed kernel.Failure recovery
Device code detects lack of progress through transfer and signal-wait timeouts but delegates membership reconciliation to the existing PG control plane:
failure_generationthroughControlMailbox, and remains in the kernel.DeviceCollectiveRecoveryWorkerdrains route work, records the local failure hint, emits an epoch-qualifiedLinkEvent, and invokessyncAfterFailurewhen enabled.GroupView, the runtime publishes aPinnedupdate containing the protocol reset and replacement plan, then acknowledges the matchingready_generation.If reconciliation fails, the runtime invalidates the plan before publishing the pinned reset.
Resource ownership and operational impact
The main allocations are process-wide shared, and belong to
MooncakePGContext, so creating another subgroup does not duplicate the payload workspace.MooncakePGContext::initializeand released during context shutdown after all communicators are gone.The 40 MiB peer-accessible backing region is sub-allocated as follows:
DeviceCollectiveWorkspacepayload buffer shared by all communicators.8 * max_group_sizebytes for view epochs and32 * max_group_size * (1 + 2 * 2) * 8bytes for Ring receive-ready, payload-ready, and payload-consumed signals, for a total of1,288 * max_group_sizebytes. At a capacity of 64, this is 80.5 KiB per communicator. These slices are returned when the communicator's device runtime is destroyed.The steady bulk CUDA footprint introduced here is therefore 40 MiB per initialized context on direct P2P routes and 72 MiB after Host Proxy staging is needed, plus smaller metadata and control allocations. Context initialization also creates one Host Proxy worker, one recovery worker, the 32 mapped Host Proxy command slots, device route metadata proportional to
max_world_size, and theStrongStreamordering stream and event. Each GPU communicator adds ordinary device invocation and Ring state, a mapped host control mailbox, and a CUDA handoff event; these allocations are not remotely registered and are small relative to the bulk regions above.Supported scope and limitations
mooncakePgCommConfig_tappendspreferredGpuCollectiveBackend.See #3483 for the follow-up rollout.
Review guide
The suggested review order follows the control decision into the data path and then into recovery:
resolveGpuCollectiveBackend,AgentStateMachine::applyGroupView, andMooncakeCommunicator::allReduceGpu: consensus, update ordering, and fallback.DeviceTransferService,RouteProvider, andTransferLane: route resolution and the common device contract.DeviceCollectiveRuntimeandRingAllReduceProtocol: plan materialization, launch policy, and Ring sequencing.StrongStream,ControlUpdateState,prepareCollectiveInvocation, andcompleteChannel: graph order, update publication, safe points, and recovery handshake.test_pg_elastic.py.Module
mooncake-transfer-engine)mooncake-store)mooncake-reshard)mooncake-ep)mooncake-pg)mooncake-integration)mooncake-p2p-store)mooncake-wheel)mooncake-common)mooncake-rl)Type of Change
How Has This Been Tested?
For both legacy and new implementations:
mooncake-pg/testspassed.Benchmark
The existing benchmark exercises Mooncake PG through the PyTorch integration layer. Its measurements therefore include Python/PyTorch dispatch overhead, which can dominate small-message latency and does not accurately isolate collective performance. For a more direct comparison, I used a minimal nccl-tests shim for Mooncake PG that forwards the required NCCL AllReduce API to the Mooncake PG C API. This allows NCCL, the legacy Mooncake PG backend, and the new backend to run under the same
nccl-testsharness and configuration.The sweep compares four execution modes on a single node of 8 x H20:
NCCL_ALGO=RingandNCCL_PROTO=Simple. This provides a closer algorithmic baseline, although NCCL still chooses its own topology and channel configuration.All four modes use the same
nccl-testsmessage-size sweep, datatype, reduction operation, warmup count, and measured iteration count.Raw Results
Checklist
./scripts/code_format.shAI Assistance Disclosure
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.