Skip to content

perf(pd): negotiated P/D early handoff, overlap the P->D KV transfer with prefill - #3773

Open
ZhangLirong-amd wants to merge 10 commits into
mainfrom
lirzhang/pd-early-handoff
Open

ZhangLirong-amd wants to merge 10 commits into
mainfrom
lirzhang/pd-early-handoff

Conversation

@ZhangLirong-amd

@ZhangLirong-amd ZhangLirong-amd commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

P/D (Mooncake) early handoff as a negotiated, per-request feature. The KV transfer from P to D overlaps with P's prefill only when the chosen (P, D) pair can do it. Every other pair keeps today's relay, so no model or deployment needs an opt-out.

This replaces the earlier revision of this PR, which had a global ATOM_PD_EARLY_HANDOFF=1 default plus per-model opt-outs. That revision is kept at branch lirzhang/pd-early-handoff-old-20261127.

Default: on. ATOM_PD_EARLY_HANDOFF=1. P offers early handoff, and the router asks for it only for a pair that negotiates it; every other pair keeps the legacy relay on its own. ATOM_PD_EARLY_HANDOFF=0 on P (or ATOMESH_ATOM_PD_EARLY_HANDOFF=0 on the router) turns it off, and then nothing changes from main.

Design

1. Negotiation (wire contract v1)

where field meaning
P GET /kv_transfer_info "early_handoff": {"version": 1} Sent only when ATOM_PD_EARLY_HANDOFF=1 (the default), the connector is a Mooncake producer, DP is single-node, CoreManager.reports_dp_rank holds, and router-chunked mode (enable_chunked_transfer) is off. Router-chunked mode takes precedence.
D GET /kv_transfer_info "chunked_receive": {"version": 1, "accepts", "tp_size", "pp_size", "dcp_size", "reason"} accepts is built by chunked_receive_capability(cfg). Only its DCP clause is shared with D's own 400 check (_validate_chunked_receive, through _per_request_state_under_dcp). The PP rule is checked there in chunked_topology_supported's form, and the TP rule is restated in the router (atom.rs), so those two are kept alike by hand.
router, per request P leg kv_transfer_params.early_handoff = true Set only when all of these hold: P offers early_handoff; D accepts; D tp % P tp == 0; the request can chunk (no media, n=1, single prompt); P does not advertise chunked_transfer; and ATOMESH_ATOM_PD_EARLY_HANDOFF is not 0. Unknown D (old ATOM, non-ATOM, failed fetch) means legacy.
P answer, when asked and able 200, x-atom-pd-early-handoff: 1, application/x-ndjson Line 1 is the legacy non-streaming answer (kv_transfer_params with chunked_transfer=true, transfer_id, dp_rank, endpoint), sent at DP dispatch. Line 2 is {"atom_pd_prefill_done": {"ok": bool, "finish_reason": ...}}, sent at the prefill's end. In every other case P answers plain JSON.

Compatibility:

  • An old router never asks, so it behaves as main.
  • An old P ignores the field.
  • An old or incompatible D has no accepts=true.

Kimi-K3 (kimi_linear + DCP decode), a D with PP>1, and a D TP that is not a multiple of P TP all fall back to legacy automatically. The recipe and the benchmark YAML need no changes.

2. Router load accounting and failure visibility

  • The router keeps P's WorkerLoadGuard, including the prefill-token charge, until P's line 2, which is the prefill's end.
  • A P failure after the early answer is visible to the router:
    • Before D's headers arrive, line 2 ok=false, a broken body, or EOF fails the request with 502 prefill_error and drops D.
    • After D's headers, the router only releases P; D then fails on its own.
  • A malformed line 1, or a P body that ends or fails before line 1, answers 502 prefill_parse_error and records a failure in P's circuit breaker and the worker-error metric (WorkerOutcome::finish(false)), like every line-2 failure path.
  • A D error drops P's body, and P aborts the prefill.
  • The same logic (send_decode_during_early_prefill) serves the serial relay and main's concurrent late-kv dispatch (--atom-pd-concurrent, [atomesh] Dispatch the ATOM decode leg concurrently with prefill (--atom-pd-concurrent, default off) #3874). On late-kv, P's line 1 becomes D's kv line, and P stays charged until line 2. On D's 404 fallback, P's prefill keeps running and the relay resends.

3. P's admission rule (no fixed cap, no new timeout)

An early request may allocate its source before D's write request arrives only if:

pinned-early pages + this request's prompt pages + max(prompt pages of the other registered, unallocated chunked requests) ≤ the allocator's usable pages

A request with a per-request state slot also needs state-slot headroom. Otherwise it waits for D (the existing D-first gate).

Why this cannot deadlock:

  1. D learns of a request only from P's early answer, so every request D can hold pages for is already registered on that P rank.
  2. The rule always leaves room for the largest registered request.
  3. Whatever D reserves can therefore be admitted on P and finish.

The remaining edge case is a later, larger request that D reorders ahead of an already-pinned one. It ends in a bounded abort through the worker's existing PREFILL_LOOKUP_TIMEOUT, and a test keeps that path visible.

4. Leak fixes for early sources

  • (a) Scheduler. An early source that was allocated before D reached P is now aborted when the worker reports its transfer failed (retired). Before this fix, pd_admission_ready(False) was ignored for an already-allocated source. Implementation: the pd_admission_ready branch of MooncakeConnectorScheduler.process_pd_completions marks the retired early source SequenceStatus.ABORTED, as it already does for a retired waiting request (what Scheduler.abort_request does for a running one). No connector-base method and no scheduler loop is added.
  • (b) Worker. A retired transfer that gets a new allocation, or that never reported safe, now reports pd_source_safe instead of being skipped. This releases its blocks and state slot. Late metadata for a source that already reported safe still cannot resurrect it.

5. Split out: ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE

Answering the router when P first schedules the request (instead of at DP dispatch) is no longer part of this PR. It needs this PR's admission rule, and the rule does not need it. It will come back in its own follow-up PR on top of this one, delivered through a P/D-owned hook rather than the engine loops, together with its gate answer, its deadlock tests and 4P8D numbers. This PR adds no engine-loop code for it: EngineCore, PPEngineCoreProc, request.py, the connector base and MultiConnectorScheduler are as on main.

Env

env default meaning
ATOM_PD_EARLY_HANDOFF 1 P offers early handoff in /kv_transfer_info; a pair the router does not ask for keeps the legacy relay. 0 never offers it.
ATOM_PD_EARLY_HANDOFF_SPECULATIVE 1 Lets the admission rule above skip the D-first gate. 0 always waits for D; kept for A/B only.
ATOMESH_ATOM_PD_EARLY_HANDOFF (router) on 0 never asks P for early handoff.

Tests (CPU)

  • tests/test_pd_early_handoff.py, 51 test functions (the 12 answer-at-schedule cases moved to the follow-up with the flag):
    • negotiation, i.e. the D shapes including Kimi-K3 and the flag/precedence cases;
    • the admission rule, including both opposite-order counterexamples, the 6/4-page one, usable pages and state slots;
    • the NDJSON answer and its failure paths;
    • D never arriving;
    • an end-to-end P stall past the lookup timeout, which checks that blocks and the state slot are released and that the next request completes;
    • the retired-source abort (test_failed_report_for_an_allocated_early_source_aborts_it).
  • Mutation checks: removing each pin release, each leak fix (the ABORTED mark, the worker retired-transfer branch) makes at least one test fail.
  • Rust (atom/mesh):
    • the decision matrix and discovery parsing;
    • NDJSON relay tests (P load held to line 2, P failure before and after D's headers, D error cancels P, a broken line 1 recorded as P's failure);
    • late-kv + early handoff (P load held to line 2, and the 404 fallback keeps P running).

GPU A/B

g51, 1P1D = P DEP4 + D DEP4 on one node, c256, 1230 s window, one run per arm:

arm TTFT mean / p50 / p90 / p99 ms ITL mean ms total tok/s errors
A EH=0 543 / 420 / 822 / 3218 5.668 1,036,325 0
B EH=1 495 / 361 / 752 / 3821 5.699 1,037,260 0
C B + at-schedule (split out, see §5) 489 / 361 / 768 / 3207 5.700 1,039,317 0

Measured before the rebase onto main. The router binary was built from the generic router commit, before the late-kv merge.

Copilot AI balanced review requested due to automatic review settings November 24, 2026 06:57
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Gate checks are published on every PR so required checks do not stay missing
  • ✅ Expensive jobs run only after the PR is approved, or when a matching ci:* label is present
  • ✅ Pre Checkin must pass before approved heavy jobs continue
  • ✅ Without a matching label, expensive jobs also require a relevant path
  • ✅ A matching ci:* label is an explicit request and can open the gate even when paths would otherwise skip it

Path scope:

  • Native ATOM, vLLM, and SGLang use ignore lists: docs/markdown and unrelated plugin or Mesh paths are skipped
  • ATOMesh uses an include list: Mesh code, the ATOMesh accuracy workflow and its 1P1D launcher, plus the shared models_accuracy.json and accuracy_to_dashboard.py. ATOMesh benchmarks run after merge or on dispatch, not on PRs
  • Relevant path alone does not start expensive jobs; approval still opens the automatic path-scoped gate
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, SGLang, and ATOMesh
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests
ci:mesh Run the ATOMesh accuracy tests, standalone and 1P1D, for Mesh-related changes

Without a matching ci:* label, heavy jobs are skipped when the path is not relevant or the PR is not approved.
Add labels via the sidebar or gh pr edit 3773 --add-label <label>

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

🟡 Changes recommended

Early handoff can deadlock prefill/decode admission until timeout recovery and abort pipeline-parallel prefills because the dispatch rank is not recorded.

2 open issues
What changed in this PR

Adds opt-in early handoff to Mooncake prefill/decode disaggregation, allowing decode-side allocation and KV transfer to overlap prefill without changing the router.

Changes:

  • Returns transfer metadata once the producer’s data-parallel rank is known, while prefill continues in the background.
  • Adds the default-off ATOM_PD_EARLY_HANDOFF switch and uses the existing chunked-transfer path.
  • Adds CPU coverage for transfer timing, request cleanup, rank reporting, and legacy fallbacks.
File Description
tests/​test_pd_early_handoff.py Tests early responses, transfer ordering, cleanup, and fallbacks.
atom/​utils/​envs.py Registers and documents the opt-in environment flag.
atom/​model_engine/​engine_core_mgr.py Records dispatched data-parallel ranks for handoff metadata.
atom/​kv_transfer/​disaggregation/​mooncake/​mooncake_connector.py Enables chunked transfer and bypasses decode-readiness gating for early requests.
atom/​entrypoints/​openai/​api_server.py Selects eligible requests, returns early metadata, and drains detached prefills.

Review effort: Balanced

Comment thread atom/model_engine/engine_core_mgr.py Resolved

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

some changes needed..

test/run with pp>1 on the P side and the flag on? and evidence for opposite admission order?

ci green.

Comment thread atom/model_engine/engine_core_mgr.py Resolved
Comment thread atom/utils/envs.py Resolved
Comment thread tests/test_pd_early_handoff.py Resolved
ZhangLirong-amd added a commit to ZhangLirong-amd/InferenceX that referenced this pull request Nov 24, 2026
Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:19
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Pushed 05a96aa.

PP>1 on P with the flag on: it was broken: the PP branch never recorded a rank, so every early prefill failed closed. Fixed by recording rank 0 (a PP pipeline is one DP rank; D reaches every stage via remote_pp_size) and covered by CPU tests, together with the existing PP chunked-transfer tests. Not run on GPU: our test cluster can't register Mooncake RDMA memory right now, so no P/D GPU run with PP>1 is possible there; stated as an open item in the description.

Opposite admission order: reproduced on CPU with the real P/D schedulers and transfer workers (one prompt per side, D admits B first): the previous head made no progress in either the page-limited or the byte-limited variant. Early requests now keep the D-first admission gate, so P admits in D's order; the probe and the new test_opposite_admission_order_progresses_in_early_mode pass. This changes the design slightly (P no longer starts before D reserved), so the GPU A/B numbers in the description are marked as from revision 1 until re-measured.

Regression vs merge base: identical pass/fail lists (2,457 passed / 21 failed in test_pd*, test_kv*, test_scheduler*, test_engine*, test_dp*, test_mooncake*, test_envs*; 3,451 passed / 21 failed in entrypoints + related). The failures are the same container-environment ones on both sides. Black clean; ruff findings only pre-existing ones in engine_core_mgr.py.

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

🟡 Changes recommended

The new test file lacks required copyright lines, and the topology documentation omits decode-side prerequisites whose violation causes HTTP 400 errors rather than legacy-transfer fallback.

2 open issues
2 resolved since last review

Review effort: Balanced

Comment thread docs/environment_variables.md Resolved
Comment thread tests/test_pd_early_handoff.py Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:33

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

🔵 Needs a closer look

Human review is needed because GPU results cover the superseded ungated revision, leaving the revised P/D admission timing and PP producer early handoff unvalidated on GPU.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

