Skip to content

Fix scale-up semantics with two-phase extension protocol - #1968

Merged
UNIDY2002 merged 15 commits into
mainfrom
fix-scaleup-p0-crash
May 17, 2026
Merged

UNIDY2002 merged 15 commits into
mainfrom
fix-scaleup-p0-crash

Conversation

@UNIDY2002

@UNIDY2002 UNIDY2002 commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

Description

This PR fixes Mooncake PG elastic scale-up semantics by introducing an optional max_world_size at backend initialization time.

Key idea:

  • Keep PyTorch process group group_size unchanged (healthy ranks remain the only participants in collectives).
  • Allow the ConnectionPoller to poll up to max_world_size (a capacity / observation upper bound) so existing ranks can observe joiners without calling extend_group_size_to().
  • Preserve the two-phase scale-up flow:
    • healthy ranks: get_peer_state() polling → recover_ranks()
    • joiners: join_group()

Motivation: why we need to decouple “polling range” from “group size”

In elastic scale-up, there are ranks that are not yet part of the current collective group, but we still want healthy ranks to proactively:

  • discover their metadata in the store,
  • establish transport readiness,
  • and expose a readiness signal to the control loop.

Previously, this often required calling extend_group_size_to() first, which expands the group size and can make subsequent collectives implicitly include ranks that have not joined yet.

With max_world_size, we decouple these concepts:

  • group_size (what collectives must consider right now)
  • pollingLimit / max_world_size (what the poller is allowed to observe and warm up)

API / behavior changes

  • Add an optional max_world_size to MooncakeBackendOptions.
    • When set, internal rank metadata and active_ranks tensor can be pre-sized to max_world_size.
    • Ranks in [group_size, max_world_size) are treated as inactive reserved slots initially.
  • ConnectionPoller uses pollingLimit_ (default = groupSize_) as the polling upper bound.
    • Only ranks < groupSize_ contribute to totalConnectedPeers_ (so waitUntilAllConnected() semantics remain correct).

Ideal calling sequence (two-phase scale-up protocol, no extend)

  1. Initial ranks start
    • dist.init_process_group(..., world_size=group_size, pg_options=MooncakeBackendOptions(..., max_world_size=MAX))
  2. Joiners start in extension mode
    • dist.init_process_group(..., world_size=MAX, pg_options=MooncakeBackendOptions(..., is_extension=True, max_world_size=MAX))
    • pg.join_group(backend) publishes metadata and blocks until recovered state is published.
  3. Healthy ranks poll readiness
    • repeatedly call pg.get_peer_state(backend, join_ranks) until all ready.
  4. Healthy ranks recover / activate
    • pg.recover_ranks(backend, join_ranks) activates joiners.
  5. Collectives after recovery
    • newly recovered ranks participate in subsequent collectives.

Notes:

  • get_peer_state() is a collective among healthy ranks; application code must ensure all active ranks enter it consistently.

Module

  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake Store (mooncake-store)
  • Mooncake EP (mooncake-ep)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • PyTorch Backend (mooncake-pg)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

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

How Has This Been Tested?

Verified in the existing k8s environment sunxun/mooncake-pg-elastic-test on CPU (forcing TCP via env, without involving intra-node NVLink):

  • MC_FORCE_TCP=1 python -m pytest -q /tmp/Mooncake-src/Mooncake/mooncake-pg/tests/test_pg_elastic.py -k "TestMooncakePGElasticCPU and test_extension"
  • MC_FORCE_TCP=1 python -m pytest -q /tmp/Mooncake-src/Mooncake/mooncake-wheel/tests/test_mooncake_backend_elastic.py -k elastic

Checklist

  • I have performed a self-review of my own code.
  • I have formatted my own code using ./scripts/code_format.sh before submitting.
  • I have updated the documentation.
  • I have added tests to prove my changes are effective.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements a two-phase scale-up protocol for elastic world size extension, ensuring newly added ranks start as inactive and are only activated after signaling readiness. Key changes include updating MooncakeBackend::extendGroupSizeTo to initialize ranks as inactive and adding pg.join_group and pg.recover_ranks to the extension workflow. Feedback identifies a potential race condition in mooncake_backend.cpp where the group size is updated before rank metadata is fully initialized, and a missing timeout in a polling loop within the test suite.

Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@UNIDY2002

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements a two-phase scale-up protocol for the Mooncake backend, enabling ranks to join a group by establishing transport readiness before explicit activation. Key changes include the introduction of a max_world_size parameter for pre-allocating metadata, a pollingLimit_ in the connection poller to monitor potential joiners, and updates to ensure newly added ranks remain inactive until recovered. Review feedback identifies a potential bug where the connected peer counter may fail to update for ranks warmed up before joining, and suggests optimizations for collective operation overhead and tensor resizing logic during group expansion.

