[Refactor] Omni Stage Runtime and Distributed Replica Control Plane (#3855)

Signed-off-by: yinpeiqi <yinpeiqi809@gmail.com>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Chenguang ZHENG <645327136@qq.com>
This commit is contained in:
authored and GitHub committed 2026-06-17 14:13:20 +08:00
1 parent 83e3b129f0
commit 64a5bb92de
28 files changed
+3490 -3094

No files matched your search

File diff suppressed because it is too large. Load diff
+194
View File
@@ -0,0 +1,194 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""MembershipController: distributed replica lifecycle management.
Extracted from Orchestrator to keep request-flow code free of distributed
concerns. Owns the OmniCoordClientForHub, watches for replica
disappearances, and handles register/unregister by building head-side
clients via an injected factory and mutating StagePool membership.
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
from vllm.logger import init_logger
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
)
from vllm_omni.distributed.omni_coordinator.messages import ReplicaStatus
from vllm_omni.distributed.omni_coordinator.omni_coord_client_for_hub import OmniCoordClientForHub
from vllm_omni.engine.messages import EngineQueueMessage, ErrorMessage
from vllm_omni.engine.stage_pool import StagePool
logger = init_logger(__name__)
RemoteReplicaFactory = Callable[[int, int], Any]
class MembershipController:
"""Manages dynamic replica attach/detach for distributed mode.
Constructed by DistStageRuntime and passed to Orchestrator.
The Orchestrator delegates register/unregister messages here.
"""
WATCH_INTERVAL_S: float = 0.5
def __init__(
self,
stage_pools: list[StagePool],
coordinator_pub_address: str,
load_balancer_factory: Callable[[], LoadBalancer],
remote_replica_factory: RemoteReplicaFactory,
) -> None:
self._stage_pools = stage_pools
self._remote_replica_factory = remote_replica_factory
self._membership_tasks: set[asyncio.Task[None]] = set()
self._shutdown_event = asyncio.Event()
self._watcher_task: asyncio.Task[None] | None = None
self._output_queue: asyncio.Queue[EngineQueueMessage] | None = None
self._cleanup_callback: Callable[[list[str]], Awaitable[None]] | None = None
self._hub = OmniCoordClientForHub(coordinator_pub_address)
factory = load_balancer_factory
for pool in self._stage_pools:
pool.attach_hub(self._hub)
pool.attach_load_balancer(factory())
def start(self) -> asyncio.Task[None]:
"""Start the replica watcher as a background task. Returns the task."""
self._watcher_task = asyncio.create_task(self._watch_replica_list(), name="membership-watcher")
return self._watcher_task
async def handle_register(self, stage_id: int, replica_id: int) -> None:
"""Handle a register_remote_replica message (fire-and-forget)."""
self._spawn_task(
self._do_register(stage_id, replica_id),
label=f"register-s{stage_id}-r{replica_id}",
)
async def handle_unregister(
self,
stage_id: int,
input_addr: str,
output_queue: asyncio.Queue[EngineQueueMessage] | None = None,
cleanup_callback: Callable[[list[str]], Awaitable[None]] | None = None,
) -> None:
"""Handle an unregister_remote_replica message."""
pool = self._pool_for_stage_id(stage_id)
if pool is None:
return
effective_output_queue = output_queue if output_queue is not None else self._output_queue
effective_cleanup_callback = cleanup_callback if cleanup_callback is not None else self._cleanup_callback
affected = pool.invalidate_addr(input_addr)
self._detach_replica(stage_id, input_addr)
if affected and effective_cleanup_callback is not None:
await effective_cleanup_callback(affected)
if affected and effective_output_queue is not None:
for req_id in affected:
await effective_output_queue.put(
ErrorMessage(error="stage replica disappeared", request_id=req_id, stage_id=stage_id)
)
def shutdown(self) -> None:
"""Signal stop and close the hub."""
self._shutdown_event.set()
if self._hub is not None:
self._hub.close()
self._hub = None
if self._watcher_task is not None and not self._watcher_task.done():
self._watcher_task.cancel()
async def drain_tasks(self, timeout: float = 10.0) -> None:
"""Wait for in-flight membership tasks to complete."""
if self._membership_tasks:
await asyncio.wait(self._membership_tasks, timeout=timeout)
# ---- Internal ----
def _spawn_task(self, coro: Awaitable[None], *, label: str) -> None:
task = asyncio.create_task(coro, name=f"membership-{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("[MembershipController] %s task crashed", label, exc_info=exc)
task.add_done_callback(_on_done)
async def _watch_replica_list(self) -> None:
"""Convert hub replica disappearances into unregister actions."""
last_up: set[tuple[int, str]] = set()
while not self._shutdown_event.is_set():
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:
self._spawn_task(
self.handle_unregister(stage_id, addr),
label=f"unregister-s{stage_id}",
)
last_up = current
except asyncio.CancelledError:
raise
except Exception:
logger.exception("[MembershipController] _watch_replica_list iteration failed")
try:
await asyncio.sleep(self.WATCH_INTERVAL_S)
except asyncio.CancelledError:
raise
async def _do_register(self, stage_id: int, replica_id: int) -> None:
pool = self._pool_for_stage_id(stage_id)
if pool is None:
logger.warning("[MembershipController] register: stage_id %d out of range", stage_id)
return
client = await asyncio.to_thread(self._remote_replica_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 input address")
pool.add_client(input_addr, client)
logger.info(
"[MembershipController] attached remote replica stage=%d replica=%d addr=%s",
stage_id,
replica_id,
input_addr,
)
def _detach_replica(self, stage_id: int, input_addr: str) -> None:
pool = self._pool_for_stage_id(stage_id)
if pool is None:
return
client = pool.remove_client(input_addr)
if client is None:
return
try:
client.shutdown()
except Exception:
logger.exception("[MembershipController] failed to shutdown client stage=%d addr=%s", stage_id, input_addr)
logger.info("[MembershipController] detached replica stage=%d addr=%s", stage_id, input_addr)
def install_unregister_handlers(
self,
*,
output_queue: asyncio.Queue[EngineQueueMessage],
cleanup_callback: Callable[[list[str]], Awaitable[None]],
) -> None:
"""Install shared cleanup sinks for watcher-driven unregister events."""
self._output_queue = output_queue
self._cleanup_callback = cleanup_callback
def _pool_for_stage_id(self, stage_id: int) -> StagePool | None:
if not (0 <= stage_id < len(self._stage_pools)):
return None
return self._stage_pools[stage_id]
+32 -244
View File
@@ -5,19 +5,14 @@ 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.
Distributed membership (replica attach/detach, hub monitoring) is
handled by :class:`MembershipController`, which is injected optionally.
"""
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
@@ -31,14 +26,9 @@ from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.metrics.stats import IterationStats
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.membership_controller import MembershipController
from vllm_omni.engine.messages import (
AbortRequestMessage,
AddCompanionRequestMessage,
@@ -59,16 +49,6 @@ from vllm_omni.metrics.prometheus import OmniRequestCounter
from vllm_omni.metrics.stat_logger import OmniPrometheusStatLogger
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__)
@@ -159,10 +139,6 @@ 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
# Class-level defaults so tests that bypass __init__ via object.__new__
# don't AttributeError when transfer / counter emit paths access them.
_running_counter: OmniRequestCounter | None = None
@@ -178,10 +154,8 @@ class Orchestrator:
*,
async_chunk: bool = False,
pd_config: dict[str, Any] | None = None,
membership_controller: MembershipController | None = None,
running_counter: OmniRequestCounter | None = None,
coordinator_pub_address: str | None = None,
load_balancer_factory: Callable[[], LoadBalancer] | None = None,
remote_replica_factory: RemoteReplicaFactory | None = None,
transfer_emitter: Any = None,
log_stats: bool = False,
) -> None:
@@ -212,27 +186,8 @@ 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())
# Distributed membership (optional, injected by DistStageRuntime)
self._membership = membership_controller
def _init_metrics_state(
self,
@@ -308,16 +263,22 @@ 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",
)
# Start membership watcher if distributed mode is active.
membership_watcher: asyncio.Task[None] | None = None
if self._membership is not None:
self._membership.install_unregister_handlers(
output_queue=self.output_async_queue,
cleanup_callback=lambda ids: self._cleanup_request_ids(ids, abort=True),
)
membership_watcher = self._membership.start()
tasks = [request_task, output_task]
if membership_watcher is not None:
tasks.append(membership_watcher)
try:
await asyncio.gather(request_task, output_task, watch_task)
await asyncio.gather(*tasks)
except asyncio.CancelledError:
raise
except EngineDeadError as e:
@@ -332,46 +293,23 @@ class Orchestrator:
raise
finally:
self._shutdown_event.set()
for task in (request_task, output_task, watch_task):
for task in tasks:
if not task.done():
task.cancel()
try:
await asyncio.gather(request_task, output_task, watch_task, return_exceptions=True)
await asyncio.gather(*tasks, return_exceptions=True)
except Exception:
pass
# If a fatal error caused the shutdown, drain any pending
# add_request messages that were never processed and broadcast
# fatal error responses so callers are not left hanging.
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()
if self._membership is not None:
await self._membership.drain_tasks(timeout=10.0)
self._membership.shutdown()
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:
@@ -379,27 +317,6 @@ 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:
@@ -419,18 +336,11 @@ class Orchestrator:
elif msg_type == "collective_rpc":
await self._handle_collective_rpc(msg)
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")
if self._membership is not None:
await self._membership.handle_register(msg.stage_id, msg.replica_id)
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",
)
if self._membership is not None:
await self._membership.handle_unregister(msg.stage_id, msg.input_addr)
elif isinstance(msg, ShutdownRequestMessage):
logger.info("[Orchestrator] Received shutdown signal")
self._shutdown_event.set()
@@ -441,7 +351,8 @@ class Orchestrator:
for client in pool.clients:
if hasattr(client, "_shutting_down"):
client._shutting_down = True
self._shutdown_stages()
# Stage teardown runs once in run()'s finally after the
# orchestration loop observes _shutdown_event and exits.
break
else:
logger.warning("[Orchestrator] Unknown message type: %s", msg_type)
@@ -1300,7 +1211,7 @@ class Orchestrator:
for next_input in next_inputs:
# Only AR thinker stages consume encoder mm_features; downstream
# (talker/code2wav/…) must not see them (avoids encoder-cache misses).
model_stage = getattr(next_client, "model_stage", None)
model_stage = getattr(getattr(next_pool.stage_vllm_config, "model_config", None), "model_stage", None)
mm_features = req_state.mm_features if model_stage == "thinker" else None
request = build_engine_core_request_from_tokens(
request_id=req_id,
@@ -1495,129 +1406,6 @@ 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:
+2 -2
View File
@@ -26,9 +26,11 @@ class StageClient(Protocol):
stage_id: int
replica_id: int
stage_type: str
model_stage: str | None
final_output: bool
final_output_type: FinalOutputModalityType | None
default_sampling_params: OmniSamplingParams
prompt_expand_func: Any | None
requires_multimodal_data: bool
custom_process_input_func: Any | None
engine_input_source: Sequence[int]
@@ -66,8 +68,6 @@ class StagePoolClient(StageClient, Protocol):
class StagePoolLLMClient(StagePoolClient, Protocol):
"""Pool-facing API for LLM-style stages."""
model_stage: str | None
async def add_request_async(self, request: EngineCoreRequest) -> None: ...
async def get_output_async(self) -> EngineCoreOutputs: ...
+17 -123
View File
@@ -6,18 +6,12 @@ Directly inherits from vLLM's AsyncMPClient to reuse EngineCore architecture.
from __future__ import annotations
import contextlib
import inspect
import multiprocessing.connection
import os
import socket
import threading
import time
import weakref
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
import psutil
import vllm.v1.engine as _vllm_engine_module
import vllm.v1.engine.core_client as _vllm_core_client_module
from vllm.logger import init_logger
@@ -43,8 +37,6 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
SHUTDOWN_TIMEOUT_S = 5
def _default_process_engine_inputs(
source_outputs: list[Any],
@@ -78,10 +70,8 @@ class StageEngineCoreClientBase(StageClientBase):
- outputs_queue, output_queue_task
- All utility methods (get_output_async, abort_requests_async, etc.)
The subprocess is spawned externally via ``spawn_stage_core`` /
``complete_stage_handshake`` from *stage_engine_core_proc.py*.
In single-stage CLI mode, the client may instead attach to an
``engine_manager`` / ``coordinator`` pair created elsewhere.
The stage engine subprocesses are owned by vLLM-style engine managers
(`resources.engine_manager`), matching `MPClient` ownership.
"""
replica_id: int = 0
@@ -93,7 +83,6 @@ class StageEngineCoreClientBase(StageClientBase):
log_stats: bool = False,
metadata: StageMetadata | None = None,
client_addresses: dict[str, str] | None = None,
proc: Any = None,
engine_manager: Any = None,
coordinator: Any = None,
client_count: int = 1,
@@ -107,7 +96,6 @@ class StageEngineCoreClientBase(StageClientBase):
log_stats=log_stats,
metadata=metadata,
client_addresses=client_addresses,
proc=proc,
engine_manager=engine_manager,
coordinator=coordinator,
client_count=client_count,
@@ -125,7 +113,6 @@ class StageEngineCoreClientBase(StageClientBase):
executor_class: type,
log_stats: bool = False,
client_addresses: dict[str, str] | None = None,
proc: Any = None,
client_count: int = 1,
client_index: int = 0,
*,
@@ -140,10 +127,8 @@ class StageEngineCoreClientBase(StageClientBase):
via helpers in stage_init_utils.py. This constructor just stores metadata
and calls super().__init__().
The subprocess is spawned externally via ``spawn_stage_core`` /
``complete_stage_handshake`` (see *stage_engine_core_proc.py*).
The resulting ``proc`` handle is passed in so this client can
manage the process lifecycle on shutdown.
The subprocess lifecycle is owned by the engine manager attached to
vLLM's background resources, not by this client directly.
"""
# -------- Stage metadata (public fields used at runtime) --------
self.replica_id = 0
@@ -151,19 +136,17 @@ class StageEngineCoreClientBase(StageClientBase):
self.stage_id = metadata.stage_id
self.replica_id = getattr(metadata, "replica_id", 0)
self.stage_type = metadata.stage_type
self.engine_output_type = metadata.engine_output_type
self.model_stage = metadata.model_stage
self.is_comprehension = metadata.is_comprehension
self.requires_multimodal_data = metadata.requires_multimodal_data
self.engine_input_source = metadata.engine_input_source
self.final_output = metadata.final_output
self.final_output_type = metadata.final_output_type
self.default_sampling_params = metadata.default_sampling_params
self.prompt_expand_func = metadata.prompt_expand_func
self.custom_process_input_func = metadata.custom_process_input_func
self.model_stage = metadata.model_stage
self.engine_outputs: Any = None
self._proc = proc
self._shutting_down = False
self.client_addresses = dict(client_addresses or {})
self._omni_kv_config = getattr(getattr(vllm_config, "model_config", None), "omni_kv_config", None)
self._kv_sender_host = self._resolve_contact_host()
@@ -203,6 +186,7 @@ class StageEngineCoreClientBase(StageClientBase):
)
if engine_manager is not None:
self.resources.engine_manager = engine_manager
self.start_engine_core_monitor()
if coordinator is not None:
self.resources.coordinator = coordinator
except Exception:
@@ -226,9 +210,6 @@ class StageEngineCoreClientBase(StageClientBase):
self._initialize_kv_sender_endpoint()
if self._proc is not None:
self._start_proc_monitor()
logger.info(
"[%s] stage-%s [rep-%s] EngineCore running",
client_name,
@@ -236,64 +217,6 @@ class StageEngineCoreClientBase(StageClientBase):
self.replica_id,
)
def _start_proc_monitor(self) -> None:
"""Start a daemon thread that watches the subprocess sentinel.
When the subprocess dies without sending the ZMQ ``ENGINE_CORE_DEAD``
sentinel (e.g. SIGKILL, segfault, OOM-killer), this thread sets
``resources.engine_dead`` so subsequent calls raise
``EngineDeadError``.
"""
proc = self._proc
resources_ref = weakref.ref(self.resources)
stage_id = self.stage_id
replica_id = self.replica_id
def _monitor() -> None:
try:
multiprocessing.connection.wait([proc.sentinel])
except Exception:
return
# Give multiprocessing a brief chance to publish a stable exitcode
# before emitting the monitor log. Without this, the sentinel can
# fire first and the log may misleadingly print ``None``.
with contextlib.suppress(Exception):
proc.join(timeout=0)
exitcode = proc.exitcode
if exitcode is None:
deadline = time.monotonic() + 0.2
while exitcode is None and time.monotonic() < deadline:
time.sleep(0.01)
with contextlib.suppress(Exception):
proc.join(timeout=0)
exitcode = proc.exitcode
resources = resources_ref()
if resources is None or resources.engine_dead or self._shutting_down:
return
if exitcode == 0:
logger.info(
"[StageEngineCoreClient] stage-%s [rep-%s] subprocess exited cleanly.",
stage_id,
replica_id,
)
return
resources.engine_dead = True
logger.error(
"[StageEngineCoreClient] stage-%s [rep-%s] subprocess died unexpectedly (exit code %s).",
stage_id,
replica_id,
exitcode,
)
t = threading.Thread(
target=_monitor,
daemon=True,
name=f"StageCoreProcMonitor-{stage_id}",
)
t.start()
def check_health(self) -> None:
"""Raise ``EngineDeadError`` if the stage subprocess is dead.
@@ -302,9 +225,6 @@ class StageEngineCoreClientBase(StageClientBase):
"""
if self.resources.engine_dead:
raise EngineDeadError(f"Stage-{self.stage_id} engine core is dead")
if self._proc is not None and not self._proc.is_alive():
self.resources.engine_dead = True
raise EngineDeadError(f"Stage-{self.stage_id} subprocess is not alive (exit code {self._proc.exitcode})")
# ==================== Overrides ====================
@@ -335,7 +255,16 @@ class StageEngineCoreClientBase(StageClientBase):
return None
def _resolve_contact_host(self) -> str | None:
"""Resolve a routable host for this stage from its client addresses."""
"""Resolve a routable host for this stage from its client addresses.
For remote LLM replicas the ZMQ sockets are bound on the head node,
so the ZMQ addresses contain the head's IP. The ``replica_host`` key
(injected by DistStageRuntime) carries the actual replica IP where
the KV connector binds — prefer it when available.
"""
replica_host = self.client_addresses.get("replica_host")
if replica_host:
return replica_host
for key in ("input_address", "output_address", "stats_update_address"):
address = self.client_addresses.get(key)
if not address:
@@ -503,41 +432,6 @@ class StageEngineCoreClientBase(StageClientBase):
kwargs=kwargs,
)
def shutdown(self, timeout: float | None = None) -> None:
"""Shutdown managed resources and any externally spawned subprocess."""
self._shutting_down = True
child_procs: list[psutil.Process] = []
if self._proc is not None and self._proc.pid is not None:
try:
child_procs = psutil.Process(self._proc.pid).children(recursive=True)
except psutil.Error:
child_procs = []
try:
super().shutdown(timeout=timeout)
finally:
if self._proc is not None and self._proc.is_alive():
self._proc.terminate()
self._proc.join(timeout=SHUTDOWN_TIMEOUT_S)
if self._proc.is_alive():
self._proc.kill()
self._proc.join(timeout=SHUTDOWN_TIMEOUT_S)
alive_children = [proc for proc in child_procs if proc.is_running()]
for proc in alive_children:
try:
proc.terminate()
except psutil.Error:
pass
_, still_alive = psutil.wait_procs(alive_children, timeout=SHUTDOWN_TIMEOUT_S)
for proc in still_alive:
try:
proc.kill()
except psutil.Error:
pass
# The process handle is no longer reliable after best-effort cleanup.
self._proc = None
class StageEngineCoreClient(StageEngineCoreClientBase, AsyncMPClient):
"""Stage async client backed by vLLM's ``AsyncMPClient``."""
+8 -142
View File
@@ -10,40 +10,28 @@ from __future__ import annotations
import contextlib
import os
import signal
from multiprocessing.process import BaseProcess
from typing import TYPE_CHECKING, Any
from typing import Any
import msgspec
import vllm.v1.engine.core as _vllm_engine_core_module
import zmq
from vllm.logger import init_logger
from vllm.transformers_utils.config import (
maybe_register_config_serialize_by_value,
)
from vllm.utils.network_utils import get_open_zmq_ipc_path, zmq_socket_ctx
from vllm.utils.system_utils import (
decorate_logs,
get_mp_context,
set_process_title,
)
from vllm.v1.engine import EngineCoreRequestType
from vllm.v1.engine.core import EngineCoreProc, EngineShutdownState
from vllm.v1.engine.utils import (
EngineHandshakeMetadata,
EngineZmqAddresses,
SignalCallback,
get_engine_zmq_addresses,
)
from vllm.v1.utils import shutdown
from vllm_omni.distributed.omni_coordinator import OmniCoordClientForStage
from vllm_omni.distributed.omni_coordinator import create_stage_coord_client
from vllm_omni.engine import OmniEngineCoreRequest
from vllm_omni.engine.stage_init_utils import set_death_signal
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.executor import Executor
logger = init_logger(__name__)
@@ -106,7 +94,7 @@ class StageEngineCoreProc(EngineCoreProc):
)
engine_core: StageEngineCoreProc | None = None
coord_client: OmniCoordClientForStage | None = None
coord_client = None
try:
# NOTE: previous revisions hardcoded data_parallel_size=1 here
# (TODO referencing issue #984). The hardcoding has been removed
@@ -154,29 +142,17 @@ class StageEngineCoreProc(EngineCoreProc):
"EngineCore handshake did not populate input/output addresses; "
"cannot start OmniCoordClientForStage"
)
coord_client = OmniCoordClientForStage(
scheduler = getattr(engine_core, "scheduler", None)
if scheduler is None:
raise RuntimeError("EngineCore scheduler is not initialized")
coord_client = create_stage_coord_client(
coord_zmq_addr=omni_coordinator_address,
input_addr=addresses.inputs[0],
output_addr=addresses.outputs[0],
stage_id=int(omni_stage_id),
queue_length_getter=scheduler.get_num_unfinished_requests,
)
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))
@@ -212,113 +188,3 @@ class StageEngineCoreProc(EngineCoreProc):
coord_client.close()
if engine_core is not None:
engine_core.shutdown()
def spawn_stage_core(
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool = False,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
) -> tuple[EngineZmqAddresses, BaseProcess, str]:
"""Spawn a *StageEngineCoreProc* subprocess without performing the handshake.
Must be called while the correct device env vars are set (e.g. under
the stage-launch lock). Call ``complete_stage_handshake`` afterwards.
Returns ``(addresses, process, handshake_address)``.
"""
addresses = get_engine_zmq_addresses(vllm_config)
handshake_address = get_open_zmq_ipc_path()
ctx = get_mp_context()
proc = ctx.Process(
target=StageEngineCoreProc.run_stage_core,
name="StageEngineCoreProc",
kwargs={
"vllm_config": vllm_config,
"local_client": True,
"handshake_address": handshake_address,
"executor_class": executor_class,
"log_stats": log_stats,
"dp_rank": 0,
"local_dp_rank": 0,
"omni_stage_id": omni_stage_id,
"omni_replica_id": omni_replica_id,
},
)
proc.start()
return addresses, proc, handshake_address
def complete_stage_handshake(
proc: BaseProcess,
handshake_address: str,
addresses: EngineZmqAddresses,
vllm_config: VllmConfig,
handshake_timeout: int,
) -> None:
"""Perform the HELLO/INIT/READY handshake with an already-spawned proc.
On failure the process is terminated before re-raising.
"""
try:
_perform_handshake(proc, handshake_address, addresses, vllm_config, handshake_timeout)
except Exception:
shutdown([proc])
raise
def _perform_handshake(
proc: BaseProcess,
handshake_address: str,
addresses: EngineZmqAddresses,
vllm_config: VllmConfig,
handshake_timeout: int,
) -> None:
"""Run the HELLO / INIT / READY handshake with the subprocess."""
with zmq_socket_ctx(handshake_address, zmq.ROUTER, bind=True) as handshake_socket:
poller = zmq.Poller()
poller.register(handshake_socket, zmq.POLLIN)
poller.register(proc.sentinel, zmq.POLLIN)
identity, msg = _recv(poller, handshake_socket, proc, "HELLO", handshake_timeout)
if msg.get("status") != "HELLO":
raise RuntimeError(f"Expected HELLO, got: {msg}")
init_payload = EngineHandshakeMetadata(
addresses=addresses,
parallel_config={},
)
handshake_socket.send_multipart([identity, msgspec.msgpack.encode(init_payload)])
identity, msg = _recv(poller, handshake_socket, proc, "READY", handshake_timeout)
if msg.get("status") != "READY":
raise RuntimeError(f"Expected READY, got: {msg}")
num_gpu_blocks = msg.get("num_gpu_blocks")
if num_gpu_blocks is not None:
vllm_config.cache_config.num_gpu_blocks = num_gpu_blocks
def _recv(
poller: zmq.Poller,
handshake_socket: zmq.Socket,
proc: BaseProcess,
expected: str,
timeout_s: int = 600,
) -> tuple[bytes, dict]:
"""Wait for one handshake message; raise if the process dies first."""
timeout_ms = timeout_s * 1000
while True:
events = dict(poller.poll(timeout=timeout_ms))
if not events:
raise TimeoutError(
f"Timed out waiting for {expected} from StageEngineCoreProc after {timeout_s}s. "
f"This typically indicates model loading or initialization is taking too long. "
f"Consider increasing `stage_init_timeout` for large models."
)
if handshake_socket in events:
identity, raw = handshake_socket.recv_multipart()
return identity, msgspec.msgpack.decode(raw)
if proc.exitcode is not None:
raise RuntimeError(f"StageEngineCoreProc died during {expected} (exit code {proc.exitcode})")
@@ -47,7 +47,7 @@ except ImportError: # pragma: no cover - depends on vLLM build
set_device_control_env_var = None # type: ignore[assignment]
class OmniCoreEngineProcManager(CoreEngineProcManager):
class StageEngineCoreProcManager(CoreEngineProcManager):
"""Spawn :class:`StageEngineCoreProc` subprocesses with omni kwargs.
The body mirrors :class:`CoreEngineProcManager.__init__` because the
@@ -102,7 +102,7 @@ class OmniCoreEngineProcManager(CoreEngineProcManager):
# 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
# those each spawn their own StageEngineCoreProcManager and never join
# a vLLM DP group across replicas.
has_intra_replica_dp = vllm_config.parallel_config.data_parallel_size > 1
File diff suppressed because it is too large. Load diff
+22 -84
View File
@@ -51,6 +51,7 @@ class ReplicaInitPlan:
omni_kv_connector: tuple[dict[str, Any] | None, str | None, str | None]
stage_vllm_config: Any | None = None
executor_class: type | None = None
engine_args_dict: dict[str, Any] | None = None
@dataclass
@@ -58,65 +59,8 @@ class LogicalStageInitPlan:
"""Startup plan for one logical stage."""
stage_idx: int
configured_stage_id: int
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
replicas: list[ReplicaInitPlan]
def _resolve_model_to_local_path(model: str) -> str:
@@ -359,6 +303,26 @@ def inject_kv_stage_info(stage_cfg: Any, stage_id: int, stage_configs: Sequence[
logger.debug("Failed to inject stage info into omni_kv_config: %s", e)
def inject_omni_kv_connector_config(
engine_args_dict: dict[str, Any],
omni_kv_connector: tuple[dict[str, Any] | None, str | None, str | None],
stage_id: int,
) -> None:
"""Inject resolved connector config into a stage engine-args dict."""
omni_conn_cfg, omni_from, omni_to = omni_kv_connector
if not omni_conn_cfg:
return
omni_kv = engine_args_dict.get("omni_kv_config") or {}
if not isinstance(omni_kv, dict):
omni_kv = dict(omni_kv)
omni_kv["connector_config"] = omni_conn_cfg
omni_kv["omni_from_stage"] = omni_from
omni_kv["omni_to_stage"] = omni_to
omni_kv.setdefault("stage_id", stage_id)
engine_args_dict["omni_kv_config"] = omni_kv
@dataclass
class StageMetadata:
"""Lightweight stage attributes extracted from stage_config."""
@@ -1061,32 +1025,6 @@ def release_device_locks(lock_fds: list[int]) -> None:
pass
def acquire_diffusion_device_locks(
stage_id: int,
od_config: Any,
stage_init_timeout: int,
) -> list[int]:
"""Acquire init locks for the GPU set used by a diffusion stage.
Diffusion stages express their device count via ``OmniDiffusionConfig``'s
``parallel_config.world_size`` rather than the LLM-style
``tensor_parallel_size`` knob, so adapt to the shape that
``acquire_device_locks`` understands.
"""
parallel_config = getattr(od_config, "parallel_config", None)
world_size = getattr(parallel_config, "world_size", 1)
try:
world_size = max(1, int(world_size))
except (TypeError, ValueError):
world_size = 1
return acquire_device_locks(
stage_id,
{"tensor_parallel_size": world_size},
stage_init_timeout,
)
def load_omni_transfer_config_for_model(model: str, config_path: str | None) -> Any:
"""Load omni transfer config from an explicit path or resolved model config.
File diff suppressed because it is too large. Load diff