CI on 0a952da is green. Description now has a Related section linking #3772, #3777, #3781 and the draft recipe #3759. The GPU numbers stay marked as revision 1 (gate skipped); a repeat A/B on revision 2 is still open.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (5)

  1. Replace the attribute probes with declared fields and an explicit gate.

    • atom/entrypoints/openai/api_server.py:913: getattr(pc, "is_multinode_dp", False). ParallelConfig.is_multinode_dp always exists (atom/config.py:1128), and your test fake sets it too. Use pc.is_multinode_dp.
    • api_server.py:1055: getattr(seq, "pd_routed_dp_rank", None). Declare pd_routed_dp_rank: int | None = None as a class-level default on Sequence. That adds nothing to the pickle, and the read can be direct.
    • api_server.py:912: hasattr(engine.core_mgr, "_add_prepared_requests"). This probe also gets the class wrong. DisaggCoreManager (RapidServe, engine_core_mgr.py:2596) inherits _add_prepared_requests, so it passes, but it overrides add_request (:2796) and never records the rank. With RapidServe + a Mooncake producer + the flag, every P/D prefill would then take the fail-closed 500 at api_server.py:1056-1063 instead of the legacy path.
    • Gate explicitly instead, e.g. a reports_dp_rank class attribute that is True on CoreManager and False on DisaggCoreManager/RemoteCoreManager. It is cached, so there is no per-request cost.
  2. Share one helper for the producer endpoint. _early_handoff_endpoint (api_server.py:915-929) copies kv_transfer_info (api_server.py:3762-3778): the same iter_connector_configs loop, the same mooncake/kv_producer predicate and the same producer_endpoint(...) call. Use one helper, e.g. _mooncake_producer_endpoint(cfg).

  3. Document what the legacy router relay now does differently. The doc row says "The router and D are unchanged". The protocol is unchanged, but:

    • the router drops P's load guard as soon as P answers (atom/mesh/src/routers/http_pd_router.rs:1174-1175), so with several P its load accounting no longer covers P's queued prefill;
    • a P failure after the early 200 (engine reject, P crash, expiry) is invisible to the router, and D only learns of it through its own timeouts.

    State both in the ATOM_PD_EARLY_HANDOFF row, as the PR body's Risks section already partly does.

  4. Re-measure on this head. Revision 2 adds the D-first gate, so P now waits for the router→D→P hop. The A/B and C1 tables are from the ungated revision 1. Post an off/on A/B on 0a952da (plus the C1 idle table) before merge.

  5. Nit: mooncake_connector.py:498 stores self.early_handoff but uses it only on the next line. Make it a local.

Note for the combined recipe (#3759, owner #3777): with ATOM_DP_IDLE_WHEN_BLOCKED also on, an early request held at the D-first admission gate makes has_forward_work() vote "work", so P runs back-to-back DP dummies until D reserves. That is tracked on #3777.

Checked, no change needed: with the flag off, nothing changes apart from storing the rank after the frame is pickled. Also checked: the rank is recorded correctly on every dispatch path (DP, single engine, PP head, failed send); the drain task releases io_processor state; an expired early request is aborted and reclaimed; the router relay renames dp_rank and D takes the first token from the handoff; the CI lane ran all 25 tests.


Reviewed at 0a952da (Deep; 2 independent passes + cross-PR interaction pass). Already fixed: PP>1 rank, D-first gate (deadlock), doc row incl. D receive limits, PP/_dispatch_to_dp_ranks tests, real /kv_transfer_info test, header.

@valar-cop

valar-cop commented Nov 24, 2026 •

Copy link
Copy Markdown

@zufayu
zufayu requested review from Jasen2201 and valarLip November 25, 2026 01:02
Copilot AI balanced review requested due to automatic review settings November 25, 2026 01:43
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip thanks. Pushed 52c282f.

  1. Probes replaced:
    • pc.is_multinode_dp is read directly.
    • Sequence.pd_routed_dp_rank: int | None = None is now a class-level default and is read directly. An unset rank stays out of __getstate__ (test_unset_routed_rank_is_not_pickled).
    • Explicit gate: reports_dp_rank is True on CoreManager and False on DisaggCoreManager and RemoteCoreManager. It replaces the _add_prepared_requests probe. test_core_managers_that_do_not_report_the_rank_keep_the_legacy_path checks that both keep the legacy path (no fail-closed 500), with CoreManager as the positive control. It fails if DisaggCoreManager reports True.
  2. Shared helper: _mooncake_producer_endpoint(cfg, advertised_only=...), used by _early_handoff_endpoint and /kv_transfer_info. The existing positive and negative /kv_transfer_info test still passes.
  3. Docs: the row and the envs.py comment now say the protocol is unchanged, but the relay drops P's load guard at the early answer (so with several P the router's load accounting no longer covers P's queued prefill), and a P failure after the early answer is invisible to the router, so D only learns of it through its own timeouts.
  4. Re-measure on this head: not done yet. It needs an off/on A/B plus the C1 idle table on a GPU P/D setup. The description keeps the numbers marked as from the ungated revision 1.
  5. early_handoff in MooncakeConnectorScheduler.__init__ is now a local.

On the #3777 note: #3777 now treats a request held at the D-first admission gate as blocked (has_forward_work checks admission_ready as Phase 2 does).

CPU checks (v3 container): test_pd_early_handoff.py 27 passed. Regression over the same broad set: 6,343 passed / 4 failed on both 0a952da and the new head, with identical failures (entrypoints, environment). Black and ruff are clean on the changed lines. The 3 ruff findings in engine_core_mgr.py are pre-existing.

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

🔵 Needs a closer look

Human review is needed because the gated revision’s distributed admission and PP-producer early handoff lack GPU progress and latency validation, while published GPU results cover only the superseded ungated revision.

No open issues 🎉

Review effort: Balanced

@ZhangLirong-amd
ZhangLirong-amd force-pushed the lirzhang/pd-early-handoff branch from 52c282f to 254d6da Compare November 25, 2026 02:32
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

Normalized commit authors (force-push); no code change, the tree is identical to the previous head 52c282f.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (1)

  1. Re-measure on this head (round-1 item 4, still open). The A/B and C1 idle tables in the description are still from the ungated revision 1 (pr_body "GPU numbers are from revision 1"). Revision 2 makes P wait for the router→D→P hop. Post an off/on A/B and the C1 idle table on 254d6da before merge.

Everything else from round 1 is fixed at head:

  • pc.is_multinode_dp (api_server.py:938) and seq.pd_routed_dp_rank (:1066) are read directly. The class default (sequence.py:268) keeps an unset rank out of __getstate__.
  • reports_dp_rank is True on CoreManager and False on DisaggCoreManager and RemoteCoreManager. Those are the only core_mgr types the API server sees, and the new test pins all three.
  • _mooncake_producer_endpoint (api_server.py:901-924) is shared. With advertised_only=True, /kv_transfer_info returns exactly what main returns.
  • The doc row states the dropped router load guard and the P failures the router cannot see (http_pd_router.rs:1174-1175).
  • early_handoff is a local.

Cross-PR with #3777 (d3145cb): a request held at the D-first gate is now voted blocked. The idle drain still ships chunked_admissions and polls pd_admission_ready, so P wakes within about 1-1.5 ms of D's reservation. Expiry or failure aborts the request and the group wakes. Confirmed with a probe on the merged tree.

Please also resolve the 4 valar-cop threads. They are fixed at head.


Reviewed at 254d6da (round 2; delta pass + prior asks, CoreManager sibling enumeration, /kv_transfer_info contract check, cross-PR merge probe). Already fixed: attribute probes, explicit rank gate, shared producer helper, router-relay doc, local nit.

@ZhangLirong-amd
ZhangLirong-amd force-pushed the lirzhang/pd-early-handoff branch from 254d6da to 992400a Compare November 25, 2026 13:02
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip thanks. Pushed dbf30c7 (normal push on 5c28c71).

  1. test_pd_source_claim.py (3 AttributeError: _early_sources): fixed. cancel_preadmission, request_finished, send_finished and process_pd_completions now go through _forget_early_source, guarded by _speculative like _unpin; request_finished touches _answered only with _answer_at_schedule. On rocm/atom-dev:latest (where the module is not skipped): 3 failed at 5c28c71, all pass now. CPU-CI regression that does not depend on the importorskip: test_lifecycle_without_speculative_touches_no_early_source_state.
  2. Nits: the chunked_receive_capability docstring now says only the DCP clause is shared with the receive's refusal (PP is checked in chunked_topology_supported's form, TP is restated in atom.rs); ATOMESH_ATOM_PD_EARLY_HANDOFF has a row in docs/environment_variables.md (test: test_router_kill_switch_is_documented); _retired_chunked_transfers is annotated OrderedDict[ReqId, bool].

