Skip to content
114 changes: 87 additions & 27 deletions atom/entrypoints/atomesh/atom_standalone_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@
from typing import Any

from atom import SamplingParams
from atom.entrypoints.openai.api_server import _build_sampling_params, _coerce_n
from atom.entrypoints.chat_utils import has_multimodal_content
from atom.entrypoints.openai.api_server import (
_build_sampling_params,
_coerce_n,
load_multimodal_processor,
prepare_chat_multimodal_inputs,
)
from atom.entrypoints.openai.chat_encoders import (
apply_chat_template,
chat_template_source,
load_custom_message_encoder,
render_probe_prompt,
resolve_reasoning_toggle,
)
from atom.entrypoints.openai.images import check_chat_images
from atom.entrypoints.openai.protocol import (
CHAT_COMPLETION_CHUNK_OBJECT,
DEFAULT_MAX_TOKENS,
Expand All @@ -34,6 +41,7 @@
DEFAULT_TOP_P,
STREAM_DONE_MESSAGE,
TEXT_COMPLETION_OBJECT,
ChatMessage,
CompletionRequest,
check_media_handoff,
ended_by_stop,
Expand All @@ -44,6 +52,7 @@
NO_REASONING,
ReasoningChannel,
prompt_starts_in_reasoning,
prompt_tokens_start_in_reasoning,
template_opens_reasoning_implicitly,
thinking_switched_off,
)
Expand Down Expand Up @@ -74,23 +83,25 @@
@dataclasses.dataclass
class EngineRequest:
request_id: str
prompt: str
prompt: str | list[int]
sampling_params: SamplingParams
effective_n: int
future: concurrent.futures.Future[list[dict[str, Any]]]
kv_transfer_params: dict[str, Any] | None = None
data_parallel_rank: int | None = None
multimodal_data: dict[str, Any] | None = None


@dataclasses.dataclass
class EngineStreamRequest:
request_id: str
prompt: str
prompt: str | list[int]
sampling_params: SamplingParams
effective_n: int
stream_queue: queue.Queue[dict[str, Any]]
kv_transfer_params: dict[str, Any] | None = None
data_parallel_rank: int | None = None
multimodal_data: dict[str, Any] | None = None


class AtomEngineService:
Expand Down Expand Up @@ -134,12 +145,13 @@ def __init__(self, engine: Any, tokenizer: Any) -> None:

def generate(
self,
prompt: str,
prompt: str | list[int],
sampling_params: SamplingParams,
request_id: str,
effective_n: int,
kv_transfer_params: dict[str, Any] | None = None,
data_parallel_rank: int | None = None,
multimodal_data: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
if self._closed.is_set():
raise RuntimeError("ATOM standalone engine service is closed")
Expand All @@ -159,6 +171,7 @@ def generate(
future=future,
kv_transfer_params=kv_transfer_params,
data_parallel_rank=data_parallel_rank,
multimodal_data=multimodal_data,
)
)
try:
Expand Down Expand Up @@ -237,12 +250,13 @@ def _submit_request(self, request: EngineRequest) -> None:

def start_stream(
self,
prompt: str,
prompt: str | list[int],
sampling_params: SamplingParams,
request_id: str,
effective_n: int,
kv_transfer_params: dict[str, Any] | None = None,
data_parallel_rank: int | None = None,
multimodal_data: dict[str, Any] | None = None,
) -> queue.Queue[dict[str, Any]]:
if self._closed.is_set():
raise RuntimeError("ATOM standalone engine service is closed")
Expand All @@ -258,6 +272,7 @@ def start_stream(
stream_queue=stream_queue,
kv_transfer_params=kv_transfer_params,
data_parallel_rank=data_parallel_rank,
multimodal_data=multimodal_data,
)
)
return stream_queue
Expand Down Expand Up @@ -398,6 +413,7 @@ def completion_callback(request_output: Any) -> None:
stream_callback=completion_callback,
kv_transfer_params=request.kv_transfer_params,
data_parallel_rank=request.data_parallel_rank,
multimodal_data=request.multimodal_data,
)

def _preprocess_fanout_stream_request(
Expand Down Expand Up @@ -425,6 +441,7 @@ def completion_callback(request_output: Any) -> None:
kv_transfer_params=request.kv_transfer_params,
parent_request_id=request.request_id,
data_parallel_rank=request.data_parallel_rank,
multimodal_data=request.multimodal_data,
)

def _preprocess_single_request(self, request: EngineRequest) -> Any:
Expand All @@ -443,6 +460,7 @@ def completion_callback(request_output: Any) -> None:
stream_callback=completion_callback,
kv_transfer_params=request.kv_transfer_params,
data_parallel_rank=request.data_parallel_rank,
multimodal_data=request.multimodal_data,
)
state.set_num_tokens_input(seq.num_prompt_tokens)
return seq
Expand Down Expand Up @@ -470,6 +488,7 @@ def completion_callback(request_output: Any) -> None:
kv_transfer_params=request.kv_transfer_params,
parent_request_id=request.request_id,
data_parallel_rank=request.data_parallel_rank,
multimodal_data=request.multimodal_data,
)
if seqs:
state.set_num_tokens_input(seqs[0].num_prompt_tokens)
Expand Down Expand Up @@ -680,7 +699,7 @@ def __init__(
self,
request_id: str,
model_name: str,
prompt: str,
prompt: str | list[int],
tokenizer: Any,
stream_queue: queue.Queue[dict[str, Any]],
n: int,
Expand All @@ -692,7 +711,9 @@ def __init__(
self.request_id = request_id
self.model_name = model_name
self.stream_queue = stream_queue
self.num_tokens_input = len(tokenizer.encode(prompt))
self.num_tokens_input = len(
tokenizer.encode(prompt) if isinstance(prompt, str) else prompt
)
self.num_tokens_output = [0] * n
# Same prompt for every sibling, so the same starting state. Without
# this a template that opens the reasoning channel in the prompt has
Expand Down Expand Up @@ -1212,13 +1233,17 @@ def __init__(
)

self.engine_service = AtomEngineService(engine, tokenizer)
# Loaded by the first request with an image, under the lock so that
# concurrent first requests load it once.
self._multimodal_processor = None
self._multimodal_processor_lock = threading.Lock()

self._streams: dict[str, ChatCompletionStreamState] = {}
self._completion_streams: dict[str, CompletionStreamState] = {}
self._streams_lock = threading.Lock()

def _reasoning_channel(
self, prompt: str, template_kwargs: dict[str, Any] | None = None
self, prompt: str | list[int], template_kwargs: dict[str, Any] | None = None
) -> ReasoningChannel:
"""How to read this response's reasoning channel.

Expand All @@ -1239,7 +1264,11 @@ def _reasoning_channel(
"""
return ReasoningChannel(
dialect=self.reasoning_dialect,
starts_open=prompt_starts_in_reasoning(prompt)
starts_open=(
prompt_starts_in_reasoning(prompt)
if isinstance(prompt, str)
else prompt_tokens_start_in_reasoning(prompt, self.tokenizer.decode)
)
or (
self.model_starts_in_reasoning
and not thinking_switched_off(template_kwargs, self.reasoning_toggle)
Expand All @@ -1260,15 +1289,8 @@ def chat_completions(self, request_data: dict[str, Any]) -> dict[str, Any]:
if request_data.get("chat_template_kwargs"):
template_kwargs.update(request_data["chat_template_kwargs"])

prompt = apply_chat_template(
self.tokenizer,
self.custom_message_encoder,
[
self._chat_message_to_template_dict(msg)
for msg in self._get_chat_messages(request_data)
],
tools=request_data.get("tools"),
**template_kwargs,
prompt, multimodal_data = self._chat_engine_input(
request_data, template_kwargs
)

effective_n = _coerce_n(
Expand All @@ -1287,6 +1309,7 @@ def chat_completions(self, request_data: dict[str, Any]) -> dict[str, Any]:
request_id,
effective_n,
data_parallel_rank=data_parallel_rank,
multimodal_data=multimodal_data,
)
if not outputs:
raise RuntimeError("No output generated")
Expand All @@ -1306,6 +1329,7 @@ def chat_completions(self, request_data: dict[str, Any]) -> dict[str, Any]:
request_id,
effective_n,
data_parallel_rank=data_parallel_rank,
multimodal_data=multimodal_data,
)
if not outputs:
raise RuntimeError("No output generated")
Expand Down Expand Up @@ -1489,15 +1513,8 @@ def start_chat_completions_stream(self, request_data: dict[str, Any]) -> str:
if request_data.get("chat_template_kwargs"):
template_kwargs.update(request_data["chat_template_kwargs"])

prompt = apply_chat_template(
self.tokenizer,
self.custom_message_encoder,
[
self._chat_message_to_template_dict(msg)
for msg in self._get_chat_messages(request_data)
],
tools=request_data.get("tools"),
**template_kwargs,
prompt, multimodal_data = self._chat_engine_input(
request_data, template_kwargs
)

effective_n = _coerce_n(
Expand All @@ -1514,6 +1531,7 @@ def start_chat_completions_stream(self, request_data: dict[str, Any]) -> str:
request_id,
effective_n,
data_parallel_rank=self._get_data_parallel_rank(request_data),
multimodal_data=multimodal_data,
)
stream_state = ChatCompletionStreamState(
request_id=request_id,
Expand All @@ -1534,6 +1552,48 @@ def start_chat_completions_stream(self, request_data: dict[str, Any]) -> str:
logger.exception("ATOM standalone start_chat_completions_stream failed")
raise

def _chat_engine_input(
self, request_data: dict[str, Any], template_kwargs: dict[str, Any]
) -> tuple[str | list[int], dict[str, Any] | None]:
"""A chat request's prompt for the engine, and its images' data.

A request with images is prepared as the OpenAI server prepares it:
its image parts checked, fetched and expanded into the model's
placeholders, so its prompt arrives as token ids. Blocking.
"""
messages = self._get_chat_messages(request_data)
# Checked first, as the OpenAI server does: a `file` image part is in
# its `image_url` form only once checked.
checked = check_chat_images([ChatMessage.model_validate(m) for m in messages])
if has_multimodal_content([{"content": m.content} for m in checked]):
# Tool-call arguments go to the template as sent, as on the text
# path below.
return prepare_chat_multimodal_inputs(
self.engine.config,
self._get_multimodal_processor(),
checked,
template_kwargs,
request_data.get("tools"),
preserve_tool_call_arguments=True,
)
prompt = apply_chat_template(
self.tokenizer,
self.custom_message_encoder,
[self._chat_message_to_template_dict(msg) for msg in messages],
tools=request_data.get("tools"),
**template_kwargs,
)
return prompt, None

def _get_multimodal_processor(self) -> Any:
with self._multimodal_processor_lock:
if self._multimodal_processor is None:
logger.info("Loading multimodal processor for %s", self.model_name)
self._multimodal_processor = load_multimodal_processor(
self.engine.config, self.tokenizer, self.custom_message_encoder
)
return self._multimodal_processor

def drain_chat_completions_stream(
self,
stream_id: str,
Expand Down
53 changes: 40 additions & 13 deletions atom/entrypoints/openai/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,30 +753,42 @@ def _has_multimodal_content(messages: list[Any]) -> bool:
)


def load_multimodal_processor(config, tokenizer, custom_message_encoder):
"""The processor that turns a chat with images into the engine's input."""
processor = get_native_multimodal_processor(
config, tokenizer, custom_message_encoder
)
if processor is None:
# The checkpoint path: model_name may be --served-model-name.
processor = AutoProcessor.from_pretrained(config.model, trust_remote_code=True)
# A checkpoint that ships its template for the tokenizer only
# (MiniMax-M3.1) renders with the server's, --chat-template included.
if processor.chat_template is None:
processor.chat_template = tokenizer.chat_template
return processor


def _get_multimodal_processor():
global processor
if processor is None:
logger.info(f"Loading multimodal processor from {model_name}...")
processor = get_native_multimodal_processor(
processor = load_multimodal_processor(
_get_engine_config(), tokenizer, custom_message_encoder
)
if processor is None:
# The checkpoint path: model_name may be --served-model-name.
processor = AutoProcessor.from_pretrained(
_get_engine_config().model, trust_remote_code=True
)
# A checkpoint that ships its template for the tokenizer only
# (MiniMax-M3.1) renders with the server's, --chat-template included.
if processor.chat_template is None:
processor.chat_template = tokenizer.chat_template
return processor


def _prepare_multimodal_inputs(
def prepare_chat_multimodal_inputs(
config,
processor,
messages: list[Any],
chat_template_kwargs: dict[str, Any],
tools: Any = None,
*,
preserve_tool_call_arguments: bool,
) -> tuple[list[int], dict[str, Any]]:
"""The prompt token ids and multimodal data for ``messages``, whose image
parts ``check_chat_images`` has checked. Blocking: it fetches the images."""
# The images arrive decoded: the processor's media loader reads any
# source it is given, server paths included.
conversation, media = parse_chat_messages(
Expand All @@ -793,15 +805,30 @@ def _prepare_multimodal_inputs(
)
)
return prepare_multimodal_inputs(
_get_engine_config(),
_get_multimodal_processor(),
config,
processor,
conversation,
media,
chat_template_kwargs,
tools=tools,
)


def _prepare_multimodal_inputs(
messages: list[Any],
chat_template_kwargs: dict[str, Any],
tools: Any = None,
) -> tuple[list[int], dict[str, Any]]:
return prepare_chat_multimodal_inputs(
_get_engine_config(),
_get_multimodal_processor(),
messages,
chat_template_kwargs,
tools,
preserve_tool_call_arguments=preserve_tool_call_arguments,
)


# ── Batched stream dispatch ──────────────────────────────────────────────


Expand Down
Loading