Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
4ccc75e
feat(engine): multimodal PD through the chat path
junyyang-amd Nov 16, 2026
2740581
PD image decode: MRoPE delta reaches decode positions, cache_seed gat…
junyyang-amd Nov 19, 2026
57ed4d9
fix(engine): image PD decode positions, cache_seed gate, handoff key …
junyyang-amd Nov 19, 2026
fb89abd
style(tests): sort imports in test_pd_prompt_token_ids.py
junyyang-amd Nov 19, 2026
2815d8d
Merge ROCm/ATOM junyyang/mm-epd-e1 (fb89abd0b) into up-e1
junyyang-amd Nov 20, 2026
696b6ab
tests: drop the duplicate conftest import the up-e1 sync merge left
junyyang-amd Nov 20, 2026
557c505
up-e1: no local prefill of a media-dropped image decode leg; handoff …
junyyang-amd Nov 20, 2026
5eff928
Merge ROCm/ATOM main into task-184
junyyang-amd Nov 20, 2026
e95bd72
Media-dropped leg test: main's connector interface and its early-load…
junyyang-amd Nov 20, 2026
0d21d44
up-e1: merge ROCm/ATOM main; media-dropped leg test on main's connect…
junyyang-amd Nov 20, 2026
07583dc
Merge ROCm/ATOM main (cccc96a03) into up-e1
junyyang-amd Nov 21, 2026
d235ed1
up-e1: no per-request cost on the text path; prompt-bounded MRoPE del…
junyyang-amd Nov 21, 2026
e15afb2
up-e1: merge ROCm/ATOM main; third review round on ROCm/ATOM#3410 (#205)
junyyang-amd Nov 21, 2026
b6648e5
Merge main 811b02bb4 into junyyang/mm-epd-e1
junyyang-amd Nov 23, 2026
87279c0
Merge main be321a375 into junyyang/mm-epd-e1
junyyang-amd Nov 24, 2026
e0c73a0
Merge main 59444c3f3 into junyyang/mm-epd-e1
junyyang-amd Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions atom/entrypoints/atomesh/atom_standalone_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
STREAM_DONE_MESSAGE,
TEXT_COMPLETION_OBJECT,
CompletionRequest,
check_media_handoff,
ended_by_stop,
openai_stop_reason,
openai_stop_reason_with_calls,
Expand Down Expand Up @@ -1351,7 +1352,7 @@ def completions(self, request_data: dict[str, Any]) -> dict[str, Any]:
sampling_params,
request_id,
effective_n,
kv_transfer_params=request_data.get("kv_transfer_params"),
kv_transfer_params=self._kv_transfer_params(request_data),
data_parallel_rank=self._get_data_parallel_rank(request_data),
)
if not outputs:
Expand Down Expand Up @@ -1392,7 +1393,7 @@ def start_completions_stream(self, request_data: dict[str, Any]) -> str:
sampling_params,
request_id,
effective_n,
kv_transfer_params=request_data.get("kv_transfer_params"),
kv_transfer_params=self._kv_transfer_params(request_data),
data_parallel_rank=self._get_data_parallel_rank(request_data),
)
stream_state = CompletionStreamState(
Expand Down Expand Up @@ -1681,6 +1682,13 @@ def _request_field(request: Any, field: str, default: Any = None) -> Any:
value = getattr(request, field, default)
return default if value is None else value

def _kv_transfer_params(self, request_data: dict[str, Any]) -> Any:
"""The request's handoff metadata, refused (ValueError) out of range."""
params = request_data.get("kv_transfer_params")
if params:
check_media_handoff(params, self.engine.config.max_model_len)
return params

def _build_sampling_params(
self,
request: dict[str, Any] | CompletionRequest,
Expand Down
53 changes: 41 additions & 12 deletions atom/entrypoints/openai/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from atom.model_engine.llm_engine import load_tokenizer
from atom.model_engine.request import RequestOutput
from atom.model_engine.segment_tokenizer import PrefixEncoding
from atom.model_engine.sequence import new_token_ids
from atom.model_engine.sequence import leaves_media_on_prefill, new_token_ids
from atom.multimodal.processing import prepare_multimodal_inputs
from atom.multimodal.registry import get_native_multimodal_processor
from atom.observability.tracing import TraceMiddleware, set_request_id
Expand Down Expand Up @@ -107,6 +107,7 @@
CompletionRequest,
ModelCard,
ModelList,
check_media_handoff,
ended_by_stop,
validate_max_tokens,
)
Expand Down Expand Up @@ -1038,6 +1039,7 @@ async def generate_async_multimodal(
multimodal_data: dict[str, Any],
sampling_params: SamplingParams,
request_id: str,
kv_transfer_params: dict[str, Any] | None = None,
data_parallel_rank: int | None = None,
dp_session_id: str | None = None,
dp_parent_session_id: str | None = None,
Expand All @@ -1053,8 +1055,11 @@ async def generate_async_multimodal(
all_token_ids = new_token_ids()
finish_reason: str | None = None
seq = None
kv_transfer_output_meta_info = None

def completion_callback(request_output: RequestOutput):
nonlocal kv_transfer_output_meta_info
kv_transfer_output_meta_info = request_output.kv_transfer_params_output
now = time.time()
loop.call_soon_threadsafe(
token_queue.put_nowait,
Expand All @@ -1071,6 +1076,7 @@ def do_preprocess():
token_ids,
sampling_params,
stream_callback=completion_callback,
kv_transfer_params=kv_transfer_params,
multimodal_data=multimodal_data,
data_parallel_rank=data_parallel_rank,
dp_session_id=dp_session_id,
Expand Down Expand Up @@ -1132,6 +1138,13 @@ def do_preprocess():
"tpot": tpot,
"latency": finished_at - started_at,
}
if kv_transfer_output_meta_info is not None:
# Decode has no media: it seeds its prefix cache and positions with these.
response["kv_transfer_output_meta_info"] = {
**kv_transfer_output_meta_info,
"cache_seed": seq.cache_seed,
"mrope_position_delta": seq.mrope_position_delta,
}
if return_token_ids and seq is not None:
response["prompt_token_ids"] = list(seq.prompt_token_ids)
yield response
Expand Down Expand Up @@ -1331,6 +1344,16 @@ def _validate_chunked_receive(params: dict[str, Any] | None) -> None:
)


def _validate_kv_transfer_params(params: dict[str, Any] | None) -> None:
"""Refuse handoff metadata no leg can serve, before enqueue or SSE headers.

Every endpoint that takes `kv_transfer_params` calls this first.
"""
_validate_chunked_receive(params)
if params:
check_media_handoff(params, _get_engine_max_model_len())


def _engine_kv_transfer_params(
kv_transfer_params: dict[str, Any] | None,
) -> dict[str, Any] | None:
Expand Down Expand Up @@ -1416,8 +1439,10 @@ async def _prepare_engine_input(
``_prepare_prompt`` as before."""
if _has_multimodal_content(messages):
if kv_transfer_params is not None:
# A prefill leg cannot hand an image request off, so neither leg
# can finish it: refused here, not as a router error or a stall.
# Only `/v1/chat/completions` hands an image request off (its
# prefill returns the cache seed and MRoPE delta the decode needs);
# here neither leg could finish it: refused, not a router error or
# a stall.
raise ValueError("image input cannot be combined with kv_transfer_params")
_get_multimodal_processor() # on the loop, as the chat path does
token_ids, multimodal_data = await asyncio.to_thread(
Expand Down Expand Up @@ -2101,7 +2126,7 @@ async def _chat_completions(
beta = isinstance(request, BetaChatCompletionRequest)
route = "beta_chat_completions" if beta else "chat_completions"
validate_model(request.model)
_validate_chunked_receive(request.kv_transfer_params)
_validate_kv_transfer_params(request.kv_transfer_params)

try:
request.tools = normalize_chat_tools(request.tools)
Expand Down Expand Up @@ -2203,12 +2228,15 @@ async def _chat_completions(

_log_request_model("request", request_id, request)

is_multimodal = _has_multimodal_content(messages)
multimodal_data = None
kv_transfer_params = request.kv_transfer_params
if assistant_prefix is not None and (
is_multimodal or request.get_prompt_token_ids() is not None
):
pretokenized = request.get_prompt_token_ids()
# A decode leg takes its prefill's expanded ids; its media went to P.
# Without P's cache seed its blocks would hash as text: keep the media.
is_multimodal = _has_multimodal_content(messages) and not (
pretokenized is not None and leaves_media_on_prefill(kv_transfer_params)
)
if assistant_prefix is not None and (is_multimodal or pretokenized is not None):
# Only rendered text can be continued.
raise ValueError(
"an assistant prefix cannot be combined with image input or "
Expand All @@ -2228,7 +2256,7 @@ async def _chat_completions(
merged_kwargs,
request.tools,
)
elif (pretokenized := request.get_prompt_token_ids()) is not None:
elif pretokenized is not None:
# Reuse prefill IDs to skip template rendering and tokenization.
prompt_or_tokens = pretokenized
kv_transfer_params = _engine_kv_transfer_params(kv_transfer_params)
Expand Down Expand Up @@ -2374,6 +2402,7 @@ async def _chat_completions(
multimodal_data,
sampling_params,
request_id,
kv_transfer_params=kv_transfer_params,
return_token_ids=bool(request.return_token_ids),
**dp_routing,
),
Expand Down Expand Up @@ -2596,7 +2625,7 @@ async def _completions(
beta = isinstance(request, BetaCompletionRequest)
route = "beta_completions" if beta else "completions"
validate_model(request.model)
_validate_chunked_receive(request.kv_transfer_params)
_validate_kv_transfer_params(request.kv_transfer_params)

try:
effective_n = _coerce_n(request.n, request.temperature)
Expand Down Expand Up @@ -2778,7 +2807,7 @@ async def anthropic_messages(request: AnthropicMessagesRequest, raw_request: Req
and returns Anthropic-formatted responses. Enables Claude Code and other
Anthropic-compatible tools to use ATOM as a backend.
"""
_validate_chunked_receive(request.kv_transfer_params)
_validate_kv_transfer_params(request.kv_transfer_params)
# One validator over the shape both endpoints share: this path already
# converts, so validating the conversion leaves a single rule rather than
# a second one in Anthropic's spelling. It checked nothing before, so a
Expand Down Expand Up @@ -3189,7 +3218,7 @@ async def responses_create(raw_request: Request):
}
},
)
_validate_chunked_receive(kv_transfer_params)
_validate_kv_transfer_params(kv_transfer_params)
kv_transfer_params = _engine_kv_transfer_params(kv_transfer_params)

