Skip to content

Commit 13d1d28

Browse files
junyyang-amdclaude
andauthored
feat(engine): multimodal PD through the chat path (#3410)
* feat(engine): multimodal PD through the chat path Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * PD image decode: MRoPE delta reaches decode positions, cache_seed gate, handoff key checks (#155) fix(engine): image PD decode positions, cache_seed gate, handoff key checks Answers valarLip's review on #3410: - A decode leg's mrope_position_delta reaches the batch (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions whose delta is nonzero), so MRoPE models decode at the right positions. - A decode leg skips its media only when kv_transfer_params carries cache_seed; otherwise the media is preprocessed as before. - cache_seed and mrope_position_delta in kv_transfer_params must be ints, else 400 before enqueue (check_media_handoff). - Preemption reads Sequence.media_on_prefill_instance. - generate_async_multimodal reads kv_transfer_params_output directly. MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070 for the single instance at this head, 0 failed requests. Closes #147. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(engine): image PD decode positions, cache_seed gate, handoff key checks Answers the review on #3410: - A decode leg's mrope_position_delta reaches the batch (ScheduledBatch.mrope_position_deltas keeps a seq without mrope_positions whose delta is nonzero), so MRoPE models decode at the right positions. - A decode leg skips its media only when kv_transfer_params carries cache_seed; otherwise the media is preprocessed as before. - cache_seed and mrope_position_delta in kv_transfer_params must be ints, else 400 before enqueue (check_media_handoff). - Preemption reads Sequence.media_on_prefill_instance. - generate_async_multimodal reads kv_transfer_params_output directly. MiniMax-M3.1-Flash full MMStar through 1P1D scores 0.7305 against 0.7070 for the single instance at this commit, 0 failed requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style(tests): sort imports in test_pd_prompt_token_ids.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * tests: drop the duplicate conftest import the up-e1 sync merge left Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * up-e1: no local prefill of a media-dropped image decode leg; handoff keys checked on every endpoint (#181) A chat decode leg whose prefill kept the image is no longer prefilled locally (no KV connector, an offload resume, a moriio requeue, a tier load declined after allocation): the scheduler finishes it as unschedulable. `leaves_media_on_prefill` in `sequence.py` marks such a leg, and only it reads `cache_seed` and `mrope_position_delta`. Both keys are range-checked as a 400 on chat, completions, `/v1/messages`, `/v1/responses` and the standalone service when `kv_transfer_params` is set. The decode-position arithmetic moves to `token_layout/decode.py` (`mrope_decode_positions`). `docs/api_image_input.md` describes the chat image P/D contract, including that an offload-tier D refuses image decode legs. Closes #180. * Media-dropped leg test: main's connector interface and its early-load way in The test's SimpleNamespace connectors lacked the scheduler capability defaults main added (lookup_pending, supports_early_load); build them on the shared KVConnectorSchedulerBase stub instead. Add main's early tier load as a way in: the leg resumes from it and is refused there too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * up-e1: no per-request cost on the text path; prompt-bounded MRoPE delta; DSpark and RapidServe refuse a media-dropped leg - Sequence: media_on_prefill_instance is a class default, set only when a request carries kv_transfer_params; the scheduler's refusals and the HTTP and standalone handoff checks run only for a request with params. - The engine intake refuses a handed-off mrope_position_delta outside [1 - prompt length, 0], refuses a media-dropped leg on RapidServe (whose prefill never reaches Scheduler.schedule), and tells the model's request validator about it: DeepSeek-V4.1 refuses DSpark on it. - mrope_decode_positions is decode_positions plus the repeated deltas. - The offload-tier D text is gone; the refusal's ways in are tested as they arise: a failed receive is new, the tier cases run on an offload-only instance. - A fresh image leg waits for its remote KV; stale test and proto text fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f343ede commit 13d1d28

13 files changed

Lines changed: 811 additions & 44 deletions

File tree

‎atom/entrypoints/openai/api_server.py‎

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
from atom.model_engine.llm_engine import InputOutputProcessor, load_tokenizer
5454
from atom.model_engine.request import RequestOutput
5555
from atom.model_engine.segment_tokenizer import PrefixEncoding
56-
from atom.model_engine.sequence import new_token_ids
56+
from atom.model_engine.sequence import leaves_media_on_prefill, new_token_ids
5757
from atom.multimodal.processing import prepare_multimodal_inputs
5858
from atom.multimodal.registry import get_native_multimodal_processor
5959
from atom.observability.tracing import TraceMiddleware, set_request_id
@@ -108,6 +108,7 @@
108108
CompletionRequest,
109109
ModelCard,
110110
ModelList,
111+
check_media_handoff,
111112
ended_by_stop,
112113
validate_max_tokens,
113114
)
@@ -1064,6 +1065,7 @@ async def generate_async_multimodal(
10641065
multimodal_data: dict[str, Any],
10651066
sampling_params: SamplingParams,
10661067
request_id: str,
1068+
kv_transfer_params: dict[str, Any] | None = None,
10671069
data_parallel_rank: int | None = None,
10681070
dp_session_id: str | None = None,
10691071
dp_parent_session_id: str | None = None,
@@ -1079,8 +1081,11 @@ async def generate_async_multimodal(
10791081
all_token_ids = new_token_ids()
10801082
finish_reason: str | None = None
10811083
seq = None
1084+
kv_transfer_output_meta_info = None
10821085

10831086
def completion_callback(request_output: RequestOutput):
1087+
nonlocal kv_transfer_output_meta_info
1088+
kv_transfer_output_meta_info = request_output.kv_transfer_params_output
10841089
now = time.time()
10851090
loop.call_soon_threadsafe(
10861091
token_queue.put_nowait,
@@ -1097,6 +1102,7 @@ def do_preprocess():
10971102
token_ids,
10981103
sampling_params,
10991104
stream_callback=completion_callback,
1105+
kv_transfer_params=kv_transfer_params,
11001106
multimodal_data=multimodal_data,
11011107
data_parallel_rank=data_parallel_rank,
11021108
dp_session_id=dp_session_id,
@@ -1158,6 +1164,13 @@ def do_preprocess():
11581164
"tpot": tpot,
11591165
"latency": finished_at - started_at,
11601166
}
1167+
if kv_transfer_output_meta_info is not None:
1168+
# Decode has no media: it seeds its prefix cache and positions with these.
1169+
response["kv_transfer_output_meta_info"] = {
1170+
**kv_transfer_output_meta_info,
1171+
"cache_seed": seq.cache_seed,
1172+
"mrope_position_delta": seq.mrope_position_delta,
1173+
}
11611174
if return_token_ids and seq is not None:
11621175
response["prompt_token_ids"] = list(seq.prompt_token_ids)
11631176
yield response
@@ -1368,6 +1381,17 @@ def _validate_chunked_receive(params: dict[str, Any] | None) -> None:
13681381
)
13691382

13701383

1384+
def _validate_kv_transfer_params(params: dict[str, Any] | None) -> None:
1385+
"""Refuse handoff metadata no leg can serve, before enqueue or SSE headers.
1386+
1387+
Every endpoint that takes `kv_transfer_params` calls this first.
1388+
"""
1389+
if not params:
1390+
return
1391+
_validate_chunked_receive(params)
1392+
check_media_handoff(params, _get_engine_max_model_len())
1393+
1394+
13711395
def _engine_kv_transfer_params(
13721396
kv_transfer_params: dict[str, Any] | None,
13731397
) -> dict[str, Any] | None:
@@ -1439,8 +1463,10 @@ async def _prepare_engine_input(
14391463
on the chat path, one without through ``_prepare_prompt``."""
14401464
if _has_multimodal_content(messages):
14411465
if kv_transfer_params is not None:
1442-
# A prefill leg cannot hand an image request off, so neither leg
1443-
# can finish it: refused here, not as a router error or a stall.
1466+
# Only `/v1/chat/completions` hands an image request off (its
1467+
# prefill returns the cache seed and MRoPE delta the decode needs);
1468+
# here neither leg could finish it: refused, not a router error or
1469+
# a stall.
14441470
raise ValueError("image input cannot be combined with kv_transfer_params")
14451471
_get_multimodal_processor() # on the loop, as the chat path does
14461472
token_ids, multimodal_data = await asyncio.to_thread(
@@ -2128,7 +2154,7 @@ async def _chat_completions(
21282154
beta = isinstance(request, BetaChatCompletionRequest)
21292155
route = "beta_chat_completions" if beta else "chat_completions"
21302156
validate_model(request.model)
2131-
_validate_chunked_receive(request.kv_transfer_params)
2157+
_validate_kv_transfer_params(request.kv_transfer_params)
21322158

21332159
try:
21342160
request.tools = normalize_chat_tools(request.tools)
@@ -2230,12 +2256,15 @@ async def _chat_completions(
22302256

22312257
_log_request_model("request", request_id, request)
22322258

2233-
is_multimodal = _has_multimodal_content(messages)
22342259
multimodal_data = None
22352260
kv_transfer_params = request.kv_transfer_params
2236-
if assistant_prefix is not None and (
2237-
is_multimodal or request.get_prompt_token_ids() is not None
2238-
):
2261+
pretokenized = request.get_prompt_token_ids()
2262+
# A decode leg takes its prefill's expanded ids; its media went to P.
2263+
# Without P's cache seed its blocks would hash as text: keep the media.
2264+
is_multimodal = _has_multimodal_content(messages) and not (
2265+
pretokenized is not None and leaves_media_on_prefill(kv_transfer_params)
2266+
)
2267+
if assistant_prefix is not None and (is_multimodal or pretokenized is not None):
22392268
# Only rendered text can be continued.
22402269
raise ValueError(
22412270
"an assistant prefix cannot be combined with image input or "
@@ -2255,7 +2284,7 @@ async def _chat_completions(
22552284
merged_kwargs,
22562285
request.tools,
22572286
)
2258-
elif (pretokenized := request.get_prompt_token_ids()) is not None:
2287+
elif pretokenized is not None:
22592288
# Reuse prefill IDs to skip template rendering and tokenization.
22602289
prompt_or_tokens = pretokenized
22612290
kv_transfer_params = _engine_kv_transfer_params(kv_transfer_params)
@@ -2401,6 +2430,7 @@ async def _chat_completions(
24012430
multimodal_data,
24022431
sampling_params,
24032432
request_id,
2433+
kv_transfer_params=kv_transfer_params,
24042434
return_token_ids=bool(request.return_token_ids),
24052435
**dp_routing,
24062436
),
@@ -2628,7 +2658,7 @@ async def _completions(
26282658
beta = isinstance(request, BetaCompletionRequest)
26292659
route = "beta_completions" if beta else "completions"
26302660
validate_model(request.model)
2631-
_validate_chunked_receive(request.kv_transfer_params)
2661+
_validate_kv_transfer_params(request.kv_transfer_params)
26322662

26332663
try:
26342664
effective_n = _coerce_n(request.n, request.temperature)
@@ -2815,7 +2845,7 @@ async def anthropic_messages(request: AnthropicMessagesRequest, raw_request: Req
28152845
and returns Anthropic-formatted responses. Enables Claude Code and other
28162846
Anthropic-compatible tools to use ATOM as a backend.
28172847
"""
2818-
_validate_chunked_receive(request.kv_transfer_params)
2848+
_validate_kv_transfer_params(request.kv_transfer_params)
28192849
# One validator over the shape both endpoints share: this path already
28202850
# converts, so validating the conversion leaves a single rule rather than
28212851
# a second one in Anthropic's spelling. It checked nothing before, so a
@@ -3248,7 +3278,7 @@ async def responses_create(raw_request: Request):
32483278
}
32493279
},
32503280
)
3251-
_validate_chunked_receive(kv_transfer_params)
3281+
_validate_kv_transfer_params(kv_transfer_params)
32523282
kv_transfer_params = _engine_kv_transfer_params(kv_transfer_params)
32533283

