Skip to content

[PG] Refactor P2PProxy with shared chunk pools and receiver-driven credit-based flow control - #1971

Merged
UNIDY2002 merged 8 commits into
kvcache-ai:mainfrom
caozhanhao:pr/p2p_pool
May 7, 2026
Merged

UNIDY2002 merged 8 commits into
kvcache-ai:mainfrom
caozhanhao:pr/p2p_pool

Conversation

@caozhanhao

@caozhanhao caozhanhao commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Receiver-driven credit-based protocol: The receiver now drives the flow by advertising free RecvPool chunks to the sender via PublishSlots. The sender remains passive and only performs RDMA Writes after receiving an invitation.
  • Chunk pools: Replaced monolithic per-rank ring buffers with shared SendPool and RecvPool, each managed by a P2PChunkPool. (Separating send and receive memory can prevent deadlocks where all memory could be reserved for receiving with none left for sending.)
  • Control regions: Restructured control memory into publish_region (receivers invite senders) and completion_region (senders acknowledge finished transfers).
  • Header-footer double-token guard: PublishSlot and CompletionSlot use 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

  • Per-chunk state machines:
    • Sender: Fetch Invite -> Copy-In (staging) -> RDMA Write -> Acknowledge
    • Receiver: Advertise -> Poll Completion -> Copy-Out
  • Non-blocking allocations: All pool acquisitions are strictly non-blocking. If a pool is exhausted the step function returns false immediately and retries on the next polling iteration.
  • Credit-based flow control: The receiver issues up to kP2PControlRingSize (64) outstanding invitations per peer, and the sender stages data only when credits are available.