compatibility = api_compatibility_for(custom_message_encoder)
Expand Down
32 changes: 30 additions & 2 deletions atom/entrypoints/openai/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,40 @@ def validate_max_tokens(max_tokens: int) -> int:
_PROMPT_TOKEN_IDS_ADAPTER = TypeAdapter(PromptTokenIds)


def check_media_handoff(
kv_transfer_params: dict[str, Any], max_model_len: int | None
) -> None:
"""Reject an image handoff key out of range.

`cache_seed` roots a 64-bit prefix hash chain; `mrope_position_delta`
moves decode positions, which must stay within the context.
"""
if "cache_seed" in kv_transfer_params:
seed = kv_transfer_params["cache_seed"]
if type(seed) is not int or not 0 <= seed < 2**64:
raise ValueError(
"kv_transfer_params['cache_seed'] must be an integer in [0, 2**64)"
)
if "mrope_position_delta" in kv_transfer_params:
delta = kv_transfer_params["mrope_position_delta"]
if type(delta) is not int or (
max_model_len is not None and abs(delta) > max_model_len
):
raise ValueError(
"kv_transfer_params['mrope_position_delta'] must be an integer "
f"no larger in magnitude than max_model_len ({max_model_len})"
)


def resolve_prompt_token_ids(
prompt_token_ids: PromptTokenIds | None,
kv_transfer_params: dict[str, Any] | None,
) -> PromptTokenIds | None:
"""Resolve IDs from the top-level field or vLLM-compatible PD metadata.

Reject empty lists and conflicting IDs between the two locations.
On a chat decode leg whose prefill kept the image, these are the
prefill's ids, image placeholders expanded. Reject empty lists and
conflicting IDs between the two locations.
"""
from_kv = (kv_transfer_params or {}).get("prompt_token_ids")
if prompt_token_ids is None and from_kv is None:
Expand Down Expand Up @@ -300,7 +327,8 @@ class ChatCompletionRequest(BaseModel):
# Optional KV-transfer metadata for P/D disaggregation.
kv_transfer_params: dict[str, Any] | None = None
data_parallel_rank: int | None = None
# Pre-tokenized text prompt; messages are still required and validated.
# Pre-tokenized prompt (an image decode leg's has its prefill's image
# placeholders expanded); messages are still required and validated.
prompt_token_ids: PromptTokenIds | None = None
# Echo prompt IDs in non-streaming responses, including n > 1.
return_token_ids: bool | None = None
Expand Down
4 changes: 3 additions & 1 deletion atom/model_engine/engine_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,9 @@ def prepare_kv_change(self, *, weights: bool, deadline: float) -> None:
"""Get the KV pool ready to be zeroed, freed or recomputed, or raise.

Waits until KV transfers in flight have reported back, then preempts
what is running so it recomputes on what follows. When the weights
what is running so it recomputes on what follows; an image decode leg
whose media its prefill kept cannot recompute, and is finished
instead (`Scheduler.preempt_running`). When the weights
change, the KV connector must also drop what it keeps for later
requests. Raises with the reason, changing nothing that was running.
"""
Expand Down
34 changes: 29 additions & 5 deletions atom/model_engine/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,12 +360,13 @@ def __init__(
self.mrope_positions_by_req = {
seq.id: seq.mrope_positions
for seq in seqs.values()
if getattr(seq, "mrope_positions", None) is not None
if seq.mrope_positions is not None
}
# A decode leg has no positions, only the delta its prefill handed it.
self.mrope_position_deltas = {
seq.id: getattr(seq, "mrope_position_delta", 0)
seq.id: seq.mrope_position_delta
for seq in seqs.values()
if getattr(seq, "mrope_positions", None) is not None
if seq.mrope_positions is not None or seq.mrope_position_delta
}

# num_cached_tokens for chunked prefill support
Expand Down Expand Up @@ -685,7 +686,8 @@ class Scheduler:
_ENGINE_LABEL = ""
_METRICS_ROLE = ""
# A preempted sequence recomputes its prompt here, which a KV change relies
# on to keep what was running (see `preempt_running`).
# on to keep what was running (see `preempt_running`); an image decode leg
# whose media its prefill kept cannot, and is finished instead.
can_recompute_prompts = True
pd_admission: PdAdmissionController | None = None

Expand Down Expand Up @@ -2350,6 +2352,12 @@ def _schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]] | None:
self._schedule_first_decode_after_remote_kv(seq)
continue

# Without a load, every way on from here prefills locally: no
# connector, an offload resume of the received KV, a requeue the
# connector no longer loads, a preempted decode.
if not needs_remote_load and self._refuse_prefill_without_media(seq):
continue

if offload_resume:
# Blocks already held from the pre-park allocate; only re-check
# the batch budget. No re-match / re-allocate / re-park.
Expand Down Expand Up @@ -2622,6 +2630,9 @@ def _schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]] | None:
self._park_for_remote_load(seq, skipped_waiting_requests)
self._inflight_prefix_wait.pop(seq.id, None)
continue
# A tier load declined after `allocate` prefills locally too.
if self._refuse_prefill_without_media(seq):
continue

if seq.offload_joint.boundary_tokens:
# The KV leg was refused after the state leg was aimed at the
Expand Down Expand Up @@ -3403,6 +3414,17 @@ def _query_connector_prefill_match(self, seq: Sequence, *, skip: bool) -> bool:
)
return needs_remote_load

def _refuse_prefill_without_media(self, seq: Sequence) -> bool:
"""Finish `seq` instead of prefilling it locally when it is a decode
leg whose media its prefill kept: its image placeholders would run as
text. True when it was finished."""
if not seq.media_on_prefill_instance:
return False
self._finish_rejected_waiting(
seq, reason="unschedulable: image decode leg has no media"
)
return True