32543284
compatibility = api_compatibility_for(custom_message_encoder)

‎atom/entrypoints/openai/protocol.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,40 @@ def validate_max_tokens(max_tokens: int) -> int:
4848
_PROMPT_TOKEN_IDS_ADAPTER = TypeAdapter(PromptTokenIds)
4949

5050

51+
def check_media_handoff(
52+
kv_transfer_params: dict[str, Any], max_model_len: int | None
53+
) -> None:
54+
"""Reject an image handoff key out of range.
55+
56+
`cache_seed` roots a 64-bit prefix hash chain; `mrope_position_delta`
57+
moves decode positions, which must stay within the context.
58+
"""
59+
if "cache_seed" in kv_transfer_params:
60+
seed = kv_transfer_params["cache_seed"]
61+
if type(seed) is not int or not 0 <= seed < 2**64:
62+
raise ValueError(
63+
"kv_transfer_params['cache_seed'] must be an integer in [0, 2**64)"
64+
)
65+
if "mrope_position_delta" in kv_transfer_params:
66+
delta = kv_transfer_params["mrope_position_delta"]
67+
if type(delta) is not int or (
68+
max_model_len is not None and abs(delta) > max_model_len
69+
):
70+
raise ValueError(
71+
"kv_transfer_params['mrope_position_delta'] must be an integer "
72+
f"no larger in magnitude than max_model_len ({max_model_len})"
73+
)
74+
75+
5176
def resolve_prompt_token_ids(
5277
prompt_token_ids: PromptTokenIds | None,
5378
kv_transfer_params: dict[str, Any] | None,
5479
) -> PromptTokenIds | None:
5580
"""Resolve IDs from the top-level field or vLLM-compatible PD metadata.
5681
57-
Reject empty lists and conflicting IDs between the two locations.
82+
On a chat decode leg whose prefill kept the image, these are the
83+
prefill's ids, image placeholders expanded. Reject empty lists and
84+
conflicting IDs between the two locations.
5885
"""
5986
from_kv = (kv_transfer_params or {}).get("prompt_token_ids")
6087
if prompt_token_ids is None and from_kv is None:
@@ -300,7 +327,8 @@ class ChatCompletionRequest(BaseModel):
300327
# Optional KV-transfer metadata for P/D disaggregation.
301328
kv_transfer_params: dict[str, Any] | None = None
302329
data_parallel_rank: int | None = None
303-
# Pre-tokenized text prompt; messages are still required and validated.
330+
# Pre-tokenized prompt (an image decode leg's has its prefill's image
331+
# placeholders expanded); messages are still required and validated.
304332
prompt_token_ids: PromptTokenIds | None = None
305333
# Echo prompt IDs in non-streaming responses, including n > 1.
306334
return_token_ids: bool | None = None