Items 2 (split out ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE), 3 (drop take_sources_to_abort and mark the retired early source in process_pd_completions) and 4 (split out the worker-side retired-transfer change) are scope/design changes; they are not in this push and I will answer them separately.

Tests (CPU container rocm/atom-dev:latest, same 100+ files: pd/kv/mooncake/scheduler/engine/dp/envs/entrypoints...): main e5c559a 7933 passed / 43 failed, this head 8019 / 43; the 43 failures are identical on both. black and ruff clean on the changed files; no Rust change in this push.

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

🔵 Needs a closer look

Human assessment is needed because a docstring clarity finding passed the severity filter but was omitted from the published review.

No open issues 🎉

Review effort: Balanced

Review round 6, item 3: drop `take_sources_to_abort` (connector base,
Multi fan-out, the scheduler loop and the fake patches). The
`pd_admission_ready` branch of `process_pd_completions` now marks a
retired early source `SequenceStatus.ABORTED`, as it already does for a
retired waiting request. An allocated early source holds a send claim,
so it is never preempted and is running; `Scheduler.abort_request` marks
a running request the same way and the step's postprocess finishes it.

Also add a flag-off test for main's router-chunked mode: a save for a
retired transfer there is only the cancellation of a request that never
got a source; the worker reports it safe once and the scheduler, which
holds no claim for it, changes nothing else.
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:34
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip thanks for round 6. We would like to keep both pieces you asked to split out in this PR. This comment covers item 2; items 3 and 4 come in a separate comment with the next push.

2. ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE: we keep it in this PR

  • Opt-in, default 0. When it is unset, _answer_at_schedule is False, take_early_answers always returns [], and P sends line 1 at DP dispatch exactly as it does without the flag. Tests for the default path: test_answer_waits_for_allocation_or_the_gate[False] and test_router_chunked_leg_is_never_answered_by_the_scheduler.

  • No new mechanism. The flag only changes when P sends line 1 of the same negotiated NDJSON answer. Negotiation, line 2, P's load guard and the router stay as they are. A separate PR would bring back the same api_server answer path and the same connector state, so the two PRs would edit the same lines.

  • It depends on this PR's admission rule. When the rule sends a request to the D-first gate, P must answer it immediately (admission_ready → _answer_early). Otherwise P waits for D, and D waits for P's answer. The argument and its tests belong with the rule:

    • test_at_schedule_gate_answers_without_deadlock
    • test_idle_ranks_answer_a_gated_request (every DP rank gated, ATOM_DP_IDLE_WHEN_BLOCKED)
    • test_at_schedule_answers_progress_with_real_schedulers
    • API side: test_at_schedule_the_answer_waits_for_the_scheduler, test_at_schedule_a_request_ending_unscheduled_fails and test_at_schedule_router_leaving_before_the_answer_aborts
  • A/B. You are right that C is level with B at c256 1P1D (489 vs 495 ms). The flag targets a long P queue, where an answer sent at dispatch binds D's rank well before the KV lands. That is the 4P8D c512/c768 run, which is still pending. The flag stays at 0 until that run is done.

  • Shared classes. I agree the footprint is too large. Without splitting, I can move the delivery into a P/D-owned hook in this PR:

    • EngineCore, the DP idle drain and the PP loop would no longer call send_early_handoff_answers;
    • take_early_answers would come off KVConnectorSchedulerBase and MultiConnectorScheduler;
    • PrefillScheduler.kv_connector = None and the fake patches in test_dp_sync_interval, test_engine_loop_idle_accounting, test_engine_core_kv_wait, test_scheduler_metrics and test_stream_silence_watchdog would go.

    Would that resolve item 2 for you?

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

This answers the Copilot overview note on non-streaming early handoff (load tracking released too early, prefill failures and disconnect cancellation lost while P is still prefilling). The behaviour is intended, and P's load is not released early.

  • P's load guard is released only at P's line 2 (or at EOF or a body error), never at D's answer.
    • Before D's headers arrive, send_decode_during_early_prefill releases the guard when line 2 comes in (early_prefill_success_releases_its_load_before_decode_answers).
    • If D's headers arrive first, the guard moves into a detached watcher that holds it until line 2 (atom_early_handoff_holds_prefill_past_decode_headers_until_line_two, atom_early_handoff_client_disconnect_keeps_prefill_charged_until_line_two).
    • A non-streaming D sends its headers only with the complete body. That body needs all of P's KV, so P has normally sent line 2 by then.
  • Prefill failures. If P fails before D answers, the router returns 502 prefill_error and drops D (atom_early_handoff_prefill_failure_cancels_decode). If P fails after D has answered, either P's KV already reached D and D's answer is complete, or it did not, and then D's receive fails and D ends the request itself. The router logs P's failure in both cases.
  • Client disconnect after D has answered. The disconnect does not cancel P. This is the same detached-drain model as main's vLLM path (prefill_task.detach()). P stays charged until line 2, and the worker's existing source-release paths free its source.

No code change for this point.

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip items 3 and 4 of round 6. Pushed 17eb360 (normal push on dbf30c7).