3. Reliability & Failure Handling

  • Per-peer generation tracking: Added p2pGenerations to ExtensionState so that each peer pair maintains an independent protocol generation, enabling safe recovery and reconnections.
  • Tri-state operation status: Replaced std::atomic<bool> completed with OpStatus (kPending / kSuccess / kFailed) in MooncakeP2PWork. wait() now correctly distinguishes timeout from actual failure and throws on kFailed.
  • Unified ExtensionState serialization: Merged separate store keys (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

  • Environment-variable tuning: Added MOONCAKE_P2P_POOL_SIZE (default 128 MB) and MOONCAKE_P2P_CHUNK_SIZE (default 16 MB) to allow runtime tuning of P2P memory usage without recompilation.
  • API style unification: Renamed public methods for consistency. (e.g., GetInstance -> getInstance, BindMeta -> bindMeta)
  • Simplified metadata: SegmentInfo shrank 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:

  1. Maximized RDMA Bandwidth Utilization via Larger Chunks

    • Old: The fixed buffer layout forced an inefficient 2 MB chunk size.
    • New: By utilizing shared pools, the default chunk size was increased to 16 MB (an 8x increase), without requiring extra memory.
  2. Fine-Grained Pipelining (Eliminating Batch-Commit Serialization)

    • Old: The legacy design relied on a single global head pointer to notify the receiver. Because only one head RDMA update could be in-flight at a time, if Chunk 1 finished transferring while Chunk 0's head update was still traversing the network, Chunk 1's completion notification was forcefully stalled. This single-point bottleneck could frequently interrupt the pipeline.
    • New: By transitioning to independent, per-chunk 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:

Architecture Send Buffer Recv Buffer Total Memory Used
Old Design (to achieve 16MB slot) 128 MB × 8 = 1 GB 128 MB × 8 = 1 GB 2 GB
New Design 128 MB 128 MB 256 MB

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:

  • Old design: Each process group instantiated a dedicated P2PProxy with 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:
    $\sum (\text{group size} \times 32 \text{ MB})$
  • New design: The memory pools are hoisted from the P2PProxy level to the P2PDeviceWorker level. In a typical setup where one process runs on a single device, all groups' P2PProxy instances within the process run on the same P2PDeviceWorker. Consequently, they all share a single global P2PChunkPool. 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.
Architecture Total Memory Used Transfer Unit
Old design (Default buffers) $\sum (\text{group size} \times 32 \text{ MB})$ 2 MB
New design 256 MB (Constant) 16 MB

Example: With three groups of sizes 2, 4, and 8, the old design would allocate $(2+4+8) \times 32 \text{ MB} = 448 \text{ MB}$ just to provide a tiny 2 MB transfer unit. The new design stays at 256 MB globally, while simultaneously delivering a 16 MB minimal transfer unit (8× larger) to all groups.

Benchmarks

Setup & Configurations

Tests were conducted on a single node equipped with 8 × H20-3e.

Config Total (Send + Recv) Memory Minimal transfer unit Note
Original (256 MB) 16 MB × 8 × 2 = 256 MB 2 MB Default (kP2PBufferSize = 1 << 24)
Original (2048 MB) 128 MB × 8 × 2 = 2 GB 16 MB Modified (kP2PBufferSize = 1 << 27)
New (This PR) 128 MB × 2 = 256 MB (Shared) 16 MB Default
NCCL - - Default

Note: In practice, the new implementation's performance scales even better with larger chunk sizes. However, those results are omitted because the primary goal is achieving better performance without incurring additional memory overhead.

Result

PGBench

p2p_pool_pr

Note: The chart above is plotted with out-of-place bandwidth. PGBench with send/recv can be conceptually viewed as a k=1 regular-k benchmark. Under this condition (low-concurrency), the bandwidth improvements are even more pronounced -- reaching approximately 5x higher peak throughput compared to the original 256 MB baseline.

P2P Regular K (K=4)

Overview

  • Bandwidth:

    • Increased by ~2.4x compared to the original default (121 GB/s -> 297 GB/s).
    • Increased by ~1.85x compared to the larger-memory original (2048 MB) configuration (160 GB/s -> 297 GB/s).
  • Iteration Latency:

    • Reduced by >50% compared to the original default (17.6 ms -> 7.2 ms).
    • Reduced by ~46% compared to the larger-memory original (2048 MB) configuration (13.4 ms -> 7.2 ms).

Details

  • Original (256 MB)
# p2p regular-k benchmark  
# backend=mooncake device=cuda world_size=8 k=4 dtype=float  
# tensor_bytes=268435456 element_count=67108864 warmup=5 iters=100  
lat_mean_us=17610.078 lat_p50_us=15606.874 lat_p95_us=17250.967 lat_p99_us=26650.512 rank_bidir_GBps=121.946 cluster_bidir_GBps=975.570 wrong=0
  • Original (2048 MB)
# p2p regular-k benchmark  
# backend=mooncake device=cuda world_size=8 k=4 dtype=float  
# tensor_bytes=268435456 element_count=67108864 warmup=5 iters=100  
lat_mean_us=13375.125 lat_p50_us=11736.808 lat_p95_us=13831.891 lat_p99_us=16987.017 rank_bidir_GBps=160.558 cluster_bidir_GBps=1284.464 wrong=0
  • New
# p2p regular-k benchmark  
# backend=mooncake device=cuda world_size=8 k=4 dtype=float  
# tensor_bytes=268435456 element_count=67108864 warmup=5 iters=100  
lat_mean_us=7227.835 lat_p50_us=5587.480 lat_p95_us=6221.791 lat_p99_us=8897.243 rank_bidir_GBps=297.113 cluster_bidir_GBps=2376.904 wrong=0
  • NCCL
# p2p regular-k benchmark  
# backend=nccl device=cuda world_size=8 k=4 dtype=float  
# tensor_bytes=268435456 element_count=67108864 warmup=5 iters=100  
lat_mean_us=3844.538 lat_p50_us=3823.407 lat_p95_us=4018.876 lat_p99_us=4099.451 rank_bidir_GBps=558.580 cluster_bidir_GBps=4468.644 wrong=0

Reproduction commands

PGBench

Mooncake-PG + TENT
sudo env PATH="$PATH" MC_USE_TENT=1 MC_TENT_CONF='{"topology": {"rdma_blacklist": ["mlx5_0"]}}' python mooncake-pg/benchmark/pgbench.py --collective sendrecv --backe  
nd mooncake  --device cuda  -b 128K -e 1G -f 2 -g 8 -n 100 -w 5
NCCL
sudo env PATH="$PATH" python mooncake-pg/benchmark/pgbench.py --collective sendrecv --backend nccl --device cuda  -b 128K -e 1G -f 2 -g 8 -n 100 -w 5

P2P Regular K

Mooncake-PG + TENT
sudo env PATH="$PATH" MC_USE_TENT=1 MC_TENT_CONF='{"topology": {"rdma_blacklist": ["mlx5_0"]}}' python mooncake-pg/benchmark/p2p_regular_k_bench.py --backend mooncak  
e --device cuda -g 8 --tensor-bytes 256M -w 5 -n 100 -k 4
NCCL
sudo env PATH="$PATH" python mooncake-pg/benchmark/p2p_regular_k_bench.py --backend nccl --device cuda -g 8 --tensor-bytes 256M -w 5 -n 100 -k 4

Future Optimizations

  • Topology-Aware Chunk Sizing: Currently, chunk size is fixed after initialization. In heterogeneous interconnect environments, optimal chunk size depends on link efficiency. Since chunk_len_ is already determined at runtime within PublishSlot/CompletionSlot, migrating to a per-peer (or even per-op) configuration is a natural next step.
  • Finer-Grained Failure Detection: Current fault tolerance relies on a static 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 full reportBrokenPeer() teardown, mitigating disruptions caused by transient network fluctuations.
  • Node-local control plane over ShmTransport: Currently, intra-node control updates (writes to PublishSlot / CompletionSlot) go through RdmaTransport. Switching these writes to TENT's ShmTransport would further reduce control-path latency.

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?

  • Unit tests in mooncake-pg/tests passed.
  • End-to-end integration test with DeepSeekV3 passed.

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 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.

Comment thread mooncake-pg/src/p2p_proxy.cpp Resolved
Comment thread mooncake-pg/src/p2p_proxy.cpp Resolved
Comment thread mooncake-pg/src/p2p_proxy.cpp Resolved
Comment thread mooncake-pg/src/p2p_proxy.cpp Resolved
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!

@yuechen-sys yuechen-sys self-assigned this May 3, 2026
@yuechen-sys

Copy link
Copy Markdown
Member

/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 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.

Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved
Comment thread mooncake-pg/src/mooncake_backend.cpp Resolved

@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.

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!

@UNIDY2002
UNIDY2002 merged commit 84df45a into kvcache-ai:main May 7, 2026
19 checks passed
UNIDY2002 added a commit that referenced this pull request May 7, 2026
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.
A-Liuhao pushed a commit to A-Liuhao/Mooncake that referenced this pull request Jun 25, 2026
…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.
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.

4 participants