Comment thread mooncake-pg/src/connection_poller.cpp Resolved
Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
Track whether a peer has been counted in totalConnectedPeers_ so ranks that
connect before entering groupSize_ are counted once they join, preventing
waitUntilAllConnected hangs.
No functional change; aligns formatting with CI expectations.
@UNIDY2002
UNIDY2002 marked this pull request as draft April 27, 2026 13:45
Tests elastic group extension with multiple disjoint subgroups (group_a,
group_b, group_c) using the split-ranks pattern required by SGLang:
- Primary ranks initialize with initial_world_size only
- Joiners wait for the extend signal, then init with full world_size
- Each subgroup uses membership appropriate to the caller's WORLD view

Also removes the redundant test_pg_elastic_simple.py file.
When a group has max_world_size > actual_size (e.g., size=3, max=4),
_allgather_base and _reduce_scatter_base iterated meta_->size (=4) times
into a buffer sized for only actual_size (=3) ranks, causing OOB writes/reads.

Fix: skip inactive ranks (meta_->activeRanks[j] == false) in the send/recv
lambdas. Inactive ranks have j >= actual_size, so skipping them avoids the
overflow while preserving correct slot-j indexing for active ranks.

allreduce was already safe (uses activeRanks in the reduce kernel).

Add test_allgather_reduce_scatter_extension and
test_allgather_reduce_scatter_recovery to cover both the overflow path
(pre-activation with max_world_size > active ranks) and post-activation
correctness for both extension and recovery scenarios.
@UNIDY2002

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a two-phase elastic scale-up protocol for the Mooncake backend, enabling ranks to observe and activate joiners without immediate group size changes. Key implementation details include the addition of a max_world_size option to pre-size metadata, a pollingLimit in the connection poller to monitor potential joiners, and the masking of inactive ranks during collective operations like allgather and reduce_scatter. The changes also include comprehensive tests for elastic extension and rank recovery. Feedback points out a potential issue with the identity mapping of reserved ranks in subgroups and an off-by-one error in the world size validation logic.