4. Worker-side retired-transfer change: we keep it in this PR

  • It is half (b) of the leak fix that this PR's early handoff needs. Half (a), the abort of a retired early source (item 3, which stays here), only starts the cancellation. That cancellation reaches the worker as a save for a transfer the worker has already retired. On main, that save is continued without a report. Without (b), the aborted source never reports pd_source_safe, and its blocks and state slot stay deferred for good. That is the c2048 wedge (released 0 of N, state: 128/128).
  • Splitting would ship a leak fix that does not work on its own. test_p_stall_past_the_lookup_timeout_releases_the_early_source[False/True] fails if either half is removed, so a split-out PR would not fix the leak until the other one merges.
  • What it changes for main's router-chunked mode with the flag off:
    • Router-chunked P allocates only after D has reached it (_chunked_ready), and a registered transfer is never expired as an orphan.
    • So a save for a retired transfer can only be the cancellation of a request that never got a source. D's write request expired while P was stuck, P's registration is then refused, and the waiting request is aborted.
    • The worker now reports that save safe once. It records this in _retired_chunked_transfers, so a repeated save is not reported again.
    • The scheduler holds no send claim and no deferred blocks for that request, so _update_from_kv_xfer_finished does nothing more.
    • A late handoff for a transfer that already reported safe stays silent, as on main (test_late_metadata_cannot_resurrect_retired_source).
    • The only branch that releases anything is a fresh allocation for a retired ID. On main that allocation would leak, and releasing it is correct because no reader can acquire a retired transfer.
  • New test for exactly this path, flag off: test_flag_off_router_chunked_retired_transfer_releases_only_its_own_claim. It runs with ATOM_PD_EARLY_HANDOFF unset and enable_chunked_transfer taken from the config, as in router-chunked mode.
    • It drives the real scheduler and worker through orphan expiry, the refused registration, the abort and the cancellation save.
    • It checks that exactly one pd_source_safe is reported, that no claim or deferred blocks remain, that the pool is whole, and that a repeated save reports nothing more.

3. take_sources_to_abort: done in 17eb360

  • process_pd_completions now marks a retired early source SequenceStatus.ABORTED. It does this in the same pd_admission_ready branch that already aborts a retired waiting request.
  • Removed:
    • the base method;
    • the Multi fan-out;
    • the loop in Scheduler._update_from_kv_xfer_finished;
    • the fake patches in test_lmcache_offload_connector, test_scheduler_metrics and test_state_checkpoint.
  • Why the cleanup is the same.
    • An allocated early source is in _awaiting_send, so it is never preempted and stays in running.
    • Scheduler.abort_request on a running request only sets ABORTED. The step's postprocess then finishes it as aborted, which queues its cancellation. The new code produces that same state in the same step.
    • A source still waiting on an offload load is reclaimed by the next pass's _finish_rejected_waiting, the function abort_request calls.
  • Tests.
    • test_failed_report_for_an_allocated_early_source_aborts_it: only the retired source is marked, and a repeated report changes nothing.
    • The end-to-end test_p_stall_past_the_lookup_timeout_releases_the_early_source[False/True] still passes. P stalls past the lookup timeout, the transfer is retired, the source is aborted, and its blocks and state slot come back. D aborts its receive.
    • Removing the new ABORTED line fails all three.

Tests (Windows CPU venv; the same 4.4k-test set of pd/kv/mooncake/scheduler/engine/dp/multi_connector/offload/lmcache/state_checkpoint files on dbf30c7 and on this head):

  • dbf30c7: 3621 passed. This head: 3623 passed.
  • The failure set is identical except one flaky Store-lookup timing test that failed only on dbf30c7. The remaining failures come from the environment.
  • tests/test_pd_early_handoff.py: 87 passed.
  • The early-handoff, chunked-transfer, source-claim, multi-connector, scheduler-metrics, state-checkpoint, LMCache-offload and PP files: 1103 passed.
  • black and ruff are clean on the changed files. No Rust change.

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

🔵 Needs a closer look

Human assessment is needed to weigh startup delays from serial decode discovery, which can add roughly 10 seconds per unreachable endpoint even when early handoff is disabled.

No open issues 🎉

Review effort: Balanced

The router asks for early handoff per pair (P offers early_handoff, D declares chunked_receive, D TP a multiple of P TP), so an incompatible D keeps the legacy relay with the default on and no deployment needs an opt-out. Measured 1P1D c256: TTFT mean 543 -> 495 ms (-8.8%), ITL and throughput flat. ATOM_PD_EARLY_HANDOFF=0 turns it off.
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:54
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip ATOM_PD_EARLY_HANDOFF is back to default 1 (on) in 9b58679.

Why it is safe on by default:

  1. The router asks per pair. P offers early_handoff, D declares chunked_receive, and the router asks only when D accepts and D TP is a multiple of P TP. Any other D keeps the legacy relay automatically: Kimi-K3 DCP8, D PP>1, a D whose TP is not a multiple of P's, an old D, a non-ATOM D. So no deployment needs an opt-out, and this covers the Kimi-K3 400. Tests: test_d_declares_what_it_can_receive_and_refuses_exactly_that, the new test_default_on_with_an_incompatible_d_keeps_the_legacy_relay and test_default_on_with_a_compatible_pair_answers_early, and the router's atom_early_handoff_decision_matrix.
  2. A provable admission rule replaces the 50% cap. It covers pages, state slots and the allocator's usable pages. Tests: test_room_is_kept_for_the_largest_other_registered_request, test_unequal_prompts_progress_without_an_abort, test_opposite_admission_order_progresses, test_state_slots_keep_a_stateful_request_behind_the_gate, test_the_rule_counts_only_the_allocators_usable_pages.
  3. The leak is fixed, and a retired source is aborted. End-to-end test: test_p_stall_past_the_lookup_timeout_releases_the_early_source.

Measured: 1P1D on one node at c256, TTFT mean 543 -> 495 ms (-8.8%), with ITL and throughput flat. An earlier revision measured about -19% TTFT on 4P8D at c256.

ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE stays default 0, because it measured no gain. To turn early handoff off, set ATOM_PD_EARLY_HANDOFF=0 on P.

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

🟡 Changes recommended

The router drops the worker outcome when a 200 response has malformed data, premature EOF, or a body-read error, misclassifying genuine failures as cancellations and preventing circuit-breaker and worker-error accounting.

1 open issue

Review effort: Balanced

Comment thread atom/mesh/src/routers/http_pd_router.rs Resolved

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (4)

Thanks. Items 1, 3 and 5 are done:

  • _forget_early_source keeps early-source state behind _speculative, and tests/test_pd_source_claim.py passes at head.
  • process_pd_completions marks a retired early source ABORTED, which is what Scheduler.abort_request does for a running request. The base method, the Multi fan-out, the scheduler loop and the three fake patches are gone. Removing the mark fails test_failed_report_for_an_allocated_early_source_aborts_it and the c2048 stall test.
  • The nits are fixed.