‎atom/model_engine/engine_core.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,9 @@ def prepare_kv_change(self, *, weights: bool, deadline: float) -> None:
527527
Waits until KV transfers in flight have reported back (with
528528
``ATOM_STORE_ASYNC_RENEW`` a load parked on its lease renewal counts,
529529
and the metadata build may dispatch its GET meanwhile), then preempts
530-
what is running so it recomputes on what follows. When the weights
530+
what is running so it recomputes on what follows; an image decode leg
531+
whose media its prefill kept cannot recompute, and is finished
532+
instead (`Scheduler.preempt_running`). When the weights
531533
change, the KV connector must also drop what it keeps for later
532534
requests. Raises with the reason, changing nothing that was running.
533535
"""

‎atom/model_engine/llm_engine.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from atom.model_engine.engine_core_mgr import CoreManager, DisaggCoreManager
1616
from atom.model_engine.prefix_hash import hash_block_size_for, ship_prompt_hash_chain
1717
from atom.model_engine.segment_tokenizer import PrefixEncoding, SegmentTokenizer
18-
from atom.model_engine.sequence import Sequence
18+
from atom.model_engine.sequence import Sequence, leaves_media_on_prefill
1919
from atom.multimodal.registry import get_mrope_input_positions
2020
from atom.sampling_params import RequiredChannel, SamplingParams
2121
from atom.structured_output import is_structured
@@ -876,11 +876,24 @@ def preprocess_fanout(
876876
self.structured_admission(
877877
sampling_params, kv_transfer_params, multimodal_data is not None
878878
)
879+
# A decode leg whose prefill kept the media (`Sequence`'s own test).
880+
media_on_prefill = (
881+
kv_transfer_params is not None
882+
and multimodal_data is None
883+
and leaves_media_on_prefill(kv_transfer_params)
884+
)
885+
if media_on_prefill and self.config.enable_rapidserve:
886+
# RapidServe prefills every request on this GPU, with no media.
887+
raise ValueError(
888+
"RapidServe cannot serve an image decode leg whose prefill "
889+
"kept the image"
890+
)
879891
request_validator = getattr(self.config.hf_config, "validate_request", None)
880892
if request_validator is not None:
881893
request_validator(
882894
num_draft_tokens=self.num_speculative_tokens,
883895
multimodal_data=multimodal_data,
896+
media_on_prefill_instance=media_on_prefill,
884897
enable_dp_attention=self.config.enable_dp_attention,
885898
)
886899
n = max(1, int(getattr(sampling_params, "n", 1)))
@@ -895,6 +908,16 @@ def preprocess_fanout(
895908
else:
896909
prefix_encoding = None
897910
tokens = prompt_or_tokens
911+
if media_on_prefill:
912+
# An image prompt's positions never run past its text's, so the
913+
# delta its prefill hands over is at most 0; decode positions then
914+
# stay in [1, max_model_len).
915+
delta = kv_transfer_params.get("mrope_position_delta", 0)
916+
if not 1 - len(tokens) <= delta <= 0:
917+
raise ValueError(
918+
"kv_transfer_params['mrope_position_delta'] must be in "
919+
f"[{1 - len(tokens)}, 0] for a {len(tokens)}-token prompt"
920+
)
898921
mrope_positions = None
899922
mrope_position_delta = 0
900923
if multimodal_data is not None:

‎atom/model_engine/scheduler.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -362,12 +362,13 @@ def __init__(
362362
self.mrope_positions_by_req = {
363363
seq.id: seq.mrope_positions
364364
for seq in seqs.values()
365-
if getattr(seq, "mrope_positions", None) is not None
365+
if seq.mrope_positions is not None
366366
}
367+
# A decode leg has no positions, only the delta its prefill handed it.
367368
self.mrope_position_deltas = {
368-
seq.id: getattr(seq, "mrope_position_delta", 0)
369+
seq.id: seq.mrope_position_delta
369370
for seq in seqs.values()
370-
if getattr(seq, "mrope_positions", None) is not None
371+
if seq.mrope_positions is not None or seq.mrope_position_delta
371372
}
372373

373374
# num_cached_tokens for chunked prefill support
@@ -687,7 +688,8 @@ class Scheduler:
687688
_ENGINE_LABEL = ""
688689
_METRICS_ROLE = ""
689690
# A preempted sequence recomputes its prompt here, which a KV change relies
690-
# on to keep what was running (see `preempt_running`).
691+
# on to keep what was running (see `preempt_running`); an image decode leg
692+
# whose media its prefill kept cannot, and is finished instead.
691693
can_recompute_prompts = True
692694
pd_admission: PdAdmissionController | None = None
693695

@@ -2568,6 +2570,17 @@ def _schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]] | None:
25682570
self._schedule_first_decode_after_remote_kv(seq)
25692571
continue
25702572

2573+
# Without a load, every way on from here prefills locally: no
2574+
# connector, a failed receive, a requeue after its receive was
2575+
# queued, a preempted decode, an offload tier's resume on an
2576+
# instance with no P/D connector.
2577+
if (
2578+
seq.kv_transfer_params is not None
2579+
and not needs_remote_load
2580+
and self._refuse_prefill_without_media(seq)
2581+
):
2582+
continue
2583+
25712584
if offload_resume:
25722585
# Blocks already held from the pre-park allocate; only re-check
25732586
# the batch budget. No re-match / re-allocate / re-park.
@@ -2803,6 +2816,12 @@ def _schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]] | None:
28032816
self._park_for_remote_load(seq, skipped_waiting_requests)
28042817
self._inflight_prefix_wait.pop(seq.id, None)
28052818
continue
2819+
# A load an offload tier declines after `allocate` prefills
2820+
# locally too.
2821+
if seq.kv_transfer_params is not None and (
2822+
self._refuse_prefill_without_media(seq)
2823+
):
2824+
continue
28062825

28072826
if seq.offload_joint.boundary_tokens:
28082827
# The KV leg was refused after the state leg was aimed at the
@@ -3645,6 +3664,17 @@ def _query_connector_prefill_match(self, seq: Sequence, *, skip: bool) -> bool:
36453664
)
36463665
return needs_remote_load
36473666

3667+
def _refuse_prefill_without_media(self, seq: Sequence) -> bool:
3668+
"""Finish `seq` instead of prefilling it locally when it is a decode
3669+
leg whose media its prefill kept: its image placeholders would run as
3670+
text. True when it was finished."""
3671+
if not seq.media_on_prefill_instance:
3672+
return False
3673+
self._finish_rejected_waiting(
3674+
seq, reason="unschedulable: image decode leg has no media"
3675+
)
3676+
return True
3677+
36483678
def _schedule_first_decode_after_remote_kv(self, seq: Sequence) -> None:
36493679
"""P/D path: a remote prefill completed, so schedule first decode."""
36503680
# num_cached_tokens still describes this consumer's pre-existing prefix.
@@ -4684,7 +4714,9 @@ def _preempt_one_running(self) -> bool:
46844714
def preempt_running(self) -> int:
46854715
"""Preempt every running sequence ahead of a KV change; return how many.
46864716
4687-
Each recomputes its prompt and tokens once scheduled again. Raises,
4717+
Each recomputes its prompt and tokens once scheduled again, except an
4718+
image decode leg whose media its prefill kept: that one is finished
4719+
when it is next admitted, as it has nothing to recompute from. Raises,
46884720
preempting none, while one's blocks are still in use: remote KV loading
46894721
for a parked request, a KV connector holding the sequence, or its token
46904722
in flight through the pipeline. ``preempt()`` refuses nothing else, so

0 commit comments

Comments
 (0)