Comment on lines +146 to +148
for (int i = size; i < max_size; ++i) {
local2global_rank_map_[i] = i;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Initializing local2global_rank_map_ with identity for reserved slots (i >= size) assumes that future joiners will have global ranks exactly matching their local rank indices. This assumption breaks elastic scale-up for subgroups where joiners may have arbitrary global ranks. Consider allowing the user to provide a mapping or updating the map dynamically when joiner metadata is discovered in the store.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leave the case where local rank ≠ global rank to future work.

Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
@UNIDY2002
UNIDY2002 force-pushed the fix-scaleup-p0-crash branch from 01833f9 to 3c06802 Compare April 29, 2026 03:25
@UNIDY2002
UNIDY2002 marked this pull request as ready for review April 29, 2026 03:28
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@yuechen-sys yuechen-sys self-assigned this May 4, 2026
@UNIDY2002
UNIDY2002 marked this pull request as draft May 5, 2026 02:45
@UNIDY2002
UNIDY2002 marked this pull request as ready for review May 5, 2026 05:43
Resolve conflicts between PR #1968 (two-phase scale-up) and
main (ProcessGroup inheritance #2040). Key resolution:

- mooncake_backend.h: Keep maxWorldSize_ constructor overload
  but drop Options{"mooncake"} prefix (ProcessGroup doesn't use it)
- test_mooncake_backend_elastic.py: Keep two-phase protocol
  (get_peer_state -> recover_ranks) instead of simple
  extend_group_size_to; update _get_backend() to dist.group.WORLD
@UNIDY2002
UNIDY2002 marked this pull request as draft May 6, 2026 12:29
UNIDY2002 added 4 commits May 7, 2026 00:05
Re-add MooncakeP2PShim (from PR #2043) to the fix-scaleup-p0-crash
branch. The shim was lost during the previous merge conflict resolution.
It is needed because MooncakeBackend inherits ProcessGroup (not Backend)
after #2040, and P2P dispatch requires getBackend() to return a
registered Backend instance.
…e deprecated wheel PG tests

- Sync MooncakeP2PShim with upstream main (#2043): clang-format
  getBackendName to single line (80 cols), add recvAnysource comment
- Fix P2PProxy::ReleaseResources SIGABRT during process teardown by
  tolerating cudaSetDevice failure when CUDA driver is already shut down
- Remove deprecated mooncake-wheel PG tests superseded by mooncake-pg/tests:
  test_mooncake_backend.py, test_mooncake_backend_cpu.py,
  test_mooncake_backend_elastic.py, test_mooncake_backend_p2p_cpu.py,
  test_mooncake_backend_chunk.py, test_mooncake_backend_perf.py
Merges the P2P credit/ack protocol refactor from upstream main:
- CreditSlot/AckSlot replace old head/tail ring buffer
- P2PChunkPool for send/recv staging
- Per-peer epoch tracking (peer_epoch_) for stale detection
- ExtensionState serialization now includes p2pEpochs
- All P2PProxy methods renamed to camelCase

Our CUDA driver shutdown tolerance in releaseResources() is preserved:
upstream's setCudaDeviceIfNeeded() uses TORCH_CHECK which aborts on
cudaErrorCudartUnloading during process teardown.
Before this change, getSize() returned meta_->size which was set to
max_world_size at init time, causing dist.get_world_size() to report
the pre-allocated capacity instead of the actual member count.

Introduce meta_->activeSize to track the visible group size:
- meta_->size remains the capacity (= max_world_size), used by
  collectives to iterate over all slots (activeRanks masks inactive)
- meta_->activeSize tracks the actual member count, returned by
  getSize() / dist.get_world_size()
- activeSize starts at world_size (not max_world_size) and grows
  when extendGroupSizeTo() or recoverRanks() expands the group

For extension ranks, activeSize equals world_size; local-only
behavior before joinGroup() is ensured by activeRanks masking.

Add assertions in test_extension to verify world_size transitions.
@UNIDY2002

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements elastic group size management and a two-phase scale-up protocol. It introduces maxWorldSize for pre-allocating rank metadata, activeSize to track participating ranks, and a pollingLimit in the connection poller to detect joiners. Collective operations were updated to respect active ranks, and safety checks were added for CUDA driver shutdown during resource release. Feedback suggests refactoring duplicated peer-counting logic in connection_poller.cpp and optimizing the activeSize update in mooncake_backend.cpp using std::max_element.

Comment on lines +297 to +303
if (pollingRank <
groupSize_.load(std::memory_order_acquire)) {
totalConnectedPeers_.fetch_add(
1, std::memory_order_release);
peerState.countedInGroup = true;
backend_wakeup_cv_.notify_all();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This block of logic for counting a newly connected peer is duplicated in three places within this function (here, lines 344-350, and lines 375-381). This duplication can make maintenance harder and lead to inconsistencies if one instance is changed but not others.

Consider extracting this logic into a private helper method within the ConnectionContext class. A similar pattern is also used on lines 417-424, which could potentially be unified into the same helper by adding a check for !peerState.countedInGroup.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not fixing

Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
UNIDY2002 and others added 2 commits May 8, 2026 08:57
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
@UNIDY2002
UNIDY2002 marked this pull request as ready for review May 8, 2026 01:02
@UNIDY2002
UNIDY2002 force-pushed the fix-scaleup-p0-crash branch 4 times, most recently from dd05432 to 8f5bb0c Compare May 8, 2026 10:35
@UNIDY2002
UNIDY2002 force-pushed the fix-scaleup-p0-crash branch from 8f5bb0c to 3270818 Compare May 8, 2026 11:21
@UNIDY2002
UNIDY2002 enabled auto-merge (squash) May 12, 2026 01:26
@UNIDY2002
UNIDY2002 disabled auto-merge May 12, 2026 01:26

@yuechen-sys yuechen-sys left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@UNIDY2002
UNIDY2002 merged commit 26b2456 into main May 17, 2026
19 of 21 checks passed
@UNIDY2002
UNIDY2002 deleted the fix-scaleup-p0-crash branch May 17, 2026 01:28
A-Liuhao pushed a commit to A-Liuhao/Mooncake that referenced this pull request Jun 25, 2026
…e-ai#1968)

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants