[FEAT] support multi-stage deployment (#2396)

Signed-off-by: ZhengWG <zwg0606@gmail.com>
Signed-off-by: Zheng Wengang <zwg0606@gmail.com>
Signed-off-by: Peiqi Yin <60515999+yinpeiqi@users.noreply.github.com>
Signed-off-by: yinpe <11810305@mail.sustech.edu.cn>
Signed-off-by: yinpeiqi <yinpeiqi809@gmail.com>
Co-authored-by: Peiqi Yin <60515999+yinpeiqi@users.noreply.github.com>
Co-authored-by: yinpe <11810305@mail.sustech.edu.cn>
Co-authored-by: yinpeiqi <yinpeiqi809@gmail.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: Chenguang Zheng <645327136@qq.com>
This commit is contained in:
authored and GitHub committed 2026-05-06 19:33:18 +08:00
1 parent e969d2e99f
commit 1e5f288a91
55 files changed
+4684 -3407

No files matched your search

+36
View File
@@ -76,6 +76,42 @@ class OmniEngineCoreRequest(EngineCoreRequest):
# Optional additional information dictionary (serialized)
additional_information: AdditionalInformationPayload | None = None
@classmethod
def from_request(
cls,
request: EngineCoreRequest,
*,
prompt_embeds: torch.Tensor | None = None,
additional_information: AdditionalInformationPayload | None = None,
) -> "OmniEngineCoreRequest":
"""Clone an EngineCoreRequest into an OmniEngineCoreRequest with optional payload overrides."""
if prompt_embeds is None:
prompt_embeds = request.prompt_embeds
if additional_information is None:
additional_information = getattr(request, "additional_information", None)
return cls(
request_id=request.request_id,
prompt_token_ids=request.prompt_token_ids,
mm_features=request.mm_features,
sampling_params=request.sampling_params,
pooling_params=request.pooling_params,
arrival_time=request.arrival_time,
lora_request=request.lora_request,
cache_salt=request.cache_salt,
data_parallel_rank=request.data_parallel_rank,
prompt_embeds=prompt_embeds,
client_index=request.client_index,
current_wave=request.current_wave,
priority=request.priority,
trace_headers=request.trace_headers,
resumable=request.resumable,
external_req_id=request.external_req_id,
reasoning_ended=request.reasoning_ended,
additional_information=additional_information,
)
class OmniEngineCoreOutput(EngineCoreOutput):
pooling_output: dict[str, torch.Tensor] | None = None
File diff suppressed because it is too large. Load diff
+4 -17
View File
@@ -10,8 +10,6 @@ from __future__ import annotations
import logging
from typing import Any
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
logger = logging.getLogger(__name__)
@@ -31,6 +29,10 @@ class CfgCompanionTracker:
def has_companions(self, parent_id: str) -> bool:
return parent_id in self._companion_map
def get_parent_id(self, req_id: str) -> str | None:
"""Return the parent request id for a companion, or None."""
return self._companion_to_parent.get(req_id)
def all_companions_done(self, parent_id: str) -> bool:
role_map = self._companion_map.get(parent_id, {})
done_set = self._done.get(parent_id, set())
@@ -50,21 +52,6 @@ class CfgCompanionTracker:
self._companion_ids.add(companion_id)
self._companion_to_parent[companion_id] = parent_id
def attach_cfg_request_ids(self, parent_id: str, sampling_params: Any) -> Any:
cfg_ids = self.get_companion_request_ids(parent_id)
if not cfg_ids:
return sampling_params
if isinstance(sampling_params, OmniDiffusionSamplingParams):
sampling_params = sampling_params.clone()
sampling_params.cfg_kv_request_ids = cfg_ids
logger.info(
"Attaching cfg_kv_request_ids=%s to request %s",
cfg_ids,
parent_id,
)
return sampling_params
def on_companion_completed(self, companion_id: str) -> str | None:
"""Mark done. Returns parent_id only if parent is pending and all companions finished."""
parent_id = self._companion_to_parent.get(companion_id)
File diff suppressed because it is too large. Load diff
+18
View File
@@ -359,6 +359,24 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
self.parent_requests[parent_req.request_id] = parent_req
self.external_req_ids[req_state.external_req_id].append(request_id)
def remove_request(self, request_id: str) -> None:
"""Rollback one previously registered request if it was never submitted."""
req_state = self.request_states.pop(request_id, None)
if req_state is None:
return
external_req_id = getattr(req_state, "external_req_id", None)
if external_req_id is not None:
request_ids = self.external_req_ids.get(external_req_id)
if request_ids is not None:
self.external_req_ids[external_req_id] = [rid for rid in request_ids if rid != request_id]
if not self.external_req_ids[external_req_id]:
self.external_req_ids.pop(external_req_id, None)
parent_req = getattr(req_state, "parent_req", None)
if parent_req is not None:
self.parent_requests.pop(parent_req.request_id, None)
def process_outputs(
self,
engine_core_outputs: list[EngineCoreOutput],
+52 -33
View File
@@ -6,6 +6,7 @@ Directly inherits from vLLM's AsyncMPClient to reuse EngineCore architecture.
from __future__ import annotations
import inspect
import multiprocessing.connection
import socket
import threading
@@ -34,6 +35,27 @@ logger = init_logger(__name__)
SHUTDOWN_TIMEOUT_S = 5
def _default_process_engine_inputs(
source_outputs: list[Any],
prompt: Any,
requires_multimodal_data: bool,
) -> list[OmniTokensPrompt]:
from vllm_omni.inputs.data import OmniTokensPrompt
if not isinstance(prompt, list):
prompt = [prompt]
mm_data = {so.request_id: p.get("multi_modal_data") for so, p in zip(source_outputs, prompt)}
return [
OmniTokensPrompt(
prompt_token_ids=so.outputs[0].token_ids,
multi_modal_data=(mm_data[so.request_id] if requires_multimodal_data else None),
)
for so in source_outputs
]
class StageEngineCoreClientBase:
"""Shared stage-aware behavior for async EngineCore clients.
@@ -51,6 +73,8 @@ class StageEngineCoreClientBase:
``engine_manager`` / ``coordinator`` pair created elsewhere.
"""
replica_id: int = 0
@staticmethod
def make_async_mp_client(
vllm_config: Any,
@@ -109,8 +133,10 @@ class StageEngineCoreClientBase:
manage the process lifecycle on shutdown.
"""
# -------- Stage metadata (public fields used at runtime) --------
self.replica_id = 0
if metadata is not None:
self.stage_id = metadata.stage_id
self.replica_id = getattr(metadata, "replica_id", 0)
self.stage_type = metadata.stage_type
self.engine_output_type = metadata.engine_output_type
self.is_comprehension = metadata.is_comprehension
@@ -132,9 +158,10 @@ class StageEngineCoreClientBase:
client_name = self.__class__.__name__
logger.info(
"[%s] Stage-%s initializing EngineCore",
"[%s] stage-%s [rep-%s] initializing EngineCore",
client_name,
self.stage_id,
self.replica_id,
)
try:
super().__init__(
@@ -151,17 +178,19 @@ class StageEngineCoreClientBase:
self.resources.coordinator = coordinator
except Exception:
logger.exception(
"[%s] Stage-%s EngineCore init failed",
"[%s] stage-%s [rep-%s] EngineCore init failed",
client_name,
self.stage_id,
self.replica_id,
)
try:
self.shutdown()
except Exception as shutdown_error:
logger.warning(
"[%s] Stage-%s cleanup after init failure failed: %s",
"[%s] stage-%s [rep-%s] cleanup after init failure failed: %s",
client_name,
self.stage_id,
self.replica_id,
shutdown_error,
)
raise
@@ -172,9 +201,10 @@ class StageEngineCoreClientBase:
self._start_proc_monitor()
logger.info(
"[%s] Stage-%s EngineCore running",
"[%s] stage-%s [rep-%s] EngineCore running",
client_name,
self.stage_id,
self.replica_id,
)
def _start_proc_monitor(self) -> None:
@@ -188,6 +218,7 @@ class StageEngineCoreClientBase:
proc = self._proc
resources_ref = weakref.ref(self.resources)
stage_id = self.stage_id
replica_id = self.replica_id
def _monitor() -> None:
try:
@@ -199,8 +230,9 @@ class StageEngineCoreClientBase:
return
resources.engine_dead = True
logger.error(
"[StageEngineCoreClient] Stage-%s subprocess died unexpectedly (exit code %s).",
"[StageEngineCoreClient] stage-%s [rep-%s] subprocess died unexpectedly (exit code %s).",
stage_id,
replica_id,
proc.exitcode,
)
@@ -228,9 +260,10 @@ class StageEngineCoreClientBase:
async def add_request_async(self, request: EngineCoreRequest) -> None:
"""Add request to the stage engine core."""
logger.info(
"[%s] Stage-%s adding request: %s",
"[%s] stage-%s [rep-%s] add request: %s",
self.__class__.__name__,
self.stage_id,
self.replica_id,
request.request_id,
)
await super().add_request_async(request)
@@ -311,9 +344,10 @@ class StageEngineCoreClientBase:
sender_port = int(base_port) + KV_TRANSFER_PORT_OFFSET + int(from_stage)
except (TypeError, ValueError):
logger.warning(
"[StageEngineCoreClient] Stage-%s could not resolve sender_zmq_port "
"[StageEngineCoreClient] stage-%s [rep-%s] could not resolve sender_zmq_port "
"from base_port=%s and from_stage=%s",
self.stage_id,
self.replica_id,
base_port,
from_stage,
)
@@ -358,48 +392,33 @@ class StageEngineCoreClientBase:
def process_engine_inputs(
self,
stage_list: list[Any],
prompt: OmniTokensPrompt | list[OmniTokensPrompt] | None = None,
source_outputs: list[Any],
prompt: Any = None,
streaming_context: Any | None = None,
) -> list[OmniTokensPrompt]:
"""Process inputs from upstream stages."""
from vllm_omni.inputs.data import OmniTokensPrompt
"""Process inputs from upstream stages.
Transition planning is expressed in terms of the upstream outputs
and the original prompt.
"""
if self.custom_process_input_func is not None:
# Keep legacy arg call for non-streaming processors.
if bool(getattr(streaming_context, "enabled", False)):
signature = inspect.signature(self.custom_process_input_func)
if len(signature.parameters) >= 4:
return self.custom_process_input_func(
stage_list,
self.engine_input_source,
source_outputs,
prompt,
self.requires_multimodal_data,
streaming_context,
)
return self.custom_process_input_func(
stage_list,
self.engine_input_source,
source_outputs,
prompt,
self.requires_multimodal_data,
)
if not self.engine_input_source:
raise ValueError(f"engine_input_source empty for stage {self.stage_id}")
source_id = self.engine_input_source[0]
source_outputs = stage_list[source_id].engine_outputs
if not isinstance(prompt, list):
prompt = [prompt]
mm_data = {so.request_id: p.get("multi_modal_data") for so, p in zip(source_outputs, prompt)}
return [
OmniTokensPrompt(
prompt_token_ids=so.outputs[0].cumulative_token_ids,
multi_modal_data=(mm_data[so.request_id] if self.requires_multimodal_data else None),
)
for so in source_outputs
]
return _default_process_engine_inputs(source_outputs, prompt, self.requires_multimodal_data)
async def collective_rpc_async(
self,
+90 -60
View File
@@ -29,6 +29,8 @@ from vllm.v1.executor import Executor
logger = init_logger(__name__)
StageRoute = tuple[int, int]
# Poll period (ms) used by the registration/handshake loop.
_POLL_PERIOD_MS = 5_000
# Default timeout (s) for a stage to send READY.
@@ -107,28 +109,33 @@ class OmniMasterServer:
master_address: str,
master_port: int,
stage_ids: list[int],
stage_replica_counts: dict[int, int] | None = None,
) -> None:
self._address = master_address
self._port = master_port
self._allocations: dict[int, StageAllocation] = {}
self._stage_configs: dict[int, Any] = {}
self._stage_coordinator_addresses: dict[int, StageCoordinatorAddresses] = {}
self._stage_config_events: dict[int, threading.Event] = {}
self._stage_routes: dict[StageRoute, StageAllocation] = {}
self._stage_configs: dict[StageRoute, Any] = {}
self._stage_coordinator_addresses: dict[StageRoute, StageCoordinatorAddresses] = {}
self._stage_config_events: dict[StageRoute, threading.Event] = {}
self._thread: threading.Thread | None = None
self._stop_event = threading.Event()
stage_replica_counts = dict(stage_replica_counts or {})
for sid in stage_ids:
self._stage_config_events[sid] = threading.Event()
self._stage_coordinator_addresses[sid] = StageCoordinatorAddresses()
hs_port, inp_port, out_port = get_open_ports_list(count=3)
self._allocations[sid] = StageAllocation(
handshake_bind_address=f"tcp://{master_address}:{hs_port}",
handshake_connect_address=f"tcp://{master_address}:{hs_port}",
input_bind_address=f"tcp://{master_address}:{inp_port}",
input_connect_address=f"tcp://{master_address}:{inp_port}",
output_bind_address=f"tcp://{master_address}:{out_port}",
output_connect_address=f"tcp://{master_address}:{out_port}",
)
replica_count = max(1, int(stage_replica_counts.get(sid, 1)))
for replica_id in range(replica_count):
route = (sid, replica_id)
self._stage_config_events[route] = threading.Event()
self._stage_coordinator_addresses[route] = StageCoordinatorAddresses()
hs_port, inp_port, out_port = get_open_ports_list(count=3)
self._stage_routes[route] = StageAllocation(
handshake_bind_address=f"tcp://{master_address}:{hs_port}",
handshake_connect_address=f"tcp://{master_address}:{hs_port}",
input_bind_address=f"tcp://{master_address}:{inp_port}",
input_connect_address=f"tcp://{master_address}:{inp_port}",
output_bind_address=f"tcp://{master_address}:{out_port}",
output_connect_address=f"tcp://{master_address}:{out_port}",
)
logger.info(
"[OmniMasterServer] Pre-allocated addresses for stages %s (master=%s:%d)",
@@ -150,71 +157,78 @@ class OmniMasterServer:
"""Return the registration port exposed to stage launchers."""
return self._port
def get_allocation(self, stage_id: int) -> StageAllocation:
def get_allocation(self, stage_id: int, replica_id: int = 0) -> StageAllocation:
"""Return the full address allocation for *stage_id*."""
return self._allocations[stage_id]
return self._stage_routes[(stage_id, replica_id)]
def register_stage_config(
self,
stage_id: int,
stage_config: Any,
coordinator_addresses: StageCoordinatorAddresses | None = None,
replica_id: int = 0,
) -> None:
"""Store the latest stage registration payload for *stage_id*."""
if stage_id not in self._allocations:
raise KeyError(stage_id)
self._stage_configs[stage_id] = stage_config
key = (stage_id, replica_id)
if key not in self._stage_routes:
raise KeyError(key)
self._stage_configs[key] = stage_config
if coordinator_addresses is not None:
self._stage_coordinator_addresses[stage_id] = coordinator_addresses
self._stage_config_events[stage_id].set()
self._stage_coordinator_addresses[key] = coordinator_addresses
self._stage_config_events[key].set()
def get_stage_config(self, stage_id: int, timeout_s: float | None = None) -> Any:
def get_stage_config(self, stage_id: int, timeout_s: float | None = None, replica_id: int = 0) -> Any:
"""Return the stage config for *stage_id*, waiting if necessary."""
if stage_id not in self._allocations:
raise KeyError(stage_id)
key = (stage_id, replica_id)
if key not in self._stage_routes:
raise KeyError(key)
if stage_id in self._stage_configs:
return self._stage_configs[stage_id]
if key in self._stage_configs:
return self._stage_configs[key]
if not self._stage_config_events[stage_id].wait(timeout=timeout_s):
raise TimeoutError(f"Timed out waiting for stage config for stage {stage_id}.")
if not self._stage_config_events[key].wait(timeout=timeout_s):
raise TimeoutError(f"Timed out waiting for stage config for stage {stage_id} replica {replica_id}.")
return self._stage_configs[stage_id]
return self._stage_configs[key]
def get_stage_coordinator_addresses(
self,
stage_id: int,
timeout_s: float | None = None,
replica_id: int = 0,
) -> StageCoordinatorAddresses:
"""Return the registered coordinator addresses for *stage_id*."""
if stage_id not in self._allocations:
raise KeyError(stage_id)
key = (stage_id, replica_id)
if key not in self._stage_routes:
raise KeyError(key)
if not self._stage_config_events[stage_id].is_set():
if not self._stage_config_events[stage_id].wait(timeout=timeout_s):
raise TimeoutError(f"Timed out waiting for stage registration for stage {stage_id}.")
if not self._stage_config_events[key].is_set():
if not self._stage_config_events[key].wait(timeout=timeout_s):
raise TimeoutError(
f"Timed out waiting for stage registration for stage {stage_id} replica {replica_id}."
)
return self._stage_coordinator_addresses[stage_id]
return self._stage_coordinator_addresses[key]
def get_client_addresses(self, stage_id: int) -> dict[str, str]:
def get_client_addresses(self, stage_id: int, replica_id: int = 0) -> dict[str, str]:
"""Return the addresses the client-side sockets should *bind* to."""
alloc = self._allocations[stage_id]
alloc = self.get_allocation(stage_id, replica_id)
return {
"input_address": alloc.input_bind_address,
"output_address": alloc.output_bind_address,
}
def get_zmq_addresses(self, stage_id: int) -> EngineZmqAddresses:
def get_zmq_addresses(self, stage_id: int, replica_id: int = 0) -> EngineZmqAddresses:
"""Return EngineZmqAddresses using the *bind* (client) side addresses."""
alloc = self._allocations[stage_id]
alloc = self.get_allocation(stage_id, replica_id)
return EngineZmqAddresses(
inputs=[alloc.input_bind_address],
outputs=[alloc.output_bind_address],
)
def get_engine_zmq_addresses(self, stage_id: int) -> EngineZmqAddresses:
def get_engine_zmq_addresses(self, stage_id: int, replica_id: int = 0) -> EngineZmqAddresses:
"""Return EngineZmqAddresses using the *connect* (engine) addresses."""
alloc = self._allocations[stage_id]
alloc = self.get_allocation(stage_id, replica_id)
return EngineZmqAddresses(
inputs=[alloc.input_connect_address],
outputs=[alloc.output_connect_address],
@@ -266,7 +280,7 @@ class OmniMasterServer:
poller = zmq.Poller()
poller.register(reg_socket, zmq.POLLIN)
pending: set[int] = set(self._allocations.keys())
pending: set[StageRoute] = set(self._stage_routes.keys())
while pending and not self._stop_event.is_set():
events: list[tuple[zmq.Socket, int]] = poller.poll(_POLL_PERIOD_MS) # type: ignore[assignment]
@@ -276,15 +290,15 @@ class OmniMasterServer:
for sock, _ in events:
if sock is reg_socket:
sid = self._handle_registration(reg_socket)
if sid is not None:
pending.discard(sid)
route = self._handle_registration(reg_socket)
if route is not None:
pending.discard(route)
# Cleanup
reg_socket.close(linger=0)
logger.info("[OmniMasterServer] All stages registered; server thread exiting.")
def _handle_registration(self, reg_socket: zmq.Socket) -> int | None: # type: ignore[type-arg]
def _handle_registration(self, reg_socket: zmq.Socket) -> StageRoute | None: # type: ignore[type-arg]
"""Receive a stage registration and reply with the handshake address.
Returns the registered stage_id on success, or None on failure.
@@ -305,10 +319,13 @@ class OmniMasterServer:
return None
stage_id: int | None = msg.get("stage_id")
if stage_id not in self._allocations:
replica_id = int(msg.get("replica_id", 0) or 0)
key = (stage_id, replica_id)
if key not in self._stage_routes:
logger.warning(
"[OmniMasterServer] Received registration for unknown stage_id=%s",
"[OmniMasterServer] Received registration for unknown stage_id=%s replica_id=%s",
stage_id,
replica_id,
)
return None
@@ -320,9 +337,10 @@ class OmniMasterServer:
coordinator_output=msg.get("coordinator_output"),
frontend_stats_publish_address=msg.get("frontend_stats_publish_address"),
),
replica_id=replica_id,
)
alloc = self._allocations[stage_id]
alloc = self._stage_routes[key]
response = msgspec.msgpack.encode(
{
"handshake_address": alloc.handshake_connect_address,
@@ -333,11 +351,12 @@ class OmniMasterServer:
# ROUTER-DEALER: reply is [identity, payload] (no empty delimiter).
reg_socket.send_multipart([identity, response])
logger.info(
"[OmniMasterServer] Stage %d registered; assigned handshake=%s",
"[OmniMasterServer] Stage %d replica %d registered; assigned handshake=%s",
stage_id,
replica_id,
alloc.handshake_connect_address,
)
return stage_id
return key
def register_stage_with_omni_master(
@@ -348,6 +367,7 @@ def register_stage_with_omni_master(
omni_stage_config: Any = None,
coordinator: DPCoordinator | None = None,
return_addresses: bool = False,
replica_id: int = 0,
) -> str | tuple[str, str, str]:
"""Register a stage with the omni master server.
@@ -363,6 +383,7 @@ def register_stage_with_omni_master(
reg_sock.connect(f"tcp://{omni_master_address}:{omni_master_port}")
payload = {
"stage_id": omni_stage_id,
"replica_id": replica_id,
"stage_config": _serialize_stage_config(omni_stage_config),
}
if coordinator is not None:
@@ -469,9 +490,10 @@ def connect_remote_engine_cores(
vllm_config: VllmConfig,
omni_master_server: OmniMasterServer,
stage_id: int,
replica_id: int = 0,
) -> Iterator[tuple[None, DPCoordinator | None, EngineZmqAddresses, None]]:
"""Wait for remote engine cores to connect through the omni handshake."""
addresses = omni_master_server.get_zmq_addresses(stage_id)
addresses = omni_master_server.get_zmq_addresses(stage_id, replica_id=replica_id)
parallel_config = vllm_config.parallel_config
# Mirror the engine-count logic from launch_omni_core_engines.
remote_engine_count = (
@@ -482,7 +504,10 @@ def connect_remote_engine_cores(
start_index = parallel_config.data_parallel_rank if parallel_config.data_parallel_rank is not None else 0
coordinator = None
registered_coordinator_addresses = omni_master_server.get_stage_coordinator_addresses(stage_id)
registered_coordinator_addresses = omni_master_server.get_stage_coordinator_addresses(
stage_id,
replica_id=replica_id,
)
addresses.coordinator_input = registered_coordinator_addresses.coordinator_input
addresses.coordinator_output = registered_coordinator_addresses.coordinator_output
addresses.frontend_stats_publish_address = registered_coordinator_addresses.frontend_stats_publish_address
@@ -490,12 +515,13 @@ def connect_remote_engine_cores(
engines_to_handshake = [CoreEngine(index=start_index + i, local=False) for i in range(remote_engine_count)]
logger.info(
"Waiting for %d remote engine(s) for stage %d",
"Waiting for %d remote engine(s) for stage %d replica %d",
remote_engine_count,
stage_id,
replica_id,
)
handshake_bind_address = omni_master_server.get_allocation(stage_id).handshake_bind_address
handshake_bind_address = omni_master_server.get_allocation(stage_id, replica_id=replica_id).handshake_bind_address
with zmq_socket_ctx(handshake_bind_address, zmq.ROUTER, bind=True) as handshake_socket:
yield None, coordinator, addresses, None
@@ -516,9 +542,10 @@ def launch_omni_core_engines(
omni_master_server: OmniMasterServer,
stage_id: int,
stage_config: Any = None,
replica_id: int = 0,
) -> Iterator[tuple[CoreEngineProcManager, DPCoordinator | None, EngineZmqAddresses]]:
"""Launch local engine cores using the omni registration flow."""
addresses = omni_master_server.get_zmq_addresses(stage_id)
addresses = omni_master_server.get_zmq_addresses(stage_id, replica_id=replica_id)
parallel_config = vllm_config.parallel_config
# Determine the number of local engines and their ranks.
local_engine_count = (
@@ -546,17 +573,19 @@ def launch_omni_core_engines(
addresses.frontend_stats_publish_address = coordinator.get_stats_publish_address()
logger.info(
"[omni] Started DP Coordinator process for stage %d (PID: %d)",
"[omni] Started DP Coordinator process for stage %d replica %d (PID: %d)",
stage_id,
replica_id,
coordinator.proc.pid,
)
else:
coordinator = None
logger.info(
"Starting %d local engine(s) for stage %d (dp_rank=%d)",
"Starting %d local engine(s) for stage %d replica %d (dp_rank=%d)",
local_engine_count,
stage_id,
replica_id,
dp_rank,
)
@@ -568,6 +597,7 @@ def launch_omni_core_engines(
omni_stage_id=stage_id,
omni_stage_config=stage_config,
coordinator=coordinator,
replica_id=replica_id,
)
# One CoreEngine entry per local engine so wait_for_engine_startup can
@@ -575,7 +605,7 @@ def launch_omni_core_engines(
engines_to_handshake = [CoreEngine(index=start_index + i, local=True) for i in range(local_engine_count)]
# Bind the pre-allocated handshake socket for this stage.
handshake_bind_address = omni_master_server.get_allocation(stage_id).handshake_bind_address
handshake_bind_address = omni_master_server.get_allocation(stage_id, replica_id=replica_id).handshake_bind_address
with zmq_socket_ctx(handshake_bind_address, zmq.ROUTER, bind=True) as handshake_socket:
local_engine_manager = CoreEngineProcManager(
+187 -118
View File
@@ -19,21 +19,48 @@ from typing import Any, Literal
from vllm.logger import init_logger
from vllm.sampling_params import SamplingParams
from vllm.tokenizers import cached_tokenizer_from_config
from vllm.usage.usage_lib import UsageContext
from vllm.v1.engine.input_processor import InputProcessor
from vllm.v1.executor import Executor
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.engine.arg_utils import OmniEngineArgs
from vllm_omni.engine.output_processor import MultimodalOutputProcessor
from vllm_omni.entrypoints.stage_utils import _to_dict, set_stage_devices
from vllm_omni.entrypoints.utils import filter_dataclass_kwargs, resolve_model_config_path
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams
from vllm_omni.inputs.preprocess import OmniInputPreprocessor
from vllm_omni.platforms import current_omni_platform
from vllm_omni.quantization.inc_config import OmniINCConfig
logger = init_logger(__name__)
@dataclass
class ReplicaInitPlan:
"""One concrete replica startup unit within a logical stage."""
replica_id: int
num_replicas: int
launch_mode: str
stage_cfg: Any
metadata: Any
stage_connector_spec: dict[str, Any]
omni_kv_connector: tuple[dict[str, Any] | None, str | None, str | None]
stage_vllm_config: Any | None = None
executor_class: type | None = None
@dataclass
class LogicalStageInitPlan:
"""Startup plan for one logical stage."""
stage_idx: int
configured_stage_id: int
replicas: list[ReplicaInitPlan]
def _resolve_model_to_local_path(model: str) -> str:
"""Resolve an HF Hub model ID to a local cache path."""
if os.path.isdir(model):
@@ -85,6 +112,14 @@ def terminate_alive_proc(proc, timeout=5):
proc.kill()
def patch_generation_config_if_needed(model_config: Any) -> None:
"""Guard InputProcessor init for models whose config lacks model_type."""
try:
model_config.try_get_generation_config()
except Exception:
model_config.try_get_generation_config = lambda: {}
def resolve_worker_cls(engine_args: dict[str, Any]) -> None:
"""Resolve worker_cls from worker_type for non-diffusion stages."""
worker_type = engine_args.get("worker_type", None)
@@ -259,20 +294,9 @@ class StageMetadata:
runtime_cfg: Any
prompt_expand_func: Callable | None = None
cfg_kv_collect_func: Callable | None = None
@dataclass
class StartedLlmStage:
"""Resources for an LLM stage that has completed startup."""
stage_id: int
metadata: Any
vllm_config: Any
executor_class: type
addresses: Any
proc: Any = None
engine_manager: Any = None
coordinator: Any = None
# Multi-replica: replica_id distinguishes replicas of the same stage.
# For single-replica stages this defaults to 0.
replica_id: int = 0
def extract_stage_metadata(stage_config: Any) -> StageMetadata:
@@ -375,6 +399,119 @@ def prepare_engine_environment() -> None:
pass
def split_devices_for_replicas(
devices_str: str | None,
num_replicas: int,
tp_size: int,
stage_id: int,
) -> list[str]:
"""Split a devices string into per-replica subsets.
When ``num_replicas`` is 1, returns ``[devices_str]`` unchanged.
Otherwise, the total number of device IDs must equal
``num_replicas * tp_size``; each replica gets ``tp_size`` consecutive
device IDs.
Example::
split_devices_for_replicas("1,2,3,4", num_replicas=2, tp_size=2, stage_id=1)
# → ["1,2", "3,4"]
"""
if num_replicas <= 1 or devices_str is None:
return [devices_str] if devices_str is not None else [devices_str]
device_list = [d.strip() for d in devices_str.split(",") if d.strip()]
required = num_replicas * tp_size
if len(device_list) != required:
raise ValueError(
f"Stage {stage_id}: num_replicas={num_replicas}, "
f"tensor_parallel_size={tp_size} requires "
f"{required} devices, got {len(device_list)}: {devices_str}"
)
result: list[str] = []
for r in range(num_replicas):
chunk = device_list[r * tp_size : (r + 1) * tp_size]
result.append(",".join(chunk))
return result
def get_stage_tp_size(stage_cfg: Any) -> int:
"""Extract tensor_parallel_size from a stage config object."""
engine_args = getattr(stage_cfg, "engine_args", {})
if hasattr(engine_args, "get"):
return int(engine_args.get("tensor_parallel_size", 1) or 1)
return int(getattr(engine_args, "tensor_parallel_size", 1) or 1)
def get_stage_devices_per_replica(stage_cfg: Any) -> int:
"""Return the number of devices consumed by one replica of *stage_cfg*."""
if getattr(stage_cfg, "stage_type", "llm") != "diffusion":
return get_stage_tp_size(stage_cfg)
parallel_config = _get_attr_or_item(getattr(stage_cfg, "engine_args", {}), "parallel_config")
if parallel_config is None:
return 1
world_size = _get_attr_or_item(parallel_config, "world_size")
if world_size is not None:
return max(1, int(world_size))
try:
from vllm_omni.diffusion.data import DiffusionParallelConfig
return max(1, int(DiffusionParallelConfig.from_dict(_to_dict(parallel_config)).world_size))
except Exception:
return 1
def compute_replica_layout(
stage_configs: Sequence[Any],
) -> tuple[list[int], dict[int, list[str]]]:
"""Compute per-stage replica counts and device assignments.
Returns:
replicas_per_stage: num_replicas per logical stage.
replica_devices_map: stage_idx -> per-replica device strings
(only for stages with num_replicas > 1).
"""
replicas_per_stage: list[int] = []
for stage_cfg in stage_configs:
runtime_cfg = getattr(stage_cfg, "runtime", {})
num_replicas = int(
runtime_cfg.get("num_replicas", 1)
if hasattr(runtime_cfg, "get")
else getattr(runtime_cfg, "num_replicas", 1)
)
replicas_per_stage.append(max(1, num_replicas))
replica_devices_map: dict[int, list[str]] = {}
for stage_id, stage_cfg in enumerate(stage_configs):
num_replicas = replicas_per_stage[stage_id]
if num_replicas <= 1:
continue
runtime_cfg = getattr(stage_cfg, "runtime", {})
devices_str = (
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
)
devices_per_replica = get_stage_devices_per_replica(stage_cfg)
replica_devices_map[stage_id] = split_devices_for_replicas(
devices_str,
num_replicas,
devices_per_replica,
stage_id,
)
logger.info(
"[stage_init] Stage %s: %d replicas, devices_per_replica=%d, devices split: %s",
stage_id,
num_replicas,
devices_per_replica,
replica_devices_map[stage_id],
)
return replicas_per_stage, replica_devices_map
def setup_stage_devices(stage_id: int, runtime_cfg: Any) -> None:
"""Device mapping via set_stage_devices for a single stage."""
physical_devices = set_stage_devices(
@@ -419,6 +556,13 @@ def build_engine_args_dict(
if stage_type != "diffusion":
resolve_worker_cls(engine_args_dict)
if engine_args_dict.get("worker_type") == "generation":
# Non-AR generation stages (e.g. code2wav) do not benefit from
# prefix caching and can expose hybrid KV-cache layouts that vLLM's
# prefix-cache coordinator does not handle.
engine_args_dict.setdefault("disable_hybrid_kv_cache_manager", True)
engine_args_dict.setdefault("enable_prefix_caching", False)
# Check whether the stage's default_sampling_params defines extra_args.
default_sp = _to_dict(getattr(stage_config, "default_sampling_params", {}))
engine_args_dict["has_sampling_extra_args"] = bool(default_sp.get("extra_args"))
@@ -475,6 +619,35 @@ def build_vllm_config(
return vllm_config, executor_class
def build_llm_stage_output_processor(plan: LogicalStageInitPlan, stage_vllm_config: Any) -> Any | None:
"""Build one output processor per logical LLM stage."""
metadata = plan.replicas[0].metadata
if stage_vllm_config.model_config.skip_tokenizer_init:
tokenizer = None
else:
tokenizer = cached_tokenizer_from_config(
model_config=stage_vllm_config.model_config,
)
return MultimodalOutputProcessor(
tokenizer=tokenizer,
log_stats=False,
engine_core_output_type=metadata.engine_output_type,
)
def build_stage0_input_processor(stage_vllm_config: Any) -> InputProcessor:
"""Build the shared stage-0 input processor."""
patch_generation_config_if_needed(stage_vllm_config.model_config)
input_processor = InputProcessor(vllm_config=stage_vllm_config)
input_processor.input_preprocessor = OmniInputPreprocessor(
vllm_config=stage_vllm_config,
renderer=input_processor.renderer,
)
return input_processor
def acquire_device_locks(
stage_id: int,
engine_args_dict: dict[str, Any],
@@ -678,7 +851,6 @@ def build_diffusion_config(
metadata: StageMetadata,
) -> Any:
"""Build diffusion config for a stage."""
from vllm_omni.diffusion.data import OmniDiffusionConfig
engine_args_dict = build_engine_args_dict(stage_cfg, model)
od_config = OmniDiffusionConfig.from_kwargs(**engine_args_dict)
@@ -726,108 +898,5 @@ def initialize_diffusion_stage(
"""
from vllm_omni.diffusion.stage_diffusion_client import create_diffusion_client
engine_args = _to_dict(stage_cfg.engine_args)
engine_args.pop("stage_id", None)
od_config = OmniDiffusionConfig.from_kwargs(
stage_id=stage_id,
model=model,
**engine_args,
)
if metadata.cfg_kv_collect_func is not None:
od_config.cfg_kv_collect_func = metadata.cfg_kv_collect_func
od_config = build_diffusion_config(model, stage_cfg, metadata)
return create_diffusion_client(model, od_config, metadata, stage_init_timeout, batch_size, use_inline)
def _shutdown_or_close_resource(resource: Any, resource_name: str, stage_id: int) -> None:
"""vLLM CoreEngineProcManager / coordinators use ``shutdown()``, not ``close()``."""
if resource is None:
return
shutdown = getattr(resource, "shutdown", None)
if callable(shutdown):
try:
shutdown()
except Exception as cleanup_error:
logger.warning(
"[stage_init] Failed to shutdown launched %s for stage %s: %s",
resource_name,
stage_id,
cleanup_error,
)
return
close = getattr(resource, "close", None)
if callable(close):
try:
close()
except Exception as cleanup_error:
logger.warning(
"[stage_init] Failed to close launched %s for stage %s: %s",
resource_name,
stage_id,
cleanup_error,
)
def close_started_llm_stage(started: StartedLlmStage) -> None:
"""Release resources owned by a launched stage that never attached."""
if started.proc is not None:
try:
terminate_alive_proc(started.proc)
except Exception as cleanup_error:
logger.warning(
"[stage_init] Failed to terminate process for stage %s: %s",
started.stage_id,
cleanup_error,
)
_shutdown_or_close_resource(started.engine_manager, "engine manager", started.stage_id)
_shutdown_or_close_resource(started.coordinator, "coordinator", started.stage_id)
def finalize_initialized_stages(
stage_clients: list[Any | None],
input_processor: InputProcessor | None,
) -> tuple[list[Any], list[Any], list[dict[str, Any]]]:
"""Validate successful init and build runtime metadata lists."""
if any(stage_client is None for stage_client in stage_clients):
raise RuntimeError("Stage initialization completed with missing stage clients")
initialized_stage_clients = [stage_client for stage_client in stage_clients if stage_client is not None]
default_sampling_params_list = [stage_client.default_sampling_params for stage_client in initialized_stage_clients]
stage_metadata = [
{
"final_output": stage_client.final_output,
"final_output_type": stage_client.final_output_type,
"stage_type": stage_client.stage_type,
}
for stage_client in initialized_stage_clients
]
if not isinstance(input_processor, InputProcessor):
has_llm_stage = any(metadata.get("stage_type") != "diffusion" for metadata in stage_metadata)
if has_llm_stage:
raise RuntimeError("Failed to initialize stage-0 InputProcessor for LLM pipeline")
return initialized_stage_clients, default_sampling_params_list, stage_metadata
def cleanup_failed_stage_initialization(
stage_clients: list[Any | None],
started_llm_stages: list[StartedLlmStage],
) -> None:
"""Shutdown attached stages and close any launched-but-unattached engines."""
for cleanup_stage_id, stage_client in reversed(list(enumerate(stage_clients))):
if stage_client is None:
continue
try:
stage_client.shutdown()
except Exception as cleanup_error:
logger.warning(
"[stage_init] Failed to shutdown initialized stage %s after init failure: %s",
cleanup_stage_id,
cleanup_error,
)
for started in reversed(started_llm_stages):
if stage_clients[started.stage_id] is not None:
continue
close_started_llm_stage(started)
+403
View File
@@ -0,0 +1,403 @@
"""Unified stage-local runtime abstraction for vLLM-Omni."""
from __future__ import annotations
import asyncio
import time as _time
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from vllm.logger import init_logger
from vllm.v1.engine import EngineCoreOutputs
from vllm_omni.metrics.stats import StageRequestStats as StageRequestMetrics
from vllm_omni.metrics.stats import StageStats
from vllm_omni.metrics.utils import count_tokens_from_outputs
if TYPE_CHECKING:
from vllm_omni.engine.orchestrator import OrchestratorRequestState
logger = init_logger(__name__)
@dataclass
class _ReplicaMetrics:
"""Per-replica metrics accumulators owned by a stage pool."""
batch_seq: int = 0
agg_total_tokens: int = 0
agg_total_gen_time_ms: float = 0.0
class StagePool:
"""Replicas of one logical stage with RR + affinity selection."""
def __init__(
self,
stage_id: int,
clients: Any | list[Any],
*,
output_processor: Any = None,
stage_vllm_config: Any = None,
) -> None:
if isinstance(clients, list):
normalized_clients = list(clients)
else:
normalized_clients = [clients]
if not normalized_clients:
raise ValueError(f"StagePool for stage {stage_id} has no replicas")
self.stage_id = stage_id
self.clients: list[Any] = normalized_clients
self._output_processor = output_processor
self._stage_vllm_config = stage_vllm_config
self._next_replica_id = 0
self._request_bindings: dict[str, int] = {}
self._replica_metrics: list[_ReplicaMetrics] = [_ReplicaMetrics() for _ in self.clients]
# ---- Stage-level properties ----
@property
def num_replicas(self) -> int:
return len(self.clients)
@property
def stage_type(self) -> str | None:
return getattr(self.stage_client, "stage_type", None)
@property
def final_output(self) -> bool:
return bool(getattr(self.clients[0], "final_output", False))
@property
def stage_client(self) -> Any:
return self.clients[0]
@property
def stage_vllm_config(self) -> Any:
return self._stage_vllm_config
@property
def output_processor(self) -> Any:
return self._output_processor
# ---- Route binding lifecycle ----
def get_bound_replica_id(self, request_id: str) -> int | None:
"""Return the currently bound replica id for *request_id* if present."""
return self._request_bindings.get(request_id)
def get_bound_client(self, request_id: str) -> Any | None:
"""Return the currently bound client for *request_id* if present."""
replica_id = self.get_bound_replica_id(request_id)
if replica_id is None:
return None
return self.clients[replica_id]
def release_binding(self, request_id: str) -> None:
"""Drop the route binding for *request_id* in this stage."""
self._request_bindings.pop(request_id, None)
def release_bindings(self, request_ids: list[str]) -> None:
"""Drop route bindings for the given request ids in this stage."""
for request_id in request_ids:
self.release_binding(request_id)
def select_replica_id(
self,
request_id: str,
*,
affinity_request_id: str | None = None,
) -> int:
"""Pick a replica id for *request_id* and cache the choice."""
cached = self.get_bound_replica_id(request_id)
if cached is not None:
return cached
chosen = self.get_bound_replica_id(affinity_request_id) if affinity_request_id is not None else None
if chosen is None:
if self.num_replicas == 1:
chosen = 0
else:
chosen = self._next_replica_id
self._next_replica_id = (self._next_replica_id + 1) % self.num_replicas
self._request_bindings[request_id] = chosen
return chosen
# ---- Metrics ----
def build_stage_metrics(
self,
request_outputs: list[Any],
*,
submit_ts: float,
replica_id: int,
) -> StageRequestMetrics:
"""Build stage metrics for outputs produced on one replica."""
now = _time.time()
stage_gen_time_ms = (now - submit_ts) * 1000.0
num_tokens_out = count_tokens_from_outputs(request_outputs)
num_tokens_in = 0
if self.stage_id == 0:
for ro in request_outputs:
ptids = getattr(ro, "prompt_token_ids", None)
if ptids is not None:
num_tokens_in += len(ptids)
metrics = self._replica_metrics[replica_id]
metrics.batch_seq += 1
batch_id = metrics.batch_seq
metrics.agg_total_tokens += num_tokens_out
metrics.agg_total_gen_time_ms += stage_gen_time_ms
return StageRequestMetrics(
num_tokens_in=num_tokens_in,
num_tokens_out=num_tokens_out,
stage_gen_time_ms=stage_gen_time_ms,
batch_id=batch_id,
batch_size=1,
rx_decode_time_ms=0.0,
rx_transfer_bytes=0,
rx_in_flight_time_ms=0.0,
stage_stats=StageStats(
total_token=metrics.agg_total_tokens,
total_gen_time_ms=metrics.agg_total_gen_time_ms,
),
)
# ---- Stage-local admission ----
async def submit_initial(
self,
request_id: str,
req_state: OrchestratorRequestState,
request: Any,
*,
prompt_text: Any = None,
affinity_request_id: str | None = None,
submit_kwargs: dict[str, Any] | None = None,
params_override: Any = None,
) -> int:
"""Submit a stage-entry request into this pool."""
params = params_override if params_override is not None else req_state.sampling_params_list[self.stage_id]
submit_kwargs = dict(submit_kwargs or {})
if self.stage_type == "diffusion":
replica_id = self.select_replica_id(
request_id,
affinity_request_id=affinity_request_id,
)
client = self.clients[replica_id]
if isinstance(request, list):
await client.add_batch_request_async(request_id, request, params, **submit_kwargs)
else:
await client.add_request_async(request_id, request, params, **submit_kwargs)
return replica_id
replica_id = self.select_replica_id(
request_id,
affinity_request_id=affinity_request_id,
)
try:
self.output_processor.add_request(
request=request,
prompt=prompt_text,
parent_req=None,
request_index=0,
queue=None,
)
except Exception:
self.release_binding(request_id)
raise
try:
await self.clients[replica_id].add_request_async(request, **submit_kwargs)
except Exception:
self.release_binding(request_id)
rollback = getattr(self.output_processor, "remove_request", None)
if callable(rollback):
try:
rollback(request_id)
except Exception as rollback_error:
logger.warning(
"[StagePool] Failed to rollback output processor state for req=%s stage-%s: %s",
request_id,
self.stage_id,
rollback_error,
)
raise
return replica_id
async def submit_update(
self,
request_id: str,
req_state: OrchestratorRequestState,
request: Any,
*,
prompt_text: Any = None,
) -> int:
"""Submit a streaming update to an already admitted request."""
params = req_state.sampling_params_list[self.stage_id]
replica_id = self.get_bound_replica_id(request_id)
if replica_id is None:
replica_id = self.select_replica_id(request_id)
if self.stage_type == "diffusion":
await self.clients[replica_id].add_request_async(request_id, request, params)
else:
# Refresh the shared output-processor state before yielding to the
# stage client so streaming segments are merged against the latest
# prompt/token metadata.
self.output_processor.add_request(
request=request,
prompt=prompt_text,
parent_req=None,
request_index=0,
queue=None,
)
await self.clients[replica_id].add_request_async(request)
return replica_id
# ---- Stage-local polling ----
async def _poll_stage_raw(self, client: Any) -> EngineCoreOutputs | None:
"""Pull raw EngineCoreOutputs from a stage replica without processing."""
outputs = await client.get_output_async()
if not outputs.outputs:
return None
return outputs
async def process_llm_raw_outputs(
self,
replica_id: int,
raw_outputs: EngineCoreOutputs,
) -> list[Any]:
"""Run the shared LLM output processor on one raw poll result."""
client = self.clients[replica_id]
processor = self.output_processor
processed = processor.process_outputs(
raw_outputs.outputs,
raw_outputs.timestamp,
None,
)
if processed.reqs_to_abort:
await client.abort_requests_async(processed.reqs_to_abort)
if raw_outputs.scheduler_stats is not None:
processor.update_scheduler_stats(raw_outputs.scheduler_stats)
return processed.request_outputs
async def poll_llm_raw_output(
self,
replica_id: int,
*,
timeout_s: float = 0.001,
) -> EngineCoreOutputs | None:
"""Poll raw EngineCore outputs from one LLM replica once."""
client = self.clients[replica_id]
try:
return await asyncio.wait_for(
self._poll_stage_raw(client),
timeout=timeout_s,
)
except asyncio.TimeoutError:
return None
except asyncio.CancelledError:
raise
except Exception:
logger.exception(
"[StagePool] _poll_stage_raw failed for stage-%s replica-%s",
self.stage_id,
replica_id,
)
raise
def poll_diffusion_output(self, replica_id: int) -> Any | None:
"""Drain one ready diffusion output from the given replica if present."""
return self.clients[replica_id].get_diffusion_output_nowait()
# ---- Stage-local control plane ----
async def abort_requests(self, request_ids: list[str]) -> None:
"""Abort the given requests in this stage pool.
Request-bound abort routing stays inside the pool because route affinity
(`request_id -> replica_id`) is pool-owned.
"""
if not request_ids:
return
request_ids_by_replica: dict[int, list[str]] = {}
for request_id in request_ids:
replica_id = self.get_bound_replica_id(request_id)
if replica_id is None:
logger.debug("[StagePool] abort: no binding for req=%s in stage-%s", request_id, self.stage_id)
continue
request_ids_by_replica.setdefault(replica_id, []).append(request_id)
for replica_id, replica_request_ids in request_ids_by_replica.items():
await self.clients[replica_id].abort_requests_async(replica_request_ids)
# Clean up OutputProcessor state (e.g. mm_accumulated tensors) that
# would otherwise leak — aborted requests never produce a final
# EngineCoreOutput, so process_outputs() never fires its cleanup path.
all_aborted = [rid for ids in request_ids_by_replica.values() for rid in ids]
if all_aborted and self._output_processor is not None:
self._output_processor.abort_requests(all_aborted, internal=True)
async def collective_rpc(
self,
replica_id: int,
method: str,
timeout: float | None = None,
args: tuple[Any, ...] = (),
kwargs: dict[str, Any] | None = None,
) -> Any:
"""Dispatch a stage-scoped control-plane RPC to one physical route."""
kwargs = dict(kwargs or {})
client = self.clients[replica_id]
try:
if hasattr(client, "collective_rpc_async"):
return await client.collective_rpc_async(
method=method,
timeout=timeout,
args=args,
kwargs=kwargs,
)
return {
"supported": False,
"todo": True,
"reason": f"{client.__class__.__name__}.collective_rpc_async is not implemented yet",
}
except Exception as exc:
logger.exception(
"[StagePool] collective_rpc failed: stage=%s replica=%s method=%s",
self.stage_id,
replica_id,
method,
)
return {
"supported": False,
"error": str(exc),
}
def shutdown_replica(self, replica_id: int) -> None:
"""Shutdown one backend handle in this stage pool."""
client = self.clients[replica_id]
try:
client.shutdown()
logger.info(
"[StagePool] Stage %d replica %d shut down",
self.stage_id,
replica_id,
)
except Exception as e:
logger.warning(
"[StagePool] Failed to shutdown stage %d replica %d: %s",
self.stage_id,
replica_id,
e,
)