def _schedule_first_decode_after_remote_kv(self, seq: Sequence) -> None:
"""P/D path: a remote prefill completed, so schedule first decode."""
# num_cached_tokens still describes this consumer's pre-existing prefix.
Expand Down Expand Up @@ -4091,7 +4113,9 @@ def _preempt_one_running(self) -> bool:
def preempt_running(self) -> int:
"""Preempt every running sequence ahead of a KV change; return how many.

Each recomputes its prompt and tokens once scheduled again. Raises,
Each recomputes its prompt and tokens once scheduled again, except an
image decode leg whose media its prefill kept: that one is finished
when it is next admitted, as it has nothing to recompute from. Raises,
preempting none, while one's blocks are still in use: remote KV loading
for a parked request, a KV connector holding the sequence, or its token
in flight through the pipeline. ``preempt()`` refuses nothing else, so
Expand Down
26 changes: 24 additions & 2 deletions atom/model_engine/sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,17 @@ def resumes_offload_prefill(seq) -> bool:
) and len(seq.block_table) > 0


def leaves_media_on_prefill(kv_transfer_params: dict | None) -> bool:
"""True for a remote-prefill decode leg whose prefill kept the media.

Such a leg runs on its prefill's expanded prompt ids with the `cache_seed`
and `mrope_position_delta` the prefill returned, and cannot prefill
locally: it has no media to put in the placeholders.
"""
handoff = kv_transfer_params or {}
return bool(handoff.get("do_remote_prefill")) and "cache_seed" in handoff


@dataclass
class OffloadJointRecord:
"""The KV-transfer offload/joint-load protocol state for one sequence.
Expand Down Expand Up @@ -309,15 +320,26 @@ def __init__(
self.multimodal_data = multimodal_data
self.multimodal_cache_ready = False
# Immutable content identity survives payload release and preemption.
self.cache_seed = -1
# A decode leg whose prefill kept the media keeps what the prefill
# derived from it; the scheduler never prefills it locally.
self.media_on_prefill_instance = (
multimodal_data is None and leaves_media_on_prefill(kv_transfer_params)
)
self.cache_seed = (
kv_transfer_params["cache_seed"] if self.media_on_prefill_instance else -1
)
if multimodal_data is not None:
from atom.model_engine.multimodal_runtime import multimodal_cache_seed

self.cache_seed = multimodal_data.get("cache_seed")
if self.cache_seed is None:
self.cache_seed = multimodal_cache_seed(multimodal_data)
self.mrope_positions = mrope_positions
self.mrope_position_delta = mrope_position_delta
self.mrope_position_delta = (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

the delta never reaches the batch: ScheduledBatch only keeps seqs with mrope_positions, and decode seq has none, so _build_mrope_decode_positions falls back to arange. include nonzero delta seqs in the dict, and assert the delta shows up in ScheduledBatch in the test?

kv_transfer_params.get("mrope_position_delta", 0)
if self.media_on_prefill_instance
else mrope_position_delta
)
self.num_tokens = len(self.token_ids)
self.num_prompt_tokens = len(token_ids)
# Host-known prefix, excluding deferred outputs and draft placeholders.
Expand Down
Loading
Loading