Repository navigation
[PG] Refactor P2PProxy with shared chunk pools and receiver-driven credit-based flow control - #1971
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements a credit-based RDMA pull protocol for P2P transfers, introducing chunk-based memory management, explicit state machines for send and receive operations, and a generation-based fault recovery mechanism. Feedback highlights the need for stricter validation of environment variables to prevent division-by-zero errors and ensuring chunk_size fits within uint32_t limits. It is also recommended to replace inefficient cudaDeviceSynchronize() calls with event-based polling in the receiver state machine and to use atomic operations for control slot fields to avoid data races. Finally, the deserialization logic for extension states should be improved to handle malformed or truncated buffers more robustly.
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a significant redesign of the P2P communication layer, transitioning to a credit-based RDMA pull protocol. Key changes include the implementation of Publish and Completion slots with header-footer token guards for reliable RDMA writes, and the introduction of shared memory chunk pools across proxies on the same device. The update also enhances fault recovery through per-peer generations and timeout mechanisms. Feedback suggests using fixed-width integer types like int32_t instead of platform-dependent int during the serialization of the extension state to ensure consistency across different cluster nodes.
yuechen-sys
left a comment
There was a problem hiding this comment.
This PR introduces good shared memory pool abstraction through credit-based send/recv FIFO, a good point as an improvement for inference-specific communication. Thanks for your contribution!
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.
…edit-based flow control (kvcache-ai#1971) * [PG] Refactor P2P: Chunk pool + Receiver-driven pipeline * [PG] Refactor P2P State Machine for better readability. * [PG] Per-peer generation and better failure handling. * [PG] Parse pool configuration from environment. * fix typos and refine comments. * apply gemini-code-assist's suggestions. * [PG] Share P2PChunkPool across backends. * [PG] Fix poor naming and address gemini's review comments.
Description
This PR refactors P2PProxy in Mooncake-PG by introducing a receiver-driven, credit-based RDMA pull protocol. It replaces the legacy sender-driven ring-buffer design with fixed-size shared chunk pools, per-peer generation tracking, configurable memory pools, and more robust failure handling.
The primary objective of this PR is to improve P2P performance without incurring additional memory overhead.
Key Changes
1. P2P Protocol & Memory Layout
RecvPoolchunks to the sender viaPublishSlots. The sender remains passive and only performs RDMA Writes after receiving an invitation.SendPoolandRecvPool, each managed by aP2PChunkPool. (Separating send and receive memory can prevent deadlocks where all memory could be reserved for receiving with none left for sending.)publish_region(receivers invite senders) andcompletion_region(senders acknowledge finished transfers).PublishSlotandCompletionSlotuse a 64-byte aligned header/footer token pattern to detect torn RDMA writes, ensuring consumers never observe partially written control data.2. State Machine & Concurrency
falseimmediately and retries on the next polling iteration.kP2PControlRingSize(64) outstanding invitations per peer, and the sender stages data only when credits are available.3. Reliability & Failure Handling
p2pGenerationstoExtensionStateso that each peer pair maintains an independent protocol generation, enabling safe recovery and reconnections.std::atomic<bool> completedwithOpStatus(kPending/kSuccess/kFailed) inMooncakeP2PWork.wait()now correctly distinguishes timeout from actual failure and throws onkFailed.extension_task_count_*,extension_active_ranks_*) into a single binary blob (extension_state_*), reducing metadata store keys and making the state atomically observable.4. Backend Integration & Configuration
MOONCAKE_P2P_POOL_SIZE(default 128 MB) andMOONCAKE_P2P_CHUNK_SIZE(default 16 MB) to allow runtime tuning of P2P memory usage without recompilation.GetInstance->getInstance,BindMeta->bindMeta)SegmentInfoshrank from 4 P2P fields (p2p_send_buffer,p2p_recv_buffer,p2p_ctrl_send,p2p_ctrl_recv) down to 2 (p2p_publish_region,p2p_completion_region).Why Performance Improved
The significant performance gains are directly attributed to two core changes in this refactor:
Maximized RDMA Bandwidth Utilization via Larger Chunks
2 MBchunk size.16 MB(an 8x increase), without requiring extra memory.Fine-Grained Pipelining (Eliminating Batch-Commit Serialization)
CompletionSlots, the sender emits completion notifications immediately as each chunk finishes, with zero serialization dependency on previous control signals. This enables true concurrent pipelining, allowing the receiver to start pulling Chunk 1 into the GPU (cudaMemcpyAsync) while the NIC is simultaneously transmitting Chunk 0's completion.Memory Footprint Analysis
Note: The following analysis compares data-buffer (send/recv pool) memory only; control slot memory is negligible.
Single-Group: Achieving the Same Transfer Unit
The legacy design pre-allocated an independent send/recv lane for every peer. Those lanes could not be borrowed by others. The new design uses a global shared pool where all peers dynamically compete for chunks, decoupling total memory from
world_size.To achieve the same minimal transfer unit (16 MB) across 8 peers:
Multi‑Group Scaling
In real-world applications, frameworks like SGLang initialize multiple process groups with varying sizes. This exposes another critical limitation of the legacy architecture:
P2PProxywith its own buffers. Because of this 1:1 mapping between backend, proxy, and buffer, memory consumption scaled linearly with the sum of participants across all groups. Even if we compromised on performance by using the old default configuration (which yielded a suboptimal 2 MB transfer unit by allocating 16 MB send + 16 MB recv = 32 MB per peer), the total memory would still multiply across groups:P2PProxylevel to theP2PDeviceWorkerlevel. In a typical setup where one process runs on a single device, all groups'P2PProxyinstances within the process run on the sameP2PDeviceWorker. Consequently, they all share a single globalP2PChunkPool. This results in a constant total memory footprint of 256 MB per process/device -- completely independent of the number of groups or their individual world sizes.Benchmarks
Setup & Configurations
Tests were conducted on a single node equipped with 8 × H20-3e.
kP2PBufferSize=1 << 24)kP2PBufferSize=1 << 27)Result
PGBench
P2P Regular K (K=4)
Overview
Bandwidth:
Iteration Latency:
Details
Reproduction commands
PGBench
Mooncake-PG + TENT
NCCL
P2P Regular K
Mooncake-PG + TENT
NCCL
Future Optimizations
chunk_len_is already determined at runtime withinPublishSlot/CompletionSlot, migrating to a per-peer (or even per-op) configuration is a natural next step.transfer_timeout_ms_(default 5s). While effective for hard crashes, a slow NIC or temporarily congested switch might trigger false positives. Future iterations will introduce granular, per-batch retries before initiating a fullreportBrokenPeer()teardown, mitigating disruptions caused by transient network fluctuations.PublishSlot/CompletionSlot) go throughRdmaTransport. Switching these writes to TENT'sShmTransportwould further reduce control-path latency.Module
mooncake-transfer-engine)mooncake-store)mooncake-ep)mooncake-integration)mooncake-p2p-store)mooncake-wheel)mooncake-pg)mooncake-rl)Type of Change
How Has This Been Tested?
mooncake-pg/testspassed.Checklist
./scripts/code_format.shbefore submitting.