Item 4 is withdrawn. Your argument holds. With the worker branch reverted to main's silent continue, test_p_stall_past_the_lookup_timeout_releases_the_early_source[False/True] fails even though the scheduler-side abort is kept. So that branch is half of this PR's own leak fix. test_flag_off_router_chunked_retired_transfer_releases_only_its_own_claim covers what it does to main's router-chunked mode.

  1. ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE: please still split it out. On your question: the P/D-owned hook would fix the shared-class footprint, which is still at head (send_early_handoff_answers at engine_core.py:90,701,1343 and pp_engine_core.py:179, take_early_answers at base.py:231 and multi_connector.py:988, PD_EARLY_SCHEDULED_KEY at request.py:10, and the fake patches). It does not fix the rest. The flag has no measured gain yet (489 vs 495 ms), and the run that could show one (4P8D c512/c768) is still pending. The dependency runs one way: the flag needs this PR's admission rule, and the rule does not need the flag. So a follow-up on top of this PR can bring the flag, its gate answer, the deadlock tests and the hook together, with the 4P8D numbers.

  2. Keep ATOM_PD_EARLY_HANDOFF at 0 here (9b58679 flips it to 1). Negotiation makes default-on safe for incompatible pairs, but whether it pays is still unmeasured.

    • The previous env comment set the gate: "Default 0 until the GPU A/B in the docs row passes" (1P1D c256, 4P8D c512, c768 multi-P).
    • The only data is one 1P1D c256 run per arm, taken before the rebase. In that run TTFT p99 got worse: 3218 -> 3821 ms (+19%).
    • Default on, every Mooncake P takes the NDJSON relay and allocation before D under the admission rule. That is the multi-P load where the c2048 wedge came from.

    Please flip the default in a follow-up with a post-rebase A/B on those configs, or post that A/B here and explain the p99.

  3. Answer the open Copilot thread at http_pd_router.rs:1542, then resolve it. It is right. When line 1 is malformed, or P's body ends or fails before the handoff, the early-handoff branch returns 502 and drops lines without finishing its WorkerOutcome. On a 200 response, WorkerOutcome::drop treats that as a cancellation, so a P that keeps failing this way never records a failure in its circuit breaker or the worker-error metric. Every prefill_done path calls finish(false). Please call lines.outcome.finish(false) before returning the parse error, and add a router test.

  4. Nit: the squash text is stale. The title says "(opt-in)" and the body says "Default: off", which no longer matches head (or will match again after item 2). The body also still says the declaration and the 400 "cannot drift", and it describes leak fix (a) as take_sources_to_abort.

Root cause vs patch

Root problem: P could not know whether the chosen D can take a chunked receive, so a default-on flag needed per-model opt-outs. Per-pair negotiation built from D's own acceptance check, with an automatic legacy fallback, is the root fix. Verdict: root fix. The patch-like parts left are an opt-in, unmeasured mode carried in the engine loops (item 1) and a default flipped ahead of its own gate (item 2).

Prior asks: round 6 #1, #3 and #5 are fixed. #4 is withdrawn (see above). #2 is open. Rounds 1-5 still hold.


Reviewed at 9b58679 (round 7, passes A+B; true delta = old head replayed on e5c559a vs head; mutants for the ABORTED mark and the worker retired-transfer branch; Rust outcome path read only (no cargo); CPU tests: test_pd_source_claim 16 passed, early-handoff/chunked/lmcache/metrics/checkpoint 844 passed, the rest are local uvicorn/jsonschema import errors). Already fixed: _early_sources guard, take_sources_to_abort, nits, Kimi-K3 (by negotiation).

@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip on round 7 item 2. ATOM_PD_EARLY_HANDOFF stays at default 1. No post-rebase A/B is in progress or planned; we answer with existing data instead. What this does not cover is listed at the end.

1. The published ladder ran with early handoff on. All nine points in recipes/DeepSeek-V4.1-Flash-PD.md (c1–c768, 12-GPU 1P1D, 3600 s, 0 errors) ran with ATOM_PD_EARLY_HANDOFF=1 on P. That was an older revision of this PR. The c512 and c768 launch records log the variable. c1–c32 and c256 have it from the launcher's segment default and from the recipe commands. c1024 and above ran with 0 to avoid the old state-slot leak that this PR fixes. The ladder has no OFF arm, so it shows the mode runs clean up to c768. It does not show a gain.

2. A/Bs (all on one node, 1P1D P DEP4 + D DEP4, c256, 900 s window, one run per arm):

Run Revision TTFT mean OFF → ON TTFT p99 OFF → ON
g01, 11-25 254d6da + gate skip 1.227 → 1.003 s (−18%) 6.20 → 5.76 s (−7%)
g01, 11-26 8e0df8c 0.976 → 0.788 s (−19%) 5.33 → 4.41 s (−17%)
g51, 11-27 current logic incl. leak fix, before the rebase 543 → 495 ms (−8.8%) 3218 → 3821 ms (+18.7%)
same g51 run, AT_SCHEDULE=1 543 → 489 ms (−9.9%) 3218 → 3207 ms (−0.3%)

In the g51 run, p50 is −14%, p90 −8.5%, ITL +0.5% and throughput +0.1% (ON vs OFF). Correction: my earlier comment called the −19% run "4P8D". It was this single-node DEP4+DEP4 setup.

3. The p99 in the g51 run (per-request aiperf exports, A n=10,159, B n=10,176):

  • At t=300 s the AgentX replay sends one synchronized burst: about 170 requests within one second, with about 1.3M uncached tokens. It is the same burst in every arm. Of the top 1% of requests by TTFT, this burst's minute holds 88% in OFF, 95% in ON and 86% in AT_SCHEDULE. Cold rails at the start are not the cause (minute 0 holds 4, 0 and 2 of them).
  • Without minute 5, p99 is 1518 ms OFF and 1581 ms ON (+4%).
  • Inside the burst, ON drained its later part about 0.6 s later: 90% of the burst had its first token by 5.22 s in OFF and 5.91 s in ON. P's prefill throughput during those seconds was the same in all arms: 718K, 707K and 735K new tokens scheduled in t=300–305 s. AT_SCHEDULE uses the same early-handoff path and only answers when P schedules. It drained the same burst faster than OFF (5.00 s).
  • Matching the same requests across arms (10,131 pairs): inside the burst ON is +200 ms on average (median −42 ms). Outside it, ON is −53 ms on average (median −55 ms, 9,967 pairs).
  • Noise: an i.i.d. bootstrap of the p99 ratio gives +19.2%, 95% CI −0.7% to +29.2%. The requests are not independent, though. One burst sets the p99, so a 900 s run gives a single sample of it (a bootstrap over one-minute blocks gives −65% to +233%). Across the three A/Bs above, the ON/OFF p99 ratio is −7%, −17% and +19%. Across three 3600 s c256 runs on the 12-GPU setup (about 43K requests each, all ON, one with a D-only kernel change), p99 is 1937, 1942 and 2187 ms.

