[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

@@ -8,11 +8,13 @@ from .load_balancer import (
RandomBalancer,
RoundRobinBalancer,
Task,
build_load_balancer_factory,
)
from .messages import ReplicaEvent, ReplicaInfo, ReplicaList, ReplicaStatus
from .omni_coord_client_for_hub import OmniCoordClientForHub
from .omni_coord_client_for_stage import OmniCoordClientForStage
from .omni_coord_client_for_stage import (
OmniCoordClientForStage,
create_stage_coord_client,
)
from .omni_coordinator import OmniCoordinator
from .runtime import OmniCoordinatorRuntime
@@ -24,6 +26,7 @@ __all__ = [
"ReplicaInfo",
"ReplicaList",
"OmniCoordClientForStage",
"create_stage_coord_client",
"OmniCoordClientForHub",
"Task",
"LoadBalancer",
@@ -31,5 +34,4 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -6,7 +6,6 @@ from __future__ import annotations
import random
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable
from enum import Enum
from typing import Any, TypedDict
@@ -122,22 +121,6 @@ class LeastQueueLengthBalancer(LoadBalancer):
return random.choice(candidates)
def build_load_balancer_factory(policy: str) -> Callable[[], LoadBalancer]:
"""Translate ``--omni-lb-policy`` (string) into a per-pool LB factory."""
try:
normalized = LoadBalancingPolicy(policy)
except ValueError as exc:
valid = ", ".join(p.value for p in LoadBalancingPolicy)
raise ValueError(f"unknown --omni-lb-policy {policy!r} (valid: {valid})") from exc
if normalized is LoadBalancingPolicy.RANDOM:
return RandomBalancer
if normalized is LoadBalancingPolicy.ROUND_ROBIN:
return RoundRobinBalancer
if normalized is LoadBalancingPolicy.LEAST_QUEUE_LENGTH:
return LeastQueueLengthBalancer
raise ValueError(f"unhandled load balancing policy {normalized!r}")
__all__ = [
"Task",
"LoadBalancingPolicy",
@@ -145,5 +128,4 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -230,3 +230,30 @@ class OmniCoordClientForStage:
except zmq.ZMQError:
pass
self._closed = True
def create_stage_coord_client(
*,
coord_zmq_addr: str,
input_addr: str,
output_addr: str,
stage_id: int,
queue_length_getter: Callable[[], int] | None = None,
) -> OmniCoordClientForStage:
"""Create a stage coordinator client with an optional heartbeat hook."""
client = OmniCoordClientForStage(
coord_zmq_addr=coord_zmq_addr,
input_addr=input_addr,
output_addr=output_addr,
stage_id=stage_id,
)
if queue_length_getter is not None:
def _refresh_queue_length() -> None:
try:
client._queue_length = max(int(queue_length_getter()), 0)
except Exception:
pass
client._on_heartbeat = _refresh_queue_length
return client
@@ -190,6 +190,15 @@ class OmniCoordinator:
except zmq.ZMQError:
pass
def wait_for_shutdown(self) -> None:
"""Block until the coordinator is asked to stop.
``OmniCoordinatorRuntime`` runs the coordinator in a child process.
The child needs a small, explicit blocking lifecycle API so it does
not return immediately after construction.
"""
self._stop_event.wait()
def _parse_replica_event(self, data: dict[str, Any]) -> ReplicaEvent | None:
"""Parse wire payload dict into ReplicaEvent. Returns None if invalid."""
try:
+108 -23
View File
@@ -3,35 +3,91 @@
"""Lifecycle wrapper around :class:`OmniCoordinator`.
``OmniCoordinatorRuntime`` is the single-purpose owner of the head-side
coordinator process artifacts: it picks two free TCP ports, constructs an
:class:`OmniCoordinator` bound to them, exposes the resulting addresses, and
provides a single ``close()`` method to tear everything down.
``OmniCoordinatorRuntime`` spawns the coordinator as an independent process
(matching vLLM's DPCoordinator pattern). Physical isolation prevents GIL
contention and makes direct-object coupling impossible.
The ROUTER address is later handed to :class:`OmniMasterServer` so it can be
published to registering replicas; the PUB address is handed to the
``Orchestrator``, which constructs its :class:`OmniCoordClientForHub` against
it.
``MembershipController``, which constructs its :class:`OmniCoordClientForHub`
against it.
"""
from __future__ import annotations
import logging
import multiprocessing
import multiprocessing.connection
import os
import signal
import weakref
from typing import Any
from vllm.utils.network_utils import get_open_ports_list
from .omni_coordinator import OmniCoordinator
from vllm_omni.distributed.omni_coordinator.omni_coordinator import OmniCoordinator
logger = logging.getLogger(__name__)
class OmniCoordinatorRuntime:
"""Own one :class:`OmniCoordinator` and the two ports it binds.
def run_omni_coordinator_proc(
router_zmq_addr: str,
pub_zmq_addr: str,
heartbeat_timeout: float,
ready_pipe: Any,
) -> None:
"""Main loop running inside the coordinator child process."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
Constructor binds; :meth:`close` tears down. The class deliberately does
not expose the coordinator instance — callers should consume the
coordinator only via its wire protocol through
:class:`OmniCoordClientForStage` and :class:`OmniCoordClientForHub`.
coordinator = OmniCoordinator(
router_zmq_addr=router_zmq_addr,
pub_zmq_addr=pub_zmq_addr,
heartbeat_timeout=heartbeat_timeout,
)
ready_pipe.send("ready")
ready_pipe.close()
coordinator.wait_for_shutdown()
def _get_coordinator_mp_context() -> multiprocessing.context.BaseContext:
"""Return the multiprocessing context used for OmniCoordinator.
For the current vllm-omni startup path, ``spawn`` is too expensive: the
child re-imports a heavy CLI / model stack before it can acknowledge the
ready pipe, which can exceed the coordinator startup timeout. Prefer
``fork`` on platforms that support it.
``fork`` must happen before the parent initializes CUDA or owns long-lived
ZMQ sockets; otherwise the child inherits unsafe state. If coordinator
startup moves later, switch this to ``spawn``/``forkserver``.
TODO: make the coordinator child entry cheap and spawn-safe, then revisit
whether ``spawn`` is still needed here.
"""
if os.name != "nt" and "fork" in multiprocessing.get_all_start_methods():
return multiprocessing.get_context("fork")
return multiprocessing.get_context("spawn")
def _shutdown_proc(proc: multiprocessing.Process) -> None:
"""Best-effort process termination for weakref finalizer."""
if proc.is_alive():
proc.terminate()
proc.join(timeout=5)
if proc.is_alive():
proc.kill()
proc.join(timeout=2)
class OmniCoordinatorRuntime:
"""Own one :class:`OmniCoordinator` running in a child process.
Constructor spawns the process; :meth:`close` tears it down.
The class deliberately does not expose the coordinator instance —
callers consume it only via ZMQ through :class:`OmniCoordClientForStage`
and :class:`OmniCoordClientForHub`.
"""
def __init__(
@@ -50,25 +106,54 @@ class OmniCoordinatorRuntime:
self.pub_address: str = f"tcp://{host}:{pub_port}"
self._closed = False
self._coordinator = OmniCoordinator(
router_zmq_addr=self.router_address,
pub_zmq_addr=self.pub_address,
heartbeat_timeout=heartbeat_timeout,
ctx = _get_coordinator_mp_context()
parent_conn, child_conn = ctx.Pipe(duplex=False)
self._proc: multiprocessing.Process = ctx.Process(
target=run_omni_coordinator_proc,
kwargs={
"router_zmq_addr": self.router_address,
"pub_zmq_addr": self.pub_address,
"heartbeat_timeout": heartbeat_timeout,
"ready_pipe": child_conn,
},
daemon=True,
name="OmniCoordinator",
)
self._proc.start()
child_conn.close()
ready = multiprocessing.connection.wait([parent_conn, self._proc.sentinel], timeout=30)
if not ready:
self._proc.terminate()
self._proc.join(timeout=5)
raise RuntimeError("OmniCoordinator process failed to start within 30s")
try:
status = parent_conn.recv()
except EOFError:
raise RuntimeError("OmniCoordinator process died during startup") from None
finally:
parent_conn.close()
if status != "ready":
raise RuntimeError(f"OmniCoordinator unexpected status: {status}")
self._finalizer = weakref.finalize(self, _shutdown_proc, self._proc)
logger.info(
"[OmniCoordinatorRuntime] Started (router=%s pub=%s heartbeat_timeout=%.1fs)",
"[OmniCoordinatorRuntime] Started (pid=%d router=%s pub=%s heartbeat_timeout=%.1fs)",
self._proc.pid,
self.router_address,
self.pub_address,
heartbeat_timeout,
)
def close(self) -> None:
"""Tear down the underlying coordinator. Idempotent."""
"""Tear down the coordinator process. Idempotent."""
if self._closed:
return
self._closed = True
try:
self._coordinator.close()
except Exception:
logger.exception("[OmniCoordinatorRuntime] coordinator close failed")
_shutdown_proc(self._proc)
self._finalizer.detach()