diff --git a/atom/entrypoints/openai/api_server.py b/atom/entrypoints/openai/api_server.py index a220d30c7aa..d05786603e2 100644 --- a/atom/entrypoints/openai/api_server.py +++ b/atom/entrypoints/openai/api_server.py @@ -924,6 +924,206 @@ async def _submit_engine_requests(seqs): raise +# --------------------------------------------------------------------------- +# P/D early handoff, negotiated per request. +# --------------------------------------------------------------------------- +# P offers it in /kv_transfer_info (`early_handoff`), D declares what it can +# receive (`chunked_receive`), and the router asks P for it per request +# (`kv_transfer_params.early_handoff`) only for a compatible pair. P then +# answers at DP dispatch: an NDJSON body whose line 1 is the usual prefill +# response with chunked-transfer metadata and whose line 2 is written when the +# prefill ends, so the router holds P's load for the whole prefill and sees a +# P failure after the early answer. +EARLY_HANDOFF_HEADER = "x-atom-pd-early-handoff" +EARLY_HANDOFF_DONE_KEY = "atom_pd_prefill_done" +# Wire version of `early_handoff` / `chunked_receive`. +EARLY_HANDOFF_VERSION = 1 +_early_handoff_endpoint_cache: list[dict[str, Any] | None] = [] + + +def _mooncake_connector(cfg, role: str) -> dict[str, Any] | None: + """This server's Mooncake connector config of `role`, or None.""" + from atom.kv_transfer.disaggregation.pd_producer import iter_connector_configs + + for sub, _ in iter_connector_configs(cfg.kv_transfer_config or {}): + if ( + sub.get("kv_connector") == "mooncake" + and sub.get("kv_role", "kv_producer") == role + ): + return sub + return None + + +def _mooncake_producer_endpoint(cfg, sub: dict[str, Any]) -> dict[str, Any]: + from atom.utils.network import get_ip + + return producer_endpoint( + host=get_ip(), + handshake_port=sub.get("handshake_port", DEFAULT_HANDSHAKE_PORT), + pp_size=cfg.pipeline_parallel_size, + block_size=cfg.kv_cache_block_size, + dcp_size=cfg.decode_context_parallel_size, + ) + + +def _early_handoff_endpoint() -> dict[str, Any] | None: + """This P's chunked-transfer endpoint when it can answer early, else None: + flag off, no Mooncake producer, multi-node DP, or a core manager that does + not learn the DP rank at dispatch (front-end workers, DisaggCoreManager).""" + if _early_handoff_endpoint_cache: + return _early_handoff_endpoint_cache[0] + endpoint = None + cfg = engine.config + if ( + envs.ATOM_PD_EARLY_HANDOFF + and engine.core_mgr.reports_dp_rank + and not cfg.parallel_config.is_multinode_dp + ): + sub = _mooncake_connector(cfg, "kv_producer") + if sub is not None: + endpoint = _mooncake_producer_endpoint(cfg, sub) + endpoint["tp_size"] = cfg.tensor_parallel_size + _early_handoff_endpoint_cache.append(endpoint) + return endpoint + + +def chunked_receive_capability(cfg) -> dict[str, Any]: + """What this server declares it can receive as a chunked-transfer D. + + `accepts` covers the constraints that depend on D alone; the router adds + the one that depends on the pair (D TP a multiple of P TP). Only the DCP + clause is shared with the receive's own refusal + (`_per_request_state_under_dcp`, in `_validate_chunked_receive`); 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 are kept alike by + hand. + """ + reason = None + if _mooncake_connector(cfg, "kv_consumer") is None: + reason = "no Mooncake consumer connector" + elif cfg.pipeline_parallel_size != 1: + reason = "chunked P/D requires D PP=1" + elif _per_request_state_under_dcp(cfg): + reason = "chunked P/D does not send per-request state to a DCP decode" + return { + "version": EARLY_HANDOFF_VERSION, + "accepts": reason is None, + "tp_size": cfg.tensor_parallel_size, + "pp_size": cfg.pipeline_parallel_size, + "dcp_size": cfg.decode_context_parallel_size, + "reason": reason, + } + + +def _per_request_state_under_dcp(cfg) -> bool: + # Not checkable at startup on P: P learns D's DCP only from a request. + return ( + cfg.decode_context_parallel_size > 1 + and cfg.hf_config.model_type + in InputOutputProcessor._per_req_cache_model_types() + ) + + +def _early_handoff_params( + kv_transfer_params: dict[str, Any] | None, +) -> dict[str, Any] | None: + """The chunked copy of a prefill leg whose router asked for early handoff, + or None to answer after the prefill as before.""" + if ( + not kv_transfer_params + or not kv_transfer_params.get("early_handoff") + or not kv_transfer_params.get("do_remote_decode") + or kv_transfer_params.get("do_remote_prefill") + or kv_transfer_params.get("chunked_transfer") + or _early_handoff_endpoint() is None + ): + return None + params = {k: v for k, v in kv_transfer_params.items() if k != "early_handoff"} + params.update( + chunked_transfer=True, + transfer_id=f"early-{uuid.uuid4().hex}", + # Lets the connector allocate before D's write request when P's pool + # provably keeps room (`_may_allocate_before_d`). + pd_early_handoff=True, + ) + return params + + +def _early_handoff_answer(transfer_id: str, dp_rank: int) -> dict[str, Any]: + """What the router relays to D: P's endpoint, the transfer and the DP rank + (`dp_rank`, renamed to `remote_dp_rank` by the relay). No first token: D + takes it, and the drafts, from the transfer's final handoff.""" + return { + **_early_handoff_endpoint(), + "do_remote_prefill": True, + "do_remote_decode": False, + "chunked_transfer": True, + "transfer_id": transfer_id, + "dp_rank": dp_rank, + } + + +def _prefill_succeeded(finish_reason: str | None) -> bool: + """Whether a finished prefill leg handed its KV off (see + `produced_no_handoff`, whose leave reason the engine reports).""" + reason = finish_reason or "" + return bool(reason) and not ( + reason == "aborted" + or reason.startswith("unschedulable") + or reason.endswith("_error") + ) + + +class _EarlyPrefill: + """A prefill whose HTTP answer left at dispatch, until the engine ends it.""" + + def __init__(self, seq, token_queue: asyncio.Queue): + self.seq = seq + self.task = asyncio.create_task(self._drain(token_queue)) + + async def _drain(self, token_queue: asyncio.Queue) -> dict[str, Any]: + try: + while True: + item = await token_queue.get() + if item.get("finished", False): + reason = item.get("finish_reason") + return {"ok": _prefill_succeeded(reason), "finish_reason": reason} + finally: + engine.io_processor.requests.pop(self.seq.id, None) + + def abort(self) -> None: + """The router gave up on this request: stop computing it.""" + if not self.task.done(): + with contextlib.suppress(Exception): + engine.core_mgr.abort_request(self.seq.id) + self.task.cancel() + + +def _nonstream_response(body: dict[str, Any], final_output: dict[str, Any]): + """The JSON answer, or for an early-handoff prefill the two-line NDJSON + answer (line 1 now, line 2 when the prefill ends).""" + early = final_output.get("_early_prefill") + if early is None: + return JSONResponse(content=body) + + async def lines(): + try: + yield json.dumps(body, separators=(",", ":")) + "\n" + done = await asyncio.shield(early.task) + yield json.dumps({EARLY_HANDOFF_DONE_KEY: done}) + "\n" + except BaseException: + # The router disconnected (D failed, or its client left), or the + # drain failed: nobody will read this prefill. + early.abort() + raise + + return StreamingResponse( + lines(), + media_type="application/x-ndjson", + headers={EARLY_HANDOFF_HEADER: "1"}, + ) + + async def generate_async( prompt_or_tokens: str | list[int] | PrefixEncoding, sampling_params: SamplingParams, @@ -985,6 +1185,10 @@ def do_preprocess(): dp_parent_session_id=dp_parent_session_id, ) + early_params = _early_handoff_params(kv_transfer_params) + if early_params is not None: + kv_transfer_params = early_params + seq = await loop.run_in_executor(None, do_preprocess) try: _validate_sequence_context_length(seq, sampling_params) @@ -993,6 +1197,43 @@ def do_preprocess(): raise await _submit_engine_requests([seq]) + if early_params is not None: + dp_rank = seq.pd_routed_dp_rank + if dp_rank is None: + # Admission happened somewhere that does not report the rank, so + # no D could find this source. Fail closed instead of stranding P. + with contextlib.suppress(Exception): + engine.core_mgr.abort_request(seq.id) + engine.io_processor.requests.pop(seq.id, None) + raise RuntimeError("P/D early handoff: DP rank unknown at dispatch") + response = { + "text": "", + "token_ids": new_token_ids(), + "logprobs": [] if sampling_params.logprobs else None, + "finish_reason": "length", + "num_tokens_input": seq.num_prompt_tokens, + "num_tokens_output": 0, + "ttft": 0.0, + "tpot": 0.0, + "latency": time.time() - started_at, + "num_cached_tokens": 0, + "kv_transfer_output_meta_info": _early_handoff_answer( + early_params["transfer_id"], int(dp_rank) + ), + # Read by `_nonstream_response`; no response builder copies it. + "_early_prefill": _EarlyPrefill(seq, token_queue), + } + if return_token_ids: + response["prompt_token_ids"] = list(seq.prompt_token_ids) + logger.debug( + "PD early handoff: request %s transfer %s answered at DP rank %d", + request_id, + early_params["transfer_id"], + dp_rank, + ) + yield response + return + _finished_ok = False try: while True: @@ -1375,13 +1616,9 @@ def _validate_chunked_receive(params: dict[str, Any] | None) -> None: status_code=400, detail="Chunked P/D requires D PP=1 and D TP a multiple of positive P TP", ) - # Not checkable at startup: chunked transfer is P's setting, and P learns - # D's DCP only from a request. - if ( - cfg.decode_context_parallel_size > 1 - and cfg.hf_config.model_type - in InputOutputProcessor._per_req_cache_model_types() - ): + # D declares this clause in /kv_transfer_info through the same predicate + # (`chunked_receive_capability`), so a negotiating router never sends it. + if _per_request_state_under_dcp(cfg): raise HTTPException( status_code=400, detail="Chunked P/D does not send per-request state to a DCP decode", @@ -2537,6 +2774,7 @@ async def _chat_completions( ) # Non-streaming + final_output: dict[str, Any] = {} if is_multimodal and effective_n > 1: outputs = await _race_disconnect( generate_async_fanout( @@ -2662,7 +2900,7 @@ async def _chat_completions( ) _log_request_model("response", request_id, resp) # Bypass FastAPI's recursive conversion of the token ID list. - return JSONResponse(content=resp.model_dump(mode="json")) + return _nonstream_response(resp.model_dump(mode="json"), final_output) except _ClientDisconnected: # Client hung up; seq already aborted + popped. Nothing to return. @@ -2910,6 +3148,7 @@ async def _completions( ) # Non-streaming + final_output: dict[str, Any] = {} if max_tokens == 0: output = await _zero_token_output(request, prompt_or_tokens) resp = ( @@ -2960,7 +3199,7 @@ async def _completions( request_id, model_name, final_output, echo=echo ) _log_request_model("response", request_id, resp) - return JSONResponse(content=resp.model_dump(mode="json")) + return _nonstream_response(resp.model_dump(mode="json"), final_output) except _ClientDisconnected: # Client hung up; seq already aborted + popped. Nothing to return. @@ -3851,23 +4090,16 @@ async def kv_transfer_info(): "kv_role": kv_role, "handshake_port": handshake_port, } - from atom.kv_transfer.disaggregation.pd_producer import iter_connector_configs - from atom.utils.network import get_ip - - for sub, _ in iter_connector_configs(kv_cfg): - if ( - sub.get("kv_connector") == "mooncake" - and sub.get("kv_role", "kv_producer") == "kv_producer" - and sub.get("enable_chunked_transfer", False) - ): - info["chunked_transfer"] = producer_endpoint( - host=get_ip(), - handshake_port=sub.get("handshake_port", DEFAULT_HANDSHAKE_PORT), - pp_size=cfg.pipeline_parallel_size, - block_size=cfg.kv_cache_block_size, - dcp_size=cfg.decode_context_parallel_size, - ) - break + producer = _mooncake_connector(cfg, "kv_producer") + if producer is not None and producer.get("enable_chunked_transfer", False): + # Router-chunked mode: the router dispatches P and D concurrently. + info["chunked_transfer"] = _mooncake_producer_endpoint(cfg, producer) + elif _early_handoff_endpoint() is not None: + # Router-chunked mode takes precedence; otherwise the router may ask + # this P for early handoff per request, for a D that can receive it. + info["early_handoff"] = {"version": EARLY_HANDOFF_VERSION} + if kv_role == "kv_consumer": + info["chunked_receive"] = chunked_receive_capability(cfg) return info diff --git a/atom/entrypoints/openai/frontend_workers.py b/atom/entrypoints/openai/frontend_workers.py index ec361723a93..2ead87ff478 100644 --- a/atom/entrypoints/openai/frontend_workers.py +++ b/atom/entrypoints/openai/frontend_workers.py @@ -375,6 +375,9 @@ class RemoteCoreManager: """Stands in for ``CoreManager`` in a worker: requests go to the hub, and the hub's outputs reach the same per-request callbacks.""" + # The hub dispatches, so a worker never learns its requests' DP ranks. + reports_dp_rank = False + def __init__(self, info: dict): self.index = info["index"] self.max_pool_tokens = info.get("max_pool_tokens") diff --git a/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py b/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py index a6c32f5a1c0..301339e6df4 100644 --- a/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py +++ b/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py @@ -11,6 +11,7 @@ from __future__ import annotations import hashlib +import heapq import logging import math import os @@ -489,9 +490,45 @@ def __init__(self, config: Config) -> None: self.block_size = config.kv_cache_block_size self.dcp_size = config.decode_context_parallel_size self.hash_block_size = self.block_size * self.dcp_size - self.enable_chunked_transfer = kv_transfer_config.get( - "enable_chunked_transfer", False + # Early handoff (ATOM_PD_EARLY_HANDOFF) drives the same chunked + # machinery from P's own early answer; the router asks for it per + # request, only for a D that declared it can receive chunked transfer. + early_handoff = bool(self.is_producer and envs.ATOM_PD_EARLY_HANDOFF) + self.enable_chunked_transfer = ( + kv_transfer_config.get("enable_chunked_transfer", False) or early_handoff ) + # Whether an early request may allocate before D's write request + # (`_may_allocate_before_d`). Every use of the state below is behind it. + self._speculative = bool( + early_handoff and envs.ATOM_PD_EARLY_HANDOFF_SPECULATIVE + ) + self._pool_pages = 0 + if self._speculative: + # The engine sizes the pool before it builds the scheduler. + self._pool_pages = int(config.num_kvcache_blocks) + if self._pool_pages <= 0: + raise ValueError( + "ATOM_PD_EARLY_HANDOFF_SPECULATIVE needs a sized KV pool " + f"(num_kvcache_blocks={self._pool_pages})" + ) + # The pool is refined to the allocator's usable pages, and the live + # state slots are learned, in `bind_block_manager`. Until then (None) + # a request with a per-request state slot keeps the gate. + self._state_slots: int | None = None + self._state_slots_per_req = 1 + # Early sources allocated before D's report, str(request id) -> pages. + # Keyed like `_awaiting_send`: `send_finished` may name either form. + self._spec_pins: dict[str, int] = {} + # Those of them holding a per-request state slot (`has_per_req_cache`). + self._spec_state_pins: set[str] = set() + # Early sources allocated before D's report, str(request id) -> the + # sequence, so a failed report (the worker retired the transfer: D was + # told it failed) stops the prefill instead of computing for nobody. + self._early_sources: dict[str, Sequence] = {} + # Max-heap of the registered, not yet allocated chunked requests + # (`_chunked_waiting`), as (-prompt pages, id); stale entries are + # dropped lazily when they reach the top. + self._waiting_pages: list[tuple[int, Any]] = [] self._chunked_receiving: dict[ReqId, Sequence] = {} self._chunked_admission_timeout_s = float( kv_transfer_config.get("chunked_admission_timeout_s", 300) @@ -676,8 +713,11 @@ def cancel_preadmission(self, seq: Sequence) -> None: self._reqs_need_save[seq.id] = previous_save if not already_claimed: self._awaiting_send.discard(str(seq.id)) + self._unpin(seq.id) + self._forget_early_source(seq.id) if previous_waiting is not None: self._chunked_waiting[seq.id] = previous_waiting + self._note_waiting(seq) if was_ready: self._chunked_ready.add(seq.id) @@ -693,9 +733,22 @@ def update_state_after_alloc(self, seq: Sequence) -> None: seq.id in self._chunked_ready, ), ) + d_reported = seq.id in self._chunked_ready self._chunked_waiting.pop(seq.id, None) self._chunked_ready.discard(seq.id) params = seq.kv_transfer_params or {} + if ( + self._speculative + and params.get("pd_early_handoff") + and not d_reported + and str(seq.id) not in self._awaiting_send + ): + # Allocated before D's report: its pages wait on D until D reaches + # P or the source is released. + self._spec_pins[str(seq.id)] = len(seq.block_table) + if seq.has_per_req_cache: + self._spec_state_pins.add(str(seq.id)) + self._early_sources[str(seq.id)] = seq if params.get("chunked_transfer") and ( self.is_producer or params.get("do_remote_prefill") ): @@ -791,6 +844,11 @@ def request_finished(self, seq: Sequence) -> None: aborted = produced_no_handoff(seq) self._chunked_waiting.pop(seq.id, None) self._chunked_ready.discard(seq.id) + self._forget_early_source(seq.id) + if aborted: + # Its cancellation is queued below. A finished source keeps + # its pin until D reaches P or the worker reports it safe. + self._unpin(seq.id) params["prefill_aborted"] = aborted if not aborted: drafts = getattr(seq, "spec_token_ids", None) @@ -891,6 +949,8 @@ def should_defer_free(self, seq: Sequence) -> bool: def send_finished(self, req_id) -> None: self._awaiting_send.discard(str(req_id)) + self._unpin(req_id) + self._forget_early_source(req_id) def abort_send(self, seq: Sequence) -> None: # request_finished queued cancellation; only the aggregated @@ -919,10 +979,122 @@ def admission_ready(self, seq: Sequence) -> bool: now + self._chunked_admission_timeout_s, ) self._pending_chunked_admissions[seq.id] = params["transfer_id"] + self._note_waiting(seq) _, deadline = self._chunked_waiting[seq.id] if self._expire_chunked_admission(seq, deadline, now): return False - return seq.id in self._chunked_ready + if seq.id in self._chunked_ready: + return True + if not params.get("pd_early_handoff"): + return False + # Otherwise it waits for D's write request (the gate). + return self._may_allocate_before_d(seq) + + # ---------------------------------------------- allocation before D's report + # + # An early request is registered like a gated one (the worker reports D's + # arrival, and a write request that arrives while P queues is not expired), + # but it may allocate its source before D reserved its pages, so P's + # prefill overlaps the router->D->P hop. Such a source waits on D. The + # danger is a cycle: P's pool full of sources waiting on D while D's pool + # holds reservations for requests P has no room for. + # + # Rule: allocate before D only if, afterwards, the pages pinned that way + # still leave room in P's pool for the largest other registered chunked + # request: pinned + pages(seq) + max_{r registered, r != seq} pages(r) + # <= pool. Why that suffices: D learns of a request only from P's early + # answer, and P answers only after it dispatched the request to this rank, + # so every request D can hold pages for against this rank is already + # registered here (or allocated, and then it progresses). Sources D has + # reserved (and every non-P/D allocation) finish and free on their own, so + # P's pool eventually holds only pins, and the room above admits whatever + # D reserved. Past the rule the request waits for D (the gate), so P falls + # back to D's order exactly when D falls behind. Remaining gap: a larger + # request registered after the pins were taken, which D reserves ahead of + # a pinned one while every D page waits on P; the worker's lookup timeout + # (PREFILL_LOOKUP_TIMEOUT) then cancels the oldest pinned source and D + # aborts that request. + + def _prompt_pages(self, seq: Sequence) -> int: + return -(-seq.num_prompt_tokens // (self.block_size * self.dcp_size)) + + def _note_waiting(self, seq: Sequence) -> None: + if not self._speculative: + return + heapq.heappush(self._waiting_pages, (-self._prompt_pages(seq), id(seq), seq.id)) + # Keep the lazy heap bounded by the live set. + if len(self._waiting_pages) > 2 * len(self._chunked_waiting) + 64: + self._waiting_pages = [ + (-self._prompt_pages(s), id(s), s.id) + for s, _ in self._chunked_waiting.values() + ] + heapq.heapify(self._waiting_pages) + + def _largest_waiting_pages(self, exclude: Sequence) -> int: + """Prompt pages of the largest registered, unallocated chunked request + other than `exclude`.""" + heap = self._waiting_pages + held = [] + try: + while heap: + _, _, req_id = heap[0] + if req_id not in self._chunked_waiting: + heapq.heappop(heap) + elif req_id == exclude.id: + held.append(heapq.heappop(heap)) + else: + return -heap[0][0] + return 0 + finally: + for entry in held: + heapq.heappush(heap, entry) + + def _unpin(self, req_id) -> None: + if self._speculative: + self._spec_pins.pop(str(req_id), None) + self._spec_state_pins.discard(str(req_id)) + + def _forget_early_source(self, req_id) -> Sequence | None: + """Drop and return `req_id`'s early source. Only a speculative + connector records them (`update_state_after_alloc`), so one without + early handoff carries no early-handoff state.""" + if not self._speculative: + return None + return self._early_sources.pop(str(req_id), None) + + def bind_block_manager(self, block_manager: Any) -> None: + """Bound the rule by what the allocator can actually hand out: its + usable pages (a checkpoint-enabled pool reserves a null block that + `num_kvcache_blocks` still counts) and its live state slots.""" + if not self._speculative: + return + self._pool_pages = int(block_manager.kv.num_usable_blocks) + self._state_slots = int(block_manager.num_state_slots) + self._state_slots_per_req = int(block_manager.state_slots_per_req) + + def _state_room_before_d(self, seq: Sequence) -> bool: + """The page rule, for per-request state slots: the slots pinned before + D, plus `seq`'s, plus room for another registered stateful request.""" + if self._state_slots is None: + return False + other_waits = any( + s.has_per_req_cache and s.id != seq.id + for s, _ in self._chunked_waiting.values() + ) + requests = len(self._spec_state_pins) + 1 + int(other_waits) + return requests * self._state_slots_per_req <= self._state_slots + + def _may_allocate_before_d(self, seq: Sequence) -> bool: + if not self._speculative: + return False + if seq.has_per_req_cache and not self._state_room_before_d(seq): + return False + need = ( + sum(self._spec_pins.values()) + + self._prompt_pages(seq) + + self._largest_waiting_pages(seq) + ) + return need <= self._pool_pages def _expire_chunked_admission( self, seq: Sequence, deadline: float, now: float @@ -948,6 +1120,10 @@ def process_pd_completions(self, output: KVConnectorOutput) -> KVConnectorOutput output.finished_sending.add(completion.operation_id) output.connector_completions.discard(completion) elif completion.channel == "pd_admission_ready": + # A source allocated before this report no longer waits on D + # (or, on failure, was already retired by the worker). + self._unpin(completion.operation_id) + source = self._forget_early_source(completion.operation_id) pending = self._chunked_waiting.get(completion.operation_id) if pending is not None: seq, _ = pending @@ -956,6 +1132,24 @@ def process_pd_completions(self, output: KVConnectorOutput) -> KVConnectorOutput else: # Retired IDs cannot authorize a new source allocation. seq.status = SequenceStatus.ABORTED + elif source is not None and not completion.succeeded: + # Allocated before D, and the worker has since retired the + # transfer (e.g. it expired D's write request as an orphan + # while this rank was stuck in a long step): D was told it + # failed and no reader will come. Stop the prefill the way + # a waiting request is refused above: mark it aborted. An + # allocated source is never preempted, so it is running, + # and `Scheduler.abort_request` marks a running request + # just so; the step's postprocess finishes it as aborted + # (one still waiting on a load is reclaimed by the next + # pass), and its cancellation retires the send claim + # (`pd_source_safe`). + logger.warning( + "P/D early source %s: transfer retired before D " + "reached P; aborting its prefill", + source.id, + ) + source.status = SequenceStatus.ABORTED output.connector_completions.discard(completion) for req_id, handoff in output.received_handoffs.items(): seq = self._chunked_receiving.pop(req_id, None) @@ -1312,7 +1506,9 @@ def __init__(self, config: Config) -> None: self._completed_prefills_cv = threading.Condition(self._completed_prefills_lock) self._chunked_prefills: dict[ReqId, ChunkedPrefill] = {} self._chunked_local_ids: dict[ReqId, ReqId] = {} - self._retired_chunked_transfers: OrderedDict[ReqId, None] = OrderedDict() + # Retired transfer id -> whether `pd_source_safe` was reported for it + # (`_retire_chunked_transfer`). + self._retired_chunked_transfers: OrderedDict[ReqId, bool] = OrderedDict() self._pending_chunked_requests: list[tuple[dict, float]] = [] self._received_handoffs: dict[ReqId, PrefillHandoff] = {} self._pending_handoffs: dict[ReqId, _PendingHandoff] = {} @@ -1935,7 +2131,28 @@ def start_load_kv(self, metadata: ConnectorMetadata) -> None: if meta.chunked_transfer: with self._completed_prefills_cv: if meta.transfer_id in self._retired_chunked_transfers: - continue # Never resurrect an already released source. + # Never resurrect an already released source. No + # reader can acquire a retired transfer, so the + # scheduler's send claim on this allocation is + # moot. Report it safe when nothing has (retired + # as an orphaned write request or a refused + # admission), and for every new allocation (a + # save without a handoff or cancellation: the + # scheduler took a fresh claim), or the finished + # request keeps its blocks and state slot forever. + # A repeat is dropped by the quorum's tombstones. + allocation = ( + meta.prefill_handoff is None + and not meta.prefill_aborted + ) + if allocation or not ( + self._retired_chunked_transfers[meta.transfer_id] + ): + self._retired_chunked_transfers[meta.transfer_id] = True + self._admission_results.add( + ConnectorCompletion("pd_source_safe", req_id, True) + ) + continue state = self._chunked_prefills.get(meta.transfer_id) if meta.prefill_aborted and ( (state is not None and state.req_id != req_id) @@ -2394,7 +2611,7 @@ def get_finished(self) -> KVConnectorOutput: ConnectorCompletion("pd_source_safe", state.req_id, True) ) state.cancel() # Late holders of the object cannot acquire it. - self._retire_chunked_transfer(transfer_id) + self._retire_chunked_transfer(transfer_id, source_reported=True) del self._chunked_prefills[transfer_id] self._chunked_local_ids.pop(state.req_id, None) self._kv_cache_ready_events.pop(state.req_id, None) @@ -2873,9 +3090,16 @@ def _acquire_chunked_reader( expected_readers=num_consumers_per_producer_rank, ) - def _retire_chunked_transfer(self, transfer_id: TransferId) -> None: - """Remember a terminal ID without retaining blocks; caller holds the lock.""" - self._retired_chunked_transfers[transfer_id] = None + def _retire_chunked_transfer( + self, transfer_id: TransferId, source_reported: bool = False + ) -> None: + """Remember a terminal ID without retaining blocks; caller holds the lock. + + The value records whether `pd_source_safe` was reported for it, so a + later save of a retired transfer can still release its claim.""" + self._retired_chunked_transfers[transfer_id] = bool( + source_reported or self._retired_chunked_transfers.get(transfer_id) + ) if len(self._retired_chunked_transfers) > CHUNKED_RETIRED_TRANSFER_LIMIT: self._retired_chunked_transfers.popitem(last=False) diff --git a/atom/mesh/src/core/placement/backend/atom.rs b/atom/mesh/src/core/placement/backend/atom.rs index 919b291ac9d..c187f927722 100644 --- a/atom/mesh/src/core/placement/backend/atom.rs +++ b/atom/mesh/src/core/placement/backend/atom.rs @@ -1,5 +1,5 @@ -use std::collections::HashMap; -use std::sync::Arc; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, LazyLock}; use serde_json::{json, Value}; use tracing::warn; @@ -9,16 +9,74 @@ use super::super::types::AdapterError; use super::{BackendAdapter, PairCtx}; use crate::core::Worker; +/// Router kill switch for early handoff; anything but "0" (or unset) keeps it on. +pub const EARLY_HANDOFF_ENV: &str = "ATOMESH_ATOM_PD_EARLY_HANDOFF"; + +/// The early-handoff wire contract version this router speaks. +pub const EARLY_HANDOFF_VERSION: u64 = 1; + +static EARLY_HANDOFF_ENABLED: LazyLock = + LazyLock::new(|| early_handoff_enabled_from(std::env::var(EARLY_HANDOFF_ENV).ok().as_deref())); + +pub fn early_handoff_enabled_from(value: Option<&str>) -> bool { + value.is_none_or(|v| v.trim() != "0") +} + +/// What a decode's `/kv_transfer_info` says about receiving a chunked transfer +/// from a prefill that answered early (`chunked_receive`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AtomChunkedReceive { + /// D-local verdict: covers PP=1 and DCP-decode constraints. + pub accepts: bool, + pub tp_size: usize, +} + +impl AtomChunkedReceive { + /// Parse a decode's `/kv_transfer_info`; None for anything but a v1 + /// `chunked_receive` from a `kv_consumer` (that decode stays on the legacy relay). + pub fn from_kv_transfer_info(data: &Value) -> Option { + if data.get("kv_role").and_then(Value::as_str) != Some("kv_consumer") { + return None; + } + let receive = data.get("chunked_receive")?; + if receive.get("version").and_then(Value::as_u64) != Some(EARLY_HANDOFF_VERSION) { + return None; + } + Some(Self { + accepts: receive.get("accepts").and_then(Value::as_bool)?, + tp_size: receive + .get("tp_size") + .and_then(Value::as_u64) + .filter(|tp| *tp >= 1)? as usize, + }) + } +} + +/// Whether a prefill's `/kv_transfer_info` offers a v1 early handoff. +pub fn offers_early_handoff(data: &Value) -> bool { + data.get("early_handoff") + .and_then(|v| v.get("version")) + .and_then(Value::as_u64) + == Some(EARLY_HANDOFF_VERSION) +} + #[derive(Default)] pub struct AtomPrefillInfo { pub tp_sizes: HashMap, pub chunked_transfer: HashMap, + /// Prefill URLs (worker and base) that offer a v1 early handoff. + pub early_handoff: HashSet, + /// Decode URLs (worker and base) with a v1 `chunked_receive`. A decode + /// missing here never gets an early-handoff prefill. + pub decode_receive: HashMap, } impl std::fmt::Debug for AtomPrefillInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("AtomPrefillInfo") .field("prefill_count", &self.tp_sizes.len()) + .field("early_handoff_prefills", &self.early_handoff.len()) + .field("decode_receive_count", &self.decode_receive.len()) .finish() } } @@ -26,11 +84,47 @@ impl std::fmt::Debug for AtomPrefillInfo { #[derive(Debug)] pub struct AtomAdapter { pub prefill_info: Arc, + early_handoff_enabled: bool, } impl AtomAdapter { pub fn new(prefill_info: Arc) -> Self { - Self { prefill_info } + Self { + prefill_info, + early_handoff_enabled: *EARLY_HANDOFF_ENABLED, + } + } + + /// Override the `ATOMESH_ATOM_PD_EARLY_HANDOFF` kill switch. + pub fn with_early_handoff(mut self, enabled: bool) -> Self { + self.early_handoff_enabled = enabled; + self + } + + /// Whether this request's prefill may answer before its prefill ends + /// (early handoff, wire contract v1). Router-chunked prefills keep their + /// own path; a decode that did not say it accepts a chunked receive, or + /// whose TP is not a multiple of the prefill's, keeps the legacy relay. + pub fn early_handoff(&self, body: &Value, pair: &AtomPairCtx) -> bool { + let info = &self.prefill_info; + if !self.early_handoff_enabled + || !Self::can_chunk_request(body, pair.carries_media) + || info.chunked_transfer.contains_key(&pair.prefill_url) + || !info.early_handoff.contains(&pair.prefill_url) + { + return false; + } + let Some(prefill_tp) = info + .tp_sizes + .get(&pair.prefill_url) + .copied() + .filter(|tp| *tp >= 1) + else { + return false; + }; + info.decode_receive + .get(&pair.decode_url) + .is_some_and(|d| d.accepts && d.tp_size % prefill_tp == 0) } /// Requests with media take the response relay: decode needs the prompt @@ -111,6 +205,7 @@ pub struct AtomPairCtx { pub prefill_url: String, pub prefill_dp_size: usize, pub prefill_dp_rank: Option, + pub decode_url: String, pub decode_dp_rank: Option, pub carries_media: bool, } @@ -132,7 +227,7 @@ impl BackendAdapter for AtomAdapter { fn prepare_pair_with_media( &self, prefill: &dyn Worker, - _decode: &dyn Worker, + decode: &dyn Worker, media_count: usize, ) -> Result { Ok(Box::new(AtomPairCtx { @@ -140,7 +235,8 @@ impl BackendAdapter for AtomAdapter { prefill_url: prefill.url().to_string(), prefill_dp_size: prefill.dp_size().unwrap_or(1), prefill_dp_rank: prefill.dp_rank(), - decode_dp_rank: _decode.dp_rank(), + decode_url: decode.url().to_string(), + decode_dp_rank: decode.dp_rank(), carries_media: media_count > 0, })) } @@ -152,6 +248,7 @@ impl BackendAdapter for AtomAdapter { .prefill_info .chunked_transfer .contains_key(&pair.prefill_url); + let early_handoff = self.early_handoff(body, pair); let obj = body.as_object_mut().ok_or(AdapterError::BodyNotObject)?; obj.insert( "kv_transfer_params".to_string(), @@ -163,6 +260,10 @@ impl BackendAdapter for AtomAdapter { if chunked { obj["kv_transfer_params"]["chunked_transfer"] = json!(true); obj["kv_transfer_params"]["transfer_id"] = json!(pair.transfer_id); + } else if early_handoff { + // P may answer with the handoff right after DP dispatch; the + // relay then holds P's load until P reports the prefill's end. + obj["kv_transfer_params"]["early_handoff"] = json!(true); } obj.insert("stream".to_string(), Value::Bool(false)); obj.insert("max_tokens".to_string(), json!(1)); diff --git a/atom/mesh/src/core/placement/tests.rs b/atom/mesh/src/core/placement/tests.rs index 96776129042..2c4eac48bc0 100644 --- a/atom/mesh/src/core/placement/tests.rs +++ b/atom/mesh/src/core/placement/tests.rs @@ -1588,7 +1588,10 @@ mod f_atom_adapter { use serde_json::json; - use super::super::backend::atom::{AtomAdapter, AtomPairCtx, AtomPrefillInfo}; + use super::super::backend::atom::{ + early_handoff_enabled_from, offers_early_handoff, AtomAdapter, AtomChunkedReceive, + AtomPairCtx, AtomPrefillInfo, + }; use super::super::backend::BackendAdapter; use super::super::test_support::*; use super::super::types::AdapterError; @@ -1610,6 +1613,7 @@ mod f_atom_adapter { prefill_url: "http://p:8000".into(), prefill_dp_size: 2, prefill_dp_rank: Some(1), + decode_url: "http://decode:8000".into(), decode_dp_rank: None, carries_media: false, }); @@ -1639,6 +1643,182 @@ mod f_atom_adapter { } } + /// P offers early handoff at `prefill_tp`; D answers `receive` (None: an old, + /// non-ATOM or unreachable D). Returns P's kv_transfer_params and D's body. + fn early_handoff_case( + prefill_tp: usize, + receive: Option, + tweak: impl FnOnce(&mut AtomPrefillInfo), + enabled: bool, + body: serde_json::Value, + media_count: usize, + ) -> (serde_json::Value, serde_json::Value) { + let prefill = make_prefill_http("http://p:8000", "m", None); + let decode = make_decode_http("http://decode:8000", "m"); + let mut info = AtomPrefillInfo::default(); + info.tp_sizes.insert(prefill.url().to_string(), prefill_tp); + info.early_handoff.insert(prefill.url().to_string()); + if let Some(receive) = receive { + info.decode_receive + .insert(decode.url().to_string(), receive); + } + tweak(&mut info); + let adapter = AtomAdapter::new(Arc::new(info)).with_early_handoff(enabled); + let ctx = adapter + .prepare_pair_with_media(prefill.as_ref(), decode.as_ref(), media_count) + .unwrap(); + let (mut p, mut d) = (body.clone(), body); + adapter.inject_prefill_fields(&mut p, &ctx).unwrap(); + adapter.inject_decode_fields(&mut d, &ctx).unwrap(); + (p["kv_transfer_params"].clone(), d) + } + + fn accepts(tp_size: usize) -> Option { + Some(AtomChunkedReceive { + accepts: true, + tp_size, + }) + } + + #[test] + fn atom_early_handoff_decision_matrix() { + let text = || json!({"prompt": [1, 2, 3], "max_tokens": 8}); + let rejecting = Some(AtomChunkedReceive { + accepts: false, + tp_size: 8, + }); + // (name, P tp, D receive, kill switch on, body, media, expected flag) + let cases = [ + ("offer+accept+tp ok", 4, accepts(8), true, text(), 0, true), + ("equal tp", 8, accepts(8), true, text(), 0, true), + ( + "D accepts=false (Kimi-K3 DCP)", + 4, + rejecting, + true, + text(), + 0, + false, + ), + ("D tp not a multiple", 4, accepts(6), true, text(), 0, false), + ("D tp smaller", 8, accepts(4), true, text(), 0, false), + ("D unknown", 4, None, true, text(), 0, false), + ("media", 4, accepts(8), true, text(), 1, false), + ( + "n=2", + 4, + accepts(8), + true, + json!({"prompt": "x", "n": 2}), + 0, + false, + ), + ("kill switch", 4, accepts(8), false, text(), 0, false), + ]; + for (name, p_tp, receive, enabled, body, media, expected) in cases { + let before = body.clone(); + let (p_kv, d) = early_handoff_case(p_tp, receive, |_| {}, enabled, body, media); + let flag = p_kv.get("early_handoff").cloned(); + if expected { + assert_eq!(flag, Some(json!(true)), "{name}: {p_kv}"); + } else { + assert_eq!(flag, None, "{name}: {p_kv}"); + } + assert!(p_kv.get("chunked_transfer").is_none(), "{name}: {p_kv}"); + // The decode body is untouched; the relay fills it from P's answer. + assert_eq!(d, before, "{name}"); + } + // P without the offer, or with an unknown TP: no flag. + let (p_kv, _) = early_handoff_case( + 4, + accepts(8), + |info| info.early_handoff.clear(), + true, + text(), + 0, + ); + assert!(p_kv.get("early_handoff").is_none(), "{p_kv}"); + let (p_kv, _) = + early_handoff_case(4, accepts(8), |info| info.tp_sizes.clear(), true, text(), 0); + assert!(p_kv.get("early_handoff").is_none(), "{p_kv}"); + // A P that also offers router-chunked transfer keeps today's chunked path. + let (p_kv, d) = early_handoff_case( + 4, + accepts(8), + |info| { + info.chunked_transfer + .insert("http://p:8000".into(), json!({"remote_host": "10.0.0.1"})); + }, + true, + text(), + 0, + ); + assert!(p_kv.get("early_handoff").is_none(), "{p_kv}"); + assert_eq!(p_kv["chunked_transfer"], true); + assert_eq!(d["kv_transfer_params"]["chunked_transfer"], true); + } + + #[test] + fn atom_early_handoff_discovery_parsing() { + assert!(early_handoff_enabled_from(None)); + assert!(early_handoff_enabled_from(Some("1"))); + assert!(early_handoff_enabled_from(Some(""))); + assert!(!early_handoff_enabled_from(Some("0"))); + assert!(!early_handoff_enabled_from(Some(" 0 "))); + + assert!(offers_early_handoff( + &json!({"kv_role": "kv_producer", "early_handoff": {"version": 1}}) + )); + for no in [ + json!({"kv_role": "kv_producer"}), + json!({"early_handoff": {"version": 2}}), + json!({"early_handoff": true}), + ] { + assert!(!offers_early_handoff(&no), "{no}"); + } + + let consumer = |receive: serde_json::Value| { + AtomChunkedReceive::from_kv_transfer_info( + &json!({"kv_role": "kv_consumer", "tp_size": 8, "chunked_receive": receive}), + ) + }; + assert_eq!( + consumer(json!({"version": 1, "accepts": true, "tp_size": 8, + "pp_size": 1, "dcp_size": 1, "reason": null})), + accepts(8) + ); + // Kimi-K3 DCP decode: answers, but declines. + assert_eq!( + consumer( + json!({"version": 1, "accepts": false, "tp_size": 8, "pp_size": 1, + "dcp_size": 8, "reason": "DCP decode keeps per-request state"}) + ), + Some(AtomChunkedReceive { + accepts: false, + tp_size: 8 + }) + ); + for bad in [ + json!(null), + json!({"version": 2, "accepts": true, "tp_size": 8}), + json!({"version": 1, "tp_size": 8}), + json!({"version": 1, "accepts": true}), + json!({"version": 1, "accepts": true, "tp_size": 0}), + ] { + assert_eq!(consumer(bad.clone()), None, "{bad}"); + } + // A producer (or an old D without the key) is never a receiver. + assert_eq!( + AtomChunkedReceive::from_kv_transfer_info(&json!({"kv_role": "kv_producer", + "chunked_receive": {"version": 1, "accepts": true, "tp_size": 8}})), + None + ); + assert_eq!( + AtomChunkedReceive::from_kv_transfer_info(&json!({"kv_role": "kv_consumer"})), + None + ); + } + fn atom_info_with(prefill_url: &str, tp_size: usize) -> Arc { let mut tp_sizes = HashMap::new(); tp_sizes.insert(prefill_url.to_string(), tp_size); @@ -1776,6 +1956,7 @@ mod f_atom_adapter { prefill_url: "http://p:8000".to_string(), prefill_dp_size: 4, prefill_dp_rank: Some(2), + decode_url: "http://decode:8000".into(), decode_dp_rank: Some(2), carries_media: false, }); @@ -1831,6 +2012,7 @@ mod f_atom_adapter { prefill_url: "http://unknown:8000".to_string(), prefill_dp_size: 1, prefill_dp_rank: None, + decode_url: "http://decode:8000".into(), decode_dp_rank: None, carries_media: false, }); diff --git a/atom/mesh/src/routers/http_pd_router.rs b/atom/mesh/src/routers/http_pd_router.rs index 5305cd69382..90fea063dd6 100644 --- a/atom/mesh/src/routers/http_pd_router.rs +++ b/atom/mesh/src/routers/http_pd_router.rs @@ -30,7 +30,7 @@ use crate::{ core::{ placement::{ backend::{ - atom::{AtomAdapter, AtomPrefillInfo}, + atom::{offers_early_handoff, AtomAdapter, AtomChunkedReceive, AtomPrefillInfo}, sglang::SglangAdapter, vllm::{VllmAdapter, VllmPrefillInfo}, BackendAdapter, PairCtx, @@ -276,6 +276,17 @@ impl WorkerResponse { result } + /// Read the body line by line (an early-handoff prefill's NDJSON answer). + fn into_lines(self) -> NdjsonLines { + let Self { inner, outcome } = self; + NdjsonLines { + stream: inner.bytes_stream().boxed(), + buf: Vec::new(), + scanned: 0, + outcome, + } + } + fn bytes_stream( self, ) -> impl futures_util::Stream> + Send { @@ -305,6 +316,111 @@ impl WorkerResponse { } } +/// Set by an ATOM prefill that answered before its prefill ended (early +/// handoff): its body is NDJSON, the handoff on line 1 and +/// `{"atom_pd_prefill_done": {"ok": bool, "finish_reason": ...}}` on line 2. +const ATOM_EARLY_HANDOFF_HEADER: &str = "x-atom-pd-early-handoff"; + +/// A worker response body read line by line. Lines have no size limit: an +/// early handoff's first line can carry a long prompt's token ids. +struct NdjsonLines { + stream: futures_util::stream::BoxStream<'static, Result>, + buf: Vec, + /// Bytes of `buf` already searched for a newline. + scanned: usize, + outcome: WorkerOutcome, +} + +impl NdjsonLines { + /// The next line without its '\n'; an unterminated tail is the last line. + async fn next_line(&mut self) -> Result>, reqwest::Error> { + loop { + if let Some(pos) = memchr::memchr(b'\n', &self.buf[self.scanned..]) { + let end = self.scanned + pos; + let rest = self.buf.split_off(end + 1); + let mut line = std::mem::replace(&mut self.buf, rest); + line.pop(); + self.scanned = 0; + return Ok(Some(line)); + } + self.scanned = self.buf.len(); + match self.stream.next().await { + Some(chunk) => self.buf.extend_from_slice(&chunk?), + None if self.buf.is_empty() => return Ok(None), + None => { + self.scanned = 0; + return Ok(Some(std::mem::take(&mut self.buf))); + } + } + } + } + + /// The next line that is not blank. + async fn next_json_line(&mut self) -> Result>, reqwest::Error> { + loop { + match self.next_line().await? { + Some(line) if line.trim_ascii().is_empty() => continue, + other => return Ok(other), + } + } + } + + /// Wait for the prefill's end: Ok once P reports `ok: true` (and its body + /// ends), Err if it reports a failure or its body ends or fails first. + async fn prefill_done(mut self) -> Result<(), String> { + loop { + let line = match self.next_json_line().await { + Ok(Some(line)) => line, + Ok(None) => { + self.outcome.finish(false); + return Err("prefill ended without atom_pd_prefill_done".to_string()); + } + Err(e) => { + self.outcome.finish(false); + return Err(format!("prefill stream failed: {e}")); + } + }; + let done = serde_json::from_slice::(&line) + .ok() + .and_then(|mut v| v.get_mut("atom_pd_prefill_done").map(Value::take)); + let Some(done) = done else { + debug!( + "ignoring an early-handoff prefill line without atom_pd_prefill_done: {}", + String::from_utf8_lossy(&line[..line.len().min(256)]) + ); + continue; + }; + if done.get("ok").and_then(Value::as_bool) != Some(true) { + self.outcome.finish(false); + return Err(format!( + "prefill failed after its early handoff: finish_reason={}", + done.get("finish_reason").unwrap_or(&Value::Null) + )); + } + // P ends its body right after the terminal line. A body that fails + // here is a failed prefill too: the caller answers 502 for it. + while let Some(chunk) = self.stream.next().await { + if let Err(e) = chunk { + self.outcome.finish(false); + return Err(format!( + "prefill stream failed after atom_pd_prefill_done: {e}" + )); + } + } + self.outcome.finish(true); + return Ok(()); + } + } +} + +/// The rest of an early-handoff prefill after its line 1: the wait for line 2 +/// (the prefill's end) and P's load guard, held until that end. Dropping it +/// hangs up on P, which aborts the prefill. +struct PrefillEnd { + done: std::pin::Pin> + Send>>, + guard: WorkerLoadGuard, +} + /// Cancel prefill on dispatch errors; successful streams can detach its drain. struct PrefillTask(Option>); @@ -446,9 +562,10 @@ impl PDRouter { Arc::new(VllmAdapter::new(info)) } BackendType::Atom => { - let info = - Arc::new(Self::fetch_atom_prefill_info(&worker_registry, &client).await?); - let a = Arc::new(AtomAdapter::new(info)); + let mut info = Self::fetch_atom_prefill_info(&worker_registry, &client).await?; + info.decode_receive = + Self::fetch_atom_decode_receive(&worker_registry, &client).await; + let a = Arc::new(AtomAdapter::new(Arc::new(info))); atom_adapter = Some(a.clone()); a } @@ -731,6 +848,7 @@ impl PDRouter { let mut tp_sizes = HashMap::new(); let mut chunked_transfer = HashMap::new(); + let mut early_handoff = HashSet::new(); let mut queried_base_urls = HashSet::new(); for worker in &prefill_workers { let worker_url = worker.url().to_string(); @@ -739,6 +857,9 @@ impl PDRouter { if let Some(tp) = tp_sizes.get(&base_url).copied() { tp_sizes.insert(worker_url.clone(), tp); } + if early_handoff.contains(&base_url) { + early_handoff.insert(worker_url.clone()); + } if let Some(meta) = chunked_transfer.get(&base_url).cloned() { chunked_transfer.insert(worker_url, meta); } @@ -772,20 +893,98 @@ impl PDRouter { base_url, kv_role )); } - info!("ATOM prefill {} tp_size={}", base_url, tp); + let offers_early = offers_early_handoff(&data); + info!( + "ATOM prefill {} tp_size={} early_handoff={}", + base_url, tp, offers_early + ); if let Some(meta) = data.get("chunked_transfer").filter(|v| v.is_object()) { chunked_transfer.insert(base_url.clone(), meta.clone()); chunked_transfer.insert(worker_url.clone(), meta.clone()); } + if offers_early { + early_handoff.insert(base_url.clone()); + early_handoff.insert(worker_url.clone()); + } tp_sizes.insert(base_url, tp); tp_sizes.insert(worker_url, tp); } Ok(AtomPrefillInfo { tp_sizes, chunked_transfer, + early_handoff, + ..Default::default() }) } + /// Query each ATOM decode's `chunked_receive`. Never fatal: a decode + /// that cannot be queried, or does not answer one, keeps the legacy relay. + async fn fetch_atom_decode_receive( + worker_registry: &WorkerRegistry, + client: &Client, + ) -> HashMap { + let mut receive = HashMap::new(); + let mut queried = HashMap::>::new(); + for worker in worker_registry.get_decode_workers() { + let worker_url = worker.url().to_string(); + let base_url = worker.base_url().trim_end_matches('/').to_string(); + let found = match queried.get(&base_url) { + Some(found) => found.clone(), + None => { + let found = Self::query_atom_decode_receive(client, &base_url).await; + queried.insert(base_url.clone(), found.clone()); + found + } + }; + if let Some(found) = found { + receive.insert(base_url, found.clone()); + receive.insert(worker_url, found); + } + } + receive + } + + async fn query_atom_decode_receive( + client: &Client, + base_url: &str, + ) -> Option { + let info_url = format!("{}/kv_transfer_info", base_url); + let data: Value = match client + .get(&info_url) + .timeout(Duration::from_secs(10)) + .send() + .await + .and_then(|resp| resp.error_for_status()) + { + Ok(resp) => match resp.json().await { + Ok(data) => data, + Err(e) => { + warn!("ATOM decode {info_url}: unparsable response ({e}); early handoff off for it"); + return None; + } + }, + Err(e) => { + warn!("ATOM decode {info_url} failed ({e}); early handoff off for it"); + return None; + } + }; + let found = AtomChunkedReceive::from_kv_transfer_info(&data); + match &found { + Some(r) => info!( + "ATOM decode {} chunked_receive accepts={} tp_size={} reason={}", + base_url, + r.accepts, + r.tp_size, + data["chunked_receive"]["reason"] + ), + None => warn!( + "ATOM decode {} has no usable v1 chunked_receive (kv_role={}); early handoff off for it", + base_url, data["kv_role"] + ), + } + found + } + fn handle_serialization_error(error: impl std::fmt::Display) -> Response { error!("Failed to serialize request error={}", error); error::internal_error("serialization_failed", "Failed to serialize request") @@ -1190,7 +1389,7 @@ impl PDRouter { .clone() .unwrap_or_else(|| "unknown".to_string()); - let kv_params = match self + let (kv_params, prefill_end) = match self .atom_prefill_kv( prefill_post, &prefill, @@ -1201,7 +1400,7 @@ impl PDRouter { ) .await { - Ok(kv) => kv, + Ok(answer) => answer, Err(response) => return response, }; @@ -1230,7 +1429,23 @@ impl PDRouter { Ok(req) => req, Err(resp) => return resp, }; - let decode_result = self.send_worker(decode_post, decode.clone(), headers).await; + let decode_send = self.send_worker(decode_post, decode.clone(), headers); + let decode_result = match prefill_end { + None => decode_send.await, + // A P still prefilling ends with D's request if D did not answer + // with success (the unused end is dropped here). + Some(end) => match Self::send_decode_during_early_prefill( + decode_send, + end, + prefill.url(), + &correlation_for_log, + ) + .await + { + Ok((result, _)) => result, + Err(response) => return response, + }, + }; events::RequestReceivedEvent {}.emit(); let res = match decode_result { @@ -1258,6 +1473,10 @@ impl PDRouter { /// answered, and the params are enriched for `ctx` with P's prompt-id echo /// carried over. Every failure is logged with `request_id`. Shared by the /// serial relay and the concurrent (late-kv) dispatch. + /// + /// An NDJSON early handoff (P answered at DP dispatch and is still + /// prefilling) also returns its `PrefillEnd`: P's load stays reserved + /// until P reports the prefill's end on line 2. async fn atom_prefill_kv( &self, prefill_post: reqwest::RequestBuilder, @@ -1266,7 +1485,7 @@ impl PDRouter { headers: Option<&HeaderMap>, ctx: &PairCtx, request_id: &str, - ) -> Result { + ) -> Result<(Value, Option), Response> { let prefill_resp = self .send_worker(prefill_post, prefill.clone(), headers) .await @@ -1305,21 +1524,56 @@ impl PDRouter { )); } - let prefill_body: Value = prefill_resp.json().await.map_err(|e| { - error!( - "ATOM prefill {} request_id={} response parse failed: {}", - prefill.url(), - request_id, - e - ); - error::bad_gateway( - "prefill_parse_error", - format!("Prefill response parse error: {}", e), - ) - })?; - - // P has completed its work; D's output stream must not keep P loaded. - drop(prefill_guard); + let (prefill_body, prefill_end) = if Self::is_ndjson_early_handoff(prefill_resp.headers()) { + let mut lines = prefill_resp.into_lines(); + let parsed = match lines.next_json_line().await { + Ok(Some(line)) => serde_json::from_slice::(&line).map_err(|e| e.to_string()), + Ok(None) => Err("prefill ended before its handoff".to_string()), + Err(e) => Err(e.to_string()), + }; + match parsed { + Ok(body) => { + let end = PrefillEnd { + done: Box::pin(lines.prefill_done()), + guard: prefill_guard, + }; + (body, Some(end)) + } + Err(e) => { + // A malformed line 1, or a body that ended or failed before + // the handoff, is P's failure (as on every `prefill_done` + // path), not a cancellation: dropping the 200 response + // unfinished would record nothing in P's circuit breaker. + lines.outcome.finish(false); + error!( + "ATOM prefill {} request_id={} early handoff parse failed: {}", + prefill.url(), + request_id, + e + ); + return Err(error::bad_gateway( + "prefill_parse_error", + format!("Prefill response parse error: {}", e), + )); + } + } + } else { + let prefill_body: Value = prefill_resp.json().await.map_err(|e| { + error!( + "ATOM prefill {} request_id={} response parse failed: {}", + prefill.url(), + request_id, + e + ); + error::bad_gateway( + "prefill_parse_error", + format!("Prefill response parse error: {}", e), + ) + })?; + // P has completed its work; D's output stream must not keep P loaded. + drop(prefill_guard); + (prefill_body, None) + }; // ATOM's prefill answers without a handoff as `"kv_transfer_params": null`. let mut kv_params = match prefill_body.get("kv_transfer_params").cloned() { @@ -1361,7 +1615,7 @@ impl PDRouter { "ATOM PD request_id={} carried {} prompt token ids to decode", request_id, carried_ids ); - Ok(kv_params) + Ok((kv_params, prefill_end)) } /// Relay mode with D dispatched concurrently (`--atom-pd-concurrent`). @@ -1454,8 +1708,11 @@ impl PDRouter { let decode_policy = self.dispatch(&decode, headers); let flow_request_id = request_id.clone(); + let prefill_url = prefill.url().to_string(); let mut prefill_flow = Box::pin(async move { - let line = match self + // An early-handoff P answers at DP dispatch, so line 2 reaches D + // while P still prefills; its `PrefillEnd` comes back with it. + let answer = match self .atom_prefill_kv( prefill_post, &prefill, @@ -1466,12 +1723,14 @@ impl PDRouter { ) .await { - Ok(kv) => late_kv_line(kv).map_err(Self::handle_serialization_error), + Ok((kv, end)) => late_kv_line(kv) + .map(|line| (line, end)) + .map_err(Self::handle_serialization_error), Err(response) => Err(response), }; // D may already have answered (an error) and closed its body. - match &line { - Ok(line) => { + match &answer { + Ok((line, _)) => { let _ = tx.try_send(Ok(line.clone())); } // Abort D's body instead of ending it: D sees a disconnect @@ -1480,18 +1739,31 @@ impl PDRouter { let _ = tx.try_send(Err(std::io::Error::other("prefill failed"))); } } - line + answer }); let decode_send = Self::send(late_post, decode.clone(), decode_policy.clone()); let mut decode_send = std::pin::pin!(decode_send); // A P failure ends the request at once; D's body is aborted above. - let (kv_line, decode_result) = tokio::select! { + // An early-handoff P's end is raced against D's answer, as in the + // serial relay; it stays pending only if D did not answer with success. + let (kv_line, prefill_end, decode_result) = tokio::select! { p = &mut prefill_flow => match p { Err(response) => return response, - Ok(line) => (Some(line), decode_send.await), + Ok((line, None)) => (Some(line), None, decode_send.await), + Ok((line, Some(end))) => match Self::send_decode_during_early_prefill( + decode_send.as_mut(), + end, + &prefill_url, + &request_id, + ) + .await + { + Ok((result, end)) => (Some(line), end, result), + Err(response) => return response, + }, }, - d = &mut decode_send => (None, d), + d = &mut decode_send => (None, None, d), }; let res = match decode_result { Ok(r) => r, @@ -1512,8 +1784,9 @@ impl PDRouter { if res.status() != StatusCode::NOT_FOUND { // Only the fallback needs line 1 and line 2. If D answered before // P (an error, as D waits for line 2), cancel P: dropping its flow - // releases P's load without counting a failure. - drop((head, kv_line, prefill_flow)); + // (or an early-handoff P's pending end) releases P's load without + // counting a failure. + drop((head, kv_line, prefill_flow, prefill_end)); events::RequestReceivedEvent {}.emit(); return self .finish_atom_decode_response(res, context, decode, decode_guard) @@ -1529,10 +1802,10 @@ impl PDRouter { ATOM_LATE_KV_PATH ); } - let kv_line = match kv_line { - Some(line) => line, + let (kv_line, prefill_end) = match kv_line { + Some(line) => (line, prefill_end), None => match prefill_flow.await { - Ok(line) => line, + Ok(answer) => answer, // Dropping the 404 completes D's dispatch as a cancellation. Err(response) => return response, }, @@ -1549,7 +1822,24 @@ impl PDRouter { .headers(decode_headers) .header(CONTENT_TYPE, "application/json") .body(body); - let res = match Self::send(relay_post, decode.clone(), decode_policy).await { + let relay_send = Self::send(relay_post, decode.clone(), decode_policy); + let relay_result = match prefill_end { + None => relay_send.await, + Some(end) => { + match Self::send_decode_during_early_prefill( + relay_send, + end, + &prefill_url, + &request_id, + ) + .await + { + Ok((result, _)) => result, + Err(response) => return response, + } + } + }; + let res = match relay_result { Ok(r) => r, Err(e) => { error!( @@ -1569,6 +1859,75 @@ impl PDRouter { .await } + fn is_ndjson_early_handoff(headers: &HeaderMap) -> bool { + headers + .get(ATOM_EARLY_HANDOFF_HEADER) + .is_some_and(|v| v.as_bytes() == b"1") + } + + /// Send D while an early-handoff P is still prefilling. P's load guard is + /// released at P's line 2 (the prefill's end). Before D's headers, a P + /// failure answers 502 `prefill_error` and drops D's request. After D's + /// headers, a success leaves P's end to a detached watcher that releases + /// the guard and logs a failure (D then fails on its own). If D did not + /// answer with success, P's still-pending end is handed back: the caller + /// drops it (P aborts its prefill) or, on the late-kv 404 fallback, keeps + /// it for the relay's resend. + async fn send_decode_during_early_prefill( + decode_send: impl std::future::Future>, + end: PrefillEnd, + prefill_url: &str, + correlation: &str, + ) -> Result<(Result, Option), Response> { + tokio::pin!(decode_send); + let PrefillEnd { done, guard } = end; + let mut prefill_end = Some(done); + let mut guard = Some(guard); + let decode_result = loop { + tokio::select! { + done = async { prefill_end.as_mut().unwrap().await }, if prefill_end.is_some() => { + // P's prefill ended: release its load now, not at D's answer. + prefill_end = None; + guard = None; + if let Err(e) = done { + error!( + "ATOM prefill {} request_id={} {} before decode answered", + prefill_url, correlation, e + ); + return Err(error::bad_gateway("prefill_error", e)); + } + } + result = &mut decode_send => break result, + } + }; + // P already ended (its load was released above). + let (Some(prefill_end), Some(guard)) = (prefill_end, guard) else { + return Ok((decode_result, None)); + }; + let decode_ok = decode_result + .as_ref() + .is_ok_and(|res| res.status().is_success()); + if !decode_ok { + let end = PrefillEnd { + done: prefill_end, + guard, + }; + return Ok((decode_result, Some(end))); + } + let prefill_url = prefill_url.to_string(); + let correlation = correlation.to_string(); + tokio::spawn(crate::observability::route_trace::carry(async move { + if let Err(e) = prefill_end.await { + warn!( + "ATOM prefill {} request_id={} {} after decode answered", + prefill_url, correlation, e + ); + } + drop(guard); + })); + Ok((decode_result, None)) + } + async fn dispatch_atom_chunked_internal( &self, headers: Option<&HeaderMap>, @@ -3382,6 +3741,301 @@ mod tests { assert_eq!(sent["kv_transfer_params"]["transfer_id"], "xfer-1"); } + /// An early-handoff P mock: answers NDJSON at once with the handoff on + /// line 1, and reports the prefill's end (`ok`) on line 2 after `done_ms`. + async fn early_prefill_mock(state: Shared, done_ms: u64, ok: bool) -> String { + serve(axum::Router::new().route( + "/v1/chat/completions", + axum::routing::post(move |axum::Json(body): axum::Json| { + let state = state.clone(); + async move { + state.lock().unwrap().prefill_bodies.push(body); + let (tx, rx) = + tokio::sync::mpsc::channel::>(2); + let handoff = json!({"kv_transfer_params": { + "do_remote_prefill": true, "do_remote_decode": false, + "chunked_transfer": true, "transfer_id": "xfer-1", "dp_rank": 3}}); + let _ = tx.try_send(Ok(bytes::Bytes::from(format!("{handoff}\n")))); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(done_ms)).await; + state.lock().unwrap().prefill_replied = Some(Instant::now()); + let done = json!({"atom_pd_prefill_done": {"ok": ok}}); + let _ = tx.send(Ok(bytes::Bytes::from(format!("{done}\n")))).await; + }); + let stream = tokio_stream::wrappers::ReceiverStream::new(rx); + Response::builder() + .header(CONTENT_TYPE, "application/x-ndjson") + .header(ATOM_EARLY_HANDOFF_HEADER, "1") + .body(Body::from_stream(stream)) + .unwrap() + } + }), + )) + .await + } + + #[tokio::test] + async fn late_kv_with_early_handoff_holds_prefill_load_until_line_two() { + let state: Shared = Default::default(); + let p = early_prefill_mock(state.clone(), 400, true).await; + let d = decode_mock(state.clone(), LateRoute::Serve).await; + let router = atom_test_router(&p, true); + let body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}], + "prompt_token_ids": [1, 2]}); + let r = run_atom_pd(&router, &p, &d, body, LateKvRun::default()).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.out); + // D got P's line 1 as its kv line and answered while P still prefills. + let kv = &r.out["late"]["kv_transfer_params"]; + assert_eq!(kv["transfer_id"], "xfer-1"); + assert_eq!(kv["remote_dp_rank"], 3); + assert_eq!(kv["chunked_transfer"], true); + assert!(state.lock().unwrap().prefill_replied.is_none()); + // P stays charged until its line 2. + assert_eq!(r.prefill.load(), 1); + assert_eq!(r.decode.load(), 0); + tokio::time::sleep(Duration::from_millis(800)).await; + assert!(state.lock().unwrap().prefill_replied.is_some()); + r.assert_released(); + assert_eq!(r.prefill.circuit_breaker().total_failures(), 0); + } + + #[tokio::test] + async fn late_kv_fallback_keeps_an_early_prefill_running() { + let state: Shared = Default::default(); + let p = early_prefill_mock(state.clone(), 400, true).await; + let d = decode_mock(state.clone(), LateRoute::Missing).await; + let router = atom_test_router(&p, true); + let body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}], + "prompt_token_ids": [4, 5]}); + let r = run_atom_pd(&router, &p, &d, body, LateKvRun::default()).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.out); + { + let st = state.lock().unwrap(); + // D's 404 did not hang up on P: the relay resent with P's handoff. + assert_eq!(st.plain_hits, 1); + let sent = &st.plain_bodies[0]["kv_transfer_params"]; + assert_eq!(sent["transfer_id"], "xfer-1"); + assert_eq!(sent["remote_dp_rank"], 3); + assert!(st.prefill_replied.is_none()); + } + assert_eq!(r.prefill.load(), 1); + tokio::time::sleep(Duration::from_millis(800)).await; + r.assert_released(); + assert_eq!(r.prefill.circuit_breaker().total_failures(), 0); + assert_eq!(r.decode.circuit_breaker().total_failures(), 0); + } + + #[tokio::test] + async fn early_handoff_line_one_failure_is_recorded_as_a_prefill_failure() { + // P answers 200 with the early-handoff header, then line 1 is malformed, + // the body ends before any line, or the body fails: a 502, and one + // failure (not a cancellation) in P's circuit breaker. + for case in ["malformed", "eof", "cut"] { + let p = serve(axum::Router::new().route( + "/v1/chat/completions", + axum::routing::post(move || async move { + let (tx, rx) = + tokio::sync::mpsc::channel::>(2); + match case { + "malformed" => { + let _ = tx.try_send(Ok(bytes::Bytes::from_static(b"not json\n"))); + } + "cut" => { + let _ = tx.try_send(Err(std::io::Error::other("cut"))); + } + _ => {} + } + drop(tx); + let stream = tokio_stream::wrappers::ReceiverStream::new(rx); + Response::builder() + .header(CONTENT_TYPE, "application/x-ndjson") + .header(ATOM_EARLY_HANDOFF_HEADER, "1") + .body(Body::from_stream(stream)) + .unwrap() + }), + )) + .await; + let router = atom_test_router(&p, false); + let prefill = early_test_worker( + &p, + WorkerType::Prefill { + bootstrap_port: None, + }, + ); + let decode = early_test_worker("http://decode.invalid", WorkerType::Decode); + let ctx = router + .adapter + .prepare_pair(prefill.as_ref(), decode.as_ref()) + .unwrap(); + let post = router + .client + .post(format!("{p}/v1/chat/completions")) + .json(&json!({})); + let guard = WorkerLoadGuard::new(prefill.clone(), None); + let result = router + .atom_prefill_kv(post, &prefill, guard, None, &ctx, "req-1") + .await; + let response = match result { + Ok(_) => panic!("{case}: a broken line 1 must fail the prefill"), + Err(response) => response, + }; + assert_eq!(response.status(), StatusCode::BAD_GATEWAY, "{case}"); + assert_eq!(prefill.circuit_breaker().total_failures(), 1, "{case}"); + assert_eq!(prefill.circuit_breaker().total_successes(), 0, "{case}"); + assert_eq!(prefill.load(), 0, "{case}"); + } + } + + /// An early-handoff P whose body reports `ok` on line 2 after `done_ms`, + /// then (`cut`) fails instead of ending cleanly. + async fn early_prefill_body_mock(done_ms: u64, cut: bool) -> String { + serve(axum::Router::new().route( + "/v1/chat/completions", + axum::routing::post(move || async move { + let (tx, rx) = + tokio::sync::mpsc::channel::>(4); + let _ = tx.try_send(Ok(bytes::Bytes::from_static(b"{\"handoff\":1}\n"))); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(done_ms)).await; + let done = json!({"atom_pd_prefill_done": {"ok": true}}); + let _ = tx.send(Ok(bytes::Bytes::from(format!("{done}\n")))).await; + if cut { + tokio::time::sleep(Duration::from_millis(20)).await; + let _ = tx.send(Err(std::io::Error::other("cut"))).await; + } + }); + let stream = tokio_stream::wrappers::ReceiverStream::new(rx); + Response::builder() + .header(CONTENT_TYPE, "application/x-ndjson") + .body(Body::from_stream(stream)) + .unwrap() + }), + )) + .await + } + + /// A D that sends its headers only after `delay_ms`. + async fn slow_decode_mock(delay_ms: u64) -> String { + serve(axum::Router::new().route( + "/v1/chat/completions", + axum::routing::post(move || async move { + tokio::time::sleep(Duration::from_millis(delay_ms)).await; + axum::Json(json!({"decoded": true})) + }), + )) + .await + } + + fn early_test_worker(url: &str, worker_type: WorkerType) -> Arc { + Arc::new( + BasicWorkerBuilder::new(url) + .worker_type(worker_type) + .build(), + ) + } + + /// Posts to the early-handoff P mock and reads its line 1: what is left + /// is the wait for line 2 and P's load guard. + async fn early_prefill_end(p_url: &str, prefill: &Arc) -> PrefillEnd { + let policy: Arc = + Arc::new(CompletionPolicy::default()); + let request = Client::new() + .post(format!("{p_url}/v1/chat/completions")) + .json(&json!({})); + let guard = WorkerLoadGuard::new(prefill.clone(), None); + let response = PDRouter::send(request, prefill.clone(), policy) + .await + .unwrap(); + let mut lines = response.into_lines(); + assert!(lines.next_json_line().await.unwrap().is_some()); + PrefillEnd { + done: Box::pin(lines.prefill_done()), + guard, + } + } + + fn slow_decode_send( + d_url: &str, + decode: &Arc, + ) -> impl std::future::Future> { + let policy: Arc = + Arc::new(CompletionPolicy::default()); + let request = Client::new() + .post(format!("{d_url}/v1/chat/completions")) + .json(&json!({})); + PDRouter::send(request, decode.clone(), policy) + } + + #[tokio::test] + async fn early_prefill_body_failing_after_its_done_line_is_a_prefill_error() { + // P reports ok, then its body fails, all before D's headers: that is + // a failed prefill (502 prefill_error), not a success to wait D out. + let p_url = early_prefill_body_mock(30, true).await; + let d_url = slow_decode_mock(1500).await; + let prefill = early_test_worker( + &p_url, + WorkerType::Prefill { + bootstrap_port: None, + }, + ); + let decode = early_test_worker(&d_url, WorkerType::Decode); + let end = early_prefill_end(&p_url, &prefill).await; + let started = Instant::now(); + let result = PDRouter::send_decode_during_early_prefill( + slow_decode_send(&d_url, &decode), + end, + &p_url, + "rid", + ) + .await; + let Err(response) = result else { + panic!("a P body that fails after its done line must answer 502"); + }; + assert_eq!(response.status(), StatusCode::BAD_GATEWAY); + assert!(started.elapsed() < Duration::from_millis(1000)); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert!(String::from_utf8_lossy(&bytes).contains("prefill_error")); + assert_eq!(prefill.load(), 0); + assert_eq!(prefill.circuit_breaker().total_failures(), 1); + } + + #[tokio::test] + async fn early_prefill_success_releases_its_load_before_decode_answers() { + // P completes successfully long before D's headers: P's load guard + // goes at P's end, not at D's answer. + let p_url = early_prefill_body_mock(30, false).await; + let d_url = slow_decode_mock(600).await; + let prefill = early_test_worker( + &p_url, + WorkerType::Prefill { + bootstrap_port: None, + }, + ); + let decode = early_test_worker(&d_url, WorkerType::Decode); + let end = early_prefill_end(&p_url, &prefill).await; + assert_eq!(prefill.load(), 1); + let (result, load_while_d_runs) = tokio::join!( + PDRouter::send_decode_during_early_prefill( + slow_decode_send(&d_url, &decode), + end, + &p_url, + "rid", + ), + async { + tokio::time::sleep(Duration::from_millis(300)).await; + prefill.load() + } + ); + assert_eq!(load_while_d_runs, 0, "P stayed charged until D answered"); + let Ok((Ok(response), None)) = result else { + panic!("D's answer must come back with P's end already consumed"); + }; + assert!(response.status().is_success()); + assert_eq!(prefill.circuit_breaker().total_failures(), 0); + } + #[tokio::test] async fn late_kv_forwards_headers_and_worker_key() { for late in [LateRoute::Serve, LateRoute::Missing] { diff --git a/atom/mesh/tests/routing/http_pd_load_tests.rs b/atom/mesh/tests/routing/http_pd_load_tests.rs index 07d6f69fd0a..25dbae9cc21 100644 --- a/atom/mesh/tests/routing/http_pd_load_tests.rs +++ b/atom/mesh/tests/routing/http_pd_load_tests.rs @@ -29,6 +29,7 @@ struct GatedServer { worker: Arc, entered: Arc, captured: mpsc::UnboundedReceiver, + bodies: mpsc::UnboundedReceiver, response: Option>, task: JoinHandle<()>, } @@ -46,14 +47,17 @@ impl GatedServer { let (tx, rx) = oneshot::channel::(); let response = Arc::new(Mutex::new(Some(rx))); let (capture, captured) = mpsc::unbounded_channel(); + let (capture_body, bodies) = mpsc::unbounded_channel(); let app = Router::new().route( "/v1/chat/completions", - post(move |headers: HeaderMap| { + post(move |headers: HeaderMap, body: Bytes| { let notify = notify.clone(); let response = response.clone(); let capture = capture.clone(); + let capture_body = capture_body.clone(); async move { capture.send(headers).unwrap(); + capture_body.send(body).unwrap(); let rx = response.lock().await.take().unwrap(); notify.notify_one(); rx.await @@ -70,6 +74,7 @@ impl GatedServer { worker: Arc::new(worker.build()), entered, captured, + bodies, response: Some(tx), task, } @@ -1089,3 +1094,321 @@ async fn atom_chunked_decode_admission_rejection_cancels_pending_prefill() { assert_eq!(d.worker.load(), 0); } } + +/// An early-handoff prefill answer (wire contract v1): NDJSON whose lines the +/// test writes through the returned sender. +fn early_prefill_response() -> ( + Response, + mpsc::UnboundedSender>, +) { + let (tx, rx) = mpsc::unbounded_channel(); + let response = Response::builder() + .status(StatusCode::OK) + .header(CONTENT_TYPE, "application/x-ndjson") + .header("x-atom-pd-early-handoff", "1") + .body(Body::from_stream(UnboundedReceiverStream::new(rx))) + .unwrap(); + (response, tx) +} + +/// Line 1, split over two chunks so the relay has to join them. +fn send_early_handoff_line(tx: &mpsc::UnboundedSender>) { + let line = json!({ + "id": "cmpl-p", + "prompt_token_ids": [5, 6, 7], + "kv_transfer_params": { + "do_remote_prefill": true, "do_remote_decode": false, + "chunked_transfer": true, "transfer_id": "xfer-early", "dp_rank": 3, + "remote_host": "10.0.0.1", "remote_handshake_port": 6301, + }, + }) + .to_string() + + "\n"; + let (head, tail) = line.split_at(line.len() / 2); + tx.send(Ok(Bytes::from(head.to_string()))).unwrap(); + tx.send(Ok(Bytes::from(tail.to_string()))).unwrap(); +} + +fn prefill_done_line(ok: bool) -> Bytes { + let reason = if ok { json!("length") } else { json!("abort") }; + Bytes::from( + json!({"atom_pd_prefill_done": {"ok": ok, "finish_reason": reason}}).to_string() + "\n", + ) +} + +async fn decode_request_body(d: &mut GatedServer) -> Value { + let body = timeout(Duration::from_secs(5), d.bodies.recv()) + .await + .unwrap() + .unwrap(); + serde_json::from_slice(&body).unwrap() +} + +#[tokio::test] +async fn atom_early_handoff_starts_decode_and_holds_prefill_load_until_done() { + for streaming in [false, true] { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, streaming); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + send_early_handoff_line(&p_tx); + + // D gets its request from line 1, before P reports the prefill's end. + d.wait_entered().await; + let decode_body = decode_request_body(&mut d).await; + let kv = &decode_body["kv_transfer_params"]; + assert_eq!(kv["remote_dp_rank"], 3, "{decode_body}"); + assert_eq!(kv["remote_dp_size"], 1, "{decode_body}"); + assert_eq!(kv["remote_tp_size"], 1, "{decode_body}"); + assert_eq!(kv["transfer_id"], "xfer-early", "{decode_body}"); + assert_eq!(kv["chunked_transfer"], true, "{decode_body}"); + assert_eq!(kv["remote_host"], "10.0.0.1", "{decode_body}"); + assert_eq!(kv["prompt_token_ids"], json!([5, 6, 7]), "{decode_body}"); + + // P is still prefilling: its load stays held while D waits. + sleep(Duration::from_millis(150)).await; + assert_eq!(p.worker.load(), 1, "P load must be held until line 2"); + assert_eq!(p.worker.prefill_tokens(), 7, "P still holds the prompt"); + assert_eq!(d.worker.load(), 1); + assert!(!task.is_finished()); + + p_tx.send(Ok(prefill_done_line(true))).unwrap(); + drop(p_tx); + wait_load(&p.worker, 0).await; + assert_eq!(p.worker.prefill_tokens(), 0); + assert_eq!(d.worker.load(), 1); + + d.respond(axum::Json(json!({"choices": ["decoded"]})).into_response()); + let response = result(task).await; + assert_eq!(response.status(), StatusCode::OK, "streaming={streaming}"); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + json!({"choices": ["decoded"]}) + ); + assert_eq!((p.worker.load(), d.worker.load()), (0, 0)); + } +} + +/// D's headers can come before P's line 2 (a streaming D answers at once). +/// The response goes out; P stays charged until its line 2, whatever it says. +#[tokio::test] +async fn atom_early_handoff_holds_prefill_past_decode_headers_until_line_two() { + for ok in [true, false] { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, true); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + send_early_handoff_line(&p_tx); + d.wait_entered().await; + let (response, d_tx) = stream_response(StatusCode::OK); + d.respond(response); + let response = result(task).await; + assert_eq!(response.status(), StatusCode::OK); + sleep(Duration::from_millis(150)).await; + assert_eq!(p.worker.load(), 1, "ok={ok}: P load held until line 2"); + assert_eq!(p.worker.prefill_tokens(), 7); + // A failure reported after D's headers is only logged; D ends on its own. + p_tx.send(Ok(prefill_done_line(ok))).unwrap(); + drop(p_tx); + wait_load(&p.worker, 0).await; + assert_eq!(p.worker.prefill_tokens(), 0); + assert_eq!(d.worker.load(), 1); + d_tx.send(Ok(Bytes::from_static(b"data: [DONE]\n\n"))) + .unwrap(); + drop(d_tx); + response.into_body().collect().await.unwrap(); + assert_eq!((p.worker.load(), d.worker.load()), (0, 0)); + } +} + +/// If the client leaves after D's headers, P's load still ends with P's line 2. +#[tokio::test] +async fn atom_early_handoff_client_disconnect_keeps_prefill_charged_until_line_two() { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, true); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + send_early_handoff_line(&p_tx); + d.wait_entered().await; + let (response, _d_tx) = stream_response(StatusCode::OK); + d.respond(response); + drop(result(task).await); + assert_eq!(d.worker.load(), 0); + assert_eq!(p.worker.load(), 1); + p_tx.send(Ok(prefill_done_line(true))).unwrap(); + drop(p_tx); + wait_load(&p.worker, 0).await; +} + +#[derive(Clone, Copy, Debug)] +enum EarlyPrefillFailure { + NotOk, + EofWithoutDone, + StreamError, +} + +#[tokio::test] +async fn atom_early_handoff_prefill_failure_cancels_decode() { + for failure in [ + EarlyPrefillFailure::NotOk, + EarlyPrefillFailure::EofWithoutDone, + EarlyPrefillFailure::StreamError, + ] { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, true); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + send_early_handoff_line(&p_tx); + d.wait_entered().await; + match failure { + EarlyPrefillFailure::NotOk => p_tx.send(Ok(prefill_done_line(false))).unwrap(), + EarlyPrefillFailure::EofWithoutDone => {} + EarlyPrefillFailure::StreamError => p_tx + .send(Err(std::io::Error::other("prefill died"))) + .unwrap(), + } + drop(p_tx); + let response = result(task).await; + assert_eq!(response.status(), StatusCode::BAD_GATEWAY, "{failure:?}"); + assert_eq!(response.headers()["x-mesh-error-code"], "prefill_error"); + // D's request was dropped before it answered. + timeout( + Duration::from_secs(5), + d.response.as_mut().unwrap().closed(), + ) + .await + .unwrap_or_else(|_| panic!("{failure:?}: decode request was not cancelled")); + assert_eq!((p.worker.load(), d.worker.load()), (0, 0), "{failure:?}"); + assert_eq!(p.worker.prefill_tokens(), 0); + } +} + +#[tokio::test] +async fn atom_early_handoff_decode_error_cancels_running_prefill() { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, false); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + send_early_handoff_line(&p_tx); + d.wait_entered().await; + d.respond((StatusCode::BAD_REQUEST, "cannot receive a chunked transfer").into_response()); + let response = result(task).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + // P's body is dropped: the relay stops reading it and frees P's load. + assert_eq!((p.worker.load(), d.worker.load()), (0, 0)); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + assert!(String::from_utf8_lossy(&bytes).contains("cannot receive a chunked transfer")); + timeout(Duration::from_secs(5), p_tx.closed()) + .await + .unwrap(); +} + +#[tokio::test] +async fn atom_early_handoff_unparsable_first_line_skips_decode() { + let (mut p, d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, false); + p.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p.respond(response); + p_tx.send(Ok(Bytes::from_static(b"not json\n"))).unwrap(); + let response = result(task).await; + assert_eq!(response.status(), StatusCode::BAD_GATEWAY); + assert_eq!( + response.headers()["x-mesh-error-code"], + "prefill_parse_error" + ); + assert_eq!((p.worker.load(), d.worker.load()), (0, 0)); + assert!(timeout(Duration::from_millis(20), d.entered.notified()) + .await + .is_err()); +} + +/// A P asked for an early handoff may still answer the legacy way (an old P, +/// or one that declined this request): the relay behaves as today. +#[tokio::test] +async fn atom_legacy_prefill_answer_without_early_header_keeps_relay() { + let (mut p, mut d) = servers().await; + let task = dispatch(DispatchKind::Atom, &p, &d, false); + p.wait_entered().await; + p.respond( + axum::Json(json!({"prompt_token_ids": [9, 9], + "kv_transfer_params": {"dp_rank": 2, "remote_block_ids": [1]}})) + .into_response(), + ); + d.wait_entered().await; + // Legacy: P's load is gone as soon as it answered. + wait_load(&p.worker, 0).await; + let decode_body = decode_request_body(&mut d).await; + let kv = &decode_body["kv_transfer_params"]; + assert_eq!(kv["remote_dp_rank"], 2, "{decode_body}"); + assert_eq!(kv["remote_block_ids"], json!([1]), "{decode_body}"); + assert_eq!(kv["prompt_token_ids"], json!([9, 9]), "{decode_body}"); + d.respond(axum::Json(json!({"choices": []})).into_response()); + assert_eq!(result(task).await.status(), StatusCode::OK); + assert_eq!((p.worker.load(), d.worker.load()), (0, 0)); +} + +/// Two P instances behind one router. A request whose P answered early (line +/// 1) and whose D already answered is still prefilling on that P, so P keeps +/// its load until line 2 and the prefill policy (`cache_aware`, with the +/// recipe's balance thresholds) sends the next request to the other, idle P, +/// even though the busy P holds its prefix. Line 2 then releases the load. +/// (Before this design P's guard went at line 1, so a still-prefilling P +/// looked idle and drew the next requests.) +#[tokio::test] +async fn atom_early_handoff_multi_prefill_routes_by_in_flight_prefill_load() { + use crate::policies::{CacheAwareConfig, CacheAwarePolicy}; + + let (mut p1, mut d) = servers().await; + let p2 = GatedServer::start(WorkerType::Prefill { + bootstrap_port: None, + }) + .await; + let prefills: Vec> = vec![p1.worker.clone(), p2.worker.clone()]; + let policy = CacheAwarePolicy::with_config(CacheAwareConfig { + cache_threshold: 1.0, + balance_abs_threshold: 0, + balance_rel_threshold: 1.0, + eviction_interval_secs: 0, + max_tree_size: 1000, + }); + policy.init_workers(&prefills); + let info = SelectWorkerInfo { + request_text: Some("the shared system prompt"), + ..Default::default() + }; + // The first request's prefix goes to P1. + assert_eq!(policy.select_worker(&prefills[..1], &info).await, Some(0)); + + let task = dispatch(DispatchKind::Atom, &p1, &d, false); + p1.wait_entered().await; + let (response, p_tx) = early_prefill_response(); + p1.respond(response); + send_early_handoff_line(&p_tx); + d.wait_entered().await; + d.respond(axum::Json(json!({"choices": ["decoded"]})).into_response()); + // D answered (its headers and body are out) while P1 still prefills. + assert_eq!(result(task).await.status(), StatusCode::OK); + assert_eq!(p1.worker.load(), 1, "P1 stays charged until line 2"); + assert_eq!(p1.worker.prefill_tokens(), 7); + assert_eq!(p2.worker.load(), 0); + + // The next request with the same prefix goes to the idle P2. + assert_eq!(policy.select_worker(&prefills, &info).await, Some(1)); + + // Line 2 ends P1's prefill and its charge. + p_tx.send(Ok(prefill_done_line(true))).unwrap(); + drop(p_tx); + wait_load(&p1.worker, 0).await; + assert_eq!(p1.worker.prefill_tokens(), 0); + assert_eq!( + (p1.worker.load(), p2.worker.load(), d.worker.load()), + (0, 0, 0) + ); +} diff --git a/atom/model_engine/engine_core_mgr.py b/atom/model_engine/engine_core_mgr.py index 6cc50df6c7b..1c938b6b675 100644 --- a/atom/model_engine/engine_core_mgr.py +++ b/atom/model_engine/engine_core_mgr.py @@ -315,6 +315,9 @@ class CoreManager: _bp_dispatch_paused = False _input_send_lock = Lock() _dispatch_send_lock = Lock() + # `add_request` records the dispatched DP rank on each request + # (`Sequence.pd_routed_dp_rank`), which ATOM_PD_EARLY_HANDOFF relies on. + reports_dp_rank = True def _init_shared_state( self, @@ -1205,10 +1208,16 @@ def _add_prepared_requests(self, seqs: list[Sequence]): # drives the pipeline downstream. logger.debug(f"{self.label}: Add {len(seqs)} requests to PP head 0") self._send_request(0, _add_frame(seqs)) + # The pipeline is one DP rank; D reaches every stage through + # `remote_pp_size` (ATOM_PD_EARLY_HANDOFF). + for seq in seqs: + seq.pd_routed_dp_rank = 0 elif self._routable_engine_count == 1: # Single routable engine, send all requests logger.debug(f"{self.label}: Add {len(seqs)} requests to DP rank 0") self._send_request(0, _add_frame(seqs)) + for seq in seqs: + seq.pd_routed_dp_rank = 0 else: self._dispatch_to_dp_ranks(seqs) @@ -1390,6 +1399,10 @@ def _dispatch_to_dp_ranks(self, seqs: list[Sequence]) -> None: with self._lb_lock: self._backlog.note_sent(dp_rank, rank_seqs, self._seq_load) self._flush_credit_updates() + # After the frame is pickled: the rank's own copy never sees it. + # ATOM_PD_EARLY_HANDOFF answers the router with this rank. + for seq in rank_seqs: + seq.pd_routed_dp_rank = dp_rank batch_prefill_tokens = sum( int(getattr(seq, "num_prompt_tokens", 0) or 0) for seq in rank_seqs ) @@ -2644,6 +2657,9 @@ class DisaggCoreManager(CoreManager): addresses are established here before spawning and passed through config. """ + # Its `add_request` fans out to both halves and records no DP rank. + reports_dp_rank = False + def _build_prefix_router(self, config) -> None: """The prefill/decode pair fans out requests; neither engine is a DP target.""" diff --git a/atom/model_engine/sequence.py b/atom/model_engine/sequence.py index 4160d427b26..767cd986ad3 100644 --- a/atom/model_engine/sequence.py +++ b/atom/model_engine/sequence.py @@ -275,6 +275,10 @@ class Sequence: counter = count() # True only for a decode leg whose prefill kept the media, set in __init__. media_on_prefill_instance = False + # ATOM_PD_EARLY_HANDOFF: the DP rank `CoreManager` dispatched the request + # to, set on the front end's copy after its add frame is pickled. A class + # default, so an unset rank adds nothing to the pickled state. + pd_routed_dp_rank: int | None = None def __init__( self, diff --git a/atom/utils/envs.py b/atom/utils/envs.py index 1237b04af32..382c51d1e1a 100644 --- a/atom/utils/envs.py +++ b/atom/utils/envs.py @@ -213,6 +213,25 @@ def _dp_sync_interval_env() -> int | None: # line, so D parses the body while P works. 0 = route answers 404 and the # router falls back to its serial relay. "ATOM_PD_LATE_KV": lambda: _flag_env("ATOM_PD_LATE_KV", "0"), + # Mooncake P/D, prefill (`kv_producer`): offer early handoff in + # /kv_transfer_info (`early_handoff`). The router asks for it per request + # (`kv_transfer_params.early_handoff`) only when the chosen D declares it + # can receive chunked transfer (`chunked_receive`), so no D gets chunked + # metadata it cannot serve and no model needs a per-deployment opt-out. + # P then answers at DP dispatch with chunked-transfer metadata (line 1 of + # an NDJSON body) and ends the body when the prefill ends (line 2), so the + # router keeps P's load guard for the whole prefill. Default 1: a pair the + # router does not ask for keeps the legacy relay on its own; 0 = never + # offer (legacy relay for every pair). + "ATOM_PD_EARLY_HANDOFF": lambda: _flag_env("ATOM_PD_EARLY_HANDOFF", "1"), + # With early handoff: let an early request allocate its source before D's + # write request arrives when P's pool provably keeps room for every + # registered chunked request (see MooncakeConnectorScheduler. + # _may_allocate_before_d). 0 = always wait for D (the D-first gate); kept + # for A/B only. + "ATOM_PD_EARLY_HANDOFF_SPECULATIVE": lambda: _flag_env( + "ATOM_PD_EARLY_HANDOFF_SPECULATIVE", "1" + ), # MoRIIO P/D, decode side: "read" (the decode pulls) or "write" (the # prefill pushes). Unset = kv_transfer_config's moriio_mode, else read. "ATOM_MORIIO_MODE": lambda: os.getenv("ATOM_MORIIO_MODE", ""), diff --git a/docs/environment_variables.md b/docs/environment_variables.md index 4dd2333ffa4..3f58ce1feb9 100644 --- a/docs/environment_variables.md +++ b/docs/environment_variables.md @@ -755,6 +755,9 @@ rank configuration, deployment requirements, and registration lifetime. |----------|------|---------|-------------| | **ATOM_PD_MLA_STAGING** | bool | 1 | Prefill (`kv_producer`, plain `mooncake` connector) only. When the decode side runs DCP, gather the MLA tokens each decode rank owns into a GPU staging slot laid out as its destination pages, then RDMA one descriptor per run of adjacent destination pages instead of one per 576-byte token. Destination bytes are identical. The pool holds one 8 MiB slot per send worker (`num_worker_threads`, default 16), capped at 256 MiB per producer GPU, and is held back from the KV cache budget. A prefill learns the decode's DCP size only per request, so every Mooncake producer of a plain MLA model (not DeepSeek-V4 or an MLA hybrid such as Kimi) without producer DCP reserves the pool while this is on; set 0 where no decode runs DCP. 0 restores the per-token path. | | **ATOM_PD_FAILED_WRITE_HOLD_S** | float | 60 | Mooncake P/D. Mooncake gives up on a sync RDMA write at `MC_TRANSFER_TIMEOUT` without cancelling the work it posted, so a failed write may still land afterwards; a prefill therefore never retries one. A decode holds a failed receive's KV pages (and its staging row) this many seconds before reporting the failure; the scheduler then aborts the request and frees its pages, which no late write can reach any more. A prefill keeps a landing slot whose write failed out of use for as long. 60 s covers a write Mooncake keeps re-posting while the network is down (each of its 9 tries waits at most a 5 s connect); behind a decode whose handshake hangs it can take about 10 minutes. 0 releases at once. MoRIIO P/D holds a failed receive's blocks the same way; a MoRIIO decode in write mode refuses 0, since the hold is also what lets a push started just before its deadline finish. | +| **ATOM_PD_EARLY_HANDOFF** | bool | 1 | Mooncake P/D, read on the prefill (`kv_producer`). On by default; `0` turns it off (P never offers it, so every pair keeps the legacy relay). 1: offer early handoff in `/kv_transfer_info` (`"early_handoff": {"version": 1}`) when this P can answer at DP dispatch (single-node DP, the routing `CoreManager`, a Mooncake producer, and no `enable_chunked_transfer`, whose concurrent router mode takes precedence). Nothing changes until the router asks for it per request (`kv_transfer_params.early_handoff`). The ATOM router asks only when the chosen D declares in its `/kv_transfer_info` that it can receive chunked transfer (`"chunked_receive": {"accepts": true, ...}`: a Mooncake consumer, D PP=1, no DCP decode of a model with per-request state) and D's TP is a multiple of P's; any other pair (an old or non-ATOM D, a Kimi-K3 or DeepSeek-V4.1 DCP decode, D PP>1) keeps the legacy relay, so no deployment needs a per-model opt-out. Asked, P answers at dispatch with an NDJSON body: line 1 is the usual prefill answer carrying chunked-transfer metadata (this P's endpoint, a fresh `transfer_id`, the DP rank) and no first token; line 2, `{"atom_pd_prefill_done": {"ok": ..., "finish_reason": ...}}`, is written when the prefill ends. The router relays line 1 to D at once and keeps P's load guard until line 2, so its P load accounting covers the queued and running prefill, and a P failure after the early answer (line 2 `ok: false`, or the body breaking) fails the request instead of leaving D to its timeouts. If the router hangs up first, P aborts the prefill. Because the router asks per pair, an incompatible D needs no opt-out: it keeps the legacy relay with the default on. Measured (DeepSeek-V4.1-Flash, MI355X): 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_SPECULATIVE** | bool | 1 | With `ATOM_PD_EARLY_HANDOFF` on P. 1: an early request may allocate its source before D's write request arrives, so P's prefill overlaps the router->D->P hop, but only while `pages pinned that way + its prompt pages + the prompt pages of the largest other registered chunked request <= P's pool`; otherwise it waits for D (the D-first gate) until D reaches it or room frees. D learns of a request only from P's early answer, so every request D can hold pages for is already registered on P; keeping room for the largest of them means P can always admit what D reserved, so P's pins cannot deadlock against D's reservations. Remaining gap: a larger request registered after the pins were taken that D reserves ahead of a pinned one while all of D's pages wait on P; the worker's lookup timeout (60 s) then cancels that pinned source and D aborts its request. 0 always keeps the gate (for A/B). | +| **ATOMESH_ATOM_PD_EARLY_HANDOFF** | bool | 1 | Read by the atomesh router (`atom/mesh`, `placement/backend/atom.rs`), not by ATOM. Router kill switch for early handoff: `0` makes the router never ask for it, so every pair keeps the legacy relay (P answers after its prefill) whatever P offers and D declares; unset or any other value lets the router ask per request when P offers `early_handoff` version 1, D declares `chunked_receive` with `accepts`, and D TP is a multiple of P TP. Read once per router process. | ## Mooncake PD MLA landing diff --git a/recipes/DeepSeek-V4.1-Flash-PD.md b/recipes/DeepSeek-V4.1-Flash-PD.md index 9eeaa7e3a65..af396857452 100644 --- a/recipes/DeepSeek-V4.1-Flash-PD.md +++ b/recipes/DeepSeek-V4.1-Flash-PD.md @@ -104,7 +104,7 @@ ingress in front of the router). PR states are as of 2026-11-27. | PR | What it does | State | Side | As measured (tree `de7d8ec1c`) | How to configure now | Points that used it | Notes | |---|---|---|---|---|---|---|---| | [#3772](https://github.com/ROCm/ATOM/pull/3772) | Store load wait: the first forward waits for a Mooncake Store load that is already in flight, instead of recomputing the prefix | open | P | Old fixed-wait version: `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS=20`. Its default was 0 (off), so the variable was set explicitly. | Not on main yet. On the current PR head: `ATOM_OFFLOAD_LOAD_EVENT_WAIT`, on by default (`0` turns it off), so set nothing. The PR head removes `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS`, so drop that variable. | all (c1-c768) | The wait is now event-driven: the load-completion doorbell wakes it, and the measured forward time bounds it. There is no fixed timeout. It does nothing without a Store tier. Measured at 1P1D c256: TTFT mean -20.2%, throughput +0.55%. | -| [#3773](https://github.com/ROCm/ATOM/pull/3773) | Early handoff: P answers the router at DP dispatch, so D allocates pages and pulls KV while P is still computing | open | P | `ATOM_PD_EARLY_HANDOFF=1`. Its default was 0, so the variable was set explicitly. | Not on main yet. On the current PR head it is on by default (`1`). Set `ATOM_PD_EARLY_HANDOFF=0` explicitly wherever it should be off. | all (c1-c768) | **Known issue:** if a P step stalls for more than 60 s, early requests can leak a state slot. Once a rank has leaked `--max-num-seqs` slots, it admits no more requests, permanently. Use `0` at c1024 and above until the fix lands; the fix is in progress. Load visibility is correct only with one P instance. With several P instances behind one router, the router's view of P load is wrong. | +| [#3773](https://github.com/ROCm/ATOM/pull/3773) | Early handoff: P answers the router at DP dispatch, so D allocates pages and pulls KV while P is still computing | open | P | `ATOM_PD_EARLY_HANDOFF=1`. Its default was 0, so the variable was set explicitly. | Not on main yet. On the current PR head it is on by default (`1`). Set `ATOM_PD_EARLY_HANDOFF=0` explicitly wherever it should be off. | all (c1-c768) | The ladder ran an older revision of this PR, with one P instance at every point. That revision had two problems. First, if a P step stalled for more than 60 s, an early request could leak a state slot, and a rank that had leaked `--max-num-seqs` slots admitted no more requests; runs at c1024 and above therefore used `0`, and they are not part of this ladder. Second, P's early answer ended the router's load charge for P, so with several P instances the router did not see the prefills still running on each P. The current PR head fixes both: (1) the leak fix is in the PR: the scheduler aborts a retired early source, and the worker releases its blocks and state slot; (2) the router keeps P's load guard, prefill tokens included, until P reports the prefill's end (line 2 of its answer), so the choice between several P instances sees each P's in-flight prefills. Early handoff is also negotiated per (P, D) pair, and a pair that cannot do it keeps the legacy relay. These fixes have CPU and router tests; the current head has not been run at c1024 and above, or with several P instances, in this recipe. | | [#3777](https://github.com/ROCm/ATOM/pull/3777) | Idle when blocked: a DP rank whose only work is blocked (Store lookup or load, KV send) idles instead of forcing dummy forwards | merged 2026-11-27 | P | `ATOM_DP_IDLE_WHEN_BLOCKED=1`. The pre-merge default was 0, so the variable was set explicitly. | Set nothing. On main, leaving it unset turns it on for a P/D prefill (`kv_producer`) and off elsewhere. An explicit `0` or `1` applies to any role. | all (c1-c768) | Needs `ATOM_ENABLE_PREFILL_DELAYER=0`, because the prefill delayer turns this setting off. | | [#3854](https://github.com/ROCm/ATOM/pull/3854) | Base64 prompt ids: the prompt token ids are sent as base64-packed uint32, which cuts D's ingest cost | merged 2026-11-26 | P, D, ingress | `ATOM_PROMPT_IDS_B64=1` on P and D (pre-merge default 0; merged into the tree by hand with two conflicts). Ingress: `ATOM_FRONT_IDS_B64=1 ATOM_FRONT_SPLICE_BODY=1`. | P and D: set nothing, since `ATOM_PROMPT_IDS_B64` is on (`1`) by default on main. Ingress: keep `ATOM_FRONT_IDS_B64=1 ATOM_FRONT_SPLICE_BODY=1`. | all (c1-c768) | The two `ATOM_FRONT_*` variables belong to the external ingress, not to ATOM. Without them the ingress sends JSON ids, which still work. | | [#3873](https://github.com/ROCm/ATOM/pull/3873) | Late KV params on D: D accepts the chat request first and P's `kv_transfer_params` afterwards, on `/v1/pd/late_kv/chat/completions` | merged 2026-11-26 | D | Not in the tree and not used. | `ATOM_PD_LATE_KV=1` on D. The default is `0`, under which the route answers 404. | none | Use together with #3874. | @@ -154,8 +154,10 @@ they were not part of the measured points. P-rank x D-rank rail takes 35-60 s to set up, while P's lookup times out at 60 s (`PREFILL_LOOKUP_TIMEOUT`). Before timing, drive enough traffic that every P rank has transferred to every D rank. -- **Early handoff.** Set `ATOM_PD_EARLY_HANDOFF=0` at c1024 and above (see - #3773 above). +- **Early handoff.** The measured revision of #3773 was run only up to c768; + c1024 and above used `ATOM_PD_EARLY_HANDOFF=0` because of a state-slot leak + that the current PR head fixes (see #3773 above). On the current PR head it + is on by default; `0` on P turns it off. ### Software stack (identical on P and D, every point) @@ -2461,7 +2463,7 @@ The two-node 1P1D AgentX ladder (c1-c768, P DEP4 + D TP8 Mono or D DEP8, | 5 | Store | Mooncake Store on the same host as P/D (optional) | About -2%, within noise. A remote Store works the same way. | | 6 | D | `--moe-backend mega` (E19 = E14a + items 6 and 7) | ITL fell from 6.37 to 5.88 ms on Host A, and throughput rose to 7,572 tok/s. | | 7 | P | `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS=20` (needs ATOM #3772) | The first forward waits up to 20 ms for a Store load already in flight, instead of recomputing the prefix. | -| 8 | P | `ATOM_PD_EARLY_HANDOFF=1` (needs ATOM #3773) | P answers the router as soon as it has dispatched the request, so D allocates and pulls KV while P computes. Time from P finish to first token fell from 0.309 to 0.136 s. **Use only with a single P instance** (see [Caveats](#caveats)). | +| 8 | P | `ATOM_PD_EARLY_HANDOFF=1` (needs ATOM #3773) | P answers the router as soon as it has dispatched the request, so D allocates and pulls KV while P computes. Time from P finish to first token fell from 0.309 to 0.136 s. Measured with a single P instance. On the current PR head the router keeps P charged until P's prefill ends, so several P instances are balanced by their in-flight prefills (covered by router tests, not measured here; see [Caveats](#caveats)). | | 9 | P | `ATOM_DP_IDLE_WHEN_BLOCKED=1` (ATOM #3777, merged; on by default on a P/D prefill on main) | A DP rank whose only work is waiting on a Store lookup or load, or on a KV send, no longer forces the group into dummy forwards. Outside the arrival burst, P queueing fell from about 0.22 s to 0.083 s. Ignored while the prefill delayer is on. | | 10 | D | `--cudagraph-capture-sizes '[1,2,4,6,8,10,12,14,16,18,20,22,24,28,32,36,40,44,48,64,96,128]'` | D runs batch 15-20 per rank at C256. The old 16→24 step padded those batches. In a same-host A/B, a step at batch 17 was 2.67 ms faster and at batch 19 2.49 ms faster. Batches 16 and 24 changed by ±0.15 ms. Startup time and cudagraph memory (1.53 GB) were unchanged. | @@ -2523,9 +2525,10 @@ for their current defaults): `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS` as measured. The current PR head replaces it with `ATOM_OFFLOAD_LOAD_EVENT_WAIT` (on by default). 4. **ATOM [#3773](https://github.com/ROCm/ATOM/pull/3773)** (open): - `ATOM_PD_EARLY_HANDOFF`. It applies only when P uses single-node DP and - the router uses the legacy relay. The current PR head turns it on by - default. + `ATOM_PD_EARLY_HANDOFF`. On the current PR head it is on by default and + negotiated per (P, D) pair: P offers it only with single-node DP and + without router-chunked mode, the router asks for it only when D can take + the chunked receive, and every other pair keeps the legacy relay. 5. **ATOM [#3777](https://github.com/ROCm/ATOM/pull/3777)** (merged): `ATOM_DP_IDLE_WHEN_BLOCKED`, which includes the `BLOCKED_IDLE_SLEEP_S` GIL yield. On main it is on by default on a P/D prefill. @@ -2738,11 +2741,15 @@ in the D command above. --cudagraph-capture-sizes '[1,2,4,6,8,10,12,14,16,18,20,22,24,28,32,36,40,44,48,64,96,128]' \ ``` -`ATOM_PD_EARLY_HANDOFF` is for **one P instance only**. P answers the router -once it has dispatched the request, so the router's in-flight count for P -stays near zero. With several P instances, atomesh's least-loaded choice -between them then no longer sees each P's queue depth. Leave it unset when -more than one P serves a router. +`ATOM_PD_EARLY_HANDOFF` was measured with one P instance. In the measured +revision, P's answer at dispatch also ended the router's load charge for P, +so with several P instances atomesh's least-loaded choice no longer saw each +P's queue depth. The current PR head keeps P's load, prefill tokens +included, until P reports the prefill's end (line 2 of its answer), so the +choice between several P instances sees the prefills still running. Router +tests cover this; no multi-P run has been made with this recipe. On the +current head it is on by default; set `ATOM_PD_EARLY_HANDOFF=0` on P to turn +it off. ### 4. Router and encoding ingress @@ -2910,9 +2917,11 @@ What the tables show: without items 6-9, because the burst about 300 s into the window queues every request behind a 4-GPU P. Items 6-10 improve the mean, P50, P90 and the non-burst tail, but not this. -- **Early handoff (8) is for a single P instance.** With several P instances - behind one router, the router stops seeing P load; see - [Best configuration](#best-configuration). Under a burst, D also reserves +- **Early handoff (8) was measured with a single P instance.** In the measured + revision, the router stopped seeing P load once P answered early, so + several P instances were not balanced; the current PR head keeps P charged + until its prefill ends, see [Best configuration](#best-configuration). + Under a burst, D also reserves pages for requests still queued on P. In the A/B, D's mean waiting requests rose from 1.1 to 7.5, with no preemption and no errors. - **The full stack was measured once, on Host B only.** A same-host E19 run diff --git a/tests/entrypoints/test_pd_prompt_token_ids.py b/tests/entrypoints/test_pd_prompt_token_ids.py index ec89b6b552d..a97b9f8c070 100644 --- a/tests/entrypoints/test_pd_prompt_token_ids.py +++ b/tests/entrypoints/test_pd_prompt_token_ids.py @@ -395,12 +395,17 @@ def test_chunked_transfer_discovery_advertises_pp_and_page_geometry( kv_cache_block_size=64, decode_context_parallel_size=2, ) + # Router-chunked discovery alone; early handoff (on by default) has its + # own coverage in tests/test_pd_early_handoff.py. + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "0") + monkeypatch.setattr(api_server, "_early_handoff_endpoint_cache", []) monkeypatch.setattr(api_server, "engine", SimpleNamespace(config=config)) monkeypatch.setattr("atom.utils.network.get_ip", lambda: "127.0.0.1") info = asyncio.run(api_server.kv_transfer_info()) assert info["kv_role"] == "kv_producer" assert info["handshake_port"] == 6401 assert ("chunked_transfer" in info) is enabled + assert "early_handoff" not in info if enabled: assert info["chunked_transfer"] == { "remote_host": "127.0.0.1", diff --git a/tests/entrypoints/test_stream_silence_watchdog.py b/tests/entrypoints/test_stream_silence_watchdog.py index 1ba981b7a3a..4e7bbc35e4e 100644 --- a/tests/entrypoints/test_stream_silence_watchdog.py +++ b/tests/entrypoints/test_stream_silence_watchdog.py @@ -241,10 +241,18 @@ class TestTheEndpointUsesIt: """ def test_every_streaming_response_is_wrapped(self): + import inspect import pathlib import re - src = pathlib.Path(api_server.__file__).read_text() + src = pathlib.Path(api_server.__file__).read_text(encoding="utf-8") + # Not a client stream: P's two-line answer to the P/D router, which + # waits for the whole prefill between its lines by design (the router + # holds P's load until the second). The watchdog would read that wait + # as silence. + p_to_router = inspect.getsource(api_server._nonstream_response) + assert p_to_router.count("StreamingResponse(") == 1 + src = src.replace(p_to_router, "") total = src.count("StreamingResponse(") wrapped = len(re.findall(r"StreamingResponse\(\s*_client_stream\(", src)) assert total == 4, f"the endpoint count changed ({total}); check this test" diff --git a/tests/test_pd_chunked_transfer.py b/tests/test_pd_chunked_transfer.py index 44bf466781d..bc3234785f6 100644 --- a/tests/test_pd_chunked_transfer.py +++ b/tests/test_pd_chunked_transfer.py @@ -466,6 +466,10 @@ def scheduler_connector( parallel_config=SimpleNamespace(data_parallel_size=1, data_parallel_rank=0), kv_cache_block_size=4, decode_context_parallel_size=dcp_size, + # Sized like an engine's pool: with ATOM_PD_EARLY_HANDOFF on by + # default, a producer connector also builds the early-handoff + # admission rule, which router-chunked requests never use. + num_kvcache_blocks=1024, ) ) @@ -2216,6 +2220,7 @@ def test_a_preempted_producer_request_rejected_on_readmission_hands_nothing_off( parallel_config=SimpleNamespace(data_parallel_size=1, data_parallel_rank=0), kv_cache_block_size=4, decode_context_parallel_size=1, + num_kvcache_blocks=100, # early handoff, on by default, sizes its rule ) ) seq = seq_factory( diff --git a/tests/test_pd_early_handoff.py b/tests/test_pd_early_handoff.py new file mode 100644 index 00000000000..a9eb7611fac --- /dev/null +++ b/tests/test_pd_early_handoff.py @@ -0,0 +1,1565 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""P/D early handoff, negotiated per request. + +P offers it (`/kv_transfer_info` `early_handoff`), D declares what it can +receive (`chunked_receive`), the router asks per request. P answers at DP +dispatch with an NDJSON body whose second line marks the end of the prefill, +and may allocate before D's write request only while its pool provably keeps +room for every registered chunked request. + +CPU only. Reuses the chunked-transfer protocol fixtures (real schedulers, real +producer/consumer workers, CPU buffers in place of HBM and the NIC). +""" + +import asyncio +import json +import time +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from test_pd_chunked_transfer import ( + decode_worker, + dispatch, + idle_producer, + mc, + post_write_requests, + publish, +) + +from atom.kv_transfer.disaggregation.types import KVConnectorOutput + +TRANSFER = "early-xfer" + + +def make_scheduler_connector( + monkeypatch, is_producer, *, early, speculative=None, num_kvcache_blocks=100 +): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1" if early else "0") + if speculative is None: + monkeypatch.delenv("ATOM_PD_EARLY_HANDOFF_SPECULATIVE", raising=False) + else: + monkeypatch.setenv( + "ATOM_PD_EARLY_HANDOFF_SPECULATIVE", "1" if speculative else "0" + ) + monkeypatch.setattr(mc, "get_ip", lambda: "127.0.0.1") + monkeypatch.setattr(mc, "get_open_port", lambda: 6400) + config = SimpleNamespace( + kv_transfer_config={"kv_role": "kv_producer" if is_producer else "kv_consumer"}, + tensor_parallel_size=1, + pipeline_parallel_size=1, + parallel_config=SimpleNamespace(data_parallel_size=1, data_parallel_rank=0), + kv_cache_block_size=4, + decode_context_parallel_size=1, + num_kvcache_blocks=num_kvcache_blocks, + ) + return mc.MooncakeConnectorScheduler(config) + + +def p_params(transfer_id=TRANSFER, early=True): + """What `api_server._early_handoff_params` makes of the router's leg + (`early=False`: a router-chunked leg, which always keeps the gate).""" + params = { + "chunked_transfer": True, + "do_remote_decode": True, + "do_remote_prefill": False, + "transfer_id": transfer_id, + } + if early: + params["pd_early_handoff"] = True + return params + + +def d_params(transfer_id=TRANSFER): + """What the router relay hands D from P's early answer.""" + return { + "chunked_transfer": True, + "do_remote_prefill": True, + "do_remote_decode": False, + "transfer_id": transfer_id, + "block_size": 4, + "dcp_size": 1, + "remote_host": "cpu", + "remote_handshake_port": 6301, + "remote_pp_size": 1, + "tp_size": 1, + "remote_tp_size": 1, + "remote_dp_size": 1, + "remote_dp_rank": 0, + } + + +def _ack(p, seq, succeeded=True): + """D's write request reached every P rank (the worker's report).""" + p.process_pd_completions( + KVConnectorOutput( + connector_completions={ + mc.ConnectorCompletion("pd_admission_ready", seq.id, succeeded) + } + ) + ) + + +def _allocate(p, seq, blocks): + """What the scheduler does once `admission_ready` said yes.""" + from atom.model_engine.sequence import new_block_table + + seq.block_table = new_block_table(blocks) + p.update_state_after_alloc(seq) + return p.build_connector_meta() + + +def _finish_prefill(p, seq, token=42): + seq.prefill_completed = True + seq.append_token(token) + p.request_finished(seq) + + +def _prompt(pages, start=0): + """A prompt of exactly `pages` 4-token pages (the last one partial).""" + return list(range(start, start + 4 * pages - 2)) + + +# ------------------------------------------------------------ admission rule + + +def test_flag_off_keeps_existing_config(monkeypatch, seq_factory): + plain = make_scheduler_connector(monkeypatch, True, early=False) + assert not plain.enable_chunked_transfer and not plain._speculative + seq = seq_factory(list(range(10)), kv_transfer_params=p_params()) + with pytest.raises(ValueError, match="enable_chunked_transfer"): + plain.admission_ready(seq) + + +def test_flag_enables_chunked_producer_but_not_consumer(monkeypatch): + assert make_scheduler_connector( + monkeypatch, True, early=True + ).enable_chunked_transfer + d = make_scheduler_connector(monkeypatch, False, early=True) + assert not d.enable_chunked_transfer and not d._speculative + + +def test_early_request_on_an_idle_pool_allocates_before_d(monkeypatch, seq_factory): + """Nothing else registered: P may allocate at once, so P's prefill overlaps + the router->D->P hop. It is still registered with the worker once.""" + p = make_scheduler_connector(monkeypatch, True, early=True) + seq = seq_factory(list(range(10)), kv_transfer_params=p_params()) + for _ in range(3): # The scheduler asks on every pass. + assert p.admission_ready(seq) + assert p.build_connector_meta().chunked_admissions == {seq.id: TRANSFER} + assert p.admission_ready(seq) + assert p.build_connector_meta().chunked_admissions == {} + + +def test_a_prompt_over_half_the_pool_still_skips_on_an_idle_pool( + monkeypatch, seq_factory +): + """The fixed 50% cap of #3773 sent this to the gate; the rule does not: + with nothing else registered, a 5-page prompt fits a 6-page pool.""" + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + big = seq_factory(_prompt(5), kv_transfer_params=p_params("early-big")) + assert p.admission_ready(big) + + +def test_router_chunked_leg_keeps_the_gate(monkeypatch, seq_factory): + """A router-chunked leg (no `pd_early_handoff`): D got the request at the + same time as P and may reserve requests P has not registered yet, so the + rule's premise does not hold and it waits for D.""" + p = make_scheduler_connector(monkeypatch, True, early=True) + seq = seq_factory(list(range(10)), kv_transfer_params=p_params(early=False)) + assert not p.admission_ready(seq) + _ack(p, seq) + assert p.admission_ready(seq) + + +def test_speculative_off_keeps_the_gate(monkeypatch, seq_factory): + p = make_scheduler_connector(monkeypatch, True, early=True, speculative=False) + seq = seq_factory(list(range(10)), kv_transfer_params=p_params()) + assert not p.admission_ready(seq) + _ack(p, seq) + assert p.admission_ready(seq) + _allocate(p, seq, [0, 1, 2]) + assert not p._spec_pins + + +def test_lifecycle_without_speculative_touches_no_early_source_state( + monkeypatch, seq_factory +): + """Undo, finish, send and D's report reach no early-handoff record on a + connector that keeps none (as `tests/test_pd_source_claim.py`'s stand-in).""" + p = make_scheduler_connector(monkeypatch, True, early=True, speculative=False) + del p._early_sources + seq = seq_factory(list(range(10)), kv_transfer_params=p_params()) + p.admission_ready(seq) + _ack(p, seq) + assert p.admission_ready(seq) + from atom.model_engine.sequence import new_block_table + + seq.block_table = new_block_table([0, 1, 2]) + p.update_state_after_alloc(seq) + p.cancel_preadmission(seq) # an undispatched allocation is undone + _allocate(p, seq, [0, 1, 2]) + _ack(p, seq, succeeded=False) + _finish_prefill(p, seq) + p.send_finished(seq.id) + + +@pytest.mark.parametrize( + "pool,a_ready,b_ready", + [ + (6, False, False), # 3 + 4 > 6 and 4 + 3 > 6: both wait for D + (7, True, True), # 3 + 4 <= 7 + ], +) +def test_room_is_kept_for_the_largest_other_registered_request( + monkeypatch, seq_factory, pool, a_ready, b_ready +): + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=pool) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(4, 100), kv_transfer_params=p_params("early-b")) + p.admission_ready(a) # Both registered, as `Scheduler.add` does. + p.admission_ready(b) + assert p.admission_ready(a) is a_ready + assert p.admission_ready(b) is b_ready + # D reached B: B no longer needs room kept by anybody else's rule. + _ack(p, b) + assert p.admission_ready(b) + + +def test_pins_count_until_d_reaches_p(monkeypatch, seq_factory): + """A source allocated before D waits on D: it counts against the pool + until D's report, then it is an ordinary allocation.""" + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=7) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(4, 100), kv_transfer_params=p_params("early-b")) + c = seq_factory(_prompt(1, 200), kv_transfer_params=p_params("early-c")) + for s in (a, b, c): + p.admission_ready(s) + assert p.admission_ready(a) # 0 + 3 + 4 <= 7 + _allocate(p, a, [0, 1, 2]) + assert p._spec_pins == {str(a.id): 3} + assert not p.admission_ready(c) # 3 pinned + 1 + room for B (4) > 7 + assert not p.admission_ready(b) # 3 pinned + 4 + room for C (1) > 7 + _ack(p, a) # D reached A: its source no longer waits on D. + assert not p._spec_pins + assert p.admission_ready(c) and p.admission_ready(b) + + +def test_allocated_and_aborted_requests_leave_the_waiting_set(monkeypatch, seq_factory): + from atom.model_engine.sequence import SequenceStatus + + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=7) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + big = seq_factory(_prompt(5, 100), kv_transfer_params=p_params("early-big")) + p.admission_ready(a) + p.admission_ready(big) + assert not p.admission_ready(a) # 3 + 5 > 7 + big.status = SequenceStatus.ABORTED + big.leave_reason = "aborted" + p.request_finished(big) # leaves `_chunked_waiting`; its heap entry is stale + assert p._largest_waiting_pages(a) == 0 + assert p.admission_ready(a) + + +def test_waiting_heap_stays_bounded(monkeypatch, seq_factory): + p = make_scheduler_connector(monkeypatch, True, early=True) + for i in range(300): + s = seq_factory(_prompt(1, i * 10), kv_transfer_params=p_params(f"x{i}")) + p.admission_ready(s) + _ack(p, s) + _allocate(p, s, [0]) + assert len(p._waiting_pages) <= 2 * len(p._chunked_waiting) + 65 + + +def test_speculation_needs_a_sized_pool(monkeypatch): + with pytest.raises(ValueError, match="sized KV pool"): + make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=-1) + + +def test_allocation_after_d_reached_p_takes_no_pin(monkeypatch, seq_factory): + """D reached P first: the source never waits on D, so it is an ordinary + allocation and keeps no room from later early requests.""" + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(3, 100), kv_transfer_params=p_params("early-b")) + p.admission_ready(a) + _ack(p, a) + assert p.admission_ready(a) + _allocate(p, a, [0, 1, 2]) + assert not p._spec_pins + assert p.admission_ready(b) # 0 pinned + 3 <= 6 + + +def test_reallocation_after_d_reached_p_takes_no_pin(monkeypatch, seq_factory): + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + assert p.admission_ready(a) + _allocate(p, a, [0, 1, 2]) + assert p._spec_pins == {str(a.id): 3} + _ack(p, a) + assert not p._spec_pins + assert p.admission_ready(a) # It holds its send claim: re-admitted. + _allocate(p, a, [0, 1, 2, 3]) + assert not p._spec_pins + + +def test_undone_allocation_releases_the_pin(monkeypatch, seq_factory): + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + assert p.admission_ready(a) + from atom.model_engine.sequence import new_block_table + + a.block_table = new_block_table([0, 1, 2]) + p.update_state_after_alloc(a) + assert str(a.id) in p._spec_pins + p.cancel_preadmission(a) + assert not p._spec_pins and a.id in p._chunked_waiting + assert p._largest_waiting_pages(seq_factory([1])) == 3 # back in the heap + + +@pytest.mark.parametrize("as_str", [False, True]) +def test_send_finished_releases_the_pin(monkeypatch, seq_factory, as_str): + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + assert p.admission_ready(a) + _allocate(p, a, [0, 1, 2]) + _finish_prefill(p, a) + assert p._spec_pins == {str(a.id): 3} and p.should_defer_free(a) + p.send_finished(str(a.id) if as_str else a.id) + assert not p._spec_pins and not p.should_defer_free(a) + + +def test_aborted_early_request_releases_the_pin(monkeypatch, seq_factory): + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + assert p.admission_ready(a) + _allocate(p, a, [0, 1, 2]) + a.leave_reason = "aborted" + p.request_finished(a) + assert not p._spec_pins + assert p.build_connector_meta().reqs_to_save[a.id].prefill_aborted + + +@pytest.mark.parametrize("speculative", [False, True]) +def test_early_request_whose_d_never_comes_expires_without_a_source( + monkeypatch, seq_factory, speculative +): + """D never arrives and P never allocated (gate, or no room): the + admission timeout aborts it before it takes a source.""" + from atom.model_engine.sequence import SequenceStatus + + p = make_scheduler_connector( + monkeypatch, True, early=True, speculative=speculative, num_kvcache_blocks=3 + ) + other = seq_factory(_prompt(3, 100), kv_transfer_params=p_params("early-o")) + seq = seq_factory(_prompt(3), kv_transfer_params=p_params()) + clock = [100.0] + monkeypatch.setattr(mc.time, "monotonic", lambda: clock[0]) + p.admission_ready(other) + assert not p.admission_ready(seq) # 3 + 3 > 3 either way + clock[0] += p._chunked_admission_timeout_s + assert not p.admission_ready(seq) + assert seq.status == SequenceStatus.ABORTED + assert not seq.block_table and seq.id not in p._chunked_waiting + + +@pytest.mark.parametrize( + "name,raw,expected", + [ + ("ATOM_PD_EARLY_HANDOFF", None, True), + ("ATOM_PD_EARLY_HANDOFF", "1", True), + ("ATOM_PD_EARLY_HANDOFF", "0", False), + ("ATOM_PD_EARLY_HANDOFF_SPECULATIVE", None, True), + ("ATOM_PD_EARLY_HANDOFF_SPECULATIVE", "0", False), + ], +) +def test_env_defaults(monkeypatch, name, raw, expected): + from atom.utils import envs + + if raw is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, raw) + assert getattr(envs, name) == expected + + +# ------------------------------------------- real P and D schedulers and workers + + +def _p_scheduler(monkeypatch, num_blocks=6, speculative=None): + from conftest import MockConfig + + from atom.model_engine.scheduler import Scheduler + + p = Scheduler(MockConfig(num_kvcache_blocks=num_blocks, max_num_batched_tokens=4)) + p.kv_connector = make_scheduler_connector( + monkeypatch, + True, + early=True, + speculative=speculative, + num_kvcache_blocks=num_blocks, + ) + p.kv_connector.bind_block_manager(p.block_manager) # as `Scheduler` does + return p + + +def _d_scheduler(monkeypatch, num_blocks=6): + from conftest import MockConfig + + from atom.model_engine.scheduler import Scheduler + + d = Scheduler(MockConfig(num_kvcache_blocks=num_blocks, max_num_batched_tokens=4)) + d.kv_connector = make_scheduler_connector(monkeypatch, False, early=True) + return d + + +def _wire(pw, dw, results=None): + import msgpack + + def receive(_addr, message): + assert message[0] == mc.MSG_WRITE_REQUEST + dispatch(pw, msgpack.loads(message[1])) + + def complete(data, success): + if results is None: + assert success + else: + results.append((data["transfer_id"], success)) + dw._record_write_done( + data["request_id"], + 0, + 0, + data["write_nonce"], + success=success, + handoff=data.get("prefill_handoff"), + ) + + dw._send_on_socket.side_effect = receive + pw._notify_transfer_result.side_effect = complete + pw._ack_write_request = MagicMock( + side_effect=lambda data: dw._record_write_ack( + { + "request_id": data["request_id"], + "write_nonce": data["write_nonce"], + "pp_rank": 0, + "tp_rank": 0, + "write_window_s": mc._write_window_s(), + } + ) + ) + + +def _pair(seq_factory, name, prompt): + from atom.sampling_params import SamplingParams + + ps = seq_factory( + prompt, + sampling_params=SamplingParams(max_tokens=1), + kv_transfer_params=p_params(name), + ) + ds = seq_factory( + prompt, + sampling_params=SamplingParams(max_tokens=2), + kv_transfer_params=d_params(name), + ) + return ps, ds + + +def _drive(p, d, pw, dw, monkeypatch, done, rounds=300, watch=None): + """Step D and P alternately until `done()`; returns (finished on D, the + order P started requests in).""" + from atom.model_engine.scheduler import ScheduledBatchOutput + + finished, started = [], [] + pool = ThreadPoolExecutor(1) + pw._send_executor = pool + try: + for _ in range(rounds): + if done(finished): + break + time.sleep(0.01) # let the send thread write what was published + d._update_from_kv_xfer_finished(dw.get_finished()) + out = d.schedule() + if out is not None: + batch, seqs = out + dw.start_load_kv(batch.connector_meta_output) + if seqs: + ids = list(seqs) + finished += d.postprocess( + list(seqs.values()), + ScheduledBatchOutput(ids, [(43,)] * len(ids), None, None, None), + batch=batch, + ) + if dw._write_queue: + post_write_requests(dw, monkeypatch) + p._update_from_kv_xfer_finished(pw.get_finished()) + if watch is not None: + watch() + out = p.schedule() + if out is None: + # The engine's idle drain still ships the connector's meta. + pw.start_load_kv(p.kv_connector.build_connector_meta()) + continue + batch, seqs = out + pw.start_load_kv(batch.connector_meta_output) + for sid, seq in seqs.items(): + if sid not in started: + started.append(sid) + state = pw._chunked_prefills[seq.kv_transfer_params["transfer_id"]] + publish(state, int(batch.context_lens[0])) + pw._dispatch_ready_chunked_requests() + p.postprocess( + [seq], + ScheduledBatchOutput([sid], [(42,)], None, None, None), + batch=batch, + ) + pw.start_load_kv(p.kv_connector.build_connector_meta()) + finally: + pool.shutdown(wait=True) + return finished, started + + +@pytest.mark.parametrize("forwards_before_d", [1, 3]) +def test_p_prefills_before_d_arrives_and_d_receives_every_page( + monkeypatch, seq_factory, forwards_before_d +): + """An idle P allocates and prefills at once (3 = the whole prefill, the + handoff included, is done before D arrives). D's reader starts from block + 0: every page lands byte-identical, D gets the first token, and P frees its + source only once D's reader finished.""" + import ctypes + + from atom.model_engine.scheduler import ScheduledBatchOutput + + p = _p_scheduler(monkeypatch) + d = _d_scheduler(monkeypatch) + ps, ds = _pair(seq_factory, TRANSFER, list(range(10))) + pw, _, src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + _wire(pw, dw) + p.extend([ps]) + + def p_forward(forward): + batch, seqs = p.schedule() + assert list(seqs) == [ps.id] + assert batch.context_lens.tolist() == [min(4 * (forward + 1), 10)] + pw.start_load_kv(batch.connector_meta_output) + publish(pw._chunked_prefills[TRANSFER], int(batch.context_lens[0])) + pw._dispatch_ready_chunked_requests() + p.postprocess( + list(seqs.values()), + ScheduledBatchOutput([ps.id], [(42,)], None, None, None), + batch=batch, + ) + pw.start_load_kv(p.kv_connector.build_connector_meta()) + + pool = ThreadPoolExecutor(1) + pw._send_executor = pool + try: + for forward in range(forwards_before_d): + p_forward(forward) + assert ps.block_table and not p._is_preemptable(ps) + assert pw.transfer_engine.writes.empty() + assert p.kv_connector._spec_pins == {str(ps.id): 3} + d.extend([ds]) + batch, seqs = d.schedule() + assert not seqs and len(ds.block_table) == 3 + dw.start_load_kv(batch.connector_meta_output) + post_write_requests(dw, monkeypatch) + p._update_from_kv_xfer_finished(pw.get_finished()) + for forward in range(forwards_before_d, 3): + p_forward(forward) + pool.shutdown(wait=True) + finally: + pool.shutdown(wait=True) + pw._send_executor = SimpleNamespace(submit=lambda fn, *a, **kw: fn(*a, **kw)) + p._update_from_kv_xfer_finished(pw.get_finished()) + assert not ps.block_table and not p.deferred_free_blocks + assert not p.kv_connector._chunked_waiting and not p.kv_connector._spec_pins + d._update_from_kv_xfer_finished(dw.get_finished()) + batch, seqs = d.schedule() + assert list(seqs) == [ds.id] + assert ds.kv_transfer_params["first_token_id"] == 42 + sent = [] + while not pw.transfer_engine.writes.empty(): + sources, dsts, sizes = pw.transfer_engine.writes.get_nowait() + sent += list(zip(sources, dsts, sizes, strict=True)) + base_src, base_dst = ctypes.addressof(src), ctypes.addressof(destinations[0]) + assert sum(size for _, _, size in sent) == 12 + for s, t, size in sent: + assert bytes(src[s - base_src : s - base_src + size]) == bytes( + destinations[0][t - base_dst : t - base_dst + size] + ) + + +@pytest.mark.parametrize("byte_limit", [False, True]) +def test_opposite_admission_order_progresses(monkeypatch, seq_factory, byte_limit): + """Copilot's / valar-cop's cycle: room for one prompt per side; P queues A + then B, D admits B then A. The rule keeps room for B while B is + registered, so P does not pin A before D: it follows D's order, both + finish, nothing is cancelled.""" + from atom.kv_transfer.disaggregation.pd_admission import PdAdmissionController + + p = _p_scheduler(monkeypatch, num_blocks=3) + d_blocks = 6 if byte_limit else 3 + d = _d_scheduler(monkeypatch, num_blocks=d_blocks) + if byte_limit: + d.pd_admission = PdAdmissionController(12, 4, d.kv_connector, d.block_manager) + pa, da = _pair(seq_factory, "early-a", list(range(10))) + pb, db = _pair(seq_factory, "early-b", list(range(10))) + p.extend([pa, pb]) + d.extend([db, da]) + pw, _, _src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + _wire(pw, dw) + finished, started = _drive( + p, d, pw, dw, monkeypatch, lambda f: len(f) == 2, rounds=60 + ) + assert started == [pb.id, pa.id] + assert [s.id for s in finished] == [db.id, da.id] + assert pw._notify_transfer_result.call_count == 2 # `_wire` asserts success + assert p.block_manager.kv.num_free == 3 + assert d.block_manager.kv.num_free == d_blocks + assert not p.deferred_free_blocks and not d.deferred_free_blocks + + +def test_unequal_prompts_progress_without_an_abort(monkeypatch, seq_factory): + """Copilot's unequal case, which #3773's 50% cap could only end in a + 60 s stall and an abort: P has 6 pages, D 4; A takes 3, B 4; P queues A + then B, D admits B then A. 3 + 4 > 6, so A waits for D: P follows D's + order and both finish.""" + monkeypatch.setattr(mc, "PREFILL_LOOKUP_TIMEOUT", 0.05) + p = _p_scheduler(monkeypatch, num_blocks=6) + d = _d_scheduler(monkeypatch, num_blocks=4) + pa, da = _pair(seq_factory, "early-a", _prompt(3)) + pb, db = _pair(seq_factory, "early-b", _prompt(4, 100)) + p.extend([pa, pb]) + d.extend([db, da]) + pw, _, _src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + results = [] + _wire(pw, dw, results) + finished, started = _drive( + p, + d, + pw, + dw, + monkeypatch, + lambda f: db in f and (da in f or da.leave_reason == "aborted"), + ) + assert started == [pb.id, pa.id] + assert [s.id for s in finished] == [db.id, da.id] + assert sorted(results) == [("early-a", True), ("early-b", True)] + assert p.block_manager.kv.num_free == 6 and d.block_manager.kv.num_free == 4 + assert not p.kv_connector._spec_pins + + +def test_late_larger_request_reordered_by_d_ends_in_a_bounded_abort( + monkeypatch, seq_factory +): + """The rule's remaining gap, kept visible. A (3 pages) is the only + registered request, so P pins it before D. Only then does B (4 pages) + reach P, and D reserves B *ahead of* A (in production D got A's answer + first, so this needs D to reorder). P's 3 free pages cannot take B and + D's 4 pages hold B. The worker's lookup timeout (shortened here) cancels + A's source: B completes, D aborts A, both pools end empty.""" + from atom.model_engine.sequence import SequenceStatus + + monkeypatch.setattr(mc, "PREFILL_LOOKUP_TIMEOUT", 0.05) + monkeypatch.setenv("ATOM_PD_FAILED_WRITE_HOLD_S", "0") + p = _p_scheduler(monkeypatch, num_blocks=6) + d = _d_scheduler(monkeypatch, num_blocks=4) + pa, da = _pair(seq_factory, "early-a", _prompt(3)) + pb, db = _pair(seq_factory, "early-b", _prompt(4, 100)) + p.extend([pa]) + pw, _, _src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + results = [] + _wire(pw, dw, results) + arrived = [] + + def b_arrives_after_a_is_pinned(): + if not arrived and str(pa.id) in p.kv_connector._spec_pins: + arrived.append(True) + p.extend([pb]) + d.extend([db, da]) + + finished, started = _drive( + p, + d, + pw, + dw, + monkeypatch, + lambda f: db in f and da.leave_reason == "aborted", + watch=b_arrives_after_a_is_pinned, + ) + assert started == [pa.id, pb.id] + assert db in finished and da.status == SequenceStatus.FINISHED + assert da.leave_reason == "aborted" + assert sorted(results) == [("early-a", False), ("early-b", True)] + assert p.block_manager.kv.num_free == 6 and d.block_manager.kv.num_free == 4 + assert not p.kv_connector._spec_pins + + +def test_d_never_arrives_for_a_finished_source(monkeypatch, seq_factory): + """P prefilled an early request before D; D never comes (router or D died + after the early answer). P keeps the pin and send claim until the worker's + lookup timeout reports the source safe; then the pool is whole again.""" + from atom.model_engine.scheduler import ScheduledBatchOutput + from atom.sampling_params import SamplingParams + + p = _p_scheduler(monkeypatch, num_blocks=6) + a = seq_factory( + _prompt(3), + sampling_params=SamplingParams(max_tokens=1), + kv_transfer_params=p_params("early-a"), + ) + p.extend([a]) + for _ in range(3): + batch, seqs = p.schedule() + assert list(seqs) == [a.id] + p.postprocess( + list(seqs.values()), + ScheduledBatchOutput([a.id], [(42,)], None, None, None), + batch=batch, + ) + handoff = p.kv_connector.build_connector_meta().reqs_to_save[a.id] + assert not handoff.prefill_aborted + assert p.kv_connector._spec_pins == {str(a.id): 3} + assert a.id in p.deferred_free_blocks + p._update_from_kv_xfer_finished( + KVConnectorOutput( + connector_completions={mc.ConnectorCompletion("pd_source_safe", a.id, True)} + ) + ) + assert not p.kv_connector._spec_pins + assert not p.deferred_free_blocks and p.block_manager.kv.num_free == 6 + + +def test_late_write_request_before_p_allocation_is_not_expired(monkeypatch): + """D can reach P's listener while P still queues the request (gated + early request). Registration keeps it from being retired as an orphan.""" + from atom.kv_transfer.disaggregation.types import ConnectorMetadata + + pw, request, _, _ = idle_producer() + request["transfer_id"] = TRANSFER + meta = ConnectorMetadata() + meta.chunked_admissions = {7: TRANSFER} + pw.start_load_kv(meta) + with pw._completed_prefills_lock: + pw._pending_chunked_requests.append( + (request, mc.time.monotonic() - mc.PREFILL_LOOKUP_TIMEOUT - 1) + ) + pw._dispatch_ready_chunked_requests() + assert pw._pending_chunked_requests, "a registered transfer must keep waiting" + pw._notify_transfer_result.assert_not_called() + + +# ------------------------------- a retired transfer releases its early source + + +def test_worker_reports_a_retired_transfers_source_safe(): + """A save for a transfer the worker already retired creates no source + (no reader can acquire it), so the worker reports the send claim safe; + `continue`-ing silently left the finished request's blocks and state slot + deferred forever (c2048 hang).""" + from atom.kv_transfer.disaggregation.types import ConnectorMetadata + + pw, _, _, _ = idle_producer() + with pw._completed_prefills_lock: + pw._retire_chunked_transfer(TRANSFER) + meta = ConnectorMetadata() + meta.add_new_req_to_save( + 7, + [0, 1, 2], + {"transfer_id": TRANSFER, "chunked_transfer": True, "num_prompt_tokens": 10}, + ) + pw.start_load_kv(meta) + assert TRANSFER not in pw._chunked_prefills + out = pw.get_finished() + assert mc.ConnectorCompletion("pd_source_safe", 7, True) in ( + out.connector_completions + ) + + +def test_flag_off_router_chunked_retired_transfer_releases_only_its_own_claim( + monkeypatch, seq_factory +): + """Main's router-chunked mode, ATOM_PD_EARLY_HANDOFF=0. There P + allocates only after D reached it, so a save can meet a retired transfer + only as the cancellation of a request that never got a source: D's write + request expired as an orphan (P stuck in a long step), P's registration is + then refused, and the aborted request's cancellation reaches the worker. + The worker now reports that save safe once; the scheduler finds no claim + and no deferred blocks, so nothing else changes. A repeat is not reported + again. (A late handoff for a transfer that already reported safe stays + silent: `test_late_metadata_cannot_resurrect_retired_source`.)""" + from conftest import MockConfig + from test_pd_chunked_transfer import pd_sequence, scheduler_connector + + from atom.model_engine.scheduler import Scheduler + from atom.model_engine.sequence import SequenceStatus + + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "0") + p = Scheduler(MockConfig()) + p.kv_connector = conn = scheduler_connector(monkeypatch, True) + assert conn.enable_chunked_transfer and not conn._speculative + free = p.block_manager.kv.num_free + pw, request, _src, _dst = idle_producer() + with pw._completed_prefills_lock: + pw._pending_chunked_requests.append( + (request, mc.time.monotonic() - mc.PREFILL_LOOKUP_TIMEOUT - 1) + ) + pw._dispatch_ready_chunked_requests() + pw._notify_transfer_result.assert_called_once_with(request, success=False) + assert dict(pw._retired_chunked_transfers) == {"xfer-a": False} + + seq = pd_sequence(seq_factory) # transfer "xfer-a", as D's write request + p.add(seq) + pw.start_load_kv(conn.build_connector_meta()) + p._update_from_kv_xfer_finished(pw.get_finished()) + assert seq.status == SequenceStatus.ABORTED # a retired ID authorizes nothing + batch, scheduled = p.schedule() + assert not scheduled and not seq.block_table + cancel = batch.connector_meta_output + assert cancel.reqs_to_save[seq.id].prefill_aborted + pw.start_load_kv(cancel) + out = pw.get_finished() + assert out.connector_completions == { + mc.ConnectorCompletion("pd_source_safe", seq.id, True) + } + p._update_from_kv_xfer_finished(out) + assert not conn._awaiting_send and not conn._chunked_waiting + assert not p.deferred_free_blocks and p.block_manager.kv.num_free == free + assert not pw._chunked_prefills and not pw._chunked_local_ids + assert dict(pw._retired_chunked_transfers) == {"xfer-a": True} + pw.start_load_kv(cancel) # a repeated cancellation reports nothing more + assert not pw.get_finished().connector_completions + + +def test_failed_report_for_an_allocated_early_source_aborts_it( + monkeypatch, seq_factory +): + """`pd_admission_ready(False)` for a source allocated before D (not in + `_chunked_waiting` any more) used to be ignored, so P prefilled for + nobody. Now it is marked aborted, as a waiting request refused by the + same report is (and as `Scheduler.abort_request` marks a running one).""" + from atom.model_engine.sequence import SequenceStatus + + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(1, 100), kv_transfer_params=p_params("early-b")) + for s in (a, b): + assert p.admission_ready(s) + _allocate(p, s, [0, 1, 2] if s is a else [3]) + s.status = SequenceStatus.RUNNING + assert set(p._early_sources) == {str(a.id), str(b.id)} + _ack(p, a, succeeded=False) + _ack(p, b) # D reached B: not aborted, no longer tracked + assert a.status == SequenceStatus.ABORTED + assert b.status == SequenceStatus.RUNNING + _ack(p, a, succeeded=False) # a repeated report changes nothing more + assert not p._early_sources and not p._spec_pins + + +def _p_scheduler_with_state_slots(monkeypatch, num_blocks, state_slots): + from conftest import MockConfig + + from atom.model_engine.kv_block import STATE_SLOT_CLASS + from atom.model_engine.scheduler import Scheduler + + p = Scheduler( + MockConfig( + num_kvcache_blocks=num_blocks, + max_num_batched_tokens=4, + pool_entries={STATE_SLOT_CLASS: state_slots}, + ) + ) + p.kv_connector = make_scheduler_connector( + monkeypatch, True, early=True, num_kvcache_blocks=num_blocks + ) + p.kv_connector.bind_block_manager(p.block_manager) # as `Scheduler` does + return p + + +@pytest.mark.parametrize("per_req_state", [False, True]) +def test_p_stall_past_the_lookup_timeout_releases_the_early_source( + monkeypatch, seq_factory, per_req_state +): + """The c2048 P0 wedge, end to end. P allocates an early source before D + (idle pool), then that step stalls past PREFILL_LOOKUP_TIMEOUT before its + metadata (the registration and the save) reaches the worker. D's write + request queues meanwhile; out of the stall, `get_finished` runs before + the metadata and retires it as an orphan, telling D it failed. The + registration and the save then arrive for a retired transfer. + + P must stop the prefill, and the source -- its blocks and its state slot + -- must come back (before the fix: `released 0 of N`, `state: 128/128` + and Running 0 for good). D must abort the receive and free its pages.""" + from atom.model_engine.scheduler import ScheduledBatchOutput + from atom.model_engine.sequence import SequenceStatus + from atom.sampling_params import SamplingParams + + monkeypatch.setattr(mc, "PREFILL_LOOKUP_TIMEOUT", 0.05) + monkeypatch.setenv("ATOM_PD_FAILED_WRITE_HOLD_S", "0") + p = _p_scheduler_with_state_slots(monkeypatch, 6, 1 if per_req_state else 0) + d = _d_scheduler(monkeypatch) + ps = seq_factory( + _prompt(3), + sampling_params=SamplingParams(max_tokens=1), + kv_transfer_params=p_params(TRANSFER), + has_per_req_cache=per_req_state, + ) + _, ds = _pair(seq_factory, TRANSFER, _prompt(3)) + pw, _, _src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + results = [] + _wire(pw, dw, results) + p_free, d_free = p.block_manager.kv.num_free, d.block_manager.kv.num_free + + p.extend([ps]) + batch, seqs = p.schedule() + assert list(seqs) == [ps.id] and str(ps.id) in p.kv_connector._spec_pins + if per_req_state: + assert ps.state_slot >= 0 and not p.block_manager.state.has_free(1) + stalled_meta = batch.connector_meta_output # this step stalls + # D got P's early answer and reaches P's listener during the stall. + d.extend([ds]) + d_batch, _ = d.schedule() + dw.start_load_kv(d_batch.connector_meta_output) + post_write_requests(dw, monkeypatch) + assert pw._pending_chunked_requests + time.sleep(0.1) # the stall outlasts the (shortened) lookup timeout + # Out of the stall: get_finished runs before the step's metadata. + p._update_from_kv_xfer_finished(pw.get_finished()) + assert results == [(TRANSFER, False)] # retired as an orphan, D told + pw.start_load_kv(stalled_meta) # registration + save of a retired transfer + p._update_from_kv_xfer_finished(pw.get_finished()) + assert ps.status == SequenceStatus.ABORTED, "P must not prefill for nobody" + # The stalled forward returns; the aborted request leaves. + p.postprocess( + [ps], ScheduledBatchOutput([ps.id], [(42,)], None, None, None), batch=batch + ) + pw.start_load_kv(p.kv_connector.build_connector_meta()) + p._update_from_kv_xfer_finished(pw.get_finished()) + assert ps.status == SequenceStatus.FINISHED and ps.leave_reason == "aborted" + assert not p.deferred_free_blocks and not ps.block_table + assert p.block_manager.kv.num_free == p_free + if per_req_state: + assert p.block_manager.state.has_free(1) + conn = p.kv_connector + assert not conn._spec_pins and not conn._early_sources + assert not conn._awaiting_send and not conn._chunked_waiting + assert not pw._chunked_prefills and not pw._chunked_local_ids + # D gives up on the receive and frees its reservation. + d._update_from_kv_xfer_finished(dw.get_finished()) + assert ds.leave_reason == "aborted" + assert d.block_manager.kv.num_free == d_free + + # The rank is not wedged: the next early request allocates (its state + # slot included) and completes with D. + ps2, ds2 = _pair(seq_factory, "early-next", _prompt(3, 100)) + ps2.has_per_req_cache = per_req_state + p.extend([ps2]) + d.extend([ds2]) + finished, _ = _drive(p, d, pw, dw, monkeypatch, lambda f: ds2 in f) + assert ds2 in finished and ("early-next", True) in results + assert not p.deferred_free_blocks and p.block_manager.kv.num_free == p_free + + +def _bind(p, *, usable_pages, state_slots=0, per_req=1, reserve_null_block=False): + """`bind_block_manager` with a real `BlockPool` for the pages.""" + from atom.model_engine.block_pool import BlockPool + + pages = usable_pages + int(reserve_null_block) + kv = BlockPool(pages, reserve_null_block=reserve_null_block) + assert kv.num_usable_blocks == usable_pages + p.bind_block_manager( + SimpleNamespace(kv=kv, num_state_slots=state_slots, state_slots_per_req=per_req) + ) + + +def test_the_rule_counts_only_the_allocators_usable_pages(monkeypatch, seq_factory): + """Copilot: a checkpoint-enabled pool reserves a null block that + `num_kvcache_blocks` still counts. Seven physical blocks, six usable: + A (3) + room for B (4) does not fit, so A waits for D.""" + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=7) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(4, 100), kv_transfer_params=p_params("early-b")) + p.admission_ready(a) + p.admission_ready(b) + assert p.admission_ready(a) # 3 + 4 <= 7 before the allocator is known + _bind(p, usable_pages=6, reserve_null_block=True) + assert not p.admission_ready(a) # 3 + 4 > 6 usable + assert not p.admission_ready(b) + + +def test_state_slots_keep_a_stateful_request_behind_the_gate(monkeypatch, seq_factory): + """Copilot: six pages and one state slot on P. Pages alone admit A + (3 + 3 <= 6) though B is registered; if D reserves B first, A would hold + the only slot and B could not allocate. The rule keeps room for B's slot + too, so both wait for D, and B goes first when D reaches it.""" + p = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + a = seq_factory(_prompt(3), kv_transfer_params=p_params("early-a")) + b = seq_factory(_prompt(3, 100), kv_transfer_params=p_params("early-b")) + a.has_per_req_cache = b.has_per_req_cache = True + p.admission_ready(a) + p.admission_ready(b) + assert not p.admission_ready(a) # slots unknown before the bind: the gate + _bind(p, usable_pages=6, state_slots=1) + assert not p.admission_ready(a) # 1 + room for B's slot > 1 + assert not p.admission_ready(b) + _ack(p, b) # D reached B first: the opposite order + assert p.admission_ready(b) + _allocate(p, b, [0, 1, 2]) + assert not p._spec_pins and not p._spec_state_pins + # With two slots A may go before D, and its slot counts until D's report. + p2 = make_scheduler_connector(monkeypatch, True, early=True, num_kvcache_blocks=6) + _bind(p2, usable_pages=6, state_slots=2) + c = seq_factory(_prompt(1, 200), kv_transfer_params=p_params("early-c")) + d = seq_factory(_prompt(1, 300), kv_transfer_params=p_params("early-d")) + e = seq_factory(_prompt(1, 400), kv_transfer_params=p_params("early-e")) + for s in (c, d, e): + s.has_per_req_cache = True + p2.admission_ready(s) + assert p2.admission_ready(c) # 0 pinned + 1 + 1 <= 2 + _allocate(p2, c, [0]) + assert p2._spec_state_pins == {str(c.id)} + assert not p2.admission_ready(d) # 1 pinned + 1 + room for E > 2 + _ack(p2, c) + assert not p2._spec_state_pins and p2.admission_ready(d) + + +def test_stateful_requests_complete_when_d_reserves_the_other_first( + monkeypatch, seq_factory +): + """The same case with real schedulers and workers: P has six pages and + one state slot, D room for one request and D reserves B first. Before the + fix A took P's only slot before D, B could not allocate, and both stalled + until the lookup timeout aborted A.""" + p = _p_scheduler_with_state_slots(monkeypatch, 6, 1) + d = _d_scheduler(monkeypatch, num_blocks=3) + pa, da = _pair(seq_factory, "early-a", _prompt(3)) + pb, db = _pair(seq_factory, "early-b", _prompt(3, 100)) + pa.has_per_req_cache = pb.has_per_req_cache = True + p.extend([pa, pb]) + d.extend([db, da]) # D reserves B first; A waits for D's room + pw, _, _src, destinations = idle_producer() + dw = decode_worker(destinations[0]) + results = [] + _wire(pw, dw, results) + finished, started = _drive(p, d, pw, dw, monkeypatch, lambda f: len(f) == 2) + assert {s.id for s in finished} == {da.id, db.id} + assert started == [pb.id, pa.id] + assert ("early-a", True) in results and ("early-b", True) in results + assert p.block_manager.state.has_free(1) + assert not p.deferred_free_blocks and not d.deferred_free_blocks + + +# ----------------------------------------------------- negotiation (P and D API) + + +@pytest.fixture +def api(monkeypatch): + from atom.entrypoints.openai import api_server + + monkeypatch.setattr(api_server, "_early_handoff_endpoint_cache", []) + monkeypatch.setattr("atom.utils.network.get_ip", lambda: "10.0.0.1") + return api_server + + +def _config(role="kv_producer", **kw): + sub = {"kv_connector": "mooncake", "kv_role": role, "handshake_port": 31520} + cfg = SimpleNamespace( + kv_transfer_config={"kv_connector": "multi", "connectors": [sub]}, + tensor_parallel_size=kw.get("tp", 1), + pipeline_parallel_size=kw.get("pp", 1), + kv_cache_block_size=16, + decode_context_parallel_size=kw.get("dcp", 1), + parallel_config=SimpleNamespace( + is_multinode_dp=kw.get("multinode", False), data_parallel_size=4 + ), + hf_config=SimpleNamespace(model_type=kw.get("model_type", "deepseek_v3")), + ) + return cfg, sub + + +def _engine(api, monkeypatch, *, rank=2, multinode=False, cfg=None): + seq = SimpleNamespace( + id=11, + prompt_token_ids=[1, 2, 3], + num_prompt_tokens=3, + max_tokens=1, + pd_routed_dp_rank=None, + ) + calls = SimpleNamespace(aborted=[], params=None, callback=None) + + def preprocess(_prompt, _sampling, stream_callback=None, **kw): + calls.params = kw["kv_transfer_params"] + calls.callback = stream_callback + return seq + + class CoreMgr: + reports_dp_rank = True + + def add_request(self, seqs): + if rank is not None: + seqs[0].pd_routed_dp_rank = rank + + def abort_request(self, seq_id): + calls.aborted.append(seq_id) + + if cfg is None: + cfg, _ = _config(multinode=multinode) + engine = SimpleNamespace( + io_processor=SimpleNamespace(preprocess=preprocess, requests={11: seq}), + core_mgr=CoreMgr(), + config=cfg, + ) + monkeypatch.setattr(api, "engine", engine) + monkeypatch.setattr(api, "_validate_sequence_context_length", lambda *_a: None) + return seq, calls + + +ROUTER_ASKS = { + "do_remote_decode": True, + "do_remote_prefill": False, + "early_handoff": True, +} + + +def _finished(calls, reason="length"): + calls.callback( + SimpleNamespace( + output_tokens=[5], + logprobs=None, + finished=True, + finish_reason=reason, + num_cached_tokens=0, + kv_transfer_params_output=None, + ) + ) + + +@pytest.mark.parametrize("flag", ["0", "1"]) +def test_p_offers_early_handoff_only_with_the_flag(monkeypatch, api, flag): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", flag) + _engine(api, monkeypatch) + info = asyncio.run(api.kv_transfer_info()) + assert info["kv_role"] == "kv_producer" + assert "chunked_transfer" not in info and "chunked_receive" not in info + assert ("early_handoff" in info) is (flag == "1") + if flag == "1": + assert info["early_handoff"] == {"version": 1} + + +def test_default_on_with_an_incompatible_d_keeps_the_legacy_relay(monkeypatch, api): + """ATOM_PD_EARLY_HANDOFF unset (on by default): P offers early handoff, + a Kimi-K3 DCP8 D declares it cannot receive chunked transfer, so the + router does not ask and P answers after its prefill (legacy relay); were + chunked metadata sent anyway, D would refuse it.""" + from fastapi import HTTPException + + monkeypatch.delenv("ATOM_PD_EARLY_HANDOFF", raising=False) + d_cfg, _ = _config("kv_consumer", tp=8, dcp=8, model_type="kimi_linear") + _engine(api, monkeypatch, cfg=d_cfg) + assert asyncio.run(api.kv_transfer_info())["chunked_receive"]["accepts"] is False + with pytest.raises(HTTPException): + api._validate_chunked_receive( + {"chunked_transfer": True, "do_remote_prefill": True, "remote_tp_size": 1} + ) + + api._early_handoff_endpoint_cache.clear() + _engine(api, monkeypatch) + assert asyncio.run(api.kv_transfer_info())["early_handoff"] == {"version": 1} + # The router's request for an incompatible D carries no `early_handoff`. + assert api._early_handoff_params({"do_remote_decode": True}) is None + + +def test_default_on_with_a_compatible_pair_answers_early(monkeypatch, api): + """ATOM_PD_EARLY_HANDOFF unset: a compatible D declares it can receive, + the router asks, and P answers at dispatch with chunked metadata.""" + monkeypatch.delenv("ATOM_PD_EARLY_HANDOFF", raising=False) + d_cfg, _ = _config("kv_consumer", tp=8) + _engine(api, monkeypatch, cfg=d_cfg) + cap = asyncio.run(api.kv_transfer_info())["chunked_receive"] + assert cap["accepts"] is True and cap["tp_size"] == 8 + + api._early_handoff_endpoint_cache.clear() + _, calls = _engine(api, monkeypatch) + assert asyncio.run(api.kv_transfer_info())["early_handoff"] == {"version": 1} + assert api._early_handoff_params(dict(ROUTER_ASKS)) is not None + + async def go(): + (out,) = [o async for o in _generate(api, dict(ROUTER_ASKS))] + kv = out["kv_transfer_output_meta_info"] + assert kv["chunked_transfer"] is True + assert kv["transfer_id"].startswith("early-") + assert calls.params["pd_early_handoff"] is True + _finished(calls) + + asyncio.run(go()) + + +def test_router_chunked_mode_takes_precedence(monkeypatch, api): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _engine(api, monkeypatch) + (sub,) = api.engine.config.kv_transfer_config["connectors"] + sub["enable_chunked_transfer"] = True + info = asyncio.run(api.kv_transfer_info()) + assert info["chunked_transfer"]["remote_handshake_port"] == 31520 + assert "early_handoff" not in info + + +@pytest.mark.parametrize( + "shape,accepts", + [ + ({}, True), + ({"tp": 8, "dcp": 8, "model_type": "deepseek_v3"}, True), # GLM/DSA-like DCP + ({"tp": 8, "dcp": 8, "model_type": "kimi_linear"}, False), # Kimi-K3 D + ({"tp": 8, "dcp": 8, "model_type": "deepseek_v4"}, False), # V4.1 under DCP + ({"pp": 2}, False), + ], +) +def test_d_declares_what_it_can_receive_and_refuses_exactly_that( + monkeypatch, api, shape, accepts +): + """D's declaration and D's 400 come from the same checks: whatever D + declares it cannot receive, it also refuses; whatever it declares it can, + it accepts (from a P whose TP divides D's).""" + from fastapi import HTTPException + + from atom.model_engine.llm_engine import InputOutputProcessor + + if "model_type" in shape and not accepts: + # The shapes this test calls per-request-state models must be ones. + assert shape["model_type"] in InputOutputProcessor._per_req_cache_model_types() + cfg, _ = _config("kv_consumer", **shape) + _engine(api, monkeypatch, cfg=cfg) + info = asyncio.run(api.kv_transfer_info()) + assert info["kv_role"] == "kv_consumer" + cap = info["chunked_receive"] + assert cap["accepts"] is accepts + assert cap["tp_size"] == cfg.tensor_parallel_size + assert (cap["reason"] is None) is accepts + params = {"chunked_transfer": True, "do_remote_prefill": True, "remote_tp_size": 1} + if accepts: + api._validate_chunked_receive(params) + else: + with pytest.raises(HTTPException) as err: + api._validate_chunked_receive(params) + assert err.value.status_code == 400 + + +def test_a_d_without_a_mooncake_consumer_declares_no_receive(monkeypatch, api): + cfg, sub = _config("kv_consumer") + sub["kv_connector"] = "moriio" + _engine(api, monkeypatch, cfg=cfg) + cap = api.chunked_receive_capability(cfg) + assert cap["accepts"] is False and "Mooncake" in cap["reason"] + + +@pytest.mark.parametrize( + "flag,params,multinode", + [ + ("0", ROUTER_ASKS, False), # P does not offer it + ("1", {"do_remote_decode": True}, False), # router did not ask + ("1", ROUTER_ASKS, True), # multi-node DP + ("1", None, False), # not a PD prefill leg + ("1", {"do_remote_prefill": True, "early_handoff": True}, False), + ("1", {**ROUTER_ASKS, "chunked_transfer": True}, False), + ], +) +def test_p_answers_after_prefill_unless_asked_and_able( + monkeypatch, api, flag, params, multinode +): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", flag) + _engine(api, monkeypatch, multinode=multinode) + assert api._early_handoff_params(params) is None + + +def test_core_managers_that_do_not_report_the_rank_keep_the_legacy_path( + monkeypatch, api +): + from aiter_stub import stubbed_aiter + + with stubbed_aiter(): + from atom.entrypoints.openai.frontend_workers import RemoteCoreManager + from atom.model_engine.engine_core_mgr import CoreManager, DisaggCoreManager + + assert CoreManager.reports_dp_rank is True + assert DisaggCoreManager.reports_dp_rank is False + assert RemoteCoreManager.reports_dp_rank is False + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + for mgr_cls in (DisaggCoreManager, RemoteCoreManager): + _engine(api, monkeypatch) + api.engine.core_mgr = mgr_cls.__new__(mgr_cls) + api._early_handoff_endpoint_cache.clear() + assert api._early_handoff_params(ROUTER_ASKS) is None + assert "early_handoff" not in asyncio.run(api.kv_transfer_info()) + _engine(api, monkeypatch) + api.engine.core_mgr = CoreManager.__new__(CoreManager) + api._early_handoff_endpoint_cache.clear() + assert api._early_handoff_params(ROUTER_ASKS) is not None + + +def _generate(api, params, return_ids=True): + from atom.sampling_params import SamplingParams + + return api.generate_async( + [1, 2, 3], + SamplingParams(max_tokens=1), + "req", + kv_transfer_params=params, + return_token_ids=return_ids, + ) + + +async def _body_lines(response): + lines = [] + async for chunk in response.body_iterator: + lines.append(chunk if isinstance(chunk, str) else chunk.decode()) + return lines + + +def test_p_answers_at_dispatch_and_ends_the_body_when_the_prefill_ends( + monkeypatch, api +): + """Line 1 leaves at dispatch with the chunked metadata; line 2 only once + the engine finished the prefill. A router reading the body to its end + therefore holds P's load for the whole prefill.""" + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _, calls = _engine(api, monkeypatch) + + async def go(): + (out,) = [o async for o in _generate(api, dict(ROUTER_ASKS))] + kv = out["kv_transfer_output_meta_info"] + tid = kv["transfer_id"] + assert tid.startswith("early-") + assert calls.params == { + "do_remote_decode": True, + "do_remote_prefill": False, + "chunked_transfer": True, + "transfer_id": tid, + "pd_early_handoff": True, + } + assert kv == { + "remote_host": "10.0.0.1", + "remote_handshake_port": 31520, + "remote_pp_size": 1, + "block_size": 16, + "dcp_size": 1, + "tp_size": 1, + "do_remote_prefill": True, + "do_remote_decode": False, + "chunked_transfer": True, + "transfer_id": tid, + "dp_rank": 2, + } + body = {"kv_transfer_params": kv, "prompt_token_ids": out["prompt_token_ids"]} + response = api._nonstream_response(body, out) + assert response.headers[api.EARLY_HANDOFF_HEADER] == "1" + assert response.media_type == "application/x-ndjson" + it = response.body_iterator + line1 = await it.__anext__() + assert json.loads(line1) == body + line2 = asyncio.ensure_future(it.__anext__()) + await asyncio.sleep(0.05) + assert not line2.done(), "line 2 must wait for the end of the prefill" + assert 11 in api.engine.io_processor.requests + _finished(calls) + assert json.loads(await line2) == { + api.EARLY_HANDOFF_DONE_KEY: {"ok": True, "finish_reason": "length"} + } + with pytest.raises(StopAsyncIteration): + await it.__anext__() + assert 11 not in api.engine.io_processor.requests + + asyncio.run(go()) + assert calls.aborted == [] + + +def test_p_failure_after_the_early_answer_reaches_the_router(monkeypatch, api): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _, calls = _engine(api, monkeypatch) + + async def go(): + (out,) = [o async for o in _generate(api, dict(ROUTER_ASKS))] + response = api._nonstream_response({"x": 1}, out) + _finished(calls, reason="aborted") + lines = await _body_lines(response) + assert json.loads(lines[1])[api.EARLY_HANDOFF_DONE_KEY]["ok"] is False + + asyncio.run(go()) + + +def test_router_hanging_up_aborts_the_prefill(monkeypatch, api): + """D failed (or the client left) and the router dropped P's body: nobody + will read this prefill, so P stops computing it.""" + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _, calls = _engine(api, monkeypatch) + + async def go(): + (out,) = [o async for o in _generate(api, dict(ROUTER_ASKS))] + response = api._nonstream_response({"x": 1}, out) + it = response.body_iterator + await it.__anext__() + pending = asyncio.ensure_future(it.__anext__()) + await asyncio.sleep(0.01) + pending.cancel() # Starlette cancels the body on http.disconnect + with pytest.raises(asyncio.CancelledError): + await pending + await asyncio.sleep(0) + assert 11 not in api.engine.io_processor.requests + + asyncio.run(go()) + assert calls.aborted == [11] + + +def test_legacy_answer_is_plain_json(monkeypatch, api): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _engine(api, monkeypatch) + response = api._nonstream_response({"x": 1}, {"text": ""}) + assert response.media_type == "application/json" + assert api.EARLY_HANDOFF_HEADER not in response.headers + + +def test_p_fails_closed_without_a_rank(monkeypatch, api): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _, calls = _engine(api, monkeypatch, rank=None) + + async def go(): + return [o async for o in _generate(api, dict(ROUTER_ASKS))] + + with pytest.raises(RuntimeError, match="DP rank unknown"): + asyncio.run(go()) + assert calls.aborted == [11] + assert 11 not in api.engine.io_processor.requests + + +def test_early_answer_carries_the_pp_size(monkeypatch, api): + monkeypatch.setenv("ATOM_PD_EARLY_HANDOFF", "1") + _engine(api, monkeypatch, rank=0) + api.engine.config.pipeline_parallel_size = 2 + + async def go(): + (out,) = [o async for o in _generate(api, dict(ROUTER_ASKS))] + out["_early_prefill"].task.cancel() + return out + + kv = asyncio.run(go())["kv_transfer_output_meta_info"] + assert kv["remote_pp_size"] == 2 and kv["dp_rank"] == 0 + + +@pytest.mark.parametrize( + "reason,ok", + [ + ("length", True), + ("stop", True), + ("aborted", False), + ("unschedulable: too long", False), + ("logprob_error", False), + (None, False), + ], +) +def test_prefill_success_follows_the_engine_leave_reason(api, reason, ok): + assert api._prefill_succeeded(reason) is ok + + +# --------------------------------------------- CoreManager: dispatched DP rank + + +def test_unset_routed_rank_is_not_pickled(seq_factory): + import pickle + + seq = seq_factory([1, 2, 3]) + assert seq.pd_routed_dp_rank is None + assert "pd_routed_dp_rank" not in seq.__getstate__() + seq.pd_routed_dp_rank = 3 + assert pickle.loads(pickle.dumps(seq)).pd_routed_dp_rank == 3 + + +def _core_mgr(monkeypatch, *, pp_size=1, engines=1): + from aiter_stub import stubbed_aiter + + with stubbed_aiter(): + from atom.model_engine import engine_core_mgr as ecm + + mgr = ecm.CoreManager.__new__(ecm.CoreManager) + mgr.label = "t" + mgr.pp_size = pp_size + mgr._seq_id_to_callback = {} + sent = [] + mgr._send_request = lambda rank, frame: sent.append(rank) + monkeypatch.setattr(ecm, "_add_frame", lambda seqs: b"") + monkeypatch.setattr( + ecm.CoreManager, "_routable_engine_count", engines, raising=False + ) + monkeypatch.setattr(ecm.tracing, "bind_sequences", lambda _s: None) + return mgr, sent + + +@pytest.mark.parametrize("pp_size", [1, 2, 4]) +def test_core_manager_reports_rank_0_for_a_single_engine_or_pp_head( + monkeypatch, pp_size +): + mgr, sent = _core_mgr(monkeypatch, pp_size=pp_size) + seqs = [SimpleNamespace(id=i, stream_callback=None) for i in range(2)] + mgr._add_prepared_requests(seqs) + assert [s.pd_routed_dp_rank for s in seqs] == [0, 0] and sent == [0] + + +def test_dispatch_to_dp_ranks_records_each_rank_after_the_send(): + import pickle + + from test_dp_load_balance import _FakeSeq, _make_mgr + + class Socket: + def __init__(self, fail=False): + self.fail, self.messages = fail, [] + + def send_multipart(self, parts, copy=False): + if self.fail: + raise RuntimeError("send failed") + self.messages.append(parts) + + mgr = _make_mgr(4, strategy="least_requests") + mgr.engine_core_identities = [b"e0", b"e1", b"e2", b"e3"] + mgr.input_sockets = [Socket() for _ in range(4)] + seqs = [_FakeSeq(i, 10, data_parallel_rank=r) for i, r in enumerate([2, 0, 3])] + seqs.append(_FakeSeq(3, 10)) # load-balanced: the only idle rank, 1 + mgr._dispatch_to_dp_ranks(seqs) + assert [s.pd_routed_dp_rank for s in seqs] == [2, 0, 3, 1] + for sock in mgr.input_sockets: + (msg,) = sock.messages + _, sent = pickle.loads(msg[1]) + assert all(not hasattr(s, "pd_routed_dp_rank") for s in sent) + + mgr = _make_mgr(4, strategy="least_requests") + mgr.engine_core_identities = [b"e0", b"e1", b"e2", b"e3"] + mgr.input_sockets = [Socket(), Socket(fail=True), Socket(), Socket()] + seqs = [_FakeSeq(10 + r, 10, data_parallel_rank=r) for r in range(4)] + with pytest.raises(RuntimeError): + mgr._dispatch_to_dp_ranks(seqs) + assert [getattr(s, "pd_routed_dp_rank", None) for s in seqs] == [ + 0, + None, + None, + None, + ] + + +def test_router_kill_switch_is_documented(): + """The router's early-handoff switch (read in Rust, not `envs.py`) has a + row in the env reference like every `ATOM_PD_*` knob.""" + import re + from pathlib import Path + + root = Path(__file__).parents[1] + rust = (root / "atom/mesh/src/core/placement/backend/atom.rs").read_text() + name = re.search(r'EARLY_HANDOFF_ENV: &str = "([A-Z_]+)"', rust).group(1) + doc = (root / "docs/environment_variables.md").read_text() + assert f"**{name}**" in doc diff --git a/tests/test_pd_pp.py b/tests/test_pd_pp.py index 5b43bd48f34..3850fcd297e 100644 --- a/tests/test_pd_pp.py +++ b/tests/test_pd_pp.py @@ -371,6 +371,7 @@ def _mooncake_consumer_scheduler(mc, block_size=64, dcp_size=1): sched._pending_chunked_admissions = {} sched._chunked_waiting = {} sched._chunked_ready = set() + sched._speculative = False return sched diff --git a/tests/test_pd_source_claim.py b/tests/test_pd_source_claim.py index b2bf72ffaeb..998497b6935 100644 --- a/tests/test_pd_source_claim.py +++ b/tests/test_pd_source_claim.py @@ -71,6 +71,8 @@ def _mooncake(is_producer=True): dcp_size=1, hash_block_size=16, pp_size=1, + # Early handoff off: no early-handoff state may be touched. + _speculative=False, )