[large-scale-serving] Integrate OmniCoordinator into stage engine pipeline (#3569)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Signed-off-by: herotai214 <herotai214@gmail.com>
Co-authored-by: herotai214 <herotai214@gmail.com>
This commit is contained in:
chickeytonandherotai214 authored and GitHub committed 2026-05-19 12:08:20 +08:00
1 parent ca9fd0b71c
commit e277feacaf
33 files changed
+3033 -782

No files matched your search

+280 -53
View File
@@ -18,7 +18,7 @@ import threading
import time
import uuid
import weakref
from collections.abc import Mapping, Sequence
from collections.abc import Awaitable, Callable, Mapping, Sequence
from contextlib import ExitStack
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Literal, cast
@@ -45,6 +45,10 @@ from vllm_omni.diffusion.stage_diffusion_proc import (
from vllm_omni.distributed.omni_connectors.utils.initialization import (
resolve_omni_kv_config_for_stage,
)
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
build_load_balancer_factory,
)
from vllm_omni.engine import OmniEngineCoreRequest
from vllm_omni.engine.messages import (
AbortRequestMessage,
@@ -53,6 +57,7 @@ from vllm_omni.engine.messages import (
CollectiveRPCResultMessage,
EngineQueueMessage,
ErrorMessage,
RegisterRemoteReplicaMessage,
ShutdownRequestMessage,
StageSubmissionMessage,
)
@@ -77,6 +82,7 @@ from vllm_omni.engine.stage_engine_startup import (
from vllm_omni.engine.stage_init_utils import (
LogicalStageInitPlan,
ReplicaInitPlan,
StageRemoteFactoryContext,
_inject_inferred_kv_tp_topology,
acquire_device_locks,
acquire_diffusion_device_locks,
@@ -85,6 +91,7 @@ from vllm_omni.engine.stage_init_utils import (
build_llm_stage_output_processor,
build_stage0_input_processor,
build_vllm_config,
capture_stage_factory_contexts,
compute_replica_layout,
extract_stage_metadata,
get_stage_connector_spec,
@@ -148,6 +155,7 @@ _PARENT_ARGS_KEEP: frozenset[str] = frozenset(
# trigger the ``create_model_config`` guard).
_PARENT_ARGS_STRIP: frozenset[str] = frozenset({"stage_configs_path"})
# Fields always populated by callers (via ``from_cli_args`` / ``asdict``) so
# their presence as an override is never a surprise — suppress the
# "override ignored" warning for these.
@@ -229,10 +237,9 @@ def _weak_shutdown_async_omni_engine(
pass
for q in (request_queue, output_queue, rpc_output_queue):
if q is None:
continue
try:
q.close()
if q is not None:
q.close()
except Exception:
pass
@@ -301,6 +308,23 @@ class AsyncOmniEngine:
self._omni_master_port: int | None = kwargs.get("omni_master_port")
self._omni_master_server: OmniMasterServer | None = None
# New omni-coordinator flags. Consumed only in single_stage_mode.
# ``omni_dp_size_local`` is process-local: each invocation (head and
# every headless) launches that many replicas for its own stage.
self._omni_dp_size_local: int = int(kwargs.get("omni_dp_size_local") or 1)
if self._omni_dp_size_local < 1:
raise ValueError(f"--omni-dp-size-local must be >= 1, got {self._omni_dp_size_local}")
self._omni_lb_policy: str = str(kwargs.get("omni_lb_policy") or "random")
self._omni_heartbeat_timeout: float = float(kwargs.get("omni_heartbeat_timeout") or 30.0)
if self._omni_heartbeat_timeout <= 0:
raise ValueError(f"--omni-heartbeat-timeout must be > 0, got {self._omni_heartbeat_timeout}")
# Coordinator runtime (head-distributed only).
self._coordinator_runtime: Any | None = None
# Per-stage construction context, captured after _initialize_stages
# and used by ``_build_remote_replica`` (the RemoteReplicaFactory
# passed to Orchestrator) when a headless replica registers.
self._stage_remote_factory_contexts: dict[int, StageRemoteFactoryContext] = {}
if single_stage_mode:
logger.info(
"[AsyncOmniEngine] Single-stage mode enabled (stage_id_filter=%s, master=%s:%s)",
@@ -321,9 +345,14 @@ class AsyncOmniEngine:
self.supported_tasks: tuple[str, ...] = ("generate",)
self.default_sampling_params_list: list[OmniSamplingParams] = []
self.stage_metadata: list[StageRuntimeInfo] = []
self.request_queue: janus.Queue[EngineQueueMessage] | None = None
self.output_queue: janus.Queue[EngineQueueMessage] | None = None
self.rpc_output_queue: janus.Queue[EngineQueueMessage] | None = None
# Janus queues are constructed eagerly here (not deferred to the
# orchestrator thread) so the master server's ROUTER thread always
# sees a non-None ``self.request_queue`` when on_register fires.
# ``async_q`` lazily binds to whatever event loop first awaits on
# it (the orchestrator loop), so cross-thread use stays correct.
self.request_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self.output_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self.rpc_output_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self._shutdown_called = False
self._weak_finalizer: weakref.finalize | None = None
self._rpc_lock = threading.Lock()
@@ -443,30 +472,37 @@ class AsyncOmniEngine:
)
def _validate_single_stage_mode_replica_constraints(self) -> None:
"""Reject unsupported replica fan-out in single-stage mode."""
"""Apply --omni-dp-size-local to the local stage's runtime.num_replicas.
In the previous revision this method rejected LLM stages with
``num_replicas > 1``. The whole point of ``--omni-dp-size-local`` is
to lift that restriction for the *local* stage, so the rejection is
gone. We now use this hook to write ``--omni-dp-size-local`` onto
the self-stage's runtime config so downstream code
(``compute_replica_layout`` → ``_build_logical_stage_init_plans``)
sees a consistent view.
"""
if not self.single_stage_mode:
return
target_stage_id = self._single_stage_id_filter
if target_stage_id is None:
return
unsupported: list[tuple[int, int]] = []
for idx, stage_cfg in enumerate(self.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)
)
if num_replicas <= 1:
continue
if getattr(stage_cfg, "stage_type", "llm") == "diffusion":
continue
stage_id = int(getattr(stage_cfg, "stage_id", idx))
unsupported.append((stage_id, num_replicas))
if unsupported:
raise ValueError(
"single_stage_mode only supports num_replicas > 1 for diffusion stages; "
f"found non-diffusion stages {unsupported}"
)
runtime_cfg = getattr(stage_cfg, "runtime", None)
if runtime_cfg is None:
continue
if stage_id == target_stage_id:
# Self stage: take --omni-dp-size-local from this process.
try:
runtime_cfg.num_replicas = self._omni_dp_size_local
except Exception:
if hasattr(runtime_cfg, "__setitem__"):
runtime_cfg["num_replicas"] = self._omni_dp_size_local
# Other stages keep their config-declared num_replicas; in
# head-distributed mode they will be launched as ``launch_mode
# == "remote"`` with the configured count.
def _build_logical_stage_init_plans(
self,
@@ -540,9 +576,18 @@ class AsyncOmniEngine:
replica_metadata = extract_stage_metadata(replica_cfg)
replica_metadata.replica_id = replica_id
if self.single_stage_mode:
if replica_metadata.stage_type != "diffusion":
replica_metadata.runtime_cfg = None
# In single_stage_mode the head only owns its self stage's
# replicas; the remote-stage metadata exists only so the
# orchestrator can route requests through StagePool. Wiping
# ``runtime_cfg`` there makes sense (we don't manage those
# devices). For the *self stage* we MUST keep the
# per-replica runtime so ``setup_stage_devices`` can apply
# the device split from ``compute_replica_layout`` —
# otherwise every replica inherits the parent's full
# CUDA_VISIBLE_DEVICES and stacks on cuda:0 (OOM with any
# model whose footprint exceeds ~1/(2N) of the card).
if launch_mode == "remote" and replica_metadata.stage_type != "diffusion":
replica_metadata.runtime_cfg = None
replicas.append(
ReplicaInitPlan(
@@ -578,6 +623,11 @@ class AsyncOmniEngine:
all_stage_ids: list[int] = []
stage_replica_counts: dict[int, int] = {}
# Slots that the head itself will register (launch_mode == "local")
# — auto-assign on the master must not hand these out to remote
# headless registrations even within the race window before the
# head's own register_stage_with_omni_master call completes.
head_local_replicas: dict[int, list[int]] = {}
seen_stage_ids: set[int] = set()
for plan in stage_plans:
stage_id = plan.configured_stage_id
@@ -588,12 +638,27 @@ class AsyncOmniEngine:
seen_stage_ids.add(stage_id)
all_stage_ids.append(stage_id)
stage_replica_counts[stage_id] = len(plan.replicas)
local_rids = [rep.replica_id for rep in plan.replicas if rep.launch_mode == "local"]
if local_rids:
head_local_replicas[stage_id] = local_rids
# Start the OmniCoordinator runtime first so its router address is
# available to publish in every registration reply.
from vllm_omni.distributed.omni_coordinator import OmniCoordinatorRuntime
self._coordinator_runtime = OmniCoordinatorRuntime(
host=self._omni_master_address,
heartbeat_timeout=self._omni_heartbeat_timeout,
)
self._omni_master_server = OmniMasterServer(
master_address=self._omni_master_address,
master_port=self._omni_master_port,
stage_ids=all_stage_ids,
stage_replica_counts=stage_replica_counts,
coordinator_router_address=self._coordinator_runtime.router_address,
on_register=self._dispatch_master_register,
head_local_replicas=head_local_replicas,
)
self._omni_master_server.start()
logger.info(
@@ -601,6 +666,147 @@ class AsyncOmniEngine:
all_stage_ids,
)
# ------------------------------------------------------------------
# Remote replica factory (head-side client construction)
# ------------------------------------------------------------------
async def _build_remote_replica(self, stage_id: int, replica_id: int) -> Any:
"""Construct a head-side stage client for a newly-registered remote replica.
Used by :class:`Orchestrator` as its ``remote_replica_factory``.
The orchestrator awaits this from its own asyncio loop, so the
client is created in the same loop that owns ZMQ sockets — no
cross-thread setup is required.
Raises if the stage is not known or if its construction context
was not captured (e.g. the stage was empty at bring-up time).
"""
ctx = self._stage_remote_factory_contexts.get(stage_id)
if ctx is None:
raise RuntimeError(
f"no factory context captured for stage {stage_id}; "
f"known stages: {sorted(self._stage_remote_factory_contexts.keys())}"
)
if self._omni_master_server is None:
raise RuntimeError("OmniMasterServer is not running; cannot build remote replica")
alloc = self._omni_master_server.get_allocation(stage_id, replica_id=replica_id)
# Build a per-replica copy of the base metadata so ``replica_id``
# is correct (StageMetadata is a plain dataclass-like).
metadata = copy.copy(ctx.base_metadata)
try:
metadata.replica_id = replica_id
except Exception:
# Best-effort: if the metadata object is frozen / unusual, the
# downstream client will fall back to ``replica_id = 0``.
pass
if ctx.stage_type == "diffusion":
client = StageDiffusionClient.from_addresses(
metadata,
request_address=alloc.input_bind_address,
response_address=alloc.output_bind_address,
batch_size=ctx.diffusion_batch_size,
)
logger.info(
"[AsyncOmniEngine] Built remote diffusion client for stage=%d replica=%d (req=%s resp=%s)",
stage_id,
replica_id,
alloc.input_bind_address,
alloc.output_bind_address,
)
return client
# LLM path
if ctx.vllm_config is None or ctx.executor_class is None:
raise RuntimeError(f"stage {stage_id} factory context is missing vllm_config / executor_class")
# The headless's StageEngineCoreProc subprocess calls
# vllm.v1.engine.core.startup_handshake at boot and blocks until the
# head's handshake ROUTER answers — without this step it hits the
# built-in 5-minute timeout and exits. The bootstrap (pre-allocated)
# path runs `connect_remote_engine_cores` to perform that
# handshake; dynamic attach must do the same, otherwise every
# replica that comes in via `on_register` (auto-assigned or
# explicit-id-beyond-pre-alloc) deadlocks. Run the blocking
# handshake in a thread so the orchestrator loop stays responsive,
# then build the async client on this loop where `make_async_mp_client`
# expects to be invoked.
master_server = self._omni_master_server
ctx_vllm_config = ctx.vllm_config
ctx_executor_class = ctx.executor_class
def _run_handshake() -> Any:
with connect_remote_engine_cores(
vllm_config=ctx_vllm_config,
omni_master_server=master_server,
stage_id=stage_id,
replica_id=replica_id,
) as remote_resources:
_engine_manager, _coordinator, addresses, _ = remote_resources
return _engine_manager, _coordinator, addresses
engine_manager, coordinator, addresses = await asyncio.to_thread(_run_handshake)
client_addresses: dict[str, str] = {
"input_address": addresses.inputs[0],
"output_address": addresses.outputs[0],
}
if addresses.frontend_stats_publish_address is not None:
client_addresses["stats_update_address"] = addresses.frontend_stats_publish_address
client = StageEngineCoreClientBase.make_async_mp_client(
vllm_config=ctx_vllm_config,
executor_class=ctx_executor_class,
metadata=metadata,
client_addresses=client_addresses,
proc=None,
engine_manager=engine_manager,
coordinator=coordinator,
)
logger.info(
"[AsyncOmniEngine] Built remote LLM client for stage=%d replica=%d (input=%s)",
stage_id,
replica_id,
client_addresses["input_address"],
)
return client
# ------------------------------------------------------------------
# OmniCoordinator on_register proxy
# ------------------------------------------------------------------
def _dispatch_master_register(self, stage_id: int, replica_id: int, alloc: Any) -> None:
"""Forward a master-server registration to the orchestrator queue.
Called on :class:`OmniMasterServer`'s ROUTER thread (not the
orchestrator loop). Must return promptly. ``self.request_queue``
is initialized in :meth:`_initialize_janus_queues` (running inside
the orchestrator thread) before the master server starts, so it
is non-None here; ``janus.Queue.sync_q`` is thread-safe by
construction.
"""
if self.request_queue is None:
logger.warning(
"[AsyncOmniEngine] request_queue not initialized; dropping register_remote_replica stage=%d replica=%d",
stage_id,
replica_id,
)
return
msg = RegisterRemoteReplicaMessage(
stage_id=int(stage_id),
replica_id=int(replica_id),
)
try:
self.request_queue.sync_q.put_nowait(msg)
except Exception:
logger.exception(
"[AsyncOmniEngine] Failed to enqueue register_remote_replica for stage=%d replica=%d",
stage_id,
replica_id,
)
def _initialize_llm_replica(
self,
plan: ReplicaInitPlan,
@@ -686,6 +892,11 @@ class AsyncOmniEngine:
stage_init_timeout,
)
if self.single_stage_mode and self._omni_master_server is not None:
coord_router_addr: str | None = (
self._coordinator_runtime.router_address
if self._coordinator_runtime is not None
else None
)
engine_manager, coordinator, addresses = launch_stack.enter_context(
launch_omni_core_engines(
vllm_config=vllm_config,
@@ -695,6 +906,7 @@ class AsyncOmniEngine:
stage_id=plan.metadata.stage_id,
stage_config=stage_cfg,
replica_id=plan.replica_id,
omni_coordinator_address=coord_router_addr,
)
)
else:
@@ -830,12 +1042,20 @@ class AsyncOmniEngine:
"[AsyncOmniEngine] Stage %s diffusion registration completed",
plan.metadata.stage_id,
)
coord_router_addr: str | None = (
self._coordinator_runtime.router_address
if self._coordinator_runtime is not None
else None
)
proc, _, _, _ = spawn_diffusion_proc(
self.model,
od_config,
handshake_address=handshake_address,
request_address=request_address,
response_address=response_address,
omni_coordinator_address=coord_router_addr,
omni_stage_id=plan.metadata.stage_id,
omni_replica_id=plan.replica_id,
)
complete_diffusion_handshake(proc, handshake_address, stage_init_timeout)
logger.info(
@@ -1049,7 +1269,13 @@ class AsyncOmniEngine:
replicas_per_stage,
replica_devices_map,
)
# Capture per-stage context now (before _start_omni_master_server)
# so the on_register proxy can build head-side clients for
# registrations that arrive immediately after the server starts.
if self.single_stage_mode:
self._stage_remote_factory_contexts = capture_stage_factory_contexts(
stage_plans, diffusion_batch_size=self.diffusion_batch_size
)
self._start_omni_master_server(stage_plans)
stage_pools: list[StagePool] = []
@@ -1085,6 +1311,14 @@ class AsyncOmniEngine:
self._omni_master_server.stop()
except Exception:
logger.exception("[AsyncOmniEngine] Failed to stop OmniMasterServer during stage-init cleanup")
if self._coordinator_runtime is not None:
try:
self._coordinator_runtime.close()
except Exception:
logger.exception(
"[AsyncOmniEngine] Failed to close OmniCoordinatorRuntime during stage-init cleanup"
)
self._coordinator_runtime = None
raise
self.stage_pools = stage_pools
@@ -1104,13 +1338,6 @@ class AsyncOmniEngine:
supported_tasks.add("speech")
self.supported_tasks = tuple(supported_tasks) if supported_tasks else ("generate",)
def _initialize_janus_queues(self) -> None:
"""Initialize janus queues inside orchestrator thread loop context."""
self.request_queue = janus.Queue()
self.output_queue = janus.Queue()
self.rpc_output_queue = janus.Queue()
logger.debug("[AsyncOmniEngine] janus queues initialized in orchestrator thread loop")
def _bootstrap_orchestrator(
self,
stage_init_timeout: int,
@@ -1122,10 +1349,15 @@ class AsyncOmniEngine:
asyncio.set_event_loop(loop)
async def _run_orchestrator() -> None:
self._initialize_janus_queues()
self._initialize_stages(stage_init_timeout)
pd_config = self._detect_pd_config()
coordinator_pub_address: str | None = None
load_balancer_factory: Callable[[], LoadBalancer] | None = None
remote_replica_factory: Callable[[int, int], Awaitable[Any]] | None = None
if self._coordinator_runtime is not None:
coordinator_pub_address = self._coordinator_runtime.pub_address
load_balancer_factory = build_load_balancer_factory(self._omni_lb_policy)
remote_replica_factory = self._build_remote_replica
orchestrator = Orchestrator(
request_async_queue=self.request_queue.async_q,
output_async_queue=self.output_queue.async_q,
@@ -1133,6 +1365,9 @@ class AsyncOmniEngine:
stage_pools=self.stage_pools,
async_chunk=self.async_chunk,
pd_config=pd_config,
coordinator_pub_address=coordinator_pub_address,
load_balancer_factory=load_balancer_factory,
remote_replica_factory=remote_replica_factory,
)
if not startup_future.done():
startup_future.set_result(asyncio.get_running_loop())
@@ -1948,8 +2183,6 @@ class AsyncOmniEngine:
reasoning_ended=reasoning_ended,
resumable=resumable,
)
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
self.request_queue.sync_q.put_nowait(msg)
# CFG companion expansion: create and enqueue companion requests
@@ -2017,8 +2250,6 @@ class AsyncOmniEngine:
resumable=resumable,
message_type="streaming_update",
)
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
self.request_queue.sync_q.put_nowait(msg)
async def add_streaming_update_async(
@@ -2045,8 +2276,6 @@ class AsyncOmniEngine:
def try_get_output(self, timeout: float = 0.001) -> EngineQueueMessage | None:
"""Read one output message from the Orchestrator output queue."""
if self.output_queue is None:
return None
try:
return self.output_queue.sync_q.get(timeout=timeout)
except queue.Empty:
@@ -2056,8 +2285,6 @@ class AsyncOmniEngine:
async def try_get_output_async(self) -> EngineQueueMessage | None:
"""Async read from the Orchestrator output queue."""
if self.output_queue is None:
return None
try:
return self.output_queue.sync_q.get_nowait()
except queue.Empty:
@@ -2092,11 +2319,6 @@ class AsyncOmniEngine:
This uses a dedicated RPC output queue so control-plane messages do not
race with the normal request output polling loop.
"""
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
if self.rpc_output_queue is None:
raise RuntimeError("rpc_output_queue is not initialized")
rpc_id = uuid.uuid4().hex
msg = CollectiveRPCRequestMessage(
rpc_id=rpc_id,
@@ -2184,8 +2406,6 @@ class AsyncOmniEngine:
logger.warning("[AsyncOmniEngine] Orchestrator thread did not exit in time")
for q in (self.request_queue, self.output_queue, self.rpc_output_queue):
if q is None:
continue
try:
q.close()
except Exception:
@@ -2198,6 +2418,13 @@ class AsyncOmniEngine:
logger.exception("[AsyncOmniEngine] Failed to stop OmniMasterServer during shutdown")
self._omni_master_server = None
if self._coordinator_runtime is not None:
try:
self._coordinator_runtime.close()
except Exception:
logger.exception("[AsyncOmniEngine] Failed to close OmniCoordinatorRuntime during shutdown")
self._coordinator_runtime = None
def _try_shutdown(self, *args, **kwargs) -> None:
try:
self.shutdown()