[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

+4
View File
@@ -155,6 +155,10 @@ class OmniEngineArgs(EngineArgs):
omni_master_address: str | None = None
omni_master_port: int | None = None
# OmniCoordinator integration knobs (process-local).
omni_dp_size_local: int = 1
omni_lb_policy: str = "random"
omni_heartbeat_timeout: float = 30.0
stage_configs_path: str | None = None
output_modalities: list[str] | None = None
log_stats: bool = False
+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()
+12
View File
@@ -56,6 +56,18 @@ class ShutdownRequestMessage(EngineQueueMessage, kw_only=True):
type: Literal["shutdown"] = "shutdown"
class RegisterRemoteReplicaMessage(EngineQueueMessage, kw_only=True):
type: Literal["register_remote_replica"] = "register_remote_replica"
stage_id: int
replica_id: int
class UnregisterRemoteReplicaMessage(EngineQueueMessage, kw_only=True):
type: Literal["unregister_remote_replica"] = "unregister_remote_replica"
stage_id: int
input_addr: str
class ErrorMessage(EngineQueueMessage, kw_only=True):
type: Literal["error"] = "error"
error: str
@@ -0,0 +1,162 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Process manager for omni stage engine subprocesses.
This is a drop-in replacement for vLLM's :class:`CoreEngineProcManager` that
spawns :meth:`StageEngineCoreProc.run_stage_core` instead of the upstream
``EngineCoreProc.run_engine_core``, and forwards omni-specific kwargs
(coordinator address, stage id, per-rank replica id).
Each spawned subprocess corresponds to exactly one omni *replica*: it has its
own ZMQ allocation from :class:`OmniMasterServer` and (when an
``omni_coordinator_address`` is provided) its own
:class:`OmniCoordClientForStage` reporting heartbeat / status.
Liveness monitoring and shutdown are inherited from
:class:`CoreEngineProcManager` unchanged.
"""
from __future__ import annotations
import contextlib
import threading
import weakref
from multiprocessing.process import BaseProcess
from multiprocessing.queues import Queue
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils import numa_utils
from vllm.utils.system_utils import get_mp_context
from vllm.v1.engine.utils import CoreEngineProcManager
from vllm.v1.executor import Executor
from vllm.v1.utils import shutdown
from vllm_omni.engine.stage_engine_core_proc import StageEngineCoreProc
logger = init_logger(__name__)
try:
# ``set_device_control_env_var`` lives next to CoreEngineProcManager and
# is only required for non-CUDA DP, so we tolerate its absence on
# older / future vLLM revisions.
from vllm.v1.engine.utils import set_device_control_env_var # type: ignore
except ImportError: # pragma: no cover - depends on vLLM build
set_device_control_env_var = None # type: ignore[assignment]
class OmniCoreEngineProcManager(CoreEngineProcManager):
"""Spawn :class:`StageEngineCoreProc` subprocesses with omni kwargs.
The body mirrors :class:`CoreEngineProcManager.__init__` because the
upstream class hardcodes ``target=EngineCoreProc.run_engine_core`` and
does not expose an extensibility hook. The differences from upstream are:
* ``target`` is :meth:`StageEngineCoreProc.run_stage_core`.
* Per-rank ``omni_replica_id`` is computed as
``base_replica_id + rank_idx`` and added to each subprocess's kwargs.
* ``omni_coordinator_address`` (if provided) and ``omni_stage_id`` are
added to every subprocess's kwargs.
"""
def __init__(
self,
local_engine_count: int,
start_index: int,
local_start_index: int,
vllm_config: VllmConfig,
local_client: bool,
handshake_address: str,
executor_class: type[Executor],
log_stats: bool,
*,
omni_stage_id: int,
omni_coordinator_address: str | None = None,
omni_replica_base_id: int = 0,
client_handshake_address: str | None = None,
tensor_queue: Queue | None = None,
) -> None:
# NOTE: we intentionally do not call ``super().__init__`` — the
# parent's body hardcodes the wrong target. We re-implement it here
# while reusing the parent's instance methods (shutdown, monitor).
if local_engine_count <= 0:
raise ValueError(f"local_engine_count must be > 0, got {local_engine_count}")
context = get_mp_context()
common_kwargs: dict[str, object] = {
"vllm_config": vllm_config,
"local_client": local_client,
"handshake_address": handshake_address,
"executor_class": executor_class,
"log_stats": log_stats,
"tensor_queue": tensor_queue,
"omni_stage_id": int(omni_stage_id),
"omni_coordinator_address": omni_coordinator_address,
}
if client_handshake_address:
common_kwargs["client_handshake_address"] = client_handshake_address
# Intra-replica vLLM DP mesh (i.e. ``data_parallel_size`` ranks sharing
# one engine, one DPCoordinator, one set of weights). Distinct from
# the omni-level notion of multiple independent replicas of a stage —
# those each spawn their own OmniCoreEngineProcManager and never join
# a vLLM DP group across replicas.
has_intra_replica_dp = vllm_config.parallel_config.data_parallel_size > 1
self.processes: list[BaseProcess] = []
local_dp_ranks: list[int] = []
for index in range(local_engine_count):
local_index = local_start_index + index
global_index = start_index + index
# Each spawned subprocess is one omni replica. The replica id
# is contiguous within this manager; the master server may have
# pre-allocated a contiguous block starting at ``omni_replica_base_id``.
omni_replica_id = omni_replica_base_id + index
local_dp_ranks.append(local_index)
self.processes.append(
context.Process(
target=StageEngineCoreProc.run_stage_core,
name=(
f"StageEngineCoreProc_stage{omni_stage_id}"
f"_replica{omni_replica_id}" + (f"_DP{global_index}" if has_intra_replica_dp else "")
),
kwargs=common_kwargs
| {
"dp_rank": global_index,
"local_dp_rank": local_index,
"omni_replica_id": omni_replica_id,
},
)
)
self._finalizer = weakref.finalize(self, shutdown, self.processes)
self.manager_stopped = threading.Event()
self.failed_proc_name: str | None = None
try:
for proc, local_dp_rank in zip(self.processes, local_dp_ranks):
device_control_context: contextlib.AbstractContextManager[None] = contextlib.nullcontext()
if (
has_intra_replica_dp
and set_device_control_env_var is not None
and (not current_platform.is_cuda_alike() or vllm_config.parallel_config.use_ray)
):
device_control_context = set_device_control_env_var(vllm_config, local_dp_rank)
with (
device_control_context,
numa_utils.configure_subprocess(
vllm_config,
local_rank=0,
dp_local_rank=local_dp_rank,
process_kind="EngineCore",
),
):
proc.start()
finally:
if self.finished_procs():
self.shutdown()
+252 -8
View File
@@ -4,12 +4,20 @@ Orchestrator for vLLM-Omni multi-stage runtime.
Runs inside a background thread with its own asyncio event loop.
Owns logical request progression across stage pools and handles
stage-to-stage transfer logic.
In distributed mode (``coordinator_pub_address`` provided), it also
owns the single :class:`OmniCoordClientForHub`, runs a
:meth:`_watch_replica_list` task that converts replica disappearances
into ``unregister_remote_replica`` control messages, and handles the
``register_remote_replica`` / ``unregister_remote_replica`` flow that
attaches / detaches head-side stage clients for headless replicas.
"""
from __future__ import annotations
import asyncio
import time as _time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
@@ -22,6 +30,12 @@ from vllm.sampling_params import SamplingParams
from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
OmniCoordClientForHub,
RandomBalancer,
ReplicaStatus,
)
from vllm_omni.engine import OmniEngineCoreRequest
from vllm_omni.engine.cfg_companion_tracker import CfgCompanionTracker
from vllm_omni.engine.messages import (
@@ -32,13 +46,26 @@ from vllm_omni.engine.messages import (
EngineQueueMessage,
ErrorMessage,
OutputMessage,
RegisterRemoteReplicaMessage,
ShutdownRequestMessage,
StageMetricsMessage,
StageSubmissionMessage,
UnregisterRemoteReplicaMessage,
)
from vllm_omni.engine.serialization import serialize_additional_information
from vllm_omni.engine.stage_pool import StagePool
from vllm_omni.outputs import OmniRequestOutput
# Factory signature for building a head-side stage client for a
# *dynamically attached* (auto-assigned) remote replica.
#
# Receives ``(stage_id, replica_id)`` and returns an awaitable yielding the
# constructed client (any type — it must satisfy the shape expected by the
# matching :class:`StagePool`, i.e. expose ``client_addresses["input_address"]``
# or ``request_address``, plus the usual ``add_request_async`` /
# ``get_output_async`` / ``shutdown`` surface).
RemoteReplicaFactory = Callable[[int, int], Awaitable[Any]]
logger = init_logger(__name__)
@@ -124,6 +151,10 @@ class StreamingInputState:
class Orchestrator:
"""Runs inside a background thread's asyncio event loop."""
# Cadence at which the replica-list watcher polls for disappearances.
_WATCH_REPLICA_INTERVAL_S: float = 0.5
_WATCH_REPLICA_IDLE_INTERVAL_S: float = 1.0
def __init__(
self,
request_async_queue: janus.AsyncQueue[EngineQueueMessage],
@@ -133,6 +164,9 @@ class Orchestrator:
*,
async_chunk: bool = False,
pd_config: dict[str, Any] | None = None,
coordinator_pub_address: str | None = None,
load_balancer_factory: Callable[[], LoadBalancer] | None = None,
remote_replica_factory: RemoteReplicaFactory | None = None,
) -> None:
self.request_async_queue = request_async_queue
self.output_async_queue = output_async_queue
@@ -159,6 +193,28 @@ class Orchestrator:
self._fatal_error: str | None = None
self._fatal_error_stage_id: int | None = None
# Background tasks for fire-and-forget message handlers (currently
# only ``register_remote_replica`` and ``unregister_remote_replica``).
# Held as a set so each task's reference survives the loop and the
# task can self-deregister on completion.
self._membership_tasks: set[asyncio.Task[None]] = set()
# Distributed-mode wiring. The hub is constructed on the
# orchestrator's asyncio loop because it spawns a SUB background
# thread; building it from another thread would race the
# ``_init_done`` event.
self._hub: OmniCoordClientForHub | None = (
OmniCoordClientForHub(coordinator_pub_address) if coordinator_pub_address is not None else None
)
self._remote_replica_factory = remote_replica_factory
# Inject hub + per-pool LB into each StagePool so they can run
# distributed dispatch via ``StagePool.pick``.
if self._hub is not None:
factory = load_balancer_factory or RandomBalancer
for pool in self.stage_pools:
pool.attach_hub(self._hub)
pool.attach_load_balancer(factory())
async def run(self) -> None:
"""Main entry point for the Orchestrator event loop."""
logger.info("[Orchestrator] Starting event loop")
@@ -168,9 +224,16 @@ class Orchestrator:
self._orchestration_output_handler(),
name="orchestrator-stage-output-handler",
)
# The replica watcher only runs in distributed mode. It's still
# created in both cases so ``run()`` has a uniform task graph;
# ``_watch_replica_list`` is a no-op poll when ``self._hub`` is None.
watch_task = asyncio.create_task(
self._watch_replica_list(),
name="orchestrator-replica-watcher",
)
try:
await asyncio.gather(request_task, output_task)
await asyncio.gather(request_task, output_task, watch_task)
except asyncio.CancelledError:
raise
except EngineDeadError as e:
@@ -185,11 +248,11 @@ class Orchestrator:
raise
finally:
self._shutdown_event.set()
for task in (request_task, output_task):
for task in (request_task, output_task, watch_task):
if not task.done():
task.cancel()
try:
await asyncio.gather(request_task, output_task, return_exceptions=True)
await asyncio.gather(request_task, output_task, watch_task, return_exceptions=True)
except Exception:
pass
@@ -199,8 +262,32 @@ class Orchestrator:
if self._fatal_error is not None:
await self._drain_pending_requests_on_fatal()
# Wait briefly for any in-flight membership handlers (register /
# unregister remote replica) to finish so they don't leave the
# head-side pool in a half-attached state. Cancel anything that
# hasn't completed in time; the generic pending-task sweep below
# will collect the cancellations.
if self._membership_tasks:
try:
await asyncio.wait_for(
asyncio.gather(*self._membership_tasks, return_exceptions=True),
timeout=10.0,
)
except (asyncio.TimeoutError, Exception):
for t in self._membership_tasks:
if not t.done():
t.cancel()
self._shutdown_stages()
# Close the hub last so any in-flight dispatch still has access.
if self._hub is not None:
try:
self._hub.close()
except RuntimeError:
pass
self._hub = None
loop = asyncio.get_running_loop()
pending = [t for t in asyncio.all_tasks(loop) if t is not asyncio.current_task() and not t.done()]
for task in pending:
@@ -208,6 +295,27 @@ class Orchestrator:
if pending:
await asyncio.gather(*pending, return_exceptions=True)
# ---- Background task helpers ----
def _spawn_membership_task(self, coro: Awaitable[None], *, label: str) -> None:
"""Run a fire-and-forget membership-change coroutine.
Holds a strong reference until completion (asyncio would otherwise
garbage-collect a bare task), and logs any uncaught exception.
"""
task = asyncio.create_task(coro, name=f"orchestrator-{label}")
self._membership_tasks.add(task)
def _on_done(t: asyncio.Task[None]) -> None:
self._membership_tasks.discard(t)
if t.cancelled():
return
exc = t.exception()
if exc is not None:
logger.error("[Orchestrator] %s task crashed", label, exc_info=exc)
task.add_done_callback(_on_done)
# ---- Request handling ----
async def _request_handler(self) -> None:
@@ -226,7 +334,20 @@ class Orchestrator:
await self._handle_abort(msg)
elif msg_type == "collective_rpc":
await self._handle_collective_rpc(msg)
elif msg_type == "shutdown":
elif isinstance(msg, RegisterRemoteReplicaMessage):
# Dynamic-attach involves a ~5s blocking handshake (run in a
# thread by ``_build_remote_replica``); ``await`` here would
# block the queue and stall the next ``add_request`` until
# the attach finishes. Dispatch as a background task so the
# main message loop keeps draining.
self._spawn_membership_task(self._handle_register_remote_replica(msg), label="register_remote_replica")
elif isinstance(msg, UnregisterRemoteReplicaMessage):
# Symmetric with register: keep the main queue flowing.
self._spawn_membership_task(
self._handle_unregister_remote_replica(msg),
label="unregister_remote_replica",
)
elif isinstance(msg, ShutdownRequestMessage):
logger.info("[Orchestrator] Received shutdown signal")
self._shutdown_event.set()
# Pre-mark stage clients as shutting down to prevent
@@ -415,7 +536,7 @@ class Orchestrator:
results: list[Any] = []
stage_ids: list[int] = []
for pool in target_pools:
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
stage_result = await pool.collective_rpc(
replica_id=replica_id,
method=method,
@@ -451,7 +572,7 @@ class Orchestrator:
idle = True
for stage_id in range(self.num_stages):
pool = self.stage_pools[stage_id]
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
if self._shutdown_event.is_set():
return
@@ -1105,14 +1226,137 @@ class Orchestrator:
)
self.request_states.pop(req_id, None)
# ---- Distributed-mode replica attach / detach ----
async def _watch_replica_list(self) -> None:
"""Convert hub replica disappearances into unregister control messages."""
last_up: set[tuple[int, str]] = set()
while not self._shutdown_event.is_set():
if self._hub is None:
# No coordinator wired up; sleep coarsely and re-check shutdown.
try:
await asyncio.sleep(self._WATCH_REPLICA_IDLE_INTERVAL_S)
except asyncio.CancelledError:
raise
continue
try:
snap = self._hub.get_replica_list()
current = {(rep.stage_id, rep.input_addr) for rep in snap.replicas if rep.status == ReplicaStatus.UP}
for stage_id, addr in last_up - current:
await self.request_async_queue.put(
UnregisterRemoteReplicaMessage(
stage_id=stage_id,
input_addr=addr,
)
)
last_up = current
except asyncio.CancelledError:
raise
except Exception:
logger.exception("[Orchestrator] _watch_replica_list iteration failed")
try:
await asyncio.sleep(self._WATCH_REPLICA_INTERVAL_S)
except asyncio.CancelledError:
raise
async def _handle_register_remote_replica(self, msg: RegisterRemoteReplicaMessage) -> None:
"""Bind a head-side client for a newly registered remote replica."""
stage_id = int(msg.stage_id)
replica_id = int(msg.replica_id)
if not (0 <= stage_id < self.num_stages):
logger.warning(
"[Orchestrator] register_remote_replica: stage_id %d out of range (num_stages=%d)",
stage_id,
self.num_stages,
)
return
if self._remote_replica_factory is None:
logger.warning(
"[Orchestrator] register_remote_replica received for stage=%d replica=%d but no factory installed",
stage_id,
replica_id,
)
return
try:
await self._attach_remote_replica(stage_id, replica_id)
except Exception:
logger.exception(
"[Orchestrator] failed to attach remote replica stage=%d replica=%d",
stage_id,
replica_id,
)
async def _handle_unregister_remote_replica(self, msg: UnregisterRemoteReplicaMessage) -> None:
"""Tear down the head-side client for a vanished remote replica."""
stage_id = int(msg.stage_id)
input_addr = str(msg.input_addr)
if not (0 <= stage_id < self.num_stages):
return
pool = self.stage_pools[stage_id]
affected = pool.invalidate_addr(input_addr)
self._detach_remote_replica(stage_id, input_addr)
if affected:
await self._cleanup_request_ids(affected, abort=True)
for req_id in affected:
await self.output_async_queue.put(
ErrorMessage(
error="stage replica disappeared",
request_id=req_id,
stage_id=stage_id,
)
)
async def _attach_remote_replica(self, stage_id: int, replica_id: int) -> None:
"""Build a head-side stage client via the injected factory and register it."""
factory = self._remote_replica_factory
if factory is None:
return
pool = self.stage_pools[stage_id]
client = await factory(stage_id, replica_id)
input_addr = StagePool._client_input_addr(client)
if input_addr is None:
raise RuntimeError(
f"remote replica factory for stage {stage_id} produced a client without a discoverable input address"
)
pool.add_client(input_addr, client)
logger.info(
"[Orchestrator] attached remote replica stage=%d replica=%d addr=%s",
stage_id,
replica_id,
input_addr,
)
def _detach_remote_replica(self, stage_id: int, input_addr: str) -> None:
"""Shut down + remove the head-side client at ``input_addr``."""
pool = self.stage_pools[stage_id]
client = pool.remove_client(input_addr)
if client is None:
return
try:
client.shutdown()
except Exception:
logger.exception(
"[Orchestrator] failed to shutdown client for stage=%d addr=%s",
stage_id,
input_addr,
)
logger.info(
"[Orchestrator] detached remote replica stage=%d addr=%s",
stage_id,
input_addr,
)
def _shutdown_stages(self) -> None:
"""Shutdown all stage pools."""
if self._stages_shutdown:
return
self._stages_shutdown = True
total = sum(pool.num_replicas for pool in self.stage_pools)
total = sum(pool.live_num_replicas for pool in self.stage_pools)
logger.info("[Orchestrator] Shutting down all %d client(s)", total)
for pool in self.stage_pools:
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
pool.shutdown_replica(replica_id)
+13 -2
View File
@@ -23,6 +23,7 @@ from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.distributed.omni_connectors.utils.initialization import (
KV_TRANSFER_PORT_OFFSET,
)
from vllm_omni.distributed.omni_connectors.utils.kv_utils import kv_zmq_port
from vllm_omni.engine.stage_client import StageClientBase
from vllm_omni.engine.stage_init_utils import StageMetadata
@@ -344,7 +345,12 @@ class StageEngineCoreClientBase(StageClientBase):
try:
# Orchestrator always reports rank-0's port; receiver
# workers add their own local_rank * KV_RANK_PORT_STRIDE.
sender_port = int(base_port) + KV_TRANSFER_PORT_OFFSET + int(from_stage)
sender_port = kv_zmq_port(
int(base_port),
int(from_stage),
local_rank=0,
replica_id=self.replica_id,
)
except (TypeError, ValueError):
logger.warning(
"[StageEngineCoreClient] stage-%s [rep-%s] could not resolve sender_zmq_port "
@@ -386,7 +392,12 @@ class StageEngineCoreClientBase(StageClientBase):
# rank-0 base port; receiver workers adjust per KV_RANK_PORT_STRIDE.
return {
"host": self._kv_sender_host,
"zmq_port": base_port + kv_transfer_port_offset + int(self.stage_id),
"zmq_port": kv_zmq_port(
base_port - KV_TRANSFER_PORT_OFFSET + kv_transfer_port_offset,
int(self.stage_id),
local_rank=0,
replica_id=self.replica_id,
),
}
def set_engine_outputs(self, engine_outputs: EngineCoreOutput) -> None:
+68 -13
View File
@@ -7,6 +7,8 @@ busy loop in a subprocess, communicating with StageEngineCoreClient via ZMQ.
from __future__ import annotations
import contextlib
import os
import signal
from multiprocessing.process import BaseProcess
from typing import TYPE_CHECKING, Any
@@ -33,6 +35,8 @@ from vllm.v1.engine.utils import (
)
from vllm.v1.utils import shutdown
from vllm_omni.distributed.omni_coordinator import OmniCoordClientForStage
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.executor import Executor
@@ -53,28 +57,41 @@ class StageEngineCoreProc(EngineCoreProc):
*args: Any,
dp_rank: int = 0,
local_dp_rank: int = 0,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
**kwargs: Any,
) -> None:
"""Launch StageEngineCoreProc busy loop in background process."""
"""Launch StageEngineCoreProc busy loop in background process.
Omni-specific kwargs:
- ``omni_coordinator_address``: ROUTER address of the head-side
:class:`OmniCoordinator`. When provided, this subprocess
instantiates an :class:`OmniCoordClientForStage` after the
HELLO/INIT/READY handshake completes and reports its status +
queue length via heartbeats. The hook is wired so each
heartbeat refreshes ``queue_length`` from the live scheduler.
- ``omni_stage_id``: logical stage id this replica belongs to.
Required when ``omni_coordinator_address`` is provided.
- ``omni_replica_id``: cluster-unique replica id within the
stage (assigned by :class:`OmniMasterServer`). Used for
logging / metrics only.
"""
signal_callback: SignalCallback | None = None
maybe_register_config_serialize_by_value()
engine_core: StageEngineCoreProc | None = None
coord_client: OmniCoordClientForStage | None = None
try:
vllm_config: VllmConfig = kwargs["vllm_config"]
parallel_config = vllm_config.parallel_config
# NOTE: previous revisions hardcoded data_parallel_size=1 here
# (TODO referencing issue #984). The hardcoding has been removed
# so the DP fields propagate through from the caller exactly
# like upstream vLLM.
set_process_title(f"StageEngineCoreProc_DP{dp_rank}")
stage_label = f"stage{omni_stage_id}" if omni_stage_id is not None else "noid"
set_process_title(f"StageEngineCoreProc_{stage_label}_replica{omni_replica_id}_DP{dp_rank}")
decorate_logs()
# the current vllm-omni does not support data parallelism,
# so we set the data parallel size to 1.
# [TODO] support data parallelism in the future.
# https://github.com/vllm-project/vllm-omni/issues/984
parallel_config.data_parallel_size = 1
parallel_config.data_parallel_size_local = 1
parallel_config.data_parallel_rank = 0
parallel_config.data_parallel_index = dp_rank
os.environ["VLLM_OMNI_REPLICA_ID"] = str(max(int(omni_replica_id), 0))
engine_core = StageEngineCoreProc(
*args,
@@ -82,6 +99,41 @@ class StageEngineCoreProc(EngineCoreProc):
**kwargs,
)
# Each subprocess corresponds to exactly one omni replica with
# its own OmniMasterServer allocation, so the heartbeat client
# runs unconditionally — there is no dp_rank-based gating.
if omni_coordinator_address is not None:
if omni_stage_id is None:
raise ValueError("omni_stage_id must be provided when omni_coordinator_address is set")
addresses: EngineZmqAddresses = engine_core.addresses
if not addresses.inputs or not addresses.outputs:
raise RuntimeError(
"EngineCore handshake did not populate input/output addresses; "
"cannot start OmniCoordClientForStage"
)
coord_client = OmniCoordClientForStage(
coord_zmq_addr=omni_coordinator_address,
input_addr=addresses.inputs[0],
output_addr=addresses.outputs[0],
stage_id=int(omni_stage_id),
)
def _refresh_queue_length() -> None:
"""Pre-heartbeat hook: refresh queue_length from scheduler."""
scheduler = getattr(engine_core, "scheduler", None)
if scheduler is None:
return
try:
coord_client._queue_length = int( # type: ignore[union-attr]
scheduler.get_num_unfinished_requests()
)
except Exception:
# Live scheduler stats are best-effort — heartbeats
# must not fail because of a stats lookup error.
pass
coord_client._on_heartbeat = _refresh_queue_length
def wakeup_engine() -> None:
engine_core.input_queue.put_nowait((EngineCoreRequestType.WAKEUP, None))
@@ -111,6 +163,9 @@ class StageEngineCoreProc(EngineCoreProc):
signal.signal(signal.SIGINT, signal.SIG_DFL)
if signal_callback is not None:
signal_callback.stop()
if coord_client is not None:
with contextlib.suppress(RuntimeError):
coord_client.close()
if engine_core is not None:
engine_core.shutdown()
+390 -59
View File
@@ -4,8 +4,9 @@ from __future__ import annotations
import contextlib
import dataclasses
import socket
import threading
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from typing import Any
@@ -31,6 +32,15 @@ logger = init_logger(__name__)
StageRoute = tuple[int, int]
# Sentinel that signals "auto-assign me a replica_id" on the wire. Negative
# values are not valid replica ids, so any sub-zero value works equivalently.
AUTO_ASSIGN_REPLICA_ID = -1
# Callback signature for OmniMasterServer.on_register. Fires only for
# auto-assigned replicas (new, headless-launched). The arguments are
# (stage_id, replica_id, allocation).
OnRegisterCallback = Callable[[int, int, "StageAllocation"], None]
# Poll period (ms) used by the registration/handshake loop.
_POLL_PERIOD_MS = 5_000
# Default timeout (s) for a stage to send READY.
@@ -110,6 +120,10 @@ class OmniMasterServer:
master_port: int,
stage_ids: list[int],
stage_replica_counts: dict[int, int] | None = None,
*,
coordinator_router_address: str | None = None,
on_register: OnRegisterCallback | None = None,
head_local_replicas: dict[int, list[int]] | None = None,
) -> None:
self._address = master_address
self._port = master_port
@@ -117,25 +131,41 @@ class OmniMasterServer:
self._stage_configs: dict[StageRoute, Any] = {}
self._stage_coordinator_addresses: dict[StageRoute, StageCoordinatorAddresses] = {}
self._stage_config_events: dict[StageRoute, threading.Event] = {}
# Coordinator ROUTER address echoed back in every registration reply
# so OmniCoordClientForStage knows where to connect from inside the
# engine subprocess.
self._coordinator_router_address = coordinator_router_address
# Fires only for *newly assigned* (auto-assigned) replicas, not for
# head-side pre-allocated slots that already have head-side clients.
self._on_register = on_register
# Per-stage allocation lock + auto-assign cursor, so concurrent
# registrations from multiple headless processes for the same stage
# don't race on the routing table.
self._alloc_lock = threading.Lock()
self._stage_ids_known: set[int] = set(int(sid) for sid in stage_ids)
self._thread: threading.Thread | None = None
self._stop_event = threading.Event()
stage_replica_counts = dict(stage_replica_counts or {})
# Slots the *head* itself will fill via ``launch_omni_core_engines``
# / its own ``register_stage_with_omni_master`` call. Auto-assigning
# headless registrations must skip these even when they appear
# ``_stage_configs``-unfilled — otherwise a fast headless on the same
# host can race the head's own registration and steal slot 0.
self._head_local_slots: set[StageRoute] = set()
for sid, rids in (head_local_replicas or {}).items():
for rid in rids:
self._head_local_slots.add((int(sid), int(rid)))
for sid in stage_ids:
replica_count = max(1, int(stage_replica_counts.get(sid, 1)))
replica_count = int(stage_replica_counts.get(sid, 1))
# Allow 0 explicitly so non-self stages (head distributed mode)
# can declare "no local replicas; remote ones will register
# dynamically".
if replica_count < 0:
raise ValueError(f"stage_replica_counts[{sid}] must be >= 0, got {replica_count}")
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}",
)
self._allocate_route_locked(sid, replica_id)
logger.info(
"[OmniMasterServer] Pre-allocated addresses for stages %s (master=%s:%d)",
@@ -157,10 +187,84 @@ class OmniMasterServer:
"""Return the registration port exposed to stage launchers."""
return self._port
@property
def coordinator_router_address(self) -> str | None:
"""Return the OmniCoordinator ROUTER address echoed to replicas."""
return self._coordinator_router_address
def get_allocation(self, stage_id: int, replica_id: int = 0) -> StageAllocation:
"""Return the full address allocation for *stage_id*."""
return self._stage_routes[(stage_id, replica_id)]
# ------------------------------------------------------------------
# Allocation
# ------------------------------------------------------------------
def _allocate_route_locked(self, stage_id: int, replica_id: int) -> StageAllocation:
"""Allocate handshake/input/output ports for ``(stage_id, replica_id)``.
Idempotent: if the route already exists, returns the existing
allocation unchanged. Caller is responsible for holding
``self._alloc_lock`` when needed.
"""
route = (stage_id, replica_id)
existing = self._stage_routes.get(route)
if existing is not None:
return existing
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)
alloc = StageAllocation(
handshake_bind_address=f"tcp://{self._address}:{hs_port}",
handshake_connect_address=f"tcp://{self._address}:{hs_port}",
input_bind_address=f"tcp://{self._address}:{inp_port}",
input_connect_address=f"tcp://{self._address}:{inp_port}",
output_bind_address=f"tcp://{self._address}:{out_port}",
output_connect_address=f"tcp://{self._address}:{out_port}",
)
self._stage_routes[route] = alloc
return alloc
def _next_free_replica_id(self, stage_id: int) -> int:
"""Return the next replica id to assign for an auto-assign registration.
Strategy: prefer filling a pre-allocated-but-unfilled slot (one that
``__init__`` reserved in ``_stage_routes`` but no registration has
completed yet) so the head's bootstrap path — which waits on
``_stage_config_events[(stage_id, replica_id)]`` for specific
pre-allocated ids — unblocks. Only when every pre-allocated slot for
this stage has been filled do we allocate a fresh id.
Slots in ``_head_local_slots`` are reserved for the head's own
``launch_omni_core_engines`` registration. Auto-assign must skip
them even when ``_stage_configs`` shows them unfilled — otherwise a
same-host headless that registers before the head's own
``register_stage_with_omni_master`` call would steal slot 0.
Without this, a headless contributor using ``--omni-dp-size-local > 1``
(auto-assign mode) would skip past pre-allocated slot 0 and pick ids
beyond ``num_replicas``, deadlocking the head's
``connect_remote_engine_cores`` wait.
"""
# Pre-allocated slots that haven't received a registration yet are
# tracked by absence from ``_stage_configs``. Head-owned slots are
# not auto-assignable.
for sid, rid in sorted(self._stage_routes):
if sid != stage_id:
continue
if (sid, rid) in self._head_local_slots:
continue
if (sid, rid) not in self._stage_configs:
return rid
# Every pre-allocated slot is filled (or head-owned); allocate a
# fresh id past the existing routes.
used = {rid for (sid, rid) in self._stage_routes if sid == stage_id}
rid = 0
while rid in used:
rid += 1
return rid
def register_stage_config(
self,
stage_id: int,
@@ -280,12 +384,21 @@ class OmniMasterServer:
poller = zmq.Poller()
poller.register(reg_socket, zmq.POLLIN)
# The server runs until ``stop()`` is called so that headless replicas
# spawned after the head finished its initial bring-up can still
# register dynamically. ``pending`` is kept around purely for
# debug-level logging of which pre-allocated slots have not yet
# registered; once empty it does not terminate the loop.
pending: set[StageRoute] = set(self._stage_routes.keys())
while pending and not self._stop_event.is_set():
while not self._stop_event.is_set():
events: list[tuple[zmq.Socket, int]] = poller.poll(_POLL_PERIOD_MS) # type: ignore[assignment]
if not events:
logger.debug("[OmniMasterServer] Still waiting for registration from stages: %s", pending)
if pending:
logger.debug(
"[OmniMasterServer] Still waiting for registration from pre-allocated slots: %s",
pending,
)
continue
for sock, _ in events:
@@ -296,12 +409,12 @@ class OmniMasterServer:
# Cleanup
reg_socket.close(linger=0)
logger.info("[OmniMasterServer] All stages registered; server thread exiting.")
logger.info("[OmniMasterServer] Server thread exiting.")
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.
Returns ``(stage_id, replica_id)`` on success or ``None`` on failure.
"""
frames = reg_socket.recv_multipart()
if len(frames) < 2:
@@ -318,45 +431,186 @@ class OmniMasterServer:
logger.warning("[OmniMasterServer] Failed to decode registration message: %s", exc)
return None
stage_id: int | None = msg.get("stage_id")
replica_id = int(msg.get("replica_id", 0) or 0)
key = (stage_id, replica_id)
if key not in self._stage_routes:
stage_id_raw = msg.get("stage_id")
if not isinstance(stage_id_raw, int) or stage_id_raw < 0:
logger.warning(
"[OmniMasterServer] Received registration for unknown stage_id=%s replica_id=%s",
stage_id,
replica_id,
"[OmniMasterServer] Registration missing or invalid stage_id: %r",
stage_id_raw,
)
return None
stage_id: int = stage_id_raw
self.register_stage_config(
stage_id,
msg.get("stage_config"),
coordinator_addresses=StageCoordinatorAddresses(
coordinator_input=msg.get("coordinator_input"),
coordinator_output=msg.get("coordinator_output"),
frontend_stats_publish_address=msg.get("frontend_stats_publish_address"),
),
replica_id=replica_id,
)
incoming_replica_id = int(msg.get("replica_id", 0) or 0)
was_auto_assigned = incoming_replica_id < 0
# Distinguish two registration shapes:
# - Pre-allocated slots (concrete replica_id >= 0): the head built
# this slot during _initialize_stages. Just confirm it; do NOT
# fire ``on_register`` (the head already has a head-side client).
# - Auto-assigned slots (replica_id == AUTO_ASSIGN_REPLICA_ID):
# a *new* replica from a headless launcher. Allocate, then
# fire ``on_register`` so the orchestrator attaches.
with self._alloc_lock:
if was_auto_assigned:
replica_id = self._next_free_replica_id(stage_id)
# When auto-assign picks a slot the head pre-allocated (and
# is therefore waiting on in ``connect_remote_engine_cores``),
# the head's bootstrap path builds the head-side client. We
# must NOT also fire ``on_register`` for it; otherwise the
# orchestrator would build a duplicate client and overwrite
# the bootstrap-built one in the pool, leaking it.
preexisting_slot = (stage_id, replica_id) in self._stage_routes
alloc = self._allocate_route_locked(stage_id, replica_id)
if preexisting_slot:
was_auto_assigned = False
else:
replica_id = incoming_replica_id
if (stage_id, replica_id) not in self._stage_routes:
# Tolerate explicit replica_ids that haven't been
# pre-allocated (e.g. headless that wants a specific id).
alloc = self._allocate_route_locked(stage_id, replica_id)
was_auto_assigned = True
else:
alloc = self._stage_routes[(stage_id, replica_id)]
# Cross-host override: when the registering replica advertised
# its own bind address + ports, rewrite the StageAllocation so
# each socket is rooted on the host that actually binds it
# (the master's pre-allocated ports are unreachable from a
# remote replica's host).
#
# Diffusion and LLM stages have different binder ownership:
#
# Diffusion remote replica (StageDiffusionProc):
# - handshake: replica binds -> rewrite to replica IP
# - input : replica binds -> rewrite to replica IP
# - output : replica binds -> rewrite to replica IP
#
# LLM remote replica (CoreClient on head):
# - handshake: head binds (``connect_remote_engine_cores``)
# -> keep on master IP, worker TCP-connects
# - input : head binds (``CoreClient`` ROUTER)
# -> keep on master IP, worker TCP-connects
# - output : head binds (``CoreClient`` PULL — default
# bind=True for PULL in ``make_zmq_socket``)
# -> keep on master IP, worker TCP-connects
#
# The registrant indicates which case via the boolean
# ``replica_binds_sockets`` payload flag. It defaults to
# True (the diffusion / single-host case) so older callers
# still get the previous full-rewrite semantics. For LLM
# remote replicas, the master keeps every address on its
# own host and the remote worker establishes 3 outbound
# TCP connections to the master.
new_bind_address = msg.get("replica_bind_address")
if new_bind_address:
replica_binds_sockets = bool(msg.get("replica_binds_sockets", True))
if replica_binds_sockets:
hs_port = int(msg["replica_handshake_port"])
inp_port = int(msg["replica_input_port"])
out_port = int(msg["replica_output_port"])
hs_bind_addr = f"tcp://{new_bind_address}:{hs_port}"
inp_bind_addr = f"tcp://{new_bind_address}:{inp_port}"
out_bind_addr = f"tcp://{new_bind_address}:{out_port}"
alloc = StageAllocation(
handshake_bind_address=hs_bind_addr,
handshake_connect_address=hs_bind_addr,
input_bind_address=inp_bind_addr,
input_connect_address=inp_bind_addr,
output_bind_address=out_bind_addr,
output_connect_address=out_bind_addr,
)
self._stage_routes[(stage_id, replica_id)] = alloc
logger.info(
"[OmniMasterServer] Stage %d replica %d cross-host bind (sockets bound on %s; replica_ip=%s)",
stage_id,
replica_id,
"replica" if replica_binds_sockets else "master",
new_bind_address,
)
# Mark the slot as filled *inside* the lock. Without this,
# concurrent auto-assign registrations from a second headless
# could call ``_next_free_replica_id`` between the lock
# releasing above and the ``register_stage_config`` call
# below, observe the slot as unfilled, and hand the same
# pre-allocated handshake/input/output addresses to two
# different replicas — which then collide on
# ``zmq_socket_ctx(handshake_address, ROUTER, bind=True)``.
self.register_stage_config(
stage_id,
msg.get("stage_config"),
coordinator_addresses=StageCoordinatorAddresses(
coordinator_input=msg.get("coordinator_input"),
coordinator_output=msg.get("coordinator_output"),
frontend_stats_publish_address=msg.get("frontend_stats_publish_address"),
),
replica_id=replica_id,
)
# Fire on_register only for genuinely new (auto-assigned or newly
# allocated) replicas, on the ROUTER thread. Callback is expected to
# be cheap and non-blocking (e.g. enqueue onto an asyncio queue).
if was_auto_assigned and self._on_register is not None:
try:
self._on_register(stage_id, replica_id, alloc)
except Exception:
logger.exception(
"[OmniMasterServer] on_register callback failed for stage=%d replica=%d",
stage_id,
replica_id,
)
alloc = self._stage_routes[key]
response = msgspec.msgpack.encode(
{
"handshake_address": alloc.handshake_connect_address,
"input_address": alloc.input_bind_address,
"output_address": alloc.output_bind_address,
"replica_id": replica_id,
"coordinator_router_address": self._coordinator_router_address,
}
)
# ROUTER-DEALER: reply is [identity, payload] (no empty delimiter).
reg_socket.send_multipart([identity, response])
logger.info(
"[OmniMasterServer] Stage %d replica %d registered; assigned handshake=%s",
"[OmniMasterServer] Stage %d replica %d registered (auto=%s); handshake=%s",
stage_id,
replica_id,
was_auto_assigned,
alloc.handshake_connect_address,
)
return key
return (stage_id, replica_id)
@dataclass(frozen=True)
class StageRegistrationResponse:
"""Reply payload returned by :class:`OmniMasterServer` after a successful registration."""
handshake_address: str
input_address: str
output_address: str
replica_id: int
coordinator_router_address: str | None
def _detect_local_bind_address(master_address: str, master_port: int) -> str:
"""Return the local IP the kernel would use to reach the master.
Uses a connected UDP socket as a routing-table probe: ``connect()`` on
SOCK_DGRAM sends no packets but forces a route lookup, after which
``getsockname()[0]`` exposes the source IP that an outbound packet to
``(master_address, master_port)`` would carry. For a co-located master
this returns the loopback or eth0 IP (same effect as the legacy
``self._address`` behaviour); for a remote master it returns the
NIC IP that's actually reachable from the master — which is exactly
the address the headless's per-stage ZMQ sockets must bind on.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((master_address, master_port))
return s.getsockname()[0]
finally:
s.close()
def register_stage_with_omni_master(
@@ -367,23 +621,37 @@ 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]:
replica_id: int | None = 0,
return_full_response: bool = False,
replica_bind_address: str | None = None,
replica_binds_sockets: bool = True,
) -> str | tuple[str, str, str] | StageRegistrationResponse:
"""Register a stage with the omni master server.
Returns the per-stage handshake address by default. When
``return_addresses`` is true, also returns the stage input/output
addresses allocated by the master.
addresses allocated by the master. When ``return_full_response`` is
true, returns the full :class:`StageRegistrationResponse` including the
assigned ``replica_id`` and the OmniCoordinator ROUTER address (if
published by the master).
Pass ``replica_id=None`` to request auto-assignment of a free replica
id by the master (used by headless launchers).
"""
if replica_id is None:
wire_replica_id = AUTO_ASSIGN_REPLICA_ID
else:
wire_replica_id = int(replica_id)
reg_ctx = zmq.Context()
try:
reg_sock: zmq.Socket = reg_ctx.socket(zmq.DEALER) # type: ignore[attr-defined]
try:
reg_sock.connect(f"tcp://{omni_master_address}:{omni_master_port}")
payload = {
payload: dict[str, Any] = {
"stage_id": omni_stage_id,
"replica_id": replica_id,
"replica_id": wire_replica_id,
"stage_config": _serialize_stage_config(omni_stage_config),
}
if coordinator is not None:
@@ -392,6 +660,31 @@ def register_stage_with_omni_master(
payload["coordinator_output"] = coordinator_output
payload["frontend_stats_publish_address"] = coordinator.get_stats_publish_address()
# Always advertise THIS host's local bind address + 3 locally
# free ports so the master can root the per-stage socket
# allocation on the replica's own interface. For a co-located
# replica the detected IP matches the master's address and
# the override is a no-op semantically; for a cross-host
# replica it's what makes the headless's ROUTER bind succeed
# (otherwise the master would hand back ``tcp://<master_ip>:port``
# and ``zmq.bind`` would EADDRNOTAVAIL on the remote host).
if replica_bind_address is None:
replica_bind_address = _detect_local_bind_address(omni_master_address, omni_master_port)
hs_port, inp_port, out_port = get_open_ports_list(count=3)
payload["replica_bind_address"] = replica_bind_address
payload["replica_handshake_port"] = hs_port
payload["replica_input_port"] = inp_port
payload["replica_output_port"] = out_port
# ``False`` only for LLM headless replicas: the head's
# ``connect_remote_engine_cores`` is the binder for the
# handshake ROUTER, and ``CoreClient.__init__`` binds the
# input ROUTER and the output PULL (``make_zmq_socket``
# defaults bind=True for PULL). The master must keep all
# three addresses on the master's host so the head can
# ``bind`` them; the remote LLM worker TCP-connects across
# hosts on all three.
payload["replica_binds_sockets"] = bool(replica_binds_sockets)
reg_sock.send(msgspec.msgpack.encode(payload))
timeout_ms = _DEFAULT_STARTUP_TIMEOUT_S * 1_000
if not reg_sock.poll(timeout=timeout_ms):
@@ -402,13 +695,16 @@ def register_stage_with_omni_master(
f"for stage {omni_stage_id}."
)
response_bytes = reg_sock.recv()
response = msgspec.msgpack.decode(response_bytes)
handshake_address: str = response["handshake_address"]
input_address: str = response["input_address"]
output_address: str = response["output_address"]
response_msg = msgspec.msgpack.decode(response_bytes)
handshake_address: str = response_msg["handshake_address"]
input_address: str = response_msg["input_address"]
output_address: str = response_msg["output_address"]
assigned_replica_id: int = int(response_msg.get("replica_id", wire_replica_id))
coord_router_addr: str | None = response_msg.get("coordinator_router_address")
logger.info(
"Stage %d registered; handshake_address=%s",
"Stage %d replica %d registered; handshake_address=%s",
omni_stage_id,
assigned_replica_id,
handshake_address,
)
finally:
@@ -416,6 +712,14 @@ def register_stage_with_omni_master(
finally:
reg_ctx.term()
if return_full_response:
return StageRegistrationResponse(
handshake_address=handshake_address,
input_address=input_address,
output_address=output_address,
replica_id=assigned_replica_id,
coordinator_router_address=coord_router_addr,
)
if return_addresses:
return handshake_address, input_address, output_address
return handshake_address
@@ -543,8 +847,16 @@ def launch_omni_core_engines(
stage_id: int,
stage_config: Any = None,
replica_id: int = 0,
*,
omni_coordinator_address: str | None = None,
) -> Iterator[tuple[CoreEngineProcManager, DPCoordinator | None, EngineZmqAddresses]]:
"""Launch local engine cores using the omni registration flow."""
"""Launch local engine cores using the omni registration flow.
When ``omni_coordinator_address`` is provided, the spawned engine
subprocesses use :class:`OmniCoreEngineProcManager` and each
instantiates an :class:`OmniCoordClientForStage` after the handshake
completes so the head's :class:`OmniCoordinator` knows about them.
"""
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.
@@ -608,16 +920,35 @@ def launch_omni_core_engines(
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(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
)
if omni_coordinator_address is not None:
# Use the omni subclass so each spawned subprocess instantiates
# an OmniCoordClientForStage and heartbeats to the coordinator.
from vllm_omni.engine.omni_core_engine_proc_manager import OmniCoreEngineProcManager
local_engine_manager: CoreEngineProcManager = OmniCoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
omni_stage_id=stage_id,
omni_coordinator_address=omni_coordinator_address,
omni_replica_base_id=replica_id,
)
else:
local_engine_manager = CoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
)
yield local_engine_manager, coordinator, addresses
+115 -19
View File
@@ -61,6 +61,63 @@ class LogicalStageInitPlan:
replicas: list[ReplicaInitPlan]
@dataclass
class StageRemoteFactoryContext:
"""Per-stage context cached by AsyncOmniEngine for dynamic replica attach.
Populated once during ``_bootstrap_orchestrator`` from the per-stage
init plans. ``_build_remote_replica`` consumes it to construct the
right head-side stage client when a headless replica registers.
"""
stage_id: int
stage_type: str
stage_cfg: Any
base_metadata: Any
# LLM-only fields:
vllm_config: Any | None = None
executor_class: type | None = None
# Diffusion-only fields:
diffusion_batch_size: int = 1
def capture_stage_factory_contexts(
stage_plans: Sequence[LogicalStageInitPlan],
diffusion_batch_size: int,
) -> dict[int, StageRemoteFactoryContext]:
"""Snapshot per-stage construction context for dynamic replica attach.
Called once after ``_initialize_stages`` finishes. The captured
context holds everything ``_build_remote_replica`` needs to build a
fresh head-side client when a new headless replica registers
(vllm_config / executor_class for LLM, batch_size for diffusion,
plus the base stage metadata).
Per-replica fields like ``replica_id`` are filled in at build time,
not at capture time.
"""
contexts: dict[int, StageRemoteFactoryContext] = {}
for plan in stage_plans:
if not plan.replicas:
# Stage was declared but has zero replicas locally; we still
# want to be able to attach incoming headless ones, so use
# the stage_cfg-derived context if any replica plan exists.
continue
template = plan.replicas[0]
stage_id = int(plan.configured_stage_id)
stage_type = template.metadata.stage_type or "llm"
contexts[stage_id] = StageRemoteFactoryContext(
stage_id=stage_id,
stage_type=stage_type,
stage_cfg=template.stage_cfg,
base_metadata=template.metadata,
vllm_config=template.stage_vllm_config,
executor_class=template.executor_class,
diffusion_batch_size=diffusion_batch_size,
)
return contexts
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):
@@ -420,32 +477,59 @@ def split_devices_for_replicas(
"""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.
Otherwise, two YAML shapes are accepted:
Example::
1. **Legacy / pool mode** — ``len(devices) == num_replicas * tp_size``:
the string enumerates the full per-stage pool. Each replica gets
``tp_size`` consecutive entries. The values are logical indices
into the launcher's ``CUDA_VISIBLE_DEVICES``.
split_devices_for_replicas("1,2,3,4", num_replicas=2, tp_size=2, stage_id=1)
# → ["1,2", "3,4"]
``split_devices_for_replicas("1,2,3,4", 2, 2, 1) → ["1,2", "3,4"]``
2. **Template mode** — ``len(devices) == tp_size``: the YAML declares
a single per-replica template (the same shape one replica would
use), and is **dp-independent**. Each replica r gets the offsets
``[r*tp_size + a for a in template]`` of the launcher's
``CUDA_VISIBLE_DEVICES``. The template's entries must lie in
``[0, tp_size)``.
``split_devices_for_replicas("0,1", 2, 2, 1) → ["0,1", "2,3"]``
``split_devices_for_replicas("0,1", 4, 2, 1) → ["0,1", "2,3", "4,5", "6,7"]``
This lets the same ``devices: "0,1"`` YAML work for any
``--omni-dp-size-local``: the launcher's CVD scales, the YAML
does not.
Any other length raises ``ValueError`` (the two modes are
length-disjoint for ``num_replicas > 1``).
"""
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
if len(device_list) == num_replicas * tp_size:
return [",".join(device_list[r * tp_size : (r + 1) * tp_size]) for r in range(num_replicas)]
if len(device_list) == tp_size:
try:
offsets = [int(a) for a in device_list]
except ValueError as e:
raise ValueError(f"Stage {stage_id}: template-mode devices must be ints, got {devices_str!r}") from e
bad = [a for a in offsets if not (0 <= a < tp_size)]
if bad:
raise ValueError(
f"Stage {stage_id}: template-mode device offset(s) {bad} "
f"out of range [0, {tp_size}); devices={devices_str!r}"
)
return [",".join(str(r * tp_size + a) for a in offsets) for r in range(num_replicas)]
raise ValueError(
f"Stage {stage_id}: devices={devices_str!r} has {len(device_list)} id(s); "
f"need either {tp_size} (template, dp-independent) or "
f"{num_replicas * tp_size} (pool / legacy). "
f"num_replicas={num_replicas}, tensor_parallel_size={tp_size}."
)
def get_stage_tp_size(stage_cfg: Any) -> int:
@@ -479,9 +563,19 @@ def get_stage_devices_per_replica(stage_cfg: Any) -> int:
def compute_replica_layout(
stage_configs: Sequence[Any],
*,
allow_zero: bool = False,
) -> tuple[list[int], dict[int, list[str]]]:
"""Compute per-stage replica counts and device assignments.
Args:
stage_configs: per-stage config objects with a ``runtime`` sub-config
exposing ``num_replicas`` and ``devices``.
allow_zero: when True, ``num_replicas == 0`` is honored (used by
single-stage / head-distributed mode for non-self stages that
will be filled dynamically by remote registrations); when False
(default), the count is clamped to at least 1.
Returns:
replicas_per_stage: num_replicas per logical stage.
replica_devices_map: stage_idx -> per-replica device strings
@@ -495,7 +589,9 @@ def compute_replica_layout(
if hasattr(runtime_cfg, "get")
else getattr(runtime_cfg, "num_replicas", 1)
)
replicas_per_stage.append(max(1, num_replicas))
if num_replicas < 0:
raise ValueError(f"num_replicas must be >= 0, got {num_replicas}")
replicas_per_stage.append(num_replicas if allow_zero else max(1, num_replicas))
replica_devices_map: dict[int, list[str]] = {}
for stage_id, stage_cfg in enumerate(stage_configs):
+355 -32
View File
@@ -10,6 +10,13 @@ from typing import TYPE_CHECKING, Any, cast
from vllm.logger import init_logger
from vllm.v1.engine import EngineCoreOutputs
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
OmniCoordClientForHub,
ReplicaInfo,
ReplicaStatus,
)
from vllm_omni.distributed.omni_coordinator.load_balancer import Task
from vllm_omni.engine.stage_client import (
StagePoolClient,
StagePoolDiffusionClient,
@@ -35,7 +42,33 @@ class _ReplicaMetrics:
class StagePool:
"""Replicas of one logical stage with RR + affinity selection."""
"""Replicas of one logical stage + per-stage routing (LB + affinity).
The pool owns the head-side stage clients for one logical stage. It also
absorbs the per-stage dispatch responsibility (load balancing, affinity
tracking, bounded-wait pick) that used to live in a separate
``StageDispatcher`` class — see the design doc for the rationale.
In distributed mode (when an :class:`OmniCoordClientForHub` and a
:class:`LoadBalancer` are injected via :meth:`attach_hub` /
:meth:`attach_load_balancer`), :meth:`pick` consults the hub's cached
replica list and routes via the load balancer, sticking subsequent calls
for the same ``request_id`` to the same replica.
In non-distributed mode (no hub attached), :meth:`pick` falls back to the
legacy ``select_replica_id`` round-robin path so the multi-stage
in-process invocation is unchanged.
Dynamic replica membership: when a remote replica is added or removed
(driven by :class:`Orchestrator` via :meth:`add_client` /
:meth:`remove_client`), the pool keeps stable integer ``replica_id``s by
storing clients in a list whose entries can be ``None`` after a removal.
Iteration callers should use :meth:`live_replica_ids` rather than
``range(pool.num_replicas)`` to skip the gaps.
"""
DISPATCH_WAIT_TIMEOUT_S: float = 10.0
DISPATCH_RETRY_INTERVAL_S: float = 0.1
def __init__(
self,
@@ -50,33 +83,69 @@ class StagePool:
else:
normalized_clients = [clients]
if not normalized_clients:
raise ValueError(f"StagePool for stage {stage_id} has no replicas")
# Allow empty pools when running in distributed head mode for a
# non-self stage; clients will arrive via add_client(...).
self.stage_id = stage_id
self.clients: list[StagePoolClient] = normalized_clients
# Slots can become None after a dynamic remove_client (distributed mode);
# iterate via live_replica_ids() to skip holes.
self.clients: list[StagePoolClient | None] = list(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]
# Distributed-mode state. Populated by add_client / remove_client.
self._addr_to_replica_id: dict[str, int] = {}
for replica_id, client in enumerate(self.clients):
if client is not None:
addr = self._client_input_addr(client)
if addr is not None:
self._addr_to_replica_id[addr] = replica_id
# Distributed-mode dispatch hooks (injected by Orchestrator on bring-up).
self._hub: OmniCoordClientForHub | None = None
self._lb: LoadBalancer | None = None
# ``request_id`` → ``input_addr`` affinity (distributed mode only).
# Kept separate from the legacy ``_request_bindings`` so the two
# binding shapes do not collide.
self._affinity: dict[str, str] = {}
# ---- Stage-level properties ----
@property
def num_replicas(self) -> int:
"""Total slot count, including ``None`` holes from removed replicas.
Use :meth:`live_replica_ids` to iterate only live entries.
"""
return len(self.clients)
@property
def live_num_replicas(self) -> int:
"""Number of currently live (non-None) replicas in this pool."""
return sum(1 for c in self.clients if c is not None)
def live_replica_ids(self) -> list[int]:
"""Return the indices of currently live replicas in this pool."""
return [i for i, c in enumerate(self.clients) if c is not None]
@property
def stage_type(self) -> str | None:
return self.stage_client.stage_type
client = self.stage_client
return None if client is None else client.stage_type
@property
def final_output(self) -> bool:
return self.clients[0].final_output
client = self.stage_client
return False if client is None else bool(client.final_output)
@property
def stage_client(self) -> StagePoolClient:
return self.clients[0]
def stage_client(self) -> StagePoolClient | None:
for client in self.clients:
if client is not None:
return client
return None
@property
def llm_stage_client(self) -> StagePoolLLMClient:
@@ -90,11 +159,209 @@ class StagePool:
def output_processor(self) -> Any:
return self._output_processor
# ---- Route binding lifecycle ----
@property
def is_distributed(self) -> bool:
"""True iff a hub has been attached (i.e. running in head-distributed mode)."""
return self._hub is not None
# ---- Distributed-mode dispatch hooks ----
def attach_hub(self, hub: OmniCoordClientForHub | None) -> None:
"""Inject the shared :class:`OmniCoordClientForHub`.
Called once by :class:`Orchestrator` after the hub is constructed.
``hub=None`` keeps the pool in legacy mode (no behavior change).
"""
self._hub = hub
def attach_load_balancer(self, lb: LoadBalancer | None) -> None:
"""Inject the per-pool :class:`LoadBalancer` for distributed-mode pick."""
self._lb = lb
# ---- Dynamic membership (distributed mode) ----
@staticmethod
def _client_input_addr(client: Any) -> str | None:
"""Return the input ZMQ address advertised by ``client`` if any.
LLM clients expose ``client_addresses["input_address"]``; diffusion
clients expose ``request_address``. Both are stable strings used by
:class:`OmniCoordinator` to key replicas.
"""
request_address = getattr(client, "request_address", None)
if isinstance(request_address, str) and request_address:
return request_address
addrs = getattr(client, "client_addresses", None)
if isinstance(addrs, dict):
addr = addrs.get("input_address")
if isinstance(addr, str) and addr:
return addr
return None
def add_client(self, input_addr: str, client: Any) -> int:
"""Register a head-side client for ``input_addr``.
Returns the assigned ``replica_id`` (index into :attr:`clients`).
If the address is already known, replaces the existing client and
returns its existing id (this should not happen in practice — the
master server assigns unique slots — but the contract is idempotent
to keep the dispatch layer robust).
"""
if not input_addr:
raise ValueError("input_addr must be a non-empty string")
existing = self._addr_to_replica_id.get(input_addr)
if existing is not None:
self.clients[existing] = client
return existing
replica_id = len(self.clients)
self.clients.append(client)
self._addr_to_replica_id[input_addr] = replica_id
self._replica_metrics.append(_ReplicaMetrics())
return replica_id
def remove_client(self, input_addr: str) -> Any | None:
"""Remove the client at ``input_addr``. Returns the removed client or ``None``.
Slot is marked ``None`` to preserve indices for outstanding bindings.
"""
replica_id = self._addr_to_replica_id.pop(input_addr, None)
if replica_id is None:
return None
client = self.clients[replica_id]
self.clients[replica_id] = None
return client
def get_client_by_addr(self, input_addr: str) -> Any | None:
"""Return the live client for ``input_addr`` if present."""
replica_id = self._addr_to_replica_id.get(input_addr)
if replica_id is None:
return None
return self.clients[replica_id]
def get_replica_id_by_addr(self, input_addr: str) -> int | None:
"""Return the stable replica_id for ``input_addr`` if registered."""
return self._addr_to_replica_id.get(input_addr)
# ---- Per-request distributed dispatch ----
async def pick(
self,
request_id: str,
task: Task | None = None,
*,
affinity_request_id: str | None = None,
) -> int:
"""Return a replica id for ``request_id``.
In distributed mode: consults the hub for UP replicas, runs the load
balancer, and records affinity so future picks for the same
``request_id`` return the same replica. Bounded wait up to
``DISPATCH_WAIT_TIMEOUT_S`` when no UP replica is currently usable.
In non-distributed (legacy) mode: delegates to
:meth:`select_replica_id`.
"""
if self._hub is None or self._lb is None:
return self.select_replica_id(request_id, affinity_request_id=affinity_request_id)
# 1. Sticky: previously bound and still serviceable?
bound_addr = self._affinity.get(request_id)
if bound_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(bound_addr)
if replica_id is not None:
return replica_id
# Bound replica is gone or DOWN — fall through to re-select.
self._affinity.pop(request_id, None)
# 2. Inherited affinity (CFG companion sharing a parent request_id).
if affinity_request_id is not None:
parent_addr = self._affinity.get(affinity_request_id)
if parent_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(parent_addr)
if replica_id is not None:
self._affinity[request_id] = parent_addr
return replica_id
# 3. Fresh pick: poll hub + LB with bounded wait.
task = task or Task(request_id=request_id)
deadline = _time.monotonic() + self.DISPATCH_WAIT_TIMEOUT_S
while True:
candidates = self._collect_serviceable_replicas()
if candidates:
# LB chose an index *into our candidates list*.
lb_idx = self._lb.select(task, [rep for rep, _ in candidates])
replica_info, replica_id = candidates[lb_idx]
self._affinity[request_id] = replica_info.input_addr
return replica_id
now = _time.monotonic()
if now >= deadline:
raise RuntimeError(f"no UP replica for stage {self.stage_id} after {self.DISPATCH_WAIT_TIMEOUT_S:.1f}s")
await asyncio.sleep(min(self.DISPATCH_RETRY_INTERVAL_S, deadline - now))
def _collect_serviceable_replicas(self) -> list[tuple[ReplicaInfo, int]]:
"""Return list of ``(ReplicaInfo, replica_id)`` for UP, attached replicas."""
if self._hub is None:
return []
snap = self._hub.get_replicas_for_stage(self.stage_id)
out: list[tuple[ReplicaInfo, int]] = []
for rep in snap.replicas:
if rep.status != ReplicaStatus.UP:
continue
replica_id = self._addr_to_replica_id.get(rep.input_addr)
if replica_id is None:
continue # Hub knows about it but head-side client not attached yet.
if self.clients[replica_id] is None:
continue
out.append((rep, replica_id))
return out
def _serviceable_replica_id_for_addr(self, input_addr: str) -> int | None:
"""Return ``replica_id`` for ``input_addr`` iff currently UP + attached."""
if self._hub is None:
return None
replica_id = self._addr_to_replica_id.get(input_addr)
if replica_id is None or self.clients[replica_id] is None:
return None
snap = self._hub.get_replicas_for_stage(self.stage_id)
for rep in snap.replicas:
if rep.input_addr == input_addr and rep.status == ReplicaStatus.UP:
return replica_id
return None
def bind(self, request_id: str, input_addr: str) -> None:
"""Explicitly record affinity (distributed mode)."""
self._affinity[request_id] = input_addr
def release(self, request_id: str) -> None:
"""Drop affinity (distributed mode) and legacy binding for ``request_id``."""
self._affinity.pop(request_id, None)
self.release_binding(request_id)
def invalidate_addr(self, input_addr: str) -> list[str]:
"""Drop affinity rows pointing at ``input_addr``; return affected request ids."""
affected: list[str] = [rid for rid, addr in self._affinity.items() if addr == input_addr]
for rid in affected:
self._affinity.pop(rid, None)
return affected
# ---- Legacy (non-distributed) route binding ----
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)
"""Return the currently bound replica id for *request_id* if present.
In distributed mode the binding may have been recorded via
:meth:`pick`; we honor it transparently here.
"""
legacy = self._request_bindings.get(request_id)
if legacy is not None:
return legacy
addr = self._affinity.get(request_id)
if addr is None:
return None
return self._addr_to_replica_id.get(addr)
def get_bound_client(self, request_id: str) -> StagePoolClient | None:
"""Return the currently bound client for *request_id* if present."""
@@ -113,6 +380,7 @@ class StagePool:
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)
self._affinity.pop(request_id, None)
def release_bindings(self, request_ids: list[str]) -> None:
"""Drop route bindings for the given request ids in this stage."""
@@ -125,27 +393,43 @@ class StagePool:
*,
affinity_request_id: str | None = None,
) -> int:
"""Pick a replica id for *request_id* and cache the choice."""
"""Pick a replica id for *request_id* and cache the choice (legacy path)."""
cached = self.get_bound_replica_id(request_id)
if cached is not None:
if cached is not None and self.clients[cached] is not None:
return cached
chosen = self.get_bound_replica_id(affinity_request_id) if affinity_request_id is not None else None
chosen: int | None = None
if affinity_request_id is not None:
parent = self.get_bound_replica_id(affinity_request_id)
if parent is not None and self.clients[parent] is not None:
chosen = parent
if chosen is None:
if self.num_replicas == 1:
chosen = 0
live = self.live_replica_ids()
if not live:
raise RuntimeError(f"stage {self.stage_id} has no live replicas")
if len(live) == 1:
chosen = live[0]
else:
chosen = self._next_replica_id
self._next_replica_id = (self._next_replica_id + 1) % self.num_replicas
# Round-robin over live replicas only.
start = self._next_replica_id % len(live)
chosen = live[start]
self._next_replica_id = (self._next_replica_id + 1) % len(live)
self._request_bindings[request_id] = chosen
return chosen
def _llm_client(self, replica_id: int) -> StagePoolLLMClient:
return cast(StagePoolLLMClient, self.clients[replica_id])
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
return cast(StagePoolLLMClient, client)
def _diffusion_client(self, replica_id: int) -> StagePoolDiffusionClient:
return cast(StagePoolDiffusionClient, self.clients[replica_id])
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
return cast(StagePoolDiffusionClient, client)
# ---- Metrics ----
@@ -206,7 +490,7 @@ class StagePool:
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(
replica_id = await self._pick_or_select(
request_id,
affinity_request_id=affinity_request_id,
)
@@ -217,10 +501,13 @@ class StagePool:
await client.add_request_async(request_id, request, params, **submit_kwargs)
return replica_id
replica_id = self.select_replica_id(
replica_id = await self._pick_or_select(
request_id,
affinity_request_id=affinity_request_id,
)
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
try:
self.output_processor.add_request(
request=request,
@@ -262,8 +549,12 @@ class StagePool:
"""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 replica_id is None or self.clients[replica_id] is None:
replica_id = await self._pick_or_select(request_id)
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
if self.stage_type == "diffusion":
await self._diffusion_client(replica_id).add_request_async(request_id, request, params)
@@ -281,6 +572,17 @@ class StagePool:
await self._llm_client(replica_id).add_request_async(request)
return replica_id
async def _pick_or_select(
self,
request_id: str,
*,
affinity_request_id: str | None = None,
) -> int:
"""Bridge to ``pick`` in distributed mode or ``select_replica_id`` legacy."""
if self.is_distributed:
return await self.pick(request_id, affinity_request_id=affinity_request_id)
return self.select_replica_id(request_id, affinity_request_id=affinity_request_id)
# ---- Stage-local polling ----
async def _poll_stage_raw(self, client: StagePoolLLMClient) -> EngineCoreOutputs | None:
@@ -296,7 +598,10 @@ class StagePool:
raw_outputs: EngineCoreOutputs,
) -> list[Any]:
"""Run the shared LLM output processor on one raw poll result."""
client = self._llm_client(replica_id)
raw_client = self.clients[replica_id]
if raw_client is None:
return []
client = cast(StagePoolLLMClient, raw_client)
processor = self.output_processor
processed = processor.process_outputs(
raw_outputs.outputs,
@@ -319,7 +624,10 @@ class StagePool:
timeout_s: float = 0.001,
) -> EngineCoreOutputs | None:
"""Poll raw EngineCore outputs from one LLM replica once."""
client = self._llm_client(replica_id)
raw_client = self.clients[replica_id]
if raw_client is None:
return None
client = cast(StagePoolLLMClient, raw_client)
try:
return await asyncio.wait_for(
self._poll_stage_raw(client),
@@ -339,7 +647,10 @@ class StagePool:
def poll_diffusion_output(self, replica_id: int) -> Any | None:
"""Drain one ready diffusion output from the given replica if present."""
return self._diffusion_client(replica_id).get_diffusion_output_nowait()
raw_client = self.clients[replica_id]
if raw_client is None:
return None
return cast(StagePoolDiffusionClient, raw_client).get_diffusion_output_nowait()
# ---- Stage-local control plane ----
@@ -347,7 +658,7 @@ class StagePool:
"""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.
(``request_id -> replica_id``) is pool-owned.
"""
if not request_ids:
return
@@ -355,13 +666,16 @@ class StagePool:
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)
if replica_id is None or self.clients[replica_id] is None:
logger.debug("[StagePool] abort: no live 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)
client = self.clients[replica_id]
if client is None:
continue
await client.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
@@ -377,10 +691,15 @@ class StagePool:
timeout: float | None = None,
args: tuple[Any, ...] = (),
kwargs: dict[str, Any] | None = None,
) -> Any:
) -> dict[str, Any] | Any:
"""Dispatch a stage-scoped control-plane RPC to one physical route."""
kwargs = dict(kwargs or {})
client = self.clients[replica_id]
if client is None:
return {
"supported": False,
"error": f"stage {self.stage_id} replica {replica_id} is not attached",
}
try:
return await client.collective_rpc_async(
method=method,
@@ -402,7 +721,11 @@ class StagePool:
def shutdown_replica(self, replica_id: int) -> None:
"""Shutdown one backend handle in this stage pool."""
if replica_id >= len(self.clients):
return
client = self.clients[replica_id]
if client is None:
return
try:
client.shutdown()
logger.info(