Repository navigation
[Refactor] pd: Consolidate sender and receiver implementations - #41140
ShangmingCai merged 17 commits into
Conversation
f00c8bf to
e59c5fb
Compare
d62fa9f to
c4fa949
Compare
There was a problem hiding this comment.
Thanks for the PR. Items:
- Rebase. Main's Mooncake worker already calls
wait_event.synchronize(). Keep that path in the unifiedsend()and correct the "only Mori useswait_event" statement. - Agree the merge order with #38959 (
poll_pp_consensus), #37358 (four new mori registration fields) and #40861 (NIXLwait_eventaccessor). - Add cross-node RDMA, staging and mori/AMD validation; only single-node H200 is covered.
- Mooncake/mori
transfer_latency_sis now measured from the first enqueue, which shifts nightly baselines. Please flag this to the nightly owners.
c4fa949 to
540545d
Compare
|
@Lzy17 Thanks for the review! I have rebased onto the latest main and resolved the conflicts. Once #38959, #37358, and #40861 are merged, I will update this PR accordingly. For performance testing, I currently only have a single H200 node locally, so I will ask around whether someone can help run the tests. Finally, regarding |
|
Thanks for the rebase. I don't know of a specific owner for |
540545d to
049050b
Compare
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Mooncake now consumes the early-send wait event in its worker, as Mori does, so the shared send() comment names both. Drive the Mooncake early-send case through a real MooncakeKVSender, since send() delegates to CommonKVSender. Drop the removed chunk_id, notif and NIXL manager fields from the invalidated-peer reload tests.
Mori registration now carries the DCP size and rank and the state and KV layer ids, so the wire test expects those four frames. Drop the removed chunk_id and NIXL notif arguments from the new Mooncake abort-ack and heterogeneous-TP SWA tests. Cover poll_pp_consensus on the shared sender.
NIXL decode registration now carries the state pool data lengths for prepared state transfers, so the wire test expects that frame. Drop the removed notification argument from the new prepared-state rejection test.
The NIXL manager no longer has transfer_source_rank, the exceptions dict, transfer statuses or check_transfer_done, and the receiver no longer has started_transfer. Stop setting them on the fixtures, and drop the update_transfer_status assertion that a MagicMock always satisfies.
…event prefill.py passes indices_event to senders that set supports_host_tensor_indices, and the Mooncake worker synchronizes on it before reading the pinned indices. Assert that MooncakeKVSender.send and MooncakeKVManager.add_transfer_request carry it onto the queued chunk.
f5e25e5 to
4f87239
Compare
CommonKVSender.__init__ always sets both fields, so clear() and failure_exception() access them without getattr. The tests that build a sender with __new__ now set conclude_state themselves.
CommonKVReceiver.send_metadata and every build_receiver_metadata_message take device_kv_indices explicitly instead of forwarding **backend_kwargs. Only Mooncake encodes it; NIXL and Mori accept and ignore it.
The registration and metadata builders return List[bytes], and the metadata builder takes is_dummy per peer. send_metadata invalidates the cached bootstrap infos itself when a send fails, so _send_bootstrap_message uses operation only for the failure reason.
| with self.kv_mgr.failure_lock: | ||
| failure_reason = self.kv_mgr.failure_records.pop(self.bootstrap_room, None) |
There was a problem hiding this comment.
maybe put pop after clear, that order seems more reasonable to me
| with self.kv_mgr.failure_lock: | ||
| failure_reason = self.kv_mgr.failure_records.pop(self.bootstrap_room, None) | ||
| self.clear() |
…taking the failure reason Only NIXL measured transfer_latency_s on the sender before the lifecycle was shared; Mooncake and Mori used the last-chunk fallback in the metrics collector. Gate the sender measurement behind reports_transfer_latency so kv_transfer_latency_ms and kv_transfer_speed_gb_s keep their meaning for every backend. failure_exception() now clears the room before popping failure_records, matching main. Popping first left the room live during clear(), so a late Failed status or worker failure could re-record a reason under a room that was about to be dropped and never be removed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The backend senders used to set init_time after the shared constructor returned, so the bootstrap timeout window never included the DP-rank registration call. Set it at the end of CommonKVSender.__init__ to keep that window. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
/tag-and-rerun-ci |
maybe_send_cached_prefix_chunk records a completion event on forward_stream and attaches it to the sender so the transfer worker can wait for the prior step's prefill writes before reading those prefix pages. Since sgl-project#41140 the shared CommonKVSender.send passes it to add_transfer_request, but nixl's add_transfer_request accepted wait_event and never put it on the queued chunk, and its worker never waited, so the RDMA read raced the writes it was meant to order against. SGLANG_DISAGG_PREFILL_EARLY_SEND_CACHED_PREFIX defaults to True, so this is the default PD path. The failure is silent: the transfer did move the bytes, they just were not final, so decode reads partially written KV and only an output-quality check can catch it. nixl's add_transfer_request now carries the event on the TransferKVChunk, and the worker waits the way mooncake's does: before the failed-room check and before the staging gather, skipped for a room that already failed, and cleared so a chunk re-enqueued on a watermark defer does not wait again. The wait is the worker thread's first device call, so the thread binds to kv_args.gpu_id before its first wait, as create_backend does; otherwise CUDA opens a context on device 0 on every prefill rank not on GPU 0. The CommonKVSender.send comment now lists nixl among the workers that synchronize on the event. Adds tests that the mooncake worker waits before the staging gather, that the nixl worker binds its device and waits before reading KV and before the staging gather and skips the wait for a failed room, and that NixlKVSender.send hands the event to the next queued chunk only.
Motivation
Mooncake, NIXL, and Mori each implement their own KV sender / receiver lifecycle (sending, registration, metadata publication, polling, timeouts, cleanup, failure handling). The code is duplicated, and the backends are inconsistent in details such as failure-reason recording, terminal-state latching, and timeout trigger conditions.
NIXL determines transfer completion differently from the other two backends:
{room}_kv_*,{room}_aux,{room}_state_*,{room}_stg_*, etc.). Decode callsagent.get_new_notifs()inNixlKVReceiver.poll()and usesTransferStatusto count, per PP rank, the arrival of chunks, parts, aux, and state to determine completion. Decode has to maintain a separate set of counting logic, and notifs are only read inside the receiver'spoll().This PR consolidates the sender / receiver lifecycle of the three backends into a common implementation, and switches NIXL completion notification to the same ZMQ mechanism used by Mooncake / Mori, no longer using NIXL notifs.
Refs: RFC #33861, Tracking #34510.
Modifications
1. NIXL switches to the same ZMQ completion mechanism as Mooncake and removes notifs
Prefill side
conclude_transfer(Success), which sends aKV_STATUSmessage to all non-dummy decode endpoints of the room. The failure path is the same as upstream: it sendsKV_STATUS=Failedwith the failure reason.CHUNK_READYis sent, sharingsend_chunk_readywith Mooncake. Before the next peer reuses the prefill-side packing buffer, the worker likewise waits for that handle to complete. [Feat] [Intel] disaggregation: Support XPU for staging-buffer KV transfer #40861 added the same per-write wait only on XPU, where it observed KV corruption when the next decode rank's gather overwrote a staging buffer that was still being written. This PR waits on every device, so the XPU-only wait is removed.send_notif.Decode side
KV_STATUS,CHUNK_READY,STAGING_REQ, andABORT_ACK.KV_STATUSis counted per prefill rank viaapply_prefill_status, and the room is set toSuccessoncerequired_prefill_response_numis reached;CHUNK_READYis passed to the staging handler viahandle_chunk_ready, shared with Mooncake.poll()only readsrequest_statusand no longer callsget_new_notifs().Removed
TransferStatus,update_transfer_status()and its notif parsing functions (_track_kv_arrival,_track_kv_part_arrival,_handle_stg_notification,_handle_aux_notification,_maybe_submit_last_scatter), andcheck_transfer_done().transfer_source_rank,TransferKVChunk.chunk_id, the chunk counter in the sender, thechunk_idparameter ofadd_transfer_request, the NIXL manager'sexceptionsdict, and the receiver'sstarted_transfer/expects_state.notifparameter of each NIXL send function.{room}_state_{rank}notification added by [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740, which made decode wait for every state component instead of counting the first component's notification. Decode now concludes only onKV_STATUS=Success, which prefill sends after every handle of the last chunk, including the prepared and generic state handles, has completed. TheDecode expects state but prefill has nonewarning is removed with it, matching Mooncake, which skips the state transfer without a warning in that case.Unchanged
state_data_lensregistration frame added by [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740.make_prepped_xferper request, the per-component generic fallback, and the stride-mismatch rejection. Only its completion notification is replaced, as listed under Removed.2. Sender / receiver lifecycle consolidated into the common implementation
send,poll,poll_pp_consensus,clear,failure_exception,aborton the sender and_register_kv_args,send_metadata,clear,failure_exception,aborton the receiver are implemented inCommonKVSender/CommonKVReceiver.poll()andpoll_pp_consensus()share_poll_with_status(), parameterized bycheck_statusvscheck_status_pp_consensus. The receiver'spoll()uses the upstream common implementation.NixlKVSender,NixlKVReceiver,MooncakeKVReceiver, andMoriKVReceiverare empty subclasses.MooncakeKVSenderonly keeps the trace decoratormooncake_trace_funconsendand thesupports_host_tensor_indices = Trueopt-in from [Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492.MoriKVSenderonly keepsclear, which holds the Mori-specific_abort_ack_lockwhen deferred KV release is enabled.build_receiver_registration_message()/build_receiver_metadata_message(): per-backend message encoding; the wire format is unchanged. Mooncake'sdevice_kv_indicesfor DSV4 HiSparse is an explicit parameter ofsend_metadata()and of every builder; NIXL and Mori accept and ignore it.prepare_send_state_indices(): returns the input unchanged by default; Mori uses it to skip CP-replicated state and to normalize per component.sender_trace_module: set to"mooncake"by Mooncake, used to create the sender's trace context.add_transfer_request(): unified across the three backends to 4 positional arguments plus keyword argumentswait_event,indices_eventandtrace_ctx, with each backend ignoring unused parameters.wait_eventis used by Mooncake and Mori: both workers callwait_event.synchronize()before reading source KV, preserving Mooncake's existing path onmain. NIXL currently ignores it; NIXL'swait_eventsupport is handled by [Fix] disaggregation: Fix the early-send wait event on non-CUDA devices and in nixl #43299.indices_eventis used only by Mooncake:CommonKVSender.send()forwards it, and the worker synchronizes on it before reading the pinned host indices ([Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492).trace_ctxis used only by Mooncake.send_chunk_ready()/handle_chunk_ready()are moved toCommonKVManagerand shared by Mooncake and NIXL.prefill_response_trackerchanges fromdefaultdict(set)to a plaindict, with the entry created when the receiver is constructed. The listener thread only reads the entry, so aSuccessarriving afterclear()does not re-create it._staging_ctxis declared onCommonKVManagerwith a default value ofNone.Behavior Changes After Unification
NIXL protocol
Source of the completion signal: decode completion changes from counting RDMA notifications to counting
KV_STATUS=Successmessages sent by prefill ranks, matching Mooncake.When
Successis sent:Successis sent when all handles of the last chunk have completed. If an earlier staging chunk has been deferred due to insufficient staging space and is still queued:Transferringwhile_staging_outstanding > 0, so the source KV is not released;This matches how Mooncake handles it. Before this change, NIXL decode relied on notif counting to wait for all chunks to arrive.
Staging deferral retry: when a chunk is deferred, the worker first waits for the writes already posted in the current round to complete, and then retries; previously it retried immediately without waiting for the posted handles. The retry still reprocesses all decode peers of the chunk, the same as before this change and as Mooncake.
Failure exception: the sender's
failure_exception()raisesKVTransferError, with the reason text taken fromfailure_records. Before this change, NIXL re-raised the original exception object caught in the worker, so the exception type and text format in scheduler logs change.Abort received only by prefill: if an abort reaches only the prefill side while the last chunk's writes are in flight, prefill does not send
Success, and decode does not complete the request. When prefill has already cleared the room, it sends no status, and decode fails the request afterSGLANG_DISAGGREGATION_WAITING_TIMEOUT. This matches Mooncake. Before this change, NIXL decode counted all notifs once the writes landed and completed the request.Sender (all three backends)
send()returns immediately once the sender has reached a terminal state (Success/Failed) and no longer enqueues. Before this change, Mooncake / Mori relied on the status check insideadd_transfer_request, and NIXL relied on_send_failed, which was only set infailure_exception().transfer_latency_sis still reported by the sender only for NIXL (reports_transfer_latency); Mooncake and Mori keep the metrics collector's last-chunk fallback, sosglang:kv_transfer_latency_msandsglang:kv_transfer_speed_gb_sare unchanged for every backend.failure_exception()clears the room before popping the failure reason, on both the sender and the receiver, as onmain.poll()returnsFailedwhen the room is not inrequest_status. Before this change, Mooncake raisedKeyErrorin this case and NIXL returnedWaitingForInput.poll()writesconclude_stateonce it observes a terminal state; before this change NIXL did not latch it.clear()saves the terminal state before removing manager state; cleanup of staging prefetch records (prefetched_rooms/prefetch_requested) is extended from NIXL to Mooncake.aux_indexandstate_indicesare only passed with the last chunk. Before this change NIXL passed them with every chunk, but the worker only read them on the last chunk, so behavior is unchanged.failure_exception()is unified asFailed due to an unknown reason from another rank, replacingNIXL KVSender Exceptionfor NIXL andKV transfer failedfor Mori.Receiver (all three backends)
bootstrap_infosisNone,send_metadata()uniformly records a failure reason and sets the status toFailed. Before this change, NIXL only logged without recording a reason, and Mori returned directly.send_metadata()raisesNotImplementedErrorwhen givenKVTransferDestination.HOST. None of the three backends implements host destinations; before this change, passing this argument raisedTypeErrordue to a signature mismatch.clear()writesconclude_statebefore removing manager state: a terminal state keeps its value, and a non-terminal state is recorded asFailed.abort()can be called repeatedly and does not overwrite an already recorded failure reason when alreadyFailed. Mori'sabort()no longer immediately callsclear()and removes the failure reason: cleanup is done byfailure_exception(), which the scheduler calls after the nextpoll()returnsFailed, so reasons such asAborted by AbortReq.are preserved. Before this change, Mori's failure reason was removed early, andfailure_exception()could only reportunknown reason from another rank.failure_exception()is unified, replacingNIXL KVReceiver Exceptionfor NIXL andKV transfer failedfor Mori.poll(): after metadata is published, the waiting timeout is checked in theWaitingForInputstate. Before this change, NIXL conditioned this onstarted_transferand read notifs insidepoll().bootstrap_room is Nonechecks in the Mori receiver are removed. The scheduler already rejects disaggregation requests without abootstrap_roomon intake, except for the FAKE backend, which usesFakeKVReceiver.Mooncake decode
CHUNK_READYhandlinghandle_chunk_ready(): malformed messages are dropped after logging a warning; late messages for cleared rooms are dropped; a warning is logged when the staging handler is not initialized. Before this change these cases raised an exception and triggered anassert, respectively.Wire compatibility
Accuracy Tests
test/registered/unit/disaggregation/on the revision rebased ontomainafter [Test] cpu: prune mirror and tautology cases from the per-commit CPU suite #45672 pruned the suite: 359 passed, 298 subtests passed (14 cases that require CUDA were skipped).test_common_sender_lifecycle.py:add_transfer_requestargument contract of the three backends with two chunks, whereaux_indexandstate_indicesare only passed with the last chunk;Successis held while a staging chunk is deferred;poll_pp_consensus()concludes on the slowest PP stage while holdingSuccessfor outstanding deferred staging chunks;test_receiver_connection_pool.py:dcp_size,dcp_rank,state_layer_ids, andkv_layer_idsframes from [AMD][PD] enable mori transfer for PD decode DCP #37358, NIXL'sstate_data_lensframe from [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740, and forwarding of Mooncakedevice_kv_indices;Successfrom multiple prefill ranks;CHUNK_READY;Successconcurrent withclear()does not re-create the rank tracker.test_nixl_backend_basic.py:Successis sent only after the KV, aux, and state handles have all completed;Successis not sent when any handle fails; a deferred staging chunk still completes its transfer after the last chunk has sentSuccess;CHUNK_READYandKV_STATUS.test_mooncake_transfer_batching.py: the early-send tests also assert thatMooncakeKVSender.send()andMooncakeKVManager.add_transfer_request()carryindices_eventonto the queued chunk.test_mooncake_deferred_kv_release.pyandtest_nixl_deferred_kv_release.pydropchunk_id;test_disaggregation_wire.pyadds a default value for thenotifparameter; the SWA state transfer test intest_disaggregation_wire.pyand the prepared-state stride-mismatch test from [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740 intest_nixl_backend_basic.pydrop the removednotifargument.main(f5e25e52a7). The rebase adds theindices_eventforwarding for [Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492 and removes the XPU-only staging wait from [Feat] [Intel] disaggregation: Support XPU for staging-buffer KV transfer #40861.cuda_ipcand TCP, and Mooncake over TCP, on Qwen3-8B and Qwen3.6-27B: GSM8K accuracy differs from the baseline within run-to-run variation; at concurrency 1 the output tokens are bitwise identical to a non-PD deployment; the servers stay healthy with no KV leak after abort stress and failure injection.SGLANG_DISAGG_STAGING_BUFFER=1) on Qwen3-8B./healthendpoints return 200, all queue gauges return to 0, and there are no KV leaks or tracebacks. A subsequent GSM8K-200 run scores 0.96 on both versions.transfer_workerpostssend_kvcache_stagedas a GPU VRAM RDMA write and immediately postssend_auxas a CPU DRAM RDMA write before waiting on_await_handles. Having an in-flight VRAM write and an in-flight DRAM write concurrently on the same worker causes the NIXLLIBFABRICbackend to intermittently stall. This PR waits for the staged KV write to finish and sendsCHUNK_READYbefore callingsend_aux, serializing the two writes and eliminating the hang.auxnotifications; the baseline only called_maybe_submit_last_scatterupon receiving the last chunk orauxnotification, so the late arrival of an earlier chunk never triggered final completion. This PR marks transfer completion viaKV_STATUS=Successand checks all chunk scatters inadvance_scatter, eliminating this out-of-order deadlock.Speed Tests and Profiling
Setup: a single node with 8× H200, Qwen3-8B, one prefill (TP1) and one decode (TP1) instance, NIXL backend (UCX). The baseline and this PR were run alternately, restarting the servers for every run, with random-token inputs and fixed output lengths.
UCX_TLS=tcp,cuda_copy): across loads with 2048–32768 input tokens and concurrency 1–128 (3 runs per version), no detectable difference in TTFT, ITL, or throughput.cuda_ipc): at concurrency 1 with 2048 input and 4 output tokens (15 runs per version), mean TTFT increases by 0.99 ms (69.59 → 70.58 ms, +1.4%) and p99 TTFT by 1.21 ms. The added time is in transfer-completion detection: decode-sidedecode_transferredincreases by about 1.1 ms and prefill-sideprefill_transfer_kv_cacheby about 0.6 ms, while prefill forward time is unchanged. At concurrency 16–256, no detectable difference was observed.agent.get_new_notifs()directly insidepoll()to read NIC-delivered notifications from memory, which takes about 1 µs. In this PR, prefill sendsKV_STATUSover ZMQ to the backgrounddecode_listener_threadblocked inrecv_multipart(), which wakes both ZMQ I/O threads and the sleeping listener thread and hands off the Python GIL to the decode scheduler thread, taking about 1.0–1.3 ms per message.prefill_transfer_kv_cachemeasures the time from enteringdisagg_prefill_inflight_queueuntil the scheduler thread observesSuccessinsender.poll(). The synchronous ZMQ send in the transfer worker interacts with GIL scheduling against the prefill main thread, shifting whensender.poll()observesSuccessby roughly one scheduler iteration at concurrency 1; at concurrency 16–256 this is hidden by batch execution.Cross-node RDMA + staging performance
Setup matches the cross-node validation above: prefill TP2 on one node, decode TP1 on a second node, default 4096 MB staging ring buffer, Qwen3-8B, alternating runs with full server restarts.
Summary of results:
prefill_transfer_kv_cacheincreases by a fixed 0.2–0.4 ms per request at low concurrency: on H200 at concurrency 1,prefill_transfer_kv_cacheincreases by 0.24 ms at 2k input (7.31 → 7.54 ms) and by 0.38 ms at 32k input (31.20 → 31.59 ms); on B300 the last-chunk tail similarly increases by about 0.40 ms. Because this is a tiny fraction of total TTFT, end-to-end TTFT is unchanged.prefill_transfer_kv_cacheincreases from 1460 ms to 1836 ms (+376 ms, +26%),decode_transferredincreases from 9349 ms to 9551 ms, and mean TTFT increases from 9668 ms to 9870 ms (+2.1%). On B300, faster compute and EFA transfer keep the default staging buffer from saturating, so both versions perform identically; artificially shrinking the staging pool to fit only a single chunk reproduces the same saturation mechanism, increasing per-request ring wait time by 48% and deferral count by 72%.Root causes:
prefill_transfer_kv_cacheincreases by 0.2–0.4 ms per request:send_kvcache_stagedandsend_auxtogether and waits for both in a single_await_handlescall, hiding the smallauxwrite behind the KV write, at the cost of theLIBFABRICconcurrent-write hang noted above.CHUNK_READY(~0.09 ms), then postssend_auxand runs a second_await_handlesforauxcompletion (~0.30 ms on average including posting and waiting), and finally marksSuccess. Multi-chunk requests also pay ~0.10 ms per non-last chunk for synchronousCHUNK_READYsends.advance_scatterat the start of the decode loop, and sends back a ZMQWATERMARK.poll()viaagent.get_new_notifs()and submits the scatter kernel immediately, taking 0.54 ms on average from prefill write completion to scatter submission. In this PR, prefill first observes write completion and sends ZMQCHUNK_READYto decode's blockingdecode_listener_thread; waking the background thread and acquiring the GIL under load takes 1.97 ms on average. Because the background thread can submit scatters while the decode main thread is insiderun_batch, subsequent wait time until the nextadvance_scattercheck is about 0.6 ms shorter than in the baseline, leaving a net turnaround increase of ~0.8–1.0 ms per staging slot.disagg_prefill_inflight_queue, adding 376 ms to average queue residency while increasing end-to-end mean TTFT by 2.1%.Comparison with other backends and design trade-off:
CHUNK_READY, background decode listener thread scatter submission, andKV_STATUS—and shares the same performance characteristics. Mori does not use a staging buffer and is unaffected.Checklist
isort,ruff format,ruff check).main.CI States
Latest PR Test (Base): ❌ Run #39944512143
Latest PR Test (Extra): ❌ Run #39944512107
Latest PR Test (AMD ROCm 10): ❌ Run #39944512192