So the +19% reflects where requests landed in one burst. It is not a consistent tail cost. We cannot rule out a burst-only effect of up to about 0.6 s (+12% at the burst's p90) from binding every burst request to D at dispatch. If it is real, it touches about 1–2% of requests in this trace, while the rest are about 55 ms faster each.

4. Safety (already accepted in this review): per-pair negotiation with automatic legacy fallback, the admission rule over state slots and usable pages, and the leak fix (a)+(b) with test_p_stall_past_the_lookup_timeout_releases_the_early_source[False/True]. The c2048 wedge you mention was that leak, in the old revision with early handoff on. (a)+(b) fix it, but the fix has not been run on GPU at c2048.

Off switch: ATOM_PD_EARLY_HANDOFF=0 on P (or ATOMESH_ATOM_PD_EARLY_HANDOFF=0 on the router) restores the legacy relay.

Not covered: no post-rebase GPU A/B, and no ON/OFF A/B at 4P8D c512/c768 or with multiple P instances (the ladder at c512/c768 is ON only and has no multi-P point). With several P instances behind one router, the router's view of P load is known to be wrong, as the recipe notes.

Review round 7 (#3773), item 1. The flag has no measured gain yet and is
where the engine-loop footprint came from; the dependency runs one way (it
needs this PR's admission rule, the rule does not need it), so it returns in
its own PR on top of this one, through a P/D-owned hook.

Removed with it, all used by the flag alone:
- send_early_handoff_answers and its calls in the EngineCore step, the DP
  idle drain and the PP head loop;
- take_early_answers on KVConnectorSchedulerBase, MultiConnectorScheduler
  and MooncakeConnectorScheduler (with _answer_early, _answer_at_schedule,
  _early_answers, _answered);
- PD_EARLY_SCHEDULED_KEY (request.py) and the api_server wait for it;
- PrefillScheduler.kv_connector = None;
- the env, its docs row, its tests and the fake patches in
  test_dp_sync_interval, test_engine_loop_idle_accounting,
  test_engine_core_kv_wait, test_lmcache_offload_connector,
  test_scheduler_metrics and test_pd_source_claim.

Kept: the admission rule's gate. An early request that may not allocate
before D still waits for D's write request (admission_ready returns
_may_allocate_before_d), and default early handoff answers at DP dispatch
as before.
Review round 7 (#3773), item 3 (Copilot thread at http_pd_router.rs:1542).
When P answers 200 with the early-handoff header but line 1 is malformed, or
its body ends or fails before line 1, atom_prefill_kv returned 502 and
dropped the response's WorkerOutcome unfinished. On a 200 response
WorkerOutcome::drop treats that as a cancellation, so a P failing this way
never reached its circuit breaker or the worker-error metric. The branch now
calls lines.outcome.finish(false) first, as every prefill_done path does.

Test: early_handoff_line_one_failure_is_recorded_as_a_prefill_failure
(malformed / eof / cut: 502, one circuit-breaker failure, no success, P's
load released).
Copilot AI balanced review requested due to automatic review settings November 27, 2026 12:29
@ZhangLirong-amd ZhangLirong-amd changed the title perf(pd): negotiated P/D early handoff, overlap the P->D KV transfer with prefill (opt-in) perf(pd): negotiated P/D early handoff, overlap the P->D KV transfer with prefill Nov 27, 2026

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

🟡 Changes recommended

The advertised ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE switch is never read, so it cannot enable schedule-time handoff or reproduce benchmark arm C.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread atom/entrypoints/openai/api_server.py Resolved
@ZhangLirong-amd

Copy link
Copy Markdown
Collaborator Author

@valarLip thanks. Head is 11cc7e4.

1. ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE is split out (ea043bf).

  • Removed, all used by the flag alone:
    • send_early_handoff_answers and its calls in the EngineCore step, the DP idle drain and the PP head loop;
    • take_early_answers on the connector base, MultiConnectorScheduler and the Mooncake scheduler (with _answer_early / _answered);
    • PD_EARLY_SCHEDULED_KEY and the api_server wait for it;
    • PrefillScheduler.kv_connector = None;
    • the env, its docs row, its 12 test cases, and the fake patches in test_dp_sync_interval, test_engine_loop_idle_accounting, test_engine_core_kv_wait, test_lmcache_offload_connector, test_scheduler_metrics and test_pd_source_claim.
  • engine_core.py, pp_engine_core.py, request.py, base.py and multi_connector.py are now identical to main.
  • Kept: the admission rule's gate. An early request that may not allocate before D still waits for D's write request (admission_ready returns _may_allocate_before_d). Default early handoff still answers at DP dispatch.
  • The removed diff is kept for the follow-up PR. That PR will deliver the event through a P/D-owned hook and bring the 4P8D numbers.

2. Default stays on. Item 2 is answered with the existing evidence in #3773 (comment) (the published ladder ran with it on, the earlier A/Bs, and a p99 analysis of the existing per-request data).

3. Router (11cc7e4).

  • Change: the early-handoff branch of atom_prefill_kv now calls lines.outcome.finish(false) before the 502 prefill_parse_error. This covers a malformed line 1 and a P body that ends or fails before line 1.
  • Test: early_handoff_line_one_failure_is_recorded_as_a_prefill_failure. For malformed, EOF and body-error cases it checks a 502, one circuit-breaker failure, no success, and P's load released.
  • The Copilot thread is answered and resolved.

4. Title and body updated.

  • Default on, and no "(opt-in)".
  • Only the DCP clause is said to be shared with D's 400.
  • Leak fix (a) is described as the ABORTED mark in process_pd_completions.
  • AT_SCHEDULE is described as split out to a follow-up.

Tests, against 9b58679:

  • test_pd_early_handoff + test_pd_source_claim + test_pd_chunked_transfer + test_pd_pp + test_envs: 495 passed. That is 507 minus the 12 AT_SCHEDULE cases.
  • Broad pd / kv / mooncake / scheduler / engine / dp / lmcache / state_checkpoint / entrypoints set: 7375 passed, with the same 35 failures on both heads (local entrypoint and uvicorn environment). No new failures.
  • black and ruff are clean.
  • atom/mesh: cargo fmt --check is clean, and cargo test --lib gives 1450 passed (1449 before).

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (2)

Thanks. Items 1, 3 and 4 are done:

  • ATOM_PD_EARLY_HANDOFF_AT_SCHEDULE is gone. engine_core.py, pp_engine_core.py, request.py, scheduler.py, the connector base, MultiConnectorScheduler and the five patched fakes now match the merge base, and nothing in the tree refers to the flag. The gate in admission_ready is now just _may_allocate_before_d. That is safe because the answer always goes out at DP dispatch, so D learns of every gated request. Reverting the line to return True fails 12 tests in test_pd_early_handoff.py.
  • The router's line-1 failure now calls finish(false), and early_handoff_line_one_failure_is_recorded_as_a_prefill_failure covers malformed, EOF and broken bodies.
  • The title and body match the head.

On item 2, the p99 analysis is accepted, and part of the ask is withdrawn. The burst explanation holds up, and a 4P8D or multi-P perf A/B is no longer required. Two things still block the default flip to 1:

  1. The default-on path has never run on GPU where it used to wedge. The published ladder ran ON only up to c768, on an older revision. c1024 and above ran with 0 because of the state-slot leak this PR fixes, and leak fix (a)+(b) has only CPU tests. A default reaches every Mooncake P/D deployment, including those concurrencies. Please either keep the default at 0 here and flip it in the follow-up with the AT_SCHEDULE PR, or post one run of this head with early handoff ON:

    • 1P1D at c1024, plus c2048 if possible, for the recipe's duration;
    • 0 errors and no stall;
    • after the drain, P's pinned-early pages, state slots and early sources are back to 0.

    This is a safety check, not a perf A/B.

  2. The recipe on main now gives the wrong advice for default on. recipes/DeepSeek-V4.1-Flash-PD.md says:

    • "ATOM_PD_EARLY_HANDOFF is for one P instance only … Leave it unset when more than one P serves a router" (:2741). With the default at 1, leaving it unset turns it on.
    • "Use 0 at c1024 and above until the fix lands" (:107, :157).
    • "Use only with a single P instance" (:2464).

    The PR body says the router now keeps P's load guard until line 2, but your round-7 reply still calls multi-P load "known to be wrong, as the recipe notes". Please say which of these still holds at this head and update the recipe in this PR. If multi-P load accounting is still wrong, the default has to stay 0, because the default reaches multi-P deployments too.

Also reply to and resolve the outdated Copilot thread at api_server.py:1234. The flag it mentions was removed in ea043bf.

Root cause vs patch

Root problem: P could not know whether the chosen D can take a chunked receive, so a default-on flag needed per-model opt-outs. Per-pair negotiation built from D's own acceptance check, with an automatic legacy fallback, is the root fix, and the engine loops no longer carry the opt-in mode. Verdict: root fix. What is left is a default flipped before the regime it once broke has been run (item 2).

Prior asks: round 7 #1, #3 and #4 are fixed. #2 is narrowed to the two points above. Rounds 1-6 still hold.


Reviewed at 11cc7e4 (round 8, passes A+B; true delta = 9b58679..head, merge base unchanged; mutant for the admission gate; Rust read only (no cargo); CPU tests: pd_early_handoff/source_claim/chunked/pp/envs 462 passed, the rest are local uvicorn/jsonschema import errors). Already fixed: AT_SCHEDULE split, router line-1 outcome, squash text, _early_sources guard, ABORTED mark, Kimi-K3 (by negotiation).

… by in-flight prefill load

The recipe still said early handoff is for one P instance only, to leave
it unset with several P instances, and to use 0 at c1024 and above. With
the default on, leaving it unset turns it on. Rewrite those lines for the
head:
- The ladder ran an older revision with EH=1 on one P instance, c1-c768.
  c1024 and above used 0 because of the old state-slot leak.
- The leak fix is in this PR.
- Early handoff is negotiated per (P, D) pair.
- The router holds P's load guard, prefill tokens included, until P's
  line 2.
No GPU result is claimed for c1024+ or multi-P.

Router test atom_early_handoff_multi_prefill_routes_by_in_flight_prefill_load:
two P instances and cache_aware with the recipe's thresholds. While an
early-handoff request whose D already answered is still prefilling on P1,
the next request with the same prefix goes to the idle P2. Line 2 then
releases P1.
Copilot AI balanced review requested due to automatic review settings November 27, 2026 14:29
@ZhangLirong-amd

ZhangLirong-amd commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

@valarLip thanks. Changes are in 55968ae.

1. Recipe (updated in this PR). These are the lines in recipes/DeepSeek-V4.1-Flash-PD.md that gave the wrong advice:

They now say:

  • The ladder ran an older revision of this PR, with ATOM_PD_EARLY_HANDOFF=1 and one P instance at every point (c1-c768).
  • c1024 and above used 0 because of the old state-slot leak. Those runs are not part of the ladder.
  • The leak fix is in this PR: the scheduler aborts a retired early source, and the worker releases its blocks and state slot.
  • Early handoff is negotiated per (P, D) pair. A pair that cannot use it keeps the legacy relay.
  • The router keeps P's load guard until line 2.
  • The default is on, and 0 on P turns it off.

I claim no GPU result for c1024 and above or for multi-P. The recipe says these are covered by CPU and router tests only.

2. Multi-P load accounting is correct at this head. My round-7 reply was wrong on this point: "known to be wrong, as the recipe notes" described the old design. In the old design P's guard was released at the early answer, so a P that was still prefilling looked idle. The c1536 imbalance (P waiting 19 vs 477) came from that design. At head:

  • reserve_pair charges P with WorkerLoadGuard::new(prefill).with_prefill_tokens(..) (http_pd_router.rs:637).
  • On an NDJSON early-handoff answer, atom_prefill_kv moves that guard into PrefillEnd (:1527-1541). It is dropped only when line 2 arrives, or on P's failure or cancel.
  • Only the legacy JSON answer drops it at the answer (:1574).
  • The serial relay and the late-kv dispatch share this path.

Existing tests:

  • atom_early_handoff_starts_decode_and_holds_prefill_load_until_done: load 1 and prefill tokens 7 held after D got line 1, released at line 2.
  • atom_early_handoff_holds_prefill_past_decode_headers_until_line_two: P is still charged after D's headers, whether line 2 reports ok or not.
  • atom_early_handoff_client_disconnect_keeps_prefill_charged_until_line_two.
  • late_kv_with_early_handoff_holds_prefill_load_until_line_two.
  • early_prefill_success_releases_its_load_before_decode_answers: released at line 2, not at D's answer.

New test, since none had two Ps: atom_early_handoff_multi_prefill_routes_by_in_flight_prefill_load. It uses two P workers and cache_aware with the recipe's thresholds (abs 0, rel 1.0), with P1 holding the prefix. An early-handoff request runs on P1, and its D has already answered. While P1 is still prefilling (no line 2), the next request with the same prefix goes to the idle P2. Line 2 then releases P1's load and prefill tokens. If the guard were released at line 1, the two Ps would look balanced and the prefix would pick P1.

3. Copilot thread api_server.py:1234: replied and resolved. The flag was removed in ea043bf.

Default. It stays 1 for now. A GPU run of this head with early handoff ON is in progress: 1P1D at c1024, plus c2048 if feasible, for the recipe's duration. It checks for 0 errors and no stall, and that P's pinned-early pages, state slots and early sources are back to 0 after the drain. I will post it here when it finishes.

CPU tests (rocm/atom-dev, head vs 11cc7e4):

  • early_handoff, source_claim, chunked, pp and envs: 495 passed.
  • Broad pd/kv/mooncake/scheduler/engine/dp/lmcache/checkpoint/entrypoints set: 7375 passed. The 35 failures are the same at both heads; they are the local uvicorn/jsonschema import errors.
  • cargo test --lib: 1451 passed (1450 before, plus the new test).
  • cargo fmt --check is clean.

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

🔵 Needs a closer look

Human assessment is needed because an unpublished finding shows that malformed early-handoff transfer metadata can be treated as cancellation, hiding failures from circuit-breaker and worker-error tracking.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants